1 //===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
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 contains code to emit Objective-C code as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGObjCRuntime.h"
15 #include "CodeGenFunction.h"
16 #include "CodeGenModule.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/StmtObjC.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/Target/TargetData.h"
23 using namespace clang;
24 using namespace CodeGen;
25 
26 /// Emits an instance of NSConstantString representing the object.
27 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
28 {
29   llvm::Constant *C =
30       CGM.getObjCRuntime().GenerateConstantString(E->getString());
31   // FIXME: This bitcast should just be made an invariant on the Runtime.
32   return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
33 }
34 
35 /// Emit a selector.
36 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
37   // Untyped selector.
38   // Note that this implementation allows for non-constant strings to be passed
39   // as arguments to @selector().  Currently, the only thing preventing this
40   // behaviour is the type checking in the front end.
41   return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
42 }
43 
44 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
45   // FIXME: This should pass the Decl not the name.
46   return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
47 }
48 
49 
50 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
51                                             ReturnValueSlot Return) {
52   // Only the lookup mechanism and first two arguments of the method
53   // implementation vary between runtimes.  We can get the receiver and
54   // arguments in generic code.
55 
56   CGObjCRuntime &Runtime = CGM.getObjCRuntime();
57   bool isSuperMessage = false;
58   bool isClassMessage = false;
59   ObjCInterfaceDecl *OID = 0;
60   // Find the receiver
61   llvm::Value *Receiver = 0;
62   switch (E->getReceiverKind()) {
63   case ObjCMessageExpr::Instance:
64     Receiver = EmitScalarExpr(E->getInstanceReceiver());
65     break;
66 
67   case ObjCMessageExpr::Class: {
68     const ObjCObjectType *ObjTy
69       = E->getClassReceiver()->getAs<ObjCObjectType>();
70     assert(ObjTy && "Invalid Objective-C class message send");
71     OID = ObjTy->getInterface();
72     assert(OID && "Invalid Objective-C class message send");
73     Receiver = Runtime.GetClass(Builder, OID);
74     isClassMessage = true;
75     break;
76   }
77 
78   case ObjCMessageExpr::SuperInstance:
79     Receiver = LoadObjCSelf();
80     isSuperMessage = true;
81     break;
82 
83   case ObjCMessageExpr::SuperClass:
84     Receiver = LoadObjCSelf();
85     isSuperMessage = true;
86     isClassMessage = true;
87     break;
88   }
89 
90   CallArgList Args;
91   EmitCallArgs(Args, E->getMethodDecl(), E->arg_begin(), E->arg_end());
92 
93   QualType ResultType =
94     E->getMethodDecl() ? E->getMethodDecl()->getResultType() : E->getType();
95 
96   if (isSuperMessage) {
97     // super is only valid in an Objective-C method
98     const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
99     bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
100     return Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
101                                             E->getSelector(),
102                                             OMD->getClassInterface(),
103                                             isCategoryImpl,
104                                             Receiver,
105                                             isClassMessage,
106                                             Args,
107                                             E->getMethodDecl());
108   }
109 
110   return Runtime.GenerateMessageSend(*this, Return, ResultType,
111                                      E->getSelector(),
112                                      Receiver, Args, OID,
113                                      E->getMethodDecl());
114 }
115 
116 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
117 /// the LLVM function and sets the other context used by
118 /// CodeGenFunction.
119 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
120                                       const ObjCContainerDecl *CD) {
121   FunctionArgList Args;
122   // Check if we should generate debug info for this method.
123   if (CGM.getDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
124     DebugInfo = CGM.getDebugInfo();
125 
126   llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
127 
128   const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(OMD);
129   CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
130 
131   Args.push_back(std::make_pair(OMD->getSelfDecl(),
132                                 OMD->getSelfDecl()->getType()));
133   Args.push_back(std::make_pair(OMD->getCmdDecl(),
134                                 OMD->getCmdDecl()->getType()));
135 
136   for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
137        E = OMD->param_end(); PI != E; ++PI)
138     Args.push_back(std::make_pair(*PI, (*PI)->getType()));
139 
140   StartFunction(OMD, OMD->getResultType(), Fn, Args, OMD->getLocStart());
141 }
142 
143 /// Generate an Objective-C method.  An Objective-C method is a C function with
144 /// its pointer, name, and types registered in the class struture.
145 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
146   StartObjCMethod(OMD, OMD->getClassInterface());
147   EmitStmt(OMD->getBody());
148   FinishFunction(OMD->getBodyRBrace());
149 }
150 
151 // FIXME: I wasn't sure about the synthesis approach. If we end up generating an
152 // AST for the whole body we can just fall back to having a GenerateFunction
153 // which takes the body Stmt.
154 
155 /// GenerateObjCGetter - Generate an Objective-C property getter
156 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
157 /// is illegal within a category.
158 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
159                                          const ObjCPropertyImplDecl *PID) {
160   ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
161   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
162   bool IsAtomic =
163     !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
164   ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
165   assert(OMD && "Invalid call to generate getter (empty method)");
166   StartObjCMethod(OMD, IMP->getClassInterface());
167 
168   // Determine if we should use an objc_getProperty call for
169   // this. Non-atomic properties are directly evaluated.
170   // atomic 'copy' and 'retain' properties are also directly
171   // evaluated in gc-only mode.
172   if (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
173       IsAtomic &&
174       (PD->getSetterKind() == ObjCPropertyDecl::Copy ||
175        PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
176     llvm::Value *GetPropertyFn =
177       CGM.getObjCRuntime().GetPropertyGetFunction();
178 
179     if (!GetPropertyFn) {
180       CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
181       FinishFunction();
182       return;
183     }
184 
185     // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
186     // FIXME: Can't this be simpler? This might even be worse than the
187     // corresponding gcc code.
188     CodeGenTypes &Types = CGM.getTypes();
189     ValueDecl *Cmd = OMD->getCmdDecl();
190     llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
191     QualType IdTy = getContext().getObjCIdType();
192     llvm::Value *SelfAsId =
193       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
194     llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
195     llvm::Value *True =
196       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
197     CallArgList Args;
198     Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
199     Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
200     Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
201     Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
202     // FIXME: We shouldn't need to get the function info here, the
203     // runtime already should have computed it to build the function.
204     RValue RV = EmitCall(Types.getFunctionInfo(PD->getType(), Args,
205                                                FunctionType::ExtInfo()),
206                          GetPropertyFn, ReturnValueSlot(), Args);
207     // We need to fix the type here. Ivars with copy & retain are
208     // always objects so we don't need to worry about complex or
209     // aggregates.
210     RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
211                                            Types.ConvertType(PD->getType())));
212     EmitReturnOfRValue(RV, PD->getType());
213   } else {
214     if (Ivar->getType()->isAnyComplexType()) {
215       LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
216                                     Ivar, 0);
217       ComplexPairTy Pair = LoadComplexFromAddr(LV.getAddress(),
218                                                LV.isVolatileQualified());
219       StoreComplexToAddr(Pair, ReturnValue, LV.isVolatileQualified());
220     }
221     else if (hasAggregateLLVMType(Ivar->getType())) {
222       bool IsStrong = false;
223       if ((IsAtomic || (IsStrong = IvarTypeWithAggrGCObjects(Ivar->getType())))
224           && CurFnInfo->getReturnInfo().getKind() == ABIArgInfo::Indirect
225           && CGM.getObjCRuntime().GetGetStructFunction()) {
226         LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
227                                       Ivar, 0);
228         llvm::Value *GetCopyStructFn =
229           CGM.getObjCRuntime().GetGetStructFunction();
230         CodeGenTypes &Types = CGM.getTypes();
231         // objc_copyStruct (ReturnValue, &structIvar,
232         //                  sizeof (Type of Ivar), isAtomic, false);
233         CallArgList Args;
234         RValue RV = RValue::get(Builder.CreateBitCast(ReturnValue,
235                                     Types.ConvertType(getContext().VoidPtrTy)));
236         Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
237         RV = RValue::get(Builder.CreateBitCast(LV.getAddress(),
238                                     Types.ConvertType(getContext().VoidPtrTy)));
239         Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
240         // sizeof (Type of Ivar)
241         uint64_t Size =  getContext().getTypeSize(Ivar->getType()) / 8;
242         llvm::Value *SizeVal =
243           llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy), Size);
244         Args.push_back(std::make_pair(RValue::get(SizeVal),
245                                       getContext().LongTy));
246         llvm::Value *isAtomic =
247           llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
248                                  IsAtomic ? 1 : 0);
249         Args.push_back(std::make_pair(RValue::get(isAtomic),
250                                       getContext().BoolTy));
251         llvm::Value *hasStrong =
252           llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy),
253                                  IsStrong ? 1 : 0);
254         Args.push_back(std::make_pair(RValue::get(hasStrong),
255                                       getContext().BoolTy));
256         EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
257                                        FunctionType::ExtInfo()),
258                  GetCopyStructFn, ReturnValueSlot(), Args);
259       }
260       else {
261         if (PID->getGetterCXXConstructor()) {
262           ReturnStmt *Stmt =
263             new (getContext()) ReturnStmt(SourceLocation(),
264                                           PID->getGetterCXXConstructor(),
265                                           0);
266           EmitReturnStmt(*Stmt);
267         }
268         else {
269           LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
270                                         Ivar, 0);
271           EmitAggregateCopy(ReturnValue, LV.getAddress(), Ivar->getType());
272         }
273       }
274     } else {
275       LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(),
276                                     Ivar, 0);
277       CodeGenTypes &Types = CGM.getTypes();
278       RValue RV = EmitLoadOfLValue(LV, Ivar->getType());
279       RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
280                        Types.ConvertType(PD->getType())));
281       EmitReturnOfRValue(RV, PD->getType());
282     }
283   }
284 
285   FinishFunction();
286 }
287 
288 /// GenerateObjCSetter - Generate an Objective-C property setter
289 /// function. The given Decl must be an ObjCImplementationDecl. @synthesize
290 /// is illegal within a category.
291 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
292                                          const ObjCPropertyImplDecl *PID) {
293   ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
294   const ObjCPropertyDecl *PD = PID->getPropertyDecl();
295   ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
296   assert(OMD && "Invalid call to generate setter (empty method)");
297   StartObjCMethod(OMD, IMP->getClassInterface());
298 
299   bool IsCopy = PD->getSetterKind() == ObjCPropertyDecl::Copy;
300   bool IsAtomic =
301     !(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic);
302 
303   // Determine if we should use an objc_setProperty call for
304   // this. Properties with 'copy' semantics always use it, as do
305   // non-atomic properties with 'release' semantics as long as we are
306   // not in gc-only mode.
307   if (IsCopy ||
308       (CGM.getLangOptions().getGCMode() != LangOptions::GCOnly &&
309        PD->getSetterKind() == ObjCPropertyDecl::Retain)) {
310     llvm::Value *SetPropertyFn =
311       CGM.getObjCRuntime().GetPropertySetFunction();
312 
313     if (!SetPropertyFn) {
314       CGM.ErrorUnsupported(PID, "Obj-C getter requiring atomic copy");
315       FinishFunction();
316       return;
317     }
318 
319     // Emit objc_setProperty((id) self, _cmd, offset, arg,
320     //                       <is-atomic>, <is-copy>).
321     // FIXME: Can't this be simpler? This might even be worse than the
322     // corresponding gcc code.
323     CodeGenTypes &Types = CGM.getTypes();
324     ValueDecl *Cmd = OMD->getCmdDecl();
325     llvm::Value *CmdVal = Builder.CreateLoad(LocalDeclMap[Cmd], "cmd");
326     QualType IdTy = getContext().getObjCIdType();
327     llvm::Value *SelfAsId =
328       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
329     llvm::Value *Offset = EmitIvarOffset(IMP->getClassInterface(), Ivar);
330     llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
331     llvm::Value *ArgAsId =
332       Builder.CreateBitCast(Builder.CreateLoad(Arg, "arg"),
333                             Types.ConvertType(IdTy));
334     llvm::Value *True =
335       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
336     llvm::Value *False =
337       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
338     CallArgList Args;
339     Args.push_back(std::make_pair(RValue::get(SelfAsId), IdTy));
340     Args.push_back(std::make_pair(RValue::get(CmdVal), Cmd->getType()));
341     Args.push_back(std::make_pair(RValue::get(Offset), getContext().LongTy));
342     Args.push_back(std::make_pair(RValue::get(ArgAsId), IdTy));
343     Args.push_back(std::make_pair(RValue::get(IsAtomic ? True : False),
344                                   getContext().BoolTy));
345     Args.push_back(std::make_pair(RValue::get(IsCopy ? True : False),
346                                   getContext().BoolTy));
347     // FIXME: We shouldn't need to get the function info here, the runtime
348     // already should have computed it to build the function.
349     EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
350                                    FunctionType::ExtInfo()),
351              SetPropertyFn,
352              ReturnValueSlot(), Args);
353   } else if (IsAtomic && hasAggregateLLVMType(Ivar->getType()) &&
354              !Ivar->getType()->isAnyComplexType() &&
355              IndirectObjCSetterArg(*CurFnInfo)
356              && CGM.getObjCRuntime().GetSetStructFunction()) {
357     // objc_copyStruct (&structIvar, &Arg,
358     //                  sizeof (struct something), true, false);
359     llvm::Value *GetCopyStructFn =
360       CGM.getObjCRuntime().GetSetStructFunction();
361     CodeGenTypes &Types = CGM.getTypes();
362     CallArgList Args;
363     LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), Ivar, 0);
364     RValue RV = RValue::get(Builder.CreateBitCast(LV.getAddress(),
365                                     Types.ConvertType(getContext().VoidPtrTy)));
366     Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
367     llvm::Value *Arg = LocalDeclMap[*OMD->param_begin()];
368     llvm::Value *ArgAsPtrTy =
369       Builder.CreateBitCast(Arg,
370                             Types.ConvertType(getContext().VoidPtrTy));
371     RV = RValue::get(ArgAsPtrTy);
372     Args.push_back(std::make_pair(RV, getContext().VoidPtrTy));
373     // sizeof (Type of Ivar)
374     uint64_t Size =  getContext().getTypeSize(Ivar->getType()) / 8;
375     llvm::Value *SizeVal =
376       llvm::ConstantInt::get(Types.ConvertType(getContext().LongTy), Size);
377     Args.push_back(std::make_pair(RValue::get(SizeVal),
378                                   getContext().LongTy));
379     llvm::Value *True =
380       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 1);
381     Args.push_back(std::make_pair(RValue::get(True), getContext().BoolTy));
382     llvm::Value *False =
383       llvm::ConstantInt::get(Types.ConvertType(getContext().BoolTy), 0);
384     Args.push_back(std::make_pair(RValue::get(False), getContext().BoolTy));
385     EmitCall(Types.getFunctionInfo(getContext().VoidTy, Args,
386                                    FunctionType::ExtInfo()),
387              GetCopyStructFn, ReturnValueSlot(), Args);
388   } else if (PID->getSetterCXXAssignment()) {
389     EmitIgnoredExpr(PID->getSetterCXXAssignment());
390   } else {
391     // FIXME: Find a clean way to avoid AST node creation.
392     SourceLocation Loc = PD->getLocation();
393     ValueDecl *Self = OMD->getSelfDecl();
394     ObjCIvarDecl *Ivar = PID->getPropertyIvarDecl();
395     DeclRefExpr Base(Self, Self->getType(), VK_RValue, Loc);
396     ParmVarDecl *ArgDecl = *OMD->param_begin();
397     DeclRefExpr Arg(ArgDecl, ArgDecl->getType(), VK_LValue, Loc);
398     ObjCIvarRefExpr IvarRef(Ivar, Ivar->getType(), Loc, &Base, true, true);
399 
400     // The property type can differ from the ivar type in some situations with
401     // Objective-C pointer types, we can always bit cast the RHS in these cases.
402     if (getContext().getCanonicalType(Ivar->getType()) !=
403         getContext().getCanonicalType(ArgDecl->getType())) {
404       ImplicitCastExpr ArgCasted(ImplicitCastExpr::OnStack,
405                                  Ivar->getType(), CK_BitCast, &Arg,
406                                  VK_RValue);
407       BinaryOperator Assign(&IvarRef, &ArgCasted, BO_Assign,
408                             Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
409       EmitStmt(&Assign);
410     } else {
411       BinaryOperator Assign(&IvarRef, &Arg, BO_Assign,
412                             Ivar->getType(), VK_RValue, OK_Ordinary, Loc);
413       EmitStmt(&Assign);
414     }
415   }
416 
417   FinishFunction();
418 }
419 
420 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
421                                                  ObjCMethodDecl *MD,
422                                                  bool ctor) {
423   llvm::SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
424   MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
425   StartObjCMethod(MD, IMP->getClassInterface());
426   for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
427        E = IMP->init_end(); B != E; ++B) {
428     CXXCtorInitializer *Member = (*B);
429     IvarInitializers.push_back(Member);
430   }
431   if (ctor) {
432     for (unsigned I = 0, E = IvarInitializers.size(); I != E; ++I) {
433       CXXCtorInitializer *IvarInit = IvarInitializers[I];
434       FieldDecl *Field = IvarInit->getAnyMember();
435       QualType FieldType = Field->getType();
436       ObjCIvarDecl  *Ivar = cast<ObjCIvarDecl>(Field);
437       LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
438                                     LoadObjCSelf(), Ivar, 0);
439       EmitAggExpr(IvarInit->getInit(), AggValueSlot::forLValue(LV, true));
440     }
441     // constructor returns 'self'.
442     CodeGenTypes &Types = CGM.getTypes();
443     QualType IdTy(CGM.getContext().getObjCIdType());
444     llvm::Value *SelfAsId =
445       Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
446     EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
447   } else {
448     // dtor
449     for (size_t i = IvarInitializers.size(); i > 0; --i) {
450       FieldDecl *Field = IvarInitializers[i - 1]->getAnyMember();
451       QualType FieldType = Field->getType();
452       const ConstantArrayType *Array =
453         getContext().getAsConstantArrayType(FieldType);
454       if (Array)
455         FieldType = getContext().getBaseElementType(FieldType);
456 
457       ObjCIvarDecl  *Ivar = cast<ObjCIvarDecl>(Field);
458       LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
459                                     LoadObjCSelf(), Ivar, 0);
460       const RecordType *RT = FieldType->getAs<RecordType>();
461       CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
462       CXXDestructorDecl *Dtor = FieldClassDecl->getDestructor();
463       if (!Dtor->isTrivial()) {
464         if (Array) {
465           const llvm::Type *BasePtr = ConvertType(FieldType);
466           BasePtr = llvm::PointerType::getUnqual(BasePtr);
467           llvm::Value *BaseAddrPtr =
468             Builder.CreateBitCast(LV.getAddress(), BasePtr);
469           EmitCXXAggrDestructorCall(Dtor,
470                                     Array, BaseAddrPtr);
471         } else {
472           EmitCXXDestructorCall(Dtor,
473                                 Dtor_Complete, /*ForVirtualBase=*/false,
474                                 LV.getAddress());
475         }
476       }
477     }
478   }
479   FinishFunction();
480 }
481 
482 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
483   CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
484   it++; it++;
485   const ABIArgInfo &AI = it->info;
486   // FIXME. Is this sufficient check?
487   return (AI.getKind() == ABIArgInfo::Indirect);
488 }
489 
490 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
491   if (CGM.getLangOptions().getGCMode() == LangOptions::NonGC)
492     return false;
493   if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
494     return FDTTy->getDecl()->hasObjectMember();
495   return false;
496 }
497 
498 llvm::Value *CodeGenFunction::LoadObjCSelf() {
499   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
500   return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
501 }
502 
503 QualType CodeGenFunction::TypeOfSelfObject() {
504   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
505   ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
506   const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
507     getContext().getCanonicalType(selfDecl->getType()));
508   return PTy->getPointeeType();
509 }
510 
511 LValue
512 CodeGenFunction::EmitObjCPropertyRefLValue(const ObjCPropertyRefExpr *E) {
513   // This is a special l-value that just issues sends when we load or
514   // store through it.
515 
516   // For certain base kinds, we need to emit the base immediately.
517   llvm::Value *Base;
518   if (E->isSuperReceiver())
519     Base = LoadObjCSelf();
520   else if (E->isClassReceiver())
521     Base = CGM.getObjCRuntime().GetClass(Builder, E->getClassReceiver());
522   else
523     Base = EmitScalarExpr(E->getBase());
524   return LValue::MakePropertyRef(E, Base);
525 }
526 
527 static RValue GenerateMessageSendSuper(CodeGenFunction &CGF,
528                                        ReturnValueSlot Return,
529                                        QualType ResultType,
530                                        Selector S,
531                                        llvm::Value *Receiver,
532                                        const CallArgList &CallArgs) {
533   const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CGF.CurFuncDecl);
534   bool isClassMessage = OMD->isClassMethod();
535   bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
536   return CGF.CGM.getObjCRuntime()
537                 .GenerateMessageSendSuper(CGF, Return, ResultType,
538                                           S, OMD->getClassInterface(),
539                                           isCategoryImpl, Receiver,
540                                           isClassMessage, CallArgs);
541 }
542 
543 RValue CodeGenFunction::EmitLoadOfPropertyRefLValue(LValue LV,
544                                                     ReturnValueSlot Return) {
545   const ObjCPropertyRefExpr *E = LV.getPropertyRefExpr();
546   QualType ResultType;
547   Selector S;
548   if (E->isExplicitProperty()) {
549     const ObjCPropertyDecl *Property = E->getExplicitProperty();
550     S = Property->getGetterName();
551     ResultType = E->getType();
552   } else {
553     const ObjCMethodDecl *Getter = E->getImplicitPropertyGetter();
554     S = Getter->getSelector();
555     ResultType = Getter->getResultType(); // with reference!
556   }
557 
558   llvm::Value *Receiver = LV.getPropertyRefBaseAddr();
559 
560   // Accesses to 'super' follow a different code path.
561   if (E->isSuperReceiver())
562     return GenerateMessageSendSuper(*this, Return, ResultType,
563                                     S, Receiver, CallArgList());
564 
565   const ObjCInterfaceDecl *ReceiverClass
566     = (E->isClassReceiver() ? E->getClassReceiver() : 0);
567   return CGM.getObjCRuntime().
568              GenerateMessageSend(*this, Return, ResultType, S,
569                                  Receiver, CallArgList(), ReceiverClass);
570 }
571 
572 void CodeGenFunction::EmitStoreThroughPropertyRefLValue(RValue Src,
573                                                         LValue Dst) {
574   const ObjCPropertyRefExpr *E = Dst.getPropertyRefExpr();
575   Selector S = E->getSetterSelector();
576   QualType ArgType;
577   if (E->isImplicitProperty()) {
578     const ObjCMethodDecl *Setter = E->getImplicitPropertySetter();
579     ObjCMethodDecl::param_iterator P = Setter->param_begin();
580     ArgType = (*P)->getType();
581   } else {
582     ArgType = E->getType();
583   }
584 
585   CallArgList Args;
586   Args.push_back(std::make_pair(Src, ArgType));
587 
588   llvm::Value *Receiver = Dst.getPropertyRefBaseAddr();
589   QualType ResultType = getContext().VoidTy;
590 
591   if (E->isSuperReceiver()) {
592     GenerateMessageSendSuper(*this, ReturnValueSlot(),
593                              ResultType, S, Receiver, Args);
594     return;
595   }
596 
597   const ObjCInterfaceDecl *ReceiverClass
598     = (E->isClassReceiver() ? E->getClassReceiver() : 0);
599 
600   CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
601                                            ResultType, S, Receiver, Args,
602                                            ReceiverClass);
603 }
604 
605 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
606   llvm::Constant *EnumerationMutationFn =
607     CGM.getObjCRuntime().EnumerationMutationFunction();
608 
609   if (!EnumerationMutationFn) {
610     CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
611     return;
612   }
613 
614   JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
615   JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
616 
617   // Fast enumeration state.
618   QualType StateTy = getContext().getObjCFastEnumerationStateType();
619   llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
620   EmitNullInitialization(StatePtr, StateTy);
621 
622   // Number of elements in the items array.
623   static const unsigned NumItems = 16;
624 
625   // Fetch the countByEnumeratingWithState:objects:count: selector.
626   IdentifierInfo *II[] = {
627     &CGM.getContext().Idents.get("countByEnumeratingWithState"),
628     &CGM.getContext().Idents.get("objects"),
629     &CGM.getContext().Idents.get("count")
630   };
631   Selector FastEnumSel =
632     CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
633 
634   QualType ItemsTy =
635     getContext().getConstantArrayType(getContext().getObjCIdType(),
636                                       llvm::APInt(32, NumItems),
637                                       ArrayType::Normal, 0);
638   llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
639 
640   // Emit the collection pointer.
641   llvm::Value *Collection = EmitScalarExpr(S.getCollection());
642 
643   // Send it our message:
644   CallArgList Args;
645 
646   // The first argument is a temporary of the enumeration-state type.
647   Args.push_back(std::make_pair(RValue::get(StatePtr),
648                                 getContext().getPointerType(StateTy)));
649 
650   // The second argument is a temporary array with space for NumItems
651   // pointers.  We'll actually be loading elements from the array
652   // pointer written into the control state; this buffer is so that
653   // collections that *aren't* backed by arrays can still queue up
654   // batches of elements.
655   Args.push_back(std::make_pair(RValue::get(ItemsPtr),
656                                 getContext().getPointerType(ItemsTy)));
657 
658   // The third argument is the capacity of that temporary array.
659   const llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
660   llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
661   Args.push_back(std::make_pair(RValue::get(Count),
662                                 getContext().UnsignedLongTy));
663 
664   // Start the enumeration.
665   RValue CountRV =
666     CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
667                                              getContext().UnsignedLongTy,
668                                              FastEnumSel,
669                                              Collection, Args);
670 
671   // The initial number of objects that were returned in the buffer.
672   llvm::Value *initialBufferLimit = CountRV.getScalarVal();
673 
674   llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
675   llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
676 
677   llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
678 
679   // If the limit pointer was zero to begin with, the collection is
680   // empty; skip all this.
681   Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
682                        EmptyBB, LoopInitBB);
683 
684   // Otherwise, initialize the loop.
685   EmitBlock(LoopInitBB);
686 
687   // Save the initial mutations value.  This is the value at an
688   // address that was written into the state object by
689   // countByEnumeratingWithState:objects:count:.
690   llvm::Value *StateMutationsPtrPtr =
691     Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
692   llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
693                                                       "mutationsptr");
694 
695   llvm::Value *initialMutations =
696     Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
697 
698   // Start looping.  This is the point we return to whenever we have a
699   // fresh, non-empty batch of objects.
700   llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
701   EmitBlock(LoopBodyBB);
702 
703   // The current index into the buffer.
704   llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, "forcoll.index");
705   index->addIncoming(zero, LoopInitBB);
706 
707   // The current buffer size.
708   llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, "forcoll.count");
709   count->addIncoming(initialBufferLimit, LoopInitBB);
710 
711   // Check whether the mutations value has changed from where it was
712   // at start.  StateMutationsPtr should actually be invariant between
713   // refreshes.
714   StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
715   llvm::Value *currentMutations
716     = Builder.CreateLoad(StateMutationsPtr, "statemutations");
717 
718   llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
719   llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcool.notmutated");
720 
721   Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
722                        WasNotMutatedBB, WasMutatedBB);
723 
724   // If so, call the enumeration-mutation function.
725   EmitBlock(WasMutatedBB);
726   llvm::Value *V =
727     Builder.CreateBitCast(Collection,
728                           ConvertType(getContext().getObjCIdType()),
729                           "tmp");
730   CallArgList Args2;
731   Args2.push_back(std::make_pair(RValue::get(V),
732                                 getContext().getObjCIdType()));
733   // FIXME: We shouldn't need to get the function info here, the runtime already
734   // should have computed it to build the function.
735   EmitCall(CGM.getTypes().getFunctionInfo(getContext().VoidTy, Args2,
736                                           FunctionType::ExtInfo()),
737            EnumerationMutationFn, ReturnValueSlot(), Args2);
738 
739   // Otherwise, or if the mutation function returns, just continue.
740   EmitBlock(WasNotMutatedBB);
741 
742   // Initialize the element variable.
743   RunCleanupsScope elementVariableScope(*this);
744   bool elementIsDecl;
745   LValue elementLValue;
746   QualType elementType;
747   if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
748     EmitStmt(SD);
749     const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
750 
751     DeclRefExpr tempDRE(const_cast<VarDecl*>(D), D->getType(),
752                         VK_LValue, SourceLocation());
753     elementLValue = EmitLValue(&tempDRE);
754     elementType = D->getType();
755     elementIsDecl = true;
756   } else {
757     elementLValue = LValue(); // suppress warning
758     elementType = cast<Expr>(S.getElement())->getType();
759     elementIsDecl = false;
760   }
761   const llvm::Type *convertedElementType = ConvertType(elementType);
762 
763   // Fetch the buffer out of the enumeration state.
764   // TODO: this pointer should actually be invariant between
765   // refreshes, which would help us do certain loop optimizations.
766   llvm::Value *StateItemsPtr =
767     Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
768   llvm::Value *EnumStateItems =
769     Builder.CreateLoad(StateItemsPtr, "stateitems");
770 
771   // Fetch the value at the current index from the buffer.
772   llvm::Value *CurrentItemPtr =
773     Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
774   llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
775 
776   // Cast that value to the right type.
777   CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
778                                       "currentitem");
779 
780   // Make sure we have an l-value.  Yes, this gets evaluated every
781   // time through the loop.
782   if (!elementIsDecl)
783     elementLValue = EmitLValue(cast<Expr>(S.getElement()));
784 
785   EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue, elementType);
786 
787   // Perform the loop body, setting up break and continue labels.
788   BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
789   {
790     RunCleanupsScope Scope(*this);
791     EmitStmt(S.getBody());
792   }
793   BreakContinueStack.pop_back();
794 
795   // Destroy the element variable now.
796   elementVariableScope.ForceCleanup();
797 
798   // Check whether there are more elements.
799   EmitBlock(AfterBody.getBlock());
800 
801   llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
802 
803   // First we check in the local buffer.
804   llvm::Value *indexPlusOne
805     = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
806 
807   // If we haven't overrun the buffer yet, we can continue.
808   Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
809                        LoopBodyBB, FetchMoreBB);
810 
811   index->addIncoming(indexPlusOne, AfterBody.getBlock());
812   count->addIncoming(count, AfterBody.getBlock());
813 
814   // Otherwise, we have to fetch more elements.
815   EmitBlock(FetchMoreBB);
816 
817   CountRV =
818     CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
819                                              getContext().UnsignedLongTy,
820                                              FastEnumSel,
821                                              Collection, Args);
822 
823   // If we got a zero count, we're done.
824   llvm::Value *refetchCount = CountRV.getScalarVal();
825 
826   // (note that the message send might split FetchMoreBB)
827   index->addIncoming(zero, Builder.GetInsertBlock());
828   count->addIncoming(refetchCount, Builder.GetInsertBlock());
829 
830   Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
831                        EmptyBB, LoopBodyBB);
832 
833   // No more elements.
834   EmitBlock(EmptyBB);
835 
836   if (!elementIsDecl) {
837     // If the element was not a declaration, set it to be null.
838 
839     llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
840     elementLValue = EmitLValue(cast<Expr>(S.getElement()));
841     EmitStoreThroughLValue(RValue::get(null), elementLValue, elementType);
842   }
843 
844   EmitBlock(LoopEnd.getBlock());
845 }
846 
847 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
848   CGM.getObjCRuntime().EmitTryStmt(*this, S);
849 }
850 
851 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
852   CGM.getObjCRuntime().EmitThrowStmt(*this, S);
853 }
854 
855 void CodeGenFunction::EmitObjCAtSynchronizedStmt(
856                                               const ObjCAtSynchronizedStmt &S) {
857   CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
858 }
859 
860 CGObjCRuntime::~CGObjCRuntime() {}
861 
862 
863