Clang Project

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