clang  19.0.0git
CGObjCGNU.cpp
Go to the documentation of this file.
1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This provides Objective-C code generation targeting the GNU runtime. The
10 // class in this file generates structures used by the GNU Objective-C runtime
11 // library. These structures are defined in objc/objc.h and objc/objc-api.h in
12 // the GNU runtime distribution.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "CGCXXABI.h"
17 #include "CGCleanup.h"
18 #include "CGObjCRuntime.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "CodeGenTypes.h"
22 #include "SanitizerMetadata.h"
23 #include "clang/AST/ASTContext.h"
24 #include "clang/AST/Attr.h"
25 #include "clang/AST/Decl.h"
26 #include "clang/AST/DeclObjC.h"
27 #include "clang/AST/RecordLayout.h"
28 #include "clang/AST/StmtObjC.h"
32 #include "llvm/ADT/SmallVector.h"
33 #include "llvm/ADT/StringMap.h"
34 #include "llvm/IR/DataLayout.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/IR/LLVMContext.h"
37 #include "llvm/IR/Module.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/ConvertUTF.h"
40 #include <cctype>
41 
42 using namespace clang;
43 using namespace CodeGen;
44 
45 namespace {
46 
47 /// Class that lazily initialises the runtime function. Avoids inserting the
48 /// types and the function declaration into a module if they're not used, and
49 /// avoids constructing the type more than once if it's used more than once.
50 class LazyRuntimeFunction {
51  CodeGenModule *CGM = nullptr;
52  llvm::FunctionType *FTy = nullptr;
53  const char *FunctionName = nullptr;
54  llvm::FunctionCallee Function = nullptr;
55 
56 public:
57  LazyRuntimeFunction() = default;
58 
59  /// Initialises the lazy function with the name, return type, and the types
60  /// of the arguments.
61  template <typename... Tys>
62  void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
63  Tys *... Types) {
64  CGM = Mod;
65  FunctionName = name;
66  Function = nullptr;
67  if(sizeof...(Tys)) {
68  SmallVector<llvm::Type *, 8> ArgTys({Types...});
69  FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
70  }
71  else {
72  FTy = llvm::FunctionType::get(RetTy, std::nullopt, false);
73  }
74  }
75 
76  llvm::FunctionType *getType() { return FTy; }
77 
78  /// Overloaded cast operator, allows the class to be implicitly cast to an
79  /// LLVM constant.
80  operator llvm::FunctionCallee() {
81  if (!Function) {
82  if (!FunctionName)
83  return nullptr;
84  Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
85  }
86  return Function;
87  }
88 };
89 
90 
91 /// GNU Objective-C runtime code generation. This class implements the parts of
92 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
93 /// GNUstep and ObjFW).
94 class CGObjCGNU : public CGObjCRuntime {
95 protected:
96  /// The LLVM module into which output is inserted
97  llvm::Module &TheModule;
98  /// strut objc_super. Used for sending messages to super. This structure
99  /// contains the receiver (object) and the expected class.
100  llvm::StructType *ObjCSuperTy;
101  /// struct objc_super*. The type of the argument to the superclass message
102  /// lookup functions.
103  llvm::PointerType *PtrToObjCSuperTy;
104  /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
105  /// SEL is included in a header somewhere, in which case it will be whatever
106  /// type is declared in that header, most likely {i8*, i8*}.
107  llvm::PointerType *SelectorTy;
108  /// Element type of SelectorTy.
109  llvm::Type *SelectorElemTy;
110  /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
111  /// places where it's used
112  llvm::IntegerType *Int8Ty;
113  /// Pointer to i8 - LLVM type of char*, for all of the places where the
114  /// runtime needs to deal with C strings.
115  llvm::PointerType *PtrToInt8Ty;
116  /// struct objc_protocol type
117  llvm::StructType *ProtocolTy;
118  /// Protocol * type.
119  llvm::PointerType *ProtocolPtrTy;
120  /// Instance Method Pointer type. This is a pointer to a function that takes,
121  /// at a minimum, an object and a selector, and is the generic type for
122  /// Objective-C methods. Due to differences between variadic / non-variadic
123  /// calling conventions, it must always be cast to the correct type before
124  /// actually being used.
125  llvm::PointerType *IMPTy;
126  /// Type of an untyped Objective-C object. Clang treats id as a built-in type
127  /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
128  /// but if the runtime header declaring it is included then it may be a
129  /// pointer to a structure.
130  llvm::PointerType *IdTy;
131  /// Element type of IdTy.
132  llvm::Type *IdElemTy;
133  /// Pointer to a pointer to an Objective-C object. Used in the new ABI
134  /// message lookup function and some GC-related functions.
135  llvm::PointerType *PtrToIdTy;
136  /// The clang type of id. Used when using the clang CGCall infrastructure to
137  /// call Objective-C methods.
138  CanQualType ASTIdTy;
139  /// LLVM type for C int type.
140  llvm::IntegerType *IntTy;
141  /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
142  /// used in the code to document the difference between i8* meaning a pointer
143  /// to a C string and i8* meaning a pointer to some opaque type.
144  llvm::PointerType *PtrTy;
145  /// LLVM type for C long type. The runtime uses this in a lot of places where
146  /// it should be using intptr_t, but we can't fix this without breaking
147  /// compatibility with GCC...
148  llvm::IntegerType *LongTy;
149  /// LLVM type for C size_t. Used in various runtime data structures.
150  llvm::IntegerType *SizeTy;
151  /// LLVM type for C intptr_t.
152  llvm::IntegerType *IntPtrTy;
153  /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
154  llvm::IntegerType *PtrDiffTy;
155  /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
156  /// variables.
157  llvm::PointerType *PtrToIntTy;
158  /// LLVM type for Objective-C BOOL type.
159  llvm::Type *BoolTy;
160  /// 32-bit integer type, to save us needing to look it up every time it's used.
161  llvm::IntegerType *Int32Ty;
162  /// 64-bit integer type, to save us needing to look it up every time it's used.
163  llvm::IntegerType *Int64Ty;
164  /// The type of struct objc_property.
165  llvm::StructType *PropertyMetadataTy;
166  /// Metadata kind used to tie method lookups to message sends. The GNUstep
167  /// runtime provides some LLVM passes that can use this to do things like
168  /// automatic IMP caching and speculative inlining.
169  unsigned msgSendMDKind;
170  /// Does the current target use SEH-based exceptions? False implies
171  /// Itanium-style DWARF unwinding.
172  bool usesSEHExceptions;
173  /// Does the current target uses C++-based exceptions?
174  bool usesCxxExceptions;
175 
176  /// Helper to check if we are targeting a specific runtime version or later.
177  bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
178  const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
179  return (R.getKind() == kind) &&
180  (R.getVersion() >= VersionTuple(major, minor));
181  }
182 
183  std::string ManglePublicSymbol(StringRef Name) {
184  return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
185  }
186 
187  std::string SymbolForProtocol(Twine Name) {
188  return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
189  }
190 
191  std::string SymbolForProtocolRef(StringRef Name) {
192  return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
193  }
194 
195 
196  /// Helper function that generates a constant string and returns a pointer to
197  /// the start of the string. The result of this function can be used anywhere
198  /// where the C code specifies const char*.
199  llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
201  CGM.GetAddrOfConstantCString(std::string(Str), Name);
202  return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
203  Array.getPointer(), Zeros);
204  }
205 
206  /// Emits a linkonce_odr string, whose name is the prefix followed by the
207  /// string value. This allows the linker to combine the strings between
208  /// different modules. Used for EH typeinfo names, selector strings, and a
209  /// few other things.
210  llvm::Constant *ExportUniqueString(const std::string &Str,
211  const std::string &prefix,
212  bool Private=false) {
213  std::string name = prefix + Str;
214  auto *ConstStr = TheModule.getGlobalVariable(name);
215  if (!ConstStr) {
216  llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
217  auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
218  llvm::GlobalValue::LinkOnceODRLinkage, value, name);
219  GV->setComdat(TheModule.getOrInsertComdat(name));
220  if (Private)
221  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
222  ConstStr = GV;
223  }
224  return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
225  ConstStr, Zeros);
226  }
227 
228  /// Returns a property name and encoding string.
229  llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
230  const Decl *Container) {
231  assert(!isRuntime(ObjCRuntime::GNUstep, 2));
232  if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
233  std::string NameAndAttributes;
234  std::string TypeStr =
235  CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
236  NameAndAttributes += '\0';
237  NameAndAttributes += TypeStr.length() + 3;
238  NameAndAttributes += TypeStr;
239  NameAndAttributes += '\0';
240  NameAndAttributes += PD->getNameAsString();
241  return MakeConstantString(NameAndAttributes);
242  }
243  return MakeConstantString(PD->getNameAsString());
244  }
245 
246  /// Push the property attributes into two structure fields.
247  void PushPropertyAttributes(ConstantStructBuilder &Fields,
248  const ObjCPropertyDecl *property, bool isSynthesized=true, bool
249  isDynamic=true) {
250  int attrs = property->getPropertyAttributes();
251  // For read-only properties, clear the copy and retain flags
253  attrs &= ~ObjCPropertyAttribute::kind_copy;
254  attrs &= ~ObjCPropertyAttribute::kind_retain;
255  attrs &= ~ObjCPropertyAttribute::kind_weak;
256  attrs &= ~ObjCPropertyAttribute::kind_strong;
257  }
258  // The first flags field has the same attribute values as clang uses internally
259  Fields.addInt(Int8Ty, attrs & 0xff);
260  attrs >>= 8;
261  attrs <<= 2;
262  // For protocol properties, synthesized and dynamic have no meaning, so we
263  // reuse these flags to indicate that this is a protocol property (both set
264  // has no meaning, as a property can't be both synthesized and dynamic)
265  attrs |= isSynthesized ? (1<<0) : 0;
266  attrs |= isDynamic ? (1<<1) : 0;
267  // The second field is the next four fields left shifted by two, with the
268  // low bit set to indicate whether the field is synthesized or dynamic.
269  Fields.addInt(Int8Ty, attrs & 0xff);
270  // Two padding fields
271  Fields.addInt(Int8Ty, 0);
272  Fields.addInt(Int8Ty, 0);
273  }
274 
275  virtual llvm::Constant *GenerateCategoryProtocolList(const
276  ObjCCategoryDecl *OCD);
277  virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
278  int count) {
279  // int count;
280  Fields.addInt(IntTy, count);
281  // int size; (only in GNUstep v2 ABI.
282  if (isRuntime(ObjCRuntime::GNUstep, 2)) {
283  llvm::DataLayout td(&TheModule);
284  Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
285  CGM.getContext().getCharWidth());
286  }
287  // struct objc_property_list *next;
288  Fields.add(NULLPtr);
289  // struct objc_property properties[]
290  return Fields.beginArray(PropertyMetadataTy);
291  }
292  virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
293  const ObjCPropertyDecl *property,
294  const Decl *OCD,
295  bool isSynthesized=true, bool
296  isDynamic=true) {
297  auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
298  ASTContext &Context = CGM.getContext();
299  Fields.add(MakePropertyEncodingString(property, OCD));
300  PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
301  auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
302  if (accessor) {
303  std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
304  llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
305  Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
306  Fields.add(TypeEncoding);
307  } else {
308  Fields.add(NULLPtr);
309  Fields.add(NULLPtr);
310  }
311  };
312  addPropertyMethod(property->getGetterMethodDecl());
313  addPropertyMethod(property->getSetterMethodDecl());
314  Fields.finishAndAddTo(PropertiesArray);
315  }
316 
317  /// Ensures that the value has the required type, by inserting a bitcast if
318  /// required. This function lets us avoid inserting bitcasts that are
319  /// redundant.
320  llvm::Value *EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
321  if (V->getType() == Ty)
322  return V;
323  return B.CreateBitCast(V, Ty);
324  }
325 
326  // Some zeros used for GEPs in lots of places.
327  llvm::Constant *Zeros[2];
328  /// Null pointer value. Mainly used as a terminator in various arrays.
329  llvm::Constant *NULLPtr;
330  /// LLVM context.
331  llvm::LLVMContext &VMContext;
332 
333 protected:
334 
335  /// Placeholder for the class. Lots of things refer to the class before we've
336  /// actually emitted it. We use this alias as a placeholder, and then replace
337  /// it with a pointer to the class structure before finally emitting the
338  /// module.
339  llvm::GlobalAlias *ClassPtrAlias;
340  /// Placeholder for the metaclass. Lots of things refer to the class before
341  /// we've / actually emitted it. We use this alias as a placeholder, and then
342  /// replace / it with a pointer to the metaclass structure before finally
343  /// emitting the / module.
344  llvm::GlobalAlias *MetaClassPtrAlias;
345  /// All of the classes that have been generated for this compilation units.
346  std::vector<llvm::Constant*> Classes;
347  /// All of the categories that have been generated for this compilation units.
348  std::vector<llvm::Constant*> Categories;
349  /// All of the Objective-C constant strings that have been generated for this
350  /// compilation units.
351  std::vector<llvm::Constant*> ConstantStrings;
352  /// Map from string values to Objective-C constant strings in the output.
353  /// Used to prevent emitting Objective-C strings more than once. This should
354  /// not be required at all - CodeGenModule should manage this list.
355  llvm::StringMap<llvm::Constant*> ObjCStrings;
356  /// All of the protocols that have been declared.
357  llvm::StringMap<llvm::Constant*> ExistingProtocols;
358  /// For each variant of a selector, we store the type encoding and a
359  /// placeholder value. For an untyped selector, the type will be the empty
360  /// string. Selector references are all done via the module's selector table,
361  /// so we create an alias as a placeholder and then replace it with the real
362  /// value later.
363  typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
364  /// Type of the selector map. This is roughly equivalent to the structure
365  /// used in the GNUstep runtime, which maintains a list of all of the valid
366  /// types for a selector in a table.
367  typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
368  SelectorMap;
369  /// A map from selectors to selector types. This allows us to emit all
370  /// selectors of the same name and type together.
371  SelectorMap SelectorTable;
372 
373  /// Selectors related to memory management. When compiling in GC mode, we
374  /// omit these.
375  Selector RetainSel, ReleaseSel, AutoreleaseSel;
376  /// Runtime functions used for memory management in GC mode. Note that clang
377  /// supports code generation for calling these functions, but neither GNU
378  /// runtime actually supports this API properly yet.
379  LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
380  WeakAssignFn, GlobalAssignFn;
381 
382  typedef std::pair<std::string, std::string> ClassAliasPair;
383  /// All classes that have aliases set for them.
384  std::vector<ClassAliasPair> ClassAliases;
385 
386 protected:
387  /// Function used for throwing Objective-C exceptions.
388  LazyRuntimeFunction ExceptionThrowFn;
389  /// Function used for rethrowing exceptions, used at the end of \@finally or
390  /// \@synchronize blocks.
391  LazyRuntimeFunction ExceptionReThrowFn;
392  /// Function called when entering a catch function. This is required for
393  /// differentiating Objective-C exceptions and foreign exceptions.
394  LazyRuntimeFunction EnterCatchFn;
395  /// Function called when exiting from a catch block. Used to do exception
396  /// cleanup.
397  LazyRuntimeFunction ExitCatchFn;
398  /// Function called when entering an \@synchronize block. Acquires the lock.
399  LazyRuntimeFunction SyncEnterFn;
400  /// Function called when exiting an \@synchronize block. Releases the lock.
401  LazyRuntimeFunction SyncExitFn;
402 
403 private:
404  /// Function called if fast enumeration detects that the collection is
405  /// modified during the update.
406  LazyRuntimeFunction EnumerationMutationFn;
407  /// Function for implementing synthesized property getters that return an
408  /// object.
409  LazyRuntimeFunction GetPropertyFn;
410  /// Function for implementing synthesized property setters that return an
411  /// object.
412  LazyRuntimeFunction SetPropertyFn;
413  /// Function used for non-object declared property getters.
414  LazyRuntimeFunction GetStructPropertyFn;
415  /// Function used for non-object declared property setters.
416  LazyRuntimeFunction SetStructPropertyFn;
417 
418 protected:
419  /// The version of the runtime that this class targets. Must match the
420  /// version in the runtime.
421  int RuntimeVersion;
422  /// The version of the protocol class. Used to differentiate between ObjC1
423  /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
424  /// components and can not contain declared properties. We always emit
425  /// Objective-C 2 property structures, but we have to pretend that they're
426  /// Objective-C 1 property structures when targeting the GCC runtime or it
427  /// will abort.
428  const int ProtocolVersion;
429  /// The version of the class ABI. This value is used in the class structure
430  /// and indicates how various fields should be interpreted.
431  const int ClassABIVersion;
432  /// Generates an instance variable list structure. This is a structure
433  /// containing a size and an array of structures containing instance variable
434  /// metadata. This is used purely for introspection in the fragile ABI. In
435  /// the non-fragile ABI, it's used for instance variable fixup.
436  virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
437  ArrayRef<llvm::Constant *> IvarTypes,
438  ArrayRef<llvm::Constant *> IvarOffsets,
439  ArrayRef<llvm::Constant *> IvarAlign,
440  ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
441 
442  /// Generates a method list structure. This is a structure containing a size
443  /// and an array of structures containing method metadata.
444  ///
445  /// This structure is used by both classes and categories, and contains a next
446  /// pointer allowing them to be chained together in a linked list.
447  llvm::Constant *GenerateMethodList(StringRef ClassName,
448  StringRef CategoryName,
450  bool isClassMethodList);
451 
452  /// Emits an empty protocol. This is used for \@protocol() where no protocol
453  /// is found. The runtime will (hopefully) fix up the pointer to refer to the
454  /// real protocol.
455  virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
456 
457  /// Generates a list of property metadata structures. This follows the same
458  /// pattern as method and instance variable metadata lists.
459  llvm::Constant *GeneratePropertyList(const Decl *Container,
460  const ObjCContainerDecl *OCD,
461  bool isClassProperty=false,
462  bool protocolOptionalProperties=false);
463 
464  /// Generates a list of referenced protocols. Classes, categories, and
465  /// protocols all use this structure.
466  llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
467 
468  /// To ensure that all protocols are seen by the runtime, we add a category on
469  /// a class defined in the runtime, declaring no methods, but adopting the
470  /// protocols. This is a horribly ugly hack, but it allows us to collect all
471  /// of the protocols without changing the ABI.
472  void GenerateProtocolHolderCategory();
473 
474  /// Generates a class structure.
475  llvm::Constant *GenerateClassStructure(
476  llvm::Constant *MetaClass,
477  llvm::Constant *SuperClass,
478  unsigned info,
479  const char *Name,
480  llvm::Constant *Version,
481  llvm::Constant *InstanceSize,
482  llvm::Constant *IVars,
483  llvm::Constant *Methods,
484  llvm::Constant *Protocols,
485  llvm::Constant *IvarOffsets,
486  llvm::Constant *Properties,
487  llvm::Constant *StrongIvarBitmap,
488  llvm::Constant *WeakIvarBitmap,
489  bool isMeta=false);
490 
491  /// Generates a method list. This is used by protocols to define the required
492  /// and optional methods.
493  virtual llvm::Constant *GenerateProtocolMethodList(
495  /// Emits optional and required method lists.
496  template<class T>
497  void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
498  llvm::Constant *&Optional) {
501  for (const auto *I : Methods)
502  if (I->isOptional())
503  OptionalMethods.push_back(I);
504  else
505  RequiredMethods.push_back(I);
506  Required = GenerateProtocolMethodList(RequiredMethods);
507  Optional = GenerateProtocolMethodList(OptionalMethods);
508  }
509 
510  /// Returns a selector with the specified type encoding. An empty string is
511  /// used to return an untyped selector (with the types field set to NULL).
512  virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
513  const std::string &TypeEncoding);
514 
515  /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
516  /// contains the class and ivar names, in the v2 ABI this contains the type
517  /// encoding as well.
518  virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
519  const ObjCIvarDecl *Ivar) {
520  const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
521  + '.' + Ivar->getNameAsString();
522  return Name;
523  }
524  /// Returns the variable used to store the offset of an instance variable.
525  llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
526  const ObjCIvarDecl *Ivar);
527  /// Emits a reference to a class. This allows the linker to object if there
528  /// is no class of the matching name.
529  void EmitClassRef(const std::string &className);
530 
531  /// Emits a pointer to the named class
532  virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
533  const std::string &Name, bool isWeak);
534 
535  /// Looks up the method for sending a message to the specified object. This
536  /// mechanism differs between the GCC and GNU runtimes, so this method must be
537  /// overridden in subclasses.
538  virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
539  llvm::Value *&Receiver,
540  llvm::Value *cmd,
541  llvm::MDNode *node,
542  MessageSendInfo &MSI) = 0;
543 
544  /// Looks up the method for sending a message to a superclass. This
545  /// mechanism differs between the GCC and GNU runtimes, so this method must
546  /// be overridden in subclasses.
547  virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
548  Address ObjCSuper,
549  llvm::Value *cmd,
550  MessageSendInfo &MSI) = 0;
551 
552  /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
553  /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
554  /// bits set to their values, LSB first, while larger ones are stored in a
555  /// structure of this / form:
556  ///
557  /// struct { int32_t length; int32_t values[length]; };
558  ///
559  /// The values in the array are stored in host-endian format, with the least
560  /// significant bit being assumed to come first in the bitfield. Therefore,
561  /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
562  /// while a bitfield / with the 63rd bit set will be 1<<64.
563  llvm::Constant *MakeBitField(ArrayRef<bool> bits);
564 
565 public:
566  CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
567  unsigned protocolClassVersion, unsigned classABI=1);
568 
569  ConstantAddress GenerateConstantString(const StringLiteral *) override;
570 
571  RValue
572  GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
573  QualType ResultType, Selector Sel,
574  llvm::Value *Receiver, const CallArgList &CallArgs,
575  const ObjCInterfaceDecl *Class,
576  const ObjCMethodDecl *Method) override;
577  RValue
578  GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
579  QualType ResultType, Selector Sel,
580  const ObjCInterfaceDecl *Class,
581  bool isCategoryImpl, llvm::Value *Receiver,
582  bool IsClassMessage, const CallArgList &CallArgs,
583  const ObjCMethodDecl *Method) override;
584  llvm::Value *GetClass(CodeGenFunction &CGF,
585  const ObjCInterfaceDecl *OID) override;
586  llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
587  Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
588  llvm::Value *GetSelector(CodeGenFunction &CGF,
589  const ObjCMethodDecl *Method) override;
590  virtual llvm::Constant *GetConstantSelector(Selector Sel,
591  const std::string &TypeEncoding) {
592  llvm_unreachable("Runtime unable to generate constant selector");
593  }
594  llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
595  return GetConstantSelector(M->getSelector(),
597  }
598  llvm::Constant *GetEHType(QualType T) override;
599 
600  llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
601  const ObjCContainerDecl *CD) override;
602 
603  // Map to unify direct method definitions.
604  llvm::DenseMap<const ObjCMethodDecl *, llvm::Function *>
605  DirectMethodDefinitions;
606  void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
607  const ObjCMethodDecl *OMD,
608  const ObjCContainerDecl *CD) override;
609  void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
610  void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
611  void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
612  llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
613  const ObjCProtocolDecl *PD) override;
614  void GenerateProtocol(const ObjCProtocolDecl *PD) override;
615 
616  virtual llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD);
617 
618  llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD) override {
619  return GenerateProtocolRef(PD);
620  }
621 
622  llvm::Function *ModuleInitFunction() override;
623  llvm::FunctionCallee GetPropertyGetFunction() override;
624  llvm::FunctionCallee GetPropertySetFunction() override;
625  llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
626  bool copy) override;
627  llvm::FunctionCallee GetSetStructFunction() override;
628  llvm::FunctionCallee GetGetStructFunction() override;
629  llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
630  llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
631  llvm::FunctionCallee EnumerationMutationFunction() override;
632 
633  void EmitTryStmt(CodeGenFunction &CGF,
634  const ObjCAtTryStmt &S) override;
635  void EmitSynchronizedStmt(CodeGenFunction &CGF,
636  const ObjCAtSynchronizedStmt &S) override;
637  void EmitThrowStmt(CodeGenFunction &CGF,
638  const ObjCAtThrowStmt &S,
639  bool ClearInsertionPoint=true) override;
640  llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
641  Address AddrWeakObj) override;
642  void EmitObjCWeakAssign(CodeGenFunction &CGF,
643  llvm::Value *src, Address dst) override;
644  void EmitObjCGlobalAssign(CodeGenFunction &CGF,
645  llvm::Value *src, Address dest,
646  bool threadlocal=false) override;
647  void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
648  Address dest, llvm::Value *ivarOffset) override;
649  void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
650  llvm::Value *src, Address dest) override;
651  void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
652  Address SrcPtr,
653  llvm::Value *Size) override;
654  LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
655  llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
656  unsigned CVRQualifiers) override;
657  llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
658  const ObjCInterfaceDecl *Interface,
659  const ObjCIvarDecl *Ivar) override;
660  llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
661  llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
662  const CGBlockInfo &blockInfo) override {
663  return NULLPtr;
664  }
665  llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
666  const CGBlockInfo &blockInfo) override {
667  return NULLPtr;
668  }
669 
670  llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
671  return NULLPtr;
672  }
673 };
674 
675 /// Class representing the legacy GCC Objective-C ABI. This is the default when
676 /// -fobjc-nonfragile-abi is not specified.
677 ///
678 /// The GCC ABI target actually generates code that is approximately compatible
679 /// with the new GNUstep runtime ABI, but refrains from using any features that
680 /// would not work with the GCC runtime. For example, clang always generates
681 /// the extended form of the class structure, and the extra fields are simply
682 /// ignored by GCC libobjc.
683 class CGObjCGCC : public CGObjCGNU {
684  /// The GCC ABI message lookup function. Returns an IMP pointing to the
685  /// method implementation for this message.
686  LazyRuntimeFunction MsgLookupFn;
687  /// The GCC ABI superclass message lookup function. Takes a pointer to a
688  /// structure describing the receiver and the class, and a selector as
689  /// arguments. Returns the IMP for the corresponding method.
690  LazyRuntimeFunction MsgLookupSuperFn;
691 
692 protected:
693  llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
694  llvm::Value *cmd, llvm::MDNode *node,
695  MessageSendInfo &MSI) override {
696  CGBuilderTy &Builder = CGF.Builder;
697  llvm::Value *args[] = {
698  EnforceType(Builder, Receiver, IdTy),
699  EnforceType(Builder, cmd, SelectorTy) };
700  llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
701  imp->setMetadata(msgSendMDKind, node);
702  return imp;
703  }
704 
705  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
706  llvm::Value *cmd, MessageSendInfo &MSI) override {
707  CGBuilderTy &Builder = CGF.Builder;
708  llvm::Value *lookupArgs[] = {
709  EnforceType(Builder, ObjCSuper.emitRawPointer(CGF), PtrToObjCSuperTy),
710  cmd};
711  return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
712  }
713 
714 public:
715  CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
716  // IMP objc_msg_lookup(id, SEL);
717  MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
718  // IMP objc_msg_lookup_super(struct objc_super*, SEL);
719  MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
720  PtrToObjCSuperTy, SelectorTy);
721  }
722 };
723 
724 /// Class used when targeting the new GNUstep runtime ABI.
725 class CGObjCGNUstep : public CGObjCGNU {
726  /// The slot lookup function. Returns a pointer to a cacheable structure
727  /// that contains (among other things) the IMP.
728  LazyRuntimeFunction SlotLookupFn;
729  /// The GNUstep ABI superclass message lookup function. Takes a pointer to
730  /// a structure describing the receiver and the class, and a selector as
731  /// arguments. Returns the slot for the corresponding method. Superclass
732  /// message lookup rarely changes, so this is a good caching opportunity.
733  LazyRuntimeFunction SlotLookupSuperFn;
734  /// Specialised function for setting atomic retain properties
735  LazyRuntimeFunction SetPropertyAtomic;
736  /// Specialised function for setting atomic copy properties
737  LazyRuntimeFunction SetPropertyAtomicCopy;
738  /// Specialised function for setting nonatomic retain properties
739  LazyRuntimeFunction SetPropertyNonAtomic;
740  /// Specialised function for setting nonatomic copy properties
741  LazyRuntimeFunction SetPropertyNonAtomicCopy;
742  /// Function to perform atomic copies of C++ objects with nontrivial copy
743  /// constructors from Objective-C ivars.
744  LazyRuntimeFunction CxxAtomicObjectGetFn;
745  /// Function to perform atomic copies of C++ objects with nontrivial copy
746  /// constructors to Objective-C ivars.
747  LazyRuntimeFunction CxxAtomicObjectSetFn;
748  /// Type of a slot structure pointer. This is returned by the various
749  /// lookup functions.
750  llvm::Type *SlotTy;
751  /// Type of a slot structure.
752  llvm::Type *SlotStructTy;
753 
754  public:
755  llvm::Constant *GetEHType(QualType T) override;
756 
757  protected:
758  llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
759  llvm::Value *cmd, llvm::MDNode *node,
760  MessageSendInfo &MSI) override {
761  CGBuilderTy &Builder = CGF.Builder;
762  llvm::FunctionCallee LookupFn = SlotLookupFn;
763 
764  // Store the receiver on the stack so that we can reload it later
765  RawAddress ReceiverPtr =
766  CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
767  Builder.CreateStore(Receiver, ReceiverPtr);
768 
769  llvm::Value *self;
770 
771  if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
772  self = CGF.LoadObjCSelf();
773  } else {
774  self = llvm::ConstantPointerNull::get(IdTy);
775  }
776 
777  // The lookup function is guaranteed not to capture the receiver pointer.
778  if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
779  LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
780 
781  llvm::Value *args[] = {
782  EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
783  EnforceType(Builder, cmd, SelectorTy),
784  EnforceType(Builder, self, IdTy)};
785  llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
786  slot->setOnlyReadsMemory();
787  slot->setMetadata(msgSendMDKind, node);
788 
789  // Load the imp from the slot
790  llvm::Value *imp = Builder.CreateAlignedLoad(
791  IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
792  CGF.getPointerAlign());
793 
794  // The lookup function may have changed the receiver, so make sure we use
795  // the new one.
796  Receiver = Builder.CreateLoad(ReceiverPtr, true);
797  return imp;
798  }
799 
800  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
801  llvm::Value *cmd,
802  MessageSendInfo &MSI) override {
803  CGBuilderTy &Builder = CGF.Builder;
804  llvm::Value *lookupArgs[] = {ObjCSuper.emitRawPointer(CGF), cmd};
805 
806  llvm::CallInst *slot =
807  CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
808  slot->setOnlyReadsMemory();
809 
810  return Builder.CreateAlignedLoad(
811  IMPTy, Builder.CreateStructGEP(SlotStructTy, slot, 4),
812  CGF.getPointerAlign());
813  }
814 
815  public:
816  CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
817  CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
818  unsigned ClassABI) :
819  CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
820  const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
821 
822  SlotStructTy = llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
823  SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
824  // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
825  SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
826  SelectorTy, IdTy);
827  // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
828  SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
829  PtrToObjCSuperTy, SelectorTy);
830  // If we're in ObjC++ mode, then we want to make
831  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
832  if (usesCxxExceptions) {
833  // void *__cxa_begin_catch(void *e)
834  EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
835  // void __cxa_end_catch(void)
836  ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
837  // void objc_exception_rethrow(void*)
838  ExceptionReThrowFn.init(&CGM, "__cxa_rethrow", PtrTy);
839  } else if (usesSEHExceptions) {
840  // void objc_exception_rethrow(void)
841  ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
842  } else if (CGM.getLangOpts().CPlusPlus) {
843  // void *__cxa_begin_catch(void *e)
844  EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
845  // void __cxa_end_catch(void)
846  ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
847  // void _Unwind_Resume_or_Rethrow(void*)
848  ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
849  PtrTy);
850  } else if (R.getVersion() >= VersionTuple(1, 7)) {
851  // id objc_begin_catch(void *e)
852  EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
853  // void objc_end_catch(void)
854  ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
855  // void _Unwind_Resume_or_Rethrow(void*)
856  ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
857  }
858  SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
859  SelectorTy, IdTy, PtrDiffTy);
860  SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
861  IdTy, SelectorTy, IdTy, PtrDiffTy);
862  SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
863  IdTy, SelectorTy, IdTy, PtrDiffTy);
864  SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
865  VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
866  // void objc_setCppObjectAtomic(void *dest, const void *src, void
867  // *helper);
868  CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
869  PtrTy, PtrTy);
870  // void objc_getCppObjectAtomic(void *dest, const void *src, void
871  // *helper);
872  CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
873  PtrTy, PtrTy);
874  }
875 
876  llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
877  // The optimised functions were added in version 1.7 of the GNUstep
878  // runtime.
879  assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
880  VersionTuple(1, 7));
881  return CxxAtomicObjectGetFn;
882  }
883 
884  llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
885  // The optimised functions were added in version 1.7 of the GNUstep
886  // runtime.
887  assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
888  VersionTuple(1, 7));
889  return CxxAtomicObjectSetFn;
890  }
891 
892  llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
893  bool copy) override {
894  // The optimised property functions omit the GC check, and so are not
895  // safe to use in GC mode. The standard functions are fast in GC mode,
896  // so there is less advantage in using them.
897  assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
898  // The optimised functions were added in version 1.7 of the GNUstep
899  // runtime.
900  assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
901  VersionTuple(1, 7));
902 
903  if (atomic) {
904  if (copy) return SetPropertyAtomicCopy;
905  return SetPropertyAtomic;
906  }
907 
908  return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
909  }
910 };
911 
912 /// GNUstep Objective-C ABI version 2 implementation.
913 /// This is the ABI that provides a clean break with the legacy GCC ABI and
914 /// cleans up a number of things that were added to work around 1980s linkers.
915 class CGObjCGNUstep2 : public CGObjCGNUstep {
916  enum SectionKind
917  {
918  SelectorSection = 0,
919  ClassSection,
920  ClassReferenceSection,
921  CategorySection,
922  ProtocolSection,
923  ProtocolReferenceSection,
924  ClassAliasSection,
925  ConstantStringSection
926  };
927  /// The subset of `objc_class_flags` used at compile time.
928  enum ClassFlags {
929  /// This is a metaclass
930  ClassFlagMeta = (1 << 0),
931  /// This class has been initialised by the runtime (+initialize has been
932  /// sent if necessary).
933  ClassFlagInitialized = (1 << 8),
934  };
935  static const char *const SectionsBaseNames[8];
936  static const char *const PECOFFSectionsBaseNames[8];
937  template<SectionKind K>
938  std::string sectionName() {
939  if (CGM.getTriple().isOSBinFormatCOFF()) {
940  std::string name(PECOFFSectionsBaseNames[K]);
941  name += "$m";
942  return name;
943  }
944  return SectionsBaseNames[K];
945  }
946  /// The GCC ABI superclass message lookup function. Takes a pointer to a
947  /// structure describing the receiver and the class, and a selector as
948  /// arguments. Returns the IMP for the corresponding method.
949  LazyRuntimeFunction MsgLookupSuperFn;
950  /// Function to ensure that +initialize is sent to a class.
951  LazyRuntimeFunction SentInitializeFn;
952  /// A flag indicating if we've emitted at least one protocol.
953  /// If we haven't, then we need to emit an empty protocol, to ensure that the
954  /// __start__objc_protocols and __stop__objc_protocols sections exist.
955  bool EmittedProtocol = false;
956  /// A flag indicating if we've emitted at least one protocol reference.
957  /// If we haven't, then we need to emit an empty protocol, to ensure that the
958  /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
959  /// exist.
960  bool EmittedProtocolRef = false;
961  /// A flag indicating if we've emitted at least one class.
962  /// If we haven't, then we need to emit an empty protocol, to ensure that the
963  /// __start__objc_classes and __stop__objc_classes sections / exist.
964  bool EmittedClass = false;
965  /// Generate the name of a symbol for a reference to a class. Accesses to
966  /// classes should be indirected via this.
967 
968  typedef std::pair<std::string, std::pair<llvm::GlobalVariable*, int>>
969  EarlyInitPair;
970  std::vector<EarlyInitPair> EarlyInitList;
971 
972  std::string SymbolForClassRef(StringRef Name, bool isWeak) {
973  if (isWeak)
974  return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
975  else
976  return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
977  }
978  /// Generate the name of a class symbol.
979  std::string SymbolForClass(StringRef Name) {
980  return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
981  }
982  void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
983  ArrayRef<llvm::Value*> Args) {
985  for (auto *Arg : Args)
986  Types.push_back(Arg->getType());
987  llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
988  false);
989  llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
990  B.CreateCall(Fn, Args);
991  }
992 
993  ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
994 
995  auto Str = SL->getString();
996  CharUnits Align = CGM.getPointerAlign();
997 
998  // Look for an existing one
999  llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1000  if (old != ObjCStrings.end())
1001  return ConstantAddress(old->getValue(), IdElemTy, Align);
1002 
1003  bool isNonASCII = SL->containsNonAscii();
1004 
1005  auto LiteralLength = SL->getLength();
1006 
1007  if ((CGM.getTarget().getPointerWidth(LangAS::Default) == 64) &&
1008  (LiteralLength < 9) && !isNonASCII) {
1009  // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
1010  // ASCII characters in the high 56 bits, followed by a 4-bit length and a
1011  // 3-bit tag (which is always 4).
1012  uint64_t str = 0;
1013  // Fill in the characters
1014  for (unsigned i=0 ; i<LiteralLength ; i++)
1015  str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
1016  // Fill in the length
1017  str |= LiteralLength << 3;
1018  // Set the tag
1019  str |= 4;
1020  auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
1021  llvm::ConstantInt::get(Int64Ty, str), IdTy);
1022  ObjCStrings[Str] = ObjCStr;
1023  return ConstantAddress(ObjCStr, IdElemTy, Align);
1024  }
1025 
1026  StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1027 
1028  if (StringClass.empty()) StringClass = "NSConstantString";
1029 
1030  std::string Sym = SymbolForClass(StringClass);
1031 
1032  llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1033 
1034  if (!isa) {
1035  isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1036  llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
1037  if (CGM.getTriple().isOSBinFormatCOFF()) {
1038  cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1039  }
1040  }
1041 
1042  // struct
1043  // {
1044  // Class isa;
1045  // uint32_t flags;
1046  // uint32_t length; // Number of codepoints
1047  // uint32_t size; // Number of bytes
1048  // uint32_t hash;
1049  // const char *data;
1050  // };
1051 
1052  ConstantInitBuilder Builder(CGM);
1053  auto Fields = Builder.beginStruct();
1054  if (!CGM.getTriple().isOSBinFormatCOFF()) {
1055  Fields.add(isa);
1056  } else {
1057  Fields.addNullPointer(PtrTy);
1058  }
1059  // For now, all non-ASCII strings are represented as UTF-16. As such, the
1060  // number of bytes is simply double the number of UTF-16 codepoints. In
1061  // ASCII strings, the number of bytes is equal to the number of non-ASCII
1062  // codepoints.
1063  if (isNonASCII) {
1064  unsigned NumU8CodeUnits = Str.size();
1065  // A UTF-16 representation of a unicode string contains at most the same
1066  // number of code units as a UTF-8 representation. Allocate that much
1067  // space, plus one for the final null character.
1068  SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1069  const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1070  llvm::UTF16 *ToPtr = &ToBuf[0];
1071  (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1072  &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1073  uint32_t StringLength = ToPtr - &ToBuf[0];
1074  // Add null terminator
1075  *ToPtr = 0;
1076  // Flags: 2 indicates UTF-16 encoding
1077  Fields.addInt(Int32Ty, 2);
1078  // Number of UTF-16 codepoints
1079  Fields.addInt(Int32Ty, StringLength);
1080  // Number of bytes
1081  Fields.addInt(Int32Ty, StringLength * 2);
1082  // Hash. Not currently initialised by the compiler.
1083  Fields.addInt(Int32Ty, 0);
1084  // pointer to the data string.
1085  auto Arr = llvm::ArrayRef(&ToBuf[0], ToPtr + 1);
1086  auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1087  auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1088  /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1089  Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1090  Fields.add(Buffer);
1091  } else {
1092  // Flags: 0 indicates ASCII encoding
1093  Fields.addInt(Int32Ty, 0);
1094  // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1095  Fields.addInt(Int32Ty, Str.size());
1096  // Number of bytes
1097  Fields.addInt(Int32Ty, Str.size());
1098  // Hash. Not currently initialised by the compiler.
1099  Fields.addInt(Int32Ty, 0);
1100  // Data pointer
1101  Fields.add(MakeConstantString(Str));
1102  }
1103  std::string StringName;
1104  bool isNamed = !isNonASCII;
1105  if (isNamed) {
1106  StringName = ".objc_str_";
1107  for (int i=0,e=Str.size() ; i<e ; ++i) {
1108  unsigned char c = Str[i];
1109  if (isalnum(c))
1110  StringName += c;
1111  else if (c == ' ')
1112  StringName += '_';
1113  else {
1114  isNamed = false;
1115  break;
1116  }
1117  }
1118  }
1119  llvm::GlobalVariable *ObjCStrGV =
1120  Fields.finishAndCreateGlobal(
1121  isNamed ? StringRef(StringName) : ".objc_string",
1122  Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1123  : llvm::GlobalValue::PrivateLinkage);
1124  ObjCStrGV->setSection(sectionName<ConstantStringSection>());
1125  if (isNamed) {
1126  ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1127  ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1128  }
1129  if (CGM.getTriple().isOSBinFormatCOFF()) {
1130  std::pair<llvm::GlobalVariable*, int> v{ObjCStrGV, 0};
1131  EarlyInitList.emplace_back(Sym, v);
1132  }
1133  ObjCStrings[Str] = ObjCStrGV;
1134  ConstantStrings.push_back(ObjCStrGV);
1135  return ConstantAddress(ObjCStrGV, IdElemTy, Align);
1136  }
1137 
1138  void PushProperty(ConstantArrayBuilder &PropertiesArray,
1139  const ObjCPropertyDecl *property,
1140  const Decl *OCD,
1141  bool isSynthesized=true, bool
1142  isDynamic=true) override {
1143  // struct objc_property
1144  // {
1145  // const char *name;
1146  // const char *attributes;
1147  // const char *type;
1148  // SEL getter;
1149  // SEL setter;
1150  // };
1151  auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1152  ASTContext &Context = CGM.getContext();
1153  Fields.add(MakeConstantString(property->getNameAsString()));
1154  std::string TypeStr =
1155  CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1156  Fields.add(MakeConstantString(TypeStr));
1157  std::string typeStr;
1158  Context.getObjCEncodingForType(property->getType(), typeStr);
1159  Fields.add(MakeConstantString(typeStr));
1160  auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1161  if (accessor) {
1162  std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1163  Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1164  } else {
1165  Fields.add(NULLPtr);
1166  }
1167  };
1168  addPropertyMethod(property->getGetterMethodDecl());
1169  addPropertyMethod(property->getSetterMethodDecl());
1170  Fields.finishAndAddTo(PropertiesArray);
1171  }
1172 
1173  llvm::Constant *
1174  GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1175  // struct objc_protocol_method_description
1176  // {
1177  // SEL selector;
1178  // const char *types;
1179  // };
1180  llvm::StructType *ObjCMethodDescTy =
1181  llvm::StructType::get(CGM.getLLVMContext(),
1182  { PtrToInt8Ty, PtrToInt8Ty });
1183  ASTContext &Context = CGM.getContext();
1184  ConstantInitBuilder Builder(CGM);
1185  // struct objc_protocol_method_description_list
1186  // {
1187  // int count;
1188  // int size;
1189  // struct objc_protocol_method_description methods[];
1190  // };
1191  auto MethodList = Builder.beginStruct();
1192  // int count;
1193  MethodList.addInt(IntTy, Methods.size());
1194  // int size; // sizeof(struct objc_method_description)
1195  llvm::DataLayout td(&TheModule);
1196  MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1197  CGM.getContext().getCharWidth());
1198  // struct objc_method_description[]
1199  auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1200  for (auto *M : Methods) {
1201  auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1202  Method.add(CGObjCGNU::GetConstantSelector(M));
1203  Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1204  Method.finishAndAddTo(MethodArray);
1205  }
1206  MethodArray.finishAndAddTo(MethodList);
1207  return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1208  CGM.getPointerAlign());
1209  }
1210  llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1211  override {
1212  const auto &ReferencedProtocols = OCD->getReferencedProtocols();
1213  auto RuntimeProtocols = GetRuntimeProtocolList(ReferencedProtocols.begin(),
1214  ReferencedProtocols.end());
1216  for (const auto *PI : RuntimeProtocols)
1217  Protocols.push_back(GenerateProtocolRef(PI));
1218  return GenerateProtocolList(Protocols);
1219  }
1220 
1221  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1222  llvm::Value *cmd, MessageSendInfo &MSI) override {
1223  // Don't access the slot unless we're trying to cache the result.
1224  CGBuilderTy &Builder = CGF.Builder;
1225  llvm::Value *lookupArgs[] = {
1226  CGObjCGNU::EnforceType(Builder, ObjCSuper.emitRawPointer(CGF),
1227  PtrToObjCSuperTy),
1228  cmd};
1229  return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1230  }
1231 
1232  llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1233  std::string SymbolName = SymbolForClassRef(Name, isWeak);
1234  auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1235  if (ClassSymbol)
1236  return ClassSymbol;
1237  ClassSymbol = new llvm::GlobalVariable(TheModule,
1238  IdTy, false, llvm::GlobalValue::ExternalLinkage,
1239  nullptr, SymbolName);
1240  // If this is a weak symbol, then we are creating a valid definition for
1241  // the symbol, pointing to a weak definition of the real class pointer. If
1242  // this is not a weak reference, then we are expecting another compilation
1243  // unit to provide the real indirection symbol.
1244  if (isWeak)
1245  ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1246  Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1247  nullptr, SymbolForClass(Name)));
1248  else {
1249  if (CGM.getTriple().isOSBinFormatCOFF()) {
1250  IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1253 
1254  const ObjCInterfaceDecl *OID = nullptr;
1255  for (const auto *Result : DC->lookup(&II))
1256  if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1257  break;
1258 
1259  // The first Interface we find may be a @class,
1260  // which should only be treated as the source of
1261  // truth in the absence of a true declaration.
1262  assert(OID && "Failed to find ObjCInterfaceDecl");
1263  const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
1264  if (OIDDef != nullptr)
1265  OID = OIDDef;
1266 
1267  auto Storage = llvm::GlobalValue::DefaultStorageClass;
1268  if (OID->hasAttr<DLLImportAttr>())
1269  Storage = llvm::GlobalValue::DLLImportStorageClass;
1270  else if (OID->hasAttr<DLLExportAttr>())
1271  Storage = llvm::GlobalValue::DLLExportStorageClass;
1272 
1273  cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1274  }
1275  }
1276  assert(ClassSymbol->getName() == SymbolName);
1277  return ClassSymbol;
1278  }
1279  llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1280  const std::string &Name,
1281  bool isWeak) override {
1282  return CGF.Builder.CreateLoad(
1283  Address(GetClassVar(Name, isWeak), IdTy, CGM.getPointerAlign()));
1284  }
1285  int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1286  // typedef enum {
1287  // ownership_invalid = 0,
1288  // ownership_strong = 1,
1289  // ownership_weak = 2,
1290  // ownership_unsafe = 3
1291  // } ivar_ownership;
1292  int Flag;
1293  switch (Ownership) {
1295  Flag = 1;
1296  break;
1297  case Qualifiers::OCL_Weak:
1298  Flag = 2;
1299  break;
1301  Flag = 3;
1302  break;
1303  case Qualifiers::OCL_None:
1305  assert(Ownership != Qualifiers::OCL_Autoreleasing);
1306  Flag = 0;
1307  }
1308  return Flag;
1309  }
1310  llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1311  ArrayRef<llvm::Constant *> IvarTypes,
1312  ArrayRef<llvm::Constant *> IvarOffsets,
1313  ArrayRef<llvm::Constant *> IvarAlign,
1314  ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1315  llvm_unreachable("Method should not be called!");
1316  }
1317 
1318  llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1319  std::string Name = SymbolForProtocol(ProtocolName);
1320  auto *GV = TheModule.getGlobalVariable(Name);
1321  if (!GV) {
1322  // Emit a placeholder symbol.
1323  GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1324  llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1325  GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1326  }
1327  return GV;
1328  }
1329 
1330  /// Existing protocol references.
1331  llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1332 
1333  llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1334  const ObjCProtocolDecl *PD) override {
1335  auto Name = PD->getNameAsString();
1336  auto *&Ref = ExistingProtocolRefs[Name];
1337  if (!Ref) {
1338  auto *&Protocol = ExistingProtocols[Name];
1339  if (!Protocol)
1340  Protocol = GenerateProtocolRef(PD);
1341  std::string RefName = SymbolForProtocolRef(Name);
1342  assert(!TheModule.getGlobalVariable(RefName));
1343  // Emit a reference symbol.
1344  auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy, false,
1345  llvm::GlobalValue::LinkOnceODRLinkage,
1346  Protocol, RefName);
1347  GV->setComdat(TheModule.getOrInsertComdat(RefName));
1348  GV->setSection(sectionName<ProtocolReferenceSection>());
1349  GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1350  Ref = GV;
1351  }
1352  EmittedProtocolRef = true;
1353  return CGF.Builder.CreateAlignedLoad(ProtocolPtrTy, Ref,
1354  CGM.getPointerAlign());
1355  }
1356 
1357  llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1358  llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1359  Protocols.size());
1360  llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1361  Protocols);
1362  ConstantInitBuilder builder(CGM);
1363  auto ProtocolBuilder = builder.beginStruct();
1364  ProtocolBuilder.addNullPointer(PtrTy);
1365  ProtocolBuilder.addInt(SizeTy, Protocols.size());
1366  ProtocolBuilder.add(ProtocolArray);
1367  return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1368  CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1369  }
1370 
1371  void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1372  // Do nothing - we only emit referenced protocols.
1373  }
1374  llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) override {
1375  std::string ProtocolName = PD->getNameAsString();
1376  auto *&Protocol = ExistingProtocols[ProtocolName];
1377  if (Protocol)
1378  return Protocol;
1379 
1380  EmittedProtocol = true;
1381 
1382  auto SymName = SymbolForProtocol(ProtocolName);
1383  auto *OldGV = TheModule.getGlobalVariable(SymName);
1384 
1385  // Use the protocol definition, if there is one.
1386  if (const ObjCProtocolDecl *Def = PD->getDefinition())
1387  PD = Def;
1388  else {
1389  // If there is no definition, then create an external linkage symbol and
1390  // hope that someone else fills it in for us (and fail to link if they
1391  // don't).
1392  assert(!OldGV);
1393  Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1394  /*isConstant*/false,
1395  llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1396  return Protocol;
1397  }
1398 
1400  auto RuntimeProtocols =
1401  GetRuntimeProtocolList(PD->protocol_begin(), PD->protocol_end());
1402  for (const auto *PI : RuntimeProtocols)
1403  Protocols.push_back(GenerateProtocolRef(PI));
1404  llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1405 
1406  // Collect information about methods
1407  llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1408  llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1409  EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1410  OptionalInstanceMethodList);
1411  EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1412  OptionalClassMethodList);
1413 
1414  // The isa pointer must be set to a magic number so the runtime knows it's
1415  // the correct layout.
1416  ConstantInitBuilder builder(CGM);
1417  auto ProtocolBuilder = builder.beginStruct();
1418  ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1419  llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1420  ProtocolBuilder.add(MakeConstantString(ProtocolName));
1421  ProtocolBuilder.add(ProtocolList);
1422  ProtocolBuilder.add(InstanceMethodList);
1423  ProtocolBuilder.add(ClassMethodList);
1424  ProtocolBuilder.add(OptionalInstanceMethodList);
1425  ProtocolBuilder.add(OptionalClassMethodList);
1426  // Required instance properties
1427  ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1428  // Optional instance properties
1429  ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1430  // Required class properties
1431  ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1432  // Optional class properties
1433  ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1434 
1435  auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1436  CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1437  GV->setSection(sectionName<ProtocolSection>());
1438  GV->setComdat(TheModule.getOrInsertComdat(SymName));
1439  if (OldGV) {
1440  OldGV->replaceAllUsesWith(GV);
1441  OldGV->removeFromParent();
1442  GV->setName(SymName);
1443  }
1444  Protocol = GV;
1445  return GV;
1446  }
1447  llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1448  const std::string &TypeEncoding) override {
1449  return GetConstantSelector(Sel, TypeEncoding);
1450  }
1451  std::string GetSymbolNameForTypeEncoding(const std::string &TypeEncoding) {
1452  std::string MangledTypes = std::string(TypeEncoding);
1453  // @ is used as a special character in ELF symbol names (used for symbol
1454  // versioning), so mangle the name to not include it. Replace it with a
1455  // character that is not a valid type encoding character (and, being
1456  // non-printable, never will be!)
1457  if (CGM.getTriple().isOSBinFormatELF())
1458  std::replace(MangledTypes.begin(), MangledTypes.end(), '@', '\1');
1459  // = in dll exported names causes lld to fail when linking on Windows.
1460  if (CGM.getTriple().isOSWindows())
1461  std::replace(MangledTypes.begin(), MangledTypes.end(), '=', '\2');
1462  return MangledTypes;
1463  }
1464  llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1465  if (TypeEncoding.empty())
1466  return NULLPtr;
1467  std::string MangledTypes =
1468  GetSymbolNameForTypeEncoding(std::string(TypeEncoding));
1469  std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1470  auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1471  if (!TypesGlobal) {
1472  llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1473  TypeEncoding);
1474  auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1475  true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
1476  GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
1477  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1478  TypesGlobal = GV;
1479  }
1480  return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1481  TypesGlobal, Zeros);
1482  }
1483  llvm::Constant *GetConstantSelector(Selector Sel,
1484  const std::string &TypeEncoding) override {
1485  std::string MangledTypes = GetSymbolNameForTypeEncoding(TypeEncoding);
1486  auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1487  MangledTypes).str();
1488  if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1489  return GV;
1490  ConstantInitBuilder builder(CGM);
1491  auto SelBuilder = builder.beginStruct();
1492  SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1493  true));
1494  SelBuilder.add(GetTypeString(TypeEncoding));
1495  auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1496  CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1497  GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1498  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1499  GV->setSection(sectionName<SelectorSection>());
1500  return GV;
1501  }
1502  llvm::StructType *emptyStruct = nullptr;
1503 
1504  /// Return pointers to the start and end of a section. On ELF platforms, we
1505  /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1506  /// to the start and end of section names, as long as those section names are
1507  /// valid identifiers and the symbols are referenced but not defined. On
1508  /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1509  /// by subsections and place everything that we want to reference in a middle
1510  /// subsection and then insert zero-sized symbols in subsections a and z.
1511  std::pair<llvm::Constant*,llvm::Constant*>
1512  GetSectionBounds(StringRef Section) {
1513  if (CGM.getTriple().isOSBinFormatCOFF()) {
1514  if (emptyStruct == nullptr) {
1515  emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1516  emptyStruct->setBody({}, /*isPacked*/true);
1517  }
1518  auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1519  auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1520  auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1521  /*isConstant*/false,
1522  llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1523  Section);
1524  Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1525  Sym->setSection((Section + SecSuffix).str());
1526  Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1527  Section).str()));
1528  Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
1529  return Sym;
1530  };
1531  return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1532  }
1533  auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1534  /*isConstant*/false,
1535  llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1536  Section);
1537  Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1538  auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1539  /*isConstant*/false,
1540  llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1541  Section);
1542  Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1543  return { Start, Stop };
1544  }
1545  CatchTypeInfo getCatchAllTypeInfo() override {
1546  return CGM.getCXXABI().getCatchAllTypeInfo();
1547  }
1548  llvm::Function *ModuleInitFunction() override {
1549  llvm::Function *LoadFunction = llvm::Function::Create(
1550  llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1551  llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1552  &TheModule);
1553  LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1554  LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1555 
1556  llvm::BasicBlock *EntryBB =
1557  llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1558  CGBuilderTy B(CGM, VMContext);
1559  B.SetInsertPoint(EntryBB);
1560  ConstantInitBuilder builder(CGM);
1561  auto InitStructBuilder = builder.beginStruct();
1562  InitStructBuilder.addInt(Int64Ty, 0);
1563  auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1564  for (auto *s : sectionVec) {
1565  auto bounds = GetSectionBounds(s);
1566  InitStructBuilder.add(bounds.first);
1567  InitStructBuilder.add(bounds.second);
1568  }
1569  auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1570  CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1571  InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1572  InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1573 
1574  CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1575  B.CreateRetVoid();
1576  // Make sure that the optimisers don't delete this function.
1577  CGM.addCompilerUsedGlobal(LoadFunction);
1578  // FIXME: Currently ELF only!
1579  // We have to do this by hand, rather than with @llvm.ctors, so that the
1580  // linker can remove the duplicate invocations.
1581  auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1582  /*isConstant*/false, llvm::GlobalValue::LinkOnceAnyLinkage,
1583  LoadFunction, ".objc_ctor");
1584  // Check that this hasn't been renamed. This shouldn't happen, because
1585  // this function should be called precisely once.
1586  assert(InitVar->getName() == ".objc_ctor");
1587  // In Windows, initialisers are sorted by the suffix. XCL is for library
1588  // initialisers, which run before user initialisers. We are running
1589  // Objective-C loads at the end of library load. This means +load methods
1590  // will run before any other static constructors, but that static
1591  // constructors can see a fully initialised Objective-C state.
1592  if (CGM.getTriple().isOSBinFormatCOFF())
1593  InitVar->setSection(".CRT$XCLz");
1594  else
1595  {
1596  if (CGM.getCodeGenOpts().UseInitArray)
1597  InitVar->setSection(".init_array");
1598  else
1599  InitVar->setSection(".ctors");
1600  }
1601  InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1602  InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
1603  CGM.addUsedGlobal(InitVar);
1604  for (auto *C : Categories) {
1605  auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
1606  Cat->setSection(sectionName<CategorySection>());
1607  CGM.addUsedGlobal(Cat);
1608  }
1609  auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1610  StringRef Section) {
1611  auto nullBuilder = builder.beginStruct();
1612  for (auto *F : Init)
1613  nullBuilder.add(F);
1614  auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1615  false, llvm::GlobalValue::LinkOnceODRLinkage);
1616  GV->setSection(Section);
1617  GV->setComdat(TheModule.getOrInsertComdat(Name));
1618  GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1619  CGM.addUsedGlobal(GV);
1620  return GV;
1621  };
1622  for (auto clsAlias : ClassAliases)
1623  createNullGlobal(std::string(".objc_class_alias") +
1624  clsAlias.second, { MakeConstantString(clsAlias.second),
1625  GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1626  // On ELF platforms, add a null value for each special section so that we
1627  // can always guarantee that the _start and _stop symbols will exist and be
1628  // meaningful. This is not required on COFF platforms, where our start and
1629  // stop symbols will create the section.
1630  if (!CGM.getTriple().isOSBinFormatCOFF()) {
1631  createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1632  sectionName<SelectorSection>());
1633  if (Categories.empty())
1634  createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1635  NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1636  sectionName<CategorySection>());
1637  if (!EmittedClass) {
1638  createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
1639  sectionName<ClassSection>());
1640  createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1641  sectionName<ClassReferenceSection>());
1642  }
1643  if (!EmittedProtocol)
1644  createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1645  NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1646  NULLPtr}, sectionName<ProtocolSection>());
1647  if (!EmittedProtocolRef)
1648  createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1649  sectionName<ProtocolReferenceSection>());
1650  if (ClassAliases.empty())
1651  createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1652  sectionName<ClassAliasSection>());
1653  if (ConstantStrings.empty()) {
1654  auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1655  createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1656  i32Zero, i32Zero, i32Zero, NULLPtr },
1657  sectionName<ConstantStringSection>());
1658  }
1659  }
1660  ConstantStrings.clear();
1661  Categories.clear();
1662  Classes.clear();
1663 
1664  if (EarlyInitList.size() > 0) {
1665  auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1666  {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1667  &CGM.getModule());
1668  llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1669  Init));
1670  for (const auto &lateInit : EarlyInitList) {
1671  auto *global = TheModule.getGlobalVariable(lateInit.first);
1672  if (global) {
1673  llvm::GlobalVariable *GV = lateInit.second.first;
1674  b.CreateAlignedStore(
1675  global,
1676  b.CreateStructGEP(GV->getValueType(), GV, lateInit.second.second),
1677  CGM.getPointerAlign().getAsAlign());
1678  }
1679  }
1680  b.CreateRetVoid();
1681  // We can't use the normal LLVM global initialisation array, because we
1682  // need to specify that this runs early in library initialisation.
1683  auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1684  /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1685  Init, ".objc_early_init_ptr");
1686  InitVar->setSection(".CRT$XCLb");
1687  CGM.addUsedGlobal(InitVar);
1688  }
1689  return nullptr;
1690  }
1691  /// In the v2 ABI, ivar offset variables use the type encoding in their name
1692  /// to trigger linker failures if the types don't match.
1693  std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1694  const ObjCIvarDecl *Ivar) override {
1695  std::string TypeEncoding;
1696  CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1697  TypeEncoding = GetSymbolNameForTypeEncoding(TypeEncoding);
1698  const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1699  + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1700  return Name;
1701  }
1702  llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1703  const ObjCInterfaceDecl *Interface,
1704  const ObjCIvarDecl *Ivar) override {
1705  const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1706  llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1707  if (!IvarOffsetPointer)
1708  IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1709  llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1710  CharUnits Align = CGM.getIntAlign();
1711  llvm::Value *Offset =
1712  CGF.Builder.CreateAlignedLoad(IntTy, IvarOffsetPointer, Align);
1713  if (Offset->getType() != PtrDiffTy)
1714  Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1715  return Offset;
1716  }
1717  void GenerateClass(const ObjCImplementationDecl *OID) override {
1718  ASTContext &Context = CGM.getContext();
1719  bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
1720 
1721  // Get the class name
1722  ObjCInterfaceDecl *classDecl =
1723  const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1724  std::string className = classDecl->getNameAsString();
1725  auto *classNameConstant = MakeConstantString(className);
1726 
1727  ConstantInitBuilder builder(CGM);
1728  auto metaclassFields = builder.beginStruct();
1729  // struct objc_class *isa;
1730  metaclassFields.addNullPointer(PtrTy);
1731  // struct objc_class *super_class;
1732  metaclassFields.addNullPointer(PtrTy);
1733  // const char *name;
1734  metaclassFields.add(classNameConstant);
1735  // long version;
1736  metaclassFields.addInt(LongTy, 0);
1737  // unsigned long info;
1738  // objc_class_flag_meta
1739  metaclassFields.addInt(LongTy, ClassFlags::ClassFlagMeta);
1740  // long instance_size;
1741  // Setting this to zero is consistent with the older ABI, but it might be
1742  // more sensible to set this to sizeof(struct objc_class)
1743  metaclassFields.addInt(LongTy, 0);
1744  // struct objc_ivar_list *ivars;
1745  metaclassFields.addNullPointer(PtrTy);
1746  // struct objc_method_list *methods
1747  // FIXME: Almost identical code is copied and pasted below for the
1748  // class, but refactoring it cleanly requires C++14 generic lambdas.
1749  if (OID->classmeth_begin() == OID->classmeth_end())
1750  metaclassFields.addNullPointer(PtrTy);
1751  else {
1752  SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1753  ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1754  OID->classmeth_end());
1755  metaclassFields.add(
1756  GenerateMethodList(className, "", ClassMethods, true));
1757  }
1758  // void *dtable;
1759  metaclassFields.addNullPointer(PtrTy);
1760  // IMP cxx_construct;
1761  metaclassFields.addNullPointer(PtrTy);
1762  // IMP cxx_destruct;
1763  metaclassFields.addNullPointer(PtrTy);
1764  // struct objc_class *subclass_list
1765  metaclassFields.addNullPointer(PtrTy);
1766  // struct objc_class *sibling_class
1767  metaclassFields.addNullPointer(PtrTy);
1768  // struct objc_protocol_list *protocols;
1769  metaclassFields.addNullPointer(PtrTy);
1770  // struct reference_list *extra_data;
1771  metaclassFields.addNullPointer(PtrTy);
1772  // long abi_version;
1773  metaclassFields.addInt(LongTy, 0);
1774  // struct objc_property_list *properties
1775  metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1776 
1777  auto *metaclass = metaclassFields.finishAndCreateGlobal(
1778  ManglePublicSymbol("OBJC_METACLASS_") + className,
1779  CGM.getPointerAlign());
1780 
1781  auto classFields = builder.beginStruct();
1782  // struct objc_class *isa;
1783  classFields.add(metaclass);
1784  // struct objc_class *super_class;
1785  // Get the superclass name.
1786  const ObjCInterfaceDecl * SuperClassDecl =
1787  OID->getClassInterface()->getSuperClass();
1788  llvm::Constant *SuperClass = nullptr;
1789  if (SuperClassDecl) {
1790  auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1791  SuperClass = TheModule.getNamedGlobal(SuperClassName);
1792  if (!SuperClass)
1793  {
1794  SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1795  llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1796  if (IsCOFF) {
1797  auto Storage = llvm::GlobalValue::DefaultStorageClass;
1798  if (SuperClassDecl->hasAttr<DLLImportAttr>())
1799  Storage = llvm::GlobalValue::DLLImportStorageClass;
1800  else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1801  Storage = llvm::GlobalValue::DLLExportStorageClass;
1802 
1803  cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1804  }
1805  }
1806  if (!IsCOFF)
1807  classFields.add(SuperClass);
1808  else
1809  classFields.addNullPointer(PtrTy);
1810  } else
1811  classFields.addNullPointer(PtrTy);
1812  // const char *name;
1813  classFields.add(classNameConstant);
1814  // long version;
1815  classFields.addInt(LongTy, 0);
1816  // unsigned long info;
1817  // !objc_class_flag_meta
1818  classFields.addInt(LongTy, 0);
1819  // long instance_size;
1820  int superInstanceSize = !SuperClassDecl ? 0 :
1821  Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1822  // Instance size is negative for classes that have not yet had their ivar
1823  // layout calculated.
1824  classFields.addInt(LongTy,
1825  0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1826  superInstanceSize));
1827 
1828  if (classDecl->all_declared_ivar_begin() == nullptr)
1829  classFields.addNullPointer(PtrTy);
1830  else {
1831  int ivar_count = 0;
1832  for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1833  IVD = IVD->getNextIvar()) ivar_count++;
1834  llvm::DataLayout td(&TheModule);
1835  // struct objc_ivar_list *ivars;
1836  ConstantInitBuilder b(CGM);
1837  auto ivarListBuilder = b.beginStruct();
1838  // int count;
1839  ivarListBuilder.addInt(IntTy, ivar_count);
1840  // size_t size;
1841  llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1842  PtrToInt8Ty,
1843  PtrToInt8Ty,
1844  PtrToInt8Ty,
1845  Int32Ty,
1846  Int32Ty);
1847  ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1848  CGM.getContext().getCharWidth());
1849  // struct objc_ivar ivars[]
1850  auto ivarArrayBuilder = ivarListBuilder.beginArray();
1851  for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1852  IVD = IVD->getNextIvar()) {
1853  auto ivarTy = IVD->getType();
1854  auto ivarBuilder = ivarArrayBuilder.beginStruct();
1855  // const char *name;
1856  ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1857  // const char *type;
1858  std::string TypeStr;
1859  //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1860  Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1861  ivarBuilder.add(MakeConstantString(TypeStr));
1862  // int *offset;
1863  uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1864  uint64_t Offset = BaseOffset - superInstanceSize;
1865  llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1866  std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1867  llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1868  if (OffsetVar)
1869  OffsetVar->setInitializer(OffsetValue);
1870  else
1871  OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1872  false, llvm::GlobalValue::ExternalLinkage,
1873  OffsetValue, OffsetName);
1874  auto ivarVisibility =
1875  (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1876  IVD->getAccessControl() == ObjCIvarDecl::Package ||
1877  classDecl->getVisibility() == HiddenVisibility) ?
1880  OffsetVar->setVisibility(ivarVisibility);
1881  if (ivarVisibility != llvm::GlobalValue::HiddenVisibility)
1882  CGM.setGVProperties(OffsetVar, OID->getClassInterface());
1883  ivarBuilder.add(OffsetVar);
1884  // Ivar size
1885  ivarBuilder.addInt(Int32Ty,
1886  CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
1887  // Alignment will be stored as a base-2 log of the alignment.
1888  unsigned align =
1889  llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1890  // Objects that require more than 2^64-byte alignment should be impossible!
1891  assert(align < 64);
1892  // uint32_t flags;
1893  // Bits 0-1 are ownership.
1894  // Bit 2 indicates an extended type encoding
1895  // Bits 3-8 contain log2(aligment)
1896  ivarBuilder.addInt(Int32Ty,
1897  (align << 3) | (1<<2) |
1898  FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1899  ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1900  }
1901  ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1902  auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
1903  CGM.getPointerAlign(), /*constant*/ false,
1904  llvm::GlobalValue::PrivateLinkage);
1905  classFields.add(ivarList);
1906  }
1907  // struct objc_method_list *methods
1909  InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1910  OID->instmeth_end());
1911  for (auto *propImpl : OID->property_impls())
1912  if (propImpl->getPropertyImplementation() ==
1914  auto addIfExists = [&](const ObjCMethodDecl *OMD) {
1915  if (OMD && OMD->hasBody())
1916  InstanceMethods.push_back(OMD);
1917  };
1918  addIfExists(propImpl->getGetterMethodDecl());
1919  addIfExists(propImpl->getSetterMethodDecl());
1920  }
1921 
1922  if (InstanceMethods.size() == 0)
1923  classFields.addNullPointer(PtrTy);
1924  else
1925  classFields.add(
1926  GenerateMethodList(className, "", InstanceMethods, false));
1927 
1928  // void *dtable;
1929  classFields.addNullPointer(PtrTy);
1930  // IMP cxx_construct;
1931  classFields.addNullPointer(PtrTy);
1932  // IMP cxx_destruct;
1933  classFields.addNullPointer(PtrTy);
1934  // struct objc_class *subclass_list
1935  classFields.addNullPointer(PtrTy);
1936  // struct objc_class *sibling_class
1937  classFields.addNullPointer(PtrTy);
1938  // struct objc_protocol_list *protocols;
1939  auto RuntimeProtocols = GetRuntimeProtocolList(classDecl->protocol_begin(),
1940  classDecl->protocol_end());
1942  for (const auto *I : RuntimeProtocols)
1943  Protocols.push_back(GenerateProtocolRef(I));
1944 
1945  if (Protocols.empty())
1946  classFields.addNullPointer(PtrTy);
1947  else
1948  classFields.add(GenerateProtocolList(Protocols));
1949  // struct reference_list *extra_data;
1950  classFields.addNullPointer(PtrTy);
1951  // long abi_version;
1952  classFields.addInt(LongTy, 0);
1953  // struct objc_property_list *properties
1954  classFields.add(GeneratePropertyList(OID, classDecl));
1955 
1956  llvm::GlobalVariable *classStruct =
1957  classFields.finishAndCreateGlobal(SymbolForClass(className),
1958  CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1959 
1960  auto *classRefSymbol = GetClassVar(className);
1961  classRefSymbol->setSection(sectionName<ClassReferenceSection>());
1962  classRefSymbol->setInitializer(classStruct);
1963 
1964  if (IsCOFF) {
1965  // we can't import a class struct.
1966  if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1967  classStruct->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1968  cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1969  }
1970 
1971  if (SuperClass) {
1972  std::pair<llvm::GlobalVariable*, int> v{classStruct, 1};
1973  EarlyInitList.emplace_back(std::string(SuperClass->getName()),
1974  std::move(v));
1975  }
1976 
1977  }
1978 
1979 
1980  // Resolve the class aliases, if they exist.
1981  // FIXME: Class pointer aliases shouldn't exist!
1982  if (ClassPtrAlias) {
1983  ClassPtrAlias->replaceAllUsesWith(classStruct);
1984  ClassPtrAlias->eraseFromParent();
1985  ClassPtrAlias = nullptr;
1986  }
1987  if (auto Placeholder =
1988  TheModule.getNamedGlobal(SymbolForClass(className)))
1989  if (Placeholder != classStruct) {
1990  Placeholder->replaceAllUsesWith(classStruct);
1991  Placeholder->eraseFromParent();
1992  classStruct->setName(SymbolForClass(className));
1993  }
1994  if (MetaClassPtrAlias) {
1995  MetaClassPtrAlias->replaceAllUsesWith(metaclass);
1996  MetaClassPtrAlias->eraseFromParent();
1997  MetaClassPtrAlias = nullptr;
1998  }
1999  assert(classStruct->getName() == SymbolForClass(className));
2000 
2001  auto classInitRef = new llvm::GlobalVariable(TheModule,
2002  classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
2003  classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
2004  classInitRef->setSection(sectionName<ClassSection>());
2005  CGM.addUsedGlobal(classInitRef);
2006 
2007  EmittedClass = true;
2008  }
2009  public:
2010  CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
2011  MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2012  PtrToObjCSuperTy, SelectorTy);
2013  SentInitializeFn.init(&CGM, "objc_send_initialize",
2014  llvm::Type::getVoidTy(VMContext), IdTy);
2015  // struct objc_property
2016  // {
2017  // const char *name;
2018  // const char *attributes;
2019  // const char *type;
2020  // SEL getter;
2021  // SEL setter;
2022  // }
2023  PropertyMetadataTy =
2024  llvm::StructType::get(CGM.getLLVMContext(),
2025  { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
2026  }
2027 
2028  void GenerateDirectMethodPrologue(CodeGenFunction &CGF, llvm::Function *Fn,
2029  const ObjCMethodDecl *OMD,
2030  const ObjCContainerDecl *CD) override {
2031  auto &Builder = CGF.Builder;
2032  bool ReceiverCanBeNull = true;
2033  auto selfAddr = CGF.GetAddrOfLocalVar(OMD->getSelfDecl());
2034  auto selfValue = Builder.CreateLoad(selfAddr);
2035 
2036  // Generate:
2037  //
2038  // /* unless the receiver is never NULL */
2039  // if (self == nil) {
2040  // return (ReturnType){ };
2041  // }
2042  //
2043  // /* for class methods only to force class lazy initialization */
2044  // if (!__objc_{class}_initialized)
2045  // {
2046  // objc_send_initialize(class);
2047  // __objc_{class}_initialized = 1;
2048  // }
2049  //
2050  // _cmd = @selector(...)
2051  // ...
2052 
2053  if (OMD->isClassMethod()) {
2054  const ObjCInterfaceDecl *OID = cast<ObjCInterfaceDecl>(CD);
2055 
2056  // Nullable `Class` expressions cannot be messaged with a direct method
2057  // so the only reason why the receive can be null would be because
2058  // of weak linking.
2059  ReceiverCanBeNull = isWeakLinkedClass(OID);
2060  }
2061 
2062  llvm::MDBuilder MDHelper(CGM.getLLVMContext());
2063  if (ReceiverCanBeNull) {
2064  llvm::BasicBlock *SelfIsNilBlock =
2065  CGF.createBasicBlock("objc_direct_method.self_is_nil");
2066  llvm::BasicBlock *ContBlock =
2067  CGF.createBasicBlock("objc_direct_method.cont");
2068 
2069  // if (self == nil) {
2070  auto selfTy = cast<llvm::PointerType>(selfValue->getType());
2071  auto Zero = llvm::ConstantPointerNull::get(selfTy);
2072 
2073  Builder.CreateCondBr(Builder.CreateICmpEQ(selfValue, Zero),
2074  SelfIsNilBlock, ContBlock,
2075  MDHelper.createBranchWeights(1, 1 << 20));
2076 
2077  CGF.EmitBlock(SelfIsNilBlock);
2078 
2079  // return (ReturnType){ };
2080  auto retTy = OMD->getReturnType();
2081  Builder.SetInsertPoint(SelfIsNilBlock);
2082  if (!retTy->isVoidType()) {
2083  CGF.EmitNullInitialization(CGF.ReturnValue, retTy);
2084  }
2086  // }
2087 
2088  // rest of the body
2089  CGF.EmitBlock(ContBlock);
2090  Builder.SetInsertPoint(ContBlock);
2091  }
2092 
2093  if (OMD->isClassMethod()) {
2094  // Prefix of the class type.
2095  auto *classStart =
2096  llvm::StructType::get(PtrTy, PtrTy, PtrTy, LongTy, LongTy);
2097  auto &astContext = CGM.getContext();
2098  auto flags = Builder.CreateLoad(
2099  Address{Builder.CreateStructGEP(classStart, selfValue, 4), LongTy,
2101  astContext.getTypeAlign(astContext.UnsignedLongTy))});
2102  auto isInitialized =
2103  Builder.CreateAnd(flags, ClassFlags::ClassFlagInitialized);
2104  llvm::BasicBlock *notInitializedBlock =
2105  CGF.createBasicBlock("objc_direct_method.class_uninitialized");
2106  llvm::BasicBlock *initializedBlock =
2107  CGF.createBasicBlock("objc_direct_method.class_initialized");
2108  Builder.CreateCondBr(Builder.CreateICmpEQ(isInitialized, Zeros[0]),
2109  notInitializedBlock, initializedBlock,
2110  MDHelper.createBranchWeights(1, 1 << 20));
2111  CGF.EmitBlock(notInitializedBlock);
2112  Builder.SetInsertPoint(notInitializedBlock);
2113  CGF.EmitRuntimeCall(SentInitializeFn, selfValue);
2114  Builder.CreateBr(initializedBlock);
2115  CGF.EmitBlock(initializedBlock);
2116  Builder.SetInsertPoint(initializedBlock);
2117  }
2118 
2119  // only synthesize _cmd if it's referenced
2120  if (OMD->getCmdDecl()->isUsed()) {
2121  // `_cmd` is not a parameter to direct methods, so storage must be
2122  // explicitly declared for it.
2123  CGF.EmitVarDecl(*OMD->getCmdDecl());
2124  Builder.CreateStore(GetSelector(CGF, OMD),
2125  CGF.GetAddrOfLocalVar(OMD->getCmdDecl()));
2126  }
2127  }
2128 };
2129 
2130 const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
2131 {
2132 "__objc_selectors",
2133 "__objc_classes",
2134 "__objc_class_refs",
2135 "__objc_cats",
2136 "__objc_protocols",
2137 "__objc_protocol_refs",
2138 "__objc_class_aliases",
2139 "__objc_constant_string"
2140 };
2141 
2142 const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2143 {
2144 ".objcrt$SEL",
2145 ".objcrt$CLS",
2146 ".objcrt$CLR",
2147 ".objcrt$CAT",
2148 ".objcrt$PCL",
2149 ".objcrt$PCR",
2150 ".objcrt$CAL",
2151 ".objcrt$STR"
2152 };
2153 
2154 /// Support for the ObjFW runtime.
2155 class CGObjCObjFW: public CGObjCGNU {
2156 protected:
2157  /// The GCC ABI message lookup function. Returns an IMP pointing to the
2158  /// method implementation for this message.
2159  LazyRuntimeFunction MsgLookupFn;
2160  /// stret lookup function. While this does not seem to make sense at the
2161  /// first look, this is required to call the correct forwarding function.
2162  LazyRuntimeFunction MsgLookupFnSRet;
2163  /// The GCC ABI superclass message lookup function. Takes a pointer to a
2164  /// structure describing the receiver and the class, and a selector as
2165  /// arguments. Returns the IMP for the corresponding method.
2166  LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
2167 
2168  llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2169  llvm::Value *cmd, llvm::MDNode *node,
2170  MessageSendInfo &MSI) override {
2171  CGBuilderTy &Builder = CGF.Builder;
2172  llvm::Value *args[] = {
2173  EnforceType(Builder, Receiver, IdTy),
2174  EnforceType(Builder, cmd, SelectorTy) };
2175 
2176  llvm::CallBase *imp;
2177  if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2178  imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2179  else
2180  imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2181 
2182  imp->setMetadata(msgSendMDKind, node);
2183  return imp;
2184  }
2185 
2186  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
2187  llvm::Value *cmd, MessageSendInfo &MSI) override {
2188  CGBuilderTy &Builder = CGF.Builder;
2189  llvm::Value *lookupArgs[] = {
2190  EnforceType(Builder, ObjCSuper.emitRawPointer(CGF), PtrToObjCSuperTy),
2191  cmd,
2192  };
2193 
2194  if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2195  return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2196  else
2197  return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2198  }
2199 
2200  llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2201  bool isWeak) override {
2202  if (isWeak)
2203  return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
2204 
2205  EmitClassRef(Name);
2206  std::string SymbolName = "_OBJC_CLASS_" + Name;
2207  llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
2208  if (!ClassSymbol)
2209  ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2210  llvm::GlobalValue::ExternalLinkage,
2211  nullptr, SymbolName);
2212  return ClassSymbol;
2213  }
2214 
2215 public:
2216  CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2217  // IMP objc_msg_lookup(id, SEL);
2218  MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
2219  MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
2220  SelectorTy);
2221  // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2222  MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2223  PtrToObjCSuperTy, SelectorTy);
2224  MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
2225  PtrToObjCSuperTy, SelectorTy);
2226  }
2227 };
2228 } // end anonymous namespace
2229 
2230 /// Emits a reference to a dummy variable which is emitted with each class.
2231 /// This ensures that a linker error will be generated when trying to link
2232 /// together modules where a referenced class is not defined.
2233 void CGObjCGNU::EmitClassRef(const std::string &className) {
2234  std::string symbolRef = "__objc_class_ref_" + className;
2235  // Don't emit two copies of the same symbol
2236  if (TheModule.getGlobalVariable(symbolRef))
2237  return;
2238  std::string symbolName = "__objc_class_name_" + className;
2239  llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2240  if (!ClassSymbol) {
2241  ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2242  llvm::GlobalValue::ExternalLinkage,
2243  nullptr, symbolName);
2244  }
2245  new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
2246  llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
2247 }
2248 
2249 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
2250  unsigned protocolClassVersion, unsigned classABI)
2251  : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
2252  VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2253  MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
2254  ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
2255 
2256  msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
2257  usesSEHExceptions =
2258  cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2259  usesCxxExceptions =
2260  cgm.getContext().getTargetInfo().getTriple().isOSCygMing() &&
2261  isRuntime(ObjCRuntime::GNUstep, 2);
2262 
2263  CodeGenTypes &Types = CGM.getTypes();
2264  IntTy = cast<llvm::IntegerType>(
2265  Types.ConvertType(CGM.getContext().IntTy));
2266  LongTy = cast<llvm::IntegerType>(
2267  Types.ConvertType(CGM.getContext().LongTy));
2268  SizeTy = cast<llvm::IntegerType>(
2269  Types.ConvertType(CGM.getContext().getSizeType()));
2270  PtrDiffTy = cast<llvm::IntegerType>(
2271  Types.ConvertType(CGM.getContext().getPointerDiffType()));
2272  BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
2273 
2274  Int8Ty = llvm::Type::getInt8Ty(VMContext);
2275  // C string type. Used in lots of places.
2276  PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
2277  ProtocolPtrTy = llvm::PointerType::getUnqual(
2278  Types.ConvertType(CGM.getContext().getObjCProtoType()));
2279 
2280  Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
2281  Zeros[1] = Zeros[0];
2282  NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2283  // Get the selector Type.
2284  QualType selTy = CGM.getContext().getObjCSelType();
2285  if (QualType() == selTy) {
2286  SelectorTy = PtrToInt8Ty;
2287  SelectorElemTy = Int8Ty;
2288  } else {
2289  SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2290  SelectorElemTy = CGM.getTypes().ConvertTypeForMem(selTy->getPointeeType());
2291  }
2292 
2293  PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
2294  PtrTy = PtrToInt8Ty;
2295 
2296  Int32Ty = llvm::Type::getInt32Ty(VMContext);
2297  Int64Ty = llvm::Type::getInt64Ty(VMContext);
2298 
2299  IntPtrTy =
2300  CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
2301 
2302  // Object type
2303  QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2304  ASTIdTy = CanQualType();
2305  if (UnqualIdTy != QualType()) {
2306  ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
2307  IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2308  IdElemTy = CGM.getTypes().ConvertTypeForMem(
2309  ASTIdTy.getTypePtr()->getPointeeType());
2310  } else {
2311  IdTy = PtrToInt8Ty;
2312  IdElemTy = Int8Ty;
2313  }
2314  PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
2315  ProtocolTy = llvm::StructType::get(IdTy,
2316  PtrToInt8Ty, // name
2317  PtrToInt8Ty, // protocols
2318  PtrToInt8Ty, // instance methods
2319  PtrToInt8Ty, // class methods
2320  PtrToInt8Ty, // optional instance methods
2321  PtrToInt8Ty, // optional class methods
2322  PtrToInt8Ty, // properties
2323  PtrToInt8Ty);// optional properties
2324 
2325  // struct objc_property_gsv1
2326  // {
2327  // const char *name;
2328  // char attributes;
2329  // char attributes2;
2330  // char unused1;
2331  // char unused2;
2332  // const char *getter_name;
2333  // const char *getter_types;
2334  // const char *setter_name;
2335  // const char *setter_types;
2336  // }
2337  PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2338  PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2339  PtrToInt8Ty, PtrToInt8Ty });
2340 
2341  ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
2342  PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2343 
2344  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
2345 
2346  // void objc_exception_throw(id);
2347  ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2348  ExceptionReThrowFn.init(&CGM,
2349  usesCxxExceptions ? "objc_exception_rethrow"
2350  : "objc_exception_throw",
2351  VoidTy, IdTy);
2352  // int objc_sync_enter(id);
2353  SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
2354  // int objc_sync_exit(id);
2355  SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
2356 
2357  // void objc_enumerationMutation (id)
2358  EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
2359 
2360  // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2361  GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
2362  PtrDiffTy, BoolTy);
2363  // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2364  SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
2365  PtrDiffTy, IdTy, BoolTy, BoolTy);
2366  // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2367  GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2368  PtrDiffTy, BoolTy, BoolTy);
2369  // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2370  SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2371  PtrDiffTy, BoolTy, BoolTy);
2372 
2373  // IMP type
2374  llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
2375  IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2376  true));
2377 
2378  const LangOptions &Opts = CGM.getLangOpts();
2379  if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
2380  RuntimeVersion = 10;
2381 
2382  // Don't bother initialising the GC stuff unless we're compiling in GC mode
2383  if (Opts.getGC() != LangOptions::NonGC) {
2384  // This is a bit of an hack. We should sort this out by having a proper
2385  // CGObjCGNUstep subclass for GC, but we may want to really support the old
2386  // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
2387  // Get selectors needed in GC mode
2388  RetainSel = GetNullarySelector("retain", CGM.getContext());
2389  ReleaseSel = GetNullarySelector("release", CGM.getContext());
2390  AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2391 
2392  // Get functions needed in GC mode
2393 
2394  // id objc_assign_ivar(id, id, ptrdiff_t);
2395  IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
2396  // id objc_assign_strongCast (id, id*)
2397  StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
2398  PtrToIdTy);
2399  // id objc_assign_global(id, id*);
2400  GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
2401  // id objc_assign_weak(id, id*);
2402  WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
2403  // id objc_read_weak(id*);
2404  WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
2405  // void *objc_memmove_collectable(void*, void *, size_t);
2406  MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
2407  SizeTy);
2408  }
2409 }
2410 
2411 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
2412  const std::string &Name, bool isWeak) {
2413  llvm::Constant *ClassName = MakeConstantString(Name);
2414  // With the incompatible ABI, this will need to be replaced with a direct
2415  // reference to the class symbol. For the compatible nonfragile ABI we are
2416  // still performing this lookup at run time but emitting the symbol for the
2417  // class externally so that we can make the switch later.
2418  //
2419  // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2420  // with memoized versions or with static references if it's safe to do so.
2421  if (!isWeak)
2422  EmitClassRef(Name);
2423 
2424  llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2425  llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
2426  return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
2427 }
2428 
2429 // This has to perform the lookup every time, since posing and related
2430 // techniques can modify the name -> class mapping.
2431 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
2432  const ObjCInterfaceDecl *OID) {
2433  auto *Value =
2434  GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
2435  if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2436  CGM.setGVProperties(ClassSymbol, OID);
2437  return Value;
2438 }
2439 
2440 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
2441  auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2442  if (CGM.getTriple().isOSBinFormatCOFF()) {
2443  if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2444  IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2446  DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2447 
2448  const VarDecl *VD = nullptr;
2449  for (const auto *Result : DC->lookup(&II))
2450  if ((VD = dyn_cast<VarDecl>(Result)))
2451  break;
2452 
2453  CGM.setGVProperties(ClassSymbol, VD);
2454  }
2455  }
2456  return Value;
2457 }
2458 
2459 llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2460  const std::string &TypeEncoding) {
2462  llvm::GlobalAlias *SelValue = nullptr;
2463 
2464  for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2465  e = Types.end() ; i!=e ; i++) {
2466  if (i->first == TypeEncoding) {
2467  SelValue = i->second;
2468  break;
2469  }
2470  }
2471  if (!SelValue) {
2472  SelValue = llvm::GlobalAlias::create(SelectorElemTy, 0,
2473  llvm::GlobalValue::PrivateLinkage,
2474  ".objc_selector_" + Sel.getAsString(),
2475  &TheModule);
2476  Types.emplace_back(TypeEncoding, SelValue);
2477  }
2478 
2479  return SelValue;
2480 }
2481 
2482 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2483  llvm::Value *SelValue = GetSelector(CGF, Sel);
2484 
2485  // Store it to a temporary. Does this satisfy the semantics of
2486  // GetAddrOfSelector? Hopefully.
2487  Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2488  CGF.getPointerAlign());
2489  CGF.Builder.CreateStore(SelValue, tmp);
2490  return tmp;
2491 }
2492 
2493 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
2494  return GetTypedSelector(CGF, Sel, std::string());
2495 }
2496 
2497 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2498  const ObjCMethodDecl *Method) {
2499  std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
2500  return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
2501 }
2502 
2503 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
2504  if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2505  // With the old ABI, there was only one kind of catchall, which broke
2506  // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2507  // a pointer indicating object catchalls, and NULL to indicate real
2508  // catchalls
2509  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2510  return MakeConstantString("@id");
2511  } else {
2512  return nullptr;
2513  }
2514  }
2515 
2516  // All other types should be Objective-C interface pointer types.
2518  assert(OPT && "Invalid @catch type.");
2519  const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2520  assert(IDecl && "Invalid @catch type.");
2521  return MakeConstantString(IDecl->getIdentifier()->getName());
2522 }
2523 
2524 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
2525  if (usesSEHExceptions)
2526  return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2527 
2528  if (!CGM.getLangOpts().CPlusPlus && !usesCxxExceptions)
2529  return CGObjCGNU::GetEHType(T);
2530 
2531  // For Objective-C++, we want to provide the ability to catch both C++ and
2532  // Objective-C objects in the same function.
2533 
2534  // There's a particular fixed type info for 'id'.
2535  if (T->isObjCIdType() ||
2536  T->isObjCQualifiedIdType()) {
2537  llvm::Constant *IDEHType =
2538  CGM.getModule().getGlobalVariable("__objc_id_type_info");
2539  if (!IDEHType)
2540  IDEHType =
2541  new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2542  false,
2543  llvm::GlobalValue::ExternalLinkage,
2544  nullptr, "__objc_id_type_info");
2545  return IDEHType;
2546  }
2547 
2548  const ObjCObjectPointerType *PT =
2550  assert(PT && "Invalid @catch type.");
2551  const ObjCInterfaceType *IT = PT->getInterfaceType();
2552  assert(IT && "Invalid @catch type.");
2553  std::string className =
2554  std::string(IT->getDecl()->getIdentifier()->getName());
2555 
2556  std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2557 
2558  // Return the existing typeinfo if it exists
2559  if (llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName))
2560  return typeinfo;
2561 
2562  // Otherwise create it.
2563 
2564  // vtable for gnustep::libobjc::__objc_class_type_info
2565  // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2566  // platform's name mangling.
2567  const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
2568  auto *Vtable = TheModule.getGlobalVariable(vtableName);
2569  if (!Vtable) {
2570  Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
2571  llvm::GlobalValue::ExternalLinkage,
2572  nullptr, vtableName);
2573  }
2574  llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
2575  auto *BVtable =
2576  llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two);
2577 
2578  llvm::Constant *typeName =
2579  ExportUniqueString(className, "__objc_eh_typename_");
2580 
2581  ConstantInitBuilder builder(CGM);
2582  auto fields = builder.beginStruct();
2583  fields.add(BVtable);
2584  fields.add(typeName);
2585  llvm::Constant *TI =
2586  fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2587  CGM.getPointerAlign(),
2588  /*constant*/ false,
2589  llvm::GlobalValue::LinkOnceODRLinkage);
2590  return TI;
2591 }
2592 
2593 /// Generate an NSConstantString object.
2594 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
2595 
2596  std::string Str = SL->getString().str();
2597  CharUnits Align = CGM.getPointerAlign();
2598 
2599  // Look for an existing one
2600  llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2601  if (old != ObjCStrings.end())
2602  return ConstantAddress(old->getValue(), Int8Ty, Align);
2603 
2604  StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2605 
2606  if (StringClass.empty()) StringClass = "NSConstantString";
2607 
2608  std::string Sym = "_OBJC_CLASS_";
2609  Sym += StringClass;
2610 
2611  llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2612 
2613  if (!isa)
2614  isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */ false,
2615  llvm::GlobalValue::ExternalWeakLinkage,
2616  nullptr, Sym);
2617 
2618  ConstantInitBuilder Builder(CGM);
2619  auto Fields = Builder.beginStruct();
2620  Fields.add(isa);
2621  Fields.add(MakeConstantString(Str));
2622  Fields.addInt(IntTy, Str.size());
2623  llvm::Constant *ObjCStr = Fields.finishAndCreateGlobal(".objc_str", Align);
2624  ObjCStrings[Str] = ObjCStr;
2625  ConstantStrings.push_back(ObjCStr);
2626  return ConstantAddress(ObjCStr, Int8Ty, Align);
2627 }
2628 
2629 ///Generates a message send where the super is the receiver. This is a message
2630 ///send to self with special delivery semantics indicating which class's method
2631 ///should be called.
2632 RValue
2633 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
2634  ReturnValueSlot Return,
2635  QualType ResultType,
2636  Selector Sel,
2637  const ObjCInterfaceDecl *Class,
2638  bool isCategoryImpl,
2639  llvm::Value *Receiver,
2640  bool IsClassMessage,
2641  const CallArgList &CallArgs,
2642  const ObjCMethodDecl *Method) {
2643  CGBuilderTy &Builder = CGF.Builder;
2644  if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2645  if (Sel == RetainSel || Sel == AutoreleaseSel) {
2646  return RValue::get(EnforceType(Builder, Receiver,
2647  CGM.getTypes().ConvertType(ResultType)));
2648  }
2649  if (Sel == ReleaseSel) {
2650  return RValue::get(nullptr);
2651  }
2652  }
2653 
2654  llvm::Value *cmd = GetSelector(CGF, Sel);
2655  CallArgList ActualArgs;
2656 
2657  ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2658  ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2659  ActualArgs.addFrom(CallArgs);
2660 
2661  MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2662 
2663  llvm::Value *ReceiverClass = nullptr;
2664  bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2665  if (isV2ABI) {
2666  ReceiverClass = GetClassNamed(CGF,
2667  Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
2668  if (IsClassMessage) {
2669  // Load the isa pointer of the superclass is this is a class method.
2670  ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2671  llvm::PointerType::getUnqual(IdTy));
2672  ReceiverClass =
2673  Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2674  }
2675  ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
2676  } else {
2677  if (isCategoryImpl) {
2678  llvm::FunctionCallee classLookupFunction = nullptr;
2679  if (IsClassMessage) {
2680  classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2681  IdTy, PtrTy, true), "objc_get_meta_class");
2682  } else {
2683  classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2684  IdTy, PtrTy, true), "objc_get_class");
2685  }
2686  ReceiverClass = Builder.CreateCall(classLookupFunction,
2687  MakeConstantString(Class->getNameAsString()));
2688  } else {
2689  // Set up global aliases for the metaclass or class pointer if they do not
2690  // already exist. These will are forward-references which will be set to
2691  // pointers to the class and metaclass structure created for the runtime
2692  // load function. To send a message to super, we look up the value of the
2693  // super_class pointer from either the class or metaclass structure.
2694  if (IsClassMessage) {
2695  if (!MetaClassPtrAlias) {
2696  MetaClassPtrAlias = llvm::GlobalAlias::create(
2697  IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
2698  ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2699  }
2700  ReceiverClass = MetaClassPtrAlias;
2701  } else {
2702  if (!ClassPtrAlias) {
2703  ClassPtrAlias = llvm::GlobalAlias::create(
2704  IdElemTy, 0, llvm::GlobalValue::InternalLinkage,
2705  ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2706  }
2707  ReceiverClass = ClassPtrAlias;
2708  }
2709  }
2710  // Cast the pointer to a simplified version of the class structure
2711  llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2712  ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2713  llvm::PointerType::getUnqual(CastTy));
2714  // Get the superclass pointer
2715  ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2716  // Load the superclass pointer
2717  ReceiverClass =
2718  Builder.CreateAlignedLoad(IdTy, ReceiverClass, CGF.getPointerAlign());
2719  }
2720  // Construct the structure used to look up the IMP
2721  llvm::StructType *ObjCSuperTy =
2722  llvm::StructType::get(Receiver->getType(), IdTy);
2723 
2724  Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
2725  CGF.getPointerAlign());
2726 
2727  Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2728  Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
2729 
2730  // Get the IMP
2731  llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
2732  imp = EnforceType(Builder, imp, MSI.MessengerType);
2733 
2734  llvm::Metadata *impMD[] = {
2735  llvm::MDString::get(VMContext, Sel.getAsString()),
2736  llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
2737  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2738  llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
2739  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2740 
2741  CGCallee callee(CGCalleeInfo(), imp);
2742 
2743  llvm::CallBase *call;
2744  RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2745  call->setMetadata(msgSendMDKind, node);
2746  return msgRet;
2747 }
2748 
2749 /// Generate code for a message send expression.
2750 RValue
2751 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
2752  ReturnValueSlot Return,
2753  QualType ResultType,
2754  Selector Sel,
2755  llvm::Value *Receiver,
2756  const CallArgList &CallArgs,
2757  const ObjCInterfaceDecl *Class,
2758  const ObjCMethodDecl *Method) {
2759  CGBuilderTy &Builder = CGF.Builder;
2760 
2761  // Strip out message sends to retain / release in GC mode
2762  if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2763  if (Sel == RetainSel || Sel == AutoreleaseSel) {
2764  return RValue::get(EnforceType(Builder, Receiver,
2765  CGM.getTypes().ConvertType(ResultType)));
2766  }
2767  if (Sel == ReleaseSel) {
2768  return RValue::get(nullptr);
2769  }
2770  }
2771 
2772  bool isDirect = Method && Method->isDirectMethod();
2773 
2774  IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2775  llvm::Value *cmd;
2776  if (!isDirect) {
2777  if (Method)
2778  cmd = GetSelector(CGF, Method);
2779  else
2780  cmd = GetSelector(CGF, Sel);
2781  cmd = EnforceType(Builder, cmd, SelectorTy);
2782  }
2783 
2784  Receiver = EnforceType(Builder, Receiver, IdTy);
2785 
2786  llvm::Metadata *impMD[] = {
2787  llvm::MDString::get(VMContext, Sel.getAsString()),
2788  llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2789  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2790  llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
2791  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2792 
2793  CallArgList ActualArgs;
2794  ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2795  if (!isDirect)
2796  ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2797  ActualArgs.addFrom(CallArgs);
2798 
2799  MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2800 
2801  // Message sends are expected to return a zero value when the
2802  // receiver is nil. At one point, this was only guaranteed for
2803  // simple integer and pointer types, but expectations have grown
2804  // over time.
2805  //
2806  // Given a nil receiver, the GNU runtime's message lookup will
2807  // return a stub function that simply sets various return-value
2808  // registers to zero and then returns. That's good enough for us
2809  // if and only if (1) the calling conventions of that stub are
2810  // compatible with the signature we're using and (2) the registers
2811  // it sets are sufficient to produce a zero value of the return type.
2812  // Rather than doing a whole target-specific analysis, we assume it
2813  // only works for void, integer, and pointer types, and in all
2814  // other cases we do an explicit nil check is emitted code. In
2815  // addition to ensuring we produce a zero value for other types, this
2816  // sidesteps the few outright CC incompatibilities we know about that
2817  // could otherwise lead to crashes, like when a method is expected to
2818  // return on the x87 floating point stack or adjust the stack pointer
2819  // because of an indirect return.
2820  bool hasParamDestroyedInCallee = false;
2821  bool requiresExplicitZeroResult = false;
2822  bool requiresNilReceiverCheck = [&] {
2823  // We never need a check if we statically know the receiver isn't nil.
2824  if (!canMessageReceiverBeNull(CGF, Method, /*IsSuper*/ false,
2825  Class, Receiver))
2826  return false;
2827 
2828  // If there's a consumed argument, we need a nil check.
2829  if (Method && Method->hasParamDestroyedInCallee()) {
2830  hasParamDestroyedInCallee = true;
2831  }
2832 
2833  // If the return value isn't flagged as unused, and the result
2834  // type isn't in our narrow set where we assume compatibility,
2835  // we need a nil check to ensure a nil value.
2836  if (!Return.isUnused()) {
2837  if (ResultType->isVoidType()) {
2838  // void results are definitely okay.
2839  } else if (ResultType->hasPointerRepresentation() &&
2840  CGM.getTypes().isZeroInitializable(ResultType)) {
2841  // Pointer types should be fine as long as they have
2842  // bitwise-zero null pointers. But do we need to worry
2843  // about unusual address spaces?
2844  } else if (ResultType->isIntegralOrEnumerationType()) {
2845  // Bitwise zero should always be zero for integral types.
2846  // FIXME: we probably need a size limit here, but we've
2847  // never imposed one before
2848  } else {
2849  // Otherwise, use an explicit check just to be sure, unless we're
2850  // calling a direct method, where the implementation does this for us.
2851  requiresExplicitZeroResult = !isDirect;
2852  }
2853  }
2854 
2855  return hasParamDestroyedInCallee || requiresExplicitZeroResult;
2856  }();
2857 
2858  // We will need to explicitly zero-initialize an aggregate result slot
2859  // if we generally require explicit zeroing and we have an aggregate
2860  // result.
2861  bool requiresExplicitAggZeroing =
2862  requiresExplicitZeroResult && CGF.hasAggregateEvaluationKind(ResultType);
2863 
2864  // The block we're going to end up in after any message send or nil path.
2865  llvm::BasicBlock *continueBB = nullptr;
2866  // The block that eventually branched to continueBB along the nil path.
2867  llvm::BasicBlock *nilPathBB = nullptr;
2868  // The block to do explicit work in along the nil path, if necessary.
2869  llvm::BasicBlock *nilCleanupBB = nullptr;
2870 
2871  // Emit the nil-receiver check.
2872  if (requiresNilReceiverCheck) {
2873  llvm::BasicBlock *messageBB = CGF.createBasicBlock("msgSend");
2874  continueBB = CGF.createBasicBlock("continue");
2875 
2876  // If we need to zero-initialize an aggregate result or destroy
2877  // consumed arguments, we'll need a separate cleanup block.
2878  // Otherwise we can just branch directly to the continuation block.
2879  if (requiresExplicitAggZeroing || hasParamDestroyedInCallee) {
2880  nilCleanupBB = CGF.createBasicBlock("nilReceiverCleanup");
2881  } else {
2882  nilPathBB = Builder.GetInsertBlock();
2883  }
2884 
2885  llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
2886  llvm::Constant::getNullValue(Receiver->getType()));
2887  Builder.CreateCondBr(isNil, nilCleanupBB ? nilCleanupBB : continueBB,
2888  messageBB);
2889  CGF.EmitBlock(messageBB);
2890  }
2891 
2892  // Get the IMP to call
2893  llvm::Value *imp;
2894 
2895  // If this is a direct method, just emit it here.
2896  if (isDirect)
2897  imp = GenerateMethod(Method, Method->getClassInterface());
2898  else
2899  // If we have non-legacy dispatch specified, we try using the
2900  // objc_msgSend() functions. These are not supported on all platforms
2901  // (or all runtimes on a given platform), so we
2902  switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
2904  imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
2905  break;
2906  case CodeGenOptions::Mixed:
2907  case CodeGenOptions::NonLegacy:
2908  StringRef name = "objc_msgSend";
2909  if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2910  name = "objc_msgSend_fpret";
2911  } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
2912  name = "objc_msgSend_stret";
2913 
2914  // The address of the memory block is be passed in x8 for POD type,
2915  // or in x0 for non-POD type (marked as inreg).
2916  bool shouldCheckForInReg =
2917  CGM.getContext()
2918  .getTargetInfo()
2919  .getTriple()
2920  .isWindowsMSVCEnvironment() &&
2921  CGM.getContext().getTargetInfo().getTriple().isAArch64();
2922  if (shouldCheckForInReg && CGM.ReturnTypeHasInReg(MSI.CallInfo)) {
2923  name = "objc_msgSend_stret2";
2924  }
2925  }
2926  // The actual types here don't matter - we're going to bitcast the
2927  // function anyway
2928  imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2929  name)
2930  .getCallee();
2931  }
2932 
2933  // Reset the receiver in case the lookup modified it
2934  ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
2935 
2936  imp = EnforceType(Builder, imp, MSI.MessengerType);
2937 
2938  llvm::CallBase *call;
2939  CGCallee callee(CGCalleeInfo(), imp);
2940  RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2941  if (!isDirect)
2942  call->setMetadata(msgSendMDKind, node);
2943 
2944  if (requiresNilReceiverCheck) {
2945  llvm::BasicBlock *nonNilPathBB = CGF.Builder.GetInsertBlock();
2946  CGF.Builder.CreateBr(continueBB);
2947 
2948  // Emit the nil path if we decided it was necessary above.
2949  if (nilCleanupBB) {
2950  CGF.EmitBlock(nilCleanupBB);
2951 
2952  if (hasParamDestroyedInCallee) {
2953  destroyCalleeDestroyedArguments(CGF, Method, CallArgs);
2954  }
2955 
2956  if (requiresExplicitAggZeroing) {
2957  assert(msgRet.isAggregate());
2958  Address addr = msgRet.getAggregateAddress();
2959  CGF.EmitNullInitialization(addr, ResultType);
2960  }
2961 
2962  nilPathBB = CGF.Builder.GetInsertBlock();
2963  CGF.Builder.CreateBr(continueBB);
2964  }
2965 
2966  // Enter the continuation block and emit a phi if required.
2967  CGF.EmitBlock(continueBB);
2968  if (msgRet.isScalar()) {
2969  // If the return type is void, do nothing
2970  if (llvm::Value *v = msgRet.getScalarVal()) {
2971  llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
2972  phi->addIncoming(v, nonNilPathBB);
2973  phi->addIncoming(CGM.EmitNullConstant(ResultType), nilPathBB);
2974  msgRet = RValue::get(phi);
2975  }
2976  } else if (msgRet.isAggregate()) {
2977  // Aggregate zeroing is handled in nilCleanupBB when it's required.
2978  } else /* isComplex() */ {
2979  std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
2980  llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
2981  phi->addIncoming(v.first, nonNilPathBB);
2982  phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2983  nilPathBB);
2984  llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
2985  phi2->addIncoming(v.second, nonNilPathBB);
2986  phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2987  nilPathBB);
2988  msgRet = RValue::getComplex(phi, phi2);
2989  }
2990  }
2991  return msgRet;
2992 }
2993 
2994 /// Generates a MethodList. Used in construction of a objc_class and
2995 /// objc_category structures.
2996 llvm::Constant *CGObjCGNU::
2997 GenerateMethodList(StringRef ClassName,
2998  StringRef CategoryName,
3000  bool isClassMethodList) {
3001  if (Methods.empty())
3002  return NULLPtr;
3003 
3004  ConstantInitBuilder Builder(CGM);
3005 
3006  auto MethodList = Builder.beginStruct();
3007  MethodList.addNullPointer(CGM.Int8PtrTy);
3008  MethodList.addInt(Int32Ty, Methods.size());
3009 
3010  // Get the method structure type.
3011  llvm::StructType *ObjCMethodTy =
3012  llvm::StructType::get(CGM.getLLVMContext(), {
3013  PtrToInt8Ty, // Really a selector, but the runtime creates it us.
3014  PtrToInt8Ty, // Method types
3015  IMPTy // Method pointer
3016  });
3017  bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
3018  if (isV2ABI) {
3019  // size_t size;
3020  llvm::DataLayout td(&TheModule);
3021  MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
3022  CGM.getContext().getCharWidth());
3023  ObjCMethodTy =
3024  llvm::StructType::get(CGM.getLLVMContext(), {
3025  IMPTy, // Method pointer
3026  PtrToInt8Ty, // Selector
3027  PtrToInt8Ty // Extended type encoding
3028  });
3029  } else {
3030  ObjCMethodTy =
3031  llvm::StructType::get(CGM.getLLVMContext(), {
3032  PtrToInt8Ty, // Really a selector, but the runtime creates it us.
3033  PtrToInt8Ty, // Method types
3034  IMPTy // Method pointer
3035  });
3036  }
3037  auto MethodArray = MethodList.beginArray();
3038  ASTContext &Context = CGM.getContext();
3039  for (const auto *OMD : Methods) {
3040  llvm::Constant *FnPtr =
3041  TheModule.getFunction(getSymbolNameForMethod(OMD));
3042  assert(FnPtr && "Can't generate metadata for method that doesn't exist");
3043  auto Method = MethodArray.beginStruct(ObjCMethodTy);
3044  if (isV2ABI) {
3045  Method.add(FnPtr);
3046  Method.add(GetConstantSelector(OMD->getSelector(),
3047  Context.getObjCEncodingForMethodDecl(OMD)));
3048  Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
3049  } else {
3050  Method.add(MakeConstantString(OMD->getSelector().getAsString()));
3051  Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
3052  Method.add(FnPtr);
3053  }
3054  Method.finishAndAddTo(MethodArray);
3055  }
3056  MethodArray.finishAndAddTo(MethodList);
3057 
3058  // Create an instance of the structure
3059  return MethodList.finishAndCreateGlobal(".objc_method_list",
3060  CGM.getPointerAlign());
3061 }
3062 
3063 /// Generates an IvarList. Used in construction of a objc_class.
3064 llvm::Constant *CGObjCGNU::
3065 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
3066  ArrayRef<llvm::Constant *> IvarTypes,
3067  ArrayRef<llvm::Constant *> IvarOffsets,
3068  ArrayRef<llvm::Constant *> IvarAlign,
3069  ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
3070  if (IvarNames.empty())
3071  return NULLPtr;
3072 
3073  ConstantInitBuilder Builder(CGM);
3074 
3075  // Structure containing array count followed by array.
3076  auto IvarList = Builder.beginStruct();
3077  IvarList.addInt(IntTy, (int)IvarNames.size());
3078 
3079  // Get the ivar structure type.
3080  llvm::StructType *ObjCIvarTy =
3081  llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
3082 
3083  // Array of ivar structures.
3084  auto Ivars = IvarList.beginArray(ObjCIvarTy);
3085  for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
3086  auto Ivar = Ivars.beginStruct(ObjCIvarTy);
3087  Ivar.add(IvarNames[i]);
3088  Ivar.add(IvarTypes[i]);
3089  Ivar.add(IvarOffsets[i]);
3090  Ivar.finishAndAddTo(Ivars);
3091  }
3092  Ivars.finishAndAddTo(IvarList);
3093 
3094  // Create an instance of the structure
3095  return IvarList.finishAndCreateGlobal(".objc_ivar_list",
3096  CGM.getPointerAlign());
3097 }
3098 
3099 /// Generate a class structure
3100 llvm::Constant *CGObjCGNU::GenerateClassStructure(
3101  llvm::Constant *MetaClass,
3102  llvm::Constant *SuperClass,
3103  unsigned info,
3104  const char *Name,
3105  llvm::Constant *Version,
3106  llvm::Constant *InstanceSize,
3107  llvm::Constant *IVars,
3108  llvm::Constant *Methods,
3109  llvm::Constant *Protocols,
3110  llvm::Constant *IvarOffsets,
3111  llvm::Constant *Properties,
3112  llvm::Constant *StrongIvarBitmap,
3113  llvm::Constant *WeakIvarBitmap,
3114  bool isMeta) {
3115  // Set up the class structure
3116  // Note: Several of these are char*s when they should be ids. This is
3117  // because the runtime performs this translation on load.
3118  //
3119  // Fields marked New ABI are part of the GNUstep runtime. We emit them
3120  // anyway; the classes will still work with the GNU runtime, they will just
3121  // be ignored.
3122  llvm::StructType *ClassTy = llvm::StructType::get(
3123  PtrToInt8Ty, // isa
3124  PtrToInt8Ty, // super_class
3125  PtrToInt8Ty, // name
3126  LongTy, // version
3127  LongTy, // info
3128  LongTy, // instance_size
3129  IVars->getType(), // ivars
3130  Methods->getType(), // methods
3131  // These are all filled in by the runtime, so we pretend
3132  PtrTy, // dtable
3133  PtrTy, // subclass_list
3134  PtrTy, // sibling_class
3135  PtrTy, // protocols
3136  PtrTy, // gc_object_type
3137  // New ABI:
3138  LongTy, // abi_version
3139  IvarOffsets->getType(), // ivar_offsets
3140  Properties->getType(), // properties
3141  IntPtrTy, // strong_pointers
3142  IntPtrTy // weak_pointers
3143  );
3144 
3145  ConstantInitBuilder Builder(CGM);
3146  auto Elements = Builder.beginStruct(ClassTy);
3147 
3148  // Fill in the structure
3149 
3150  // isa
3151  Elements.add(MetaClass);
3152  // super_class
3153  Elements.add(SuperClass);
3154  // name
3155  Elements.add(MakeConstantString(Name, ".class_name"));
3156  // version
3157  Elements.addInt(LongTy, 0);
3158  // info
3159  Elements.addInt(LongTy, info);
3160  // instance_size
3161  if (isMeta) {
3162  llvm::DataLayout td(&TheModule);
3163  Elements.addInt(LongTy,
3164  td.getTypeSizeInBits(ClassTy) /
3165  CGM.getContext().getCharWidth());
3166  } else
3167  Elements.add(InstanceSize);
3168  // ivars
3169  Elements.add(IVars);
3170  // methods
3171  Elements.add(Methods);
3172  // These are all filled in by the runtime, so we pretend
3173  // dtable
3174  Elements.add(NULLPtr);
3175  // subclass_list
3176  Elements.add(NULLPtr);
3177  // sibling_class
3178  Elements.add(NULLPtr);
3179  // protocols
3180  Elements.add(Protocols);
3181  // gc_object_type
3182  Elements.add(NULLPtr);
3183  // abi_version
3184  Elements.addInt(LongTy, ClassABIVersion);
3185  // ivar_offsets
3186  Elements.add(IvarOffsets);
3187  // properties
3188  Elements.add(Properties);
3189  // strong_pointers
3190  Elements.add(StrongIvarBitmap);
3191  // weak_pointers
3192  Elements.add(WeakIvarBitmap);
3193  // Create an instance of the structure
3194  // This is now an externally visible symbol, so that we can speed up class
3195  // messages in the next ABI. We may already have some weak references to
3196  // this, so check and fix them properly.
3197  std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
3198  std::string(Name));
3199  llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
3200  llvm::Constant *Class =
3201  Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
3202  llvm::GlobalValue::ExternalLinkage);
3203  if (ClassRef) {
3204  ClassRef->replaceAllUsesWith(Class);
3205  ClassRef->removeFromParent();
3206  Class->setName(ClassSym);
3207  }
3208  return Class;
3209 }
3210 
3211 llvm::Constant *CGObjCGNU::
3212 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
3213  // Get the method structure type.
3214  llvm::StructType *ObjCMethodDescTy =
3215  llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
3216  ASTContext &Context = CGM.getContext();
3217  ConstantInitBuilder Builder(CGM);
3218  auto MethodList = Builder.beginStruct();
3219  MethodList.addInt(IntTy, Methods.size());
3220  auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
3221  for (auto *M : Methods) {
3222  auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
3223  Method.add(MakeConstantString(M->getSelector().getAsString()));
3224  Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
3225  Method.finishAndAddTo(MethodArray);
3226  }
3227  MethodArray.finishAndAddTo(MethodList);
3228  return MethodList.finishAndCreateGlobal(".objc_method_list",
3229  CGM.getPointerAlign());
3230 }
3231 
3232 // Create the protocol list structure used in classes, categories and so on
3233 llvm::Constant *
3234 CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3235 
3236  ConstantInitBuilder Builder(CGM);
3237  auto ProtocolList = Builder.beginStruct();
3238  ProtocolList.add(NULLPtr);
3239  ProtocolList.addInt(LongTy, Protocols.size());
3240 
3241  auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
3242  for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3243  iter != endIter ; iter++) {
3244  llvm::Constant *protocol = nullptr;
3245  llvm::StringMap<llvm::Constant*>::iterator value =
3246  ExistingProtocols.find(*iter);
3247  if (value == ExistingProtocols.end()) {
3248  protocol = GenerateEmptyProtocol(*iter);
3249  } else {
3250  protocol = value->getValue();
3251  }
3252  Elements.add(protocol);
3253  }
3254  Elements.finishAndAddTo(ProtocolList);
3255  return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3256  CGM.getPointerAlign());
3257 }
3258 
3259 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
3260  const ObjCProtocolDecl *PD) {
3261  auto protocol = GenerateProtocolRef(PD);
3262  llvm::Type *T =
3264  return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
3265 }
3266 
3267 llvm::Constant *CGObjCGNU::GenerateProtocolRef(const ObjCProtocolDecl *PD) {
3268  llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3269  if (!protocol)
3270  GenerateProtocol(PD);
3271  assert(protocol && "Unknown protocol");
3272  return protocol;
3273 }
3274 
3275 llvm::Constant *
3276 CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
3277  llvm::Constant *ProtocolList = GenerateProtocolList({});
3278  llvm::Constant *MethodList = GenerateProtocolMethodList({});
3279  // Protocols are objects containing lists of the methods implemented and
3280  // protocols adopted.
3281  ConstantInitBuilder Builder(CGM);
3282  auto Elements = Builder.beginStruct();
3283 
3284  // The isa pointer must be set to a magic number so the runtime knows it's
3285  // the correct layout.
3286  Elements.add(llvm::ConstantExpr::getIntToPtr(
3287  llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3288 
3289  Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
3290  Elements.add(ProtocolList); /* .protocol_list */
3291  Elements.add(MethodList); /* .instance_methods */
3292  Elements.add(MethodList); /* .class_methods */
3293  Elements.add(MethodList); /* .optional_instance_methods */
3294  Elements.add(MethodList); /* .optional_class_methods */
3295  Elements.add(NULLPtr); /* .properties */
3296  Elements.add(NULLPtr); /* .optional_properties */
3297  return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
3298  CGM.getPointerAlign());
3299 }
3300 
3301 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
3302  if (PD->isNonRuntimeProtocol())
3303  return;
3304 
3305  std::string ProtocolName = PD->getNameAsString();
3306 
3307  // Use the protocol definition, if there is one.
3308  if (const ObjCProtocolDecl *Def = PD->getDefinition())
3309  PD = Def;
3310 
3311  SmallVector<std::string, 16> Protocols;
3312  for (const auto *PI : PD->protocols())
3313  Protocols.push_back(PI->getNameAsString());
3315  SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3316  for (const auto *I : PD->instance_methods())
3317  if (I->isOptional())
3318  OptionalInstanceMethods.push_back(I);
3319  else
3320  InstanceMethods.push_back(I);
3321  // Collect information about class methods:
3323  SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3324  for (const auto *I : PD->class_methods())
3325  if (I->isOptional())
3326  OptionalClassMethods.push_back(I);
3327  else
3328  ClassMethods.push_back(I);
3329 
3330  llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3331  llvm::Constant *InstanceMethodList =
3332  GenerateProtocolMethodList(InstanceMethods);
3333  llvm::Constant *ClassMethodList =
3334  GenerateProtocolMethodList(ClassMethods);
3335  llvm::Constant *OptionalInstanceMethodList =
3336  GenerateProtocolMethodList(OptionalInstanceMethods);
3337  llvm::Constant *OptionalClassMethodList =
3338  GenerateProtocolMethodList(OptionalClassMethods);
3339 
3340  // Property metadata: name, attributes, isSynthesized, setter name, setter
3341  // types, getter name, getter types.
3342  // The isSynthesized value is always set to 0 in a protocol. It exists to
3343  // simplify the runtime library by allowing it to use the same data
3344  // structures for protocol metadata everywhere.
3345 
3346  llvm::Constant *PropertyList =
3347  GeneratePropertyList(nullptr, PD, false, false);
3348  llvm::Constant *OptionalPropertyList =
3349  GeneratePropertyList(nullptr, PD, false, true);
3350 
3351  // Protocols are objects containing lists of the methods implemented and
3352  // protocols adopted.
3353  // The isa pointer must be set to a magic number so the runtime knows it's
3354  // the correct layout.
3355  ConstantInitBuilder Builder(CGM);
3356  auto Elements = Builder.beginStruct();
3357  Elements.add(
3358  llvm::ConstantExpr::getIntToPtr(
3359  llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3360  Elements.add(MakeConstantString(ProtocolName));
3361  Elements.add(ProtocolList);
3362  Elements.add(InstanceMethodList);
3363  Elements.add(ClassMethodList);
3364  Elements.add(OptionalInstanceMethodList);
3365  Elements.add(OptionalClassMethodList);
3366  Elements.add(PropertyList);
3367  Elements.add(OptionalPropertyList);
3368  ExistingProtocols[ProtocolName] =
3369  Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign());
3370 }
3371 void CGObjCGNU::GenerateProtocolHolderCategory() {
3372  // Collect information about instance methods
3373 
3374  ConstantInitBuilder Builder(CGM);
3375  auto Elements = Builder.beginStruct();
3376 
3377  const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3378  const std::string CategoryName = "AnotherHack";
3379  Elements.add(MakeConstantString(CategoryName));
3380  Elements.add(MakeConstantString(ClassName));
3381  // Instance method list
3382  Elements.add(GenerateMethodList(ClassName, CategoryName, {}, false));
3383  // Class method list
3384  Elements.add(GenerateMethodList(ClassName, CategoryName, {}, true));
3385 
3386  // Protocol list
3387  ConstantInitBuilder ProtocolListBuilder(CGM);
3388  auto ProtocolList = ProtocolListBuilder.beginStruct();
3389  ProtocolList.add(NULLPtr);
3390  ProtocolList.addInt(LongTy, ExistingProtocols.size());
3391  auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3392  for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
3393  iter != endIter ; iter++) {
3394  ProtocolElements.add(iter->getValue());
3395  }
3396  ProtocolElements.finishAndAddTo(ProtocolList);
3397  Elements.add(ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3398  CGM.getPointerAlign()));
3399  Categories.push_back(
3400  Elements.finishAndCreateGlobal("", CGM.getPointerAlign()));
3401 }
3402 
3403 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3404 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3405 /// bits set to their values, LSB first, while larger ones are stored in a
3406 /// structure of this / form:
3407 ///
3408 /// struct { int32_t length; int32_t values[length]; };
3409 ///
3410 /// The values in the array are stored in host-endian format, with the least
3411 /// significant bit being assumed to come first in the bitfield. Therefore, a
3412 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3413 /// bitfield / with the 63rd bit set will be 1<<64.
3414 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
3415  int bitCount = bits.size();
3416  int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
3417  if (bitCount < ptrBits) {
3418  uint64_t val = 1;
3419  for (int i=0 ; i<bitCount ; ++i) {
3420  if (bits[i]) val |= 1ULL<<(i+1);
3421  }
3422  return llvm::ConstantInt::get(IntPtrTy, val);
3423  }
3425  int v=0;
3426  while (v < bitCount) {
3427  int32_t word = 0;
3428  for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3429  if (bits[v]) word |= 1<<i;
3430  v++;
3431  }
3432  values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3433  }
3434 
3435  ConstantInitBuilder builder(CGM);
3436  auto fields = builder.beginStruct();
3437  fields.addInt(Int32Ty, values.size());
3438  auto array = fields.beginArray();
3439  for (auto *v : values) array.add(v);
3440  array.finishAndAddTo(fields);
3441 
3442  llvm::Constant *GS =
3443  fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
3444  llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
3445  return ptr;
3446 }
3447 
3448 llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3449  ObjCCategoryDecl *OCD) {
3450  const auto &RefPro = OCD->getReferencedProtocols();
3451  const auto RuntimeProtos =
3452  GetRuntimeProtocolList(RefPro.begin(), RefPro.end());
3453  SmallVector<std::string, 16> Protocols;
3454  for (const auto *PD : RuntimeProtos)
3455  Protocols.push_back(PD->getNameAsString());
3456  return GenerateProtocolList(Protocols);
3457 }
3458 
3459 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
3460  const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3461  std::string ClassName = Class->getNameAsString();
3462  std::string CategoryName = OCD->getNameAsString();
3463 
3464  // Collect the names of referenced protocols
3465  const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3466 
3467  ConstantInitBuilder Builder(CGM);
3468  auto Elements = Builder.beginStruct();
3469  Elements.add(MakeConstantString(CategoryName));
3470  Elements.add(MakeConstantString(ClassName));
3471  // Instance method list
3472  SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3473  InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3474  OCD->instmeth_end());
3475  Elements.add(
3476  GenerateMethodList(ClassName, CategoryName, InstanceMethods, false));
3477 
3478  // Class method list
3479 
3480  SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3481  ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3482  OCD->classmeth_end());
3483  Elements.add(GenerateMethodList(ClassName, CategoryName, ClassMethods, true));
3484 
3485  // Protocol list
3486  Elements.add(GenerateCategoryProtocolList(CatDecl));
3487  if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3488  const ObjCCategoryDecl *Category =
3489  Class->FindCategoryDeclaration(OCD->getIdentifier());
3490  if (Category) {
3491  // Instance properties
3492  Elements.add(GeneratePropertyList(OCD, Category, false));
3493  // Class properties
3494  Elements.add(GeneratePropertyList(OCD, Category, true));
3495  } else {
3496  Elements.addNullPointer(PtrTy);
3497  Elements.addNullPointer(PtrTy);
3498  }
3499  }
3500 
3501  Categories.push_back(Elements.finishAndCreateGlobal(
3502  std::string(".objc_category_") + ClassName + CategoryName,
3503  CGM.getPointerAlign()));
3504 }
3505 
3506 llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3507  const ObjCContainerDecl *OCD,
3508  bool isClassProperty,
3509  bool protocolOptionalProperties) {
3510 
3513  bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3514  ASTContext &Context = CGM.getContext();
3515 
3516  std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3517  = [&](const ObjCProtocolDecl *Proto) {
3518  for (const auto *P : Proto->protocols())
3519  collectProtocolProperties(P);
3520  for (const auto *PD : Proto->properties()) {
3521  if (isClassProperty != PD->isClassProperty())
3522  continue;
3523  // Skip any properties that are declared in protocols that this class
3524  // conforms to but are not actually implemented by this class.
3525  if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3526  continue;
3527  if (!PropertySet.insert(PD->getIdentifier()).second)
3528  continue;
3529  Properties.push_back(PD);
3530  }
3531  };
3532 
3533  if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3534  for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3535  for (auto *PD : ClassExt->properties()) {
3536  if (isClassProperty != PD->isClassProperty())
3537  continue;
3538  PropertySet.insert(PD->getIdentifier());
3539  Properties.push_back(PD);
3540  }
3541 
3542  for (const auto *PD : OCD->properties()) {
3543  if (isClassProperty != PD->isClassProperty())
3544  continue;
3545  // If we're generating a list for a protocol, skip optional / required ones
3546  // when generating the other list.
3547  if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3548  continue;
3549  // Don't emit duplicate metadata for properties that were already in a
3550  // class extension.
3551  if (!PropertySet.insert(PD->getIdentifier()).second)
3552  continue;
3553 
3554  Properties.push_back(PD);
3555  }
3556 
3557  if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3558  for (const auto *P : OID->all_referenced_protocols())
3559  collectProtocolProperties(P);
3560  else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3561  for (const auto *P : CD->protocols())
3562  collectProtocolProperties(P);
3563 
3564  auto numProperties = Properties.size();
3565 
3566  if (numProperties == 0)
3567  return NULLPtr;
3568 
3569  ConstantInitBuilder builder(CGM);
3570  auto propertyList = builder.beginStruct();
3571  auto properties = PushPropertyListHeader(propertyList, numProperties);
3572 
3573  // Add all of the property methods need adding to the method list and to the
3574  // property metadata list.
3575  for (auto *property : Properties) {
3576  bool isSynthesized = false;
3577  bool isDynamic = false;
3578  if (!isProtocol) {
3579  auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3580  if (propertyImpl) {
3581  isSynthesized = (propertyImpl->getPropertyImplementation() ==
3582  ObjCPropertyImplDecl::Synthesize);
3583  isDynamic = (propertyImpl->getPropertyImplementation() ==
3584  ObjCPropertyImplDecl::Dynamic);
3585  }
3586  }
3587  PushProperty(properties, property, Container, isSynthesized, isDynamic);
3588  }
3589  properties.finishAndAddTo(propertyList);
3590 
3591  return propertyList.finishAndCreateGlobal(".objc_property_list",
3592  CGM.getPointerAlign());
3593 }
3594 
3595 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3596  // Get the class declaration for which the alias is specified.
3597  ObjCInterfaceDecl *ClassDecl =
3598  const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
3599  ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3600  OAD->getNameAsString());
3601 }
3602 
3603 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3604  ASTContext &Context = CGM.getContext();
3605 
3606  // Get the superclass name.
3607  const ObjCInterfaceDecl * SuperClassDecl =
3608  OID->getClassInterface()->getSuperClass();
3609  std::string SuperClassName;
3610  if (SuperClassDecl) {
3611  SuperClassName = SuperClassDecl->getNameAsString();
3612  EmitClassRef(SuperClassName);
3613  }
3614 
3615  // Get the class name
3616  ObjCInterfaceDecl *ClassDecl =
3617  const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
3618  std::string ClassName = ClassDecl->getNameAsString();
3619 
3620  // Emit the symbol that is used to generate linker errors if this class is
3621  // referenced in other modules but not declared.
3622  std::string classSymbolName = "__objc_class_name_" + ClassName;
3623  if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
3624  symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
3625  } else {
3626  new llvm::GlobalVariable(TheModule, LongTy, false,
3627  llvm::GlobalValue::ExternalLinkage,
3628  llvm::ConstantInt::get(LongTy, 0),
3629  classSymbolName);
3630  }
3631 
3632  // Get the size of instances.
3633  int instanceSize =
3635 
3636  // Collect information about instance variables.
3642 
3643  ConstantInitBuilder IvarOffsetBuilder(CGM);
3644  auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
3645  SmallVector<bool, 16> WeakIvars;
3646  SmallVector<bool, 16> StrongIvars;
3647 
3648  int superInstanceSize = !SuperClassDecl ? 0 :
3649  Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
3650  // For non-fragile ivars, set the instance size to 0 - {the size of just this
3651  // class}. The runtime will then set this to the correct value on load.
3652  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3653  instanceSize = 0 - (instanceSize - superInstanceSize);
3654  }
3655 
3656  for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3657  IVD = IVD->getNextIvar()) {
3658  // Store the name
3659  IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
3660  // Get the type encoding for this ivar
3661  std::string TypeStr;
3662  Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
3663  IvarTypes.push_back(MakeConstantString(TypeStr));
3664  IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3665  Context.getTypeSize(IVD->getType())));
3666  // Get the offset
3667  uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
3668  uint64_t Offset = BaseOffset;
3669  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3670  Offset = BaseOffset - superInstanceSize;
3671  }
3672  llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3673  // Create the direct offset value
3674  std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3675  IVD->getNameAsString();
3676 
3677  llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3678  if (OffsetVar) {
3679  OffsetVar->setInitializer(OffsetValue);
3680  // If this is the real definition, change its linkage type so that
3681  // different modules will use this one, rather than their private
3682  // copy.
3683  OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3684  } else
3685  OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
3686  false, llvm::GlobalValue::ExternalLinkage,
3687  OffsetValue, OffsetName);
3688  IvarOffsets.push_back(OffsetValue);
3689  IvarOffsetValues.add(OffsetVar);
3690  Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
3691  IvarOwnership.push_back(lt);
3692  switch (lt) {
3693  case Qualifiers::OCL_Strong:
3694  StrongIvars.push_back(true);
3695  WeakIvars.push_back(false);
3696  break;
3697  case Qualifiers::OCL_Weak:
3698  StrongIvars.push_back(false);
3699  WeakIvars.push_back(true);
3700  break;
3701  default:
3702  StrongIvars.push_back(false);
3703  WeakIvars.push_back(false);
3704  }
3705  }
3706  llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3707  llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
3708  llvm::GlobalVariable *IvarOffsetArray =
3709  IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3710  CGM.getPointerAlign());
3711 
3712  // Collect information about instance methods
3714  InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3715  OID->instmeth_end());
3716 
3718  ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3719  OID->classmeth_end());
3720 
3721  llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3722 
3723  // Collect the names of referenced protocols
3724  auto RefProtocols = ClassDecl->protocols();
3725  auto RuntimeProtocols =
3726  GetRuntimeProtocolList(RefProtocols.begin(), RefProtocols.end());
3727  SmallVector<std::string, 16> Protocols;
3728  for (const auto *I : RuntimeProtocols)
3729  Protocols.push_back(I->getNameAsString());
3730 
3731  // Get the superclass pointer.
3732  llvm::Constant *SuperClass;
3733  if (!SuperClassName.empty()) {
3734  SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3735  } else {
3736  SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
3737  }
3738  // Empty vector used to construct empty method lists
3740  // Generate the method and instance variable lists
3741  llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
3742  InstanceMethods, false);
3743  llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
3744  ClassMethods, true);
3745  llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
3746  IvarOffsets, IvarAligns, IvarOwnership);
3747  // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
3748  // we emit a symbol containing the offset for each ivar in the class. This
3749  // allows code compiled for the non-Fragile ABI to inherit from code compiled
3750  // for the legacy ABI, without causing problems. The converse is also
3751  // possible, but causes all ivar accesses to be fragile.
3752 
3753  // Offset pointer for getting at the correct field in the ivar list when
3754  // setting up the alias. These are: The base address for the global, the
3755  // ivar array (second field), the ivar in this list (set for each ivar), and
3756  // the offset (third field in ivar structure)
3757  llvm::Type *IndexTy = Int32Ty;
3758  llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
3759  llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3760  llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
3761 
3762  unsigned ivarIndex = 0;
3763  for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3764  IVD = IVD->getNextIvar()) {
3765  const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
3766  offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
3767  // Get the correct ivar field
3768  llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
3769  cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3770  offsetPointerIndexes);
3771  // Get the existing variable, if one exists.
3772  llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3773  if (offset) {
3774  offset->setInitializer(offsetValue);
3775  // If this is the real definition, change its linkage type so that
3776  // different modules will use this one, rather than their private
3777  // copy.
3778  offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
3779  } else
3780  // Add a new alias if there isn't one already.
3781  new llvm::GlobalVariable(TheModule, offsetValue->getType(),
3782  false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
3783  ++ivarIndex;
3784  }
3785  llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
3786 
3787  //Generate metaclass for class methods
3788  llvm::Constant *MetaClassStruct = GenerateClassStructure(
3789  NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
3790  NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3791  GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
3792  CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3793  OID->getClassInterface());
3794 
3795  // Generate the class structure
3796  llvm::Constant *ClassStruct = GenerateClassStructure(
3797  MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3798  llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3799  GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3800  StrongIvarBitmap, WeakIvarBitmap);
3801  CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3802  OID->getClassInterface());
3803 
3804  // Resolve the class aliases, if they exist.
3805  if (ClassPtrAlias) {
3806  ClassPtrAlias->replaceAllUsesWith(ClassStruct);
3807  ClassPtrAlias->eraseFromParent();
3808  ClassPtrAlias = nullptr;
3809  }
3810  if (MetaClassPtrAlias) {
3811  MetaClassPtrAlias->replaceAllUsesWith(MetaClassStruct);
3812  MetaClassPtrAlias->eraseFromParent();
3813  MetaClassPtrAlias = nullptr;
3814  }
3815 
3816  // Add class structure to list to be added to the symtab later
3817  Classes.push_back(ClassStruct);
3818 }
3819 
3820 llvm::Function *CGObjCGNU::ModuleInitFunction() {
3821  // Only emit an ObjC load function if no Objective-C stuff has been called
3822  if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
3823  ExistingProtocols.empty() && SelectorTable.empty())
3824  return nullptr;
3825 
3826  // Add all referenced protocols to a category.
3827  GenerateProtocolHolderCategory();
3828 
3829  llvm::StructType *selStructTy = dyn_cast<llvm::StructType>(SelectorElemTy);
3830  if (!selStructTy) {
3831  selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3832  { PtrToInt8Ty, PtrToInt8Ty });
3833  }
3834 
3835  // Generate statics list:
3836  llvm::Constant *statics = NULLPtr;
3837  if (!ConstantStrings.empty()) {
3838  llvm::GlobalVariable *fileStatics = [&] {
3839  ConstantInitBuilder builder(CGM);
3840  auto staticsStruct = builder.beginStruct();
3841 
3842  StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3843  if (stringClass.empty()) stringClass = "NXConstantString";
3844  staticsStruct.add(MakeConstantString(stringClass,
3845  ".objc_static_class_name"));
3846 
3847  auto array = staticsStruct.beginArray();
3848  array.addAll(ConstantStrings);
3849  array.add(NULLPtr);
3850  array.finishAndAddTo(staticsStruct);
3851 
3852  return staticsStruct.finishAndCreateGlobal(".objc_statics",
3853  CGM.getPointerAlign());
3854  }();
3855 
3856  ConstantInitBuilder builder(CGM);
3857  auto allStaticsArray = builder.beginArray(fileStatics->getType());
3858  allStaticsArray.add(fileStatics);
3859  allStaticsArray.addNullPointer(fileStatics->getType());
3860 
3861  statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3862  CGM.getPointerAlign());
3863  }
3864 
3865  // Array of classes, categories, and constant objects.
3866 
3867  SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3868  unsigned selectorCount;
3869 
3870  // Pointer to an array of selectors used in this module.
3871  llvm::GlobalVariable *selectorList = [&] {
3872  ConstantInitBuilder builder(CGM);
3873  auto selectors = builder.beginArray(selStructTy);
3874  auto &table = SelectorTable; // MSVC workaround
3875  std::vector<Selector> allSelectors;
3876  for (auto &entry : table)
3877  allSelectors.push_back(entry.first);
3878  llvm::sort(allSelectors);
3879 
3880  for (auto &untypedSel : allSelectors) {
3881  std::string selNameStr = untypedSel.getAsString();
3882  llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
3883 
3884  for (TypedSelector &sel : table[untypedSel]) {
3885  llvm::Constant *selectorTypeEncoding = NULLPtr;
3886  if (!sel.first.empty())
3887  selectorTypeEncoding =
3888  MakeConstantString(sel.first, ".objc_sel_types");
3889 
3890  auto selStruct = selectors.beginStruct(selStructTy);
3891  selStruct.add(selName);
3892  selStruct.add(selectorTypeEncoding);
3893  selStruct.finishAndAddTo(selectors);
3894 
3895  // Store the selector alias for later replacement
3896  selectorAliases.push_back(sel.second);
3897  }
3898  }
3899 
3900  // Remember the number of entries in the selector table.
3901  selectorCount = selectors.size();
3902 
3903  // NULL-terminate the selector list. This should not actually be required,
3904  // because the selector list has a length field. Unfortunately, the GCC
3905  // runtime decides to ignore the length field and expects a NULL terminator,
3906  // and GCC cooperates with this by always setting the length to 0.
3907  auto selStruct = selectors.beginStruct(selStructTy);
3908  selStruct.add(NULLPtr);
3909  selStruct.add(NULLPtr);
3910  selStruct.finishAndAddTo(selectors);
3911 
3912  return selectors.finishAndCreateGlobal(".objc_selector_list",
3913  CGM.getPointerAlign());
3914  }();
3915 
3916  // Now that all of the static selectors exist, create pointers to them.
3917  for (unsigned i = 0; i < selectorCount; ++i) {
3918  llvm::Constant *idxs[] = {
3919  Zeros[0],
3920  llvm::ConstantInt::get(Int32Ty, i)
3921  };
3922  // FIXME: We're generating redundant loads and stores here!
3923  llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3924  selectorList->getValueType(), selectorList, idxs);
3925  selectorAliases[i]->replaceAllUsesWith(selPtr);
3926  selectorAliases[i]->eraseFromParent();
3927  }
3928 
3929  llvm::GlobalVariable *symtab = [&] {
3930  ConstantInitBuilder builder(CGM);
3931  auto symtab = builder.beginStruct();
3932 
3933  // Number of static selectors
3934  symtab.addInt(LongTy, selectorCount);
3935 
3936  symtab.add(selectorList);
3937 
3938  // Number of classes defined.
3939  symtab.addInt(CGM.Int16Ty, Classes.size());
3940  // Number of categories defined
3941  symtab.addInt(CGM.Int16Ty, Categories.size());
3942 
3943  // Create an array of classes, then categories, then static object instances
3944  auto classList = symtab.beginArray(PtrToInt8Ty);
3945  classList.addAll(Classes);
3946  classList.addAll(Categories);
3947  // NULL-terminated list of static object instances (mainly constant strings)
3948  classList.add(statics);
3949  classList.add(NULLPtr);
3950  classList.finishAndAddTo(symtab);
3951 
3952  // Construct the symbol table.
3953  return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3954  }();
3955 
3956  // The symbol table is contained in a module which has some version-checking
3957  // constants
3958  llvm::Constant *module = [&] {
3959  llvm::Type *moduleEltTys[] = {
3960  LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3961  };
3962  llvm::StructType *moduleTy = llvm::StructType::get(
3963  CGM.getLLVMContext(),
3964  ArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
3965 
3966  ConstantInitBuilder builder(CGM);
3967  auto module = builder.beginStruct(moduleTy);
3968  // Runtime version, used for ABI compatibility checking.
3969  module.addInt(LongTy, RuntimeVersion);
3970  // sizeof(ModuleTy)
3971  module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3972 
3973  // The path to the source file where this module was declared
3975  OptionalFileEntryRef mainFile = SM.getFileEntryRefForID(SM.getMainFileID());
3976  std::string path =
3977  (mainFile->getDir().getName() + "/" + mainFile->getName()).str();
3978  module.add(MakeConstantString(path, ".objc_source_file_name"));
3979  module.add(symtab);
3980 
3981  if (RuntimeVersion >= 10) {
3982  switch (CGM.getLangOpts().getGC()) {
3983  case LangOptions::GCOnly:
3984  module.addInt(IntTy, 2);
3985  break;
3986  case LangOptions::NonGC:
3987  if (CGM.getLangOpts().ObjCAutoRefCount)
3988  module.addInt(IntTy, 1);
3989  else
3990  module.addInt(IntTy, 0);
3991  break;
3992  case LangOptions::HybridGC:
3993  module.addInt(IntTy, 1);
3994  break;
3995  }
3996  }
3997 
3998  return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3999  }();
4000 
4001  // Create the load function calling the runtime entry point with the module
4002  // structure
4003  llvm::Function * LoadFunction = llvm::Function::Create(
4004  llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
4005  llvm::GlobalValue::InternalLinkage, ".objc_load_function",
4006  &TheModule);
4007  llvm::BasicBlock *EntryBB =
4008  llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
4009  CGBuilderTy Builder(CGM, VMContext);
4010  Builder.SetInsertPoint(EntryBB);
4011 
4012  llvm::FunctionType *FT =
4013  llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
4014  llvm::FunctionCallee Register =
4015  CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
4016  Builder.CreateCall(Register, module);
4017 
4018  if (!ClassAliases.empty()) {
4019  llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
4020  llvm::FunctionType *RegisterAliasTy =
4021  llvm::FunctionType::get(Builder.getVoidTy(),
4022  ArgTypes, false);
4023  llvm::Function *RegisterAlias = llvm::Function::Create(
4024  RegisterAliasTy,
4025  llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
4026  &TheModule);
4027  llvm::BasicBlock *AliasBB =
4028  llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
4029  llvm::BasicBlock *NoAliasBB =
4030  llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
4031 
4032  // Branch based on whether the runtime provided class_registerAlias_np()
4033  llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
4034  llvm::Constant::getNullValue(RegisterAlias->getType()));
4035  Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
4036 
4037  // The true branch (has alias registration function):
4038  Builder.SetInsertPoint(AliasBB);
4039  // Emit alias registration calls:
4040  for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
4041  iter != ClassAliases.end(); ++iter) {
4042  llvm::Constant *TheClass =
4043  TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
4044  if (TheClass) {
4045  Builder.CreateCall(RegisterAlias,
4046  {TheClass, MakeConstantString(iter->second)});
4047  }
4048  }
4049  // Jump to end:
4050  Builder.CreateBr(NoAliasBB);
4051 
4052  // Missing alias registration function, just return from the function:
4053  Builder.SetInsertPoint(NoAliasBB);
4054  }
4055  Builder.CreateRetVoid();
4056 
4057  return LoadFunction;
4058 }
4059 
4060 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
4061  const ObjCContainerDecl *CD) {
4062  CodeGenTypes &Types = CGM.getTypes();
4063  llvm::FunctionType *MethodTy =
4064  Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
4065 
4066  bool isDirect = OMD->isDirectMethod();
4067  std::string FunctionName =
4068  getSymbolNameForMethod(OMD, /*include category*/ !isDirect);
4069 
4070  if (!isDirect)
4071  return llvm::Function::Create(MethodTy,
4072  llvm::GlobalVariable::InternalLinkage,
4073  FunctionName, &TheModule);
4074 
4075  auto *COMD = OMD->getCanonicalDecl();
4076  auto I = DirectMethodDefinitions.find(COMD);
4077  llvm::Function *OldFn = nullptr, *Fn = nullptr;
4078 
4079  if (I == DirectMethodDefinitions.end()) {
4080  auto *F =
4081  llvm::Function::Create(MethodTy, llvm::GlobalVariable::ExternalLinkage,
4082  FunctionName, &TheModule);
4083  DirectMethodDefinitions.insert(std::make_pair(COMD, F));
4084  return F;
4085  }
4086 
4087  // Objective-C allows for the declaration and implementation types
4088  // to differ slightly.
4089  //
4090  // If we're being asked for the Function associated for a method
4091  // implementation, a previous value might have been cached
4092  // based on the type of the canonical declaration.
4093  //
4094  // If these do not match, then we'll replace this function with
4095  // a new one that has the proper type below.
4096  if (!OMD->getBody() || COMD->getReturnType() == OMD->getReturnType())
4097  return I->second;
4098 
4099  OldFn = I->second;
4100  Fn = llvm::Function::Create(MethodTy, llvm::GlobalValue::ExternalLinkage, "",
4101  &CGM.getModule());
4102  Fn->takeName(OldFn);
4103  OldFn->replaceAllUsesWith(Fn);
4104  OldFn->eraseFromParent();
4105 
4106  // Replace the cached function in the map.
4107  I->second = Fn;
4108  return Fn;
4109 }
4110 
4111 void CGObjCGNU::GenerateDirectMethodPrologue(CodeGenFunction &CGF,
4112  llvm::Function *Fn,
4113  const ObjCMethodDecl *OMD,
4114  const ObjCContainerDecl *CD) {
4115  // GNU runtime doesn't support direct calls at this time
4116 }
4117 
4118 llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
4119  return GetPropertyFn;
4120 }
4121 
4122 llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
4123  return SetPropertyFn;
4124 }
4125 
4126 llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
4127  bool copy) {
4128  return nullptr;
4129 }
4130 
4131 llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
4132  return GetStructPropertyFn;
4133 }
4134 
4135 llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
4136  return SetStructPropertyFn;
4137 }
4138 
4139 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
4140  return nullptr;
4141 }
4142 
4143 llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
4144  return nullptr;
4145 }
4146 
4147 llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
4148  return EnumerationMutationFn;
4149 }
4150 
4151 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
4152  const ObjCAtSynchronizedStmt &S) {
4153  EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
4154 }
4155 
4156 
4157 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
4158  const ObjCAtTryStmt &S) {
4159  // Unlike the Apple non-fragile runtimes, which also uses
4160  // unwind-based zero cost exceptions, the GNU Objective C runtime's
4161  // EH support isn't a veneer over C++ EH. Instead, exception
4162  // objects are created by objc_exception_throw and destroyed by
4163  // the personality function; this avoids the need for bracketing
4164  // catch handlers with calls to __blah_begin_catch/__blah_end_catch
4165  // (or even _Unwind_DeleteException), but probably doesn't
4166  // interoperate very well with foreign exceptions.
4167  //
4168  // In Objective-C++ mode, we actually emit something equivalent to the C++
4169  // exception handler.
4170  EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
4171 }
4172 
4173 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
4174  const ObjCAtThrowStmt &S,
4175  bool ClearInsertionPoint) {
4176  llvm::Value *ExceptionAsObject;
4177  bool isRethrow = false;
4178 
4179  if (const Expr *ThrowExpr = S.getThrowExpr()) {
4180  llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
4181  ExceptionAsObject = Exception;
4182  } else {
4183  assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
4184  "Unexpected rethrow outside @catch block.");
4185  ExceptionAsObject = CGF.ObjCEHValueStack.back();
4186  isRethrow = true;
4187  }
4188  if (isRethrow && (usesSEHExceptions || usesCxxExceptions)) {
4189  // For SEH, ExceptionAsObject may be undef, because the catch handler is
4190  // not passed it for catchalls and so it is not visible to the catch
4191  // funclet. The real thrown object will still be live on the stack at this
4192  // point and will be rethrown. If we are explicitly rethrowing the object
4193  // that was passed into the `@catch` block, then this code path is not
4194  // reached and we will instead call `objc_exception_throw` with an explicit
4195  // argument.
4196  llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
4197  Throw->setDoesNotReturn();
4198  } else {
4199  ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
4200  llvm::CallBase *Throw =
4201  CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
4202  Throw->setDoesNotReturn();
4203  }
4204  CGF.Builder.CreateUnreachable();
4205  if (ClearInsertionPoint)
4206  CGF.Builder.ClearInsertionPoint();
4207 }
4208 
4209 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
4210  Address AddrWeakObj) {
4211  CGBuilderTy &B = CGF.Builder;
4212  return B.CreateCall(
4213  WeakReadFn, EnforceType(B, AddrWeakObj.emitRawPointer(CGF), PtrToIdTy));
4214 }
4215 
4216 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
4217  llvm::Value *src, Address dst) {
4218  CGBuilderTy &B = CGF.Builder;
4219  src = EnforceType(B, src, IdTy);
4220  llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);
4221  B.CreateCall(WeakAssignFn, {src, dstVal});
4222 }
4223 
4224 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
4225  llvm::Value *src, Address dst,
4226  bool threadlocal) {
4227  CGBuilderTy &B = CGF.Builder;
4228  src = EnforceType(B, src, IdTy);
4229  llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);
4230  // FIXME. Add threadloca assign API
4231  assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
4232  B.CreateCall(GlobalAssignFn, {src, dstVal});
4233 }
4234 
4235 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
4236  llvm::Value *src, Address dst,
4237  llvm::Value *ivarOffset) {
4238  CGBuilderTy &B = CGF.Builder;
4239  src = EnforceType(B, src, IdTy);
4240  llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), IdTy);
4241  B.CreateCall(IvarAssignFn, {src, dstVal, ivarOffset});
4242 }
4243 
4244 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
4245  llvm::Value *src, Address dst) {
4246  CGBuilderTy &B = CGF.Builder;
4247  src = EnforceType(B, src, IdTy);
4248  llvm::Value *dstVal = EnforceType(B, dst.emitRawPointer(CGF), PtrToIdTy);
4249  B.CreateCall(StrongCastAssignFn, {src, dstVal});
4250 }
4251 
4252 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
4253  Address DestPtr,
4254  Address SrcPtr,
4255  llvm::Value *Size) {
4256  CGBuilderTy &B = CGF.Builder;
4257  llvm::Value *DestPtrVal = EnforceType(B, DestPtr.emitRawPointer(CGF), PtrTy);
4258  llvm::Value *SrcPtrVal = EnforceType(B, SrcPtr.emitRawPointer(CGF), PtrTy);
4259 
4260  B.CreateCall(MemMoveFn, {DestPtrVal, SrcPtrVal, Size});
4261 }
4262 
4263 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4264  const ObjCInterfaceDecl *ID,
4265  const ObjCIvarDecl *Ivar) {
4266  const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
4267  // Emit the variable and initialize it with what we think the correct value
4268  // is. This allows code compiled with non-fragile ivars to work correctly
4269  // when linked against code which isn't (most of the time).
4270  llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
4271  if (!IvarOffsetPointer)
4272  IvarOffsetPointer = new llvm::GlobalVariable(
4273  TheModule, llvm::PointerType::getUnqual(VMContext), false,
4274  llvm::GlobalValue::ExternalLinkage, nullptr, Name);
4275  return IvarOffsetPointer;
4276 }
4277 
4278 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
4279  QualType ObjectTy,
4280  llvm::Value *BaseValue,
4281  const ObjCIvarDecl *Ivar,
4282  unsigned CVRQualifiers) {
4283  const ObjCInterfaceDecl *ID =
4284  ObjectTy->castAs<ObjCObjectType>()->getInterface();
4285  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4286  EmitIvarOffset(CGF, ID, Ivar));
4287 }
4288 
4290  const ObjCInterfaceDecl *OID,
4291  const ObjCIvarDecl *OIVD) {
4292  for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4293  next = next->getNextIvar()) {
4294  if (OIVD == next)
4295  return OID;
4296  }
4297 
4298  // Otherwise check in the super class.
4299  if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4300  return FindIvarInterface(Context, Super, OIVD);
4301 
4302  return nullptr;
4303 }
4304 
4305 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
4306  const ObjCInterfaceDecl *Interface,
4307  const ObjCIvarDecl *Ivar) {
4308  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
4309  Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
4310 
4311  // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4312  // and ExternalLinkage, so create a reference to the ivar global and rely on
4313  // the definition being created as part of GenerateClass.
4314  if (RuntimeVersion < 10 ||
4315  CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
4316  return CGF.Builder.CreateZExtOrBitCast(
4318  Int32Ty,
4320  llvm::PointerType::getUnqual(VMContext),
4321  ObjCIvarOffsetVariable(Interface, Ivar),
4322  CGF.getPointerAlign(), "ivar"),
4323  CharUnits::fromQuantity(4)),
4324  PtrDiffTy);
4325  std::string name = "__objc_ivar_offset_value_" +
4326  Interface->getNameAsString() +"." + Ivar->getNameAsString();
4327  CharUnits Align = CGM.getIntAlign();
4328  llvm::Value *Offset = TheModule.getGlobalVariable(name);
4329  if (!Offset) {
4330  auto GV = new llvm::GlobalVariable(TheModule, IntTy,
4331  false, llvm::GlobalValue::LinkOnceAnyLinkage,
4332  llvm::Constant::getNullValue(IntTy), name);
4333  GV->setAlignment(Align.getAsAlign());
4334  Offset = GV;
4335  }
4336  Offset = CGF.Builder.CreateAlignedLoad(IntTy, Offset, Align);
4337  if (Offset->getType() != PtrDiffTy)
4338  Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4339  return Offset;
4340  }
4341  uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4342  return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
4343 }
4344 
4345 CGObjCRuntime *
4347  auto Runtime = CGM.getLangOpts().ObjCRuntime;
4348  switch (Runtime.getKind()) {
4349  case ObjCRuntime::GNUstep:
4350  if (Runtime.getVersion() >= VersionTuple(2, 0))
4351  return new CGObjCGNUstep2(CGM);
4352  return new CGObjCGNUstep(CGM);
4353 
4354  case ObjCRuntime::GCC:
4355  return new CGObjCGCC(CGM);
4356 
4357  case ObjCRuntime::ObjFW:
4358  return new CGObjCObjFW(CGM);
4359 
4360  case ObjCRuntime::FragileMacOSX:
4361  case ObjCRuntime::MacOSX:
4362  case ObjCRuntime::iOS:
4363  case ObjCRuntime::WatchOS:
4364  llvm_unreachable("these runtimes are not GNU runtimes");
4365  }
4366  llvm_unreachable("bad runtime");
4367 }
Defines the clang::ASTContext interface.
#define V(N, I)
Definition: ASTContext.h:3299
StringRef P
static char ID
Definition: Arena.cpp:183
#define SM(sm)
Definition: Cuda.cpp:83
static const ObjCInterfaceDecl * FindIvarInterface(ASTContext &Context, const ObjCInterfaceDecl *OID, const ObjCIvarDecl *OIVD)
Definition: CGObjCGNU.cpp:4289
static bool isNamed(const NamedDecl *ND, const char(&Str)[Len])
Definition: Decl.cpp:3267
Defines the clang::FileManager interface and associated types.
unsigned Offset
Definition: Format.cpp:2978
int Category
Definition: Format.cpp:2979
Defines the SourceManager interface.
Defines the Objective-C statement AST node classes.
__device__ __2f16 b
__device__ __2f16 float __ockl_bool s
__device__ __2f16 float c
do v
Definition: arm_acle.h:83
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:185
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
SourceManager & getSourceManager()
Definition: ASTContext.h:708
CanQualType LongTy
Definition: ASTContext.h:1103
void getObjCEncodingForType(QualType T, std::string &S, const FieldDecl *Field=nullptr, QualType *NotEncodedT=nullptr) const
Emit the Objective-CC type encoding for the given type T into S.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2589
std::string getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
std::string getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
getObjCEncodingForPropertyDecl - Return the encoded type for this method declaration.
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
IdentifierTable & Idents
Definition: ASTContext.h:647
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
QualType getObjCProtoType() const
Retrieve the type of the Objective-C Protocol class.
Definition: ASTContext.h:2124
QualType getPointerDiffType() const
Return the unique type for "ptrdiff_t" (C99 7.17) defined in <stddef.h>.
ObjCPropertyImplDecl * getObjCPropertyImplDeclForPropertyDecl(const ObjCPropertyDecl *PD, const Decl *Container) const
CanQualType BoolTy
Definition: ASTContext.h:1095
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2088
CanQualType getSizeType() const
Return the unique type for "size_t" (C99 7.17), defined in <stddef.h>.
CanQualType IntTy
Definition: ASTContext.h:1103
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2078
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2355
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
void getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, QualType T, std::string &S, bool Extended) const
getObjCEncodingForMethodParameter - Return the encoded type for a single method parameter or return t...
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:760
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1076
uint64_t getCharWidth() const
Return the size of the character type, in bits.
Definition: ASTContext.h:2359
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:193
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
llvm::Align getAsAlign() const
getAsAlign - Returns Quantity as a valid llvm::Align, Beware llvm::Align assumes power of two 8-bit b...
Definition: CharUnits.h:189
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:185
static CharUnits fromQuantity(QuantityType Quantity)
fromQuantity - Construct a CharUnits quantity from a raw integer type.
Definition: CharUnits.h:63
Like RawAddress, an abstract representation of an aligned address, but the pointer contained in this ...
Definition: Address.h:111
llvm::Value * emitRawPointer(CodeGenFunction &CGF) const
Return the pointer contained in this class after authenticating it and adding offset to it if necessa...
Definition: Address.h:220
CGBlockInfo - Information to generate a block literal.
Definition: CGBlocks.h:156
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:128
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:136
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:108
virtual CatchTypeInfo getCatchAllTypeInfo()
Definition: CGCXXABI.cpp:338
virtual llvm::Constant * getAddrOfRTTIDescriptor(QualType Ty)=0
Abstract information about a function or function prototype.
Definition: CGCall.h:40
All available information about a concrete callee.
Definition: CGCall.h:62
Implements runtime-specific code generation functions.
Definition: CGObjCRuntime.h:65
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:257
void add(RValue rvalue, QualType type)
Definition: CGCall.h:281
void addFrom(const CallArgList &other)
Add all the arguments from another CallArgList to this one.
Definition: CGCall.h:290
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
void EmitNullInitialization(Address DestPtr, QualType Ty)
EmitNullInitialization - Generate code to set a value of the given type to null, If the type contains...
llvm::CallBase * EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition: CGCall.cpp:4952
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
SmallVector< llvm::Value *, 8 > ObjCEHValueStack
ObjCEHValueStack - Stack of Objective-C exception values, used for rethrows.
llvm::Value * EmitObjCThrowOperand(const Expr *expr)
Definition: CGObjC.cpp:3497
void EmitBranchThroughCleanup(JumpDest Dest)
EmitBranchThroughCleanup - Emit a branch from the current insert block through the normal cleanup han...
Definition: CGCleanup.cpp:1096
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
RValue EmitCall(const CGFunctionInfo &CallInfo, const CGCallee &Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, llvm::CallBase **callOrInvoke, bool IsMustTail, SourceLocation Loc)
EmitCall - Generate a call of the given function, expecting the given result type,...
Definition: CGCall.cpp:5108
JumpDest ReturnBlock
ReturnBlock - Unified return block.
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp", llvm::Value *ArraySize=nullptr)
CreateTempAlloca - This creates an alloca and inserts it into the entry block if ArraySize is nullptr...
Definition: CGExpr.cpp:116
llvm::CallInst * EmitRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Value * LoadObjCSelf()
LoadObjCSelf - Load the value of self.
Definition: CGObjC.cpp:1745
void EmitVarDecl(const VarDecl &D)
EmitVarDecl - Emit a local variable declaration.
Definition: CGDecl.cpp:193
static bool hasAggregateEvaluationKind(QualType T)
Address GetAddrOfLocalVar(const VarDecl *VD)
GetAddrOfLocalVar - Return the address of a local variable.
Address ReturnValue
ReturnValue - The temporary alloca to hold the return value.
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:578
This class organizes the cross-function state that is used while generating LLVM code.
void setGVProperties(llvm::GlobalValue *GV, GlobalDecl GD) const
Set visibility, dllimport/dllexport and dso_local.
const TargetInfo & getTarget() const
llvm::FunctionCallee CreateRuntimeFunction(llvm::FunctionType *Ty, StringRef Name, llvm::AttributeList ExtraAttrs=llvm::AttributeList(), bool Local=false, bool AssumeConvergent=false)
Create or return a runtime function declaration with the specified type and name.
void addCompilerUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.compiler.used metadata.
const llvm::DataLayout & getDataLayout() const
bool ReturnTypeUsesFPRet(QualType ResultType)
Return true iff the given type uses 'fpret' when used as a return type.
Definition: CGCall.cpp:1607
llvm::Module & getModule() const
const LangOptions & getLangOpts() const
void addUsedGlobal(llvm::GlobalValue *GV)
Add a global to a list to be added to the llvm.used metadata.
const llvm::Triple & getTriple() const
llvm::LLVMContext & getLLVMContext()
CGCXXABI & getCXXABI() const
bool ReturnTypeHasInReg(const CGFunctionInfo &FI)
Return true iff the given type has inreg set.
Definition: CGCall.cpp:1597
bool ReturnTypeUsesSRet(const CGFunctionInfo &FI)
Return true iff the given type uses 'sret' when used as a return type.
Definition: CGCall.cpp:1592
ASTContext & getContext() const
const CodeGenOptions & getCodeGenOpts() const
llvm::Constant * EmitNullConstant(QualType T)
Return the result of value-initializing the given type, i.e.
ConstantAddress GetAddrOfConstantCString(const std::string &Str, const char *GlobalName=nullptr)
Returns a pointer to a character array containing the literal and a terminating '\0' character.
This class organizes the cross-module state that is used while lowering AST types to LLVM types.
Definition: CodeGenTypes.h:54
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
bool isZeroInitializable(QualType T)
IsZeroInitializable - Return whether a type can be zero-initialized (in the C++ sense) with an LLVM z...
llvm::Type * ConvertTypeForMem(QualType T, bool ForBitField=false)
ConvertTypeForMem - Convert type T into a llvm::Type.
A specialization of Address that requires the address to be an LLVM Constant.
Definition: Address.h:260
llvm::GlobalVariable * finishAndCreateGlobal(As &&...args)
Given that this builder was created by beginning an array or struct directly on a ConstantInitBuilder...
ArrayBuilder beginArray(llvm::Type *eltTy=nullptr)
StructBuilder beginStruct(llvm::StructType *ty=nullptr)
void finishAndAddTo(AggregateBuilderBase &parent)
Given that this builder was created by beginning an array or struct component on the given parent bui...
A helper class of ConstantInitBuilder, used for building constant array initializers.
The standard implementation of ConstantInitBuilder used in Clang.
A helper class of ConstantInitBuilder, used for building constant struct initializers.
LValue - This represents an lvalue references.
Definition: CGValue.h:181
RValue - This trivial value class is used to represent the result of an expression that is evaluated.
Definition: CGValue.h:41
bool isScalar() const
Definition: CGValue.h:63
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition: CGValue.h:77
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:70
bool isAggregate() const
Definition: CGValue.h:65
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition: CGValue.h:82
An abstract representation of an aligned address.
Definition: Address.h:41
llvm::Value * getPointer() const
Definition: Address.h:65
ReturnValueSlot - Contains the address where the return value of a function can be stored,...
Definition: CGCall.h:355
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
static void add(Kind k)
Definition: DeclBase.cpp:202
bool isWeakImported() const
Determine whether this is a weak-imported symbol.
Definition: DeclBase.cpp:820
@ OBJC_TQ_None
Definition: DeclBase.h:199
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:530
bool hasAttr() const
Definition: DeclBase.h:583
StringRef getName() const
This represents one expression.
Definition: Expr.h:110
StringRef getName() const
The name of this FileEntry.
Definition: FileEntry.h:61
DirectoryEntryRef getDir() const
Definition: FileEntry.h:73
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:482
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:517
std::string ObjCConstantStringClass
Definition: LangOptions.h:521
Visibility getVisibility() const
Determines the visibility of this entity.
Definition: Decl.h:420
std::string getNameAsString() const
Get a human-readable name for the declaration, even if it is one of the special kinds of names (C++ c...
Definition: Decl.h:292
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
Represents Objective-C's @synchronized statement.
Definition: StmtObjC.h:303
Represents Objective-C's @throw statement.
Definition: StmtObjC.h:358
Represents Objective-C's @try ... @catch ... @finally statement.
Definition: StmtObjC.h:167
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2326
const ObjCProtocolList & getReferencedProtocols() const
Definition: DeclObjC.h:2393
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2542
ObjCCategoryDecl * getCategoryDecl() const
Definition: DeclObjC.cpp:2199
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2772
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2790
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:947
classmeth_iterator classmeth_end() const
Definition: DeclObjC.h:1057
classmeth_iterator classmeth_begin() const
Definition: DeclObjC.h:1053
instmeth_range instance_methods() const
Definition: DeclObjC.h:1032
instmeth_iterator instmeth_end() const
Definition: DeclObjC.h:1040
instmeth_iterator instmeth_begin() const
Definition: DeclObjC.h:1036
prop_range properties() const
Definition: DeclObjC.h:966
classmeth_range class_methods() const
Definition: DeclObjC.h:1049
propimpl_range property_impls() const
Definition: DeclObjC.h:2510
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2483
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2594
Represents an ObjC class declaration.
Definition: DeclObjC.h:1153
all_protocol_range all_referenced_protocols() const
Definition: DeclObjC.h:1416
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1541
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
Definition: DeclObjC.cpp:1672
protocol_range protocols() const
Definition: DeclObjC.h:1358
protocol_iterator protocol_end() const
Definition: DeclObjC.h:1373
protocol_iterator protocol_begin() const
Definition: DeclObjC.h:1362
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:352
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1760
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6964
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.cpp:903
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1950
ObjCInterfaceDecl * getContainingInterface()
Return the class interface that this ivar is logically contained in; this is either the interface whe...
Definition: DeclObjC.cpp:1875
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1985
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:140
bool hasParamDestroyedInCallee() const
True if the method has a parameter that's destroyed in the callee.
Definition: DeclObjC.cpp:901
Stmt * getBody() const override
Retrieve the body of this method, if it has one.
Definition: DeclObjC.cpp:909
ObjCMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclObjC.cpp:1012
ImplicitParamDecl * getCmdDecl() const
Definition: DeclObjC.h:420
ImplicitParamDecl * getSelfDecl() const
Definition: DeclObjC.h:418
bool isDirectMethod() const
True if the method is tagged as objc_direct.
Definition: DeclObjC.cpp:871
Selector getSelector() const
Definition: DeclObjC.h:327
QualType getReturnType() const
Definition: DeclObjC.h:329
bool isClassMethod() const
Definition: DeclObjC.h:434
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.cpp:1211
Represents a pointer to an Objective C object.
Definition: Type.h:7020
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:7057
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1798
Represents a class type in Objective C.
Definition: Type.h:6766
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:6999
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:730
ObjCMethodDecl * getGetterMethodDecl() const
Definition: DeclObjC.h:900
QualType getType() const
Definition: DeclObjC.h:803
ObjCMethodDecl * getSetterMethodDecl() const
Definition: DeclObjC.h:903
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2082
bool isNonRuntimeProtocol() const
This is true iff the protocol is tagged with the objc_non_runtime_protocol attribute.
Definition: DeclObjC.cpp:1961
protocol_iterator protocol_begin() const
Definition: DeclObjC.h:2162
protocol_range protocols() const
Definition: DeclObjC.h:2158
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
Definition: DeclObjC.h:2247
protocol_iterator protocol_end() const
Definition: DeclObjC.h:2169
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:28
const VersionTuple & getVersion() const
Definition: ObjCRuntime.h:78
Kind getKind() const
Definition: ObjCRuntime.h:77
bool isNonFragile() const
Does this runtime follow the set of implied behaviors for a "non-fragile" ABI?
Definition: ObjCRuntime.h:82
Kind
The basic Objective-C runtimes that we know about.
Definition: ObjCRuntime.h:31
@ GNUstep
'gnustep' is the modern non-fragile GNUstep runtime.
Definition: ObjCRuntime.h:56
A (possibly-)qualified type.
Definition: Type.h:940
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:347
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:340
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:336
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:350
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:353
This table allows us to fully hide how we implement multi-keyword caching.
Smart pointer class that efficiently represents Objective-C method names.
std::string getAsString() const
Derive the full selector name (e.g.
This class handles loading and caching of source files into memory.
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1773
bool containsNonAscii() const
Definition: Expr.h:1905
unsigned getLength() const
Definition: Expr.h:1890
uint32_t getCodeUnit(size_t i) const
Definition: Expr.h:1865
StringRef getString() const
Definition: Expr.h:1850
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition: TargetInfo.h:472
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
The top declaration context.
Definition: Decl.h:84
static DeclContext * castToDeclContext(const TranslationUnitDecl *D)
Definition: Decl.h:130
bool isVoidType() const
Definition: Type.h:7939
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8227
bool isObjCQualifiedIdType() const
Definition: Type.h:7781
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8054
bool isObjCIdType() const
Definition: Type.h:7793
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8160
bool hasPointerRepresentation() const
Whether this type is represented natively as a pointer.
Definition: Type.h:8101
QualType getType() const
Definition: Decl.h:718
Represents a variable declaration or definition.
Definition: Decl.h:919
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
Definition: CGObjCGNU.cpp:4346
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:65
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition: PrimType.h:99
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1877
bool Init(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1472
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
RangeSelector node(std::string ID)
Selects a node, including trailing semicolon, if any (for declarations and non-expression statements)...
RangeSelector name(std::string ID)
Given a node with a "name", (like NamedDecl, DeclRefExpr, CxxCtorInitializer, and TypeLoc) selects th...
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition: Address.h:294
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
Selector GetNullarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing a nullary selector.
Definition: ASTContext.h:3439
const FunctionProtoType * T
@ Interface
The "__interface" keyword introduces the elaborated-type-specifier.
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ HiddenVisibility
Objects with "hidden" visibility are not seen by the dynamic linker.
Definition: Visibility.h:37
@ DefaultVisibility
Objects with "default" visibility are seen by the dynamic linker and act like normal objects.
Definition: Visibility.h:46
unsigned long uint64_t
The MS C++ ABI needs a pointer to RTTI data plus some flags to describe the type of a catch handler,...
Definition: CGCleanup.h:39