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