CGObjCMac.cpp revision 6d657c4809d9128be88705d32768de007b988212
1//===------- CGObjCMac.cpp - Interface to Apple Objective-C Runtime -------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides Objective-C code generation targetting the Apple runtime.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CGObjCRuntime.h"
15
16#include "CodeGenModule.h"
17#include "CodeGenFunction.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/Basic/LangOptions.h"
22
23#include "llvm/Module.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/Target/TargetData.h"
26#include <sstream>
27
28using namespace clang;
29using namespace CodeGen;
30
31namespace {
32
33  typedef std::vector<llvm::Constant*> ConstantVector;
34
35  // FIXME: We should find a nicer way to make the labels for
36  // metadata, string concatenation is lame.
37
38/// ObjCTypesHelper - Helper class that encapsulates lazy
39/// construction of varies types used during ObjC generation.
40class ObjCTypesHelper {
41private:
42  CodeGen::CodeGenModule &CGM;
43
44  llvm::Function *MessageSendFn, *MessageSendStretFn, *MessageSendFpretFn;
45  llvm::Function *MessageSendSuperFn, *MessageSendSuperStretFn,
46    *MessageSendSuperFpretFn;
47
48public:
49  const llvm::Type *ShortTy, *IntTy, *LongTy;
50  const llvm::Type *Int8PtrTy;
51
52  /// ObjectPtrTy - LLVM type for object handles (typeof(id))
53  const llvm::Type *ObjectPtrTy;
54
55  /// PtrObjectPtrTy - LLVM type for id *
56  const llvm::Type *PtrObjectPtrTy;
57
58  /// SelectorPtrTy - LLVM type for selector handles (typeof(SEL))
59  const llvm::Type *SelectorPtrTy;
60  /// ProtocolPtrTy - LLVM type for external protocol handles
61  /// (typeof(Protocol))
62  const llvm::Type *ExternalProtocolPtrTy;
63
64  // SuperCTy - clang type for struct objc_super.
65  QualType SuperCTy;
66  // SuperPtrCTy - clang type for struct objc_super *.
67  QualType SuperPtrCTy;
68
69  /// SuperTy - LLVM type for struct objc_super.
70  const llvm::StructType *SuperTy;
71  /// SuperPtrTy - LLVM type for struct objc_super *.
72  const llvm::Type *SuperPtrTy;
73
74  /// SymtabTy - LLVM type for struct objc_symtab.
75  const llvm::StructType *SymtabTy;
76  /// SymtabPtrTy - LLVM type for struct objc_symtab *.
77  const llvm::Type *SymtabPtrTy;
78  /// ModuleTy - LLVM type for struct objc_module.
79  const llvm::StructType *ModuleTy;
80
81  /// ProtocolTy - LLVM type for struct objc_protocol.
82  const llvm::StructType *ProtocolTy;
83  /// ProtocolPtrTy - LLVM type for struct objc_protocol *.
84  const llvm::Type *ProtocolPtrTy;
85  /// ProtocolExtensionTy - LLVM type for struct
86  /// objc_protocol_extension.
87  const llvm::StructType *ProtocolExtensionTy;
88  /// ProtocolExtensionTy - LLVM type for struct
89  /// objc_protocol_extension *.
90  const llvm::Type *ProtocolExtensionPtrTy;
91  /// MethodDescriptionTy - LLVM type for struct
92  /// objc_method_description.
93  const llvm::StructType *MethodDescriptionTy;
94  /// MethodDescriptionListTy - LLVM type for struct
95  /// objc_method_description_list.
96  const llvm::StructType *MethodDescriptionListTy;
97  /// MethodDescriptionListPtrTy - LLVM type for struct
98  /// objc_method_description_list *.
99  const llvm::Type *MethodDescriptionListPtrTy;
100  /// PropertyTy - LLVM type for struct objc_property (struct _prop_t
101  /// in GCC parlance).
102  const llvm::StructType *PropertyTy;
103  /// PropertyListTy - LLVM type for struct objc_property_list
104  /// (_prop_list_t in GCC parlance).
105  const llvm::StructType *PropertyListTy;
106  /// PropertyListPtrTy - LLVM type for struct objc_property_list*.
107  const llvm::Type *PropertyListPtrTy;
108  /// ProtocolListTy - LLVM type for struct objc_property_list.
109  const llvm::Type *ProtocolListTy;
110  /// ProtocolListPtrTy - LLVM type for struct objc_property_list*.
111  const llvm::Type *ProtocolListPtrTy;
112  /// CategoryTy - LLVM type for struct objc_category.
113  const llvm::StructType *CategoryTy;
114  /// ClassTy - LLVM type for struct objc_class.
115  const llvm::StructType *ClassTy;
116  /// ClassPtrTy - LLVM type for struct objc_class *.
117  const llvm::Type *ClassPtrTy;
118  /// ClassExtensionTy - LLVM type for struct objc_class_ext.
119  const llvm::StructType *ClassExtensionTy;
120  /// ClassExtensionPtrTy - LLVM type for struct objc_class_ext *.
121  const llvm::Type *ClassExtensionPtrTy;
122  /// CacheTy - LLVM type for struct objc_cache.
123  const llvm::Type *CacheTy;
124  /// CachePtrTy - LLVM type for struct objc_cache *.
125  const llvm::Type *CachePtrTy;
126  // IvarTy - LLVM type for struct objc_ivar.
127  const llvm::StructType *IvarTy;
128  /// IvarListTy - LLVM type for struct objc_ivar_list.
129  const llvm::Type *IvarListTy;
130  /// IvarListPtrTy - LLVM type for struct objc_ivar_list *.
131  const llvm::Type *IvarListPtrTy;
132  // MethodTy - LLVM type for struct objc_method.
133  const llvm::StructType *MethodTy;
134  /// MethodListTy - LLVM type for struct objc_method_list.
135  const llvm::Type *MethodListTy;
136  /// MethodListPtrTy - LLVM type for struct objc_method_list *.
137  const llvm::Type *MethodListPtrTy;
138
139  llvm::Function *GetPropertyFn, *SetPropertyFn;
140  llvm::Function *EnumerationMutationFn;
141
142  /// ExceptionDataTy - LLVM type for struct _objc_exception_data.
143  const llvm::Type *ExceptionDataTy;
144
145  /// ExceptionThrowFn - LLVM objc_exception_throw function.
146  llvm::Function *ExceptionThrowFn;
147
148  /// ExceptionTryEnterFn - LLVM objc_exception_try_enter function.
149  llvm::Function *ExceptionTryEnterFn;
150
151  /// ExceptionTryExitFn - LLVM objc_exception_try_exit function.
152  llvm::Function *ExceptionTryExitFn;
153
154  /// ExceptionExtractFn - LLVM objc_exception_extract function.
155  llvm::Function *ExceptionExtractFn;
156
157  /// ExceptionMatchFn - LLVM objc_exception_match function.
158  llvm::Function *ExceptionMatchFn;
159
160  /// SetJmpFn - LLVM _setjmp function.
161  llvm::Function *SetJmpFn;
162
163  /// SyncEnterFn - LLVM object_sync_enter function.
164  llvm::Function *SyncEnterFn;
165
166  /// SyncExitFn - LLVM object_sync_exit function.
167  llvm::Function *SyncExitFn;
168
169  /// GcReadWeakFn -- LLVM objc_read_weak (id *src) function.
170  llvm::Function *GcReadWeakFn;
171
172  /// GcAssignWeakFn -- LLVM objc_assign_weak function.
173  llvm::Function *GcAssignWeakFn;
174
175  /// GcAssignGlobalFn -- LLVM objc_assign_global function.
176  llvm::Function *GcAssignGlobalFn;
177
178  /// GcAssignStrongCastFn -- LLVM objc_assign_strongCast function.
179  llvm::Function *GcAssignStrongCastFn;
180
181public:
182  ObjCTypesHelper(CodeGen::CodeGenModule &cgm);
183  ~ObjCTypesHelper();
184
185
186  llvm::Function *getSendFn(bool IsSuper) {
187    return IsSuper ? MessageSendSuperFn : MessageSendFn;
188  }
189
190  llvm::Function *getSendStretFn(bool IsSuper) {
191    return IsSuper ? MessageSendSuperStretFn : MessageSendStretFn;
192  }
193
194  llvm::Function *getSendFpretFn(bool IsSuper) {
195    return IsSuper ? MessageSendSuperFpretFn : MessageSendFpretFn;
196  }
197};
198
199class CGObjCMac : public CodeGen::CGObjCRuntime {
200private:
201  CodeGen::CodeGenModule &CGM;
202  ObjCTypesHelper ObjCTypes;
203  /// ObjCABI - FIXME: Not sure yet.
204  unsigned ObjCABI;
205
206  /// LazySymbols - Symbols to generate a lazy reference for. See
207  /// DefinedSymbols and FinishModule().
208  std::set<IdentifierInfo*> LazySymbols;
209
210  /// DefinedSymbols - External symbols which are defined by this
211  /// module. The symbols in this list and LazySymbols are used to add
212  /// special linker symbols which ensure that Objective-C modules are
213  /// linked properly.
214  std::set<IdentifierInfo*> DefinedSymbols;
215
216  /// ClassNames - uniqued class names.
217  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassNames;
218
219  /// MethodVarNames - uniqued method variable names.
220  llvm::DenseMap<Selector, llvm::GlobalVariable*> MethodVarNames;
221
222  /// MethodVarTypes - uniqued method type signatures. We have to use
223  /// a StringMap here because have no other unique reference.
224  llvm::StringMap<llvm::GlobalVariable*> MethodVarTypes;
225
226  /// MethodDefinitions - map of methods which have been defined in
227  /// this translation unit.
228  llvm::DenseMap<const ObjCMethodDecl*, llvm::Function*> MethodDefinitions;
229
230  /// PropertyNames - uniqued method variable names.
231  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> PropertyNames;
232
233  /// ClassReferences - uniqued class references.
234  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> ClassReferences;
235
236  /// SelectorReferences - uniqued selector references.
237  llvm::DenseMap<Selector, llvm::GlobalVariable*> SelectorReferences;
238
239  /// Protocols - Protocols for which an objc_protocol structure has
240  /// been emitted. Forward declarations are handled by creating an
241  /// empty structure whose initializer is filled in when/if defined.
242  llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*> Protocols;
243
244  /// DefinedProtocols - Protocols which have actually been
245  /// defined. We should not need this, see FIXME in GenerateProtocol.
246  llvm::DenseSet<IdentifierInfo*> DefinedProtocols;
247
248  /// DefinedClasses - List of defined classes.
249  std::vector<llvm::GlobalValue*> DefinedClasses;
250
251  /// DefinedCategories - List of defined categories.
252  std::vector<llvm::GlobalValue*> DefinedCategories;
253
254  /// UsedGlobals - List of globals to pack into the llvm.used metadata
255  /// to prevent them from being clobbered.
256  std::vector<llvm::GlobalVariable*> UsedGlobals;
257
258  /// EmitImageInfo - Emit the image info marker used to encode some module
259  /// level information.
260  void EmitImageInfo();
261
262  /// EmitModuleInfo - Another marker encoding module level
263  /// information.
264  void EmitModuleInfo();
265
266  /// EmitModuleSymols - Emit module symbols, the list of defined
267  /// classes and categories. The result has type SymtabPtrTy.
268  llvm::Constant *EmitModuleSymbols();
269
270  /// FinishModule - Write out global data structures at the end of
271  /// processing a translation unit.
272  void FinishModule();
273
274  /// EmitClassExtension - Generate the class extension structure used
275  /// to store the weak ivar layout and properties. The return value
276  /// has type ClassExtensionPtrTy.
277  llvm::Constant *EmitClassExtension(const ObjCImplementationDecl *ID);
278
279  /// EmitClassRef - Return a Value*, of type ObjCTypes.ClassPtrTy,
280  /// for the given class.
281  llvm::Value *EmitClassRef(CGBuilderTy &Builder,
282                            const ObjCInterfaceDecl *ID);
283
284  CodeGen::RValue EmitMessageSend(CodeGen::CodeGenFunction &CGF,
285                                  QualType ResultType,
286                                  Selector Sel,
287                                  llvm::Value *Arg0,
288                                  QualType Arg0Ty,
289                                  bool IsSuper,
290                                  const CallArgList &CallArgs);
291
292  /// EmitIvarList - Emit the ivar list for the given
293  /// implementation. If ForClass is true the list of class ivars
294  /// (i.e. metaclass ivars) is emitted, otherwise the list of
295  /// interface ivars will be emitted. The return value has type
296  /// IvarListPtrTy.
297  llvm::Constant *EmitIvarList(const ObjCImplementationDecl *ID,
298                               bool ForClass,
299                               const llvm::Type *InterfaceTy);
300
301  /// EmitMetaClass - Emit a forward reference to the class structure
302  /// for the metaclass of the given interface. The return value has
303  /// type ClassPtrTy.
304  llvm::Constant *EmitMetaClassRef(const ObjCInterfaceDecl *ID);
305
306  /// EmitMetaClass - Emit a class structure for the metaclass of the
307  /// given implementation. The return value has type ClassPtrTy.
308  llvm::Constant *EmitMetaClass(const ObjCImplementationDecl *ID,
309                                llvm::Constant *Protocols,
310                                const llvm::Type *InterfaceTy,
311                                const ConstantVector &Methods);
312
313  llvm::Constant *GetMethodConstant(const ObjCMethodDecl *MD);
314
315  llvm::Constant *GetMethodDescriptionConstant(const ObjCMethodDecl *MD);
316
317  /// EmitMethodList - Emit the method list for the given
318  /// implementation. The return value has type MethodListPtrTy.
319  llvm::Constant *EmitMethodList(const std::string &Name,
320                                 const char *Section,
321                                 const ConstantVector &Methods);
322
323  /// EmitMethodDescList - Emit a method description list for a list of
324  /// method declarations.
325  ///  - TypeName: The name for the type containing the methods.
326  ///  - IsProtocol: True iff these methods are for a protocol.
327  ///  - ClassMethds: True iff these are class methods.
328  ///  - Required: When true, only "required" methods are
329  ///    listed. Similarly, when false only "optional" methods are
330  ///    listed. For classes this should always be true.
331  ///  - begin, end: The method list to output.
332  ///
333  /// The return value has type MethodDescriptionListPtrTy.
334  llvm::Constant *EmitMethodDescList(const std::string &Name,
335                                     const char *Section,
336                                     const ConstantVector &Methods);
337
338  /// EmitPropertyList - Emit the given property list. The return
339  /// value has type PropertyListPtrTy.
340  llvm::Constant *EmitPropertyList(const std::string &Name,
341                                   const Decl *Container,
342                                   ObjCPropertyDecl * const *begin,
343                                   ObjCPropertyDecl * const *end);
344
345  /// GetOrEmitProtocol - Get the protocol object for the given
346  /// declaration, emitting it if necessary. The return value has type
347  /// ProtocolPtrTy.
348  llvm::Constant *GetOrEmitProtocol(const ObjCProtocolDecl *PD);
349
350  /// GetOrEmitProtocolRef - Get a forward reference to the protocol
351  /// object for the given declaration, emitting it if needed. These
352  /// forward references will be filled in with empty bodies if no
353  /// definition is seen. The return value has type ProtocolPtrTy.
354  llvm::Constant *GetOrEmitProtocolRef(const ObjCProtocolDecl *PD);
355
356  /// EmitProtocolExtension - Generate the protocol extension
357  /// structure used to store optional instance and class methods, and
358  /// protocol properties. The return value has type
359  /// ProtocolExtensionPtrTy.
360  llvm::Constant *
361  EmitProtocolExtension(const ObjCProtocolDecl *PD,
362                        const ConstantVector &OptInstanceMethods,
363                        const ConstantVector &OptClassMethods);
364
365  /// EmitProtocolList - Generate the list of referenced
366  /// protocols. The return value has type ProtocolListPtrTy.
367  llvm::Constant *EmitProtocolList(const std::string &Name,
368                                   ObjCProtocolDecl::protocol_iterator begin,
369                                   ObjCProtocolDecl::protocol_iterator end);
370
371  /// EmitSelector - Return a Value*, of type ObjCTypes.SelectorPtrTy,
372  /// for the given selector.
373  llvm::Value *EmitSelector(CGBuilderTy &Builder, Selector Sel);
374
375  /// GetProtocolRef - Return a reference to the internal protocol
376  /// description, creating an empty one if it has not been
377  /// defined. The return value has type ProtocolPtrTy.
378  llvm::Constant *GetProtocolRef(const ObjCProtocolDecl *PD);
379
380  /// GetClassName - Return a unique constant for the given selector's
381  /// name. The return value has type char *.
382  llvm::Constant *GetClassName(IdentifierInfo *Ident);
383
384  /// GetMethodVarName - Return a unique constant for the given
385  /// selector's name. The return value has type char *.
386  llvm::Constant *GetMethodVarName(Selector Sel);
387  llvm::Constant *GetMethodVarName(IdentifierInfo *Ident);
388  llvm::Constant *GetMethodVarName(const std::string &Name);
389
390  /// GetMethodVarType - Return a unique constant for the given
391  /// selector's name. The return value has type char *.
392
393  // FIXME: This is a horrible name.
394  llvm::Constant *GetMethodVarType(const ObjCMethodDecl *D);
395  llvm::Constant *GetMethodVarType(const std::string &Name);
396
397  /// GetPropertyName - Return a unique constant for the given
398  /// name. The return value has type char *.
399  llvm::Constant *GetPropertyName(IdentifierInfo *Ident);
400
401  // FIXME: This can be dropped once string functions are unified.
402  llvm::Constant *GetPropertyTypeString(const ObjCPropertyDecl *PD,
403                                        const Decl *Container);
404
405  /// GetNameForMethod - Return a name for the given method.
406  /// \param[out] NameOut - The return value.
407  void GetNameForMethod(const ObjCMethodDecl *OMD,
408                        std::string &NameOut);
409
410public:
411  CGObjCMac(CodeGen::CodeGenModule &cgm);
412  virtual llvm::Constant *GenerateConstantString(const std::string &String);
413
414  virtual CodeGen::RValue GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
415                                              QualType ResultType,
416                                              Selector Sel,
417                                              llvm::Value *Receiver,
418                                              bool IsClassMessage,
419                                              const CallArgList &CallArgs);
420
421  virtual CodeGen::RValue
422  GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
423                           QualType ResultType,
424                           Selector Sel,
425                           const ObjCInterfaceDecl *Class,
426                           llvm::Value *Receiver,
427                           bool IsClassMessage,
428                           const CallArgList &CallArgs);
429
430  virtual llvm::Value *GetClass(CGBuilderTy &Builder,
431                                const ObjCInterfaceDecl *ID);
432
433  virtual llvm::Value *GetSelector(CGBuilderTy &Builder, Selector Sel);
434
435  virtual llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD);
436
437  virtual void GenerateCategory(const ObjCCategoryImplDecl *CMD);
438
439  virtual void GenerateClass(const ObjCImplementationDecl *ClassDecl);
440
441  virtual llvm::Value *GenerateProtocolRef(CGBuilderTy &Builder,
442                                           const ObjCProtocolDecl *PD);
443
444  virtual void GenerateProtocol(const ObjCProtocolDecl *PD);
445
446  virtual llvm::Function *ModuleInitFunction();
447  virtual llvm::Function *GetPropertyGetFunction();
448  virtual llvm::Function *GetPropertySetFunction();
449  virtual llvm::Function *EnumerationMutationFunction();
450
451  virtual void EmitTryStmt(CodeGen::CodeGenFunction &CGF,
452                           const ObjCAtTryStmt &S);
453  virtual void EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
454                             const ObjCAtThrowStmt &S);
455  virtual void EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
456                                    const ObjCAtSynchronizedStmt &S);
457
458};
459} // end anonymous namespace
460
461/* *** Helper Functions *** */
462
463/// getConstantGEP() - Help routine to construct simple GEPs.
464static llvm::Constant *getConstantGEP(llvm::Constant *C,
465                                      unsigned idx0,
466                                      unsigned idx1) {
467  llvm::Value *Idxs[] = {
468    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx0),
469    llvm::ConstantInt::get(llvm::Type::Int32Ty, idx1)
470  };
471  return llvm::ConstantExpr::getGetElementPtr(C, Idxs, 2);
472}
473
474/* *** CGObjCMac Public Interface *** */
475
476CGObjCMac::CGObjCMac(CodeGen::CodeGenModule &cgm)
477  : CGM(cgm),
478    ObjCTypes(cgm),
479    ObjCABI(1)
480{
481  // FIXME: How does this get set in GCC? And what does it even mean?
482  if (ObjCTypes.LongTy != CGM.getTypes().ConvertType(CGM.getContext().IntTy))
483      ObjCABI = 2;
484
485  EmitImageInfo();
486}
487
488/// GetClass - Return a reference to the class for the given interface
489/// decl.
490llvm::Value *CGObjCMac::GetClass(CGBuilderTy &Builder,
491                                 const ObjCInterfaceDecl *ID) {
492  return EmitClassRef(Builder, ID);
493}
494
495/// GetSelector - Return the pointer to the unique'd string for this selector.
496llvm::Value *CGObjCMac::GetSelector(CGBuilderTy &Builder, Selector Sel) {
497  return EmitSelector(Builder, Sel);
498}
499
500/// Generate a constant CFString object.
501/*
502   struct __builtin_CFString {
503     const int *isa; // point to __CFConstantStringClassReference
504     int flags;
505     const char *str;
506     long length;
507   };
508*/
509
510llvm::Constant *CGObjCMac::GenerateConstantString(const std::string &String) {
511  return CGM.GetAddrOfConstantCFString(String);
512}
513
514/// Generates a message send where the super is the receiver.  This is
515/// a message send to self with special delivery semantics indicating
516/// which class's method should be called.
517CodeGen::RValue
518CGObjCMac::GenerateMessageSendSuper(CodeGen::CodeGenFunction &CGF,
519                                    QualType ResultType,
520                                    Selector Sel,
521                                    const ObjCInterfaceDecl *Class,
522                                    llvm::Value *Receiver,
523                                    bool IsClassMessage,
524                                    const CodeGen::CallArgList &CallArgs) {
525  // Create and init a super structure; this is a (receiver, class)
526  // pair we will pass to objc_msgSendSuper.
527  llvm::Value *ObjCSuper =
528    CGF.Builder.CreateAlloca(ObjCTypes.SuperTy, 0, "objc_super");
529  llvm::Value *ReceiverAsObject =
530    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy);
531  CGF.Builder.CreateStore(ReceiverAsObject,
532                          CGF.Builder.CreateStructGEP(ObjCSuper, 0));
533
534  // If this is a class message the metaclass is passed as the target.
535  llvm::Value *Target;
536  if (IsClassMessage) {
537    llvm::Value *MetaClassPtr = EmitMetaClassRef(Class);
538    llvm::Value *SuperPtr = CGF.Builder.CreateStructGEP(MetaClassPtr, 1);
539    llvm::Value *Super = CGF.Builder.CreateLoad(SuperPtr);
540    Target = Super;
541  } else {
542    Target = EmitClassRef(CGF.Builder, Class->getSuperClass());
543  }
544  // FIXME: We shouldn't need to do this cast, rectify the ASTContext
545  // and ObjCTypes types.
546  const llvm::Type *ClassTy =
547    CGM.getTypes().ConvertType(CGF.getContext().getObjCClassType());
548  Target = CGF.Builder.CreateBitCast(Target, ClassTy);
549  CGF.Builder.CreateStore(Target,
550                          CGF.Builder.CreateStructGEP(ObjCSuper, 1));
551
552  return EmitMessageSend(CGF, ResultType, Sel,
553                         ObjCSuper, ObjCTypes.SuperPtrCTy,
554                         true, CallArgs);
555}
556
557/// Generate code for a message send expression.
558CodeGen::RValue CGObjCMac::GenerateMessageSend(CodeGen::CodeGenFunction &CGF,
559                                               QualType ResultType,
560                                               Selector Sel,
561                                               llvm::Value *Receiver,
562                                               bool IsClassMessage,
563                                               const CallArgList &CallArgs) {
564  llvm::Value *Arg0 =
565    CGF.Builder.CreateBitCast(Receiver, ObjCTypes.ObjectPtrTy, "tmp");
566  return EmitMessageSend(CGF, ResultType, Sel,
567                         Arg0, CGF.getContext().getObjCIdType(),
568                         false, CallArgs);
569}
570
571CodeGen::RValue CGObjCMac::EmitMessageSend(CodeGen::CodeGenFunction &CGF,
572                                           QualType ResultType,
573                                           Selector Sel,
574                                           llvm::Value *Arg0,
575                                           QualType Arg0Ty,
576                                           bool IsSuper,
577                                           const CallArgList &CallArgs) {
578  CallArgList ActualArgs;
579  ActualArgs.push_back(std::make_pair(RValue::get(Arg0), Arg0Ty));
580  ActualArgs.push_back(std::make_pair(RValue::get(EmitSelector(CGF.Builder,
581                                                               Sel)),
582                                      CGF.getContext().getObjCSelType()));
583  ActualArgs.insert(ActualArgs.end(), CallArgs.begin(), CallArgs.end());
584
585  const llvm::FunctionType *FTy =
586    CGM.getTypes().GetFunctionType(CGCallInfo(ResultType, ActualArgs),
587                                   false);
588
589  llvm::Constant *Fn;
590  if (CGM.ReturnTypeUsesSret(ResultType)) {
591    Fn = ObjCTypes.getSendStretFn(IsSuper);
592  } else if (ResultType->isFloatingType()) {
593    // FIXME: Sadly, this is wrong. This actually depends on the
594    // architecture. This happens to be right for x86-32 though.
595    Fn = ObjCTypes.getSendFpretFn(IsSuper);
596  } else {
597    Fn = ObjCTypes.getSendFn(IsSuper);
598  }
599  Fn = llvm::ConstantExpr::getBitCast(Fn, llvm::PointerType::getUnqual(FTy));
600  return CGF.EmitCall(Fn, ResultType, ActualArgs);
601}
602
603llvm::Value *CGObjCMac::GenerateProtocolRef(CGBuilderTy &Builder,
604                                            const ObjCProtocolDecl *PD) {
605  // FIXME: I don't understand why gcc generates this, or where it is
606  // resolved. Investigate. Its also wasteful to look this up over and
607  // over.
608  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
609
610  return llvm::ConstantExpr::getBitCast(GetProtocolRef(PD),
611                                        ObjCTypes.ExternalProtocolPtrTy);
612}
613
614void CGObjCMac::GenerateProtocol(const ObjCProtocolDecl *PD) {
615  // FIXME: We shouldn't need this, the protocol decl should contain
616  // enough information to tell us whether this was a declaration or a
617  // definition.
618  DefinedProtocols.insert(PD->getIdentifier());
619
620  // If we have generated a forward reference to this protocol, emit
621  // it now. Otherwise do nothing, the protocol objects are lazily
622  // emitted.
623  if (Protocols.count(PD->getIdentifier()))
624    GetOrEmitProtocol(PD);
625}
626
627llvm::Constant *CGObjCMac::GetProtocolRef(const ObjCProtocolDecl *PD) {
628  if (DefinedProtocols.count(PD->getIdentifier()))
629    return GetOrEmitProtocol(PD);
630  return GetOrEmitProtocolRef(PD);
631}
632
633/*
634     // APPLE LOCAL radar 4585769 - Objective-C 1.0 extensions
635  struct _objc_protocol {
636    struct _objc_protocol_extension *isa;
637    char *protocol_name;
638    struct _objc_protocol_list *protocol_list;
639    struct _objc__method_prototype_list *instance_methods;
640    struct _objc__method_prototype_list *class_methods
641  };
642
643  See EmitProtocolExtension().
644*/
645llvm::Constant *CGObjCMac::GetOrEmitProtocol(const ObjCProtocolDecl *PD) {
646  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
647
648  // Early exit if a defining object has already been generated.
649  if (Entry && Entry->hasInitializer())
650    return Entry;
651
652  // FIXME: I don't understand why gcc generates this, or where it is
653  // resolved. Investigate. Its also wasteful to look this up over and
654  // over.
655  LazySymbols.insert(&CGM.getContext().Idents.get("Protocol"));
656
657  const char *ProtocolName = PD->getIdentifierName();
658
659  // Construct method lists.
660  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
661  std::vector<llvm::Constant*> OptInstanceMethods, OptClassMethods;
662  for (ObjCProtocolDecl::instmeth_iterator i = PD->instmeth_begin(),
663         e = PD->instmeth_end(); i != e; ++i) {
664    ObjCMethodDecl *MD = *i;
665    llvm::Constant *C = GetMethodDescriptionConstant(MD);
666    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
667      OptInstanceMethods.push_back(C);
668    } else {
669      InstanceMethods.push_back(C);
670    }
671  }
672
673  for (ObjCProtocolDecl::classmeth_iterator i = PD->classmeth_begin(),
674         e = PD->classmeth_end(); i != e; ++i) {
675    ObjCMethodDecl *MD = *i;
676    llvm::Constant *C = GetMethodDescriptionConstant(MD);
677    if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
678      OptClassMethods.push_back(C);
679    } else {
680      ClassMethods.push_back(C);
681    }
682  }
683
684  std::vector<llvm::Constant*> Values(5);
685  Values[0] = EmitProtocolExtension(PD, OptInstanceMethods, OptClassMethods);
686  Values[1] = GetClassName(PD->getIdentifier());
687  Values[2] =
688    EmitProtocolList(std::string("\01L_OBJC_PROTOCOL_REFS_")+PD->getName(),
689                     PD->protocol_begin(),
690                     PD->protocol_end());
691  Values[3] =
692    EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_")
693                       + PD->getName(),
694                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
695                       InstanceMethods);
696  Values[4] =
697    EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_")
698                       + PD->getName(),
699                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
700                       ClassMethods);
701  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
702                                                   Values);
703
704  if (Entry) {
705    // Already created, fix the linkage and update the initializer.
706    Entry->setLinkage(llvm::GlobalValue::InternalLinkage);
707    Entry->setInitializer(Init);
708  } else {
709    Entry =
710      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
711                               llvm::GlobalValue::InternalLinkage,
712                               Init,
713                               std::string("\01L_OBJC_PROTOCOL_")+ProtocolName,
714                               &CGM.getModule());
715    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
716    UsedGlobals.push_back(Entry);
717    // FIXME: Is this necessary? Why only for protocol?
718    Entry->setAlignment(4);
719  }
720
721  return Entry;
722}
723
724llvm::Constant *CGObjCMac::GetOrEmitProtocolRef(const ObjCProtocolDecl *PD) {
725  llvm::GlobalVariable *&Entry = Protocols[PD->getIdentifier()];
726
727  if (!Entry) {
728    // We use the initializer as a marker of whether this is a forward
729    // reference or not. At module finalization we add the empty
730    // contents for protocols which were referenced but never defined.
731    Entry =
732      new llvm::GlobalVariable(ObjCTypes.ProtocolTy, false,
733                               llvm::GlobalValue::ExternalLinkage,
734                               0,
735                               std::string("\01L_OBJC_PROTOCOL_")+PD->getName(),
736                               &CGM.getModule());
737    Entry->setSection("__OBJC,__protocol,regular,no_dead_strip");
738    UsedGlobals.push_back(Entry);
739    // FIXME: Is this necessary? Why only for protocol?
740    Entry->setAlignment(4);
741  }
742
743  return Entry;
744}
745
746/*
747  struct _objc_protocol_extension {
748    uint32_t size;
749    struct objc_method_description_list *optional_instance_methods;
750    struct objc_method_description_list *optional_class_methods;
751    struct objc_property_list *instance_properties;
752  };
753*/
754llvm::Constant *
755CGObjCMac::EmitProtocolExtension(const ObjCProtocolDecl *PD,
756                                 const ConstantVector &OptInstanceMethods,
757                                 const ConstantVector &OptClassMethods) {
758  uint64_t Size =
759    CGM.getTargetData().getABITypeSize(ObjCTypes.ProtocolExtensionTy);
760  std::vector<llvm::Constant*> Values(4);
761  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
762  Values[1] =
763    EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_INSTANCE_METHODS_OPT_")
764                       + PD->getName(),
765                       "__OBJC,__cat_inst_meth,regular,no_dead_strip",
766                       OptInstanceMethods);
767  Values[2] =
768    EmitMethodDescList(std::string("\01L_OBJC_PROTOCOL_CLASS_METHODS_OPT_")
769                       + PD->getName(),
770                       "__OBJC,__cat_cls_meth,regular,no_dead_strip",
771                       OptClassMethods);
772  Values[3] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_PROTO_LIST_") +
773                               PD->getName(),
774                               0,
775                               PD->classprop_begin(),
776                               PD->classprop_end());
777
778  // Return null if no extension bits are used.
779  if (Values[1]->isNullValue() && Values[2]->isNullValue() &&
780      Values[3]->isNullValue())
781    return llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
782
783  llvm::Constant *Init =
784    llvm::ConstantStruct::get(ObjCTypes.ProtocolExtensionTy, Values);
785  llvm::GlobalVariable *GV =
786      new llvm::GlobalVariable(ObjCTypes.ProtocolExtensionTy, false,
787                               llvm::GlobalValue::InternalLinkage,
788                               Init,
789                               (std::string("\01L_OBJC_PROTOCOLEXT_") +
790                                PD->getName()),
791                               &CGM.getModule());
792  // No special section, but goes in llvm.used
793  UsedGlobals.push_back(GV);
794
795  return GV;
796}
797
798/*
799  struct objc_protocol_list {
800    struct objc_protocol_list *next;
801    long count;
802    Protocol *list[];
803  };
804*/
805llvm::Constant *
806CGObjCMac::EmitProtocolList(const std::string &Name,
807                            ObjCProtocolDecl::protocol_iterator begin,
808                            ObjCProtocolDecl::protocol_iterator end) {
809  std::vector<llvm::Constant*> ProtocolRefs;
810
811  for (; begin != end; ++begin)
812    ProtocolRefs.push_back(GetProtocolRef(*begin));
813
814  // Just return null for empty protocol lists
815  if (ProtocolRefs.empty())
816    return llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
817
818  // This list is null terminated.
819  ProtocolRefs.push_back(llvm::Constant::getNullValue(ObjCTypes.ProtocolPtrTy));
820
821  std::vector<llvm::Constant*> Values(3);
822  // This field is only used by the runtime.
823  Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
824  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, ProtocolRefs.size() - 1);
825  Values[2] =
826    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.ProtocolPtrTy,
827                                                  ProtocolRefs.size()),
828                             ProtocolRefs);
829
830  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
831  llvm::GlobalVariable *GV =
832    new llvm::GlobalVariable(Init->getType(), false,
833                             llvm::GlobalValue::InternalLinkage,
834                             Init,
835                             Name,
836                             &CGM.getModule());
837  GV->setSection("__OBJC,__cat_cls_meth,regular,no_dead_strip");
838  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.ProtocolListPtrTy);
839}
840
841/*
842  struct _objc_property {
843    const char * const name;
844    const char * const attributes;
845  };
846
847  struct _objc_property_list {
848    uint32_t entsize; // sizeof (struct _objc_property)
849    uint32_t prop_count;
850    struct _objc_property[prop_count];
851  };
852*/
853llvm::Constant *CGObjCMac::EmitPropertyList(const std::string &Name,
854                                            const Decl *Container,
855                                            ObjCPropertyDecl * const *begin,
856                                            ObjCPropertyDecl * const *end) {
857  std::vector<llvm::Constant*> Properties, Prop(2);
858  for (; begin != end; ++begin) {
859    const ObjCPropertyDecl *PD = *begin;
860    Prop[0] = GetPropertyName(PD->getIdentifier());
861    Prop[1] = GetPropertyTypeString(PD, Container);
862    Properties.push_back(llvm::ConstantStruct::get(ObjCTypes.PropertyTy,
863                                                   Prop));
864  }
865
866  // Return null for empty list.
867  if (Properties.empty())
868    return llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
869
870  unsigned PropertySize =
871    CGM.getTargetData().getABITypeSize(ObjCTypes.PropertyTy);
872  std::vector<llvm::Constant*> Values(3);
873  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, PropertySize);
874  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Properties.size());
875  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.PropertyTy,
876                                             Properties.size());
877  Values[2] = llvm::ConstantArray::get(AT, Properties);
878  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
879
880  llvm::GlobalVariable *GV =
881    new llvm::GlobalVariable(Init->getType(), false,
882                             llvm::GlobalValue::InternalLinkage,
883                             Init,
884                             Name,
885                             &CGM.getModule());
886  // No special section on property lists?
887  UsedGlobals.push_back(GV);
888  return llvm::ConstantExpr::getBitCast(GV,
889                                        ObjCTypes.PropertyListPtrTy);
890
891}
892
893/*
894  struct objc_method_description_list {
895    int count;
896    struct objc_method_description list[];
897  };
898*/
899llvm::Constant *
900CGObjCMac::GetMethodDescriptionConstant(const ObjCMethodDecl *MD) {
901  std::vector<llvm::Constant*> Desc(2);
902  Desc[0] = llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
903                                           ObjCTypes.SelectorPtrTy);
904  Desc[1] = GetMethodVarType(MD);
905  return llvm::ConstantStruct::get(ObjCTypes.MethodDescriptionTy,
906                                   Desc);
907}
908
909llvm::Constant *CGObjCMac::EmitMethodDescList(const std::string &Name,
910                                              const char *Section,
911                                              const ConstantVector &Methods) {
912  // Return null for empty list.
913  if (Methods.empty())
914    return llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
915
916  std::vector<llvm::Constant*> Values(2);
917  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
918  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodDescriptionTy,
919                                             Methods.size());
920  Values[1] = llvm::ConstantArray::get(AT, Methods);
921  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
922
923  llvm::GlobalVariable *GV =
924    new llvm::GlobalVariable(Init->getType(), false,
925                             llvm::GlobalValue::InternalLinkage,
926                             Init, Name, &CGM.getModule());
927  GV->setSection(Section);
928  UsedGlobals.push_back(GV);
929  return llvm::ConstantExpr::getBitCast(GV,
930                                        ObjCTypes.MethodDescriptionListPtrTy);
931}
932
933/*
934  struct _objc_category {
935    char *category_name;
936    char *class_name;
937    struct _objc_method_list *instance_methods;
938    struct _objc_method_list *class_methods;
939    struct _objc_protocol_list *protocols;
940    uint32_t size; // <rdar://4585769>
941    struct _objc_property_list *instance_properties;
942  };
943 */
944void CGObjCMac::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
945  unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.CategoryTy);
946
947  // FIXME: This is poor design, the OCD should have a pointer to the
948  // category decl. Additionally, note that Category can be null for
949  // the @implementation w/o an @interface case. Sema should just
950  // create one for us as it does for @implementation so everyone else
951  // can live life under a clear blue sky.
952  const ObjCInterfaceDecl *Interface = OCD->getClassInterface();
953  const ObjCCategoryDecl *Category =
954    Interface->FindCategoryDeclaration(OCD->getIdentifier());
955  std::string ExtName(std::string(Interface->getName()) +
956                      "_" +
957                      OCD->getName());
958
959  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
960  for (ObjCCategoryImplDecl::instmeth_iterator i = OCD->instmeth_begin(),
961         e = OCD->instmeth_end(); i != e; ++i) {
962    // Instance methods should always be defined.
963    InstanceMethods.push_back(GetMethodConstant(*i));
964  }
965  for (ObjCCategoryImplDecl::classmeth_iterator i = OCD->classmeth_begin(),
966         e = OCD->classmeth_end(); i != e; ++i) {
967    // Class methods should always be defined.
968    ClassMethods.push_back(GetMethodConstant(*i));
969  }
970
971  std::vector<llvm::Constant*> Values(7);
972  Values[0] = GetClassName(OCD->getIdentifier());
973  Values[1] = GetClassName(Interface->getIdentifier());
974  Values[2] =
975    EmitMethodList(std::string("\01L_OBJC_CATEGORY_INSTANCE_METHODS_") +
976                   ExtName,
977                   "__OBJC,__cat_inst_meth,regular,no_dead_strip",
978                   InstanceMethods);
979  Values[3] =
980    EmitMethodList(std::string("\01L_OBJC_CATEGORY_CLASS_METHODS_") + ExtName,
981                   "__OBJC,__cat_class_meth,regular,no_dead_strip",
982                   ClassMethods);
983  if (Category) {
984    Values[4] =
985      EmitProtocolList(std::string("\01L_OBJC_CATEGORY_PROTOCOLS_") + ExtName,
986                       Category->protocol_begin(),
987                       Category->protocol_end());
988  } else {
989    Values[4] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
990  }
991  Values[5] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
992
993  // If there is no category @interface then there can be no properties.
994  if (Category) {
995    Values[6] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") + ExtName,
996                                 OCD,
997                                 Category->classprop_begin(),
998                                 Category->classprop_end());
999  } else {
1000    Values[6] = llvm::Constant::getNullValue(ObjCTypes.PropertyListPtrTy);
1001  }
1002
1003  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.CategoryTy,
1004                                                   Values);
1005
1006  llvm::GlobalVariable *GV =
1007    new llvm::GlobalVariable(ObjCTypes.CategoryTy, false,
1008                             llvm::GlobalValue::InternalLinkage,
1009                             Init,
1010                             std::string("\01L_OBJC_CATEGORY_")+ExtName,
1011                             &CGM.getModule());
1012  GV->setSection("__OBJC,__category,regular,no_dead_strip");
1013  UsedGlobals.push_back(GV);
1014  DefinedCategories.push_back(GV);
1015}
1016
1017// FIXME: Get from somewhere?
1018enum ClassFlags {
1019  eClassFlags_Factory              = 0x00001,
1020  eClassFlags_Meta                 = 0x00002,
1021  // <rdr://5142207>
1022  eClassFlags_HasCXXStructors      = 0x02000,
1023  eClassFlags_Hidden               = 0x20000,
1024  eClassFlags_ABI2_Hidden          = 0x00010,
1025  eClassFlags_ABI2_HasCXXStructors = 0x00004   // <rdr://4923634>
1026};
1027
1028// <rdr://5142207&4705298&4843145>
1029static bool IsClassHidden(const ObjCInterfaceDecl *ID) {
1030  if (const VisibilityAttr *attr = ID->getAttr<VisibilityAttr>()) {
1031    // FIXME: Support -fvisibility
1032    switch (attr->getVisibility()) {
1033    default:
1034      assert(0 && "Unknown visibility");
1035      return false;
1036    case VisibilityAttr::DefaultVisibility:
1037    case VisibilityAttr::ProtectedVisibility:  // FIXME: What do we do here?
1038      return false;
1039    case VisibilityAttr::HiddenVisibility:
1040      return true;
1041    }
1042  } else {
1043    return false; // FIXME: Support -fvisibility
1044  }
1045}
1046
1047/*
1048  struct _objc_class {
1049    Class isa;
1050    Class super_class;
1051    const char *name;
1052    long version;
1053    long info;
1054    long instance_size;
1055    struct _objc_ivar_list *ivars;
1056    struct _objc_method_list *methods;
1057    struct _objc_cache *cache;
1058    struct _objc_protocol_list *protocols;
1059    // Objective-C 1.0 extensions (<rdr://4585769>)
1060    const char *ivar_layout;
1061    struct _objc_class_ext *ext;
1062  };
1063
1064  See EmitClassExtension();
1065 */
1066void CGObjCMac::GenerateClass(const ObjCImplementationDecl *ID) {
1067  DefinedSymbols.insert(ID->getIdentifier());
1068
1069  const char *ClassName = ID->getIdentifierName();
1070  // FIXME: Gross
1071  ObjCInterfaceDecl *Interface =
1072    const_cast<ObjCInterfaceDecl*>(ID->getClassInterface());
1073  llvm::Constant *Protocols =
1074    EmitProtocolList(std::string("\01L_OBJC_CLASS_PROTOCOLS_") + ID->getName(),
1075                     Interface->protocol_begin(),
1076                     Interface->protocol_end());
1077  const llvm::Type *InterfaceTy =
1078   CGM.getTypes().ConvertType(CGM.getContext().getObjCInterfaceType(Interface));
1079  unsigned Flags = eClassFlags_Factory;
1080  unsigned Size = CGM.getTargetData().getABITypeSize(InterfaceTy);
1081
1082  // FIXME: Set CXX-structors flag.
1083  if (IsClassHidden(ID->getClassInterface()))
1084    Flags |= eClassFlags_Hidden;
1085
1086  std::vector<llvm::Constant*> InstanceMethods, ClassMethods;
1087  for (ObjCImplementationDecl::instmeth_iterator i = ID->instmeth_begin(),
1088         e = ID->instmeth_end(); i != e; ++i) {
1089    // Instance methods should always be defined.
1090    InstanceMethods.push_back(GetMethodConstant(*i));
1091  }
1092  for (ObjCImplementationDecl::classmeth_iterator i = ID->classmeth_begin(),
1093         e = ID->classmeth_end(); i != e; ++i) {
1094    // Class methods should always be defined.
1095    ClassMethods.push_back(GetMethodConstant(*i));
1096  }
1097
1098  for (ObjCImplementationDecl::propimpl_iterator i = ID->propimpl_begin(),
1099         e = ID->propimpl_end(); i != e; ++i) {
1100    ObjCPropertyImplDecl *PID = *i;
1101
1102    if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1103      ObjCPropertyDecl *PD = PID->getPropertyDecl();
1104
1105      if (ObjCMethodDecl *MD = PD->getGetterMethodDecl())
1106        if (llvm::Constant *C = GetMethodConstant(MD))
1107          InstanceMethods.push_back(C);
1108      if (ObjCMethodDecl *MD = PD->getSetterMethodDecl())
1109        if (llvm::Constant *C = GetMethodConstant(MD))
1110          InstanceMethods.push_back(C);
1111    }
1112  }
1113
1114  std::vector<llvm::Constant*> Values(12);
1115  Values[ 0] = EmitMetaClass(ID, Protocols, InterfaceTy, ClassMethods);
1116  if (ObjCInterfaceDecl *Super = Interface->getSuperClass()) {
1117    // Record a reference to the super class.
1118    LazySymbols.insert(Super->getIdentifier());
1119
1120    Values[ 1] =
1121      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1122                                     ObjCTypes.ClassPtrTy);
1123  } else {
1124    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1125  }
1126  Values[ 2] = GetClassName(ID->getIdentifier());
1127  // Version is always 0.
1128  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1129  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1130  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1131  Values[ 6] = EmitIvarList(ID, false, InterfaceTy);
1132  Values[ 7] =
1133    EmitMethodList(std::string("\01L_OBJC_INSTANCE_METHODS_") + ID->getName(),
1134                   "__OBJC,__inst_meth,regular,no_dead_strip",
1135                   InstanceMethods);
1136  // cache is always NULL.
1137  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1138  Values[ 9] = Protocols;
1139  // FIXME: Set ivar_layout
1140  Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1141  Values[11] = EmitClassExtension(ID);
1142  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1143                                                   Values);
1144
1145  llvm::GlobalVariable *GV =
1146    new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1147                             llvm::GlobalValue::InternalLinkage,
1148                             Init,
1149                             std::string("\01L_OBJC_CLASS_")+ClassName,
1150                             &CGM.getModule());
1151  GV->setSection("__OBJC,__class,regular,no_dead_strip");
1152  UsedGlobals.push_back(GV);
1153  // FIXME: Why?
1154  GV->setAlignment(32);
1155  DefinedClasses.push_back(GV);
1156}
1157
1158llvm::Constant *CGObjCMac::EmitMetaClass(const ObjCImplementationDecl *ID,
1159                                         llvm::Constant *Protocols,
1160                                         const llvm::Type *InterfaceTy,
1161                                         const ConstantVector &Methods) {
1162  const char *ClassName = ID->getIdentifierName();
1163  unsigned Flags = eClassFlags_Meta;
1164  unsigned Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ClassTy);
1165
1166  if (IsClassHidden(ID->getClassInterface()))
1167    Flags |= eClassFlags_Hidden;
1168
1169  std::vector<llvm::Constant*> Values(12);
1170  // The isa for the metaclass is the root of the hierarchy.
1171  const ObjCInterfaceDecl *Root = ID->getClassInterface();
1172  while (const ObjCInterfaceDecl *Super = Root->getSuperClass())
1173    Root = Super;
1174  Values[ 0] =
1175    llvm::ConstantExpr::getBitCast(GetClassName(Root->getIdentifier()),
1176                                   ObjCTypes.ClassPtrTy);
1177  // The super class for the metaclass is emitted as the name of the
1178  // super class. The runtime fixes this up to point to the
1179  // *metaclass* for the super class.
1180  if (ObjCInterfaceDecl *Super = ID->getClassInterface()->getSuperClass()) {
1181    Values[ 1] =
1182      llvm::ConstantExpr::getBitCast(GetClassName(Super->getIdentifier()),
1183                                     ObjCTypes.ClassPtrTy);
1184  } else {
1185    Values[ 1] = llvm::Constant::getNullValue(ObjCTypes.ClassPtrTy);
1186  }
1187  Values[ 2] = GetClassName(ID->getIdentifier());
1188  // Version is always 0.
1189  Values[ 3] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1190  Values[ 4] = llvm::ConstantInt::get(ObjCTypes.LongTy, Flags);
1191  Values[ 5] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1192  Values[ 6] = EmitIvarList(ID, true, InterfaceTy);
1193  Values[ 7] =
1194    EmitMethodList(std::string("\01L_OBJC_CLASS_METHODS_") + ID->getName(),
1195                   "__OBJC,__inst_meth,regular,no_dead_strip",
1196                   Methods);
1197  // cache is always NULL.
1198  Values[ 8] = llvm::Constant::getNullValue(ObjCTypes.CachePtrTy);
1199  Values[ 9] = Protocols;
1200  // ivar_layout for metaclass is always NULL.
1201  Values[10] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1202  // The class extension is always unused for metaclasses.
1203  Values[11] = llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1204  llvm::Constant *Init = llvm::ConstantStruct::get(ObjCTypes.ClassTy,
1205                                                   Values);
1206
1207  std::string Name("\01L_OBJC_METACLASS_");
1208  Name += ClassName;
1209
1210  // Check for a forward reference.
1211  llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name);
1212  if (GV) {
1213    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1214           "Forward metaclass reference has incorrect type.");
1215    GV->setLinkage(llvm::GlobalValue::InternalLinkage);
1216    GV->setInitializer(Init);
1217  } else {
1218    GV = new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1219                                  llvm::GlobalValue::InternalLinkage,
1220                                  Init, Name,
1221                                  &CGM.getModule());
1222  }
1223  GV->setSection("__OBJC,__meta_class,regular,no_dead_strip");
1224  UsedGlobals.push_back(GV);
1225  // FIXME: Why?
1226  GV->setAlignment(32);
1227
1228  return GV;
1229}
1230
1231llvm::Constant *CGObjCMac::EmitMetaClassRef(const ObjCInterfaceDecl *ID) {
1232  std::string Name("\01L_OBJC_METACLASS_");
1233  Name += ID->getName();
1234
1235  // FIXME: Should we look these up somewhere other than the
1236  // module. Its a bit silly since we only generate these while
1237  // processing an implementation, so exactly one pointer would work
1238  // if know when we entered/exitted an implementation block.
1239
1240  // Check for an existing forward reference.
1241  if (llvm::GlobalVariable *GV = CGM.getModule().getGlobalVariable(Name)) {
1242    assert(GV->getType()->getElementType() == ObjCTypes.ClassTy &&
1243           "Forward metaclass reference has incorrect type.");
1244    return GV;
1245  } else {
1246    // Generate as an external reference to keep a consistent
1247    // module. This will be patched up when we emit the metaclass.
1248    return new llvm::GlobalVariable(ObjCTypes.ClassTy, false,
1249                                    llvm::GlobalValue::ExternalLinkage,
1250                                    0,
1251                                    Name,
1252                                    &CGM.getModule());
1253  }
1254}
1255
1256/*
1257  struct objc_class_ext {
1258    uint32_t size;
1259    const char *weak_ivar_layout;
1260    struct _objc_property_list *properties;
1261  };
1262*/
1263llvm::Constant *
1264CGObjCMac::EmitClassExtension(const ObjCImplementationDecl *ID) {
1265  uint64_t Size =
1266    CGM.getTargetData().getABITypeSize(ObjCTypes.ClassExtensionTy);
1267
1268  std::vector<llvm::Constant*> Values(3);
1269  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Size);
1270  // FIXME: Output weak_ivar_layout string.
1271  Values[1] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1272  Values[2] = EmitPropertyList(std::string("\01L_OBJC_$_PROP_LIST_") +
1273                               ID->getName(),
1274                               ID,
1275                               ID->getClassInterface()->classprop_begin(),
1276                               ID->getClassInterface()->classprop_end());
1277
1278  // Return null if no extension bits are used.
1279  if (Values[1]->isNullValue() && Values[2]->isNullValue())
1280    return llvm::Constant::getNullValue(ObjCTypes.ClassExtensionPtrTy);
1281
1282  llvm::Constant *Init =
1283    llvm::ConstantStruct::get(ObjCTypes.ClassExtensionTy, Values);
1284  llvm::GlobalVariable *GV =
1285    new llvm::GlobalVariable(ObjCTypes.ClassExtensionTy, false,
1286                             llvm::GlobalValue::InternalLinkage,
1287                             Init,
1288                             (std::string("\01L_OBJC_CLASSEXT_") +
1289                              ID->getName()),
1290                             &CGM.getModule());
1291  // No special section, but goes in llvm.used
1292  UsedGlobals.push_back(GV);
1293
1294  return GV;
1295}
1296
1297/*
1298  struct objc_ivar {
1299    char *ivar_name;
1300    char *ivar_type;
1301    int ivar_offset;
1302  };
1303
1304  struct objc_ivar_list {
1305    int ivar_count;
1306    struct objc_ivar list[count];
1307  };
1308 */
1309llvm::Constant *CGObjCMac::EmitIvarList(const ObjCImplementationDecl *ID,
1310                                        bool ForClass,
1311                                        const llvm::Type *InterfaceTy) {
1312  std::vector<llvm::Constant*> Ivars, Ivar(3);
1313
1314  // When emitting the root class GCC emits ivar entries for the
1315  // actual class structure. It is not clear if we need to follow this
1316  // behavior; for now lets try and get away with not doing it. If so,
1317  // the cleanest solution would be to make up an ObjCInterfaceDecl
1318  // for the class.
1319  if (ForClass)
1320    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1321
1322  const llvm::StructLayout *Layout =
1323    CGM.getTargetData().getStructLayout(cast<llvm::StructType>(InterfaceTy));
1324  for (ObjCInterfaceDecl::ivar_iterator
1325         i = ID->getClassInterface()->ivar_begin(),
1326         e = ID->getClassInterface()->ivar_end(); i != e; ++i) {
1327    ObjCIvarDecl *V = *i;
1328    unsigned Offset =
1329      Layout->getElementOffset(CGM.getTypes().getLLVMFieldNo(V));
1330    std::string TypeStr;
1331    Ivar[0] = GetMethodVarName(V->getIdentifier());
1332    CGM.getContext().getObjCEncodingForType(V->getType(), TypeStr, true);
1333    Ivar[1] = GetMethodVarType(TypeStr);
1334    Ivar[2] = llvm::ConstantInt::get(ObjCTypes.IntTy, Offset);
1335    Ivars.push_back(llvm::ConstantStruct::get(ObjCTypes.IvarTy, Ivar));
1336  }
1337
1338  // Return null for empty list.
1339  if (Ivars.empty())
1340    return llvm::Constant::getNullValue(ObjCTypes.IvarListPtrTy);
1341
1342  std::vector<llvm::Constant*> Values(2);
1343  Values[0] = llvm::ConstantInt::get(ObjCTypes.IntTy, Ivars.size());
1344  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.IvarTy,
1345                                             Ivars.size());
1346  Values[1] = llvm::ConstantArray::get(AT, Ivars);
1347  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1348
1349  const char *Prefix = (ForClass ? "\01L_OBJC_CLASS_VARIABLES_" :
1350                        "\01L_OBJC_INSTANCE_VARIABLES_");
1351  llvm::GlobalVariable *GV =
1352    new llvm::GlobalVariable(Init->getType(), false,
1353                             llvm::GlobalValue::InternalLinkage,
1354                             Init,
1355                             std::string(Prefix) + ID->getName(),
1356                             &CGM.getModule());
1357  if (ForClass) {
1358    GV->setSection("__OBJC,__cls_vars,regular,no_dead_strip");
1359    // FIXME: Why is this only here?
1360    GV->setAlignment(32);
1361  } else {
1362    GV->setSection("__OBJC,__instance_vars,regular,no_dead_strip");
1363  }
1364  UsedGlobals.push_back(GV);
1365  return llvm::ConstantExpr::getBitCast(GV,
1366                                        ObjCTypes.IvarListPtrTy);
1367}
1368
1369/*
1370  struct objc_method {
1371    SEL method_name;
1372    char *method_types;
1373    void *method;
1374  };
1375
1376  struct objc_method_list {
1377    struct objc_method_list *obsolete;
1378    int count;
1379    struct objc_method methods_list[count];
1380  };
1381*/
1382
1383/// GetMethodConstant - Return a struct objc_method constant for the
1384/// given method if it has been defined. The result is null if the
1385/// method has not been defined. The return value has type MethodPtrTy.
1386llvm::Constant *CGObjCMac::GetMethodConstant(const ObjCMethodDecl *MD) {
1387  // FIXME: Use DenseMap::lookup
1388  llvm::Function *Fn = MethodDefinitions[MD];
1389  if (!Fn)
1390    return 0;
1391
1392  std::vector<llvm::Constant*> Method(3);
1393  Method[0] =
1394    llvm::ConstantExpr::getBitCast(GetMethodVarName(MD->getSelector()),
1395                                   ObjCTypes.SelectorPtrTy);
1396  Method[1] = GetMethodVarType(MD);
1397  Method[2] = llvm::ConstantExpr::getBitCast(Fn, ObjCTypes.Int8PtrTy);
1398  return llvm::ConstantStruct::get(ObjCTypes.MethodTy, Method);
1399}
1400
1401llvm::Constant *CGObjCMac::EmitMethodList(const std::string &Name,
1402                                          const char *Section,
1403                                          const ConstantVector &Methods) {
1404  // Return null for empty list.
1405  if (Methods.empty())
1406    return llvm::Constant::getNullValue(ObjCTypes.MethodListPtrTy);
1407
1408  std::vector<llvm::Constant*> Values(3);
1409  Values[0] = llvm::Constant::getNullValue(ObjCTypes.Int8PtrTy);
1410  Values[1] = llvm::ConstantInt::get(ObjCTypes.IntTy, Methods.size());
1411  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.MethodTy,
1412                                             Methods.size());
1413  Values[2] = llvm::ConstantArray::get(AT, Methods);
1414  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1415
1416  llvm::GlobalVariable *GV =
1417    new llvm::GlobalVariable(Init->getType(), false,
1418                             llvm::GlobalValue::InternalLinkage,
1419                             Init,
1420                             Name,
1421                             &CGM.getModule());
1422  GV->setSection(Section);
1423  UsedGlobals.push_back(GV);
1424  return llvm::ConstantExpr::getBitCast(GV,
1425                                        ObjCTypes.MethodListPtrTy);
1426}
1427
1428llvm::Function *CGObjCMac::GenerateMethod(const ObjCMethodDecl *OMD) {
1429  std::string Name;
1430  GetNameForMethod(OMD, Name);
1431
1432  const llvm::FunctionType *MethodTy =
1433    CGM.getTypes().GetFunctionType(CGFunctionInfo(OMD, CGM.getContext()));
1434  llvm::Function *Method =
1435    llvm::Function::Create(MethodTy,
1436                           llvm::GlobalValue::InternalLinkage,
1437                           Name,
1438                           &CGM.getModule());
1439  MethodDefinitions.insert(std::make_pair(OMD, Method));
1440
1441  return Method;
1442}
1443
1444llvm::Function *CGObjCMac::ModuleInitFunction() {
1445  // Abuse this interface function as a place to finalize.
1446  FinishModule();
1447
1448  return NULL;
1449}
1450
1451llvm::Function *CGObjCMac::GetPropertyGetFunction() {
1452  return ObjCTypes.GetPropertyFn;
1453}
1454
1455llvm::Function *CGObjCMac::GetPropertySetFunction() {
1456  return ObjCTypes.SetPropertyFn;
1457}
1458
1459llvm::Function *CGObjCMac::EnumerationMutationFunction()
1460{
1461  return ObjCTypes.EnumerationMutationFn;
1462}
1463
1464/*
1465
1466Objective-C setjmp-longjmp (sjlj) Exception Handling
1467--
1468
1469The basic framework for a @try-catch-finally is as follows:
1470{
1471  objc_exception_data d;
1472  id _rethrow = null;
1473
1474  objc_exception_try_enter(&d);
1475  if (!setjmp(d.jmp_buf)) {
1476    ... try body ...
1477  } else {
1478    // exception path
1479    id _caught = objc_exception_extract(&d);
1480
1481    // enter new try scope for handlers
1482    if (!setjmp(d.jmp_buf)) {
1483      ... match exception and execute catch blocks ...
1484
1485      // fell off end, rethrow.
1486      _rethrow = _caught;
1487      ... jump-through-finally to finally_rethrow ...
1488    } else {
1489      // exception in catch block
1490      _rethrow = objc_exception_extract(&d);
1491      ... jump-through-finally_no_exit to finally_rethrow ...
1492    }
1493  }
1494  ... jump-through-finally to finally_end ...
1495
1496finally:
1497  // match either the initial try_enter or the catch try_enter,
1498  // depending on the path followed.
1499  objc_exception_try_exit(&d);
1500finally_no_exit:
1501  ... finally block ....
1502  ... dispatch to finally destination ...
1503
1504finally_rethrow:
1505  objc_exception_throw(_rethrow);
1506
1507finally_end:
1508}
1509
1510This framework differs slightly from the one gcc uses, in that gcc
1511uses _rethrow to determine if objc_exception_try_exit should be called
1512and if the object should be rethrown. This breaks in the face of
1513throwing nil and introduces unnecessary branches.
1514
1515We specialize this framework for a few particular circumstances:
1516
1517 - If there are no catch blocks, then we avoid emitting the second
1518   exception handling context.
1519
1520 - If there is a catch-all catch block (i.e. @catch(...) or @catch(id
1521   e)) we avoid emitting the code to rethrow an uncaught exception.
1522
1523 - FIXME: If there is no @finally block we can do a few more
1524   simplifications.
1525
1526Rethrows and Jumps-Through-Finally
1527--
1528
1529Support for implicit rethrows and jumping through the finally block is
1530handled by storing the current exception-handling context in
1531ObjCEHStack.
1532
1533In order to implement proper @finally semantics, we support one basic
1534mechanism for jumping through the finally block to an arbitrary
1535destination. Constructs which generate exits from a @try or @catch
1536block use this mechanism to implement the proper semantics by chaining
1537jumps, as necessary.
1538
1539This mechanism works like the one used for indirect goto: we
1540arbitrarily assign an ID to each destination and store the ID for the
1541destination in a variable prior to entering the finally block. At the
1542end of the finally block we simply create a switch to the proper
1543destination.
1544
1545*/
1546
1547void CGObjCMac::EmitTryStmt(CodeGen::CodeGenFunction &CGF,
1548                            const ObjCAtTryStmt &S) {
1549  // Create various blocks we refer to for handling @finally.
1550  llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1551  llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1552  llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1553  llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1554  llvm::Value *DestCode =
1555    CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1556
1557  // Generate jump code. Done here so we can directly add things to
1558  // the switch instruction.
1559  llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
1560  llvm::SwitchInst *FinallySwitch =
1561    llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1562                             FinallyEnd, 10, FinallyJump);
1563
1564  // Push an EH context entry, used for handling rethrows and jumps
1565  // through finally.
1566  CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1567                                       FinallySwitch, DestCode);
1568  CGF.ObjCEHStack.push_back(&EHEntry);
1569
1570  // Allocate memory for the exception data and rethrow pointer.
1571  llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1572                                                    "exceptiondata.ptr");
1573  llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1574                                                 "_rethrow");
1575
1576  // Enter a new try block and call setjmp.
1577  CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1578  llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1579                                                       "jmpbufarray");
1580  JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1581  llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1582                                                     JmpBufPtr, "result");
1583
1584  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1585  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1586  CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
1587                           TryHandler, TryBlock);
1588
1589  // Emit the @try block.
1590  CGF.EmitBlock(TryBlock);
1591  CGF.EmitStmt(S.getTryBody());
1592  CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1593
1594  // Emit the "exception in @try" block.
1595  CGF.EmitBlock(TryHandler);
1596
1597  // Retrieve the exception object.  We may emit multiple blocks but
1598  // nothing can cross this so the value is already in SSA form.
1599  llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1600                                               ExceptionData,
1601                                               "caught");
1602  EHEntry.Exception = Caught;
1603  if (const ObjCAtCatchStmt* CatchStmt = S.getCatchStmts()) {
1604    // Enter a new exception try block (in case a @catch block throws
1605    // an exception).
1606    CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1607
1608    llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1609                                                       JmpBufPtr, "result");
1610    llvm::Value *Threw = CGF.Builder.CreateIsNotNull(SetJmpResult, "threw");
1611
1612    llvm::BasicBlock *CatchBlock = CGF.createBasicBlock("catch");
1613    llvm::BasicBlock *CatchHandler = CGF.createBasicBlock("catch.handler");
1614    CGF.Builder.CreateCondBr(Threw, CatchHandler, CatchBlock);
1615
1616    CGF.EmitBlock(CatchBlock);
1617
1618    // Handle catch list. As a special case we check if everything is
1619    // matched and avoid generating code for falling off the end if
1620    // so.
1621    bool AllMatched = false;
1622    for (; CatchStmt; CatchStmt = CatchStmt->getNextCatchStmt()) {
1623      llvm::BasicBlock *NextCatchBlock = CGF.createBasicBlock("catch");
1624
1625      const DeclStmt *CatchParam =
1626        cast_or_null<DeclStmt>(CatchStmt->getCatchParamStmt());
1627      const VarDecl *VD = 0;
1628      const PointerType *PT = 0;
1629
1630      // catch(...) always matches.
1631      if (!CatchParam) {
1632        AllMatched = true;
1633      } else {
1634        VD = cast<VarDecl>(CatchParam->getSolitaryDecl());
1635        PT = VD->getType()->getAsPointerType();
1636
1637        // catch(id e) always matches.
1638        // FIXME: For the time being we also match id<X>; this should
1639        // be rejected by Sema instead.
1640        if ((PT && CGF.getContext().isObjCIdType(PT->getPointeeType())) ||
1641            VD->getType()->isObjCQualifiedIdType())
1642          AllMatched = true;
1643      }
1644
1645      if (AllMatched) {
1646        if (CatchParam) {
1647          CGF.EmitStmt(CatchParam);
1648          assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
1649          CGF.Builder.CreateStore(Caught, CGF.GetAddrOfLocalVar(VD));
1650        }
1651
1652        CGF.EmitStmt(CatchStmt->getCatchBody());
1653        CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1654        break;
1655      }
1656
1657      assert(PT && "Unexpected non-pointer type in @catch");
1658      QualType T = PT->getPointeeType();
1659      const ObjCInterfaceType *ObjCType = T->getAsObjCInterfaceType();
1660      assert(ObjCType && "Catch parameter must have Objective-C type!");
1661
1662      // Check if the @catch block matches the exception object.
1663      llvm::Value *Class = EmitClassRef(CGF.Builder, ObjCType->getDecl());
1664
1665      llvm::Value *Match = CGF.Builder.CreateCall2(ObjCTypes.ExceptionMatchFn,
1666                                                   Class, Caught, "match");
1667
1668      llvm::BasicBlock *MatchedBlock = CGF.createBasicBlock("matched");
1669
1670      CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(Match, "matched"),
1671                               MatchedBlock, NextCatchBlock);
1672
1673      // Emit the @catch block.
1674      CGF.EmitBlock(MatchedBlock);
1675      CGF.EmitStmt(CatchParam);
1676      assert(CGF.HaveInsertPoint() && "DeclStmt destroyed insert point?");
1677
1678      llvm::Value *Tmp =
1679        CGF.Builder.CreateBitCast(Caught, CGF.ConvertType(VD->getType()),
1680                                  "tmp");
1681      CGF.Builder.CreateStore(Tmp, CGF.GetAddrOfLocalVar(VD));
1682
1683      CGF.EmitStmt(CatchStmt->getCatchBody());
1684      CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1685
1686      CGF.EmitBlock(NextCatchBlock);
1687    }
1688
1689    if (!AllMatched) {
1690      // None of the handlers caught the exception, so store it to be
1691      // rethrown at the end of the @finally block.
1692      CGF.Builder.CreateStore(Caught, RethrowPtr);
1693      CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow);
1694    }
1695
1696    // Emit the exception handler for the @catch blocks.
1697    CGF.EmitBlock(CatchHandler);
1698    CGF.Builder.CreateStore(CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1699                                                   ExceptionData),
1700                            RethrowPtr);
1701    CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1702  } else {
1703    CGF.Builder.CreateStore(Caught, RethrowPtr);
1704    CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1705  }
1706
1707  // Pop the exception-handling stack entry. It is important to do
1708  // this now, because the code in the @finally block is not in this
1709  // context.
1710  CGF.ObjCEHStack.pop_back();
1711
1712  // Emit the @finally block.
1713  CGF.EmitBlock(FinallyBlock);
1714  CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
1715
1716  CGF.EmitBlock(FinallyNoExit);
1717  if (const ObjCAtFinallyStmt* FinallyStmt = S.getFinallyStmt())
1718    CGF.EmitStmt(FinallyStmt->getFinallyBody());
1719
1720  CGF.EmitBlock(FinallyJump);
1721
1722  CGF.EmitBlock(FinallyRethrow);
1723  CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1724                         CGF.Builder.CreateLoad(RethrowPtr));
1725  CGF.Builder.CreateUnreachable();
1726
1727  CGF.EmitBlock(FinallyEnd);
1728}
1729
1730void CGObjCMac::EmitThrowStmt(CodeGen::CodeGenFunction &CGF,
1731                              const ObjCAtThrowStmt &S) {
1732  llvm::Value *ExceptionAsObject;
1733
1734  if (const Expr *ThrowExpr = S.getThrowExpr()) {
1735    llvm::Value *Exception = CGF.EmitScalarExpr(ThrowExpr);
1736    ExceptionAsObject =
1737      CGF.Builder.CreateBitCast(Exception, ObjCTypes.ObjectPtrTy, "tmp");
1738  } else {
1739    assert((!CGF.ObjCEHStack.empty() && CGF.ObjCEHStack.back()->Exception) &&
1740           "Unexpected rethrow outside @catch block.");
1741    ExceptionAsObject = CGF.ObjCEHStack.back()->Exception;
1742  }
1743
1744  CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn, ExceptionAsObject);
1745  CGF.Builder.CreateUnreachable();
1746
1747  // Clear the insertion point to indicate we are in unreachable code.
1748  CGF.Builder.ClearInsertionPoint();
1749}
1750
1751void CodeGenFunction::EmitJumpThroughFinally(ObjCEHEntry *E,
1752                                             llvm::BasicBlock *Dst,
1753                                             bool ExecuteTryExit) {
1754  if (!HaveInsertPoint())
1755    return;
1756
1757  // Find the destination code for this block. We always use 0 for the
1758  // fallthrough block (default destination).
1759  llvm::SwitchInst *SI = E->FinallySwitch;
1760  llvm::ConstantInt *ID;
1761  if (Dst == SI->getDefaultDest()) {
1762    ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
1763  } else {
1764    ID = SI->findCaseDest(Dst);
1765    if (!ID) {
1766      // No code found, get a new unique one by just using the number
1767      // of switch successors.
1768      ID = llvm::ConstantInt::get(llvm::Type::Int32Ty, SI->getNumSuccessors());
1769      SI->addCase(ID, Dst);
1770    }
1771  }
1772
1773  // Set the destination code and branch.
1774  Builder.CreateStore(ID, E->DestCode);
1775  EmitBranch(ExecuteTryExit ? E->FinallyBlock : E->FinallyNoExit);
1776}
1777
1778/// EmitSynchronizedStmt - Code gen for @synchronized(expr) stmt;
1779/// Effectively generating code for:
1780/// objc_sync_enter(expr);
1781/// @try stmt @finally { objc_sync_exit(expr); }
1782void CGObjCMac::EmitSynchronizedStmt(CodeGen::CodeGenFunction &CGF,
1783                                     const ObjCAtSynchronizedStmt &S) {
1784  // Create various blocks we refer to for handling @finally.
1785  llvm::BasicBlock *FinallyBlock = CGF.createBasicBlock("finally");
1786  llvm::BasicBlock *FinallyNoExit = CGF.createBasicBlock("finally.noexit");
1787  llvm::BasicBlock *FinallyRethrow = CGF.createBasicBlock("finally.throw");
1788  llvm::BasicBlock *FinallyEnd = CGF.createBasicBlock("finally.end");
1789  llvm::Value *DestCode =
1790  CGF.CreateTempAlloca(llvm::Type::Int32Ty, "finally.dst");
1791
1792  // Generate jump code. Done here so we can directly add things to
1793  // the switch instruction.
1794  llvm::BasicBlock *FinallyJump = CGF.createBasicBlock("finally.jump");
1795  llvm::SwitchInst *FinallySwitch =
1796  llvm::SwitchInst::Create(new llvm::LoadInst(DestCode, "", FinallyJump),
1797                           FinallyEnd, 10, FinallyJump);
1798
1799  // Push an EH context entry, used for handling rethrows and jumps
1800  // through finally.
1801  CodeGenFunction::ObjCEHEntry EHEntry(FinallyBlock, FinallyNoExit,
1802                                       FinallySwitch, DestCode);
1803  CGF.ObjCEHStack.push_back(&EHEntry);
1804
1805  // Allocate memory for the exception data and rethrow pointer.
1806  llvm::Value *ExceptionData = CGF.CreateTempAlloca(ObjCTypes.ExceptionDataTy,
1807                                                    "exceptiondata.ptr");
1808  llvm::Value *RethrowPtr = CGF.CreateTempAlloca(ObjCTypes.ObjectPtrTy,
1809                                                 "_rethrow");
1810  // Call objc_sync_enter(sync.expr)
1811  CGF.Builder.CreateCall(ObjCTypes.SyncEnterFn,
1812                         CGF.EmitScalarExpr(S.getSynchExpr()));
1813
1814  // Enter a new try block and call setjmp.
1815  CGF.Builder.CreateCall(ObjCTypes.ExceptionTryEnterFn, ExceptionData);
1816  llvm::Value *JmpBufPtr = CGF.Builder.CreateStructGEP(ExceptionData, 0,
1817                                                       "jmpbufarray");
1818  JmpBufPtr = CGF.Builder.CreateStructGEP(JmpBufPtr, 0, "tmp");
1819  llvm::Value *SetJmpResult = CGF.Builder.CreateCall(ObjCTypes.SetJmpFn,
1820                                                     JmpBufPtr, "result");
1821
1822  llvm::BasicBlock *TryBlock = CGF.createBasicBlock("try");
1823  llvm::BasicBlock *TryHandler = CGF.createBasicBlock("try.handler");
1824  CGF.Builder.CreateCondBr(CGF.Builder.CreateIsNotNull(SetJmpResult, "threw"),
1825                           TryHandler, TryBlock);
1826
1827  // Emit the @try block.
1828  CGF.EmitBlock(TryBlock);
1829  CGF.EmitStmt(S.getSynchBody());
1830  CGF.EmitJumpThroughFinally(&EHEntry, FinallyEnd);
1831
1832  // Emit the "exception in @try" block.
1833  CGF.EmitBlock(TryHandler);
1834
1835  // Retrieve the exception object.  We may emit multiple blocks but
1836  // nothing can cross this so the value is already in SSA form.
1837  llvm::Value *Caught = CGF.Builder.CreateCall(ObjCTypes.ExceptionExtractFn,
1838                                               ExceptionData,
1839                                               "caught");
1840  EHEntry.Exception = Caught;
1841  CGF.Builder.CreateStore(Caught, RethrowPtr);
1842  CGF.EmitJumpThroughFinally(&EHEntry, FinallyRethrow, false);
1843
1844  // Pop the exception-handling stack entry. It is important to do
1845  // this now, because the code in the @finally block is not in this
1846  // context.
1847  CGF.ObjCEHStack.pop_back();
1848
1849  // Emit the @finally block.
1850  CGF.EmitBlock(FinallyBlock);
1851  CGF.Builder.CreateCall(ObjCTypes.ExceptionTryExitFn, ExceptionData);
1852
1853  CGF.EmitBlock(FinallyNoExit);
1854  // objc_sync_exit(expr); As finally's sole statement.
1855  CGF.Builder.CreateCall(ObjCTypes.SyncExitFn,
1856                         CGF.EmitScalarExpr(S.getSynchExpr()));
1857
1858  CGF.EmitBlock(FinallyJump);
1859
1860  CGF.EmitBlock(FinallyRethrow);
1861  CGF.Builder.CreateCall(ObjCTypes.ExceptionThrowFn,
1862                         CGF.Builder.CreateLoad(RethrowPtr));
1863  CGF.Builder.CreateUnreachable();
1864
1865  CGF.EmitBlock(FinallyEnd);
1866}
1867
1868/* *** Private Interface *** */
1869
1870/// EmitImageInfo - Emit the image info marker used to encode some module
1871/// level information.
1872///
1873/// See: <rdr://4810609&4810587&4810587>
1874/// struct IMAGE_INFO {
1875///   unsigned version;
1876///   unsigned flags;
1877/// };
1878enum ImageInfoFlags {
1879  eImageInfo_FixAndContinue   = (1 << 0), // FIXME: Not sure what this implies
1880  eImageInfo_GarbageCollected = (1 << 1),
1881  eImageInfo_GCOnly           = (1 << 2)
1882};
1883
1884void CGObjCMac::EmitImageInfo() {
1885  unsigned version = 0; // Version is unused?
1886  unsigned flags = 0;
1887
1888  // FIXME: Fix and continue?
1889  if (CGM.getLangOptions().getGCMode() != LangOptions::NonGC)
1890    flags |= eImageInfo_GarbageCollected;
1891  if (CGM.getLangOptions().getGCMode() == LangOptions::GCOnly)
1892    flags |= eImageInfo_GCOnly;
1893
1894  // Emitted as int[2];
1895  llvm::Constant *values[2] = {
1896    llvm::ConstantInt::get(llvm::Type::Int32Ty, version),
1897    llvm::ConstantInt::get(llvm::Type::Int32Ty, flags)
1898  };
1899  llvm::ArrayType *AT = llvm::ArrayType::get(llvm::Type::Int32Ty, 2);
1900  llvm::GlobalVariable *GV =
1901    new llvm::GlobalVariable(AT, true,
1902                             llvm::GlobalValue::InternalLinkage,
1903                             llvm::ConstantArray::get(AT, values, 2),
1904                             "\01L_OBJC_IMAGE_INFO",
1905                             &CGM.getModule());
1906
1907  if (ObjCABI == 1) {
1908    GV->setSection("__OBJC, __image_info,regular");
1909  } else {
1910    GV->setSection("__DATA, __objc_imageinfo, regular, no_dead_strip");
1911  }
1912
1913  UsedGlobals.push_back(GV);
1914}
1915
1916
1917// struct objc_module {
1918//   unsigned long version;
1919//   unsigned long size;
1920//   const char *name;
1921//   Symtab symtab;
1922// };
1923
1924// FIXME: Get from somewhere
1925static const int ModuleVersion = 7;
1926
1927void CGObjCMac::EmitModuleInfo() {
1928  uint64_t Size = CGM.getTargetData().getABITypeSize(ObjCTypes.ModuleTy);
1929
1930  std::vector<llvm::Constant*> Values(4);
1931  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, ModuleVersion);
1932  Values[1] = llvm::ConstantInt::get(ObjCTypes.LongTy, Size);
1933  // This used to be the filename, now it is unused. <rdr://4327263>
1934  Values[2] = GetClassName(&CGM.getContext().Idents.get(""));
1935  Values[3] = EmitModuleSymbols();
1936
1937  llvm::GlobalVariable *GV =
1938    new llvm::GlobalVariable(ObjCTypes.ModuleTy, false,
1939                             llvm::GlobalValue::InternalLinkage,
1940                             llvm::ConstantStruct::get(ObjCTypes.ModuleTy,
1941                                                       Values),
1942                             "\01L_OBJC_MODULES",
1943                             &CGM.getModule());
1944  GV->setSection("__OBJC,__module_info,regular,no_dead_strip");
1945  UsedGlobals.push_back(GV);
1946}
1947
1948llvm::Constant *CGObjCMac::EmitModuleSymbols() {
1949  unsigned NumClasses = DefinedClasses.size();
1950  unsigned NumCategories = DefinedCategories.size();
1951
1952  // Return null if no symbols were defined.
1953  if (!NumClasses && !NumCategories)
1954    return llvm::Constant::getNullValue(ObjCTypes.SymtabPtrTy);
1955
1956  std::vector<llvm::Constant*> Values(5);
1957  Values[0] = llvm::ConstantInt::get(ObjCTypes.LongTy, 0);
1958  Values[1] = llvm::Constant::getNullValue(ObjCTypes.SelectorPtrTy);
1959  Values[2] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumClasses);
1960  Values[3] = llvm::ConstantInt::get(ObjCTypes.ShortTy, NumCategories);
1961
1962  // The runtime expects exactly the list of defined classes followed
1963  // by the list of defined categories, in a single array.
1964  std::vector<llvm::Constant*> Symbols(NumClasses + NumCategories);
1965  for (unsigned i=0; i<NumClasses; i++)
1966    Symbols[i] = llvm::ConstantExpr::getBitCast(DefinedClasses[i],
1967                                                ObjCTypes.Int8PtrTy);
1968  for (unsigned i=0; i<NumCategories; i++)
1969    Symbols[NumClasses + i] =
1970      llvm::ConstantExpr::getBitCast(DefinedCategories[i],
1971                                     ObjCTypes.Int8PtrTy);
1972
1973  Values[4] =
1974    llvm::ConstantArray::get(llvm::ArrayType::get(ObjCTypes.Int8PtrTy,
1975                                                  NumClasses + NumCategories),
1976                             Symbols);
1977
1978  llvm::Constant *Init = llvm::ConstantStruct::get(Values);
1979
1980  llvm::GlobalVariable *GV =
1981    new llvm::GlobalVariable(Init->getType(), false,
1982                             llvm::GlobalValue::InternalLinkage,
1983                             Init,
1984                             "\01L_OBJC_SYMBOLS",
1985                             &CGM.getModule());
1986  GV->setSection("__OBJC,__symbols,regular,no_dead_strip");
1987  UsedGlobals.push_back(GV);
1988  return llvm::ConstantExpr::getBitCast(GV, ObjCTypes.SymtabPtrTy);
1989}
1990
1991llvm::Value *CGObjCMac::EmitClassRef(CGBuilderTy &Builder,
1992                                     const ObjCInterfaceDecl *ID) {
1993  LazySymbols.insert(ID->getIdentifier());
1994
1995  llvm::GlobalVariable *&Entry = ClassReferences[ID->getIdentifier()];
1996
1997  if (!Entry) {
1998    llvm::Constant *Casted =
1999      llvm::ConstantExpr::getBitCast(GetClassName(ID->getIdentifier()),
2000                                     ObjCTypes.ClassPtrTy);
2001    Entry =
2002      new llvm::GlobalVariable(ObjCTypes.ClassPtrTy, false,
2003                               llvm::GlobalValue::InternalLinkage,
2004                               Casted, "\01L_OBJC_CLASS_REFERENCES_",
2005                               &CGM.getModule());
2006    Entry->setSection("__OBJC,__cls_refs,literal_pointers,no_dead_strip");
2007    UsedGlobals.push_back(Entry);
2008  }
2009
2010  return Builder.CreateLoad(Entry, false, "tmp");
2011}
2012
2013llvm::Value *CGObjCMac::EmitSelector(CGBuilderTy &Builder, Selector Sel) {
2014  llvm::GlobalVariable *&Entry = SelectorReferences[Sel];
2015
2016  if (!Entry) {
2017    llvm::Constant *Casted =
2018      llvm::ConstantExpr::getBitCast(GetMethodVarName(Sel),
2019                                     ObjCTypes.SelectorPtrTy);
2020    Entry =
2021      new llvm::GlobalVariable(ObjCTypes.SelectorPtrTy, false,
2022                               llvm::GlobalValue::InternalLinkage,
2023                               Casted, "\01L_OBJC_SELECTOR_REFERENCES_",
2024                               &CGM.getModule());
2025    Entry->setSection("__OBJC,__message_refs,literal_pointers,no_dead_strip");
2026    UsedGlobals.push_back(Entry);
2027  }
2028
2029  return Builder.CreateLoad(Entry, false, "tmp");
2030}
2031
2032llvm::Constant *CGObjCMac::GetClassName(IdentifierInfo *Ident) {
2033  llvm::GlobalVariable *&Entry = ClassNames[Ident];
2034
2035  if (!Entry) {
2036    llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2037    Entry =
2038      new llvm::GlobalVariable(C->getType(), false,
2039                               llvm::GlobalValue::InternalLinkage,
2040                               C, "\01L_OBJC_CLASS_NAME_",
2041                               &CGM.getModule());
2042    Entry->setSection("__TEXT,__cstring,cstring_literals");
2043    UsedGlobals.push_back(Entry);
2044  }
2045
2046  return getConstantGEP(Entry, 0, 0);
2047}
2048
2049llvm::Constant *CGObjCMac::GetMethodVarName(Selector Sel) {
2050  llvm::GlobalVariable *&Entry = MethodVarNames[Sel];
2051
2052  if (!Entry) {
2053    llvm::Constant *C = llvm::ConstantArray::get(Sel.getName());
2054    Entry =
2055      new llvm::GlobalVariable(C->getType(), false,
2056                               llvm::GlobalValue::InternalLinkage,
2057                               C, "\01L_OBJC_METH_VAR_NAME_",
2058                               &CGM.getModule());
2059    Entry->setSection("__TEXT,__cstring,cstring_literals");
2060    UsedGlobals.push_back(Entry);
2061  }
2062
2063  return getConstantGEP(Entry, 0, 0);
2064}
2065
2066// FIXME: Merge into a single cstring creation function.
2067llvm::Constant *CGObjCMac::GetMethodVarName(IdentifierInfo *ID) {
2068  return GetMethodVarName(CGM.getContext().Selectors.getNullarySelector(ID));
2069}
2070
2071// FIXME: Merge into a single cstring creation function.
2072llvm::Constant *CGObjCMac::GetMethodVarName(const std::string &Name) {
2073  return GetMethodVarName(&CGM.getContext().Idents.get(Name));
2074}
2075
2076llvm::Constant *CGObjCMac::GetMethodVarType(const std::string &Name) {
2077  llvm::GlobalVariable *&Entry = MethodVarTypes[Name];
2078
2079  if (!Entry) {
2080    llvm::Constant *C = llvm::ConstantArray::get(Name);
2081    Entry =
2082      new llvm::GlobalVariable(C->getType(), false,
2083                               llvm::GlobalValue::InternalLinkage,
2084                               C, "\01L_OBJC_METH_VAR_TYPE_",
2085                               &CGM.getModule());
2086    Entry->setSection("__TEXT,__cstring,cstring_literals");
2087    UsedGlobals.push_back(Entry);
2088  }
2089
2090  return getConstantGEP(Entry, 0, 0);
2091}
2092
2093// FIXME: Merge into a single cstring creation function.
2094llvm::Constant *CGObjCMac::GetMethodVarType(const ObjCMethodDecl *D) {
2095  std::string TypeStr;
2096  CGM.getContext().getObjCEncodingForMethodDecl(const_cast<ObjCMethodDecl*>(D),
2097                                                TypeStr);
2098  return GetMethodVarType(TypeStr);
2099}
2100
2101// FIXME: Merge into a single cstring creation function.
2102llvm::Constant *CGObjCMac::GetPropertyName(IdentifierInfo *Ident) {
2103  llvm::GlobalVariable *&Entry = PropertyNames[Ident];
2104
2105  if (!Entry) {
2106    llvm::Constant *C = llvm::ConstantArray::get(Ident->getName());
2107    Entry =
2108      new llvm::GlobalVariable(C->getType(), false,
2109                               llvm::GlobalValue::InternalLinkage,
2110                               C, "\01L_OBJC_PROP_NAME_ATTR_",
2111                               &CGM.getModule());
2112    Entry->setSection("__TEXT,__cstring,cstring_literals");
2113    UsedGlobals.push_back(Entry);
2114  }
2115
2116  return getConstantGEP(Entry, 0, 0);
2117}
2118
2119// FIXME: Merge into a single cstring creation function.
2120// FIXME: This Decl should be more precise.
2121llvm::Constant *CGObjCMac::GetPropertyTypeString(const ObjCPropertyDecl *PD,
2122                                                 const Decl *Container) {
2123  std::string TypeStr;
2124  CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container, TypeStr);
2125  return GetPropertyName(&CGM.getContext().Idents.get(TypeStr));
2126}
2127
2128void CGObjCMac::GetNameForMethod(const ObjCMethodDecl *D,
2129                                 std::string &NameOut) {
2130  // FIXME: Find the mangling GCC uses.
2131  std::stringstream s;
2132  s << (D->isInstance() ? "-" : "+");
2133  s << "[";
2134  s << D->getClassInterface()->getName();
2135  s << " ";
2136  s << D->getSelector().getName();
2137  s << "]";
2138  NameOut = s.str();
2139}
2140
2141void CGObjCMac::FinishModule() {
2142  EmitModuleInfo();
2143
2144  // Emit the dummy bodies for any protocols which were referenced but
2145  // never defined.
2146  for (llvm::DenseMap<IdentifierInfo*, llvm::GlobalVariable*>::iterator
2147         i = Protocols.begin(), e = Protocols.end(); i != e; ++i) {
2148    if (i->second->hasInitializer())
2149      continue;
2150
2151    std::vector<llvm::Constant*> Values(5);
2152    Values[0] = llvm::Constant::getNullValue(ObjCTypes.ProtocolExtensionPtrTy);
2153    Values[1] = GetClassName(i->first);
2154    Values[2] = llvm::Constant::getNullValue(ObjCTypes.ProtocolListPtrTy);
2155    Values[3] = Values[4] =
2156      llvm::Constant::getNullValue(ObjCTypes.MethodDescriptionListPtrTy);
2157    i->second->setLinkage(llvm::GlobalValue::InternalLinkage);
2158    i->second->setInitializer(llvm::ConstantStruct::get(ObjCTypes.ProtocolTy,
2159                                                        Values));
2160  }
2161
2162  std::vector<llvm::Constant*> Used;
2163  for (std::vector<llvm::GlobalVariable*>::iterator i = UsedGlobals.begin(),
2164         e = UsedGlobals.end(); i != e; ++i) {
2165    Used.push_back(llvm::ConstantExpr::getBitCast(*i, ObjCTypes.Int8PtrTy));
2166  }
2167
2168  llvm::ArrayType *AT = llvm::ArrayType::get(ObjCTypes.Int8PtrTy, Used.size());
2169  llvm::GlobalValue *GV =
2170    new llvm::GlobalVariable(AT, false,
2171                             llvm::GlobalValue::AppendingLinkage,
2172                             llvm::ConstantArray::get(AT, Used),
2173                             "llvm.used",
2174                             &CGM.getModule());
2175
2176  GV->setSection("llvm.metadata");
2177
2178  // Add assembler directives to add lazy undefined symbol references
2179  // for classes which are referenced but not defined. This is
2180  // important for correct linker interaction.
2181
2182  // FIXME: Uh, this isn't particularly portable.
2183  std::stringstream s;
2184  for (std::set<IdentifierInfo*>::iterator i = LazySymbols.begin(),
2185         e = LazySymbols.end(); i != e; ++i) {
2186    s << "\t.lazy_reference .objc_class_name_" << (*i)->getName() << "\n";
2187  }
2188  for (std::set<IdentifierInfo*>::iterator i = DefinedSymbols.begin(),
2189         e = DefinedSymbols.end(); i != e; ++i) {
2190    s << "\t.objc_class_name_" << (*i)->getName() << "=0\n"
2191      << "\t.globl .objc_class_name_" << (*i)->getName() << "\n";
2192  }
2193  CGM.getModule().appendModuleInlineAsm(s.str());
2194}
2195
2196/* *** */
2197
2198ObjCTypesHelper::ObjCTypesHelper(CodeGen::CodeGenModule &cgm)
2199  : CGM(cgm)
2200{
2201  CodeGen::CodeGenTypes &Types = CGM.getTypes();
2202  ASTContext &Ctx = CGM.getContext();
2203
2204  ShortTy = Types.ConvertType(Ctx.ShortTy);
2205  IntTy = Types.ConvertType(Ctx.IntTy);
2206  LongTy = Types.ConvertType(Ctx.LongTy);
2207  Int8PtrTy = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
2208
2209  ObjectPtrTy = Types.ConvertType(Ctx.getObjCIdType());
2210  PtrObjectPtrTy = llvm::PointerType::getUnqual(ObjectPtrTy);
2211  SelectorPtrTy = Types.ConvertType(Ctx.getObjCSelType());
2212
2213  // FIXME: It would be nice to unify this with the opaque type, so
2214  // that the IR comes out a bit cleaner.
2215  const llvm::Type *T = Types.ConvertType(Ctx.getObjCProtoType());
2216  ExternalProtocolPtrTy = llvm::PointerType::getUnqual(T);
2217
2218  MethodDescriptionTy =
2219    llvm::StructType::get(SelectorPtrTy,
2220                          Int8PtrTy,
2221                          NULL);
2222  CGM.getModule().addTypeName("struct._objc_method_description",
2223                              MethodDescriptionTy);
2224
2225  MethodDescriptionListTy =
2226    llvm::StructType::get(IntTy,
2227                          llvm::ArrayType::get(MethodDescriptionTy, 0),
2228                          NULL);
2229  CGM.getModule().addTypeName("struct._objc_method_description_list",
2230                              MethodDescriptionListTy);
2231  MethodDescriptionListPtrTy =
2232    llvm::PointerType::getUnqual(MethodDescriptionListTy);
2233
2234  PropertyTy = llvm::StructType::get(Int8PtrTy,
2235                                     Int8PtrTy,
2236                                     NULL);
2237  CGM.getModule().addTypeName("struct._objc_property",
2238                              PropertyTy);
2239
2240  PropertyListTy = llvm::StructType::get(IntTy,
2241                                         IntTy,
2242                                         llvm::ArrayType::get(PropertyTy, 0),
2243                                         NULL);
2244  CGM.getModule().addTypeName("struct._objc_property_list",
2245                              PropertyListTy);
2246  PropertyListPtrTy = llvm::PointerType::getUnqual(PropertyListTy);
2247
2248  // Protocol description structures
2249
2250  ProtocolExtensionTy =
2251    llvm::StructType::get(Types.ConvertType(Ctx.IntTy),
2252                          llvm::PointerType::getUnqual(MethodDescriptionListTy),
2253                          llvm::PointerType::getUnqual(MethodDescriptionListTy),
2254                          PropertyListPtrTy,
2255                          NULL);
2256  CGM.getModule().addTypeName("struct._objc_protocol_extension",
2257                              ProtocolExtensionTy);
2258  ProtocolExtensionPtrTy = llvm::PointerType::getUnqual(ProtocolExtensionTy);
2259
2260  // Handle recursive construction of Protocol and ProtocolList types
2261
2262  llvm::PATypeHolder ProtocolTyHolder = llvm::OpaqueType::get();
2263  llvm::PATypeHolder ProtocolListTyHolder = llvm::OpaqueType::get();
2264
2265  T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolListTyHolder),
2266                            LongTy,
2267                            llvm::ArrayType::get(ProtocolTyHolder, 0),
2268                            NULL);
2269  cast<llvm::OpaqueType>(ProtocolListTyHolder.get())->refineAbstractTypeTo(T);
2270
2271  T = llvm::StructType::get(llvm::PointerType::getUnqual(ProtocolExtensionTy),
2272                            Int8PtrTy,
2273                            llvm::PointerType::getUnqual(ProtocolListTyHolder),
2274                            MethodDescriptionListPtrTy,
2275                            MethodDescriptionListPtrTy,
2276                            NULL);
2277  cast<llvm::OpaqueType>(ProtocolTyHolder.get())->refineAbstractTypeTo(T);
2278
2279  ProtocolListTy = cast<llvm::StructType>(ProtocolListTyHolder.get());
2280  CGM.getModule().addTypeName("struct._objc_protocol_list",
2281                              ProtocolListTy);
2282  ProtocolListPtrTy = llvm::PointerType::getUnqual(ProtocolListTy);
2283
2284  ProtocolTy = cast<llvm::StructType>(ProtocolTyHolder.get());
2285  CGM.getModule().addTypeName("struct.__objc_protocol", ProtocolTy);
2286  ProtocolPtrTy = llvm::PointerType::getUnqual(ProtocolTy);
2287
2288  // Class description structures
2289
2290  IvarTy = llvm::StructType::get(Int8PtrTy,
2291                                 Int8PtrTy,
2292                                 IntTy,
2293                                 NULL);
2294  CGM.getModule().addTypeName("struct._objc_ivar", IvarTy);
2295
2296  IvarListTy = llvm::OpaqueType::get();
2297  CGM.getModule().addTypeName("struct._objc_ivar_list", IvarListTy);
2298  IvarListPtrTy = llvm::PointerType::getUnqual(IvarListTy);
2299
2300  MethodTy = llvm::StructType::get(SelectorPtrTy,
2301                                   Int8PtrTy,
2302                                   Int8PtrTy,
2303                                   NULL);
2304  CGM.getModule().addTypeName("struct._objc_method", MethodTy);
2305
2306  MethodListTy = llvm::OpaqueType::get();
2307  CGM.getModule().addTypeName("struct._objc_method_list", MethodListTy);
2308  MethodListPtrTy = llvm::PointerType::getUnqual(MethodListTy);
2309
2310  CacheTy = llvm::OpaqueType::get();
2311  CGM.getModule().addTypeName("struct._objc_cache", CacheTy);
2312  CachePtrTy = llvm::PointerType::getUnqual(CacheTy);
2313
2314  ClassExtensionTy =
2315    llvm::StructType::get(IntTy,
2316                          Int8PtrTy,
2317                          PropertyListPtrTy,
2318                          NULL);
2319  CGM.getModule().addTypeName("struct._objc_class_extension", ClassExtensionTy);
2320  ClassExtensionPtrTy = llvm::PointerType::getUnqual(ClassExtensionTy);
2321
2322  llvm::PATypeHolder ClassTyHolder = llvm::OpaqueType::get();
2323
2324  T = llvm::StructType::get(llvm::PointerType::getUnqual(ClassTyHolder),
2325                            llvm::PointerType::getUnqual(ClassTyHolder),
2326                            Int8PtrTy,
2327                            LongTy,
2328                            LongTy,
2329                            LongTy,
2330                            IvarListPtrTy,
2331                            MethodListPtrTy,
2332                            CachePtrTy,
2333                            ProtocolListPtrTy,
2334                            Int8PtrTy,
2335                            ClassExtensionPtrTy,
2336                            NULL);
2337  cast<llvm::OpaqueType>(ClassTyHolder.get())->refineAbstractTypeTo(T);
2338
2339  ClassTy = cast<llvm::StructType>(ClassTyHolder.get());
2340  CGM.getModule().addTypeName("struct._objc_class", ClassTy);
2341  ClassPtrTy = llvm::PointerType::getUnqual(ClassTy);
2342
2343  CategoryTy = llvm::StructType::get(Int8PtrTy,
2344                                     Int8PtrTy,
2345                                     MethodListPtrTy,
2346                                     MethodListPtrTy,
2347                                     ProtocolListPtrTy,
2348                                     IntTy,
2349                                     PropertyListPtrTy,
2350                                     NULL);
2351  CGM.getModule().addTypeName("struct._objc_category", CategoryTy);
2352
2353  // I'm not sure I like this. The implicit coordination is a bit
2354  // gross. We should solve this in a reasonable fashion because this
2355  // is a pretty common task (match some runtime data structure with
2356  // an LLVM data structure).
2357
2358  // FIXME: This is leaked.
2359  // FIXME: Merge with rewriter code?
2360  RecordDecl *RD = RecordDecl::Create(Ctx, TagDecl::TK_struct, 0,
2361                                      SourceLocation(),
2362                                      &Ctx.Idents.get("_objc_super"));
2363  FieldDecl *FieldDecls[2];
2364  FieldDecls[0] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2365                                    Ctx.getObjCIdType());
2366  FieldDecls[1] = FieldDecl::Create(Ctx, SourceLocation(), 0,
2367                                    Ctx.getObjCClassType());
2368  RD->defineBody(Ctx, FieldDecls, 2);
2369
2370  SuperCTy = Ctx.getTagDeclType(RD);
2371  SuperPtrCTy = Ctx.getPointerType(SuperCTy);
2372
2373  SuperTy = cast<llvm::StructType>(Types.ConvertType(SuperCTy));
2374  SuperPtrTy = llvm::PointerType::getUnqual(SuperTy);
2375
2376  // Global metadata structures
2377
2378  SymtabTy = llvm::StructType::get(LongTy,
2379                                   SelectorPtrTy,
2380                                   ShortTy,
2381                                   ShortTy,
2382                                   llvm::ArrayType::get(Int8PtrTy, 0),
2383                                   NULL);
2384  CGM.getModule().addTypeName("struct._objc_symtab", SymtabTy);
2385  SymtabPtrTy = llvm::PointerType::getUnqual(SymtabTy);
2386
2387  ModuleTy =
2388    llvm::StructType::get(LongTy,
2389                          LongTy,
2390                          Int8PtrTy,
2391                          SymtabPtrTy,
2392                          NULL);
2393  CGM.getModule().addTypeName("struct._objc_module", ModuleTy);
2394
2395  // Message send functions.
2396
2397  std::vector<const llvm::Type*> Params;
2398  Params.push_back(ObjectPtrTy);
2399  Params.push_back(SelectorPtrTy);
2400  MessageSendFn =
2401    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2402                                                      Params,
2403                                                      true),
2404                              "objc_msgSend");
2405
2406  Params.clear();
2407  Params.push_back(Int8PtrTy);
2408  Params.push_back(ObjectPtrTy);
2409  Params.push_back(SelectorPtrTy);
2410  MessageSendStretFn =
2411    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2412                                                      Params,
2413                                                      true),
2414                              "objc_msgSend_stret");
2415
2416  Params.clear();
2417  Params.push_back(ObjectPtrTy);
2418  Params.push_back(SelectorPtrTy);
2419  // FIXME: This should be long double on x86_64?
2420  MessageSendFpretFn =
2421    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::DoubleTy,
2422                                                      Params,
2423                                                      true),
2424                              "objc_msgSend_fpret");
2425
2426  Params.clear();
2427  Params.push_back(SuperPtrTy);
2428  Params.push_back(SelectorPtrTy);
2429  MessageSendSuperFn =
2430    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2431                                                      Params,
2432                                                      true),
2433                              "objc_msgSendSuper");
2434
2435  Params.clear();
2436  Params.push_back(Int8PtrTy);
2437  Params.push_back(SuperPtrTy);
2438  Params.push_back(SelectorPtrTy);
2439  MessageSendSuperStretFn =
2440    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2441                                                      Params,
2442                                                      true),
2443                              "objc_msgSendSuper_stret");
2444
2445  // There is no objc_msgSendSuper_fpret? How can that work?
2446  MessageSendSuperFpretFn = MessageSendSuperFn;
2447
2448  // Property manipulation functions.
2449
2450  Params.clear();
2451  Params.push_back(ObjectPtrTy);
2452  Params.push_back(SelectorPtrTy);
2453  Params.push_back(LongTy);
2454  Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2455  GetPropertyFn =
2456    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2457                                                      Params,
2458                                                      false),
2459                              "objc_getProperty");
2460
2461  Params.clear();
2462  Params.push_back(ObjectPtrTy);
2463  Params.push_back(SelectorPtrTy);
2464  Params.push_back(LongTy);
2465  Params.push_back(ObjectPtrTy);
2466  Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2467  Params.push_back(Types.ConvertTypeForMem(Ctx.BoolTy));
2468  SetPropertyFn =
2469    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2470                                                      Params,
2471                                                      false),
2472                              "objc_setProperty");
2473
2474  // Enumeration mutation.
2475
2476  Params.clear();
2477  Params.push_back(ObjectPtrTy);
2478  EnumerationMutationFn =
2479    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2480                                                      Params,
2481                                                      false),
2482                              "objc_enumerationMutation");
2483
2484  // FIXME: This is the size of the setjmp buffer and should be
2485  // target specific. 18 is what's used on 32-bit X86.
2486  uint64_t SetJmpBufferSize = 18;
2487
2488  // Exceptions
2489  const llvm::Type *StackPtrTy =
2490    llvm::ArrayType::get(llvm::PointerType::getUnqual(llvm::Type::Int8Ty), 4);
2491
2492  ExceptionDataTy =
2493    llvm::StructType::get(llvm::ArrayType::get(llvm::Type::Int32Ty,
2494                                               SetJmpBufferSize),
2495                          StackPtrTy, NULL);
2496  CGM.getModule().addTypeName("struct._objc_exception_data",
2497                              ExceptionDataTy);
2498
2499  Params.clear();
2500  Params.push_back(ObjectPtrTy);
2501  ExceptionThrowFn =
2502    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2503                                                      Params,
2504                                                      false),
2505                              "objc_exception_throw");
2506
2507  Params.clear();
2508  Params.push_back(llvm::PointerType::getUnqual(ExceptionDataTy));
2509  ExceptionTryEnterFn =
2510    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2511                                                      Params,
2512                                                      false),
2513                              "objc_exception_try_enter");
2514  ExceptionTryExitFn =
2515    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2516                                                      Params,
2517                                                      false),
2518                              "objc_exception_try_exit");
2519  ExceptionExtractFn =
2520    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2521                                                      Params,
2522                                                      false),
2523                              "objc_exception_extract");
2524
2525  Params.clear();
2526  Params.push_back(ClassPtrTy);
2527  Params.push_back(ObjectPtrTy);
2528  ExceptionMatchFn =
2529    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2530                                                      Params,
2531                                                      false),
2532                              "objc_exception_match");
2533
2534  // synchronized APIs
2535  // void objc_sync_enter (id)
2536  Params.clear();
2537  Params.push_back(ObjectPtrTy);
2538  SyncEnterFn =
2539  CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2540                                                    Params,
2541                                                    false),
2542                            "objc_sync_enter");
2543  // void objc_sync_exit (id)
2544  SyncExitFn =
2545  CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::VoidTy,
2546                                                    Params,
2547                                                    false),
2548                            "objc_sync_exit");
2549
2550
2551  Params.clear();
2552  Params.push_back(llvm::PointerType::getUnqual(llvm::Type::Int32Ty));
2553  SetJmpFn =
2554    CGM.CreateRuntimeFunction(llvm::FunctionType::get(llvm::Type::Int32Ty,
2555                                                      Params,
2556                                                      false),
2557                              "_setjmp");
2558
2559  // gc's API
2560  // id objc_read_weak (id *)
2561  Params.clear();
2562  Params.push_back(PtrObjectPtrTy);
2563  GcReadWeakFn =
2564    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2565                                                      Params,
2566                                                      false),
2567                              "objc_read_weak");
2568  // id objc_assign_weak (id, id *)
2569  Params.clear();
2570  Params.push_back(ObjectPtrTy);
2571  Params.push_back(PtrObjectPtrTy);
2572  GcAssignWeakFn =
2573  CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2574                                                    Params,
2575                                                    false),
2576                           "objc_assign_weak");
2577  GcAssignGlobalFn =
2578    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2579                                                      Params,
2580                                                      false),
2581                           "objc_assign_global");
2582  GcAssignStrongCastFn =
2583    CGM.CreateRuntimeFunction(llvm::FunctionType::get(ObjectPtrTy,
2584                                                      Params,
2585                                                      false),
2586                           "objc_assign_strongCast");
2587
2588}
2589
2590ObjCTypesHelper::~ObjCTypesHelper() {
2591}
2592
2593/* *** */
2594
2595CodeGen::CGObjCRuntime *
2596CodeGen::CreateMacObjCRuntime(CodeGen::CodeGenModule &CGM) {
2597  return new CGObjCMac(CGM);
2598}
2599