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