clang  3.9.0
CGObjCGNU.cpp
Go to the documentation of this file.
1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This provides Objective-C code generation targeting the GNU runtime. The
11 // class in this file generates structures used by the GNU Objective-C runtime
12 // library. These structures are defined in objc/objc.h and objc/objc-api.h in
13 // the GNU runtime distribution.
14 //
15 //===----------------------------------------------------------------------===//
16 
17 #include "CGObjCRuntime.h"
18 #include "CGCleanup.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtObjC.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Support/Compiler.h"
36 #include <cstdarg>
37 
38 using namespace clang;
39 using namespace CodeGen;
40 
41 namespace {
42 /// Class that lazily initialises the runtime function. Avoids inserting the
43 /// types and the function declaration into a module if they're not used, and
44 /// avoids constructing the type more than once if it's used more than once.
45 class LazyRuntimeFunction {
46  CodeGenModule *CGM;
47  llvm::FunctionType *FTy;
48  const char *FunctionName;
49  llvm::Constant *Function;
50 
51 public:
52  /// Constructor leaves this class uninitialized, because it is intended to
53  /// be used as a field in another class and not all of the types that are
54  /// used as arguments will necessarily be available at construction time.
55  LazyRuntimeFunction()
56  : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
57 
58  /// Initialises the lazy function with the name, return type, and the types
59  /// of the arguments.
60  LLVM_END_WITH_NULL
61  void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy, ...) {
62  CGM = Mod;
63  FunctionName = name;
64  Function = nullptr;
65  std::vector<llvm::Type *> ArgTys;
66  va_list Args;
67  va_start(Args, RetTy);
68  while (llvm::Type *ArgTy = va_arg(Args, llvm::Type *))
69  ArgTys.push_back(ArgTy);
70  va_end(Args);
71  FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
72  }
73 
74  llvm::FunctionType *getType() { return FTy; }
75 
76  /// Overloaded cast operator, allows the class to be implicitly cast to an
77  /// LLVM constant.
78  operator llvm::Constant *() {
79  if (!Function) {
80  if (!FunctionName)
81  return nullptr;
82  Function =
83  cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
84  }
85  return Function;
86  }
87  operator llvm::Function *() {
88  return cast<llvm::Function>((llvm::Constant *)*this);
89  }
90 };
91 
92 
93 /// GNU Objective-C runtime code generation. This class implements the parts of
94 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
95 /// GNUstep and ObjFW).
96 class CGObjCGNU : public CGObjCRuntime {
97 protected:
98  /// The LLVM module into which output is inserted
99  llvm::Module &TheModule;
100  /// strut objc_super. Used for sending messages to super. This structure
101  /// contains the receiver (object) and the expected class.
102  llvm::StructType *ObjCSuperTy;
103  /// struct objc_super*. The type of the argument to the superclass message
104  /// lookup functions.
105  llvm::PointerType *PtrToObjCSuperTy;
106  /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
107  /// SEL is included in a header somewhere, in which case it will be whatever
108  /// type is declared in that header, most likely {i8*, i8*}.
109  llvm::PointerType *SelectorTy;
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  /// Instance Method Pointer type. This is a pointer to a function that takes,
117  /// at a minimum, an object and a selector, and is the generic type for
118  /// Objective-C methods. Due to differences between variadic / non-variadic
119  /// calling conventions, it must always be cast to the correct type before
120  /// actually being used.
121  llvm::PointerType *IMPTy;
122  /// Type of an untyped Objective-C object. Clang treats id as a built-in type
123  /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
124  /// but if the runtime header declaring it is included then it may be a
125  /// pointer to a structure.
126  llvm::PointerType *IdTy;
127  /// Pointer to a pointer to an Objective-C object. Used in the new ABI
128  /// message lookup function and some GC-related functions.
129  llvm::PointerType *PtrToIdTy;
130  /// The clang type of id. Used when using the clang CGCall infrastructure to
131  /// call Objective-C methods.
132  CanQualType ASTIdTy;
133  /// LLVM type for C int type.
134  llvm::IntegerType *IntTy;
135  /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
136  /// used in the code to document the difference between i8* meaning a pointer
137  /// to a C string and i8* meaning a pointer to some opaque type.
138  llvm::PointerType *PtrTy;
139  /// LLVM type for C long type. The runtime uses this in a lot of places where
140  /// it should be using intptr_t, but we can't fix this without breaking
141  /// compatibility with GCC...
142  llvm::IntegerType *LongTy;
143  /// LLVM type for C size_t. Used in various runtime data structures.
144  llvm::IntegerType *SizeTy;
145  /// LLVM type for C intptr_t.
146  llvm::IntegerType *IntPtrTy;
147  /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
148  llvm::IntegerType *PtrDiffTy;
149  /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
150  /// variables.
151  llvm::PointerType *PtrToIntTy;
152  /// LLVM type for Objective-C BOOL type.
153  llvm::Type *BoolTy;
154  /// 32-bit integer type, to save us needing to look it up every time it's used.
155  llvm::IntegerType *Int32Ty;
156  /// 64-bit integer type, to save us needing to look it up every time it's used.
157  llvm::IntegerType *Int64Ty;
158  /// Metadata kind used to tie method lookups to message sends. The GNUstep
159  /// runtime provides some LLVM passes that can use this to do things like
160  /// automatic IMP caching and speculative inlining.
161  unsigned msgSendMDKind;
162 
163  /// Helper function that generates a constant string and returns a pointer to
164  /// the start of the string. The result of this function can be used anywhere
165  /// where the C code specifies const char*.
166  llvm::Constant *MakeConstantString(const std::string &Str,
167  const std::string &Name="") {
168  ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name.c_str());
169  return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
170  Array.getPointer(), Zeros);
171  }
172 
173  /// Emits a linkonce_odr string, whose name is the prefix followed by the
174  /// string value. This allows the linker to combine the strings between
175  /// different modules. Used for EH typeinfo names, selector strings, and a
176  /// few other things.
177  llvm::Constant *ExportUniqueString(const std::string &Str,
178  const std::string prefix) {
179  std::string name = prefix + Str;
180  auto *ConstStr = TheModule.getGlobalVariable(name);
181  if (!ConstStr) {
182  llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
183  ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
184  llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
185  }
186  return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
187  ConstStr, Zeros);
188  }
189 
190  /// Generates a global structure, initialized by the elements in the vector.
191  /// The element types must match the types of the structure elements in the
192  /// first argument.
193  llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
195  CharUnits Align,
196  StringRef Name="",
197  llvm::GlobalValue::LinkageTypes linkage
199  llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
200  auto GV = new llvm::GlobalVariable(TheModule, Ty, false,
201  linkage, C, Name);
202  GV->setAlignment(Align.getQuantity());
203  return GV;
204  }
205 
206  /// Generates a global array. The vector must contain the same number of
207  /// elements that the array type declares, of the type specified as the array
208  /// element type.
209  llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
211  CharUnits Align,
212  StringRef Name="",
213  llvm::GlobalValue::LinkageTypes linkage
215  llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
216  auto GV = new llvm::GlobalVariable(TheModule, Ty, false,
217  linkage, C, Name);
218  GV->setAlignment(Align.getQuantity());
219  return GV;
220  }
221 
222  /// Generates a global array, inferring the array type from the specified
223  /// element type and the size of the initialiser.
224  llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
226  CharUnits Align,
227  StringRef Name="",
228  llvm::GlobalValue::LinkageTypes linkage
230  llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
231  return MakeGlobal(ArrayTy, V, Align, Name, linkage);
232  }
233 
234  /// Returns a property name and encoding string.
235  llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
236  const Decl *Container) {
237  const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
238  if ((R.getKind() == ObjCRuntime::GNUstep) &&
239  (R.getVersion() >= VersionTuple(1, 6))) {
240  std::string NameAndAttributes;
241  std::string TypeStr;
242  CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
243  NameAndAttributes += '\0';
244  NameAndAttributes += TypeStr.length() + 3;
245  NameAndAttributes += TypeStr;
246  NameAndAttributes += '\0';
247  NameAndAttributes += PD->getNameAsString();
248  return MakeConstantString(NameAndAttributes);
249  }
250  return MakeConstantString(PD->getNameAsString());
251  }
252 
253  /// Push the property attributes into two structure fields.
254  void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
255  ObjCPropertyDecl *property, bool isSynthesized=true, bool
256  isDynamic=true) {
257  int attrs = property->getPropertyAttributes();
258  // For read-only properties, clear the copy and retain flags
260  attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
261  attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
262  attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
263  attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
264  }
265  // The first flags field has the same attribute values as clang uses internally
266  Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
267  attrs >>= 8;
268  attrs <<= 2;
269  // For protocol properties, synthesized and dynamic have no meaning, so we
270  // reuse these flags to indicate that this is a protocol property (both set
271  // has no meaning, as a property can't be both synthesized and dynamic)
272  attrs |= isSynthesized ? (1<<0) : 0;
273  attrs |= isDynamic ? (1<<1) : 0;
274  // The second field is the next four fields left shifted by two, with the
275  // low bit set to indicate whether the field is synthesized or dynamic.
276  Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
277  // Two padding fields
278  Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
279  Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
280  }
281 
282  /// Ensures that the value has the required type, by inserting a bitcast if
283  /// required. This function lets us avoid inserting bitcasts that are
284  /// redundant.
285  llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
286  if (V->getType() == Ty) return V;
287  return B.CreateBitCast(V, Ty);
288  }
289  Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
290  if (V.getType() == Ty) return V;
291  return B.CreateBitCast(V, Ty);
292  }
293 
294  // Some zeros used for GEPs in lots of places.
295  llvm::Constant *Zeros[2];
296  /// Null pointer value. Mainly used as a terminator in various arrays.
297  llvm::Constant *NULLPtr;
298  /// LLVM context.
299  llvm::LLVMContext &VMContext;
300 
301 private:
302  /// Placeholder for the class. Lots of things refer to the class before we've
303  /// actually emitted it. We use this alias as a placeholder, and then replace
304  /// it with a pointer to the class structure before finally emitting the
305  /// module.
306  llvm::GlobalAlias *ClassPtrAlias;
307  /// Placeholder for the metaclass. Lots of things refer to the class before
308  /// we've / actually emitted it. We use this alias as a placeholder, and then
309  /// replace / it with a pointer to the metaclass structure before finally
310  /// emitting the / module.
311  llvm::GlobalAlias *MetaClassPtrAlias;
312  /// All of the classes that have been generated for this compilation units.
313  std::vector<llvm::Constant*> Classes;
314  /// All of the categories that have been generated for this compilation units.
315  std::vector<llvm::Constant*> Categories;
316  /// All of the Objective-C constant strings that have been generated for this
317  /// compilation units.
318  std::vector<llvm::Constant*> ConstantStrings;
319  /// Map from string values to Objective-C constant strings in the output.
320  /// Used to prevent emitting Objective-C strings more than once. This should
321  /// not be required at all - CodeGenModule should manage this list.
322  llvm::StringMap<llvm::Constant*> ObjCStrings;
323  /// All of the protocols that have been declared.
324  llvm::StringMap<llvm::Constant*> ExistingProtocols;
325  /// For each variant of a selector, we store the type encoding and a
326  /// placeholder value. For an untyped selector, the type will be the empty
327  /// string. Selector references are all done via the module's selector table,
328  /// so we create an alias as a placeholder and then replace it with the real
329  /// value later.
330  typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
331  /// Type of the selector map. This is roughly equivalent to the structure
332  /// used in the GNUstep runtime, which maintains a list of all of the valid
333  /// types for a selector in a table.
334  typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
335  SelectorMap;
336  /// A map from selectors to selector types. This allows us to emit all
337  /// selectors of the same name and type together.
338  SelectorMap SelectorTable;
339 
340  /// Selectors related to memory management. When compiling in GC mode, we
341  /// omit these.
342  Selector RetainSel, ReleaseSel, AutoreleaseSel;
343  /// Runtime functions used for memory management in GC mode. Note that clang
344  /// supports code generation for calling these functions, but neither GNU
345  /// runtime actually supports this API properly yet.
346  LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
347  WeakAssignFn, GlobalAssignFn;
348 
349  typedef std::pair<std::string, std::string> ClassAliasPair;
350  /// All classes that have aliases set for them.
351  std::vector<ClassAliasPair> ClassAliases;
352 
353 protected:
354  /// Function used for throwing Objective-C exceptions.
355  LazyRuntimeFunction ExceptionThrowFn;
356  /// Function used for rethrowing exceptions, used at the end of \@finally or
357  /// \@synchronize blocks.
358  LazyRuntimeFunction ExceptionReThrowFn;
359  /// Function called when entering a catch function. This is required for
360  /// differentiating Objective-C exceptions and foreign exceptions.
361  LazyRuntimeFunction EnterCatchFn;
362  /// Function called when exiting from a catch block. Used to do exception
363  /// cleanup.
364  LazyRuntimeFunction ExitCatchFn;
365  /// Function called when entering an \@synchronize block. Acquires the lock.
366  LazyRuntimeFunction SyncEnterFn;
367  /// Function called when exiting an \@synchronize block. Releases the lock.
368  LazyRuntimeFunction SyncExitFn;
369 
370 private:
371  /// Function called if fast enumeration detects that the collection is
372  /// modified during the update.
373  LazyRuntimeFunction EnumerationMutationFn;
374  /// Function for implementing synthesized property getters that return an
375  /// object.
376  LazyRuntimeFunction GetPropertyFn;
377  /// Function for implementing synthesized property setters that return an
378  /// object.
379  LazyRuntimeFunction SetPropertyFn;
380  /// Function used for non-object declared property getters.
381  LazyRuntimeFunction GetStructPropertyFn;
382  /// Function used for non-object declared property setters.
383  LazyRuntimeFunction SetStructPropertyFn;
384 
385  /// The version of the runtime that this class targets. Must match the
386  /// version in the runtime.
387  int RuntimeVersion;
388  /// The version of the protocol class. Used to differentiate between ObjC1
389  /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
390  /// components and can not contain declared properties. We always emit
391  /// Objective-C 2 property structures, but we have to pretend that they're
392  /// Objective-C 1 property structures when targeting the GCC runtime or it
393  /// will abort.
394  const int ProtocolVersion;
395 
396  /// Generates an instance variable list structure. This is a structure
397  /// containing a size and an array of structures containing instance variable
398  /// metadata. This is used purely for introspection in the fragile ABI. In
399  /// the non-fragile ABI, it's used for instance variable fixup.
400  llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
401  ArrayRef<llvm::Constant *> IvarTypes,
402  ArrayRef<llvm::Constant *> IvarOffsets);
403 
404  /// Generates a method list structure. This is a structure containing a size
405  /// and an array of structures containing method metadata.
406  ///
407  /// This structure is used by both classes and categories, and contains a next
408  /// pointer allowing them to be chained together in a linked list.
409  llvm::Constant *GenerateMethodList(StringRef ClassName,
410  StringRef CategoryName,
411  ArrayRef<Selector> MethodSels,
412  ArrayRef<llvm::Constant *> MethodTypes,
413  bool isClassMethodList);
414 
415  /// Emits an empty protocol. This is used for \@protocol() where no protocol
416  /// is found. The runtime will (hopefully) fix up the pointer to refer to the
417  /// real protocol.
418  llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
419 
420  /// Generates a list of property metadata structures. This follows the same
421  /// pattern as method and instance variable metadata lists.
422  llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
423  SmallVectorImpl<Selector> &InstanceMethodSels,
424  SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
425 
426  /// Generates a list of referenced protocols. Classes, categories, and
427  /// protocols all use this structure.
428  llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
429 
430  /// To ensure that all protocols are seen by the runtime, we add a category on
431  /// a class defined in the runtime, declaring no methods, but adopting the
432  /// protocols. This is a horribly ugly hack, but it allows us to collect all
433  /// of the protocols without changing the ABI.
434  void GenerateProtocolHolderCategory();
435 
436  /// Generates a class structure.
437  llvm::Constant *GenerateClassStructure(
438  llvm::Constant *MetaClass,
439  llvm::Constant *SuperClass,
440  unsigned info,
441  const char *Name,
442  llvm::Constant *Version,
443  llvm::Constant *InstanceSize,
444  llvm::Constant *IVars,
445  llvm::Constant *Methods,
446  llvm::Constant *Protocols,
447  llvm::Constant *IvarOffsets,
448  llvm::Constant *Properties,
449  llvm::Constant *StrongIvarBitmap,
450  llvm::Constant *WeakIvarBitmap,
451  bool isMeta=false);
452 
453  /// Generates a method list. This is used by protocols to define the required
454  /// and optional methods.
455  llvm::Constant *GenerateProtocolMethodList(
456  ArrayRef<llvm::Constant *> MethodNames,
457  ArrayRef<llvm::Constant *> MethodTypes);
458 
459  /// Returns a selector with the specified type encoding. An empty string is
460  /// used to return an untyped selector (with the types field set to NULL).
461  llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
462  const std::string &TypeEncoding);
463 
464  /// Returns the variable used to store the offset of an instance variable.
465  llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
466  const ObjCIvarDecl *Ivar);
467  /// Emits a reference to a class. This allows the linker to object if there
468  /// is no class of the matching name.
469 
470 protected:
471  void EmitClassRef(const std::string &className);
472 
473  /// Emits a pointer to the named class
474  virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
475  const std::string &Name, bool isWeak);
476 
477  /// Looks up the method for sending a message to the specified object. This
478  /// mechanism differs between the GCC and GNU runtimes, so this method must be
479  /// overridden in subclasses.
480  virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
481  llvm::Value *&Receiver,
482  llvm::Value *cmd,
483  llvm::MDNode *node,
484  MessageSendInfo &MSI) = 0;
485 
486  /// Looks up the method for sending a message to a superclass. This
487  /// mechanism differs between the GCC and GNU runtimes, so this method must
488  /// be overridden in subclasses.
489  virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
490  Address ObjCSuper,
491  llvm::Value *cmd,
492  MessageSendInfo &MSI) = 0;
493 
494  /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
495  /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
496  /// bits set to their values, LSB first, while larger ones are stored in a
497  /// structure of this / form:
498  ///
499  /// struct { int32_t length; int32_t values[length]; };
500  ///
501  /// The values in the array are stored in host-endian format, with the least
502  /// significant bit being assumed to come first in the bitfield. Therefore,
503  /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
504  /// while a bitfield / with the 63rd bit set will be 1<<64.
505  llvm::Constant *MakeBitField(ArrayRef<bool> bits);
506 
507 public:
508  CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
509  unsigned protocolClassVersion);
510 
511  ConstantAddress GenerateConstantString(const StringLiteral *) override;
512 
513  RValue
514  GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
515  QualType ResultType, Selector Sel,
516  llvm::Value *Receiver, const CallArgList &CallArgs,
517  const ObjCInterfaceDecl *Class,
518  const ObjCMethodDecl *Method) override;
519  RValue
520  GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
521  QualType ResultType, Selector Sel,
522  const ObjCInterfaceDecl *Class,
523  bool isCategoryImpl, llvm::Value *Receiver,
524  bool IsClassMessage, const CallArgList &CallArgs,
525  const ObjCMethodDecl *Method) override;
526  llvm::Value *GetClass(CodeGenFunction &CGF,
527  const ObjCInterfaceDecl *OID) override;
528  llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
529  Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
530  llvm::Value *GetSelector(CodeGenFunction &CGF,
531  const ObjCMethodDecl *Method) override;
532  llvm::Constant *GetEHType(QualType T) override;
533 
534  llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
535  const ObjCContainerDecl *CD) override;
536  void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
537  void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
538  void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
539  llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
540  const ObjCProtocolDecl *PD) override;
541  void GenerateProtocol(const ObjCProtocolDecl *PD) override;
542  llvm::Function *ModuleInitFunction() override;
543  llvm::Constant *GetPropertyGetFunction() override;
544  llvm::Constant *GetPropertySetFunction() override;
545  llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
546  bool copy) override;
547  llvm::Constant *GetSetStructFunction() override;
548  llvm::Constant *GetGetStructFunction() override;
549  llvm::Constant *GetCppAtomicObjectGetFunction() override;
550  llvm::Constant *GetCppAtomicObjectSetFunction() override;
551  llvm::Constant *EnumerationMutationFunction() override;
552 
553  void EmitTryStmt(CodeGenFunction &CGF,
554  const ObjCAtTryStmt &S) override;
555  void EmitSynchronizedStmt(CodeGenFunction &CGF,
556  const ObjCAtSynchronizedStmt &S) override;
557  void EmitThrowStmt(CodeGenFunction &CGF,
558  const ObjCAtThrowStmt &S,
559  bool ClearInsertionPoint=true) override;
560  llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
561  Address AddrWeakObj) override;
562  void EmitObjCWeakAssign(CodeGenFunction &CGF,
563  llvm::Value *src, Address dst) override;
564  void EmitObjCGlobalAssign(CodeGenFunction &CGF,
565  llvm::Value *src, Address dest,
566  bool threadlocal=false) override;
567  void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
568  Address dest, llvm::Value *ivarOffset) override;
569  void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
570  llvm::Value *src, Address dest) override;
571  void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
572  Address SrcPtr,
573  llvm::Value *Size) override;
574  LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
575  llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
576  unsigned CVRQualifiers) override;
577  llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
578  const ObjCInterfaceDecl *Interface,
579  const ObjCIvarDecl *Ivar) override;
580  llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
581  llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
582  const CGBlockInfo &blockInfo) override {
583  return NULLPtr;
584  }
585  llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
586  const CGBlockInfo &blockInfo) override {
587  return NULLPtr;
588  }
589 
590  llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
591  return NULLPtr;
592  }
593 
594  llvm::GlobalVariable *GetClassGlobal(StringRef Name,
595  bool Weak = false) override {
596  return nullptr;
597  }
598 };
599 
600 /// Class representing the legacy GCC Objective-C ABI. This is the default when
601 /// -fobjc-nonfragile-abi is not specified.
602 ///
603 /// The GCC ABI target actually generates code that is approximately compatible
604 /// with the new GNUstep runtime ABI, but refrains from using any features that
605 /// would not work with the GCC runtime. For example, clang always generates
606 /// the extended form of the class structure, and the extra fields are simply
607 /// ignored by GCC libobjc.
608 class CGObjCGCC : public CGObjCGNU {
609  /// The GCC ABI message lookup function. Returns an IMP pointing to the
610  /// method implementation for this message.
611  LazyRuntimeFunction MsgLookupFn;
612  /// The GCC ABI superclass message lookup function. Takes a pointer to a
613  /// structure describing the receiver and the class, and a selector as
614  /// arguments. Returns the IMP for the corresponding method.
615  LazyRuntimeFunction MsgLookupSuperFn;
616 
617 protected:
618  llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
619  llvm::Value *cmd, llvm::MDNode *node,
620  MessageSendInfo &MSI) override {
621  CGBuilderTy &Builder = CGF.Builder;
622  llvm::Value *args[] = {
623  EnforceType(Builder, Receiver, IdTy),
624  EnforceType(Builder, cmd, SelectorTy) };
625  llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
626  imp->setMetadata(msgSendMDKind, node);
627  return imp.getInstruction();
628  }
629 
630  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
631  llvm::Value *cmd, MessageSendInfo &MSI) override {
632  CGBuilderTy &Builder = CGF.Builder;
633  llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
634  PtrToObjCSuperTy).getPointer(), cmd};
635  return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
636  }
637 
638 public:
639  CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
640  // IMP objc_msg_lookup(id, SEL);
641  MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy,
642  nullptr);
643  // IMP objc_msg_lookup_super(struct objc_super*, SEL);
644  MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
645  PtrToObjCSuperTy, SelectorTy, nullptr);
646  }
647 };
648 
649 /// Class used when targeting the new GNUstep runtime ABI.
650 class CGObjCGNUstep : public CGObjCGNU {
651  /// The slot lookup function. Returns a pointer to a cacheable structure
652  /// that contains (among other things) the IMP.
653  LazyRuntimeFunction SlotLookupFn;
654  /// The GNUstep ABI superclass message lookup function. Takes a pointer to
655  /// a structure describing the receiver and the class, and a selector as
656  /// arguments. Returns the slot for the corresponding method. Superclass
657  /// message lookup rarely changes, so this is a good caching opportunity.
658  LazyRuntimeFunction SlotLookupSuperFn;
659  /// Specialised function for setting atomic retain properties
660  LazyRuntimeFunction SetPropertyAtomic;
661  /// Specialised function for setting atomic copy properties
662  LazyRuntimeFunction SetPropertyAtomicCopy;
663  /// Specialised function for setting nonatomic retain properties
664  LazyRuntimeFunction SetPropertyNonAtomic;
665  /// Specialised function for setting nonatomic copy properties
666  LazyRuntimeFunction SetPropertyNonAtomicCopy;
667  /// Function to perform atomic copies of C++ objects with nontrivial copy
668  /// constructors from Objective-C ivars.
669  LazyRuntimeFunction CxxAtomicObjectGetFn;
670  /// Function to perform atomic copies of C++ objects with nontrivial copy
671  /// constructors to Objective-C ivars.
672  LazyRuntimeFunction CxxAtomicObjectSetFn;
673  /// Type of an slot structure pointer. This is returned by the various
674  /// lookup functions.
675  llvm::Type *SlotTy;
676 
677  public:
678  llvm::Constant *GetEHType(QualType T) override;
679 
680  protected:
681  llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
682  llvm::Value *cmd, llvm::MDNode *node,
683  MessageSendInfo &MSI) override {
684  CGBuilderTy &Builder = CGF.Builder;
685  llvm::Function *LookupFn = SlotLookupFn;
686 
687  // Store the receiver on the stack so that we can reload it later
688  Address ReceiverPtr =
689  CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
690  Builder.CreateStore(Receiver, ReceiverPtr);
691 
692  llvm::Value *self;
693 
694  if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
695  self = CGF.LoadObjCSelf();
696  } else {
697  self = llvm::ConstantPointerNull::get(IdTy);
698  }
699 
700  // The lookup function is guaranteed not to capture the receiver pointer.
701  LookupFn->setDoesNotCapture(1);
702 
703  llvm::Value *args[] = {
704  EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
705  EnforceType(Builder, cmd, SelectorTy),
706  EnforceType(Builder, self, IdTy) };
707  llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
708  slot.setOnlyReadsMemory();
709  slot->setMetadata(msgSendMDKind, node);
710 
711  // Load the imp from the slot
712  llvm::Value *imp = Builder.CreateAlignedLoad(
713  Builder.CreateStructGEP(nullptr, slot.getInstruction(), 4),
714  CGF.getPointerAlign());
715 
716  // The lookup function may have changed the receiver, so make sure we use
717  // the new one.
718  Receiver = Builder.CreateLoad(ReceiverPtr, true);
719  return imp;
720  }
721 
722  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
723  llvm::Value *cmd,
724  MessageSendInfo &MSI) override {
725  CGBuilderTy &Builder = CGF.Builder;
726  llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
727 
728  llvm::CallInst *slot =
729  CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
730  slot->setOnlyReadsMemory();
731 
732  return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
733  CGF.getPointerAlign());
734  }
735 
736  public:
737  CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
738  const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
739 
740  llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
741  PtrTy, PtrTy, IntTy, IMPTy, nullptr);
742  SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
743  // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
744  SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
745  SelectorTy, IdTy, nullptr);
746  // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
747  SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
748  PtrToObjCSuperTy, SelectorTy, nullptr);
749  // If we're in ObjC++ mode, then we want to make
750  if (CGM.getLangOpts().CPlusPlus) {
751  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
752  // void *__cxa_begin_catch(void *e)
753  EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, nullptr);
754  // void __cxa_end_catch(void)
755  ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, nullptr);
756  // void _Unwind_Resume_or_Rethrow(void*)
757  ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
758  PtrTy, nullptr);
759  } else if (R.getVersion() >= VersionTuple(1, 7)) {
760  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
761  // id objc_begin_catch(void *e)
762  EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, nullptr);
763  // void objc_end_catch(void)
764  ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, nullptr);
765  // void _Unwind_Resume_or_Rethrow(void*)
766  ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
767  PtrTy, nullptr);
768  }
769  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
770  SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
771  SelectorTy, IdTy, PtrDiffTy, nullptr);
772  SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
773  IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
774  SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
775  IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
776  SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
777  VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, nullptr);
778  // void objc_setCppObjectAtomic(void *dest, const void *src, void
779  // *helper);
780  CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
781  PtrTy, PtrTy, nullptr);
782  // void objc_getCppObjectAtomic(void *dest, const void *src, void
783  // *helper);
784  CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
785  PtrTy, PtrTy, nullptr);
786  }
787 
788  llvm::Constant *GetCppAtomicObjectGetFunction() override {
789  // The optimised functions were added in version 1.7 of the GNUstep
790  // runtime.
791  assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
792  VersionTuple(1, 7));
793  return CxxAtomicObjectGetFn;
794  }
795 
796  llvm::Constant *GetCppAtomicObjectSetFunction() override {
797  // The optimised functions were added in version 1.7 of the GNUstep
798  // runtime.
799  assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
800  VersionTuple(1, 7));
801  return CxxAtomicObjectSetFn;
802  }
803 
804  llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
805  bool copy) override {
806  // The optimised property functions omit the GC check, and so are not
807  // safe to use in GC mode. The standard functions are fast in GC mode,
808  // so there is less advantage in using them.
809  assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
810  // The optimised functions were added in version 1.7 of the GNUstep
811  // runtime.
812  assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
813  VersionTuple(1, 7));
814 
815  if (atomic) {
816  if (copy) return SetPropertyAtomicCopy;
817  return SetPropertyAtomic;
818  }
819 
820  return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
821  }
822 };
823 
824 /// Support for the ObjFW runtime.
825 class CGObjCObjFW: public CGObjCGNU {
826 protected:
827  /// The GCC ABI message lookup function. Returns an IMP pointing to the
828  /// method implementation for this message.
829  LazyRuntimeFunction MsgLookupFn;
830  /// stret lookup function. While this does not seem to make sense at the
831  /// first look, this is required to call the correct forwarding function.
832  LazyRuntimeFunction MsgLookupFnSRet;
833  /// The GCC ABI superclass message lookup function. Takes a pointer to a
834  /// structure describing the receiver and the class, and a selector as
835  /// arguments. Returns the IMP for the corresponding method.
836  LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
837 
838  llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
839  llvm::Value *cmd, llvm::MDNode *node,
840  MessageSendInfo &MSI) override {
841  CGBuilderTy &Builder = CGF.Builder;
842  llvm::Value *args[] = {
843  EnforceType(Builder, Receiver, IdTy),
844  EnforceType(Builder, cmd, SelectorTy) };
845 
846  llvm::CallSite imp;
847  if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
848  imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
849  else
850  imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
851 
852  imp->setMetadata(msgSendMDKind, node);
853  return imp.getInstruction();
854  }
855 
856  llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
857  llvm::Value *cmd, MessageSendInfo &MSI) override {
858  CGBuilderTy &Builder = CGF.Builder;
859  llvm::Value *lookupArgs[] = {
860  EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
861  };
862 
863  if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
864  return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
865  else
866  return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
867  }
868 
869  llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
870  bool isWeak) override {
871  if (isWeak)
872  return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
873 
874  EmitClassRef(Name);
875  std::string SymbolName = "_OBJC_CLASS_" + Name;
876  llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
877  if (!ClassSymbol)
878  ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
880  nullptr, SymbolName);
881  return ClassSymbol;
882  }
883 
884 public:
885  CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
886  // IMP objc_msg_lookup(id, SEL);
887  MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, nullptr);
888  MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
889  SelectorTy, nullptr);
890  // IMP objc_msg_lookup_super(struct objc_super*, SEL);
891  MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
892  PtrToObjCSuperTy, SelectorTy, nullptr);
893  MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
894  PtrToObjCSuperTy, SelectorTy, nullptr);
895  }
896 };
897 } // end anonymous namespace
898 
899 /// Emits a reference to a dummy variable which is emitted with each class.
900 /// This ensures that a linker error will be generated when trying to link
901 /// together modules where a referenced class is not defined.
902 void CGObjCGNU::EmitClassRef(const std::string &className) {
903  std::string symbolRef = "__objc_class_ref_" + className;
904  // Don't emit two copies of the same symbol
905  if (TheModule.getGlobalVariable(symbolRef))
906  return;
907  std::string symbolName = "__objc_class_name_" + className;
908  llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
909  if (!ClassSymbol) {
910  ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
912  nullptr, symbolName);
913  }
914  new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
915  llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
916 }
917 
918 static std::string SymbolNameForMethod( StringRef ClassName,
919  StringRef CategoryName, const Selector MethodName,
920  bool isClassMethod) {
921  std::string MethodNameColonStripped = MethodName.getAsString();
922  std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
923  ':', '_');
924  return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
925  CategoryName + "_" + MethodNameColonStripped).str();
926 }
927 
928 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
929  unsigned protocolClassVersion)
930  : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
931  VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
932  MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
933  ProtocolVersion(protocolClassVersion) {
934 
935  msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
936 
937  CodeGenTypes &Types = CGM.getTypes();
938  IntTy = cast<llvm::IntegerType>(
939  Types.ConvertType(CGM.getContext().IntTy));
940  LongTy = cast<llvm::IntegerType>(
941  Types.ConvertType(CGM.getContext().LongTy));
942  SizeTy = cast<llvm::IntegerType>(
943  Types.ConvertType(CGM.getContext().getSizeType()));
944  PtrDiffTy = cast<llvm::IntegerType>(
945  Types.ConvertType(CGM.getContext().getPointerDiffType()));
946  BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
947 
948  Int8Ty = llvm::Type::getInt8Ty(VMContext);
949  // C string type. Used in lots of places.
950  PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
951 
952  Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
953  Zeros[1] = Zeros[0];
954  NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
955  // Get the selector Type.
956  QualType selTy = CGM.getContext().getObjCSelType();
957  if (QualType() == selTy) {
958  SelectorTy = PtrToInt8Ty;
959  } else {
960  SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
961  }
962 
963  PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
964  PtrTy = PtrToInt8Ty;
965 
966  Int32Ty = llvm::Type::getInt32Ty(VMContext);
967  Int64Ty = llvm::Type::getInt64Ty(VMContext);
968 
969  IntPtrTy =
970  CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
971 
972  // Object type
973  QualType UnqualIdTy = CGM.getContext().getObjCIdType();
974  ASTIdTy = CanQualType();
975  if (UnqualIdTy != QualType()) {
976  ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
977  IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
978  } else {
979  IdTy = PtrToInt8Ty;
980  }
981  PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
982 
983  ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, nullptr);
984  PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
985 
986  llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
987 
988  // void objc_exception_throw(id);
989  ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
990  ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, nullptr);
991  // int objc_sync_enter(id);
992  SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, nullptr);
993  // int objc_sync_exit(id);
994  SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, nullptr);
995 
996  // void objc_enumerationMutation (id)
997  EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
998  IdTy, nullptr);
999 
1000  // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
1001  GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
1002  PtrDiffTy, BoolTy, nullptr);
1003  // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
1004  SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
1005  PtrDiffTy, IdTy, BoolTy, BoolTy, nullptr);
1006  // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
1007  GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
1008  PtrDiffTy, BoolTy, BoolTy, nullptr);
1009  // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
1010  SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
1011  PtrDiffTy, BoolTy, BoolTy, nullptr);
1012 
1013  // IMP type
1014  llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
1015  IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
1016  true));
1017 
1018  const LangOptions &Opts = CGM.getLangOpts();
1019  if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
1020  RuntimeVersion = 10;
1021 
1022  // Don't bother initialising the GC stuff unless we're compiling in GC mode
1023  if (Opts.getGC() != LangOptions::NonGC) {
1024  // This is a bit of an hack. We should sort this out by having a proper
1025  // CGObjCGNUstep subclass for GC, but we may want to really support the old
1026  // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
1027  // Get selectors needed in GC mode
1028  RetainSel = GetNullarySelector("retain", CGM.getContext());
1029  ReleaseSel = GetNullarySelector("release", CGM.getContext());
1030  AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
1031 
1032  // Get functions needed in GC mode
1033 
1034  // id objc_assign_ivar(id, id, ptrdiff_t);
1035  IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
1036  nullptr);
1037  // id objc_assign_strongCast (id, id*)
1038  StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
1039  PtrToIdTy, nullptr);
1040  // id objc_assign_global(id, id*);
1041  GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
1042  nullptr);
1043  // id objc_assign_weak(id, id*);
1044  WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, nullptr);
1045  // id objc_read_weak(id*);
1046  WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, nullptr);
1047  // void *objc_memmove_collectable(void*, void *, size_t);
1048  MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1049  SizeTy, nullptr);
1050  }
1051 }
1052 
1053 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
1054  const std::string &Name, bool isWeak) {
1055  llvm::Constant *ClassName = MakeConstantString(Name);
1056  // With the incompatible ABI, this will need to be replaced with a direct
1057  // reference to the class symbol. For the compatible nonfragile ABI we are
1058  // still performing this lookup at run time but emitting the symbol for the
1059  // class externally so that we can make the switch later.
1060  //
1061  // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1062  // with memoized versions or with static references if it's safe to do so.
1063  if (!isWeak)
1064  EmitClassRef(Name);
1065 
1066  llvm::Constant *ClassLookupFn =
1067  CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
1068  "objc_lookup_class");
1069  return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
1070 }
1071 
1072 // This has to perform the lookup every time, since posing and related
1073 // techniques can modify the name -> class mapping.
1074 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
1075  const ObjCInterfaceDecl *OID) {
1076  auto *Value =
1077  GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
1078  if (CGM.getTriple().isOSBinFormatCOFF()) {
1079  if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1080  auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1081  if (OID->hasAttr<DLLExportAttr>())
1082  DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1083  else if (OID->hasAttr<DLLImportAttr>())
1084  DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1085  ClassSymbol->setDLLStorageClass(DLLStorage);
1086  }
1087  }
1088  return Value;
1089 }
1090 
1091 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1092  auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
1093  if (CGM.getTriple().isOSBinFormatCOFF()) {
1094  if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
1095  IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
1096  TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1097  DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1098 
1099  const VarDecl *VD = nullptr;
1100  for (const auto &Result : DC->lookup(&II))
1101  if ((VD = dyn_cast<VarDecl>(Result)))
1102  break;
1103 
1104  auto DLLStorage = llvm::GlobalValue::DefaultStorageClass;
1105  if (!VD || VD->hasAttr<DLLImportAttr>())
1106  DLLStorage = llvm::GlobalValue::DLLImportStorageClass;
1107  else if (VD->hasAttr<DLLExportAttr>())
1108  DLLStorage = llvm::GlobalValue::DLLExportStorageClass;
1109 
1110  ClassSymbol->setDLLStorageClass(DLLStorage);
1111  }
1112  }
1113  return Value;
1114 }
1115 
1116 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1117  const std::string &TypeEncoding) {
1119  llvm::GlobalAlias *SelValue = nullptr;
1120 
1121  for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
1122  e = Types.end() ; i!=e ; i++) {
1123  if (i->first == TypeEncoding) {
1124  SelValue = i->second;
1125  break;
1126  }
1127  }
1128  if (!SelValue) {
1129  SelValue = llvm::GlobalAlias::create(
1130  SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
1131  ".objc_selector_" + Sel.getAsString(), &TheModule);
1132  Types.emplace_back(TypeEncoding, SelValue);
1133  }
1134 
1135  return SelValue;
1136 }
1137 
1138 Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
1139  llvm::Value *SelValue = GetSelector(CGF, Sel);
1140 
1141  // Store it to a temporary. Does this satisfy the semantics of
1142  // GetAddrOfSelector? Hopefully.
1143  Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
1144  CGF.getPointerAlign());
1145  CGF.Builder.CreateStore(SelValue, tmp);
1146  return tmp;
1147 }
1148 
1149 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
1150  return GetSelector(CGF, Sel, std::string());
1151 }
1152 
1153 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1154  const ObjCMethodDecl *Method) {
1155  std::string SelTypes;
1156  CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
1157  return GetSelector(CGF, Method->getSelector(), SelTypes);
1158 }
1159 
1160 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
1161  if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1162  // With the old ABI, there was only one kind of catchall, which broke
1163  // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1164  // a pointer indicating object catchalls, and NULL to indicate real
1165  // catchalls
1166  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1167  return MakeConstantString("@id");
1168  } else {
1169  return nullptr;
1170  }
1171  }
1172 
1173  // All other types should be Objective-C interface pointer types.
1175  assert(OPT && "Invalid @catch type.");
1176  const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1177  assert(IDecl && "Invalid @catch type.");
1178  return MakeConstantString(IDecl->getIdentifier()->getName());
1179 }
1180 
1181 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1182  if (!CGM.getLangOpts().CPlusPlus)
1183  return CGObjCGNU::GetEHType(T);
1184 
1185  // For Objective-C++, we want to provide the ability to catch both C++ and
1186  // Objective-C objects in the same function.
1187 
1188  // There's a particular fixed type info for 'id'.
1189  if (T->isObjCIdType() ||
1190  T->isObjCQualifiedIdType()) {
1191  llvm::Constant *IDEHType =
1192  CGM.getModule().getGlobalVariable("__objc_id_type_info");
1193  if (!IDEHType)
1194  IDEHType =
1195  new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1196  false,
1198  nullptr, "__objc_id_type_info");
1199  return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1200  }
1201 
1202  const ObjCObjectPointerType *PT =
1204  assert(PT && "Invalid @catch type.");
1205  const ObjCInterfaceType *IT = PT->getInterfaceType();
1206  assert(IT && "Invalid @catch type.");
1207  std::string className = IT->getDecl()->getIdentifier()->getName();
1208 
1209  std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1210 
1211  // Return the existing typeinfo if it exists
1212  llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
1213  if (typeinfo)
1214  return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
1215 
1216  // Otherwise create it.
1217 
1218  // vtable for gnustep::libobjc::__objc_class_type_info
1219  // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1220  // platform's name mangling.
1221  const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1222  auto *Vtable = TheModule.getGlobalVariable(vtableName);
1223  if (!Vtable) {
1224  Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1226  nullptr, vtableName);
1227  }
1228  llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
1229  auto *BVtable = llvm::ConstantExpr::getBitCast(
1230  llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
1231  PtrToInt8Ty);
1232 
1233  llvm::Constant *typeName =
1234  ExportUniqueString(className, "__objc_eh_typename_");
1235 
1236  std::vector<llvm::Constant*> fields;
1237  fields.push_back(BVtable);
1238  fields.push_back(typeName);
1239  llvm::Constant *TI =
1240  MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr),
1241  fields, CGM.getPointerAlign(),
1242  "__objc_eh_typeinfo_" + className,
1243  llvm::GlobalValue::LinkOnceODRLinkage);
1244  return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
1245 }
1246 
1247 /// Generate an NSConstantString object.
1248 ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
1249 
1250  std::string Str = SL->getString().str();
1251  CharUnits Align = CGM.getPointerAlign();
1252 
1253  // Look for an existing one
1254  llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1255  if (old != ObjCStrings.end())
1256  return ConstantAddress(old->getValue(), Align);
1257 
1258  StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1259 
1260  if (StringClass.empty()) StringClass = "NXConstantString";
1261 
1262  std::string Sym = "_OBJC_CLASS_";
1263  Sym += StringClass;
1264 
1265  llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1266 
1267  if (!isa)
1268  isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1269  llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
1270  else if (isa->getType() != PtrToIdTy)
1271  isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1272 
1273  std::vector<llvm::Constant*> Ivars;
1274  Ivars.push_back(isa);
1275  Ivars.push_back(MakeConstantString(Str));
1276  Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
1277  llvm::Constant *ObjCStr = MakeGlobal(
1278  llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, nullptr),
1279  Ivars, Align, ".objc_str");
1280  ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1281  ObjCStrings[Str] = ObjCStr;
1282  ConstantStrings.push_back(ObjCStr);
1283  return ConstantAddress(ObjCStr, Align);
1284 }
1285 
1286 ///Generates a message send where the super is the receiver. This is a message
1287 ///send to self with special delivery semantics indicating which class's method
1288 ///should be called.
1289 RValue
1290 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
1291  ReturnValueSlot Return,
1292  QualType ResultType,
1293  Selector Sel,
1294  const ObjCInterfaceDecl *Class,
1295  bool isCategoryImpl,
1296  llvm::Value *Receiver,
1297  bool IsClassMessage,
1298  const CallArgList &CallArgs,
1299  const ObjCMethodDecl *Method) {
1300  CGBuilderTy &Builder = CGF.Builder;
1301  if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1302  if (Sel == RetainSel || Sel == AutoreleaseSel) {
1303  return RValue::get(EnforceType(Builder, Receiver,
1304  CGM.getTypes().ConvertType(ResultType)));
1305  }
1306  if (Sel == ReleaseSel) {
1307  return RValue::get(nullptr);
1308  }
1309  }
1310 
1311  llvm::Value *cmd = GetSelector(CGF, Sel);
1312  CallArgList ActualArgs;
1313 
1314  ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1315  ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1316  ActualArgs.addFrom(CallArgs);
1317 
1318  MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1319 
1320  llvm::Value *ReceiverClass = nullptr;
1321  if (isCategoryImpl) {
1322  llvm::Constant *classLookupFunction = nullptr;
1323  if (IsClassMessage) {
1324  classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1325  IdTy, PtrTy, true), "objc_get_meta_class");
1326  } else {
1327  classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1328  IdTy, PtrTy, true), "objc_get_class");
1329  }
1330  ReceiverClass = Builder.CreateCall(classLookupFunction,
1331  MakeConstantString(Class->getNameAsString()));
1332  } else {
1333  // Set up global aliases for the metaclass or class pointer if they do not
1334  // already exist. These will are forward-references which will be set to
1335  // pointers to the class and metaclass structure created for the runtime
1336  // load function. To send a message to super, we look up the value of the
1337  // super_class pointer from either the class or metaclass structure.
1338  if (IsClassMessage) {
1339  if (!MetaClassPtrAlias) {
1340  MetaClassPtrAlias = llvm::GlobalAlias::create(
1341  IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1342  ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
1343  }
1344  ReceiverClass = MetaClassPtrAlias;
1345  } else {
1346  if (!ClassPtrAlias) {
1347  ClassPtrAlias = llvm::GlobalAlias::create(
1348  IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
1349  ".objc_class_ref" + Class->getNameAsString(), &TheModule);
1350  }
1351  ReceiverClass = ClassPtrAlias;
1352  }
1353  }
1354  // Cast the pointer to a simplified version of the class structure
1355  llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy, nullptr);
1356  ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1357  llvm::PointerType::getUnqual(CastTy));
1358  // Get the superclass pointer
1359  ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
1360  // Load the superclass pointer
1361  ReceiverClass =
1362  Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
1363  // Construct the structure used to look up the IMP
1364  llvm::StructType *ObjCSuperTy = llvm::StructType::get(
1365  Receiver->getType(), IdTy, nullptr);
1366 
1367  // FIXME: Is this really supposed to be a dynamic alloca?
1368  Address ObjCSuper = Address(Builder.CreateAlloca(ObjCSuperTy),
1369  CGF.getPointerAlign());
1370 
1371  Builder.CreateStore(Receiver,
1372  Builder.CreateStructGEP(ObjCSuper, 0, CharUnits::Zero()));
1373  Builder.CreateStore(ReceiverClass,
1374  Builder.CreateStructGEP(ObjCSuper, 1, CGF.getPointerSize()));
1375 
1376  ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1377 
1378  // Get the IMP
1379  llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
1380  imp = EnforceType(Builder, imp, MSI.MessengerType);
1381 
1382  llvm::Metadata *impMD[] = {
1383  llvm::MDString::get(VMContext, Sel.getAsString()),
1384  llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1385  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1386  llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
1387  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1388 
1389  llvm::Instruction *call;
1390  RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
1391  CGCalleeInfo(), &call);
1392  call->setMetadata(msgSendMDKind, node);
1393  return msgRet;
1394 }
1395 
1396 /// Generate code for a message send expression.
1397 RValue
1398 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
1399  ReturnValueSlot Return,
1400  QualType ResultType,
1401  Selector Sel,
1402  llvm::Value *Receiver,
1403  const CallArgList &CallArgs,
1404  const ObjCInterfaceDecl *Class,
1405  const ObjCMethodDecl *Method) {
1406  CGBuilderTy &Builder = CGF.Builder;
1407 
1408  // Strip out message sends to retain / release in GC mode
1409  if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1410  if (Sel == RetainSel || Sel == AutoreleaseSel) {
1411  return RValue::get(EnforceType(Builder, Receiver,
1412  CGM.getTypes().ConvertType(ResultType)));
1413  }
1414  if (Sel == ReleaseSel) {
1415  return RValue::get(nullptr);
1416  }
1417  }
1418 
1419  // If the return type is something that goes in an integer register, the
1420  // runtime will handle 0 returns. For other cases, we fill in the 0 value
1421  // ourselves.
1422  //
1423  // The language spec says the result of this kind of message send is
1424  // undefined, but lots of people seem to have forgotten to read that
1425  // paragraph and insist on sending messages to nil that have structure
1426  // returns. With GCC, this generates a random return value (whatever happens
1427  // to be on the stack / in those registers at the time) on most platforms,
1428  // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1429  // the stack.
1430  bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1431  ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
1432 
1433  llvm::BasicBlock *startBB = nullptr;
1434  llvm::BasicBlock *messageBB = nullptr;
1435  llvm::BasicBlock *continueBB = nullptr;
1436 
1437  if (!isPointerSizedReturn) {
1438  startBB = Builder.GetInsertBlock();
1439  messageBB = CGF.createBasicBlock("msgSend");
1440  continueBB = CGF.createBasicBlock("continue");
1441 
1442  llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1443  llvm::Constant::getNullValue(Receiver->getType()));
1444  Builder.CreateCondBr(isNil, continueBB, messageBB);
1445  CGF.EmitBlock(messageBB);
1446  }
1447 
1448  IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
1449  llvm::Value *cmd;
1450  if (Method)
1451  cmd = GetSelector(CGF, Method);
1452  else
1453  cmd = GetSelector(CGF, Sel);
1454  cmd = EnforceType(Builder, cmd, SelectorTy);
1455  Receiver = EnforceType(Builder, Receiver, IdTy);
1456 
1457  llvm::Metadata *impMD[] = {
1458  llvm::MDString::get(VMContext, Sel.getAsString()),
1459  llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
1460  llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
1461  llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
1462  llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1463 
1464  CallArgList ActualArgs;
1465  ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1466  ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1467  ActualArgs.addFrom(CallArgs);
1468 
1469  MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1470 
1471  // Get the IMP to call
1472  llvm::Value *imp;
1473 
1474  // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1475  // functions. These are not supported on all platforms (or all runtimes on a
1476  // given platform), so we
1477  switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1478  case CodeGenOptions::Legacy:
1479  imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
1480  break;
1481  case CodeGenOptions::Mixed:
1482  case CodeGenOptions::NonLegacy:
1483  if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1484  imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1485  "objc_msgSend_fpret");
1486  } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
1487  // The actual types here don't matter - we're going to bitcast the
1488  // function anyway
1489  imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1490  "objc_msgSend_stret");
1491  } else {
1492  imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1493  "objc_msgSend");
1494  }
1495  }
1496 
1497  // Reset the receiver in case the lookup modified it
1498  ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
1499 
1500  imp = EnforceType(Builder, imp, MSI.MessengerType);
1501 
1502  llvm::Instruction *call;
1503  RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs,
1504  CGCalleeInfo(), &call);
1505  call->setMetadata(msgSendMDKind, node);
1506 
1507 
1508  if (!isPointerSizedReturn) {
1509  messageBB = CGF.Builder.GetInsertBlock();
1510  CGF.Builder.CreateBr(continueBB);
1511  CGF.EmitBlock(continueBB);
1512  if (msgRet.isScalar()) {
1513  llvm::Value *v = msgRet.getScalarVal();
1514  llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1515  phi->addIncoming(v, messageBB);
1516  phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1517  msgRet = RValue::get(phi);
1518  } else if (msgRet.isAggregate()) {
1519  Address v = msgRet.getAggregateAddress();
1520  llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
1521  llvm::Type *RetTy = v.getElementType();
1522  Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
1523  CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
1524  phi->addIncoming(v.getPointer(), messageBB);
1525  phi->addIncoming(NullVal.getPointer(), startBB);
1526  msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
1527  } else /* isComplex() */ {
1528  std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1529  llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
1530  phi->addIncoming(v.first, messageBB);
1531  phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1532  startBB);
1533  llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
1534  phi2->addIncoming(v.second, messageBB);
1535  phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1536  startBB);
1537  msgRet = RValue::getComplex(phi, phi2);
1538  }
1539  }
1540  return msgRet;
1541 }
1542 
1543 /// Generates a MethodList. Used in construction of a objc_class and
1544 /// objc_category structures.
1545 llvm::Constant *CGObjCGNU::
1546 GenerateMethodList(StringRef ClassName,
1547  StringRef CategoryName,
1548  ArrayRef<Selector> MethodSels,
1549  ArrayRef<llvm::Constant *> MethodTypes,
1550  bool isClassMethodList) {
1551  if (MethodSels.empty())
1552  return NULLPtr;
1553  // Get the method structure type.
1554  llvm::StructType *ObjCMethodTy = llvm::StructType::get(
1555  PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1556  PtrToInt8Ty, // Method types
1557  IMPTy, //Method pointer
1558  nullptr);
1559  std::vector<llvm::Constant*> Methods;
1560  for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1561  llvm::Constant *Method =
1562  TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
1563  MethodSels[i],
1564  isClassMethodList));
1565  assert(Method && "Can't generate metadata for method that doesn't exist");
1566  llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1567  Method = llvm::ConstantExpr::getBitCast(Method,
1568  IMPTy);
1569  Methods.push_back(
1570  llvm::ConstantStruct::get(ObjCMethodTy, {C, MethodTypes[i], Method}));
1571  }
1572 
1573  // Array of method structures
1574  llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
1575  Methods.size());
1576  llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
1577  Methods);
1578 
1579  // Structure containing list pointer, array and array count
1580  llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
1581  llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1582  ObjCMethodListTy->setBody(
1583  NextPtrTy,
1584  IntTy,
1585  ObjCMethodArrayTy,
1586  nullptr);
1587 
1588  Methods.clear();
1589  Methods.push_back(llvm::ConstantPointerNull::get(
1590  llvm::PointerType::getUnqual(ObjCMethodListTy)));
1591  Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
1592  Methods.push_back(MethodArray);
1593 
1594  // Create an instance of the structure
1595  return MakeGlobal(ObjCMethodListTy, Methods, CGM.getPointerAlign(),
1596  ".objc_method_list");
1597 }
1598 
1599 /// Generates an IvarList. Used in construction of a objc_class.
1600 llvm::Constant *CGObjCGNU::
1601 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1602  ArrayRef<llvm::Constant *> IvarTypes,
1603  ArrayRef<llvm::Constant *> IvarOffsets) {
1604  if (IvarNames.size() == 0)
1605  return NULLPtr;
1606  // Get the method structure type.
1607  llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1608  PtrToInt8Ty,
1609  PtrToInt8Ty,
1610  IntTy,
1611  nullptr);
1612  std::vector<llvm::Constant*> Ivars;
1613  for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1614  Ivars.push_back(llvm::ConstantStruct::get(
1615  ObjCIvarTy, {IvarNames[i], IvarTypes[i], IvarOffsets[i]}));
1616  }
1617 
1618  // Array of method structures
1619  llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
1620  IvarNames.size());
1621 
1622  llvm::Constant *Elements[] = {
1623  llvm::ConstantInt::get(IntTy, (int)IvarNames.size()),
1624  llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars)};
1625  // Structure containing array and array count
1626  llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
1627  ObjCIvarArrayTy,
1628  nullptr);
1629 
1630  // Create an instance of the structure
1631  return MakeGlobal(ObjCIvarListTy, Elements, CGM.getPointerAlign(),
1632  ".objc_ivar_list");
1633 }
1634 
1635 /// Generate a class structure
1636 llvm::Constant *CGObjCGNU::GenerateClassStructure(
1637  llvm::Constant *MetaClass,
1638  llvm::Constant *SuperClass,
1639  unsigned info,
1640  const char *Name,
1641  llvm::Constant *Version,
1642  llvm::Constant *InstanceSize,
1643  llvm::Constant *IVars,
1644  llvm::Constant *Methods,
1645  llvm::Constant *Protocols,
1646  llvm::Constant *IvarOffsets,
1647  llvm::Constant *Properties,
1648  llvm::Constant *StrongIvarBitmap,
1649  llvm::Constant *WeakIvarBitmap,
1650  bool isMeta) {
1651  // Set up the class structure
1652  // Note: Several of these are char*s when they should be ids. This is
1653  // because the runtime performs this translation on load.
1654  //
1655  // Fields marked New ABI are part of the GNUstep runtime. We emit them
1656  // anyway; the classes will still work with the GNU runtime, they will just
1657  // be ignored.
1658  llvm::StructType *ClassTy = llvm::StructType::get(
1659  PtrToInt8Ty, // isa
1660  PtrToInt8Ty, // super_class
1661  PtrToInt8Ty, // name
1662  LongTy, // version
1663  LongTy, // info
1664  LongTy, // instance_size
1665  IVars->getType(), // ivars
1666  Methods->getType(), // methods
1667  // These are all filled in by the runtime, so we pretend
1668  PtrTy, // dtable
1669  PtrTy, // subclass_list
1670  PtrTy, // sibling_class
1671  PtrTy, // protocols
1672  PtrTy, // gc_object_type
1673  // New ABI:
1674  LongTy, // abi_version
1675  IvarOffsets->getType(), // ivar_offsets
1676  Properties->getType(), // properties
1677  IntPtrTy, // strong_pointers
1678  IntPtrTy, // weak_pointers
1679  nullptr);
1680  llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
1681  // Fill in the structure
1682  std::vector<llvm::Constant*> Elements;
1683  Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
1684  Elements.push_back(SuperClass);
1685  Elements.push_back(MakeConstantString(Name, ".class_name"));
1686  Elements.push_back(Zero);
1687  Elements.push_back(llvm::ConstantInt::get(LongTy, info));
1688  if (isMeta) {
1689  llvm::DataLayout td(&TheModule);
1690  Elements.push_back(
1691  llvm::ConstantInt::get(LongTy,
1692  td.getTypeSizeInBits(ClassTy) /
1693  CGM.getContext().getCharWidth()));
1694  } else
1695  Elements.push_back(InstanceSize);
1696  Elements.push_back(IVars);
1697  Elements.push_back(Methods);
1698  Elements.push_back(NULLPtr);
1699  Elements.push_back(NULLPtr);
1700  Elements.push_back(NULLPtr);
1701  Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
1702  Elements.push_back(NULLPtr);
1703  Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
1704  Elements.push_back(IvarOffsets);
1705  Elements.push_back(Properties);
1706  Elements.push_back(StrongIvarBitmap);
1707  Elements.push_back(WeakIvarBitmap);
1708  // Create an instance of the structure
1709  // This is now an externally visible symbol, so that we can speed up class
1710  // messages in the next ABI. We may already have some weak references to
1711  // this, so check and fix them properly.
1712  std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1713  std::string(Name));
1714  llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1715  llvm::Constant *Class =
1716  MakeGlobal(ClassTy, Elements, CGM.getPointerAlign(), ClassSym,
1718  if (ClassRef) {
1719  ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1720  ClassRef->getType()));
1721  ClassRef->removeFromParent();
1722  Class->setName(ClassSym);
1723  }
1724  return Class;
1725 }
1726 
1727 llvm::Constant *CGObjCGNU::
1728 GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1729  ArrayRef<llvm::Constant *> MethodTypes) {
1730  // Get the method structure type.
1731  llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
1732  PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1733  PtrToInt8Ty,
1734  nullptr);
1735  std::vector<llvm::Constant*> Methods;
1736  for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1737  Methods.push_back(llvm::ConstantStruct::get(
1738  ObjCMethodDescTy, {MethodNames[i], MethodTypes[i]}));
1739  }
1740  llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
1741  MethodNames.size());
1742  llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
1743  Methods);
1744  llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
1745  IntTy, ObjCMethodArrayTy, nullptr);
1746  Methods.clear();
1747  Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
1748  Methods.push_back(Array);
1749  return MakeGlobal(ObjCMethodDescListTy, Methods, CGM.getPointerAlign(),
1750  ".objc_method_list");
1751 }
1752 
1753 // Create the protocol list structure used in classes, categories and so on
1754 llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
1755  llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
1756  Protocols.size());
1757  llvm::StructType *ProtocolListTy = llvm::StructType::get(
1758  PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1759  SizeTy,
1760  ProtocolArrayTy,
1761  nullptr);
1762  std::vector<llvm::Constant*> Elements;
1763  for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1764  iter != endIter ; iter++) {
1765  llvm::Constant *protocol = nullptr;
1767  ExistingProtocols.find(*iter);
1768  if (value == ExistingProtocols.end()) {
1769  protocol = GenerateEmptyProtocol(*iter);
1770  } else {
1771  protocol = value->getValue();
1772  }
1773  llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
1774  PtrToInt8Ty);
1775  Elements.push_back(Ptr);
1776  }
1777  llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1778  Elements);
1779  Elements.clear();
1780  Elements.push_back(NULLPtr);
1781  Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
1782  Elements.push_back(ProtocolArray);
1783  return MakeGlobal(ProtocolListTy, Elements, CGM.getPointerAlign(),
1784  ".objc_protocol_list");
1785 }
1786 
1787 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
1788  const ObjCProtocolDecl *PD) {
1789  llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1790  llvm::Type *T =
1791  CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1792  return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1793 }
1794 
1795 llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1796  const std::string &ProtocolName) {
1797  SmallVector<std::string, 0> EmptyStringVector;
1798  SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1799 
1800  llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
1801  llvm::Constant *MethodList =
1802  GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1803  // Protocols are objects containing lists of the methods implemented and
1804  // protocols adopted.
1805  llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1806  PtrToInt8Ty,
1807  ProtocolList->getType(),
1808  MethodList->getType(),
1809  MethodList->getType(),
1810  MethodList->getType(),
1811  MethodList->getType(),
1812  nullptr);
1813  // The isa pointer must be set to a magic number so the runtime knows it's
1814  // the correct layout.
1815  llvm::Constant *Elements[] = {
1816  llvm::ConstantExpr::getIntToPtr(
1817  llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy),
1818  MakeConstantString(ProtocolName, ".objc_protocol_name"), ProtocolList,
1819  MethodList, MethodList, MethodList, MethodList};
1820  return MakeGlobal(ProtocolTy, Elements, CGM.getPointerAlign(),
1821  ".objc_protocol");
1822 }
1823 
1824 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1825  ASTContext &Context = CGM.getContext();
1826  std::string ProtocolName = PD->getNameAsString();
1827 
1828  // Use the protocol definition, if there is one.
1829  if (const ObjCProtocolDecl *Def = PD->getDefinition())
1830  PD = Def;
1831 
1832  SmallVector<std::string, 16> Protocols;
1833  for (const auto *PI : PD->protocols())
1834  Protocols.push_back(PI->getNameAsString());
1835  SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1836  SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1837  SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1838  SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1839  for (const auto *I : PD->instance_methods()) {
1840  std::string TypeStr;
1841  Context.getObjCEncodingForMethodDecl(I, TypeStr);
1842  if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1843  OptionalInstanceMethodNames.push_back(
1844  MakeConstantString(I->getSelector().getAsString()));
1845  OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1846  } else {
1847  InstanceMethodNames.push_back(
1848  MakeConstantString(I->getSelector().getAsString()));
1849  InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1850  }
1851  }
1852  // Collect information about class methods:
1853  SmallVector<llvm::Constant*, 16> ClassMethodNames;
1854  SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1855  SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1856  SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1857  for (const auto *I : PD->class_methods()) {
1858  std::string TypeStr;
1859  Context.getObjCEncodingForMethodDecl(I,TypeStr);
1860  if (I->getImplementationControl() == ObjCMethodDecl::Optional) {
1861  OptionalClassMethodNames.push_back(
1862  MakeConstantString(I->getSelector().getAsString()));
1863  OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1864  } else {
1865  ClassMethodNames.push_back(
1866  MakeConstantString(I->getSelector().getAsString()));
1867  ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1868  }
1869  }
1870 
1871  llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1872  llvm::Constant *InstanceMethodList =
1873  GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1874  llvm::Constant *ClassMethodList =
1875  GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1876  llvm::Constant *OptionalInstanceMethodList =
1877  GenerateProtocolMethodList(OptionalInstanceMethodNames,
1878  OptionalInstanceMethodTypes);
1879  llvm::Constant *OptionalClassMethodList =
1880  GenerateProtocolMethodList(OptionalClassMethodNames,
1881  OptionalClassMethodTypes);
1882 
1883  // Property metadata: name, attributes, isSynthesized, setter name, setter
1884  // types, getter name, getter types.
1885  // The isSynthesized value is always set to 0 in a protocol. It exists to
1886  // simplify the runtime library by allowing it to use the same data
1887  // structures for protocol metadata everywhere.
1888  llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
1889  PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1890  PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
1891  std::vector<llvm::Constant*> Properties;
1892  std::vector<llvm::Constant*> OptionalProperties;
1893 
1894  // Add all of the property methods need adding to the method list and to the
1895  // property metadata list.
1896  for (auto *property : PD->instance_properties()) {
1897  std::vector<llvm::Constant*> Fields;
1898 
1899  Fields.push_back(MakePropertyEncodingString(property, nullptr));
1900  PushPropertyAttributes(Fields, property);
1901 
1902  if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1903  std::string TypeStr;
1904  Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1905  llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1906  InstanceMethodTypes.push_back(TypeEncoding);
1907  Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1908  Fields.push_back(TypeEncoding);
1909  } else {
1910  Fields.push_back(NULLPtr);
1911  Fields.push_back(NULLPtr);
1912  }
1913  if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1914  std::string TypeStr;
1915  Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1916  llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1917  InstanceMethodTypes.push_back(TypeEncoding);
1918  Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1919  Fields.push_back(TypeEncoding);
1920  } else {
1921  Fields.push_back(NULLPtr);
1922  Fields.push_back(NULLPtr);
1923  }
1924  if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1925  OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1926  } else {
1927  Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1928  }
1929  }
1930  llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1931  llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1932  llvm::Constant* PropertyListInitFields[] =
1933  {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1934 
1935  llvm::Constant *PropertyListInit =
1936  llvm::ConstantStruct::getAnon(PropertyListInitFields);
1937  llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1938  PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1939  PropertyListInit, ".objc_property_list");
1940 
1941  llvm::Constant *OptionalPropertyArray =
1942  llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1943  OptionalProperties.size()) , OptionalProperties);
1944  llvm::Constant* OptionalPropertyListInitFields[] = {
1945  llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1946  OptionalPropertyArray };
1947 
1948  llvm::Constant *OptionalPropertyListInit =
1949  llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
1950  llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1951  OptionalPropertyListInit->getType(), false,
1952  llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1953  ".objc_property_list");
1954 
1955  // Protocols are objects containing lists of the methods implemented and
1956  // protocols adopted.
1957  llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1958  PtrToInt8Ty,
1959  ProtocolList->getType(),
1960  InstanceMethodList->getType(),
1961  ClassMethodList->getType(),
1962  OptionalInstanceMethodList->getType(),
1963  OptionalClassMethodList->getType(),
1964  PropertyList->getType(),
1965  OptionalPropertyList->getType(),
1966  nullptr);
1967  // The isa pointer must be set to a magic number so the runtime knows it's
1968  // the correct layout.
1969  llvm::Constant *Elements[] = {
1970  llvm::ConstantExpr::getIntToPtr(
1971  llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy),
1972  MakeConstantString(ProtocolName, ".objc_protocol_name"), ProtocolList,
1973  InstanceMethodList, ClassMethodList, OptionalInstanceMethodList,
1974  OptionalClassMethodList, PropertyList, OptionalPropertyList};
1975  ExistingProtocols[ProtocolName] =
1976  llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
1977  CGM.getPointerAlign(), ".objc_protocol"), IdTy);
1978 }
1979 void CGObjCGNU::GenerateProtocolHolderCategory() {
1980  // Collect information about instance methods
1981  SmallVector<Selector, 1> MethodSels;
1982  SmallVector<llvm::Constant*, 1> MethodTypes;
1983 
1984  std::vector<llvm::Constant*> Elements;
1985  const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1986  const std::string CategoryName = "AnotherHack";
1987  Elements.push_back(MakeConstantString(CategoryName));
1988  Elements.push_back(MakeConstantString(ClassName));
1989  // Instance method list
1990  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1991  ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1992  // Class method list
1993  Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1994  ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1995  // Protocol list
1996  llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1997  ExistingProtocols.size());
1998  llvm::StructType *ProtocolListTy = llvm::StructType::get(
1999  PtrTy, //Should be a recurisve pointer, but it's always NULL here.
2000  SizeTy,
2001  ProtocolArrayTy,
2002  nullptr);
2003  std::vector<llvm::Constant*> ProtocolElements;
2004  for (llvm::StringMapIterator<llvm::Constant*> iter =
2005  ExistingProtocols.begin(), endIter = ExistingProtocols.end();
2006  iter != endIter ; iter++) {
2007  llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
2008  PtrTy);
2009  ProtocolElements.push_back(Ptr);
2010  }
2011  llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
2012  ProtocolElements);
2013  ProtocolElements.clear();
2014  ProtocolElements.push_back(NULLPtr);
2015  ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
2016  ExistingProtocols.size()));
2017  ProtocolElements.push_back(ProtocolArray);
2018  Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
2019  ProtocolElements, CGM.getPointerAlign(),
2020  ".objc_protocol_list"), PtrTy));
2021  Categories.push_back(llvm::ConstantExpr::getBitCast(
2022  MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
2023  PtrTy, PtrTy, PtrTy, nullptr), Elements, CGM.getPointerAlign()),
2024  PtrTy));
2025 }
2026 
2027 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
2028 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
2029 /// bits set to their values, LSB first, while larger ones are stored in a
2030 /// structure of this / form:
2031 ///
2032 /// struct { int32_t length; int32_t values[length]; };
2033 ///
2034 /// The values in the array are stored in host-endian format, with the least
2035 /// significant bit being assumed to come first in the bitfield. Therefore, a
2036 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
2037 /// bitfield / with the 63rd bit set will be 1<<64.
2038 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
2039  int bitCount = bits.size();
2040  int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
2041  if (bitCount < ptrBits) {
2042  uint64_t val = 1;
2043  for (int i=0 ; i<bitCount ; ++i) {
2044  if (bits[i]) val |= 1ULL<<(i+1);
2045  }
2046  return llvm::ConstantInt::get(IntPtrTy, val);
2047  }
2049  int v=0;
2050  while (v < bitCount) {
2051  int32_t word = 0;
2052  for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
2053  if (bits[v]) word |= 1<<i;
2054  v++;
2055  }
2056  values.push_back(llvm::ConstantInt::get(Int32Ty, word));
2057  }
2058  llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
2059  llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
2060  llvm::Constant *fields[2] = {
2061  llvm::ConstantInt::get(Int32Ty, values.size()),
2062  array };
2063  llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
2064  nullptr), fields, CharUnits::fromQuantity(4));
2065  llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
2066  return ptr;
2067 }
2068 
2069 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
2070  std::string ClassName = OCD->getClassInterface()->getNameAsString();
2071  std::string CategoryName = OCD->getNameAsString();
2072  // Collect information about instance methods
2073  SmallVector<Selector, 16> InstanceMethodSels;
2074  SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2075  for (const auto *I : OCD->instance_methods()) {
2076  InstanceMethodSels.push_back(I->getSelector());
2077  std::string TypeStr;
2078  CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
2079  InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2080  }
2081 
2082  // Collect information about class methods
2083  SmallVector<Selector, 16> ClassMethodSels;
2084  SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2085  for (const auto *I : OCD->class_methods()) {
2086  ClassMethodSels.push_back(I->getSelector());
2087  std::string TypeStr;
2088  CGM.getContext().getObjCEncodingForMethodDecl(I,TypeStr);
2089  ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2090  }
2091 
2092  // Collect the names of referenced protocols
2093  SmallVector<std::string, 16> Protocols;
2094  const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2095  const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
2097  E = Protos.end(); I != E; ++I)
2098  Protocols.push_back((*I)->getNameAsString());
2099 
2100  llvm::Constant *Elements[] = {
2101  MakeConstantString(CategoryName), MakeConstantString(ClassName),
2102  // Instance method list
2103  llvm::ConstantExpr::getBitCast(
2104  GenerateMethodList(ClassName, CategoryName, InstanceMethodSels,
2105  InstanceMethodTypes, false),
2106  PtrTy),
2107  // Class method list
2108  llvm::ConstantExpr::getBitCast(GenerateMethodList(ClassName, CategoryName,
2109  ClassMethodSels,
2110  ClassMethodTypes, true),
2111  PtrTy),
2112  // Protocol list
2113  llvm::ConstantExpr::getBitCast(GenerateProtocolList(Protocols), PtrTy)};
2114  Categories.push_back(llvm::ConstantExpr::getBitCast(
2115  MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
2116  PtrTy, PtrTy, PtrTy, nullptr), Elements, CGM.getPointerAlign()),
2117  PtrTy));
2118 }
2119 
2120 llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
2121  SmallVectorImpl<Selector> &InstanceMethodSels,
2122  SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
2123  ASTContext &Context = CGM.getContext();
2124  // Property metadata: name, attributes, attributes2, padding1, padding2,
2125  // setter name, setter types, getter name, getter types.
2126  llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
2127  PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2128  PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, nullptr);
2129  std::vector<llvm::Constant*> Properties;
2130 
2131  // Add all of the property methods need adding to the method list and to the
2132  // property metadata list.
2133  for (auto *propertyImpl : OID->property_impls()) {
2134  std::vector<llvm::Constant*> Fields;
2135  ObjCPropertyDecl *property = propertyImpl->getPropertyDecl();
2136  bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2137  ObjCPropertyImplDecl::Synthesize);
2138  bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2139  ObjCPropertyImplDecl::Dynamic);
2140 
2141  Fields.push_back(MakePropertyEncodingString(property, OID));
2142  PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
2143  if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
2144  std::string TypeStr;
2145  Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2146  llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2147  if (isSynthesized) {
2148  InstanceMethodTypes.push_back(TypeEncoding);
2149  InstanceMethodSels.push_back(getter->getSelector());
2150  }
2151  Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2152  Fields.push_back(TypeEncoding);
2153  } else {
2154  Fields.push_back(NULLPtr);
2155  Fields.push_back(NULLPtr);
2156  }
2157  if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
2158  std::string TypeStr;
2159  Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2160  llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2161  if (isSynthesized) {
2162  InstanceMethodTypes.push_back(TypeEncoding);
2163  InstanceMethodSels.push_back(setter->getSelector());
2164  }
2165  Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2166  Fields.push_back(TypeEncoding);
2167  } else {
2168  Fields.push_back(NULLPtr);
2169  Fields.push_back(NULLPtr);
2170  }
2171  Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2172  }
2173  llvm::ArrayType *PropertyArrayTy =
2174  llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2175  llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2176  Properties);
2177  llvm::Constant* PropertyListInitFields[] =
2178  {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2179 
2180  llvm::Constant *PropertyListInit =
2181  llvm::ConstantStruct::getAnon(PropertyListInitFields);
2182  return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2183  llvm::GlobalValue::InternalLinkage, PropertyListInit,
2184  ".objc_property_list");
2185 }
2186 
2187 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2188  // Get the class declaration for which the alias is specified.
2189  ObjCInterfaceDecl *ClassDecl =
2190  const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2191  ClassAliases.emplace_back(ClassDecl->getNameAsString(),
2192  OAD->getNameAsString());
2193 }
2194 
2195 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2196  ASTContext &Context = CGM.getContext();
2197 
2198  // Get the superclass name.
2199  const ObjCInterfaceDecl * SuperClassDecl =
2200  OID->getClassInterface()->getSuperClass();
2201  std::string SuperClassName;
2202  if (SuperClassDecl) {
2203  SuperClassName = SuperClassDecl->getNameAsString();
2204  EmitClassRef(SuperClassName);
2205  }
2206 
2207  // Get the class name
2208  ObjCInterfaceDecl *ClassDecl =
2209  const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
2210  std::string ClassName = ClassDecl->getNameAsString();
2211 
2212  // Emit the symbol that is used to generate linker errors if this class is
2213  // referenced in other modules but not declared.
2214  std::string classSymbolName = "__objc_class_name_" + ClassName;
2215  if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
2216  symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
2217  } else {
2218  new llvm::GlobalVariable(TheModule, LongTy, false,
2220  llvm::ConstantInt::get(LongTy, 0),
2221  classSymbolName);
2222  }
2223 
2224  // Get the size of instances.
2225  int instanceSize =
2227 
2228  // Collect information about instance variables.
2232 
2233  std::vector<llvm::Constant*> IvarOffsetValues;
2234  SmallVector<bool, 16> WeakIvars;
2235  SmallVector<bool, 16> StrongIvars;
2236 
2237  int superInstanceSize = !SuperClassDecl ? 0 :
2238  Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
2239  // For non-fragile ivars, set the instance size to 0 - {the size of just this
2240  // class}. The runtime will then set this to the correct value on load.
2241  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2242  instanceSize = 0 - (instanceSize - superInstanceSize);
2243  }
2244 
2245  for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2246  IVD = IVD->getNextIvar()) {
2247  // Store the name
2248  IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
2249  // Get the type encoding for this ivar
2250  std::string TypeStr;
2251  Context.getObjCEncodingForType(IVD->getType(), TypeStr);
2252  IvarTypes.push_back(MakeConstantString(TypeStr));
2253  // Get the offset
2254  uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
2255  uint64_t Offset = BaseOffset;
2256  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2257  Offset = BaseOffset - superInstanceSize;
2258  }
2259  llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2260  // Create the direct offset value
2261  std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2262  IVD->getNameAsString();
2263  llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2264  if (OffsetVar) {
2265  OffsetVar->setInitializer(OffsetValue);
2266  // If this is the real definition, change its linkage type so that
2267  // different modules will use this one, rather than their private
2268  // copy.
2269  OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2270  } else
2271  OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
2273  OffsetValue,
2274  "__objc_ivar_offset_value_" + ClassName +"." +
2275  IVD->getNameAsString());
2276  IvarOffsets.push_back(OffsetValue);
2277  IvarOffsetValues.push_back(OffsetVar);
2278  Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2279  switch (lt) {
2280  case Qualifiers::OCL_Strong:
2281  StrongIvars.push_back(true);
2282  WeakIvars.push_back(false);
2283  break;
2284  case Qualifiers::OCL_Weak:
2285  StrongIvars.push_back(false);
2286  WeakIvars.push_back(true);
2287  break;
2288  default:
2289  StrongIvars.push_back(false);
2290  WeakIvars.push_back(false);
2291  }
2292  }
2293  llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2294  llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
2295  llvm::GlobalVariable *IvarOffsetArray =
2296  MakeGlobalArray(PtrToIntTy, IvarOffsetValues, CGM.getPointerAlign(),
2297  ".ivar.offsets");
2298 
2299  // Collect information about instance methods
2300  SmallVector<Selector, 16> InstanceMethodSels;
2301  SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2302  for (const auto *I : OID->instance_methods()) {
2303  InstanceMethodSels.push_back(I->getSelector());
2304  std::string TypeStr;
2305  Context.getObjCEncodingForMethodDecl(I,TypeStr);
2306  InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2307  }
2308 
2309  llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2310  InstanceMethodTypes);
2311 
2312  // Collect information about class methods
2313  SmallVector<Selector, 16> ClassMethodSels;
2314  SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2315  for (const auto *I : OID->class_methods()) {
2316  ClassMethodSels.push_back(I->getSelector());
2317  std::string TypeStr;
2318  Context.getObjCEncodingForMethodDecl(I,TypeStr);
2319  ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2320  }
2321  // Collect the names of referenced protocols
2322  SmallVector<std::string, 16> Protocols;
2323  for (const auto *I : ClassDecl->protocols())
2324  Protocols.push_back(I->getNameAsString());
2325 
2326  // Get the superclass pointer.
2327  llvm::Constant *SuperClass;
2328  if (!SuperClassName.empty()) {
2329  SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2330  } else {
2331  SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2332  }
2333  // Empty vector used to construct empty method lists
2335  // Generate the method and instance variable lists
2336  llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
2337  InstanceMethodSels, InstanceMethodTypes, false);
2338  llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
2339  ClassMethodSels, ClassMethodTypes, true);
2340  llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2341  IvarOffsets);
2342  // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
2343  // we emit a symbol containing the offset for each ivar in the class. This
2344  // allows code compiled for the non-Fragile ABI to inherit from code compiled
2345  // for the legacy ABI, without causing problems. The converse is also
2346  // possible, but causes all ivar accesses to be fragile.
2347 
2348  // Offset pointer for getting at the correct field in the ivar list when
2349  // setting up the alias. These are: The base address for the global, the
2350  // ivar array (second field), the ivar in this list (set for each ivar), and
2351  // the offset (third field in ivar structure)
2352  llvm::Type *IndexTy = Int32Ty;
2353  llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
2354  llvm::ConstantInt::get(IndexTy, 1), nullptr,
2355  llvm::ConstantInt::get(IndexTy, 2) };
2356 
2357  unsigned ivarIndex = 0;
2358  for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2359  IVD = IVD->getNextIvar()) {
2360  const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
2361  + IVD->getNameAsString();
2362  offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
2363  // Get the correct ivar field
2364  llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
2365  cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
2366  offsetPointerIndexes);
2367  // Get the existing variable, if one exists.
2368  llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2369  if (offset) {
2370  offset->setInitializer(offsetValue);
2371  // If this is the real definition, change its linkage type so that
2372  // different modules will use this one, rather than their private
2373  // copy.
2374  offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2375  } else {
2376  // Add a new alias if there isn't one already.
2377  offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2378  false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2379  (void) offset; // Silence dead store warning.
2380  }
2381  ++ivarIndex;
2382  }
2383  llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
2384 
2385  //Generate metaclass for class methods
2386  llvm::Constant *MetaClassStruct = GenerateClassStructure(
2387  NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
2388  GenerateIvarList(empty, empty, empty), ClassMethodList, NULLPtr, NULLPtr,
2389  NULLPtr, ZeroPtr, ZeroPtr, true);
2390  if (CGM.getTriple().isOSBinFormatCOFF()) {
2391  auto Storage = llvm::GlobalValue::DefaultStorageClass;
2392  if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2393  Storage = llvm::GlobalValue::DLLImportStorageClass;
2394  else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2395  Storage = llvm::GlobalValue::DLLExportStorageClass;
2396  cast<llvm::GlobalValue>(MetaClassStruct)->setDLLStorageClass(Storage);
2397  }
2398 
2399  // Generate the class structure
2400  llvm::Constant *ClassStruct = GenerateClassStructure(
2401  MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
2402  llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
2403  GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
2404  StrongIvarBitmap, WeakIvarBitmap);
2405  if (CGM.getTriple().isOSBinFormatCOFF()) {
2406  auto Storage = llvm::GlobalValue::DefaultStorageClass;
2407  if (OID->getClassInterface()->hasAttr<DLLImportAttr>())
2408  Storage = llvm::GlobalValue::DLLImportStorageClass;
2409  else if (OID->getClassInterface()->hasAttr<DLLExportAttr>())
2410  Storage = llvm::GlobalValue::DLLExportStorageClass;
2411  cast<llvm::GlobalValue>(ClassStruct)->setDLLStorageClass(Storage);
2412  }
2413 
2414  // Resolve the class aliases, if they exist.
2415  if (ClassPtrAlias) {
2416  ClassPtrAlias->replaceAllUsesWith(
2417  llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
2418  ClassPtrAlias->eraseFromParent();
2419  ClassPtrAlias = nullptr;
2420  }
2421  if (MetaClassPtrAlias) {
2422  MetaClassPtrAlias->replaceAllUsesWith(
2423  llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
2424  MetaClassPtrAlias->eraseFromParent();
2425  MetaClassPtrAlias = nullptr;
2426  }
2427 
2428  // Add class structure to list to be added to the symtab later
2429  ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
2430  Classes.push_back(ClassStruct);
2431 }
2432 
2433 llvm::Function *CGObjCGNU::ModuleInitFunction() {
2434  // Only emit an ObjC load function if no Objective-C stuff has been called
2435  if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
2436  ExistingProtocols.empty() && SelectorTable.empty())
2437  return nullptr;
2438 
2439  // Add all referenced protocols to a category.
2440  GenerateProtocolHolderCategory();
2441 
2442  llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2443  SelectorTy->getElementType());
2444  llvm::Type *SelStructPtrTy = SelectorTy;
2445  if (!SelStructTy) {
2446  SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, nullptr);
2447  SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
2448  }
2449 
2450  std::vector<llvm::Constant*> Elements;
2451  llvm::Constant *Statics = NULLPtr;
2452  // Generate statics list:
2453  if (!ConstantStrings.empty()) {
2454  llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
2455  ConstantStrings.size() + 1);
2456  ConstantStrings.push_back(NULLPtr);
2457 
2458  StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2459 
2460  if (StringClass.empty()) StringClass = "NXConstantString";
2461 
2462  Elements.push_back(MakeConstantString(StringClass,
2463  ".objc_static_class_name"));
2464  Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
2465  ConstantStrings));
2466  llvm::StructType *StaticsListTy =
2467  llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, nullptr);
2468  llvm::Type *StaticsListPtrTy =
2469  llvm::PointerType::getUnqual(StaticsListTy);
2470  Statics = MakeGlobal(StaticsListTy, Elements, CGM.getPointerAlign(),
2471  ".objc_statics");
2472  llvm::ArrayType *StaticsListArrayTy =
2473  llvm::ArrayType::get(StaticsListPtrTy, 2);
2474  Elements.clear();
2475  Elements.push_back(Statics);
2476  Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
2477  Statics = MakeGlobal(StaticsListArrayTy, Elements,
2478  CGM.getPointerAlign(), ".objc_statics_ptr");
2479  Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
2480  }
2481  // Array of classes, categories, and constant objects
2482  llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
2483  Classes.size() + Categories.size() + 2);
2484  llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
2485  llvm::Type::getInt16Ty(VMContext),
2486  llvm::Type::getInt16Ty(VMContext),
2487  ClassListTy, nullptr);
2488 
2489  Elements.clear();
2490  // Pointer to an array of selectors used in this module.
2491  std::vector<llvm::Constant*> Selectors;
2492  std::vector<llvm::GlobalAlias*> SelectorAliases;
2493  for (SelectorMap::iterator iter = SelectorTable.begin(),
2494  iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2495 
2496  std::string SelNameStr = iter->first.getAsString();
2497  llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2498 
2499  SmallVectorImpl<TypedSelector> &Types = iter->second;
2500  for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2501  e = Types.end() ; i!=e ; i++) {
2502 
2503  llvm::Constant *SelectorTypeEncoding = NULLPtr;
2504  if (!i->first.empty())
2505  SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2506 
2507  Elements.push_back(SelName);
2508  Elements.push_back(SelectorTypeEncoding);
2509  Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2510  Elements.clear();
2511 
2512  // Store the selector alias for later replacement
2513  SelectorAliases.push_back(i->second);
2514  }
2515  }
2516  unsigned SelectorCount = Selectors.size();
2517  // NULL-terminate the selector list. This should not actually be required,
2518  // because the selector list has a length field. Unfortunately, the GCC
2519  // runtime decides to ignore the length field and expects a NULL terminator,
2520  // and GCC cooperates with this by always setting the length to 0.
2521  Elements.push_back(NULLPtr);
2522  Elements.push_back(NULLPtr);
2523  Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2524  Elements.clear();
2525 
2526  // Number of static selectors
2527  Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2528  llvm::GlobalVariable *SelectorList =
2529  MakeGlobalArray(SelStructTy, Selectors, CGM.getPointerAlign(),
2530  ".objc_selector_list");
2531  Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
2532  SelStructPtrTy));
2533 
2534  // Now that all of the static selectors exist, create pointers to them.
2535  for (unsigned int i=0 ; i<SelectorCount ; i++) {
2536 
2537  llvm::Constant *Idxs[] = {Zeros[0],
2538  llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
2539  // FIXME: We're generating redundant loads and stores here!
2540  llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(
2541  SelectorList->getValueType(), SelectorList, makeArrayRef(Idxs, 2));
2542  // If selectors are defined as an opaque type, cast the pointer to this
2543  // type.
2544  SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
2545  SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2546  SelectorAliases[i]->eraseFromParent();
2547  }
2548 
2549  // Number of classes defined.
2550  Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2551  Classes.size()));
2552  // Number of categories defined
2553  Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2554  Categories.size()));
2555  // Create an array of classes, then categories, then static object instances
2556  Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2557  // NULL-terminated list of static object instances (mainly constant strings)
2558  Classes.push_back(Statics);
2559  Classes.push_back(NULLPtr);
2560  llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
2561  Elements.push_back(ClassList);
2562  // Construct the symbol table
2563  llvm::Constant *SymTab =
2564  MakeGlobal(SymTabTy, Elements, CGM.getPointerAlign());
2565 
2566  // The symbol table is contained in a module which has some version-checking
2567  // constants
2568  llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
2569  PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
2570  (RuntimeVersion >= 10) ? IntTy : nullptr, nullptr);
2571  Elements.clear();
2572  // Runtime version, used for ABI compatibility checking.
2573  Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
2574  // sizeof(ModuleTy)
2575  llvm::DataLayout td(&TheModule);
2576  Elements.push_back(
2577  llvm::ConstantInt::get(LongTy,
2578  td.getTypeSizeInBits(ModuleTy) /
2579  CGM.getContext().getCharWidth()));
2580 
2581  // The path to the source file where this module was declared
2582  SourceManager &SM = CGM.getContext().getSourceManager();
2583  const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2584  std::string path =
2585  std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2586  Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2587  Elements.push_back(SymTab);
2588 
2589  if (RuntimeVersion >= 10)
2590  switch (CGM.getLangOpts().getGC()) {
2591  case LangOptions::GCOnly:
2592  Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
2593  break;
2594  case LangOptions::NonGC:
2595  if (CGM.getLangOpts().ObjCAutoRefCount)
2596  Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2597  else
2598  Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2599  break;
2600  case LangOptions::HybridGC:
2601  Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2602  break;
2603  }
2604 
2605  llvm::Value *Module = MakeGlobal(ModuleTy, Elements, CGM.getPointerAlign());
2606 
2607  // Create the load function calling the runtime entry point with the module
2608  // structure
2609  llvm::Function * LoadFunction = llvm::Function::Create(
2610  llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
2611  llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2612  &TheModule);
2613  llvm::BasicBlock *EntryBB =
2614  llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
2615  CGBuilderTy Builder(CGM, VMContext);
2616  Builder.SetInsertPoint(EntryBB);
2617 
2618  llvm::FunctionType *FT =
2619  llvm::FunctionType::get(Builder.getVoidTy(),
2620  llvm::PointerType::getUnqual(ModuleTy), true);
2621  llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
2622  Builder.CreateCall(Register, Module);
2623 
2624  if (!ClassAliases.empty()) {
2625  llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2626  llvm::FunctionType *RegisterAliasTy =
2627  llvm::FunctionType::get(Builder.getVoidTy(),
2628  ArgTypes, false);
2629  llvm::Function *RegisterAlias = llvm::Function::Create(
2630  RegisterAliasTy,
2631  llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2632  &TheModule);
2633  llvm::BasicBlock *AliasBB =
2634  llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2635  llvm::BasicBlock *NoAliasBB =
2636  llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2637 
2638  // Branch based on whether the runtime provided class_registerAlias_np()
2639  llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2640  llvm::Constant::getNullValue(RegisterAlias->getType()));
2641  Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2642 
2643  // The true branch (has alias registration function):
2644  Builder.SetInsertPoint(AliasBB);
2645  // Emit alias registration calls:
2646  for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2647  iter != ClassAliases.end(); ++iter) {
2648  llvm::Constant *TheClass =
2649  TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2650  true);
2651  if (TheClass) {
2652  TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2653  Builder.CreateCall(RegisterAlias,
2654  {TheClass, MakeConstantString(iter->second)});
2655  }
2656  }
2657  // Jump to end:
2658  Builder.CreateBr(NoAliasBB);
2659 
2660  // Missing alias registration function, just return from the function:
2661  Builder.SetInsertPoint(NoAliasBB);
2662  }
2663  Builder.CreateRetVoid();
2664 
2665  return LoadFunction;
2666 }
2667 
2668 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
2669  const ObjCContainerDecl *CD) {
2670  const ObjCCategoryImplDecl *OCD =
2671  dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
2672  StringRef CategoryName = OCD ? OCD->getName() : "";
2673  StringRef ClassName = CD->getName();
2674  Selector MethodName = OMD->getSelector();
2675  bool isClassMethod = !OMD->isInstanceMethod();
2676 
2677  CodeGenTypes &Types = CGM.getTypes();
2678  llvm::FunctionType *MethodTy =
2680  std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2681  MethodName, isClassMethod);
2682 
2683  llvm::Function *Method
2684  = llvm::Function::Create(MethodTy,
2686  FunctionName,
2687  &TheModule);
2688  return Method;
2689 }
2690 
2691 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
2692  return GetPropertyFn;
2693 }
2694 
2695 llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
2696  return SetPropertyFn;
2697 }
2698 
2699 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2700  bool copy) {
2701  return nullptr;
2702 }
2703 
2704 llvm::Constant *CGObjCGNU::GetGetStructFunction() {
2705  return GetStructPropertyFn;
2706 }
2707 
2708 llvm::Constant *CGObjCGNU::GetSetStructFunction() {
2709  return SetStructPropertyFn;
2710 }
2711 
2712 llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2713  return nullptr;
2714 }
2715 
2716 llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
2717  return nullptr;
2718 }
2719 
2720 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
2721  return EnumerationMutationFn;
2722 }
2723 
2724 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
2725  const ObjCAtSynchronizedStmt &S) {
2726  EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
2727 }
2728 
2729 
2730 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
2731  const ObjCAtTryStmt &S) {
2732  // Unlike the Apple non-fragile runtimes, which also uses
2733  // unwind-based zero cost exceptions, the GNU Objective C runtime's
2734  // EH support isn't a veneer over C++ EH. Instead, exception
2735  // objects are created by objc_exception_throw and destroyed by
2736  // the personality function; this avoids the need for bracketing
2737  // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2738  // (or even _Unwind_DeleteException), but probably doesn't
2739  // interoperate very well with foreign exceptions.
2740  //
2741  // In Objective-C++ mode, we actually emit something equivalent to the C++
2742  // exception handler.
2743  EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2744 }
2745 
2746 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
2747  const ObjCAtThrowStmt &S,
2748  bool ClearInsertionPoint) {
2749  llvm::Value *ExceptionAsObject;
2750 
2751  if (const Expr *ThrowExpr = S.getThrowExpr()) {
2752  llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
2753  ExceptionAsObject = Exception;
2754  } else {
2755  assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2756  "Unexpected rethrow outside @catch block.");
2757  ExceptionAsObject = CGF.ObjCEHValueStack.back();
2758  }
2759  ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
2760  llvm::CallSite Throw =
2761  CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2762  Throw.setDoesNotReturn();
2763  CGF.Builder.CreateUnreachable();
2764  if (ClearInsertionPoint)
2765  CGF.Builder.ClearInsertionPoint();
2766 }
2767 
2768 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
2769  Address AddrWeakObj) {
2770  CGBuilderTy &B = CGF.Builder;
2771  AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
2772  return B.CreateCall(WeakReadFn.getType(), WeakReadFn,
2773  AddrWeakObj.getPointer());
2774 }
2775 
2776 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
2777  llvm::Value *src, Address dst) {
2778  CGBuilderTy &B = CGF.Builder;
2779  src = EnforceType(B, src, IdTy);
2780  dst = EnforceType(B, dst, PtrToIdTy);
2781  B.CreateCall(WeakAssignFn.getType(), WeakAssignFn,
2782  {src, dst.getPointer()});
2783 }
2784 
2785 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
2786  llvm::Value *src, Address dst,
2787  bool threadlocal) {
2788  CGBuilderTy &B = CGF.Builder;
2789  src = EnforceType(B, src, IdTy);
2790  dst = EnforceType(B, dst, PtrToIdTy);
2791  // FIXME. Add threadloca assign API
2792  assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI");
2793  B.CreateCall(GlobalAssignFn.getType(), GlobalAssignFn,
2794  {src, dst.getPointer()});
2795 }
2796 
2797 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
2798  llvm::Value *src, Address dst,
2799  llvm::Value *ivarOffset) {
2800  CGBuilderTy &B = CGF.Builder;
2801  src = EnforceType(B, src, IdTy);
2802  dst = EnforceType(B, dst, IdTy);
2803  B.CreateCall(IvarAssignFn.getType(), IvarAssignFn,
2804  {src, dst.getPointer(), ivarOffset});
2805 }
2806 
2807 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
2808  llvm::Value *src, Address dst) {
2809  CGBuilderTy &B = CGF.Builder;
2810  src = EnforceType(B, src, IdTy);
2811  dst = EnforceType(B, dst, PtrToIdTy);
2812  B.CreateCall(StrongCastAssignFn.getType(), StrongCastAssignFn,
2813  {src, dst.getPointer()});
2814 }
2815 
2816 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
2817  Address DestPtr,
2818  Address SrcPtr,
2819  llvm::Value *Size) {
2820  CGBuilderTy &B = CGF.Builder;
2821  DestPtr = EnforceType(B, DestPtr, PtrTy);
2822  SrcPtr = EnforceType(B, SrcPtr, PtrTy);
2823 
2824  B.CreateCall(MemMoveFn.getType(), MemMoveFn,
2825  {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
2826 }
2827 
2828 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2829  const ObjCInterfaceDecl *ID,
2830  const ObjCIvarDecl *Ivar) {
2831  const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2832  + '.' + Ivar->getNameAsString();
2833  // Emit the variable and initialize it with what we think the correct value
2834  // is. This allows code compiled with non-fragile ivars to work correctly
2835  // when linked against code which isn't (most of the time).
2836  llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2837  if (!IvarOffsetPointer) {
2838  // This will cause a run-time crash if we accidentally use it. A value of
2839  // 0 would seem more sensible, but will silently overwrite the isa pointer
2840  // causing a great deal of confusion.
2841  uint64_t Offset = -1;
2842  // We can't call ComputeIvarBaseOffset() here if we have the
2843  // implementation, because it will create an invalid ASTRecordLayout object
2844  // that we are then stuck with forever, so we only initialize the ivar
2845  // offset variable with a guess if we only have the interface. The
2846  // initializer will be reset later anyway, when we are generating the class
2847  // description.
2848  if (!CGM.getContext().getObjCImplementation(
2849  const_cast<ObjCInterfaceDecl *>(ID)))
2850  Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2851 
2852  llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
2853  /*isSigned*/true);
2854  // Don't emit the guess in non-PIC code because the linker will not be able
2855  // to replace it with the real version for a library. In non-PIC code you
2856  // must compile with the fragile ABI if you want to use ivars from a
2857  // GCC-compiled class.
2858  if (CGM.getLangOpts().PICLevel) {
2859  llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2860  Int32Ty, false,
2861  llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2862  IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2863  IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2864  IvarOffsetGV, Name);
2865  } else {
2866  IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2867  llvm::Type::getInt32PtrTy(VMContext), false,
2868  llvm::GlobalValue::ExternalLinkage, nullptr, Name);
2869  }
2870  }
2871  return IvarOffsetPointer;
2872 }
2873 
2874 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
2875  QualType ObjectTy,
2876  llvm::Value *BaseValue,
2877  const ObjCIvarDecl *Ivar,
2878  unsigned CVRQualifiers) {
2879  const ObjCInterfaceDecl *ID =
2880  ObjectTy->getAs<ObjCObjectType>()->getInterface();
2881  return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2882  EmitIvarOffset(CGF, ID, Ivar));
2883 }
2884 
2886  const ObjCInterfaceDecl *OID,
2887  const ObjCIvarDecl *OIVD) {
2888  for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2889  next = next->getNextIvar()) {
2890  if (OIVD == next)
2891  return OID;
2892  }
2893 
2894  // Otherwise check in the super class.
2895  if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2896  return FindIvarInterface(Context, Super, OIVD);
2897 
2898  return nullptr;
2899 }
2900 
2901 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
2902  const ObjCInterfaceDecl *Interface,
2903  const ObjCIvarDecl *Ivar) {
2904  if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2905  Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2906 
2907  // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
2908  // and ExternalLinkage, so create a reference to the ivar global and rely on
2909  // the definition being created as part of GenerateClass.
2910  if (RuntimeVersion < 10 ||
2911  CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
2912  return CGF.Builder.CreateZExtOrBitCast(
2914  ObjCIvarOffsetVariable(Interface, Ivar),
2915  CGF.getPointerAlign(), "ivar")),
2916  PtrDiffTy);
2917  std::string name = "__objc_ivar_offset_value_" +
2918  Interface->getNameAsString() +"." + Ivar->getNameAsString();
2919  CharUnits Align = CGM.getIntAlign();
2920  llvm::Value *Offset = TheModule.getGlobalVariable(name);
2921  if (!Offset) {
2922  auto GV = new llvm::GlobalVariable(TheModule, IntTy,
2923  false, llvm::GlobalValue::LinkOnceAnyLinkage,
2924  llvm::Constant::getNullValue(IntTy), name);
2925  GV->setAlignment(Align.getQuantity());
2926  Offset = GV;
2927  }
2928  Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
2929  if (Offset->getType() != PtrDiffTy)
2930  Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2931  return Offset;
2932  }
2933  uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2934  return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
2935 }
2936 
2937 CGObjCRuntime *
2939  switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
2940  case ObjCRuntime::GNUstep:
2941  return new CGObjCGNUstep(CGM);
2942 
2943  case ObjCRuntime::GCC:
2944  return new CGObjCGCC(CGM);
2945 
2946  case ObjCRuntime::ObjFW:
2947  return new CGObjCObjFW(CGM);
2948 
2949  case ObjCRuntime::FragileMacOSX:
2950  case ObjCRuntime::MacOSX:
2951  case ObjCRuntime::iOS:
2952  case ObjCRuntime::WatchOS:
2953  llvm_unreachable("these runtimes are not GNU runtimes");
2954  }
2955  llvm_unreachable("bad runtime");
2956 }
ReturnValueSlot - Contains the address where the return value of a function can be stored...
Definition: CGCall.h:151
Defines the clang::ASTContext interface.
static std::string SymbolNameForMethod(StringRef ClassName, StringRef CategoryName, const Selector MethodName, bool isClassMethod)
Definition: CGObjCGNU.cpp:918
ObjCInterfaceDecl * getDecl() const
Get the declaration of this interface.
Definition: Type.h:4948
static Selector GetNullarySelector(StringRef name, ASTContext &Ctx)
Utility function for constructing a nullary selector.
Definition: ASTContext.h:2605
External linkage, which indicates that the entity can be referred to from other translation units...
Definition: Linkage.h:50
StringRef getName() const
getName - Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:237
protocol_range protocols() const
Definition: DeclObjC.h:2025
Smart pointer class that efficiently represents Objective-C method names.
A (possibly-)qualified type.
Definition: Type.h:598
Represents a version number in the form major[.minor[.subminor[.build]]].
Definition: VersionTuple.h:26
#define va_end(ap)
Definition: stdarg.h:34
Defines the clang::FileManager interface and associated types.
IdentifierInfo * getIdentifier() const
getIdentifier - Get the identifier that names this declaration, if there is one.
Definition: Decl.h:232
PropertyControl getPropertyImplementation() const
Definition: DeclObjC.h:870
std::pair< llvm::Value *, llvm::Value * > getComplexVal() const
getComplexVal - Return the real/imag components of this complex value.
Definition: CGValue.h:65
llvm::AllocaInst * CreateTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateTempAlloca - This creates a alloca and inserts it into the entry block.
Definition: CGExpr.cpp:69
Implements runtime-specific code generation functions.
Definition: CGObjCRuntime.h:63
Defines the SourceManager interface.
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
llvm::LoadInst * CreateDefaultAlignedLoad(llvm::Value *Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:127
const Decl * CurCodeDecl
CurCodeDecl - This is the inner-most code context, which includes blocks.
Represents Objective-C's @throw statement.
Definition: StmtObjC.h:313
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition: Type.h:5031
const ASTRecordLayout & getASTObjCImplementationLayout(const ObjCImplementationDecl *D) const
Get or compute information about the layout of the specified Objective-C implementation.
VarDecl - An instance of this class is created to represent a variable declaration or definition...
Definition: Decl.h:768
llvm::Type * getElementType() const
Return the type of the values stored in this address.
Definition: Address.h:52
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:113
virtual bool isDynamic(OpenMPScheduleClauseKind ScheduleKind) const
Check if the specified ScheduleKind is dynamic.
Defines the Objective-C statement AST node classes.
bool isVoidType() const
Definition: Type.h:5680
llvm::Constant * getPointer() const
Definition: Address.h:84
llvm::Value * EmitObjCThrowOperand(const Expr *expr)
Definition: CGObjC.cpp:2971
One of these records is kept for each identifier that is lexed.
This table allows us to fully hide how we implement multi-keyword caching.
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
Definition: Type.h:4549
Represents a class type in Objective C.
Definition: Type.h:4727
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
llvm::Type * ConvertType(QualType T)
ConvertType - Convert type T into a llvm::Type.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:92
bool isAnyPointerType() const
Definition: Type.h:5485
static const ObjCInterfaceDecl * FindIvarInterface(ASTContext &Context, const ObjCInterfaceDecl *OID, const ObjCIvarDecl *OIVD)
Definition: CGObjCGNU.cpp:2885
RValue EmitCall(const CGFunctionInfo &FnInfo, llvm::Value *Callee, ReturnValueSlot ReturnValue, const CallArgList &Args, CGCalleeInfo CalleeInfo=CGCalleeInfo(), llvm::Instruction **callOrInvoke=nullptr)
EmitCall - Generate a call of the given function, expecting the given result type, and using the given argument list which specifies both the LLVM arguments and the types they were derived from.
Definition: CGCall.cpp:3507
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:48
void InitTempAlloca(Address Alloca, llvm::Value *Value)
InitTempAlloca - Provide an initial value for the given alloca which will be observable at all locati...
Definition: CGExpr.cpp:85
Describes a module or submodule.
Definition: Basic/Module.h:47
IdentifierTable & Idents
Definition: ASTContext.h:459
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:901
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
uint32_t Offset
Definition: CacheTokens.cpp:44
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface...
Definition: Type.h:4970
ObjCRuntime()
A bogus initialization of the runtime.
Definition: ObjCRuntime.h:65
std::string getNameAsString() const
getNameAsString - Get a human-readable name for the declaration, even if it is one of the special kin...
Definition: Decl.h:252
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
Definition: DeclObjC.h:2098
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:1968
Represents an ObjC class declaration.
Definition: DeclObjC.h:1091
propimpl_range property_impls() const
Definition: DeclObjC.h:2351
#define va_arg(ap, type)
Definition: stdarg.h:35
detail::InMemoryDirectory::const_iterator I
llvm::CallSite EmitRuntimeCallOrInvoke(llvm::Value *callee, ArrayRef< llvm::Value * > args, const Twine &name="")
Emits a call or invoke instruction to the given runtime function.
Definition: CGCall.cpp:3456
void addFrom(const CallArgList &other)
Definition: CGCall.h:85
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
llvm::CallInst * EmitNounwindRuntimeCall(llvm::Value *callee, const Twine &name="")
CGBlockInfo - Information to generate a block literal.
Definition: CGBlocks.h:153
const TargetInfo & getTarget() const
RValue - This trivial value class is used to represent the result of an expression that is evaluated...
Definition: CGValue.h:38
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.
ASTContext * Context
llvm::Value * getPointer() const
Definition: Address.h:38
Expr - This represents one expression.
Definition: Expr.h:105
StringRef getName() const
Return the actual identifier string.
bool isAggregate() const
Definition: CGValue.h:53
ASTContext & getContext() const
Represents Objective-C's @synchronized statement.
Definition: StmtObjC.h:262
void add(RValue rvalue, QualType type, bool needscopy=false)
Definition: CGCall.h:81
bool isObjCIdType() const
Definition: Type.h:5578
bool isInstanceMethod() const
Definition: DeclObjC.h:414
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:93
bool isa(CodeGen::Address addr)
Definition: Address.h:112
'gnustep' is the modern non-fragile GNUstep runtime.
Definition: ObjCRuntime.h:53
do v
Definition: arm_acle.h:78
const SourceManager & SM
Definition: Format.cpp:1184
ObjCCategoryDecl * getCategoryDecl() const
Definition: DeclObjC.cpp:1999
The l-value was considered opaque, so the alignment was determined from a type.
Address CreateBitCast(Address Addr, llvm::Type *Ty, const llvm::Twine &Name="")
Definition: CGBuilder.h:160
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:5730
const char * getName() const
Definition: FileManager.h:85
ASTContext & getContext() const
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
CharUnits getSize() const
getSize - Get the record size in characters.
Definition: RecordLayout.h:170
const TemplateArgument * iterator
Definition: Type.h:4233
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:4936
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2642
SmallVector< llvm::Value *, 8 > ObjCEHValueStack
ObjCEHValueStack - Stack of Objective-C exception values, used for rethrows.
const std::string ID
static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef< Expr * > VL, ArrayRef< Expr * > PL, ArrayRef< Expr * > IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate)
Creates clause with a list of variables VL and a linear step Step.
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:53
const CGFunctionInfo & arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD)
Objective-C methods are C functions with some implicit parameters.
Definition: CGCall.cpp:405
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2171
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2325
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
#define va_start(ap, param)
Definition: stdarg.h:33
An aligned address.
Definition: Address.h:25
const LangOptions & getLangOpts() const
std::string getAsString() const
Derive the full selector name (e.g.
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:699
const VersionTuple & getVersion() const
Definition: ObjCRuntime.h:76
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1407
FileID getMainFileID() const
Returns the FileID of the main source file.
const char * getName() const
Definition: FileManager.h:45
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:1623
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1882
CharUnits getAlignment() const
Return the alignment of this pointer.
Definition: Address.h:67
instmeth_range instance_methods() const
Definition: DeclObjC.h:979
This class organizes the cross-function state that is used while generating LLVM code.
bool isScalar() const
Definition: CGValue.h:51
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1135
std::string getNameAsString() const
Get the name of the class associated with this interface.
Definition: DeclObjC.h:2431
The basic abstraction for the target Objective-C runtime.
Definition: ObjCRuntime.h:25
llvm::Value * getScalarVal() const
getScalarVal() - Return the Value* of this scalar value.
Definition: CGValue.h:58
Address CreateStructGEP(Address Addr, unsigned Index, CharUnits Offset, const llvm::Twine &Name="")
Definition: CGBuilder.h:183
llvm::LoadInst * CreateAlignedLoad(llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:91
__builtin_va_list va_list
Definition: stdarg.h:30
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1446
std::unique_ptr< DiagnosticConsumer > create(StringRef OutputFile, DiagnosticOptions *Diags, bool MergeChildRecords=false)
Returns a DiagnosticConsumer that serializes diagnostics to a bitcode file.
llvm::LoadInst * CreateLoad(Address Addr, const llvm::Twine &Name="")
Definition: CGBuilder.h:70
StringRef getString() const
Definition: Expr.h:1514
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Selector getSelector() const
Definition: DeclObjC.h:328
detail::InMemoryDirectory::const_iterator E
llvm::StoreInst * CreateStore(llvm::Value *Val, Address Addr, bool IsVolatile=false)
Definition: CGBuilder.h:113
iterator begin() const
Definition: DeclObjC.h:65
Represents a pointer to an Objective C object.
Definition: Type.h:4991
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2461
ObjCMethodDecl * getGetterMethodDecl() const
Definition: DeclObjC.h:860
llvm::PointerType * getType() const
Return the type of the pointer value.
Definition: Address.h:44
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:5818
ObjCMethodDecl * getSetterMethodDecl() const
Definition: DeclObjC.h:863
instprop_range instance_properties() const
Definition: DeclObjC.h:934
This class organizes the cross-module state that is used while lowering AST types to LLVM types...
Definition: CodeGenTypes.h:120
bool isObjCQualifiedIdType() const
Definition: Type.h:5568
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:33
protocol_range protocols() const
Definition: DeclObjC.h:1278
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition: CGStmt.cpp:397
bool getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, std::string &S, bool Extended=false) const
Emit the encoded type for the method declaration Decl into S.
Kind getKind() const
Definition: ObjCRuntime.h:75
classmeth_range class_methods() const
Definition: DeclObjC.h:994
BoundNodesTreeBuilder *const Builder
StringRef getName() const
getName - Get the name of identifier for the class interface associated with this implementation as a...
Definition: DeclObjC.h:2426
A specialization of Address that requires the address to be an LLVM Constant.
Definition: Address.h:75
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1849
Address getAggregateAddress() const
getAggregateAddr() - Return the Value* of the address of the aggregate.
Definition: CGValue.h:70
Represents Objective-C's @try ... @catch ... @finally statement.
Definition: StmtObjC.h:154
const Expr * getThrowExpr() const
Definition: StmtObjC.h:325
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1466
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:314
TranslationUnitDecl - The top declaration context.
Definition: Decl.h:80
llvm::Value * LoadObjCSelf()
LoadObjCSelf - Load the value of self.
Definition: CGObjC.cpp:1437
LValue - This represents an lvalue references.
Definition: CGValue.h:152
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
Definition: DeclObjC.cpp:1521
const ASTRecordLayout & getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const
Get or compute information about the layout of the specified Objective-C interface.
const DirectoryEntry * getDir() const
Return the directory the file lives in.
Definition: FileManager.h:95
CallArgList - Type for representing both the value and type of arguments in a call.
Definition: CGCall.h:56
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration...
Definition: DeclObjC.h:2380
This class handles loading and caching of source files into memory.
iterator end() const
Definition: DeclObjC.h:66
CGCalleeInfo - Class to encapsulate the information about a callee to be used during the generation o...
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2626
const ObjCProtocolList & getReferencedProtocols() const
Definition: DeclObjC.h:2238
CGObjCRuntime * CreateGNUObjCRuntime(CodeGenModule &CGM)
Creates an instance of an Objective-C runtime class.
Definition: CGObjCGNU.cpp:2938
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1466