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