1 //===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This provides Objective-C code generation targeting the GNU runtime. The
11 // class in this file generates structures used by the GNU Objective-C runtime
12 // library. These structures are defined in objc/objc.h and objc/objc-api.h in
13 // the GNU runtime distribution.
15 //===----------------------------------------------------------------------===//
17 #include "CGObjCRuntime.h"
18 #include "CGCleanup.h"
19 #include "CodeGenFunction.h"
20 #include "CodeGenModule.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/RecordLayout.h"
25 #include "clang/AST/StmtObjC.h"
26 #include "clang/Basic/FileManager.h"
27 #include "clang/Basic/SourceManager.h"
28 #include "llvm/ADT/SmallVector.h"
29 #include "llvm/ADT/StringMap.h"
30 #include "llvm/IR/CallSite.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/IR/Intrinsics.h"
33 #include "llvm/IR/LLVMContext.h"
34 #include "llvm/IR/Module.h"
35 #include "llvm/Support/Compiler.h"
39 using namespace clang;
40 using namespace CodeGen;
44 /// Class that lazily initialises the runtime function. Avoids inserting the
45 /// types and the function declaration into a module if they're not used, and
46 /// avoids constructing the type more than once if it's used more than once.
47 class LazyRuntimeFunction {
49 std::vector<llvm::Type*> ArgTys;
50 const char *FunctionName;
51 llvm::Constant *Function;
53 /// Constructor leaves this class uninitialized, because it is intended to
54 /// be used as a field in another class and not all of the types that are
55 /// used as arguments will necessarily be available at construction time.
56 LazyRuntimeFunction() : CGM(0), FunctionName(0), Function(0) {}
58 /// Initialises the lazy function with the name, return type, and the types
61 void init(CodeGenModule *Mod, const char *name,
62 llvm::Type *RetTy, ...) {
68 va_start(Args, RetTy);
69 while (llvm::Type *ArgTy = va_arg(Args, llvm::Type*))
70 ArgTys.push_back(ArgTy);
72 // Push the return type on at the end so we can pop it off easily
73 ArgTys.push_back(RetTy);
75 /// Overloaded cast operator, allows the class to be implicitly cast to an
77 operator llvm::Constant*() {
79 if (0 == FunctionName) return 0;
80 // We put the return type on the end of the vector, so pop it back off
81 llvm::Type *RetTy = ArgTys.back();
83 llvm::FunctionType *FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
85 cast<llvm::Constant>(CGM->CreateRuntimeFunction(FTy, FunctionName));
86 // We won't need to use the types again, so we may as well clean up the
92 operator llvm::Function*() {
93 return cast<llvm::Function>((llvm::Constant*)*this);
99 /// GNU Objective-C runtime code generation. This class implements the parts of
100 /// Objective-C support that are specific to the GNU family of runtimes (GCC,
101 /// GNUstep and ObjFW).
102 class CGObjCGNU : public CGObjCRuntime {
104 /// The LLVM module into which output is inserted
105 llvm::Module &TheModule;
106 /// strut objc_super. Used for sending messages to super. This structure
107 /// contains the receiver (object) and the expected class.
108 llvm::StructType *ObjCSuperTy;
109 /// struct objc_super*. The type of the argument to the superclass message
110 /// lookup functions.
111 llvm::PointerType *PtrToObjCSuperTy;
112 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
113 /// SEL is included in a header somewhere, in which case it will be whatever
114 /// type is declared in that header, most likely {i8*, i8*}.
115 llvm::PointerType *SelectorTy;
116 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
117 /// places where it's used
118 llvm::IntegerType *Int8Ty;
119 /// Pointer to i8 - LLVM type of char*, for all of the places where the
120 /// runtime needs to deal with C strings.
121 llvm::PointerType *PtrToInt8Ty;
122 /// Instance Method Pointer type. This is a pointer to a function that takes,
123 /// at a minimum, an object and a selector, and is the generic type for
124 /// Objective-C methods. Due to differences between variadic / non-variadic
125 /// calling conventions, it must always be cast to the correct type before
126 /// actually being used.
127 llvm::PointerType *IMPTy;
128 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
129 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
130 /// but if the runtime header declaring it is included then it may be a
131 /// pointer to a structure.
132 llvm::PointerType *IdTy;
133 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
134 /// message lookup function and some GC-related functions.
135 llvm::PointerType *PtrToIdTy;
136 /// The clang type of id. Used when using the clang CGCall infrastructure to
137 /// call Objective-C methods.
139 /// LLVM type for C int type.
140 llvm::IntegerType *IntTy;
141 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
142 /// used in the code to document the difference between i8* meaning a pointer
143 /// to a C string and i8* meaning a pointer to some opaque type.
144 llvm::PointerType *PtrTy;
145 /// LLVM type for C long type. The runtime uses this in a lot of places where
146 /// it should be using intptr_t, but we can't fix this without breaking
147 /// compatibility with GCC...
148 llvm::IntegerType *LongTy;
149 /// LLVM type for C size_t. Used in various runtime data structures.
150 llvm::IntegerType *SizeTy;
151 /// LLVM type for C intptr_t.
152 llvm::IntegerType *IntPtrTy;
153 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
154 llvm::IntegerType *PtrDiffTy;
155 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
157 llvm::PointerType *PtrToIntTy;
158 /// LLVM type for Objective-C BOOL type.
160 /// 32-bit integer type, to save us needing to look it up every time it's used.
161 llvm::IntegerType *Int32Ty;
162 /// 64-bit integer type, to save us needing to look it up every time it's used.
163 llvm::IntegerType *Int64Ty;
164 /// Metadata kind used to tie method lookups to message sends. The GNUstep
165 /// runtime provides some LLVM passes that can use this to do things like
166 /// automatic IMP caching and speculative inlining.
167 unsigned msgSendMDKind;
168 /// Helper function that generates a constant string and returns a pointer to
169 /// the start of the string. The result of this function can be used anywhere
170 /// where the C code specifies const char*.
171 llvm::Constant *MakeConstantString(const std::string &Str,
172 const std::string &Name="") {
173 llvm::Constant *ConstStr = CGM.GetAddrOfConstantCString(Str, Name.c_str());
174 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
176 /// Emits a linkonce_odr string, whose name is the prefix followed by the
177 /// string value. This allows the linker to combine the strings between
178 /// different modules. Used for EH typeinfo names, selector strings, and a
179 /// few other things.
180 llvm::Constant *ExportUniqueString(const std::string &Str,
181 const std::string prefix) {
182 std::string name = prefix + Str;
183 llvm::Constant *ConstStr = TheModule.getGlobalVariable(name);
185 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
186 ConstStr = new llvm::GlobalVariable(TheModule, value->getType(), true,
187 llvm::GlobalValue::LinkOnceODRLinkage, value, prefix + Str);
189 return llvm::ConstantExpr::getGetElementPtr(ConstStr, Zeros);
191 /// Generates a global structure, initialized by the elements in the vector.
192 /// The element types must match the types of the structure elements in the
194 llvm::GlobalVariable *MakeGlobal(llvm::StructType *Ty,
195 ArrayRef<llvm::Constant *> V,
197 llvm::GlobalValue::LinkageTypes linkage
198 =llvm::GlobalValue::InternalLinkage) {
199 llvm::Constant *C = llvm::ConstantStruct::get(Ty, V);
200 return new llvm::GlobalVariable(TheModule, Ty, false,
203 /// Generates a global array. The vector must contain the same number of
204 /// elements that the array type declares, of the type specified as the array
206 llvm::GlobalVariable *MakeGlobal(llvm::ArrayType *Ty,
207 ArrayRef<llvm::Constant *> V,
209 llvm::GlobalValue::LinkageTypes linkage
210 =llvm::GlobalValue::InternalLinkage) {
211 llvm::Constant *C = llvm::ConstantArray::get(Ty, V);
212 return new llvm::GlobalVariable(TheModule, Ty, false,
215 /// Generates a global array, inferring the array type from the specified
216 /// element type and the size of the initialiser.
217 llvm::GlobalVariable *MakeGlobalArray(llvm::Type *Ty,
218 ArrayRef<llvm::Constant *> V,
220 llvm::GlobalValue::LinkageTypes linkage
221 =llvm::GlobalValue::InternalLinkage) {
222 llvm::ArrayType *ArrayTy = llvm::ArrayType::get(Ty, V.size());
223 return MakeGlobal(ArrayTy, V, Name, linkage);
225 /// Returns a property name and encoding string.
226 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
227 const Decl *Container) {
228 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
229 if ((R.getKind() == ObjCRuntime::GNUstep) &&
230 (R.getVersion() >= VersionTuple(1, 6))) {
231 std::string NameAndAttributes;
233 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
234 NameAndAttributes += '\0';
235 NameAndAttributes += TypeStr.length() + 3;
236 NameAndAttributes += TypeStr;
237 NameAndAttributes += '\0';
238 NameAndAttributes += PD->getNameAsString();
239 NameAndAttributes += '\0';
240 return llvm::ConstantExpr::getGetElementPtr(
241 CGM.GetAddrOfConstantString(NameAndAttributes), Zeros);
243 return MakeConstantString(PD->getNameAsString());
245 /// Push the property attributes into two structure fields.
246 void PushPropertyAttributes(std::vector<llvm::Constant*> &Fields,
247 ObjCPropertyDecl *property, bool isSynthesized=true, bool
249 int attrs = property->getPropertyAttributes();
250 // For read-only properties, clear the copy and retain flags
251 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
252 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
253 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
254 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
255 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
257 // The first flags field has the same attribute values as clang uses internally
258 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
261 // For protocol properties, synthesized and dynamic have no meaning, so we
262 // reuse these flags to indicate that this is a protocol property (both set
263 // has no meaning, as a property can't be both synthesized and dynamic)
264 attrs |= isSynthesized ? (1<<0) : 0;
265 attrs |= isDynamic ? (1<<1) : 0;
266 // The second field is the next four fields left shifted by two, with the
267 // low bit set to indicate whether the field is synthesized or dynamic.
268 Fields.push_back(llvm::ConstantInt::get(Int8Ty, attrs & 0xff));
269 // Two padding fields
270 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
271 Fields.push_back(llvm::ConstantInt::get(Int8Ty, 0));
273 /// Ensures that the value has the required type, by inserting a bitcast if
274 /// required. This function lets us avoid inserting bitcasts that are
276 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
277 if (V->getType() == Ty) return V;
278 return B.CreateBitCast(V, Ty);
280 // Some zeros used for GEPs in lots of places.
281 llvm::Constant *Zeros[2];
282 /// Null pointer value. Mainly used as a terminator in various arrays.
283 llvm::Constant *NULLPtr;
285 llvm::LLVMContext &VMContext;
287 /// Placeholder for the class. Lots of things refer to the class before we've
288 /// actually emitted it. We use this alias as a placeholder, and then replace
289 /// it with a pointer to the class structure before finally emitting the
291 llvm::GlobalAlias *ClassPtrAlias;
292 /// Placeholder for the metaclass. Lots of things refer to the class before
293 /// we've / actually emitted it. We use this alias as a placeholder, and then
294 /// replace / it with a pointer to the metaclass structure before finally
295 /// emitting the / module.
296 llvm::GlobalAlias *MetaClassPtrAlias;
297 /// All of the classes that have been generated for this compilation units.
298 std::vector<llvm::Constant*> Classes;
299 /// All of the categories that have been generated for this compilation units.
300 std::vector<llvm::Constant*> Categories;
301 /// All of the Objective-C constant strings that have been generated for this
302 /// compilation units.
303 std::vector<llvm::Constant*> ConstantStrings;
304 /// Map from string values to Objective-C constant strings in the output.
305 /// Used to prevent emitting Objective-C strings more than once. This should
306 /// not be required at all - CodeGenModule should manage this list.
307 llvm::StringMap<llvm::Constant*> ObjCStrings;
308 /// All of the protocols that have been declared.
309 llvm::StringMap<llvm::Constant*> ExistingProtocols;
310 /// For each variant of a selector, we store the type encoding and a
311 /// placeholder value. For an untyped selector, the type will be the empty
312 /// string. Selector references are all done via the module's selector table,
313 /// so we create an alias as a placeholder and then replace it with the real
315 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
316 /// Type of the selector map. This is roughly equivalent to the structure
317 /// used in the GNUstep runtime, which maintains a list of all of the valid
318 /// types for a selector in a table.
319 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
321 /// A map from selectors to selector types. This allows us to emit all
322 /// selectors of the same name and type together.
323 SelectorMap SelectorTable;
325 /// Selectors related to memory management. When compiling in GC mode, we
327 Selector RetainSel, ReleaseSel, AutoreleaseSel;
328 /// Runtime functions used for memory management in GC mode. Note that clang
329 /// supports code generation for calling these functions, but neither GNU
330 /// runtime actually supports this API properly yet.
331 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
332 WeakAssignFn, GlobalAssignFn;
334 typedef std::pair<std::string, std::string> ClassAliasPair;
335 /// All classes that have aliases set for them.
336 std::vector<ClassAliasPair> ClassAliases;
339 /// Function used for throwing Objective-C exceptions.
340 LazyRuntimeFunction ExceptionThrowFn;
341 /// Function used for rethrowing exceptions, used at the end of \@finally or
342 /// \@synchronize blocks.
343 LazyRuntimeFunction ExceptionReThrowFn;
344 /// Function called when entering a catch function. This is required for
345 /// differentiating Objective-C exceptions and foreign exceptions.
346 LazyRuntimeFunction EnterCatchFn;
347 /// Function called when exiting from a catch block. Used to do exception
349 LazyRuntimeFunction ExitCatchFn;
350 /// Function called when entering an \@synchronize block. Acquires the lock.
351 LazyRuntimeFunction SyncEnterFn;
352 /// Function called when exiting an \@synchronize block. Releases the lock.
353 LazyRuntimeFunction SyncExitFn;
357 /// Function called if fast enumeration detects that the collection is
358 /// modified during the update.
359 LazyRuntimeFunction EnumerationMutationFn;
360 /// Function for implementing synthesized property getters that return an
362 LazyRuntimeFunction GetPropertyFn;
363 /// Function for implementing synthesized property setters that return an
365 LazyRuntimeFunction SetPropertyFn;
366 /// Function used for non-object declared property getters.
367 LazyRuntimeFunction GetStructPropertyFn;
368 /// Function used for non-object declared property setters.
369 LazyRuntimeFunction SetStructPropertyFn;
371 /// The version of the runtime that this class targets. Must match the
372 /// version in the runtime.
374 /// The version of the protocol class. Used to differentiate between ObjC1
375 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
376 /// components and can not contain declared properties. We always emit
377 /// Objective-C 2 property structures, but we have to pretend that they're
378 /// Objective-C 1 property structures when targeting the GCC runtime or it
380 const int ProtocolVersion;
382 /// Generates an instance variable list structure. This is a structure
383 /// containing a size and an array of structures containing instance variable
384 /// metadata. This is used purely for introspection in the fragile ABI. In
385 /// the non-fragile ABI, it's used for instance variable fixup.
386 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
387 ArrayRef<llvm::Constant *> IvarTypes,
388 ArrayRef<llvm::Constant *> IvarOffsets);
389 /// Generates a method list structure. This is a structure containing a size
390 /// and an array of structures containing method metadata.
392 /// This structure is used by both classes and categories, and contains a next
393 /// pointer allowing them to be chained together in a linked list.
394 llvm::Constant *GenerateMethodList(const StringRef &ClassName,
395 const StringRef &CategoryName,
396 ArrayRef<Selector> MethodSels,
397 ArrayRef<llvm::Constant *> MethodTypes,
398 bool isClassMethodList);
399 /// Emits an empty protocol. This is used for \@protocol() where no protocol
400 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
402 llvm::Constant *GenerateEmptyProtocol(const std::string &ProtocolName);
403 /// Generates a list of property metadata structures. This follows the same
404 /// pattern as method and instance variable metadata lists.
405 llvm::Constant *GeneratePropertyList(const ObjCImplementationDecl *OID,
406 SmallVectorImpl<Selector> &InstanceMethodSels,
407 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes);
408 /// Generates a list of referenced protocols. Classes, categories, and
409 /// protocols all use this structure.
410 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
411 /// To ensure that all protocols are seen by the runtime, we add a category on
412 /// a class defined in the runtime, declaring no methods, but adopting the
413 /// protocols. This is a horribly ugly hack, but it allows us to collect all
414 /// of the protocols without changing the ABI.
415 void GenerateProtocolHolderCategory();
416 /// Generates a class structure.
417 llvm::Constant *GenerateClassStructure(
418 llvm::Constant *MetaClass,
419 llvm::Constant *SuperClass,
422 llvm::Constant *Version,
423 llvm::Constant *InstanceSize,
424 llvm::Constant *IVars,
425 llvm::Constant *Methods,
426 llvm::Constant *Protocols,
427 llvm::Constant *IvarOffsets,
428 llvm::Constant *Properties,
429 llvm::Constant *StrongIvarBitmap,
430 llvm::Constant *WeakIvarBitmap,
432 /// Generates a method list. This is used by protocols to define the required
433 /// and optional methods.
434 llvm::Constant *GenerateProtocolMethodList(
435 ArrayRef<llvm::Constant *> MethodNames,
436 ArrayRef<llvm::Constant *> MethodTypes);
437 /// Returns a selector with the specified type encoding. An empty string is
438 /// used to return an untyped selector (with the types field set to NULL).
439 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
440 const std::string &TypeEncoding, bool lval);
441 /// Returns the variable used to store the offset of an instance variable.
442 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
443 const ObjCIvarDecl *Ivar);
444 /// Emits a reference to a class. This allows the linker to object if there
445 /// is no class of the matching name.
447 void EmitClassRef(const std::string &className);
448 /// Emits a pointer to the named class
449 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
450 const std::string &Name, bool isWeak);
451 /// Looks up the method for sending a message to the specified object. This
452 /// mechanism differs between the GCC and GNU runtimes, so this method must be
453 /// overridden in subclasses.
454 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
455 llvm::Value *&Receiver,
458 MessageSendInfo &MSI) = 0;
459 /// Looks up the method for sending a message to a superclass. This
460 /// mechanism differs between the GCC and GNU runtimes, so this method must
461 /// be overridden in subclasses.
462 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
463 llvm::Value *ObjCSuper,
465 MessageSendInfo &MSI) = 0;
466 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
467 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
468 /// bits set to their values, LSB first, while larger ones are stored in a
469 /// structure of this / form:
471 /// struct { int32_t length; int32_t values[length]; };
473 /// The values in the array are stored in host-endian format, with the least
474 /// significant bit being assumed to come first in the bitfield. Therefore,
475 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
476 /// while a bitfield / with the 63rd bit set will be 1<<64.
477 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
479 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
480 unsigned protocolClassVersion);
482 virtual llvm::Constant *GenerateConstantString(const StringLiteral *);
485 GenerateMessageSend(CodeGenFunction &CGF,
486 ReturnValueSlot Return,
489 llvm::Value *Receiver,
490 const CallArgList &CallArgs,
491 const ObjCInterfaceDecl *Class,
492 const ObjCMethodDecl *Method);
494 GenerateMessageSendSuper(CodeGenFunction &CGF,
495 ReturnValueSlot Return,
498 const ObjCInterfaceDecl *Class,
500 llvm::Value *Receiver,
502 const CallArgList &CallArgs,
503 const ObjCMethodDecl *Method);
504 virtual llvm::Value *GetClass(CodeGenFunction &CGF,
505 const ObjCInterfaceDecl *OID);
506 virtual llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel,
508 virtual llvm::Value *GetSelector(CodeGenFunction &CGF, const ObjCMethodDecl
510 virtual llvm::Constant *GetEHType(QualType T);
512 virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
513 const ObjCContainerDecl *CD);
514 virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
515 virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
516 virtual void RegisterAlias(const ObjCCompatibleAliasDecl *OAD);
517 virtual llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
518 const ObjCProtocolDecl *PD);
519 virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
520 virtual llvm::Function *ModuleInitFunction();
521 virtual llvm::Constant *GetPropertyGetFunction();
522 virtual llvm::Constant *GetPropertySetFunction();
523 virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
525 virtual llvm::Constant *GetSetStructFunction();
526 virtual llvm::Constant *GetGetStructFunction();
527 virtual llvm::Constant *GetCppAtomicObjectGetFunction();
528 virtual llvm::Constant *GetCppAtomicObjectSetFunction();
529 virtual llvm::Constant *EnumerationMutationFunction();
531 virtual void EmitTryStmt(CodeGenFunction &CGF,
532 const ObjCAtTryStmt &S);
533 virtual void EmitSynchronizedStmt(CodeGenFunction &CGF,
534 const ObjCAtSynchronizedStmt &S);
535 virtual void EmitThrowStmt(CodeGenFunction &CGF,
536 const ObjCAtThrowStmt &S,
537 bool ClearInsertionPoint=true);
538 virtual llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
539 llvm::Value *AddrWeakObj);
540 virtual void EmitObjCWeakAssign(CodeGenFunction &CGF,
541 llvm::Value *src, llvm::Value *dst);
542 virtual void EmitObjCGlobalAssign(CodeGenFunction &CGF,
543 llvm::Value *src, llvm::Value *dest,
544 bool threadlocal=false);
545 virtual void EmitObjCIvarAssign(CodeGenFunction &CGF,
546 llvm::Value *src, llvm::Value *dest,
547 llvm::Value *ivarOffset);
548 virtual void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
549 llvm::Value *src, llvm::Value *dest);
550 virtual void EmitGCMemmoveCollectable(CodeGenFunction &CGF,
551 llvm::Value *DestPtr,
554 virtual LValue EmitObjCValueForIvar(CodeGenFunction &CGF,
556 llvm::Value *BaseValue,
557 const ObjCIvarDecl *Ivar,
558 unsigned CVRQualifiers);
559 virtual llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
560 const ObjCInterfaceDecl *Interface,
561 const ObjCIvarDecl *Ivar);
562 virtual llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF);
563 virtual llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
564 const CGBlockInfo &blockInfo) {
567 virtual llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
568 const CGBlockInfo &blockInfo) {
572 virtual llvm::Constant *BuildByrefLayout(CodeGenModule &CGM,
577 llvm::GlobalVariable *GetClassGlobal(const std::string &Name,
578 bool Weak = false) override {
582 /// Class representing the legacy GCC Objective-C ABI. This is the default when
583 /// -fobjc-nonfragile-abi is not specified.
585 /// The GCC ABI target actually generates code that is approximately compatible
586 /// with the new GNUstep runtime ABI, but refrains from using any features that
587 /// would not work with the GCC runtime. For example, clang always generates
588 /// the extended form of the class structure, and the extra fields are simply
589 /// ignored by GCC libobjc.
590 class CGObjCGCC : public CGObjCGNU {
591 /// The GCC ABI message lookup function. Returns an IMP pointing to the
592 /// method implementation for this message.
593 LazyRuntimeFunction MsgLookupFn;
594 /// The GCC ABI superclass message lookup function. Takes a pointer to a
595 /// structure describing the receiver and the class, and a selector as
596 /// arguments. Returns the IMP for the corresponding method.
597 LazyRuntimeFunction MsgLookupSuperFn;
599 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
600 llvm::Value *&Receiver,
603 MessageSendInfo &MSI) {
604 CGBuilderTy &Builder = CGF.Builder;
605 llvm::Value *args[] = {
606 EnforceType(Builder, Receiver, IdTy),
607 EnforceType(Builder, cmd, SelectorTy) };
608 llvm::CallSite imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
609 imp->setMetadata(msgSendMDKind, node);
610 return imp.getInstruction();
612 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
613 llvm::Value *ObjCSuper,
615 MessageSendInfo &MSI) {
616 CGBuilderTy &Builder = CGF.Builder;
617 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
618 PtrToObjCSuperTy), cmd};
619 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
622 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
623 // IMP objc_msg_lookup(id, SEL);
624 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
625 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
626 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
627 PtrToObjCSuperTy, SelectorTy, NULL);
630 /// Class used when targeting the new GNUstep runtime ABI.
631 class CGObjCGNUstep : public CGObjCGNU {
632 /// The slot lookup function. Returns a pointer to a cacheable structure
633 /// that contains (among other things) the IMP.
634 LazyRuntimeFunction SlotLookupFn;
635 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
636 /// a structure describing the receiver and the class, and a selector as
637 /// arguments. Returns the slot for the corresponding method. Superclass
638 /// message lookup rarely changes, so this is a good caching opportunity.
639 LazyRuntimeFunction SlotLookupSuperFn;
640 /// Specialised function for setting atomic retain properties
641 LazyRuntimeFunction SetPropertyAtomic;
642 /// Specialised function for setting atomic copy properties
643 LazyRuntimeFunction SetPropertyAtomicCopy;
644 /// Specialised function for setting nonatomic retain properties
645 LazyRuntimeFunction SetPropertyNonAtomic;
646 /// Specialised function for setting nonatomic copy properties
647 LazyRuntimeFunction SetPropertyNonAtomicCopy;
648 /// Function to perform atomic copies of C++ objects with nontrivial copy
649 /// constructors from Objective-C ivars.
650 LazyRuntimeFunction CxxAtomicObjectGetFn;
651 /// Function to perform atomic copies of C++ objects with nontrivial copy
652 /// constructors to Objective-C ivars.
653 LazyRuntimeFunction CxxAtomicObjectSetFn;
654 /// Type of an slot structure pointer. This is returned by the various
655 /// lookup functions.
658 virtual llvm::Constant *GetEHType(QualType T);
660 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
661 llvm::Value *&Receiver,
664 MessageSendInfo &MSI) {
665 CGBuilderTy &Builder = CGF.Builder;
666 llvm::Function *LookupFn = SlotLookupFn;
668 // Store the receiver on the stack so that we can reload it later
669 llvm::Value *ReceiverPtr = CGF.CreateTempAlloca(Receiver->getType());
670 Builder.CreateStore(Receiver, ReceiverPtr);
674 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
675 self = CGF.LoadObjCSelf();
677 self = llvm::ConstantPointerNull::get(IdTy);
680 // The lookup function is guaranteed not to capture the receiver pointer.
681 LookupFn->setDoesNotCapture(1);
683 llvm::Value *args[] = {
684 EnforceType(Builder, ReceiverPtr, PtrToIdTy),
685 EnforceType(Builder, cmd, SelectorTy),
686 EnforceType(Builder, self, IdTy) };
687 llvm::CallSite slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
688 slot.setOnlyReadsMemory();
689 slot->setMetadata(msgSendMDKind, node);
691 // Load the imp from the slot
693 Builder.CreateLoad(Builder.CreateStructGEP(slot.getInstruction(), 4));
695 // The lookup function may have changed the receiver, so make sure we use
697 Receiver = Builder.CreateLoad(ReceiverPtr, true);
700 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
701 llvm::Value *ObjCSuper,
703 MessageSendInfo &MSI) {
704 CGBuilderTy &Builder = CGF.Builder;
705 llvm::Value *lookupArgs[] = {ObjCSuper, cmd};
707 llvm::CallInst *slot =
708 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
709 slot->setOnlyReadsMemory();
711 return Builder.CreateLoad(Builder.CreateStructGEP(slot, 4));
714 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNU(Mod, 9, 3) {
715 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
717 llvm::StructType *SlotStructTy = llvm::StructType::get(PtrTy,
718 PtrTy, PtrTy, IntTy, IMPTy, NULL);
719 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
720 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
721 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
722 SelectorTy, IdTy, NULL);
723 // Slot_t objc_msg_lookup_super(struct objc_super*, SEL);
724 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
725 PtrToObjCSuperTy, SelectorTy, NULL);
726 // If we're in ObjC++ mode, then we want to make
727 if (CGM.getLangOpts().CPlusPlus) {
728 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
729 // void *__cxa_begin_catch(void *e)
730 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy, NULL);
731 // void __cxa_end_catch(void)
732 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy, NULL);
733 // void _Unwind_Resume_or_Rethrow(void*)
734 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
736 } else if (R.getVersion() >= VersionTuple(1, 7)) {
737 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
738 // id objc_begin_catch(void *e)
739 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy, NULL);
740 // void objc_end_catch(void)
741 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy, NULL);
742 // void _Unwind_Resume_or_Rethrow(void*)
743 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy,
746 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
747 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
748 SelectorTy, IdTy, PtrDiffTy, NULL);
749 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
750 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
751 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
752 IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
753 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
754 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy, NULL);
755 // void objc_setCppObjectAtomic(void *dest, const void *src, void
757 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
759 // void objc_getCppObjectAtomic(void *dest, const void *src, void
761 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
764 virtual llvm::Constant *GetCppAtomicObjectGetFunction() {
765 // The optimised functions were added in version 1.7 of the GNUstep
767 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
769 return CxxAtomicObjectGetFn;
771 virtual llvm::Constant *GetCppAtomicObjectSetFunction() {
772 // The optimised functions were added in version 1.7 of the GNUstep
774 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
776 return CxxAtomicObjectSetFn;
778 virtual llvm::Constant *GetOptimizedPropertySetFunction(bool atomic,
780 // The optimised property functions omit the GC check, and so are not
781 // safe to use in GC mode. The standard functions are fast in GC mode,
782 // so there is less advantage in using them.
783 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC));
784 // The optimised functions were added in version 1.7 of the GNUstep
786 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=
790 if (copy) return SetPropertyAtomicCopy;
791 return SetPropertyAtomic;
793 if (copy) return SetPropertyNonAtomicCopy;
794 return SetPropertyNonAtomic;
800 /// Support for the ObjFW runtime.
801 class CGObjCObjFW: public CGObjCGNU {
803 /// The GCC ABI message lookup function. Returns an IMP pointing to the
804 /// method implementation for this message.
805 LazyRuntimeFunction MsgLookupFn;
806 /// stret lookup function. While this does not seem to make sense at the
807 /// first look, this is required to call the correct forwarding function.
808 LazyRuntimeFunction MsgLookupFnSRet;
809 /// The GCC ABI superclass message lookup function. Takes a pointer to a
810 /// structure describing the receiver and the class, and a selector as
811 /// arguments. Returns the IMP for the corresponding method.
812 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
814 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
815 llvm::Value *&Receiver,
818 MessageSendInfo &MSI) {
819 CGBuilderTy &Builder = CGF.Builder;
820 llvm::Value *args[] = {
821 EnforceType(Builder, Receiver, IdTy),
822 EnforceType(Builder, cmd, SelectorTy) };
825 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
826 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
828 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
830 imp->setMetadata(msgSendMDKind, node);
831 return imp.getInstruction();
834 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
835 llvm::Value *ObjCSuper,
837 MessageSendInfo &MSI) {
838 CGBuilderTy &Builder = CGF.Builder;
839 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
840 PtrToObjCSuperTy), cmd};
842 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
843 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
845 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
848 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
849 const std::string &Name, bool isWeak) {
851 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
855 std::string SymbolName = "_OBJC_CLASS_" + Name;
857 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
860 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
861 llvm::GlobalValue::ExternalLinkage,
868 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
869 // IMP objc_msg_lookup(id, SEL);
870 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy, NULL);
871 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
873 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
874 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
875 PtrToObjCSuperTy, SelectorTy, NULL);
876 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
877 PtrToObjCSuperTy, SelectorTy, NULL);
880 } // end anonymous namespace
883 /// Emits a reference to a dummy variable which is emitted with each class.
884 /// This ensures that a linker error will be generated when trying to link
885 /// together modules where a referenced class is not defined.
886 void CGObjCGNU::EmitClassRef(const std::string &className) {
887 std::string symbolRef = "__objc_class_ref_" + className;
888 // Don't emit two copies of the same symbol
889 if (TheModule.getGlobalVariable(symbolRef))
891 std::string symbolName = "__objc_class_name_" + className;
892 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
894 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
895 llvm::GlobalValue::ExternalLinkage, 0, symbolName);
897 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
898 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
901 static std::string SymbolNameForMethod(const StringRef &ClassName,
902 const StringRef &CategoryName, const Selector MethodName,
903 bool isClassMethod) {
904 std::string MethodNameColonStripped = MethodName.getAsString();
905 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
907 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
908 CategoryName + "_" + MethodNameColonStripped).str();
911 CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
912 unsigned protocolClassVersion)
913 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
914 VMContext(cgm.getLLVMContext()), ClassPtrAlias(0), MetaClassPtrAlias(0),
915 RuntimeVersion(runtimeABIVersion), ProtocolVersion(protocolClassVersion) {
917 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
919 CodeGenTypes &Types = CGM.getTypes();
920 IntTy = cast<llvm::IntegerType>(
921 Types.ConvertType(CGM.getContext().IntTy));
922 LongTy = cast<llvm::IntegerType>(
923 Types.ConvertType(CGM.getContext().LongTy));
924 SizeTy = cast<llvm::IntegerType>(
925 Types.ConvertType(CGM.getContext().getSizeType()));
926 PtrDiffTy = cast<llvm::IntegerType>(
927 Types.ConvertType(CGM.getContext().getPointerDiffType()));
928 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
930 Int8Ty = llvm::Type::getInt8Ty(VMContext);
931 // C string type. Used in lots of places.
932 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
934 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
936 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
937 // Get the selector Type.
938 QualType selTy = CGM.getContext().getObjCSelType();
939 if (QualType() == selTy) {
940 SelectorTy = PtrToInt8Ty;
942 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
945 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
948 Int32Ty = llvm::Type::getInt32Ty(VMContext);
949 Int64Ty = llvm::Type::getInt64Ty(VMContext);
952 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
955 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
956 ASTIdTy = CanQualType();
957 if (UnqualIdTy != QualType()) {
958 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
959 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
963 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
965 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy, NULL);
966 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
968 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
970 // void objc_exception_throw(id);
971 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
972 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy, NULL);
973 // int objc_sync_enter(id);
974 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy, NULL);
975 // int objc_sync_exit(id);
976 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy, NULL);
978 // void objc_enumerationMutation (id)
979 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy,
982 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
983 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
984 PtrDiffTy, BoolTy, NULL);
985 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
986 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
987 PtrDiffTy, IdTy, BoolTy, BoolTy, NULL);
988 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
989 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
990 PtrDiffTy, BoolTy, BoolTy, NULL);
991 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
992 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
993 PtrDiffTy, BoolTy, BoolTy, NULL);
996 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
997 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
1000 const LangOptions &Opts = CGM.getLangOpts();
1001 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
1002 RuntimeVersion = 10;
1004 // Don't bother initialising the GC stuff unless we're compiling in GC mode
1005 if (Opts.getGC() != LangOptions::NonGC) {
1006 // This is a bit of an hack. We should sort this out by having a proper
1007 // CGObjCGNUstep subclass for GC, but we may want to really support the old
1008 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
1009 // Get selectors needed in GC mode
1010 RetainSel = GetNullarySelector("retain", CGM.getContext());
1011 ReleaseSel = GetNullarySelector("release", CGM.getContext());
1012 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
1014 // Get functions needed in GC mode
1016 // id objc_assign_ivar(id, id, ptrdiff_t);
1017 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy,
1019 // id objc_assign_strongCast (id, id*)
1020 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
1022 // id objc_assign_global(id, id*);
1023 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy,
1025 // id objc_assign_weak(id, id*);
1026 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy, NULL);
1027 // id objc_read_weak(id*);
1028 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy, NULL);
1029 // void *objc_memmove_collectable(void*, void *, size_t);
1030 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
1035 llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
1036 const std::string &Name,
1038 llvm::Value *ClassName = CGM.GetAddrOfConstantCString(Name);
1039 // With the incompatible ABI, this will need to be replaced with a direct
1040 // reference to the class symbol. For the compatible nonfragile ABI we are
1041 // still performing this lookup at run time but emitting the symbol for the
1042 // class externally so that we can make the switch later.
1044 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
1045 // with memoized versions or with static references if it's safe to do so.
1048 ClassName = CGF.Builder.CreateStructGEP(ClassName, 0);
1050 llvm::Constant *ClassLookupFn =
1051 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, PtrToInt8Ty, true),
1052 "objc_lookup_class");
1053 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
1056 // This has to perform the lookup every time, since posing and related
1057 // techniques can modify the name -> class mapping.
1058 llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
1059 const ObjCInterfaceDecl *OID) {
1060 return GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
1062 llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
1063 return GetClassNamed(CGF, "NSAutoreleasePool", false);
1066 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1067 const std::string &TypeEncoding, bool lval) {
1069 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
1070 llvm::GlobalAlias *SelValue = 0;
1073 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
1074 e = Types.end() ; i!=e ; i++) {
1075 if (i->first == TypeEncoding) {
1076 SelValue = i->second;
1080 if (0 == SelValue) {
1081 SelValue = new llvm::GlobalAlias(SelectorTy,
1082 llvm::GlobalValue::PrivateLinkage,
1083 ".objc_selector_"+Sel.getAsString(), NULL,
1085 Types.push_back(TypedSelector(TypeEncoding, SelValue));
1089 llvm::Value *tmp = CGF.CreateTempAlloca(SelValue->getType());
1090 CGF.Builder.CreateStore(SelValue, tmp);
1096 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel,
1098 return GetSelector(CGF, Sel, std::string(), lval);
1101 llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
1102 const ObjCMethodDecl *Method) {
1103 std::string SelTypes;
1104 CGM.getContext().getObjCEncodingForMethodDecl(Method, SelTypes);
1105 return GetSelector(CGF, Method->getSelector(), SelTypes, false);
1108 llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
1109 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
1110 // With the old ABI, there was only one kind of catchall, which broke
1111 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
1112 // a pointer indicating object catchalls, and NULL to indicate real
1114 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
1115 return MakeConstantString("@id");
1121 // All other types should be Objective-C interface pointer types.
1122 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
1123 assert(OPT && "Invalid @catch type.");
1124 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
1125 assert(IDecl && "Invalid @catch type.");
1126 return MakeConstantString(IDecl->getIdentifier()->getName());
1129 llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
1130 if (!CGM.getLangOpts().CPlusPlus)
1131 return CGObjCGNU::GetEHType(T);
1133 // For Objective-C++, we want to provide the ability to catch both C++ and
1134 // Objective-C objects in the same function.
1136 // There's a particular fixed type info for 'id'.
1137 if (T->isObjCIdType() ||
1138 T->isObjCQualifiedIdType()) {
1139 llvm::Constant *IDEHType =
1140 CGM.getModule().getGlobalVariable("__objc_id_type_info");
1143 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
1145 llvm::GlobalValue::ExternalLinkage,
1146 0, "__objc_id_type_info");
1147 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
1150 const ObjCObjectPointerType *PT =
1151 T->getAs<ObjCObjectPointerType>();
1152 assert(PT && "Invalid @catch type.");
1153 const ObjCInterfaceType *IT = PT->getInterfaceType();
1154 assert(IT && "Invalid @catch type.");
1155 std::string className = IT->getDecl()->getIdentifier()->getName();
1157 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
1159 // Return the existing typeinfo if it exists
1160 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
1162 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
1164 // Otherwise create it.
1166 // vtable for gnustep::libobjc::__objc_class_type_info
1167 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
1168 // platform's name mangling.
1169 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
1170 llvm::Constant *Vtable = TheModule.getGlobalVariable(vtableName);
1172 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
1173 llvm::GlobalValue::ExternalLinkage, 0, vtableName);
1175 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
1176 Vtable = llvm::ConstantExpr::getGetElementPtr(Vtable, Two);
1177 Vtable = llvm::ConstantExpr::getBitCast(Vtable, PtrToInt8Ty);
1179 llvm::Constant *typeName =
1180 ExportUniqueString(className, "__objc_eh_typename_");
1182 std::vector<llvm::Constant*> fields;
1183 fields.push_back(Vtable);
1184 fields.push_back(typeName);
1185 llvm::Constant *TI =
1186 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1187 NULL), fields, "__objc_eh_typeinfo_" + className,
1188 llvm::GlobalValue::LinkOnceODRLinkage);
1189 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
1192 /// Generate an NSConstantString object.
1193 llvm::Constant *CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
1195 std::string Str = SL->getString().str();
1197 // Look for an existing one
1198 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
1199 if (old != ObjCStrings.end())
1200 return old->getValue();
1202 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1204 if (StringClass.empty()) StringClass = "NXConstantString";
1206 std::string Sym = "_OBJC_CLASS_";
1209 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1212 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1213 llvm::GlobalValue::ExternalWeakLinkage, 0, Sym);
1214 else if (isa->getType() != PtrToIdTy)
1215 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1217 std::vector<llvm::Constant*> Ivars;
1218 Ivars.push_back(isa);
1219 Ivars.push_back(MakeConstantString(Str));
1220 Ivars.push_back(llvm::ConstantInt::get(IntTy, Str.size()));
1221 llvm::Constant *ObjCStr = MakeGlobal(
1222 llvm::StructType::get(PtrToIdTy, PtrToInt8Ty, IntTy, NULL),
1223 Ivars, ".objc_str");
1224 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
1225 ObjCStrings[Str] = ObjCStr;
1226 ConstantStrings.push_back(ObjCStr);
1230 ///Generates a message send where the super is the receiver. This is a message
1231 ///send to self with special delivery semantics indicating which class's method
1232 ///should be called.
1234 CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
1235 ReturnValueSlot Return,
1236 QualType ResultType,
1238 const ObjCInterfaceDecl *Class,
1239 bool isCategoryImpl,
1240 llvm::Value *Receiver,
1241 bool IsClassMessage,
1242 const CallArgList &CallArgs,
1243 const ObjCMethodDecl *Method) {
1244 CGBuilderTy &Builder = CGF.Builder;
1245 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1246 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1247 return RValue::get(EnforceType(Builder, Receiver,
1248 CGM.getTypes().ConvertType(ResultType)));
1250 if (Sel == ReleaseSel) {
1251 return RValue::get(0);
1255 llvm::Value *cmd = GetSelector(CGF, Sel);
1258 CallArgList ActualArgs;
1260 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
1261 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1262 ActualArgs.addFrom(CallArgs);
1264 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1266 llvm::Value *ReceiverClass = 0;
1267 if (isCategoryImpl) {
1268 llvm::Constant *classLookupFunction = 0;
1269 if (IsClassMessage) {
1270 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1271 IdTy, PtrTy, true), "objc_get_meta_class");
1273 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
1274 IdTy, PtrTy, true), "objc_get_class");
1276 ReceiverClass = Builder.CreateCall(classLookupFunction,
1277 MakeConstantString(Class->getNameAsString()));
1279 // Set up global aliases for the metaclass or class pointer if they do not
1280 // already exist. These will are forward-references which will be set to
1281 // pointers to the class and metaclass structure created for the runtime
1282 // load function. To send a message to super, we look up the value of the
1283 // super_class pointer from either the class or metaclass structure.
1284 if (IsClassMessage) {
1285 if (!MetaClassPtrAlias) {
1286 MetaClassPtrAlias = new llvm::GlobalAlias(IdTy,
1287 llvm::GlobalValue::InternalLinkage, ".objc_metaclass_ref" +
1288 Class->getNameAsString(), NULL, &TheModule);
1290 ReceiverClass = MetaClassPtrAlias;
1292 if (!ClassPtrAlias) {
1293 ClassPtrAlias = new llvm::GlobalAlias(IdTy,
1294 llvm::GlobalValue::InternalLinkage, ".objc_class_ref" +
1295 Class->getNameAsString(), NULL, &TheModule);
1297 ReceiverClass = ClassPtrAlias;
1300 // Cast the pointer to a simplified version of the class structure
1301 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
1302 llvm::PointerType::getUnqual(
1303 llvm::StructType::get(IdTy, IdTy, NULL)));
1304 // Get the superclass pointer
1305 ReceiverClass = Builder.CreateStructGEP(ReceiverClass, 1);
1306 // Load the superclass pointer
1307 ReceiverClass = Builder.CreateLoad(ReceiverClass);
1308 // Construct the structure used to look up the IMP
1309 llvm::StructType *ObjCSuperTy = llvm::StructType::get(
1310 Receiver->getType(), IdTy, NULL);
1311 llvm::Value *ObjCSuper = Builder.CreateAlloca(ObjCSuperTy);
1313 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
1314 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
1316 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
1319 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
1320 imp = EnforceType(Builder, imp, MSI.MessengerType);
1322 llvm::Value *impMD[] = {
1323 llvm::MDString::get(VMContext, Sel.getAsString()),
1324 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
1325 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), IsClassMessage)
1327 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1329 llvm::Instruction *call;
1330 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
1331 call->setMetadata(msgSendMDKind, node);
1335 /// Generate code for a message send expression.
1337 CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
1338 ReturnValueSlot Return,
1339 QualType ResultType,
1341 llvm::Value *Receiver,
1342 const CallArgList &CallArgs,
1343 const ObjCInterfaceDecl *Class,
1344 const ObjCMethodDecl *Method) {
1345 CGBuilderTy &Builder = CGF.Builder;
1347 // Strip out message sends to retain / release in GC mode
1348 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
1349 if (Sel == RetainSel || Sel == AutoreleaseSel) {
1350 return RValue::get(EnforceType(Builder, Receiver,
1351 CGM.getTypes().ConvertType(ResultType)));
1353 if (Sel == ReleaseSel) {
1354 return RValue::get(0);
1358 // If the return type is something that goes in an integer register, the
1359 // runtime will handle 0 returns. For other cases, we fill in the 0 value
1362 // The language spec says the result of this kind of message send is
1363 // undefined, but lots of people seem to have forgotten to read that
1364 // paragraph and insist on sending messages to nil that have structure
1365 // returns. With GCC, this generates a random return value (whatever happens
1366 // to be on the stack / in those registers at the time) on most platforms,
1367 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
1369 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
1370 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
1372 llvm::BasicBlock *startBB = 0;
1373 llvm::BasicBlock *messageBB = 0;
1374 llvm::BasicBlock *continueBB = 0;
1376 if (!isPointerSizedReturn) {
1377 startBB = Builder.GetInsertBlock();
1378 messageBB = CGF.createBasicBlock("msgSend");
1379 continueBB = CGF.createBasicBlock("continue");
1381 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
1382 llvm::Constant::getNullValue(Receiver->getType()));
1383 Builder.CreateCondBr(isNil, continueBB, messageBB);
1384 CGF.EmitBlock(messageBB);
1387 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
1390 cmd = GetSelector(CGF, Method);
1392 cmd = GetSelector(CGF, Sel);
1393 cmd = EnforceType(Builder, cmd, SelectorTy);
1394 Receiver = EnforceType(Builder, Receiver, IdTy);
1396 llvm::Value *impMD[] = {
1397 llvm::MDString::get(VMContext, Sel.getAsString()),
1398 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() :""),
1399 llvm::ConstantInt::get(llvm::Type::getInt1Ty(VMContext), Class!=0)
1401 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
1403 CallArgList ActualArgs;
1404 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
1405 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
1406 ActualArgs.addFrom(CallArgs);
1408 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
1410 // Get the IMP to call
1413 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
1414 // functions. These are not supported on all platforms (or all runtimes on a
1415 // given platform), so we
1416 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
1417 case CodeGenOptions::Legacy:
1418 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
1420 case CodeGenOptions::Mixed:
1421 case CodeGenOptions::NonLegacy:
1422 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
1423 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1424 "objc_msgSend_fpret");
1425 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
1426 // The actual types here don't matter - we're going to bitcast the
1428 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1429 "objc_msgSend_stret");
1431 imp = CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
1436 // Reset the receiver in case the lookup modified it
1437 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy, false);
1439 imp = EnforceType(Builder, imp, MSI.MessengerType);
1441 llvm::Instruction *call;
1442 RValue msgRet = CGF.EmitCall(MSI.CallInfo, imp, Return, ActualArgs, 0, &call);
1443 call->setMetadata(msgSendMDKind, node);
1446 if (!isPointerSizedReturn) {
1447 messageBB = CGF.Builder.GetInsertBlock();
1448 CGF.Builder.CreateBr(continueBB);
1449 CGF.EmitBlock(continueBB);
1450 if (msgRet.isScalar()) {
1451 llvm::Value *v = msgRet.getScalarVal();
1452 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1453 phi->addIncoming(v, messageBB);
1454 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
1455 msgRet = RValue::get(phi);
1456 } else if (msgRet.isAggregate()) {
1457 llvm::Value *v = msgRet.getAggregateAddr();
1458 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
1459 llvm::PointerType *RetTy = cast<llvm::PointerType>(v->getType());
1460 llvm::AllocaInst *NullVal =
1461 CGF.CreateTempAlloca(RetTy->getElementType(), "null");
1462 CGF.InitTempAlloca(NullVal,
1463 llvm::Constant::getNullValue(RetTy->getElementType()));
1464 phi->addIncoming(v, messageBB);
1465 phi->addIncoming(NullVal, startBB);
1466 msgRet = RValue::getAggregate(phi);
1467 } else /* isComplex() */ {
1468 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
1469 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
1470 phi->addIncoming(v.first, messageBB);
1471 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
1473 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
1474 phi2->addIncoming(v.second, messageBB);
1475 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
1477 msgRet = RValue::getComplex(phi, phi2);
1483 /// Generates a MethodList. Used in construction of a objc_class and
1484 /// objc_category structures.
1485 llvm::Constant *CGObjCGNU::
1486 GenerateMethodList(const StringRef &ClassName,
1487 const StringRef &CategoryName,
1488 ArrayRef<Selector> MethodSels,
1489 ArrayRef<llvm::Constant *> MethodTypes,
1490 bool isClassMethodList) {
1491 if (MethodSels.empty())
1493 // Get the method structure type.
1494 llvm::StructType *ObjCMethodTy = llvm::StructType::get(
1495 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
1496 PtrToInt8Ty, // Method types
1497 IMPTy, //Method pointer
1499 std::vector<llvm::Constant*> Methods;
1500 std::vector<llvm::Constant*> Elements;
1501 for (unsigned int i = 0, e = MethodTypes.size(); i < e; ++i) {
1503 llvm::Constant *Method =
1504 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
1506 isClassMethodList));
1507 assert(Method && "Can't generate metadata for method that doesn't exist");
1508 llvm::Constant *C = MakeConstantString(MethodSels[i].getAsString());
1509 Elements.push_back(C);
1510 Elements.push_back(MethodTypes[i]);
1511 Method = llvm::ConstantExpr::getBitCast(Method,
1513 Elements.push_back(Method);
1514 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodTy, Elements));
1517 // Array of method structures
1518 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodTy,
1520 llvm::Constant *MethodArray = llvm::ConstantArray::get(ObjCMethodArrayTy,
1523 // Structure containing list pointer, array and array count
1524 llvm::StructType *ObjCMethodListTy = llvm::StructType::create(VMContext);
1525 llvm::Type *NextPtrTy = llvm::PointerType::getUnqual(ObjCMethodListTy);
1526 ObjCMethodListTy->setBody(
1533 Methods.push_back(llvm::ConstantPointerNull::get(
1534 llvm::PointerType::getUnqual(ObjCMethodListTy)));
1535 Methods.push_back(llvm::ConstantInt::get(Int32Ty, MethodTypes.size()));
1536 Methods.push_back(MethodArray);
1538 // Create an instance of the structure
1539 return MakeGlobal(ObjCMethodListTy, Methods, ".objc_method_list");
1542 /// Generates an IvarList. Used in construction of a objc_class.
1543 llvm::Constant *CGObjCGNU::
1544 GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1545 ArrayRef<llvm::Constant *> IvarTypes,
1546 ArrayRef<llvm::Constant *> IvarOffsets) {
1547 if (IvarNames.size() == 0)
1549 // Get the method structure type.
1550 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1555 std::vector<llvm::Constant*> Ivars;
1556 std::vector<llvm::Constant*> Elements;
1557 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
1559 Elements.push_back(IvarNames[i]);
1560 Elements.push_back(IvarTypes[i]);
1561 Elements.push_back(IvarOffsets[i]);
1562 Ivars.push_back(llvm::ConstantStruct::get(ObjCIvarTy, Elements));
1565 // Array of method structures
1566 llvm::ArrayType *ObjCIvarArrayTy = llvm::ArrayType::get(ObjCIvarTy,
1571 Elements.push_back(llvm::ConstantInt::get(IntTy, (int)IvarNames.size()));
1572 Elements.push_back(llvm::ConstantArray::get(ObjCIvarArrayTy, Ivars));
1573 // Structure containing array and array count
1574 llvm::StructType *ObjCIvarListTy = llvm::StructType::get(IntTy,
1578 // Create an instance of the structure
1579 return MakeGlobal(ObjCIvarListTy, Elements, ".objc_ivar_list");
1582 /// Generate a class structure
1583 llvm::Constant *CGObjCGNU::GenerateClassStructure(
1584 llvm::Constant *MetaClass,
1585 llvm::Constant *SuperClass,
1588 llvm::Constant *Version,
1589 llvm::Constant *InstanceSize,
1590 llvm::Constant *IVars,
1591 llvm::Constant *Methods,
1592 llvm::Constant *Protocols,
1593 llvm::Constant *IvarOffsets,
1594 llvm::Constant *Properties,
1595 llvm::Constant *StrongIvarBitmap,
1596 llvm::Constant *WeakIvarBitmap,
1598 // Set up the class structure
1599 // Note: Several of these are char*s when they should be ids. This is
1600 // because the runtime performs this translation on load.
1602 // Fields marked New ABI are part of the GNUstep runtime. We emit them
1603 // anyway; the classes will still work with the GNU runtime, they will just
1605 llvm::StructType *ClassTy = llvm::StructType::get(
1607 PtrToInt8Ty, // super_class
1608 PtrToInt8Ty, // name
1611 LongTy, // instance_size
1612 IVars->getType(), // ivars
1613 Methods->getType(), // methods
1614 // These are all filled in by the runtime, so we pretend
1616 PtrTy, // subclass_list
1617 PtrTy, // sibling_class
1619 PtrTy, // gc_object_type
1621 LongTy, // abi_version
1622 IvarOffsets->getType(), // ivar_offsets
1623 Properties->getType(), // properties
1624 IntPtrTy, // strong_pointers
1625 IntPtrTy, // weak_pointers
1627 llvm::Constant *Zero = llvm::ConstantInt::get(LongTy, 0);
1628 // Fill in the structure
1629 std::vector<llvm::Constant*> Elements;
1630 Elements.push_back(llvm::ConstantExpr::getBitCast(MetaClass, PtrToInt8Ty));
1631 Elements.push_back(SuperClass);
1632 Elements.push_back(MakeConstantString(Name, ".class_name"));
1633 Elements.push_back(Zero);
1634 Elements.push_back(llvm::ConstantInt::get(LongTy, info));
1636 llvm::DataLayout td(&TheModule);
1638 llvm::ConstantInt::get(LongTy,
1639 td.getTypeSizeInBits(ClassTy) /
1640 CGM.getContext().getCharWidth()));
1642 Elements.push_back(InstanceSize);
1643 Elements.push_back(IVars);
1644 Elements.push_back(Methods);
1645 Elements.push_back(NULLPtr);
1646 Elements.push_back(NULLPtr);
1647 Elements.push_back(NULLPtr);
1648 Elements.push_back(llvm::ConstantExpr::getBitCast(Protocols, PtrTy));
1649 Elements.push_back(NULLPtr);
1650 Elements.push_back(llvm::ConstantInt::get(LongTy, 1));
1651 Elements.push_back(IvarOffsets);
1652 Elements.push_back(Properties);
1653 Elements.push_back(StrongIvarBitmap);
1654 Elements.push_back(WeakIvarBitmap);
1655 // Create an instance of the structure
1656 // This is now an externally visible symbol, so that we can speed up class
1657 // messages in the next ABI. We may already have some weak references to
1658 // this, so check and fix them properly.
1659 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
1661 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
1662 llvm::Constant *Class = MakeGlobal(ClassTy, Elements, ClassSym,
1663 llvm::GlobalValue::ExternalLinkage);
1665 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
1666 ClassRef->getType()));
1667 ClassRef->removeFromParent();
1668 Class->setName(ClassSym);
1673 llvm::Constant *CGObjCGNU::
1674 GenerateProtocolMethodList(ArrayRef<llvm::Constant *> MethodNames,
1675 ArrayRef<llvm::Constant *> MethodTypes) {
1676 // Get the method structure type.
1677 llvm::StructType *ObjCMethodDescTy = llvm::StructType::get(
1678 PtrToInt8Ty, // Really a selector, but the runtime does the casting for us.
1681 std::vector<llvm::Constant*> Methods;
1682 std::vector<llvm::Constant*> Elements;
1683 for (unsigned int i = 0, e = MethodTypes.size() ; i < e ; i++) {
1685 Elements.push_back(MethodNames[i]);
1686 Elements.push_back(MethodTypes[i]);
1687 Methods.push_back(llvm::ConstantStruct::get(ObjCMethodDescTy, Elements));
1689 llvm::ArrayType *ObjCMethodArrayTy = llvm::ArrayType::get(ObjCMethodDescTy,
1690 MethodNames.size());
1691 llvm::Constant *Array = llvm::ConstantArray::get(ObjCMethodArrayTy,
1693 llvm::StructType *ObjCMethodDescListTy = llvm::StructType::get(
1694 IntTy, ObjCMethodArrayTy, NULL);
1696 Methods.push_back(llvm::ConstantInt::get(IntTy, MethodNames.size()));
1697 Methods.push_back(Array);
1698 return MakeGlobal(ObjCMethodDescListTy, Methods, ".objc_method_list");
1701 // Create the protocol list structure used in classes, categories and so on
1702 llvm::Constant *CGObjCGNU::GenerateProtocolList(ArrayRef<std::string>Protocols){
1703 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
1705 llvm::StructType *ProtocolListTy = llvm::StructType::get(
1706 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1710 std::vector<llvm::Constant*> Elements;
1711 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
1712 iter != endIter ; iter++) {
1713 llvm::Constant *protocol = 0;
1714 llvm::StringMap<llvm::Constant*>::iterator value =
1715 ExistingProtocols.find(*iter);
1716 if (value == ExistingProtocols.end()) {
1717 protocol = GenerateEmptyProtocol(*iter);
1719 protocol = value->getValue();
1721 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(protocol,
1723 Elements.push_back(Ptr);
1725 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1728 Elements.push_back(NULLPtr);
1729 Elements.push_back(llvm::ConstantInt::get(LongTy, Protocols.size()));
1730 Elements.push_back(ProtocolArray);
1731 return MakeGlobal(ProtocolListTy, Elements, ".objc_protocol_list");
1734 llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
1735 const ObjCProtocolDecl *PD) {
1736 llvm::Value *protocol = ExistingProtocols[PD->getNameAsString()];
1738 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
1739 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
1742 llvm::Constant *CGObjCGNU::GenerateEmptyProtocol(
1743 const std::string &ProtocolName) {
1744 SmallVector<std::string, 0> EmptyStringVector;
1745 SmallVector<llvm::Constant*, 0> EmptyConstantVector;
1747 llvm::Constant *ProtocolList = GenerateProtocolList(EmptyStringVector);
1748 llvm::Constant *MethodList =
1749 GenerateProtocolMethodList(EmptyConstantVector, EmptyConstantVector);
1750 // Protocols are objects containing lists of the methods implemented and
1751 // protocols adopted.
1752 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1754 ProtocolList->getType(),
1755 MethodList->getType(),
1756 MethodList->getType(),
1757 MethodList->getType(),
1758 MethodList->getType(),
1760 std::vector<llvm::Constant*> Elements;
1761 // The isa pointer must be set to a magic number so the runtime knows it's
1762 // the correct layout.
1763 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1764 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1765 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1766 Elements.push_back(ProtocolList);
1767 Elements.push_back(MethodList);
1768 Elements.push_back(MethodList);
1769 Elements.push_back(MethodList);
1770 Elements.push_back(MethodList);
1771 return MakeGlobal(ProtocolTy, Elements, ".objc_protocol");
1774 void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
1775 ASTContext &Context = CGM.getContext();
1776 std::string ProtocolName = PD->getNameAsString();
1778 // Use the protocol definition, if there is one.
1779 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1782 SmallVector<std::string, 16> Protocols;
1783 for (ObjCProtocolDecl::protocol_iterator PI = PD->protocol_begin(),
1784 E = PD->protocol_end(); PI != E; ++PI)
1785 Protocols.push_back((*PI)->getNameAsString());
1786 SmallVector<llvm::Constant*, 16> InstanceMethodNames;
1787 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
1788 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodNames;
1789 SmallVector<llvm::Constant*, 16> OptionalInstanceMethodTypes;
1790 for (ObjCProtocolDecl::instmeth_iterator iter = PD->instmeth_begin(),
1791 E = PD->instmeth_end(); iter != E; iter++) {
1792 std::string TypeStr;
1793 Context.getObjCEncodingForMethodDecl(*iter, TypeStr);
1794 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1795 OptionalInstanceMethodNames.push_back(
1796 MakeConstantString((*iter)->getSelector().getAsString()));
1797 OptionalInstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1799 InstanceMethodNames.push_back(
1800 MakeConstantString((*iter)->getSelector().getAsString()));
1801 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
1804 // Collect information about class methods:
1805 SmallVector<llvm::Constant*, 16> ClassMethodNames;
1806 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
1807 SmallVector<llvm::Constant*, 16> OptionalClassMethodNames;
1808 SmallVector<llvm::Constant*, 16> OptionalClassMethodTypes;
1809 for (ObjCProtocolDecl::classmeth_iterator
1810 iter = PD->classmeth_begin(), endIter = PD->classmeth_end();
1811 iter != endIter ; iter++) {
1812 std::string TypeStr;
1813 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
1814 if ((*iter)->getImplementationControl() == ObjCMethodDecl::Optional) {
1815 OptionalClassMethodNames.push_back(
1816 MakeConstantString((*iter)->getSelector().getAsString()));
1817 OptionalClassMethodTypes.push_back(MakeConstantString(TypeStr));
1819 ClassMethodNames.push_back(
1820 MakeConstantString((*iter)->getSelector().getAsString()));
1821 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
1825 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1826 llvm::Constant *InstanceMethodList =
1827 GenerateProtocolMethodList(InstanceMethodNames, InstanceMethodTypes);
1828 llvm::Constant *ClassMethodList =
1829 GenerateProtocolMethodList(ClassMethodNames, ClassMethodTypes);
1830 llvm::Constant *OptionalInstanceMethodList =
1831 GenerateProtocolMethodList(OptionalInstanceMethodNames,
1832 OptionalInstanceMethodTypes);
1833 llvm::Constant *OptionalClassMethodList =
1834 GenerateProtocolMethodList(OptionalClassMethodNames,
1835 OptionalClassMethodTypes);
1837 // Property metadata: name, attributes, isSynthesized, setter name, setter
1838 // types, getter name, getter types.
1839 // The isSynthesized value is always set to 0 in a protocol. It exists to
1840 // simplify the runtime library by allowing it to use the same data
1841 // structures for protocol metadata everywhere.
1842 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
1843 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
1844 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
1845 std::vector<llvm::Constant*> Properties;
1846 std::vector<llvm::Constant*> OptionalProperties;
1848 // Add all of the property methods need adding to the method list and to the
1849 // property metadata list.
1850 for (ObjCContainerDecl::prop_iterator
1851 iter = PD->prop_begin(), endIter = PD->prop_end();
1852 iter != endIter ; iter++) {
1853 std::vector<llvm::Constant*> Fields;
1854 ObjCPropertyDecl *property = *iter;
1856 Fields.push_back(MakePropertyEncodingString(property, 0));
1857 PushPropertyAttributes(Fields, property);
1859 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
1860 std::string TypeStr;
1861 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
1862 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1863 InstanceMethodTypes.push_back(TypeEncoding);
1864 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
1865 Fields.push_back(TypeEncoding);
1867 Fields.push_back(NULLPtr);
1868 Fields.push_back(NULLPtr);
1870 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
1871 std::string TypeStr;
1872 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
1873 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
1874 InstanceMethodTypes.push_back(TypeEncoding);
1875 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
1876 Fields.push_back(TypeEncoding);
1878 Fields.push_back(NULLPtr);
1879 Fields.push_back(NULLPtr);
1881 if (property->getPropertyImplementation() == ObjCPropertyDecl::Optional) {
1882 OptionalProperties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1884 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
1887 llvm::Constant *PropertyArray = llvm::ConstantArray::get(
1888 llvm::ArrayType::get(PropertyMetadataTy, Properties.size()), Properties);
1889 llvm::Constant* PropertyListInitFields[] =
1890 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
1892 llvm::Constant *PropertyListInit =
1893 llvm::ConstantStruct::getAnon(PropertyListInitFields);
1894 llvm::Constant *PropertyList = new llvm::GlobalVariable(TheModule,
1895 PropertyListInit->getType(), false, llvm::GlobalValue::InternalLinkage,
1896 PropertyListInit, ".objc_property_list");
1898 llvm::Constant *OptionalPropertyArray =
1899 llvm::ConstantArray::get(llvm::ArrayType::get(PropertyMetadataTy,
1900 OptionalProperties.size()) , OptionalProperties);
1901 llvm::Constant* OptionalPropertyListInitFields[] = {
1902 llvm::ConstantInt::get(IntTy, OptionalProperties.size()), NULLPtr,
1903 OptionalPropertyArray };
1905 llvm::Constant *OptionalPropertyListInit =
1906 llvm::ConstantStruct::getAnon(OptionalPropertyListInitFields);
1907 llvm::Constant *OptionalPropertyList = new llvm::GlobalVariable(TheModule,
1908 OptionalPropertyListInit->getType(), false,
1909 llvm::GlobalValue::InternalLinkage, OptionalPropertyListInit,
1910 ".objc_property_list");
1912 // Protocols are objects containing lists of the methods implemented and
1913 // protocols adopted.
1914 llvm::StructType *ProtocolTy = llvm::StructType::get(IdTy,
1916 ProtocolList->getType(),
1917 InstanceMethodList->getType(),
1918 ClassMethodList->getType(),
1919 OptionalInstanceMethodList->getType(),
1920 OptionalClassMethodList->getType(),
1921 PropertyList->getType(),
1922 OptionalPropertyList->getType(),
1924 std::vector<llvm::Constant*> Elements;
1925 // The isa pointer must be set to a magic number so the runtime knows it's
1926 // the correct layout.
1927 Elements.push_back(llvm::ConstantExpr::getIntToPtr(
1928 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1929 Elements.push_back(MakeConstantString(ProtocolName, ".objc_protocol_name"));
1930 Elements.push_back(ProtocolList);
1931 Elements.push_back(InstanceMethodList);
1932 Elements.push_back(ClassMethodList);
1933 Elements.push_back(OptionalInstanceMethodList);
1934 Elements.push_back(OptionalClassMethodList);
1935 Elements.push_back(PropertyList);
1936 Elements.push_back(OptionalPropertyList);
1937 ExistingProtocols[ProtocolName] =
1938 llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolTy, Elements,
1939 ".objc_protocol"), IdTy);
1941 void CGObjCGNU::GenerateProtocolHolderCategory() {
1942 // Collect information about instance methods
1943 SmallVector<Selector, 1> MethodSels;
1944 SmallVector<llvm::Constant*, 1> MethodTypes;
1946 std::vector<llvm::Constant*> Elements;
1947 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
1948 const std::string CategoryName = "AnotherHack";
1949 Elements.push_back(MakeConstantString(CategoryName));
1950 Elements.push_back(MakeConstantString(ClassName));
1951 // Instance method list
1952 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1953 ClassName, CategoryName, MethodSels, MethodTypes, false), PtrTy));
1954 // Class method list
1955 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
1956 ClassName, CategoryName, MethodSels, MethodTypes, true), PtrTy));
1958 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(PtrTy,
1959 ExistingProtocols.size());
1960 llvm::StructType *ProtocolListTy = llvm::StructType::get(
1961 PtrTy, //Should be a recurisve pointer, but it's always NULL here.
1965 std::vector<llvm::Constant*> ProtocolElements;
1966 for (llvm::StringMapIterator<llvm::Constant*> iter =
1967 ExistingProtocols.begin(), endIter = ExistingProtocols.end();
1968 iter != endIter ; iter++) {
1969 llvm::Constant *Ptr = llvm::ConstantExpr::getBitCast(iter->getValue(),
1971 ProtocolElements.push_back(Ptr);
1973 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1975 ProtocolElements.clear();
1976 ProtocolElements.push_back(NULLPtr);
1977 ProtocolElements.push_back(llvm::ConstantInt::get(LongTy,
1978 ExistingProtocols.size()));
1979 ProtocolElements.push_back(ProtocolArray);
1980 Elements.push_back(llvm::ConstantExpr::getBitCast(MakeGlobal(ProtocolListTy,
1981 ProtocolElements, ".objc_protocol_list"), PtrTy));
1982 Categories.push_back(llvm::ConstantExpr::getBitCast(
1983 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
1984 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
1987 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
1988 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
1989 /// bits set to their values, LSB first, while larger ones are stored in a
1990 /// structure of this / form:
1992 /// struct { int32_t length; int32_t values[length]; };
1994 /// The values in the array are stored in host-endian format, with the least
1995 /// significant bit being assumed to come first in the bitfield. Therefore, a
1996 /// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
1997 /// bitfield / with the 63rd bit set will be 1<<64.
1998 llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
1999 int bitCount = bits.size();
2000 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
2001 if (bitCount < ptrBits) {
2003 for (int i=0 ; i<bitCount ; ++i) {
2004 if (bits[i]) val |= 1ULL<<(i+1);
2006 return llvm::ConstantInt::get(IntPtrTy, val);
2008 SmallVector<llvm::Constant *, 8> values;
2010 while (v < bitCount) {
2012 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
2013 if (bits[v]) word |= 1<<i;
2016 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
2018 llvm::ArrayType *arrayTy = llvm::ArrayType::get(Int32Ty, values.size());
2019 llvm::Constant *array = llvm::ConstantArray::get(arrayTy, values);
2020 llvm::Constant *fields[2] = {
2021 llvm::ConstantInt::get(Int32Ty, values.size()),
2023 llvm::Constant *GS = MakeGlobal(llvm::StructType::get(Int32Ty, arrayTy,
2025 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
2029 void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
2030 std::string ClassName = OCD->getClassInterface()->getNameAsString();
2031 std::string CategoryName = OCD->getNameAsString();
2032 // Collect information about instance methods
2033 SmallVector<Selector, 16> InstanceMethodSels;
2034 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2035 for (ObjCCategoryImplDecl::instmeth_iterator
2036 iter = OCD->instmeth_begin(), endIter = OCD->instmeth_end();
2037 iter != endIter ; iter++) {
2038 InstanceMethodSels.push_back((*iter)->getSelector());
2039 std::string TypeStr;
2040 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
2041 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2044 // Collect information about class methods
2045 SmallVector<Selector, 16> ClassMethodSels;
2046 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2047 for (ObjCCategoryImplDecl::classmeth_iterator
2048 iter = OCD->classmeth_begin(), endIter = OCD->classmeth_end();
2049 iter != endIter ; iter++) {
2050 ClassMethodSels.push_back((*iter)->getSelector());
2051 std::string TypeStr;
2052 CGM.getContext().getObjCEncodingForMethodDecl(*iter,TypeStr);
2053 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2056 // Collect the names of referenced protocols
2057 SmallVector<std::string, 16> Protocols;
2058 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
2059 const ObjCList<ObjCProtocolDecl> &Protos = CatDecl->getReferencedProtocols();
2060 for (ObjCList<ObjCProtocolDecl>::iterator I = Protos.begin(),
2061 E = Protos.end(); I != E; ++I)
2062 Protocols.push_back((*I)->getNameAsString());
2064 std::vector<llvm::Constant*> Elements;
2065 Elements.push_back(MakeConstantString(CategoryName));
2066 Elements.push_back(MakeConstantString(ClassName));
2067 // Instance method list
2068 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
2069 ClassName, CategoryName, InstanceMethodSels, InstanceMethodTypes,
2071 // Class method list
2072 Elements.push_back(llvm::ConstantExpr::getBitCast(GenerateMethodList(
2073 ClassName, CategoryName, ClassMethodSels, ClassMethodTypes, true),
2076 Elements.push_back(llvm::ConstantExpr::getBitCast(
2077 GenerateProtocolList(Protocols), PtrTy));
2078 Categories.push_back(llvm::ConstantExpr::getBitCast(
2079 MakeGlobal(llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty,
2080 PtrTy, PtrTy, PtrTy, NULL), Elements), PtrTy));
2083 llvm::Constant *CGObjCGNU::GeneratePropertyList(const ObjCImplementationDecl *OID,
2084 SmallVectorImpl<Selector> &InstanceMethodSels,
2085 SmallVectorImpl<llvm::Constant*> &InstanceMethodTypes) {
2086 ASTContext &Context = CGM.getContext();
2087 // Property metadata: name, attributes, attributes2, padding1, padding2,
2088 // setter name, setter types, getter name, getter types.
2089 llvm::StructType *PropertyMetadataTy = llvm::StructType::get(
2090 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty,
2091 PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, NULL);
2092 std::vector<llvm::Constant*> Properties;
2094 // Add all of the property methods need adding to the method list and to the
2095 // property metadata list.
2096 for (ObjCImplDecl::propimpl_iterator
2097 iter = OID->propimpl_begin(), endIter = OID->propimpl_end();
2098 iter != endIter ; iter++) {
2099 std::vector<llvm::Constant*> Fields;
2100 ObjCPropertyDecl *property = iter->getPropertyDecl();
2101 ObjCPropertyImplDecl *propertyImpl = *iter;
2102 bool isSynthesized = (propertyImpl->getPropertyImplementation() ==
2103 ObjCPropertyImplDecl::Synthesize);
2104 bool isDynamic = (propertyImpl->getPropertyImplementation() ==
2105 ObjCPropertyImplDecl::Dynamic);
2107 Fields.push_back(MakePropertyEncodingString(property, OID));
2108 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
2109 if (ObjCMethodDecl *getter = property->getGetterMethodDecl()) {
2110 std::string TypeStr;
2111 Context.getObjCEncodingForMethodDecl(getter,TypeStr);
2112 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2113 if (isSynthesized) {
2114 InstanceMethodTypes.push_back(TypeEncoding);
2115 InstanceMethodSels.push_back(getter->getSelector());
2117 Fields.push_back(MakeConstantString(getter->getSelector().getAsString()));
2118 Fields.push_back(TypeEncoding);
2120 Fields.push_back(NULLPtr);
2121 Fields.push_back(NULLPtr);
2123 if (ObjCMethodDecl *setter = property->getSetterMethodDecl()) {
2124 std::string TypeStr;
2125 Context.getObjCEncodingForMethodDecl(setter,TypeStr);
2126 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
2127 if (isSynthesized) {
2128 InstanceMethodTypes.push_back(TypeEncoding);
2129 InstanceMethodSels.push_back(setter->getSelector());
2131 Fields.push_back(MakeConstantString(setter->getSelector().getAsString()));
2132 Fields.push_back(TypeEncoding);
2134 Fields.push_back(NULLPtr);
2135 Fields.push_back(NULLPtr);
2137 Properties.push_back(llvm::ConstantStruct::get(PropertyMetadataTy, Fields));
2139 llvm::ArrayType *PropertyArrayTy =
2140 llvm::ArrayType::get(PropertyMetadataTy, Properties.size());
2141 llvm::Constant *PropertyArray = llvm::ConstantArray::get(PropertyArrayTy,
2143 llvm::Constant* PropertyListInitFields[] =
2144 {llvm::ConstantInt::get(IntTy, Properties.size()), NULLPtr, PropertyArray};
2146 llvm::Constant *PropertyListInit =
2147 llvm::ConstantStruct::getAnon(PropertyListInitFields);
2148 return new llvm::GlobalVariable(TheModule, PropertyListInit->getType(), false,
2149 llvm::GlobalValue::InternalLinkage, PropertyListInit,
2150 ".objc_property_list");
2153 void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
2154 // Get the class declaration for which the alias is specified.
2155 ObjCInterfaceDecl *ClassDecl =
2156 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
2157 std::string ClassName = ClassDecl->getNameAsString();
2158 std::string AliasName = OAD->getNameAsString();
2159 ClassAliases.push_back(ClassAliasPair(ClassName,AliasName));
2162 void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
2163 ASTContext &Context = CGM.getContext();
2165 // Get the superclass name.
2166 const ObjCInterfaceDecl * SuperClassDecl =
2167 OID->getClassInterface()->getSuperClass();
2168 std::string SuperClassName;
2169 if (SuperClassDecl) {
2170 SuperClassName = SuperClassDecl->getNameAsString();
2171 EmitClassRef(SuperClassName);
2174 // Get the class name
2175 ObjCInterfaceDecl *ClassDecl =
2176 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
2177 std::string ClassName = ClassDecl->getNameAsString();
2178 // Emit the symbol that is used to generate linker errors if this class is
2179 // referenced in other modules but not declared.
2180 std::string classSymbolName = "__objc_class_name_" + ClassName;
2181 if (llvm::GlobalVariable *symbol =
2182 TheModule.getGlobalVariable(classSymbolName)) {
2183 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
2185 new llvm::GlobalVariable(TheModule, LongTy, false,
2186 llvm::GlobalValue::ExternalLinkage, llvm::ConstantInt::get(LongTy, 0),
2190 // Get the size of instances.
2192 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
2194 // Collect information about instance variables.
2195 SmallVector<llvm::Constant*, 16> IvarNames;
2196 SmallVector<llvm::Constant*, 16> IvarTypes;
2197 SmallVector<llvm::Constant*, 16> IvarOffsets;
2199 std::vector<llvm::Constant*> IvarOffsetValues;
2200 SmallVector<bool, 16> WeakIvars;
2201 SmallVector<bool, 16> StrongIvars;
2203 int superInstanceSize = !SuperClassDecl ? 0 :
2204 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
2205 // For non-fragile ivars, set the instance size to 0 - {the size of just this
2206 // class}. The runtime will then set this to the correct value on load.
2207 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2208 instanceSize = 0 - (instanceSize - superInstanceSize);
2211 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2212 IVD = IVD->getNextIvar()) {
2214 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
2215 // Get the type encoding for this ivar
2216 std::string TypeStr;
2217 Context.getObjCEncodingForType(IVD->getType(), TypeStr);
2218 IvarTypes.push_back(MakeConstantString(TypeStr));
2220 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
2221 uint64_t Offset = BaseOffset;
2222 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2223 Offset = BaseOffset - superInstanceSize;
2225 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
2226 // Create the direct offset value
2227 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
2228 IVD->getNameAsString();
2229 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
2231 OffsetVar->setInitializer(OffsetValue);
2232 // If this is the real definition, change its linkage type so that
2233 // different modules will use this one, rather than their private
2235 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
2237 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
2238 false, llvm::GlobalValue::ExternalLinkage,
2240 "__objc_ivar_offset_value_" + ClassName +"." +
2241 IVD->getNameAsString());
2242 IvarOffsets.push_back(OffsetValue);
2243 IvarOffsetValues.push_back(OffsetVar);
2244 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
2246 case Qualifiers::OCL_Strong:
2247 StrongIvars.push_back(true);
2248 WeakIvars.push_back(false);
2250 case Qualifiers::OCL_Weak:
2251 StrongIvars.push_back(false);
2252 WeakIvars.push_back(true);
2255 StrongIvars.push_back(false);
2256 WeakIvars.push_back(false);
2259 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
2260 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
2261 llvm::GlobalVariable *IvarOffsetArray =
2262 MakeGlobalArray(PtrToIntTy, IvarOffsetValues, ".ivar.offsets");
2265 // Collect information about instance methods
2266 SmallVector<Selector, 16> InstanceMethodSels;
2267 SmallVector<llvm::Constant*, 16> InstanceMethodTypes;
2268 for (ObjCImplementationDecl::instmeth_iterator
2269 iter = OID->instmeth_begin(), endIter = OID->instmeth_end();
2270 iter != endIter ; iter++) {
2271 InstanceMethodSels.push_back((*iter)->getSelector());
2272 std::string TypeStr;
2273 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
2274 InstanceMethodTypes.push_back(MakeConstantString(TypeStr));
2277 llvm::Constant *Properties = GeneratePropertyList(OID, InstanceMethodSels,
2278 InstanceMethodTypes);
2281 // Collect information about class methods
2282 SmallVector<Selector, 16> ClassMethodSels;
2283 SmallVector<llvm::Constant*, 16> ClassMethodTypes;
2284 for (ObjCImplementationDecl::classmeth_iterator
2285 iter = OID->classmeth_begin(), endIter = OID->classmeth_end();
2286 iter != endIter ; iter++) {
2287 ClassMethodSels.push_back((*iter)->getSelector());
2288 std::string TypeStr;
2289 Context.getObjCEncodingForMethodDecl((*iter),TypeStr);
2290 ClassMethodTypes.push_back(MakeConstantString(TypeStr));
2292 // Collect the names of referenced protocols
2293 SmallVector<std::string, 16> Protocols;
2294 for (ObjCInterfaceDecl::protocol_iterator
2295 I = ClassDecl->protocol_begin(),
2296 E = ClassDecl->protocol_end(); I != E; ++I)
2297 Protocols.push_back((*I)->getNameAsString());
2301 // Get the superclass pointer.
2302 llvm::Constant *SuperClass;
2303 if (!SuperClassName.empty()) {
2304 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
2306 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2308 // Empty vector used to construct empty method lists
2309 SmallVector<llvm::Constant*, 1> empty;
2310 // Generate the method and instance variable lists
2311 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
2312 InstanceMethodSels, InstanceMethodTypes, false);
2313 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
2314 ClassMethodSels, ClassMethodTypes, true);
2315 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
2317 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
2318 // we emit a symbol containing the offset for each ivar in the class. This
2319 // allows code compiled for the non-Fragile ABI to inherit from code compiled
2320 // for the legacy ABI, without causing problems. The converse is also
2321 // possible, but causes all ivar accesses to be fragile.
2323 // Offset pointer for getting at the correct field in the ivar list when
2324 // setting up the alias. These are: The base address for the global, the
2325 // ivar array (second field), the ivar in this list (set for each ivar), and
2326 // the offset (third field in ivar structure)
2327 llvm::Type *IndexTy = Int32Ty;
2328 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
2329 llvm::ConstantInt::get(IndexTy, 1), 0,
2330 llvm::ConstantInt::get(IndexTy, 2) };
2332 unsigned ivarIndex = 0;
2333 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
2334 IVD = IVD->getNextIvar()) {
2335 const std::string Name = "__objc_ivar_offset_" + ClassName + '.'
2336 + IVD->getNameAsString();
2337 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
2338 // Get the correct ivar field
2339 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
2340 IvarList, offsetPointerIndexes);
2341 // Get the existing variable, if one exists.
2342 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
2344 offset->setInitializer(offsetValue);
2345 // If this is the real definition, change its linkage type so that
2346 // different modules will use this one, rather than their private
2348 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
2350 // Add a new alias if there isn't one already.
2351 offset = new llvm::GlobalVariable(TheModule, offsetValue->getType(),
2352 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
2353 (void) offset; // Silence dead store warning.
2357 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
2358 //Generate metaclass for class methods
2359 llvm::Constant *MetaClassStruct = GenerateClassStructure(NULLPtr,
2360 NULLPtr, 0x12L, ClassName.c_str(), 0, Zeros[0], GenerateIvarList(
2361 empty, empty, empty), ClassMethodList, NULLPtr,
2362 NULLPtr, NULLPtr, ZeroPtr, ZeroPtr, true);
2364 // Generate the class structure
2365 llvm::Constant *ClassStruct =
2366 GenerateClassStructure(MetaClassStruct, SuperClass, 0x11L,
2367 ClassName.c_str(), 0,
2368 llvm::ConstantInt::get(LongTy, instanceSize), IvarList,
2369 MethodList, GenerateProtocolList(Protocols), IvarOffsetArray,
2370 Properties, StrongIvarBitmap, WeakIvarBitmap);
2372 // Resolve the class aliases, if they exist.
2373 if (ClassPtrAlias) {
2374 ClassPtrAlias->replaceAllUsesWith(
2375 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
2376 ClassPtrAlias->eraseFromParent();
2379 if (MetaClassPtrAlias) {
2380 MetaClassPtrAlias->replaceAllUsesWith(
2381 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
2382 MetaClassPtrAlias->eraseFromParent();
2383 MetaClassPtrAlias = 0;
2386 // Add class structure to list to be added to the symtab later
2387 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
2388 Classes.push_back(ClassStruct);
2392 llvm::Function *CGObjCGNU::ModuleInitFunction() {
2393 // Only emit an ObjC load function if no Objective-C stuff has been called
2394 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
2395 ExistingProtocols.empty() && SelectorTable.empty())
2398 // Add all referenced protocols to a category.
2399 GenerateProtocolHolderCategory();
2401 llvm::StructType *SelStructTy = dyn_cast<llvm::StructType>(
2402 SelectorTy->getElementType());
2403 llvm::Type *SelStructPtrTy = SelectorTy;
2404 if (SelStructTy == 0) {
2405 SelStructTy = llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, NULL);
2406 SelStructPtrTy = llvm::PointerType::getUnqual(SelStructTy);
2409 std::vector<llvm::Constant*> Elements;
2410 llvm::Constant *Statics = NULLPtr;
2411 // Generate statics list:
2412 if (ConstantStrings.size()) {
2413 llvm::ArrayType *StaticsArrayTy = llvm::ArrayType::get(PtrToInt8Ty,
2414 ConstantStrings.size() + 1);
2415 ConstantStrings.push_back(NULLPtr);
2417 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2419 if (StringClass.empty()) StringClass = "NXConstantString";
2421 Elements.push_back(MakeConstantString(StringClass,
2422 ".objc_static_class_name"));
2423 Elements.push_back(llvm::ConstantArray::get(StaticsArrayTy,
2425 llvm::StructType *StaticsListTy =
2426 llvm::StructType::get(PtrToInt8Ty, StaticsArrayTy, NULL);
2427 llvm::Type *StaticsListPtrTy =
2428 llvm::PointerType::getUnqual(StaticsListTy);
2429 Statics = MakeGlobal(StaticsListTy, Elements, ".objc_statics");
2430 llvm::ArrayType *StaticsListArrayTy =
2431 llvm::ArrayType::get(StaticsListPtrTy, 2);
2433 Elements.push_back(Statics);
2434 Elements.push_back(llvm::Constant::getNullValue(StaticsListPtrTy));
2435 Statics = MakeGlobal(StaticsListArrayTy, Elements, ".objc_statics_ptr");
2436 Statics = llvm::ConstantExpr::getBitCast(Statics, PtrTy);
2438 // Array of classes, categories, and constant objects
2439 llvm::ArrayType *ClassListTy = llvm::ArrayType::get(PtrToInt8Ty,
2440 Classes.size() + Categories.size() + 2);
2441 llvm::StructType *SymTabTy = llvm::StructType::get(LongTy, SelStructPtrTy,
2442 llvm::Type::getInt16Ty(VMContext),
2443 llvm::Type::getInt16Ty(VMContext),
2447 // Pointer to an array of selectors used in this module.
2448 std::vector<llvm::Constant*> Selectors;
2449 std::vector<llvm::GlobalAlias*> SelectorAliases;
2450 for (SelectorMap::iterator iter = SelectorTable.begin(),
2451 iterEnd = SelectorTable.end(); iter != iterEnd ; ++iter) {
2453 std::string SelNameStr = iter->first.getAsString();
2454 llvm::Constant *SelName = ExportUniqueString(SelNameStr, ".objc_sel_name");
2456 SmallVectorImpl<TypedSelector> &Types = iter->second;
2457 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2458 e = Types.end() ; i!=e ; i++) {
2460 llvm::Constant *SelectorTypeEncoding = NULLPtr;
2461 if (!i->first.empty())
2462 SelectorTypeEncoding = MakeConstantString(i->first, ".objc_sel_types");
2464 Elements.push_back(SelName);
2465 Elements.push_back(SelectorTypeEncoding);
2466 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2469 // Store the selector alias for later replacement
2470 SelectorAliases.push_back(i->second);
2473 unsigned SelectorCount = Selectors.size();
2474 // NULL-terminate the selector list. This should not actually be required,
2475 // because the selector list has a length field. Unfortunately, the GCC
2476 // runtime decides to ignore the length field and expects a NULL terminator,
2477 // and GCC cooperates with this by always setting the length to 0.
2478 Elements.push_back(NULLPtr);
2479 Elements.push_back(NULLPtr);
2480 Selectors.push_back(llvm::ConstantStruct::get(SelStructTy, Elements));
2483 // Number of static selectors
2484 Elements.push_back(llvm::ConstantInt::get(LongTy, SelectorCount));
2485 llvm::Constant *SelectorList = MakeGlobalArray(SelStructTy, Selectors,
2486 ".objc_selector_list");
2487 Elements.push_back(llvm::ConstantExpr::getBitCast(SelectorList,
2490 // Now that all of the static selectors exist, create pointers to them.
2491 for (unsigned int i=0 ; i<SelectorCount ; i++) {
2493 llvm::Constant *Idxs[] = {Zeros[0],
2494 llvm::ConstantInt::get(Int32Ty, i), Zeros[0]};
2495 // FIXME: We're generating redundant loads and stores here!
2496 llvm::Constant *SelPtr = llvm::ConstantExpr::getGetElementPtr(SelectorList,
2497 makeArrayRef(Idxs, 2));
2498 // If selectors are defined as an opaque type, cast the pointer to this
2500 SelPtr = llvm::ConstantExpr::getBitCast(SelPtr, SelectorTy);
2501 SelectorAliases[i]->replaceAllUsesWith(SelPtr);
2502 SelectorAliases[i]->eraseFromParent();
2505 // Number of classes defined.
2506 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2508 // Number of categories defined
2509 Elements.push_back(llvm::ConstantInt::get(llvm::Type::getInt16Ty(VMContext),
2510 Categories.size()));
2511 // Create an array of classes, then categories, then static object instances
2512 Classes.insert(Classes.end(), Categories.begin(), Categories.end());
2513 // NULL-terminated list of static object instances (mainly constant strings)
2514 Classes.push_back(Statics);
2515 Classes.push_back(NULLPtr);
2516 llvm::Constant *ClassList = llvm::ConstantArray::get(ClassListTy, Classes);
2517 Elements.push_back(ClassList);
2518 // Construct the symbol table
2519 llvm::Constant *SymTab= MakeGlobal(SymTabTy, Elements);
2521 // The symbol table is contained in a module which has some version-checking
2523 llvm::StructType * ModuleTy = llvm::StructType::get(LongTy, LongTy,
2524 PtrToInt8Ty, llvm::PointerType::getUnqual(SymTabTy),
2525 (RuntimeVersion >= 10) ? IntTy : NULL, NULL);
2527 // Runtime version, used for ABI compatibility checking.
2528 Elements.push_back(llvm::ConstantInt::get(LongTy, RuntimeVersion));
2530 llvm::DataLayout td(&TheModule);
2532 llvm::ConstantInt::get(LongTy,
2533 td.getTypeSizeInBits(ModuleTy) /
2534 CGM.getContext().getCharWidth()));
2536 // The path to the source file where this module was declared
2537 SourceManager &SM = CGM.getContext().getSourceManager();
2538 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
2540 std::string(mainFile->getDir()->getName()) + '/' + mainFile->getName();
2541 Elements.push_back(MakeConstantString(path, ".objc_source_file_name"));
2542 Elements.push_back(SymTab);
2544 if (RuntimeVersion >= 10)
2545 switch (CGM.getLangOpts().getGC()) {
2546 case LangOptions::GCOnly:
2547 Elements.push_back(llvm::ConstantInt::get(IntTy, 2));
2549 case LangOptions::NonGC:
2550 if (CGM.getLangOpts().ObjCAutoRefCount)
2551 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2553 Elements.push_back(llvm::ConstantInt::get(IntTy, 0));
2555 case LangOptions::HybridGC:
2556 Elements.push_back(llvm::ConstantInt::get(IntTy, 1));
2560 llvm::Value *Module = MakeGlobal(ModuleTy, Elements);
2562 // Create the load function calling the runtime entry point with the module
2564 llvm::Function * LoadFunction = llvm::Function::Create(
2565 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
2566 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
2568 llvm::BasicBlock *EntryBB =
2569 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
2570 CGBuilderTy Builder(VMContext);
2571 Builder.SetInsertPoint(EntryBB);
2573 llvm::FunctionType *FT =
2574 llvm::FunctionType::get(Builder.getVoidTy(),
2575 llvm::PointerType::getUnqual(ModuleTy), true);
2576 llvm::Value *Register = CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
2577 Builder.CreateCall(Register, Module);
2579 if (!ClassAliases.empty()) {
2580 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
2581 llvm::FunctionType *RegisterAliasTy =
2582 llvm::FunctionType::get(Builder.getVoidTy(),
2584 llvm::Function *RegisterAlias = llvm::Function::Create(
2586 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
2588 llvm::BasicBlock *AliasBB =
2589 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
2590 llvm::BasicBlock *NoAliasBB =
2591 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
2593 // Branch based on whether the runtime provided class_registerAlias_np()
2594 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
2595 llvm::Constant::getNullValue(RegisterAlias->getType()));
2596 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
2598 // The true branch (has alias registration function):
2599 Builder.SetInsertPoint(AliasBB);
2600 // Emit alias registration calls:
2601 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
2602 iter != ClassAliases.end(); ++iter) {
2603 llvm::Constant *TheClass =
2604 TheModule.getGlobalVariable(("_OBJC_CLASS_" + iter->first).c_str(),
2606 if (0 != TheClass) {
2607 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
2608 Builder.CreateCall2(RegisterAlias, TheClass,
2609 MakeConstantString(iter->second));
2613 Builder.CreateBr(NoAliasBB);
2615 // Missing alias registration function, just return from the function:
2616 Builder.SetInsertPoint(NoAliasBB);
2618 Builder.CreateRetVoid();
2620 return LoadFunction;
2623 llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
2624 const ObjCContainerDecl *CD) {
2625 const ObjCCategoryImplDecl *OCD =
2626 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
2627 StringRef CategoryName = OCD ? OCD->getName() : "";
2628 StringRef ClassName = CD->getName();
2629 Selector MethodName = OMD->getSelector();
2630 bool isClassMethod = !OMD->isInstanceMethod();
2632 CodeGenTypes &Types = CGM.getTypes();
2633 llvm::FunctionType *MethodTy =
2634 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
2635 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
2636 MethodName, isClassMethod);
2638 llvm::Function *Method
2639 = llvm::Function::Create(MethodTy,
2640 llvm::GlobalValue::InternalLinkage,
2646 llvm::Constant *CGObjCGNU::GetPropertyGetFunction() {
2647 return GetPropertyFn;
2650 llvm::Constant *CGObjCGNU::GetPropertySetFunction() {
2651 return SetPropertyFn;
2654 llvm::Constant *CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
2659 llvm::Constant *CGObjCGNU::GetGetStructFunction() {
2660 return GetStructPropertyFn;
2662 llvm::Constant *CGObjCGNU::GetSetStructFunction() {
2663 return SetStructPropertyFn;
2665 llvm::Constant *CGObjCGNU::GetCppAtomicObjectGetFunction() {
2668 llvm::Constant *CGObjCGNU::GetCppAtomicObjectSetFunction() {
2672 llvm::Constant *CGObjCGNU::EnumerationMutationFunction() {
2673 return EnumerationMutationFn;
2676 void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
2677 const ObjCAtSynchronizedStmt &S) {
2678 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
2682 void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
2683 const ObjCAtTryStmt &S) {
2684 // Unlike the Apple non-fragile runtimes, which also uses
2685 // unwind-based zero cost exceptions, the GNU Objective C runtime's
2686 // EH support isn't a veneer over C++ EH. Instead, exception
2687 // objects are created by objc_exception_throw and destroyed by
2688 // the personality function; this avoids the need for bracketing
2689 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
2690 // (or even _Unwind_DeleteException), but probably doesn't
2691 // interoperate very well with foreign exceptions.
2693 // In Objective-C++ mode, we actually emit something equivalent to the C++
2694 // exception handler.
2695 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
2699 void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
2700 const ObjCAtThrowStmt &S,
2701 bool ClearInsertionPoint) {
2702 llvm::Value *ExceptionAsObject;
2704 if (const Expr *ThrowExpr = S.getThrowExpr()) {
2705 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
2706 ExceptionAsObject = Exception;
2708 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&
2709 "Unexpected rethrow outside @catch block.");
2710 ExceptionAsObject = CGF.ObjCEHValueStack.back();
2712 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
2713 llvm::CallSite Throw =
2714 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
2715 Throw.setDoesNotReturn();
2716 CGF.Builder.CreateUnreachable();
2717 if (ClearInsertionPoint)
2718 CGF.Builder.ClearInsertionPoint();
2721 llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
2722 llvm::Value *AddrWeakObj) {
2723 CGBuilderTy &B = CGF.Builder;
2724 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
2725 return B.CreateCall(WeakReadFn, AddrWeakObj);
2728 void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
2729 llvm::Value *src, llvm::Value *dst) {
2730 CGBuilderTy &B = CGF.Builder;
2731 src = EnforceType(B, src, IdTy);
2732 dst = EnforceType(B, dst, PtrToIdTy);
2733 B.CreateCall2(WeakAssignFn, src, dst);
2736 void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
2737 llvm::Value *src, llvm::Value *dst,
2739 CGBuilderTy &B = CGF.Builder;
2740 src = EnforceType(B, src, IdTy);
2741 dst = EnforceType(B, dst, PtrToIdTy);
2743 B.CreateCall2(GlobalAssignFn, src, dst);
2745 // FIXME. Add threadloca assign API
2746 llvm_unreachable("EmitObjCGlobalAssign - Threal Local API NYI");
2749 void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
2750 llvm::Value *src, llvm::Value *dst,
2751 llvm::Value *ivarOffset) {
2752 CGBuilderTy &B = CGF.Builder;
2753 src = EnforceType(B, src, IdTy);
2754 dst = EnforceType(B, dst, IdTy);
2755 B.CreateCall3(IvarAssignFn, src, dst, ivarOffset);
2758 void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
2759 llvm::Value *src, llvm::Value *dst) {
2760 CGBuilderTy &B = CGF.Builder;
2761 src = EnforceType(B, src, IdTy);
2762 dst = EnforceType(B, dst, PtrToIdTy);
2763 B.CreateCall2(StrongCastAssignFn, src, dst);
2766 void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
2767 llvm::Value *DestPtr,
2768 llvm::Value *SrcPtr,
2769 llvm::Value *Size) {
2770 CGBuilderTy &B = CGF.Builder;
2771 DestPtr = EnforceType(B, DestPtr, PtrTy);
2772 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
2774 B.CreateCall3(MemMoveFn, DestPtr, SrcPtr, Size);
2777 llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
2778 const ObjCInterfaceDecl *ID,
2779 const ObjCIvarDecl *Ivar) {
2780 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
2781 + '.' + Ivar->getNameAsString();
2782 // Emit the variable and initialize it with what we think the correct value
2783 // is. This allows code compiled with non-fragile ivars to work correctly
2784 // when linked against code which isn't (most of the time).
2785 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
2786 if (!IvarOffsetPointer) {
2787 // This will cause a run-time crash if we accidentally use it. A value of
2788 // 0 would seem more sensible, but will silently overwrite the isa pointer
2789 // causing a great deal of confusion.
2790 uint64_t Offset = -1;
2791 // We can't call ComputeIvarBaseOffset() here if we have the
2792 // implementation, because it will create an invalid ASTRecordLayout object
2793 // that we are then stuck with forever, so we only initialize the ivar
2794 // offset variable with a guess if we only have the interface. The
2795 // initializer will be reset later anyway, when we are generating the class
2797 if (!CGM.getContext().getObjCImplementation(
2798 const_cast<ObjCInterfaceDecl *>(ID)))
2799 Offset = ComputeIvarBaseOffset(CGM, ID, Ivar);
2801 llvm::ConstantInt *OffsetGuess = llvm::ConstantInt::get(Int32Ty, Offset,
2803 // Don't emit the guess in non-PIC code because the linker will not be able
2804 // to replace it with the real version for a library. In non-PIC code you
2805 // must compile with the fragile ABI if you want to use ivars from a
2806 // GCC-compiled class.
2807 if (CGM.getLangOpts().PICLevel || CGM.getLangOpts().PIELevel) {
2808 llvm::GlobalVariable *IvarOffsetGV = new llvm::GlobalVariable(TheModule,
2810 llvm::GlobalValue::PrivateLinkage, OffsetGuess, Name+".guess");
2811 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2812 IvarOffsetGV->getType(), false, llvm::GlobalValue::LinkOnceAnyLinkage,
2813 IvarOffsetGV, Name);
2815 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
2816 llvm::Type::getInt32PtrTy(VMContext), false,
2817 llvm::GlobalValue::ExternalLinkage, 0, Name);
2820 return IvarOffsetPointer;
2823 LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
2825 llvm::Value *BaseValue,
2826 const ObjCIvarDecl *Ivar,
2827 unsigned CVRQualifiers) {
2828 const ObjCInterfaceDecl *ID =
2829 ObjectTy->getAs<ObjCObjectType>()->getInterface();
2830 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
2831 EmitIvarOffset(CGF, ID, Ivar));
2834 static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
2835 const ObjCInterfaceDecl *OID,
2836 const ObjCIvarDecl *OIVD) {
2837 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
2838 next = next->getNextIvar()) {
2843 // Otherwise check in the super class.
2844 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
2845 return FindIvarInterface(Context, Super, OIVD);
2850 llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
2851 const ObjCInterfaceDecl *Interface,
2852 const ObjCIvarDecl *Ivar) {
2853 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2854 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
2855 if (RuntimeVersion < 10)
2856 return CGF.Builder.CreateZExtOrBitCast(
2857 CGF.Builder.CreateLoad(CGF.Builder.CreateLoad(
2858 ObjCIvarOffsetVariable(Interface, Ivar), false, "ivar")),
2860 std::string name = "__objc_ivar_offset_value_" +
2861 Interface->getNameAsString() +"." + Ivar->getNameAsString();
2862 llvm::Value *Offset = TheModule.getGlobalVariable(name);
2864 Offset = new llvm::GlobalVariable(TheModule, IntTy,
2865 false, llvm::GlobalValue::LinkOnceAnyLinkage,
2866 llvm::Constant::getNullValue(IntTy), name);
2867 Offset = CGF.Builder.CreateLoad(Offset);
2868 if (Offset->getType() != PtrDiffTy)
2869 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
2872 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
2873 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
2877 clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
2878 switch (CGM.getLangOpts().ObjCRuntime.getKind()) {
2879 case ObjCRuntime::GNUstep:
2880 return new CGObjCGNUstep(CGM);
2882 case ObjCRuntime::GCC:
2883 return new CGObjCGCC(CGM);
2885 case ObjCRuntime::ObjFW:
2886 return new CGObjCObjFW(CGM);
2888 case ObjCRuntime::FragileMacOSX:
2889 case ObjCRuntime::MacOSX:
2890 case ObjCRuntime::iOS:
2891 llvm_unreachable("these runtimes are not GNU runtimes");
2893 llvm_unreachable("bad runtime");