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 "CGDebugInfo.h"
15 #include "CGObjCRuntime.h"
16 #include "CodeGenFunction.h"
17 #include "CodeGenModule.h"
18 #include "TargetInfo.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/StmtObjC.h"
22 #include "clang/Basic/Diagnostic.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/IR/DataLayout.h"
25 #include "llvm/IR/InlineAsm.h"
26 using namespace clang;
27 using namespace CodeGen;
28
29 typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30 static TryEmitResult
31 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
32 static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
33 QualType ET,
34 const ObjCMethodDecl *Method,
35 RValue Result);
36
37 /// Given the address of a variable of pointer type, find the correct
38 /// null to store into it.
getNullForVariable(llvm::Value * addr)39 static llvm::Constant *getNullForVariable(llvm::Value *addr) {
40 llvm::Type *type =
41 cast<llvm::PointerType>(addr->getType())->getElementType();
42 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43 }
44
45 /// Emits an instance of NSConstantString representing the object.
EmitObjCStringLiteral(const ObjCStringLiteral * E)46 llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
47 {
48 llvm::Constant *C =
49 CGM.getObjCRuntime().GenerateConstantString(E->getString());
50 // FIXME: This bitcast should just be made an invariant on the Runtime.
51 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
52 }
53
54 /// EmitObjCBoxedExpr - This routine generates code to call
55 /// the appropriate expression boxing method. This will either be
56 /// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
57 ///
58 llvm::Value *
EmitObjCBoxedExpr(const ObjCBoxedExpr * E)59 CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
60 // Generate the correct selector for this literal's concrete type.
61 const Expr *SubExpr = E->getSubExpr();
62 // Get the method.
63 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
64 assert(BoxingMethod && "BoxingMethod is null");
65 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
66 Selector Sel = BoxingMethod->getSelector();
67
68 // Generate a reference to the class pointer, which will be the receiver.
69 // Assumes that the method was introduced in the class that should be
70 // messaged (avoids pulling it out of the result type).
71 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
72 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
73 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
74
75 const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
76 QualType ArgQT = argDecl->getType().getUnqualifiedType();
77 RValue RV = EmitAnyExpr(SubExpr);
78 CallArgList Args;
79 Args.add(RV, ArgQT);
80
81 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
82 BoxingMethod->getResultType(), Sel, Receiver, Args,
83 ClassDecl, BoxingMethod);
84 return Builder.CreateBitCast(result.getScalarVal(),
85 ConvertType(E->getType()));
86 }
87
EmitObjCCollectionLiteral(const Expr * E,const ObjCMethodDecl * MethodWithObjects)88 llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
89 const ObjCMethodDecl *MethodWithObjects) {
90 ASTContext &Context = CGM.getContext();
91 const ObjCDictionaryLiteral *DLE = 0;
92 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
93 if (!ALE)
94 DLE = cast<ObjCDictionaryLiteral>(E);
95
96 // Compute the type of the array we're initializing.
97 uint64_t NumElements =
98 ALE ? ALE->getNumElements() : DLE->getNumElements();
99 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
100 NumElements);
101 QualType ElementType = Context.getObjCIdType().withConst();
102 QualType ElementArrayType
103 = Context.getConstantArrayType(ElementType, APNumElements,
104 ArrayType::Normal, /*IndexTypeQuals=*/0);
105
106 // Allocate the temporary array(s).
107 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
108 llvm::Value *Keys = 0;
109 if (DLE)
110 Keys = CreateMemTemp(ElementArrayType, "keys");
111
112 // Perform the actual initialialization of the array(s).
113 for (uint64_t i = 0; i < NumElements; i++) {
114 if (ALE) {
115 // Emit the initializer.
116 const Expr *Rhs = ALE->getElement(i);
117 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
118 ElementType,
119 Context.getTypeAlignInChars(Rhs->getType()),
120 Context);
121 EmitScalarInit(Rhs, /*D=*/0, LV, /*capturedByInit=*/false);
122 } else {
123 // Emit the key initializer.
124 const Expr *Key = DLE->getKeyValueElement(i).Key;
125 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
126 ElementType,
127 Context.getTypeAlignInChars(Key->getType()),
128 Context);
129 EmitScalarInit(Key, /*D=*/0, KeyLV, /*capturedByInit=*/false);
130
131 // Emit the value initializer.
132 const Expr *Value = DLE->getKeyValueElement(i).Value;
133 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
134 ElementType,
135 Context.getTypeAlignInChars(Value->getType()),
136 Context);
137 EmitScalarInit(Value, /*D=*/0, ValueLV, /*capturedByInit=*/false);
138 }
139 }
140
141 // Generate the argument list.
142 CallArgList Args;
143 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
144 const ParmVarDecl *argDecl = *PI++;
145 QualType ArgQT = argDecl->getType().getUnqualifiedType();
146 Args.add(RValue::get(Objects), ArgQT);
147 if (DLE) {
148 argDecl = *PI++;
149 ArgQT = argDecl->getType().getUnqualifiedType();
150 Args.add(RValue::get(Keys), ArgQT);
151 }
152 argDecl = *PI;
153 ArgQT = argDecl->getType().getUnqualifiedType();
154 llvm::Value *Count =
155 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
156 Args.add(RValue::get(Count), ArgQT);
157
158 // Generate a reference to the class pointer, which will be the receiver.
159 Selector Sel = MethodWithObjects->getSelector();
160 QualType ResultType = E->getType();
161 const ObjCObjectPointerType *InterfacePointerType
162 = ResultType->getAsObjCInterfacePointerType();
163 ObjCInterfaceDecl *Class
164 = InterfacePointerType->getObjectType()->getInterface();
165 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
166 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
167
168 // Generate the message send.
169 RValue result
170 = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
171 MethodWithObjects->getResultType(),
172 Sel,
173 Receiver, Args, Class,
174 MethodWithObjects);
175 return Builder.CreateBitCast(result.getScalarVal(),
176 ConvertType(E->getType()));
177 }
178
EmitObjCArrayLiteral(const ObjCArrayLiteral * E)179 llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
180 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
181 }
182
EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral * E)183 llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
184 const ObjCDictionaryLiteral *E) {
185 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
186 }
187
188 /// Emit a selector.
EmitObjCSelectorExpr(const ObjCSelectorExpr * E)189 llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
190 // Untyped selector.
191 // Note that this implementation allows for non-constant strings to be passed
192 // as arguments to @selector(). Currently, the only thing preventing this
193 // behaviour is the type checking in the front end.
194 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
195 }
196
EmitObjCProtocolExpr(const ObjCProtocolExpr * E)197 llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
198 // FIXME: This should pass the Decl not the name.
199 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
200 }
201
202 /// \brief Adjust the type of the result of an Objective-C message send
203 /// expression when the method has a related result type.
AdjustRelatedResultType(CodeGenFunction & CGF,QualType ExpT,const ObjCMethodDecl * Method,RValue Result)204 static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
205 QualType ExpT,
206 const ObjCMethodDecl *Method,
207 RValue Result) {
208 if (!Method)
209 return Result;
210
211 if (!Method->hasRelatedResultType() ||
212 CGF.getContext().hasSameType(ExpT, Method->getResultType()) ||
213 !Result.isScalar())
214 return Result;
215
216 // We have applied a related result type. Cast the rvalue appropriately.
217 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
218 CGF.ConvertType(ExpT)));
219 }
220
221 /// Decide whether to extend the lifetime of the receiver of a
222 /// returns-inner-pointer message.
223 static bool
shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr * message)224 shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
225 switch (message->getReceiverKind()) {
226
227 // For a normal instance message, we should extend unless the
228 // receiver is loaded from a variable with precise lifetime.
229 case ObjCMessageExpr::Instance: {
230 const Expr *receiver = message->getInstanceReceiver();
231 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
232 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
233 receiver = ice->getSubExpr()->IgnoreParens();
234
235 // Only __strong variables.
236 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
237 return true;
238
239 // All ivars and fields have precise lifetime.
240 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
241 return false;
242
243 // Otherwise, check for variables.
244 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
245 if (!declRef) return true;
246 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
247 if (!var) return true;
248
249 // All variables have precise lifetime except local variables with
250 // automatic storage duration that aren't specially marked.
251 return (var->hasLocalStorage() &&
252 !var->hasAttr<ObjCPreciseLifetimeAttr>());
253 }
254
255 case ObjCMessageExpr::Class:
256 case ObjCMessageExpr::SuperClass:
257 // It's never necessary for class objects.
258 return false;
259
260 case ObjCMessageExpr::SuperInstance:
261 // We generally assume that 'self' lives throughout a method call.
262 return false;
263 }
264
265 llvm_unreachable("invalid receiver kind");
266 }
267
EmitObjCMessageExpr(const ObjCMessageExpr * E,ReturnValueSlot Return)268 RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
269 ReturnValueSlot Return) {
270 // Only the lookup mechanism and first two arguments of the method
271 // implementation vary between runtimes. We can get the receiver and
272 // arguments in generic code.
273
274 bool isDelegateInit = E->isDelegateInitCall();
275
276 const ObjCMethodDecl *method = E->getMethodDecl();
277
278 // We don't retain the receiver in delegate init calls, and this is
279 // safe because the receiver value is always loaded from 'self',
280 // which we zero out. We don't want to Block_copy block receivers,
281 // though.
282 bool retainSelf =
283 (!isDelegateInit &&
284 CGM.getLangOpts().ObjCAutoRefCount &&
285 method &&
286 method->hasAttr<NSConsumesSelfAttr>());
287
288 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
289 bool isSuperMessage = false;
290 bool isClassMessage = false;
291 ObjCInterfaceDecl *OID = 0;
292 // Find the receiver
293 QualType ReceiverType;
294 llvm::Value *Receiver = 0;
295 switch (E->getReceiverKind()) {
296 case ObjCMessageExpr::Instance:
297 ReceiverType = E->getInstanceReceiver()->getType();
298 if (retainSelf) {
299 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
300 E->getInstanceReceiver());
301 Receiver = ter.getPointer();
302 if (ter.getInt()) retainSelf = false;
303 } else
304 Receiver = EmitScalarExpr(E->getInstanceReceiver());
305 break;
306
307 case ObjCMessageExpr::Class: {
308 ReceiverType = E->getClassReceiver();
309 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
310 assert(ObjTy && "Invalid Objective-C class message send");
311 OID = ObjTy->getInterface();
312 assert(OID && "Invalid Objective-C class message send");
313 Receiver = Runtime.GetClass(*this, OID);
314 isClassMessage = true;
315 break;
316 }
317
318 case ObjCMessageExpr::SuperInstance:
319 ReceiverType = E->getSuperType();
320 Receiver = LoadObjCSelf();
321 isSuperMessage = true;
322 break;
323
324 case ObjCMessageExpr::SuperClass:
325 ReceiverType = E->getSuperType();
326 Receiver = LoadObjCSelf();
327 isSuperMessage = true;
328 isClassMessage = true;
329 break;
330 }
331
332 if (retainSelf)
333 Receiver = EmitARCRetainNonBlock(Receiver);
334
335 // In ARC, we sometimes want to "extend the lifetime"
336 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
337 // messages.
338 if (getLangOpts().ObjCAutoRefCount && method &&
339 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
340 shouldExtendReceiverForInnerPointerMessage(E))
341 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
342
343 QualType ResultType =
344 method ? method->getResultType() : E->getType();
345
346 CallArgList Args;
347 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
348
349 // For delegate init calls in ARC, do an unsafe store of null into
350 // self. This represents the call taking direct ownership of that
351 // value. We have to do this after emitting the other call
352 // arguments because they might also reference self, but we don't
353 // have to worry about any of them modifying self because that would
354 // be an undefined read and write of an object in unordered
355 // expressions.
356 if (isDelegateInit) {
357 assert(getLangOpts().ObjCAutoRefCount &&
358 "delegate init calls should only be marked in ARC");
359
360 // Do an unsafe store of null into self.
361 llvm::Value *selfAddr =
362 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
363 assert(selfAddr && "no self entry for a delegate init call?");
364
365 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
366 }
367
368 RValue result;
369 if (isSuperMessage) {
370 // super is only valid in an Objective-C method
371 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
372 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
373 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
374 E->getSelector(),
375 OMD->getClassInterface(),
376 isCategoryImpl,
377 Receiver,
378 isClassMessage,
379 Args,
380 method);
381 } else {
382 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
383 E->getSelector(),
384 Receiver, Args, OID,
385 method);
386 }
387
388 // For delegate init calls in ARC, implicitly store the result of
389 // the call back into self. This takes ownership of the value.
390 if (isDelegateInit) {
391 llvm::Value *selfAddr =
392 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
393 llvm::Value *newSelf = result.getScalarVal();
394
395 // The delegate return type isn't necessarily a matching type; in
396 // fact, it's quite likely to be 'id'.
397 llvm::Type *selfTy =
398 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
399 newSelf = Builder.CreateBitCast(newSelf, selfTy);
400
401 Builder.CreateStore(newSelf, selfAddr);
402 }
403
404 return AdjustRelatedResultType(*this, E->getType(), method, result);
405 }
406
407 namespace {
408 struct FinishARCDealloc : EHScopeStack::Cleanup {
Emit__anon87cd100e0111::FinishARCDealloc409 void Emit(CodeGenFunction &CGF, Flags flags) {
410 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
411
412 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
413 const ObjCInterfaceDecl *iface = impl->getClassInterface();
414 if (!iface->getSuperClass()) return;
415
416 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
417
418 // Call [super dealloc] if we have a superclass.
419 llvm::Value *self = CGF.LoadObjCSelf();
420
421 CallArgList args;
422 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
423 CGF.getContext().VoidTy,
424 method->getSelector(),
425 iface,
426 isCategory,
427 self,
428 /*is class msg*/ false,
429 args,
430 method);
431 }
432 };
433 }
434
435 /// StartObjCMethod - Begin emission of an ObjCMethod. This generates
436 /// the LLVM function and sets the other context used by
437 /// CodeGenFunction.
StartObjCMethod(const ObjCMethodDecl * OMD,const ObjCContainerDecl * CD,SourceLocation StartLoc)438 void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
439 const ObjCContainerDecl *CD,
440 SourceLocation StartLoc) {
441 FunctionArgList args;
442 // Check if we should generate debug info for this method.
443 if (!OMD->hasAttr<NoDebugAttr>())
444 maybeInitializeDebugInfo();
445
446 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
447
448 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
449 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
450
451 args.push_back(OMD->getSelfDecl());
452 args.push_back(OMD->getCmdDecl());
453
454 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
455 E = OMD->param_end(); PI != E; ++PI)
456 args.push_back(*PI);
457
458 CurGD = OMD;
459
460 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
461
462 // In ARC, certain methods get an extra cleanup.
463 if (CGM.getLangOpts().ObjCAutoRefCount &&
464 OMD->isInstanceMethod() &&
465 OMD->getSelector().isUnarySelector()) {
466 const IdentifierInfo *ident =
467 OMD->getSelector().getIdentifierInfoForSlot(0);
468 if (ident->isStr("dealloc"))
469 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
470 }
471 }
472
473 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
474 LValue lvalue, QualType type);
475
476 /// Generate an Objective-C method. An Objective-C method is a C function with
477 /// its pointer, name, and types registered in the class struture.
GenerateObjCMethod(const ObjCMethodDecl * OMD)478 void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
479 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
480 EmitStmt(OMD->getBody());
481 FinishFunction(OMD->getBodyRBrace());
482 }
483
484 /// emitStructGetterCall - Call the runtime function to load a property
485 /// into the return value slot.
emitStructGetterCall(CodeGenFunction & CGF,ObjCIvarDecl * ivar,bool isAtomic,bool hasStrong)486 static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
487 bool isAtomic, bool hasStrong) {
488 ASTContext &Context = CGF.getContext();
489
490 llvm::Value *src =
491 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
492 ivar, 0).getAddress();
493
494 // objc_copyStruct (ReturnValue, &structIvar,
495 // sizeof (Type of Ivar), isAtomic, false);
496 CallArgList args;
497
498 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
499 args.add(RValue::get(dest), Context.VoidPtrTy);
500
501 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
502 args.add(RValue::get(src), Context.VoidPtrTy);
503
504 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
505 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
506 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
507 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
508
509 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
510 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
511 FunctionType::ExtInfo(),
512 RequiredArgs::All),
513 fn, ReturnValueSlot(), args);
514 }
515
516 /// Determine whether the given architecture supports unaligned atomic
517 /// accesses. They don't have to be fast, just faster than a function
518 /// call and a mutex.
hasUnalignedAtomics(llvm::Triple::ArchType arch)519 static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
520 // FIXME: Allow unaligned atomic load/store on x86. (It is not
521 // currently supported by the backend.)
522 return 0;
523 }
524
525 /// Return the maximum size that permits atomic accesses for the given
526 /// architecture.
getMaxAtomicAccessSize(CodeGenModule & CGM,llvm::Triple::ArchType arch)527 static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
528 llvm::Triple::ArchType arch) {
529 // ARM has 8-byte atomic accesses, but it's not clear whether we
530 // want to rely on them here.
531
532 // In the default case, just assume that any size up to a pointer is
533 // fine given adequate alignment.
534 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
535 }
536
537 namespace {
538 class PropertyImplStrategy {
539 public:
540 enum StrategyKind {
541 /// The 'native' strategy is to use the architecture's provided
542 /// reads and writes.
543 Native,
544
545 /// Use objc_setProperty and objc_getProperty.
546 GetSetProperty,
547
548 /// Use objc_setProperty for the setter, but use expression
549 /// evaluation for the getter.
550 SetPropertyAndExpressionGet,
551
552 /// Use objc_copyStruct.
553 CopyStruct,
554
555 /// The 'expression' strategy is to emit normal assignment or
556 /// lvalue-to-rvalue expressions.
557 Expression
558 };
559
getKind() const560 StrategyKind getKind() const { return StrategyKind(Kind); }
561
hasStrongMember() const562 bool hasStrongMember() const { return HasStrong; }
isAtomic() const563 bool isAtomic() const { return IsAtomic; }
isCopy() const564 bool isCopy() const { return IsCopy; }
565
getIvarSize() const566 CharUnits getIvarSize() const { return IvarSize; }
getIvarAlignment() const567 CharUnits getIvarAlignment() const { return IvarAlignment; }
568
569 PropertyImplStrategy(CodeGenModule &CGM,
570 const ObjCPropertyImplDecl *propImpl);
571
572 private:
573 unsigned Kind : 8;
574 unsigned IsAtomic : 1;
575 unsigned IsCopy : 1;
576 unsigned HasStrong : 1;
577
578 CharUnits IvarSize;
579 CharUnits IvarAlignment;
580 };
581 }
582
583 /// Pick an implementation strategy for the given property synthesis.
PropertyImplStrategy(CodeGenModule & CGM,const ObjCPropertyImplDecl * propImpl)584 PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
585 const ObjCPropertyImplDecl *propImpl) {
586 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
587 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
588
589 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
590 IsAtomic = prop->isAtomic();
591 HasStrong = false; // doesn't matter here.
592
593 // Evaluate the ivar's size and alignment.
594 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
595 QualType ivarType = ivar->getType();
596 llvm::tie(IvarSize, IvarAlignment)
597 = CGM.getContext().getTypeInfoInChars(ivarType);
598
599 // If we have a copy property, we always have to use getProperty/setProperty.
600 // TODO: we could actually use setProperty and an expression for non-atomics.
601 if (IsCopy) {
602 Kind = GetSetProperty;
603 return;
604 }
605
606 // Handle retain.
607 if (setterKind == ObjCPropertyDecl::Retain) {
608 // In GC-only, there's nothing special that needs to be done.
609 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
610 // fallthrough
611
612 // In ARC, if the property is non-atomic, use expression emission,
613 // which translates to objc_storeStrong. This isn't required, but
614 // it's slightly nicer.
615 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
616 // Using standard expression emission for the setter is only
617 // acceptable if the ivar is __strong, which won't be true if
618 // the property is annotated with __attribute__((NSObject)).
619 // TODO: falling all the way back to objc_setProperty here is
620 // just laziness, though; we could still use objc_storeStrong
621 // if we hacked it right.
622 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
623 Kind = Expression;
624 else
625 Kind = SetPropertyAndExpressionGet;
626 return;
627
628 // Otherwise, we need to at least use setProperty. However, if
629 // the property isn't atomic, we can use normal expression
630 // emission for the getter.
631 } else if (!IsAtomic) {
632 Kind = SetPropertyAndExpressionGet;
633 return;
634
635 // Otherwise, we have to use both setProperty and getProperty.
636 } else {
637 Kind = GetSetProperty;
638 return;
639 }
640 }
641
642 // If we're not atomic, just use expression accesses.
643 if (!IsAtomic) {
644 Kind = Expression;
645 return;
646 }
647
648 // Properties on bitfield ivars need to be emitted using expression
649 // accesses even if they're nominally atomic.
650 if (ivar->isBitField()) {
651 Kind = Expression;
652 return;
653 }
654
655 // GC-qualified or ARC-qualified ivars need to be emitted as
656 // expressions. This actually works out to being atomic anyway,
657 // except for ARC __strong, but that should trigger the above code.
658 if (ivarType.hasNonTrivialObjCLifetime() ||
659 (CGM.getLangOpts().getGC() &&
660 CGM.getContext().getObjCGCAttrKind(ivarType))) {
661 Kind = Expression;
662 return;
663 }
664
665 // Compute whether the ivar has strong members.
666 if (CGM.getLangOpts().getGC())
667 if (const RecordType *recordType = ivarType->getAs<RecordType>())
668 HasStrong = recordType->getDecl()->hasObjectMember();
669
670 // We can never access structs with object members with a native
671 // access, because we need to use write barriers. This is what
672 // objc_copyStruct is for.
673 if (HasStrong) {
674 Kind = CopyStruct;
675 return;
676 }
677
678 // Otherwise, this is target-dependent and based on the size and
679 // alignment of the ivar.
680
681 // If the size of the ivar is not a power of two, give up. We don't
682 // want to get into the business of doing compare-and-swaps.
683 if (!IvarSize.isPowerOfTwo()) {
684 Kind = CopyStruct;
685 return;
686 }
687
688 llvm::Triple::ArchType arch =
689 CGM.getContext().getTargetInfo().getTriple().getArch();
690
691 // Most architectures require memory to fit within a single cache
692 // line, so the alignment has to be at least the size of the access.
693 // Otherwise we have to grab a lock.
694 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
695 Kind = CopyStruct;
696 return;
697 }
698
699 // If the ivar's size exceeds the architecture's maximum atomic
700 // access size, we have to use CopyStruct.
701 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
702 Kind = CopyStruct;
703 return;
704 }
705
706 // Otherwise, we can use native loads and stores.
707 Kind = Native;
708 }
709
710 /// \brief Generate an Objective-C property getter function.
711 ///
712 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
713 /// is illegal within a category.
GenerateObjCGetter(ObjCImplementationDecl * IMP,const ObjCPropertyImplDecl * PID)714 void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
715 const ObjCPropertyImplDecl *PID) {
716 llvm::Constant *AtomicHelperFn =
717 GenerateObjCAtomicGetterCopyHelperFunction(PID);
718 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
719 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
720 assert(OMD && "Invalid call to generate getter (empty method)");
721 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
722
723 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
724
725 FinishFunction();
726 }
727
hasTrivialGetExpr(const ObjCPropertyImplDecl * propImpl)728 static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
729 const Expr *getter = propImpl->getGetterCXXConstructor();
730 if (!getter) return true;
731
732 // Sema only makes only of these when the ivar has a C++ class type,
733 // so the form is pretty constrained.
734
735 // If the property has a reference type, we might just be binding a
736 // reference, in which case the result will be a gl-value. We should
737 // treat this as a non-trivial operation.
738 if (getter->isGLValue())
739 return false;
740
741 // If we selected a trivial copy-constructor, we're okay.
742 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
743 return (construct->getConstructor()->isTrivial());
744
745 // The constructor might require cleanups (in which case it's never
746 // trivial).
747 assert(isa<ExprWithCleanups>(getter));
748 return false;
749 }
750
751 /// emitCPPObjectAtomicGetterCall - Call the runtime function to
752 /// copy the ivar into the resturn slot.
emitCPPObjectAtomicGetterCall(CodeGenFunction & CGF,llvm::Value * returnAddr,ObjCIvarDecl * ivar,llvm::Constant * AtomicHelperFn)753 static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
754 llvm::Value *returnAddr,
755 ObjCIvarDecl *ivar,
756 llvm::Constant *AtomicHelperFn) {
757 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
758 // AtomicHelperFn);
759 CallArgList args;
760
761 // The 1st argument is the return Slot.
762 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
763
764 // The 2nd argument is the address of the ivar.
765 llvm::Value *ivarAddr =
766 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
767 CGF.LoadObjCSelf(), ivar, 0).getAddress();
768 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
769 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
770
771 // Third argument is the helper function.
772 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
773
774 llvm::Value *copyCppAtomicObjectFn =
775 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
776 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
777 args,
778 FunctionType::ExtInfo(),
779 RequiredArgs::All),
780 copyCppAtomicObjectFn, ReturnValueSlot(), args);
781 }
782
783 void
generateObjCGetterBody(const ObjCImplementationDecl * classImpl,const ObjCPropertyImplDecl * propImpl,const ObjCMethodDecl * GetterMethodDecl,llvm::Constant * AtomicHelperFn)784 CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
785 const ObjCPropertyImplDecl *propImpl,
786 const ObjCMethodDecl *GetterMethodDecl,
787 llvm::Constant *AtomicHelperFn) {
788 // If there's a non-trivial 'get' expression, we just have to emit that.
789 if (!hasTrivialGetExpr(propImpl)) {
790 if (!AtomicHelperFn) {
791 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
792 /*nrvo*/ 0);
793 EmitReturnStmt(ret);
794 }
795 else {
796 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
797 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
798 ivar, AtomicHelperFn);
799 }
800 return;
801 }
802
803 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
804 QualType propType = prop->getType();
805 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
806
807 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
808
809 // Pick an implementation strategy.
810 PropertyImplStrategy strategy(CGM, propImpl);
811 switch (strategy.getKind()) {
812 case PropertyImplStrategy::Native: {
813 // We don't need to do anything for a zero-size struct.
814 if (strategy.getIvarSize().isZero())
815 return;
816
817 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
818
819 // Currently, all atomic accesses have to be through integer
820 // types, so there's no point in trying to pick a prettier type.
821 llvm::Type *bitcastType =
822 llvm::Type::getIntNTy(getLLVMContext(),
823 getContext().toBits(strategy.getIvarSize()));
824 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
825
826 // Perform an atomic load. This does not impose ordering constraints.
827 llvm::Value *ivarAddr = LV.getAddress();
828 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
829 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
830 load->setAlignment(strategy.getIvarAlignment().getQuantity());
831 load->setAtomic(llvm::Unordered);
832
833 // Store that value into the return address. Doing this with a
834 // bitcast is likely to produce some pretty ugly IR, but it's not
835 // the *most* terrible thing in the world.
836 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
837
838 // Make sure we don't do an autorelease.
839 AutoreleaseResult = false;
840 return;
841 }
842
843 case PropertyImplStrategy::GetSetProperty: {
844 llvm::Value *getPropertyFn =
845 CGM.getObjCRuntime().GetPropertyGetFunction();
846 if (!getPropertyFn) {
847 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
848 return;
849 }
850
851 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
852 // FIXME: Can't this be simpler? This might even be worse than the
853 // corresponding gcc code.
854 llvm::Value *cmd =
855 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
856 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
857 llvm::Value *ivarOffset =
858 EmitIvarOffset(classImpl->getClassInterface(), ivar);
859
860 CallArgList args;
861 args.add(RValue::get(self), getContext().getObjCIdType());
862 args.add(RValue::get(cmd), getContext().getObjCSelType());
863 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
864 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
865 getContext().BoolTy);
866
867 // FIXME: We shouldn't need to get the function info here, the
868 // runtime already should have computed it to build the function.
869 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
870 FunctionType::ExtInfo(),
871 RequiredArgs::All),
872 getPropertyFn, ReturnValueSlot(), args);
873
874 // We need to fix the type here. Ivars with copy & retain are
875 // always objects so we don't need to worry about complex or
876 // aggregates.
877 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
878 getTypes().ConvertType(getterMethod->getResultType())));
879
880 EmitReturnOfRValue(RV, propType);
881
882 // objc_getProperty does an autorelease, so we should suppress ours.
883 AutoreleaseResult = false;
884
885 return;
886 }
887
888 case PropertyImplStrategy::CopyStruct:
889 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
890 strategy.hasStrongMember());
891 return;
892
893 case PropertyImplStrategy::Expression:
894 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
895 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
896
897 QualType ivarType = ivar->getType();
898 switch (getEvaluationKind(ivarType)) {
899 case TEK_Complex: {
900 ComplexPairTy pair = EmitLoadOfComplex(LV);
901 EmitStoreOfComplex(pair,
902 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
903 /*init*/ true);
904 return;
905 }
906 case TEK_Aggregate:
907 // The return value slot is guaranteed to not be aliased, but
908 // that's not necessarily the same as "on the stack", so
909 // we still potentially need objc_memmove_collectable.
910 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
911 return;
912 case TEK_Scalar: {
913 llvm::Value *value;
914 if (propType->isReferenceType()) {
915 value = LV.getAddress();
916 } else {
917 // We want to load and autoreleaseReturnValue ARC __weak ivars.
918 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
919 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
920
921 // Otherwise we want to do a simple load, suppressing the
922 // final autorelease.
923 } else {
924 value = EmitLoadOfLValue(LV).getScalarVal();
925 AutoreleaseResult = false;
926 }
927
928 value = Builder.CreateBitCast(value, ConvertType(propType));
929 value = Builder.CreateBitCast(value,
930 ConvertType(GetterMethodDecl->getResultType()));
931 }
932
933 EmitReturnOfRValue(RValue::get(value), propType);
934 return;
935 }
936 }
937 llvm_unreachable("bad evaluation kind");
938 }
939
940 }
941 llvm_unreachable("bad @property implementation strategy!");
942 }
943
944 /// emitStructSetterCall - Call the runtime function to store the value
945 /// from the first formal parameter into the given ivar.
emitStructSetterCall(CodeGenFunction & CGF,ObjCMethodDecl * OMD,ObjCIvarDecl * ivar)946 static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
947 ObjCIvarDecl *ivar) {
948 // objc_copyStruct (&structIvar, &Arg,
949 // sizeof (struct something), true, false);
950 CallArgList args;
951
952 // The first argument is the address of the ivar.
953 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
954 CGF.LoadObjCSelf(), ivar, 0)
955 .getAddress();
956 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
957 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
958
959 // The second argument is the address of the parameter variable.
960 ParmVarDecl *argVar = *OMD->param_begin();
961 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
962 VK_LValue, SourceLocation());
963 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
964 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
965 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
966
967 // The third argument is the sizeof the type.
968 llvm::Value *size =
969 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
970 args.add(RValue::get(size), CGF.getContext().getSizeType());
971
972 // The fourth argument is the 'isAtomic' flag.
973 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
974
975 // The fifth argument is the 'hasStrong' flag.
976 // FIXME: should this really always be false?
977 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
978
979 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
980 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
981 args,
982 FunctionType::ExtInfo(),
983 RequiredArgs::All),
984 copyStructFn, ReturnValueSlot(), args);
985 }
986
987 /// emitCPPObjectAtomicSetterCall - Call the runtime function to store
988 /// the value from the first formal parameter into the given ivar, using
989 /// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
emitCPPObjectAtomicSetterCall(CodeGenFunction & CGF,ObjCMethodDecl * OMD,ObjCIvarDecl * ivar,llvm::Constant * AtomicHelperFn)990 static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
991 ObjCMethodDecl *OMD,
992 ObjCIvarDecl *ivar,
993 llvm::Constant *AtomicHelperFn) {
994 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
995 // AtomicHelperFn);
996 CallArgList args;
997
998 // The first argument is the address of the ivar.
999 llvm::Value *ivarAddr =
1000 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1001 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1002 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1003 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1004
1005 // The second argument is the address of the parameter variable.
1006 ParmVarDecl *argVar = *OMD->param_begin();
1007 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
1008 VK_LValue, SourceLocation());
1009 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1010 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1011 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1012
1013 // Third argument is the helper function.
1014 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1015
1016 llvm::Value *copyCppAtomicObjectFn =
1017 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
1018 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1019 args,
1020 FunctionType::ExtInfo(),
1021 RequiredArgs::All),
1022 copyCppAtomicObjectFn, ReturnValueSlot(), args);
1023
1024
1025 }
1026
1027
hasTrivialSetExpr(const ObjCPropertyImplDecl * PID)1028 static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1029 Expr *setter = PID->getSetterCXXAssignment();
1030 if (!setter) return true;
1031
1032 // Sema only makes only of these when the ivar has a C++ class type,
1033 // so the form is pretty constrained.
1034
1035 // An operator call is trivial if the function it calls is trivial.
1036 // This also implies that there's nothing non-trivial going on with
1037 // the arguments, because operator= can only be trivial if it's a
1038 // synthesized assignment operator and therefore both parameters are
1039 // references.
1040 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
1041 if (const FunctionDecl *callee
1042 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1043 if (callee->isTrivial())
1044 return true;
1045 return false;
1046 }
1047
1048 assert(isa<ExprWithCleanups>(setter));
1049 return false;
1050 }
1051
UseOptimizedSetter(CodeGenModule & CGM)1052 static bool UseOptimizedSetter(CodeGenModule &CGM) {
1053 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
1054 return false;
1055 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
1056 }
1057
1058 void
generateObjCSetterBody(const ObjCImplementationDecl * classImpl,const ObjCPropertyImplDecl * propImpl,llvm::Constant * AtomicHelperFn)1059 CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
1060 const ObjCPropertyImplDecl *propImpl,
1061 llvm::Constant *AtomicHelperFn) {
1062 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
1063 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
1064 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
1065
1066 // Just use the setter expression if Sema gave us one and it's
1067 // non-trivial.
1068 if (!hasTrivialSetExpr(propImpl)) {
1069 if (!AtomicHelperFn)
1070 // If non-atomic, assignment is called directly.
1071 EmitStmt(propImpl->getSetterCXXAssignment());
1072 else
1073 // If atomic, assignment is called via a locking api.
1074 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1075 AtomicHelperFn);
1076 return;
1077 }
1078
1079 PropertyImplStrategy strategy(CGM, propImpl);
1080 switch (strategy.getKind()) {
1081 case PropertyImplStrategy::Native: {
1082 // We don't need to do anything for a zero-size struct.
1083 if (strategy.getIvarSize().isZero())
1084 return;
1085
1086 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
1087
1088 LValue ivarLValue =
1089 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1090 llvm::Value *ivarAddr = ivarLValue.getAddress();
1091
1092 // Currently, all atomic accesses have to be through integer
1093 // types, so there's no point in trying to pick a prettier type.
1094 llvm::Type *bitcastType =
1095 llvm::Type::getIntNTy(getLLVMContext(),
1096 getContext().toBits(strategy.getIvarSize()));
1097 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1098
1099 // Cast both arguments to the chosen operation type.
1100 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1101 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1102
1103 // This bitcast load is likely to cause some nasty IR.
1104 llvm::Value *load = Builder.CreateLoad(argAddr);
1105
1106 // Perform an atomic store. There are no memory ordering requirements.
1107 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1108 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1109 store->setAtomic(llvm::Unordered);
1110 return;
1111 }
1112
1113 case PropertyImplStrategy::GetSetProperty:
1114 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
1115
1116 llvm::Value *setOptimizedPropertyFn = 0;
1117 llvm::Value *setPropertyFn = 0;
1118 if (UseOptimizedSetter(CGM)) {
1119 // 10.8 and iOS 6.0 code and GC is off
1120 setOptimizedPropertyFn =
1121 CGM.getObjCRuntime()
1122 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1123 strategy.isCopy());
1124 if (!setOptimizedPropertyFn) {
1125 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1126 return;
1127 }
1128 }
1129 else {
1130 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1131 if (!setPropertyFn) {
1132 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1133 return;
1134 }
1135 }
1136
1137 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1138 // <is-atomic>, <is-copy>).
1139 llvm::Value *cmd =
1140 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1141 llvm::Value *self =
1142 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1143 llvm::Value *ivarOffset =
1144 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1145 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1146 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1147
1148 CallArgList args;
1149 args.add(RValue::get(self), getContext().getObjCIdType());
1150 args.add(RValue::get(cmd), getContext().getObjCSelType());
1151 if (setOptimizedPropertyFn) {
1152 args.add(RValue::get(arg), getContext().getObjCIdType());
1153 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1154 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1155 FunctionType::ExtInfo(),
1156 RequiredArgs::All),
1157 setOptimizedPropertyFn, ReturnValueSlot(), args);
1158 } else {
1159 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1160 args.add(RValue::get(arg), getContext().getObjCIdType());
1161 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1162 getContext().BoolTy);
1163 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1164 getContext().BoolTy);
1165 // FIXME: We shouldn't need to get the function info here, the runtime
1166 // already should have computed it to build the function.
1167 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1168 FunctionType::ExtInfo(),
1169 RequiredArgs::All),
1170 setPropertyFn, ReturnValueSlot(), args);
1171 }
1172
1173 return;
1174 }
1175
1176 case PropertyImplStrategy::CopyStruct:
1177 emitStructSetterCall(*this, setterMethod, ivar);
1178 return;
1179
1180 case PropertyImplStrategy::Expression:
1181 break;
1182 }
1183
1184 // Otherwise, fake up some ASTs and emit a normal assignment.
1185 ValueDecl *selfDecl = setterMethod->getSelfDecl();
1186 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1187 VK_LValue, SourceLocation());
1188 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1189 selfDecl->getType(), CK_LValueToRValue, &self,
1190 VK_RValue);
1191 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1192 SourceLocation(), &selfLoad, true, true);
1193
1194 ParmVarDecl *argDecl = *setterMethod->param_begin();
1195 QualType argType = argDecl->getType().getNonReferenceType();
1196 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
1197 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1198 argType.getUnqualifiedType(), CK_LValueToRValue,
1199 &arg, VK_RValue);
1200
1201 // The property type can differ from the ivar type in some situations with
1202 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1203 // The following absurdity is just to ensure well-formed IR.
1204 CastKind argCK = CK_NoOp;
1205 if (ivarRef.getType()->isObjCObjectPointerType()) {
1206 if (argLoad.getType()->isObjCObjectPointerType())
1207 argCK = CK_BitCast;
1208 else if (argLoad.getType()->isBlockPointerType())
1209 argCK = CK_BlockPointerToObjCPointerCast;
1210 else
1211 argCK = CK_CPointerToObjCPointerCast;
1212 } else if (ivarRef.getType()->isBlockPointerType()) {
1213 if (argLoad.getType()->isBlockPointerType())
1214 argCK = CK_BitCast;
1215 else
1216 argCK = CK_AnyPointerToBlockPointerCast;
1217 } else if (ivarRef.getType()->isPointerType()) {
1218 argCK = CK_BitCast;
1219 }
1220 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1221 ivarRef.getType(), argCK, &argLoad,
1222 VK_RValue);
1223 Expr *finalArg = &argLoad;
1224 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1225 argLoad.getType()))
1226 finalArg = &argCast;
1227
1228
1229 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1230 ivarRef.getType(), VK_RValue, OK_Ordinary,
1231 SourceLocation(), false);
1232 EmitStmt(&assign);
1233 }
1234
1235 /// \brief Generate an Objective-C property setter function.
1236 ///
1237 /// The given Decl must be an ObjCImplementationDecl. \@synthesize
1238 /// is illegal within a category.
GenerateObjCSetter(ObjCImplementationDecl * IMP,const ObjCPropertyImplDecl * PID)1239 void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1240 const ObjCPropertyImplDecl *PID) {
1241 llvm::Constant *AtomicHelperFn =
1242 GenerateObjCAtomicSetterCopyHelperFunction(PID);
1243 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1244 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1245 assert(OMD && "Invalid call to generate setter (empty method)");
1246 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
1247
1248 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
1249
1250 FinishFunction();
1251 }
1252
1253 namespace {
1254 struct DestroyIvar : EHScopeStack::Cleanup {
1255 private:
1256 llvm::Value *addr;
1257 const ObjCIvarDecl *ivar;
1258 CodeGenFunction::Destroyer *destroyer;
1259 bool useEHCleanupForArray;
1260 public:
DestroyIvar__anon87cd100e0311::DestroyIvar1261 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1262 CodeGenFunction::Destroyer *destroyer,
1263 bool useEHCleanupForArray)
1264 : addr(addr), ivar(ivar), destroyer(destroyer),
1265 useEHCleanupForArray(useEHCleanupForArray) {}
1266
Emit__anon87cd100e0311::DestroyIvar1267 void Emit(CodeGenFunction &CGF, Flags flags) {
1268 LValue lvalue
1269 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1270 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
1271 flags.isForNormalCleanup() && useEHCleanupForArray);
1272 }
1273 };
1274 }
1275
1276 /// Like CodeGenFunction::destroyARCStrong, but do it with a call.
destroyARCStrongWithStore(CodeGenFunction & CGF,llvm::Value * addr,QualType type)1277 static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1278 llvm::Value *addr,
1279 QualType type) {
1280 llvm::Value *null = getNullForVariable(addr);
1281 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1282 }
1283
emitCXXDestructMethod(CodeGenFunction & CGF,ObjCImplementationDecl * impl)1284 static void emitCXXDestructMethod(CodeGenFunction &CGF,
1285 ObjCImplementationDecl *impl) {
1286 CodeGenFunction::RunCleanupsScope scope(CGF);
1287
1288 llvm::Value *self = CGF.LoadObjCSelf();
1289
1290 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1291 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
1292 ivar; ivar = ivar->getNextIvar()) {
1293 QualType type = ivar->getType();
1294
1295 // Check whether the ivar is a destructible type.
1296 QualType::DestructionKind dtorKind = type.isDestructedType();
1297 if (!dtorKind) continue;
1298
1299 CodeGenFunction::Destroyer *destroyer = 0;
1300
1301 // Use a call to objc_storeStrong to destroy strong ivars, for the
1302 // general benefit of the tools.
1303 if (dtorKind == QualType::DK_objc_strong_lifetime) {
1304 destroyer = destroyARCStrongWithStore;
1305
1306 // Otherwise use the default for the destruction kind.
1307 } else {
1308 destroyer = CGF.getDestroyer(dtorKind);
1309 }
1310
1311 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1312
1313 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1314 cleanupKind & EHCleanup);
1315 }
1316
1317 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1318 }
1319
GenerateObjCCtorDtorMethod(ObjCImplementationDecl * IMP,ObjCMethodDecl * MD,bool ctor)1320 void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1321 ObjCMethodDecl *MD,
1322 bool ctor) {
1323 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
1324 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
1325
1326 // Emit .cxx_construct.
1327 if (ctor) {
1328 // Suppress the final autorelease in ARC.
1329 AutoreleaseResult = false;
1330
1331 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
1332 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1333 E = IMP->init_end(); B != E; ++B) {
1334 CXXCtorInitializer *IvarInit = (*B);
1335 FieldDecl *Field = IvarInit->getAnyMember();
1336 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
1337 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1338 LoadObjCSelf(), Ivar, 0);
1339 EmitAggExpr(IvarInit->getInit(),
1340 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
1341 AggValueSlot::DoesNotNeedGCBarriers,
1342 AggValueSlot::IsNotAliased));
1343 }
1344 // constructor returns 'self'.
1345 CodeGenTypes &Types = CGM.getTypes();
1346 QualType IdTy(CGM.getContext().getObjCIdType());
1347 llvm::Value *SelfAsId =
1348 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1349 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
1350
1351 // Emit .cxx_destruct.
1352 } else {
1353 emitCXXDestructMethod(*this, IMP);
1354 }
1355 FinishFunction();
1356 }
1357
IndirectObjCSetterArg(const CGFunctionInfo & FI)1358 bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1359 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1360 it++; it++;
1361 const ABIArgInfo &AI = it->info;
1362 // FIXME. Is this sufficient check?
1363 return (AI.getKind() == ABIArgInfo::Indirect);
1364 }
1365
IvarTypeWithAggrGCObjects(QualType Ty)1366 bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
1367 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
1368 return false;
1369 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1370 return FDTTy->getDecl()->hasObjectMember();
1371 return false;
1372 }
1373
LoadObjCSelf()1374 llvm::Value *CodeGenFunction::LoadObjCSelf() {
1375 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1376 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
1377 }
1378
TypeOfSelfObject()1379 QualType CodeGenFunction::TypeOfSelfObject() {
1380 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1381 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
1382 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1383 getContext().getCanonicalType(selfDecl->getType()));
1384 return PTy->getPointeeType();
1385 }
1386
EmitObjCForCollectionStmt(const ObjCForCollectionStmt & S)1387 void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
1388 llvm::Constant *EnumerationMutationFn =
1389 CGM.getObjCRuntime().EnumerationMutationFunction();
1390
1391 if (!EnumerationMutationFn) {
1392 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1393 return;
1394 }
1395
1396 CGDebugInfo *DI = getDebugInfo();
1397 if (DI)
1398 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
1399
1400 // The local variable comes into scope immediately.
1401 AutoVarEmission variable = AutoVarEmission::invalid();
1402 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1403 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1404
1405 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
1406
1407 // Fast enumeration state.
1408 QualType StateTy = CGM.getObjCFastEnumerationStateType();
1409 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
1410 EmitNullInitialization(StatePtr, StateTy);
1411
1412 // Number of elements in the items array.
1413 static const unsigned NumItems = 16;
1414
1415 // Fetch the countByEnumeratingWithState:objects:count: selector.
1416 IdentifierInfo *II[] = {
1417 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1418 &CGM.getContext().Idents.get("objects"),
1419 &CGM.getContext().Idents.get("count")
1420 };
1421 Selector FastEnumSel =
1422 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
1423
1424 QualType ItemsTy =
1425 getContext().getConstantArrayType(getContext().getObjCIdType(),
1426 llvm::APInt(32, NumItems),
1427 ArrayType::Normal, 0);
1428 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
1429
1430 // Emit the collection pointer. In ARC, we do a retain.
1431 llvm::Value *Collection;
1432 if (getLangOpts().ObjCAutoRefCount) {
1433 Collection = EmitARCRetainScalarExpr(S.getCollection());
1434
1435 // Enter a cleanup to do the release.
1436 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1437 } else {
1438 Collection = EmitScalarExpr(S.getCollection());
1439 }
1440
1441 // The 'continue' label needs to appear within the cleanup for the
1442 // collection object.
1443 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1444
1445 // Send it our message:
1446 CallArgList Args;
1447
1448 // The first argument is a temporary of the enumeration-state type.
1449 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
1450
1451 // The second argument is a temporary array with space for NumItems
1452 // pointers. We'll actually be loading elements from the array
1453 // pointer written into the control state; this buffer is so that
1454 // collections that *aren't* backed by arrays can still queue up
1455 // batches of elements.
1456 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
1457
1458 // The third argument is the capacity of that temporary array.
1459 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
1460 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
1461 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
1462
1463 // Start the enumeration.
1464 RValue CountRV =
1465 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1466 getContext().UnsignedLongTy,
1467 FastEnumSel,
1468 Collection, Args);
1469
1470 // The initial number of objects that were returned in the buffer.
1471 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
1472
1473 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1474 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
1475
1476 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
1477
1478 // If the limit pointer was zero to begin with, the collection is
1479 // empty; skip all this.
1480 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1481 EmptyBB, LoopInitBB);
1482
1483 // Otherwise, initialize the loop.
1484 EmitBlock(LoopInitBB);
1485
1486 // Save the initial mutations value. This is the value at an
1487 // address that was written into the state object by
1488 // countByEnumeratingWithState:objects:count:.
1489 llvm::Value *StateMutationsPtrPtr =
1490 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
1491 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
1492 "mutationsptr");
1493
1494 llvm::Value *initialMutations =
1495 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
1496
1497 // Start looping. This is the point we return to whenever we have a
1498 // fresh, non-empty batch of objects.
1499 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1500 EmitBlock(LoopBodyBB);
1501
1502 // The current index into the buffer.
1503 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
1504 index->addIncoming(zero, LoopInitBB);
1505
1506 // The current buffer size.
1507 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
1508 count->addIncoming(initialBufferLimit, LoopInitBB);
1509
1510 // Check whether the mutations value has changed from where it was
1511 // at start. StateMutationsPtr should actually be invariant between
1512 // refreshes.
1513 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
1514 llvm::Value *currentMutations
1515 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
1516
1517 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
1518 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
1519
1520 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1521 WasNotMutatedBB, WasMutatedBB);
1522
1523 // If so, call the enumeration-mutation function.
1524 EmitBlock(WasMutatedBB);
1525 llvm::Value *V =
1526 Builder.CreateBitCast(Collection,
1527 ConvertType(getContext().getObjCIdType()));
1528 CallArgList Args2;
1529 Args2.add(RValue::get(V), getContext().getObjCIdType());
1530 // FIXME: We shouldn't need to get the function info here, the runtime already
1531 // should have computed it to build the function.
1532 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1533 FunctionType::ExtInfo(),
1534 RequiredArgs::All),
1535 EnumerationMutationFn, ReturnValueSlot(), Args2);
1536
1537 // Otherwise, or if the mutation function returns, just continue.
1538 EmitBlock(WasNotMutatedBB);
1539
1540 // Initialize the element variable.
1541 RunCleanupsScope elementVariableScope(*this);
1542 bool elementIsVariable;
1543 LValue elementLValue;
1544 QualType elementType;
1545 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
1546 // Initialize the variable, in case it's a __block variable or something.
1547 EmitAutoVarInit(variable);
1548
1549 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
1550 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
1551 VK_LValue, SourceLocation());
1552 elementLValue = EmitLValue(&tempDRE);
1553 elementType = D->getType();
1554 elementIsVariable = true;
1555
1556 if (D->isARCPseudoStrong())
1557 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
1558 } else {
1559 elementLValue = LValue(); // suppress warning
1560 elementType = cast<Expr>(S.getElement())->getType();
1561 elementIsVariable = false;
1562 }
1563 llvm::Type *convertedElementType = ConvertType(elementType);
1564
1565 // Fetch the buffer out of the enumeration state.
1566 // TODO: this pointer should actually be invariant between
1567 // refreshes, which would help us do certain loop optimizations.
1568 llvm::Value *StateItemsPtr =
1569 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
1570 llvm::Value *EnumStateItems =
1571 Builder.CreateLoad(StateItemsPtr, "stateitems");
1572
1573 // Fetch the value at the current index from the buffer.
1574 llvm::Value *CurrentItemPtr =
1575 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1576 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
1577
1578 // Cast that value to the right type.
1579 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1580 "currentitem");
1581
1582 // Make sure we have an l-value. Yes, this gets evaluated every
1583 // time through the loop.
1584 if (!elementIsVariable) {
1585 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1586 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
1587 } else {
1588 EmitScalarInit(CurrentItem, elementLValue);
1589 }
1590
1591 // If we do have an element variable, this assignment is the end of
1592 // its initialization.
1593 if (elementIsVariable)
1594 EmitAutoVarCleanups(variable);
1595
1596 // Perform the loop body, setting up break and continue labels.
1597 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
1598 {
1599 RunCleanupsScope Scope(*this);
1600 EmitStmt(S.getBody());
1601 }
1602 BreakContinueStack.pop_back();
1603
1604 // Destroy the element variable now.
1605 elementVariableScope.ForceCleanup();
1606
1607 // Check whether there are more elements.
1608 EmitBlock(AfterBody.getBlock());
1609
1610 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
1611
1612 // First we check in the local buffer.
1613 llvm::Value *indexPlusOne
1614 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
1615
1616 // If we haven't overrun the buffer yet, we can continue.
1617 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1618 LoopBodyBB, FetchMoreBB);
1619
1620 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1621 count->addIncoming(count, AfterBody.getBlock());
1622
1623 // Otherwise, we have to fetch more elements.
1624 EmitBlock(FetchMoreBB);
1625
1626 CountRV =
1627 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
1628 getContext().UnsignedLongTy,
1629 FastEnumSel,
1630 Collection, Args);
1631
1632 // If we got a zero count, we're done.
1633 llvm::Value *refetchCount = CountRV.getScalarVal();
1634
1635 // (note that the message send might split FetchMoreBB)
1636 index->addIncoming(zero, Builder.GetInsertBlock());
1637 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1638
1639 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1640 EmptyBB, LoopBodyBB);
1641
1642 // No more elements.
1643 EmitBlock(EmptyBB);
1644
1645 if (!elementIsVariable) {
1646 // If the element was not a declaration, set it to be null.
1647
1648 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1649 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
1650 EmitStoreThroughLValue(RValue::get(null), elementLValue);
1651 }
1652
1653 if (DI)
1654 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
1655
1656 // Leave the cleanup we entered in ARC.
1657 if (getLangOpts().ObjCAutoRefCount)
1658 PopCleanupBlock();
1659
1660 EmitBlock(LoopEnd.getBlock());
1661 }
1662
EmitObjCAtTryStmt(const ObjCAtTryStmt & S)1663 void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
1664 CGM.getObjCRuntime().EmitTryStmt(*this, S);
1665 }
1666
EmitObjCAtThrowStmt(const ObjCAtThrowStmt & S)1667 void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
1668 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1669 }
1670
EmitObjCAtSynchronizedStmt(const ObjCAtSynchronizedStmt & S)1671 void CodeGenFunction::EmitObjCAtSynchronizedStmt(
1672 const ObjCAtSynchronizedStmt &S) {
1673 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
1674 }
1675
1676 /// Produce the code for a CK_ARCProduceObject. Just does a
1677 /// primitive retain.
EmitObjCProduceObject(QualType type,llvm::Value * value)1678 llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1679 llvm::Value *value) {
1680 return EmitARCRetain(type, value);
1681 }
1682
1683 namespace {
1684 struct CallObjCRelease : EHScopeStack::Cleanup {
CallObjCRelease__anon87cd100e0411::CallObjCRelease1685 CallObjCRelease(llvm::Value *object) : object(object) {}
1686 llvm::Value *object;
1687
Emit__anon87cd100e0411::CallObjCRelease1688 void Emit(CodeGenFunction &CGF, Flags flags) {
1689 // Releases at the end of the full-expression are imprecise.
1690 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
1691 }
1692 };
1693 }
1694
1695 /// Produce the code for a CK_ARCConsumeObject. Does a primitive
1696 /// release at the end of the full-expression.
EmitObjCConsumeObject(QualType type,llvm::Value * object)1697 llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1698 llvm::Value *object) {
1699 // If we're in a conditional branch, we need to make the cleanup
1700 // conditional.
1701 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
1702 return object;
1703 }
1704
EmitObjCExtendObjectLifetime(QualType type,llvm::Value * value)1705 llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1706 llvm::Value *value) {
1707 return EmitARCRetainAutorelease(type, value);
1708 }
1709
1710
createARCRuntimeFunction(CodeGenModule & CGM,llvm::FunctionType * type,StringRef fnName)1711 static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
1712 llvm::FunctionType *type,
1713 StringRef fnName) {
1714 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1715
1716 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
1717 // If the target runtime doesn't naturally support ARC, emit weak
1718 // references to the runtime support library. We don't really
1719 // permit this to fail, but we need a particular relocation style.
1720 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
1721 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1722 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1723 // If we have Native ARC, set nonlazybind attribute for these APIs for
1724 // performance.
1725 f->addFnAttr(llvm::Attribute::NonLazyBind);
1726 }
1727 }
1728
1729 return fn;
1730 }
1731
1732 /// Perform an operation having the signature
1733 /// i8* (i8*)
1734 /// where a null input causes a no-op and returns null.
emitARCValueOperation(CodeGenFunction & CGF,llvm::Value * value,llvm::Constant * & fn,StringRef fnName,bool isTailCall=false)1735 static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1736 llvm::Value *value,
1737 llvm::Constant *&fn,
1738 StringRef fnName,
1739 bool isTailCall = false) {
1740 if (isa<llvm::ConstantPointerNull>(value)) return value;
1741
1742 if (!fn) {
1743 llvm::FunctionType *fnType =
1744 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
1745 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1746 }
1747
1748 // Cast the argument to 'id'.
1749 llvm::Type *origType = value->getType();
1750 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1751
1752 // Call the function.
1753 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
1754 if (isTailCall)
1755 call->setTailCall();
1756
1757 // Cast the result back to the original type.
1758 return CGF.Builder.CreateBitCast(call, origType);
1759 }
1760
1761 /// Perform an operation having the following signature:
1762 /// i8* (i8**)
emitARCLoadOperation(CodeGenFunction & CGF,llvm::Value * addr,llvm::Constant * & fn,StringRef fnName)1763 static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1764 llvm::Value *addr,
1765 llvm::Constant *&fn,
1766 StringRef fnName) {
1767 if (!fn) {
1768 llvm::FunctionType *fnType =
1769 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
1770 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1771 }
1772
1773 // Cast the argument to 'id*'.
1774 llvm::Type *origType = addr->getType();
1775 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1776
1777 // Call the function.
1778 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
1779
1780 // Cast the result back to a dereference of the original type.
1781 if (origType != CGF.Int8PtrPtrTy)
1782 result = CGF.Builder.CreateBitCast(result,
1783 cast<llvm::PointerType>(origType)->getElementType());
1784
1785 return result;
1786 }
1787
1788 /// Perform an operation having the following signature:
1789 /// i8* (i8**, i8*)
emitARCStoreOperation(CodeGenFunction & CGF,llvm::Value * addr,llvm::Value * value,llvm::Constant * & fn,StringRef fnName,bool ignored)1790 static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1791 llvm::Value *addr,
1792 llvm::Value *value,
1793 llvm::Constant *&fn,
1794 StringRef fnName,
1795 bool ignored) {
1796 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1797 == value->getType());
1798
1799 if (!fn) {
1800 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
1801
1802 llvm::FunctionType *fnType
1803 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1804 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1805 }
1806
1807 llvm::Type *origType = value->getType();
1808
1809 llvm::Value *args[] = {
1810 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1811 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1812 };
1813 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
1814
1815 if (ignored) return 0;
1816
1817 return CGF.Builder.CreateBitCast(result, origType);
1818 }
1819
1820 /// Perform an operation having the following signature:
1821 /// void (i8**, i8**)
emitARCCopyOperation(CodeGenFunction & CGF,llvm::Value * dst,llvm::Value * src,llvm::Constant * & fn,StringRef fnName)1822 static void emitARCCopyOperation(CodeGenFunction &CGF,
1823 llvm::Value *dst,
1824 llvm::Value *src,
1825 llvm::Constant *&fn,
1826 StringRef fnName) {
1827 assert(dst->getType() == src->getType());
1828
1829 if (!fn) {
1830 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1831
1832 llvm::FunctionType *fnType
1833 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1834 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1835 }
1836
1837 llvm::Value *args[] = {
1838 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1839 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1840 };
1841 CGF.EmitNounwindRuntimeCall(fn, args);
1842 }
1843
1844 /// Produce the code to do a retain. Based on the type, calls one of:
1845 /// call i8* \@objc_retain(i8* %value)
1846 /// call i8* \@objc_retainBlock(i8* %value)
EmitARCRetain(QualType type,llvm::Value * value)1847 llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1848 if (type->isBlockPointerType())
1849 return EmitARCRetainBlock(value, /*mandatory*/ false);
1850 else
1851 return EmitARCRetainNonBlock(value);
1852 }
1853
1854 /// Retain the given object, with normal retain semantics.
1855 /// call i8* \@objc_retain(i8* %value)
EmitARCRetainNonBlock(llvm::Value * value)1856 llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1857 return emitARCValueOperation(*this, value,
1858 CGM.getARCEntrypoints().objc_retain,
1859 "objc_retain");
1860 }
1861
1862 /// Retain the given block, with _Block_copy semantics.
1863 /// call i8* \@objc_retainBlock(i8* %value)
1864 ///
1865 /// \param mandatory - If false, emit the call with metadata
1866 /// indicating that it's okay for the optimizer to eliminate this call
1867 /// if it can prove that the block never escapes except down the stack.
EmitARCRetainBlock(llvm::Value * value,bool mandatory)1868 llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1869 bool mandatory) {
1870 llvm::Value *result
1871 = emitARCValueOperation(*this, value,
1872 CGM.getARCEntrypoints().objc_retainBlock,
1873 "objc_retainBlock");
1874
1875 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1876 // tell the optimizer that it doesn't need to do this copy if the
1877 // block doesn't escape, where being passed as an argument doesn't
1878 // count as escaping.
1879 if (!mandatory && isa<llvm::Instruction>(result)) {
1880 llvm::CallInst *call
1881 = cast<llvm::CallInst>(result->stripPointerCasts());
1882 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1883
1884 SmallVector<llvm::Value*,1> args;
1885 call->setMetadata("clang.arc.copy_on_escape",
1886 llvm::MDNode::get(Builder.getContext(), args));
1887 }
1888
1889 return result;
1890 }
1891
1892 /// Retain the given object which is the result of a function call.
1893 /// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
1894 ///
1895 /// Yes, this function name is one character away from a different
1896 /// call with completely different semantics.
1897 llvm::Value *
EmitARCRetainAutoreleasedReturnValue(llvm::Value * value)1898 CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1899 // Fetch the void(void) inline asm which marks that we're going to
1900 // retain the autoreleased return value.
1901 llvm::InlineAsm *&marker
1902 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1903 if (!marker) {
1904 StringRef assembly
1905 = CGM.getTargetCodeGenInfo()
1906 .getARCRetainAutoreleasedReturnValueMarker();
1907
1908 // If we have an empty assembly string, there's nothing to do.
1909 if (assembly.empty()) {
1910
1911 // Otherwise, at -O0, build an inline asm that we're going to call
1912 // in a moment.
1913 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1914 llvm::FunctionType *type =
1915 llvm::FunctionType::get(VoidTy, /*variadic*/false);
1916
1917 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1918
1919 // If we're at -O1 and above, we don't want to litter the code
1920 // with this marker yet, so leave a breadcrumb for the ARC
1921 // optimizer to pick up.
1922 } else {
1923 llvm::NamedMDNode *metadata =
1924 CGM.getModule().getOrInsertNamedMetadata(
1925 "clang.arc.retainAutoreleasedReturnValueMarker");
1926 assert(metadata->getNumOperands() <= 1);
1927 if (metadata->getNumOperands() == 0) {
1928 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
1929 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
1930 }
1931 }
1932 }
1933
1934 // Call the marker asm if we made one, which we do only at -O0.
1935 if (marker) Builder.CreateCall(marker);
1936
1937 return emitARCValueOperation(*this, value,
1938 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1939 "objc_retainAutoreleasedReturnValue");
1940 }
1941
1942 /// Release the given object.
1943 /// call void \@objc_release(i8* %value)
EmitARCRelease(llvm::Value * value,ARCPreciseLifetime_t precise)1944 void CodeGenFunction::EmitARCRelease(llvm::Value *value,
1945 ARCPreciseLifetime_t precise) {
1946 if (isa<llvm::ConstantPointerNull>(value)) return;
1947
1948 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1949 if (!fn) {
1950 llvm::FunctionType *fnType =
1951 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
1952 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1953 }
1954
1955 // Cast the argument to 'id'.
1956 value = Builder.CreateBitCast(value, Int8PtrTy);
1957
1958 // Call objc_release.
1959 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
1960
1961 if (precise == ARCImpreciseLifetime) {
1962 SmallVector<llvm::Value*,1> args;
1963 call->setMetadata("clang.imprecise_release",
1964 llvm::MDNode::get(Builder.getContext(), args));
1965 }
1966 }
1967
1968 /// Destroy a __strong variable.
1969 ///
1970 /// At -O0, emit a call to store 'null' into the address;
1971 /// instrumenting tools prefer this because the address is exposed,
1972 /// but it's relatively cumbersome to optimize.
1973 ///
1974 /// At -O1 and above, just load and call objc_release.
1975 ///
1976 /// call void \@objc_storeStrong(i8** %addr, i8* null)
EmitARCDestroyStrong(llvm::Value * addr,ARCPreciseLifetime_t precise)1977 void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
1978 ARCPreciseLifetime_t precise) {
1979 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1980 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
1981 llvm::Value *null = llvm::ConstantPointerNull::get(
1982 cast<llvm::PointerType>(addrTy->getElementType()));
1983 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1984 return;
1985 }
1986
1987 llvm::Value *value = Builder.CreateLoad(addr);
1988 EmitARCRelease(value, precise);
1989 }
1990
1991 /// Store into a strong object. Always calls this:
1992 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
EmitARCStoreStrongCall(llvm::Value * addr,llvm::Value * value,bool ignored)1993 llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1994 llvm::Value *value,
1995 bool ignored) {
1996 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1997 == value->getType());
1998
1999 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2000 if (!fn) {
2001 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
2002 llvm::FunctionType *fnType
2003 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2004 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2005 }
2006
2007 llvm::Value *args[] = {
2008 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2009 Builder.CreateBitCast(value, Int8PtrTy)
2010 };
2011 EmitNounwindRuntimeCall(fn, args);
2012
2013 if (ignored) return 0;
2014 return value;
2015 }
2016
2017 /// Store into a strong object. Sometimes calls this:
2018 /// call void \@objc_storeStrong(i8** %addr, i8* %value)
2019 /// Other times, breaks it down into components.
EmitARCStoreStrong(LValue dst,llvm::Value * newValue,bool ignored)2020 llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
2021 llvm::Value *newValue,
2022 bool ignored) {
2023 QualType type = dst.getType();
2024 bool isBlock = type->isBlockPointerType();
2025
2026 // Use a store barrier at -O0 unless this is a block type or the
2027 // lvalue is inadequately aligned.
2028 if (shouldUseFusedARCCalls() &&
2029 !isBlock &&
2030 (dst.getAlignment().isZero() ||
2031 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
2032 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2033 }
2034
2035 // Otherwise, split it out.
2036
2037 // Retain the new value.
2038 newValue = EmitARCRetain(type, newValue);
2039
2040 // Read the old value.
2041 llvm::Value *oldValue = EmitLoadOfScalar(dst);
2042
2043 // Store. We do this before the release so that any deallocs won't
2044 // see the old value.
2045 EmitStoreOfScalar(newValue, dst);
2046
2047 // Finally, release the old value.
2048 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
2049
2050 return newValue;
2051 }
2052
2053 /// Autorelease the given object.
2054 /// call i8* \@objc_autorelease(i8* %value)
EmitARCAutorelease(llvm::Value * value)2055 llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2056 return emitARCValueOperation(*this, value,
2057 CGM.getARCEntrypoints().objc_autorelease,
2058 "objc_autorelease");
2059 }
2060
2061 /// Autorelease the given object.
2062 /// call i8* \@objc_autoreleaseReturnValue(i8* %value)
2063 llvm::Value *
EmitARCAutoreleaseReturnValue(llvm::Value * value)2064 CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2065 return emitARCValueOperation(*this, value,
2066 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2067 "objc_autoreleaseReturnValue",
2068 /*isTailCall*/ true);
2069 }
2070
2071 /// Do a fused retain/autorelease of the given object.
2072 /// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
2073 llvm::Value *
EmitARCRetainAutoreleaseReturnValue(llvm::Value * value)2074 CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2075 return emitARCValueOperation(*this, value,
2076 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2077 "objc_retainAutoreleaseReturnValue",
2078 /*isTailCall*/ true);
2079 }
2080
2081 /// Do a fused retain/autorelease of the given object.
2082 /// call i8* \@objc_retainAutorelease(i8* %value)
2083 /// or
2084 /// %retain = call i8* \@objc_retainBlock(i8* %value)
2085 /// call i8* \@objc_autorelease(i8* %retain)
EmitARCRetainAutorelease(QualType type,llvm::Value * value)2086 llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2087 llvm::Value *value) {
2088 if (!type->isBlockPointerType())
2089 return EmitARCRetainAutoreleaseNonBlock(value);
2090
2091 if (isa<llvm::ConstantPointerNull>(value)) return value;
2092
2093 llvm::Type *origType = value->getType();
2094 value = Builder.CreateBitCast(value, Int8PtrTy);
2095 value = EmitARCRetainBlock(value, /*mandatory*/ true);
2096 value = EmitARCAutorelease(value);
2097 return Builder.CreateBitCast(value, origType);
2098 }
2099
2100 /// Do a fused retain/autorelease of the given object.
2101 /// call i8* \@objc_retainAutorelease(i8* %value)
2102 llvm::Value *
EmitARCRetainAutoreleaseNonBlock(llvm::Value * value)2103 CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2104 return emitARCValueOperation(*this, value,
2105 CGM.getARCEntrypoints().objc_retainAutorelease,
2106 "objc_retainAutorelease");
2107 }
2108
2109 /// i8* \@objc_loadWeak(i8** %addr)
2110 /// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
EmitARCLoadWeak(llvm::Value * addr)2111 llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2112 return emitARCLoadOperation(*this, addr,
2113 CGM.getARCEntrypoints().objc_loadWeak,
2114 "objc_loadWeak");
2115 }
2116
2117 /// i8* \@objc_loadWeakRetained(i8** %addr)
EmitARCLoadWeakRetained(llvm::Value * addr)2118 llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2119 return emitARCLoadOperation(*this, addr,
2120 CGM.getARCEntrypoints().objc_loadWeakRetained,
2121 "objc_loadWeakRetained");
2122 }
2123
2124 /// i8* \@objc_storeWeak(i8** %addr, i8* %value)
2125 /// Returns %value.
EmitARCStoreWeak(llvm::Value * addr,llvm::Value * value,bool ignored)2126 llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2127 llvm::Value *value,
2128 bool ignored) {
2129 return emitARCStoreOperation(*this, addr, value,
2130 CGM.getARCEntrypoints().objc_storeWeak,
2131 "objc_storeWeak", ignored);
2132 }
2133
2134 /// i8* \@objc_initWeak(i8** %addr, i8* %value)
2135 /// Returns %value. %addr is known to not have a current weak entry.
2136 /// Essentially equivalent to:
2137 /// *addr = nil; objc_storeWeak(addr, value);
EmitARCInitWeak(llvm::Value * addr,llvm::Value * value)2138 void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2139 // If we're initializing to null, just write null to memory; no need
2140 // to get the runtime involved. But don't do this if optimization
2141 // is enabled, because accounting for this would make the optimizer
2142 // much more complicated.
2143 if (isa<llvm::ConstantPointerNull>(value) &&
2144 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2145 Builder.CreateStore(value, addr);
2146 return;
2147 }
2148
2149 emitARCStoreOperation(*this, addr, value,
2150 CGM.getARCEntrypoints().objc_initWeak,
2151 "objc_initWeak", /*ignored*/ true);
2152 }
2153
2154 /// void \@objc_destroyWeak(i8** %addr)
2155 /// Essentially objc_storeWeak(addr, nil).
EmitARCDestroyWeak(llvm::Value * addr)2156 void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2157 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2158 if (!fn) {
2159 llvm::FunctionType *fnType =
2160 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
2161 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2162 }
2163
2164 // Cast the argument to 'id*'.
2165 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2166
2167 EmitNounwindRuntimeCall(fn, addr);
2168 }
2169
2170 /// void \@objc_moveWeak(i8** %dest, i8** %src)
2171 /// Disregards the current value in %dest. Leaves %src pointing to nothing.
2172 /// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
EmitARCMoveWeak(llvm::Value * dst,llvm::Value * src)2173 void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2174 emitARCCopyOperation(*this, dst, src,
2175 CGM.getARCEntrypoints().objc_moveWeak,
2176 "objc_moveWeak");
2177 }
2178
2179 /// void \@objc_copyWeak(i8** %dest, i8** %src)
2180 /// Disregards the current value in %dest. Essentially
2181 /// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
EmitARCCopyWeak(llvm::Value * dst,llvm::Value * src)2182 void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2183 emitARCCopyOperation(*this, dst, src,
2184 CGM.getARCEntrypoints().objc_copyWeak,
2185 "objc_copyWeak");
2186 }
2187
2188 /// Produce the code to do a objc_autoreleasepool_push.
2189 /// call i8* \@objc_autoreleasePoolPush(void)
EmitObjCAutoreleasePoolPush()2190 llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2191 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2192 if (!fn) {
2193 llvm::FunctionType *fnType =
2194 llvm::FunctionType::get(Int8PtrTy, false);
2195 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2196 }
2197
2198 return EmitNounwindRuntimeCall(fn);
2199 }
2200
2201 /// Produce the code to do a primitive release.
2202 /// call void \@objc_autoreleasePoolPop(i8* %ptr)
EmitObjCAutoreleasePoolPop(llvm::Value * value)2203 void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2204 assert(value->getType() == Int8PtrTy);
2205
2206 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2207 if (!fn) {
2208 llvm::FunctionType *fnType =
2209 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
2210
2211 // We don't want to use a weak import here; instead we should not
2212 // fall into this path.
2213 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2214 }
2215
2216 EmitNounwindRuntimeCall(fn, value);
2217 }
2218
2219 /// Produce the code to do an MRR version objc_autoreleasepool_push.
2220 /// Which is: [[NSAutoreleasePool alloc] init];
2221 /// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2222 /// init is declared as: - (id) init; in its NSObject super class.
2223 ///
EmitObjCMRRAutoreleasePoolPush()2224 llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2225 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2226 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
2227 // [NSAutoreleasePool alloc]
2228 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2229 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2230 CallArgList Args;
2231 RValue AllocRV =
2232 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2233 getContext().getObjCIdType(),
2234 AllocSel, Receiver, Args);
2235
2236 // [Receiver init]
2237 Receiver = AllocRV.getScalarVal();
2238 II = &CGM.getContext().Idents.get("init");
2239 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2240 RValue InitRV =
2241 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2242 getContext().getObjCIdType(),
2243 InitSel, Receiver, Args);
2244 return InitRV.getScalarVal();
2245 }
2246
2247 /// Produce the code to do a primitive release.
2248 /// [tmp drain];
EmitObjCMRRAutoreleasePoolPop(llvm::Value * Arg)2249 void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2250 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2251 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2252 CallArgList Args;
2253 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2254 getContext().VoidTy, DrainSel, Arg, Args);
2255 }
2256
destroyARCStrongPrecise(CodeGenFunction & CGF,llvm::Value * addr,QualType type)2257 void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2258 llvm::Value *addr,
2259 QualType type) {
2260 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
2261 }
2262
destroyARCStrongImprecise(CodeGenFunction & CGF,llvm::Value * addr,QualType type)2263 void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2264 llvm::Value *addr,
2265 QualType type) {
2266 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
2267 }
2268
destroyARCWeak(CodeGenFunction & CGF,llvm::Value * addr,QualType type)2269 void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2270 llvm::Value *addr,
2271 QualType type) {
2272 CGF.EmitARCDestroyWeak(addr);
2273 }
2274
2275 namespace {
2276 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2277 llvm::Value *Token;
2278
CallObjCAutoreleasePoolObject__anon87cd100e0511::CallObjCAutoreleasePoolObject2279 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2280
Emit__anon87cd100e0511::CallObjCAutoreleasePoolObject2281 void Emit(CodeGenFunction &CGF, Flags flags) {
2282 CGF.EmitObjCAutoreleasePoolPop(Token);
2283 }
2284 };
2285 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2286 llvm::Value *Token;
2287
CallObjCMRRAutoreleasePoolObject__anon87cd100e0511::CallObjCMRRAutoreleasePoolObject2288 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2289
Emit__anon87cd100e0511::CallObjCMRRAutoreleasePoolObject2290 void Emit(CodeGenFunction &CGF, Flags flags) {
2291 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2292 }
2293 };
2294 }
2295
EmitObjCAutoreleasePoolCleanup(llvm::Value * Ptr)2296 void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
2297 if (CGM.getLangOpts().ObjCAutoRefCount)
2298 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2299 else
2300 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2301 }
2302
tryEmitARCRetainLoadOfScalar(CodeGenFunction & CGF,LValue lvalue,QualType type)2303 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2304 LValue lvalue,
2305 QualType type) {
2306 switch (type.getObjCLifetime()) {
2307 case Qualifiers::OCL_None:
2308 case Qualifiers::OCL_ExplicitNone:
2309 case Qualifiers::OCL_Strong:
2310 case Qualifiers::OCL_Autoreleasing:
2311 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
2312 false);
2313
2314 case Qualifiers::OCL_Weak:
2315 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2316 true);
2317 }
2318
2319 llvm_unreachable("impossible lifetime!");
2320 }
2321
tryEmitARCRetainLoadOfScalar(CodeGenFunction & CGF,const Expr * e)2322 static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2323 const Expr *e) {
2324 e = e->IgnoreParens();
2325 QualType type = e->getType();
2326
2327 // If we're loading retained from a __strong xvalue, we can avoid
2328 // an extra retain/release pair by zeroing out the source of this
2329 // "move" operation.
2330 if (e->isXValue() &&
2331 !type.isConstQualified() &&
2332 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2333 // Emit the lvalue.
2334 LValue lv = CGF.EmitLValue(e);
2335
2336 // Load the object pointer.
2337 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2338
2339 // Set the source pointer to NULL.
2340 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2341
2342 return TryEmitResult(result, true);
2343 }
2344
2345 // As a very special optimization, in ARC++, if the l-value is the
2346 // result of a non-volatile assignment, do a simple retain of the
2347 // result of the call to objc_storeWeak instead of reloading.
2348 if (CGF.getLangOpts().CPlusPlus &&
2349 !type.isVolatileQualified() &&
2350 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2351 isa<BinaryOperator>(e) &&
2352 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2353 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2354
2355 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2356 }
2357
2358 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2359 llvm::Value *value);
2360
2361 /// Given that the given expression is some sort of call (which does
2362 /// not return retained), emit a retain following it.
emitARCRetainCall(CodeGenFunction & CGF,const Expr * e)2363 static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2364 llvm::Value *value = CGF.EmitScalarExpr(e);
2365 return emitARCRetainAfterCall(CGF, value);
2366 }
2367
emitARCRetainAfterCall(CodeGenFunction & CGF,llvm::Value * value)2368 static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2369 llvm::Value *value) {
2370 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2371 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2372
2373 // Place the retain immediately following the call.
2374 CGF.Builder.SetInsertPoint(call->getParent(),
2375 ++llvm::BasicBlock::iterator(call));
2376 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2377
2378 CGF.Builder.restoreIP(ip);
2379 return value;
2380 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2381 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2382
2383 // Place the retain at the beginning of the normal destination block.
2384 llvm::BasicBlock *BB = invoke->getNormalDest();
2385 CGF.Builder.SetInsertPoint(BB, BB->begin());
2386 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2387
2388 CGF.Builder.restoreIP(ip);
2389 return value;
2390
2391 // Bitcasts can arise because of related-result returns. Rewrite
2392 // the operand.
2393 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2394 llvm::Value *operand = bitcast->getOperand(0);
2395 operand = emitARCRetainAfterCall(CGF, operand);
2396 bitcast->setOperand(0, operand);
2397 return bitcast;
2398
2399 // Generic fall-back case.
2400 } else {
2401 // Retain using the non-block variant: we never need to do a copy
2402 // of a block that's been returned to us.
2403 return CGF.EmitARCRetainNonBlock(value);
2404 }
2405 }
2406
2407 /// Determine whether it might be important to emit a separate
2408 /// objc_retain_block on the result of the given expression, or
2409 /// whether it's okay to just emit it in a +1 context.
shouldEmitSeparateBlockRetain(const Expr * e)2410 static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2411 assert(e->getType()->isBlockPointerType());
2412 e = e->IgnoreParens();
2413
2414 // For future goodness, emit block expressions directly in +1
2415 // contexts if we can.
2416 if (isa<BlockExpr>(e))
2417 return false;
2418
2419 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2420 switch (cast->getCastKind()) {
2421 // Emitting these operations in +1 contexts is goodness.
2422 case CK_LValueToRValue:
2423 case CK_ARCReclaimReturnedObject:
2424 case CK_ARCConsumeObject:
2425 case CK_ARCProduceObject:
2426 return false;
2427
2428 // These operations preserve a block type.
2429 case CK_NoOp:
2430 case CK_BitCast:
2431 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2432
2433 // These operations are known to be bad (or haven't been considered).
2434 case CK_AnyPointerToBlockPointerCast:
2435 default:
2436 return true;
2437 }
2438 }
2439
2440 return true;
2441 }
2442
2443 /// Try to emit a PseudoObjectExpr at +1.
2444 ///
2445 /// This massively duplicates emitPseudoObjectRValue.
tryEmitARCRetainPseudoObject(CodeGenFunction & CGF,const PseudoObjectExpr * E)2446 static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2447 const PseudoObjectExpr *E) {
2448 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2449
2450 // Find the result expression.
2451 const Expr *resultExpr = E->getResultExpr();
2452 assert(resultExpr);
2453 TryEmitResult result;
2454
2455 for (PseudoObjectExpr::const_semantics_iterator
2456 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2457 const Expr *semantic = *i;
2458
2459 // If this semantic expression is an opaque value, bind it
2460 // to the result of its source expression.
2461 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2462 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2463 OVMA opaqueData;
2464
2465 // If this semantic is the result of the pseudo-object
2466 // expression, try to evaluate the source as +1.
2467 if (ov == resultExpr) {
2468 assert(!OVMA::shouldBindAsLValue(ov));
2469 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2470 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2471
2472 // Otherwise, just bind it.
2473 } else {
2474 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2475 }
2476 opaques.push_back(opaqueData);
2477
2478 // Otherwise, if the expression is the result, evaluate it
2479 // and remember the result.
2480 } else if (semantic == resultExpr) {
2481 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2482
2483 // Otherwise, evaluate the expression in an ignored context.
2484 } else {
2485 CGF.EmitIgnoredExpr(semantic);
2486 }
2487 }
2488
2489 // Unbind all the opaques now.
2490 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2491 opaques[i].unbind(CGF);
2492
2493 return result;
2494 }
2495
2496 static TryEmitResult
tryEmitARCRetainScalarExpr(CodeGenFunction & CGF,const Expr * e)2497 tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
2498 // We should *never* see a nested full-expression here, because if
2499 // we fail to emit at +1, our caller must not retain after we close
2500 // out the full-expression.
2501 assert(!isa<ExprWithCleanups>(e));
2502
2503 // The desired result type, if it differs from the type of the
2504 // ultimate opaque expression.
2505 llvm::Type *resultType = 0;
2506
2507 while (true) {
2508 e = e->IgnoreParens();
2509
2510 // There's a break at the end of this if-chain; anything
2511 // that wants to keep looping has to explicitly continue.
2512 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2513 switch (ce->getCastKind()) {
2514 // No-op casts don't change the type, so we just ignore them.
2515 case CK_NoOp:
2516 e = ce->getSubExpr();
2517 continue;
2518
2519 case CK_LValueToRValue: {
2520 TryEmitResult loadResult
2521 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2522 if (resultType) {
2523 llvm::Value *value = loadResult.getPointer();
2524 value = CGF.Builder.CreateBitCast(value, resultType);
2525 loadResult.setPointer(value);
2526 }
2527 return loadResult;
2528 }
2529
2530 // These casts can change the type, so remember that and
2531 // soldier on. We only need to remember the outermost such
2532 // cast, though.
2533 case CK_CPointerToObjCPointerCast:
2534 case CK_BlockPointerToObjCPointerCast:
2535 case CK_AnyPointerToBlockPointerCast:
2536 case CK_BitCast:
2537 if (!resultType)
2538 resultType = CGF.ConvertType(ce->getType());
2539 e = ce->getSubExpr();
2540 assert(e->getType()->hasPointerRepresentation());
2541 continue;
2542
2543 // For consumptions, just emit the subexpression and thus elide
2544 // the retain/release pair.
2545 case CK_ARCConsumeObject: {
2546 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2547 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2548 return TryEmitResult(result, true);
2549 }
2550
2551 // Block extends are net +0. Naively, we could just recurse on
2552 // the subexpression, but actually we need to ensure that the
2553 // value is copied as a block, so there's a little filter here.
2554 case CK_ARCExtendBlockObject: {
2555 llvm::Value *result; // will be a +0 value
2556
2557 // If we can't safely assume the sub-expression will produce a
2558 // block-copied value, emit the sub-expression at +0.
2559 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2560 result = CGF.EmitScalarExpr(ce->getSubExpr());
2561
2562 // Otherwise, try to emit the sub-expression at +1 recursively.
2563 } else {
2564 TryEmitResult subresult
2565 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2566 result = subresult.getPointer();
2567
2568 // If that produced a retained value, just use that,
2569 // possibly casting down.
2570 if (subresult.getInt()) {
2571 if (resultType)
2572 result = CGF.Builder.CreateBitCast(result, resultType);
2573 return TryEmitResult(result, true);
2574 }
2575
2576 // Otherwise it's +0.
2577 }
2578
2579 // Retain the object as a block, then cast down.
2580 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
2581 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2582 return TryEmitResult(result, true);
2583 }
2584
2585 // For reclaims, emit the subexpression as a retained call and
2586 // skip the consumption.
2587 case CK_ARCReclaimReturnedObject: {
2588 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2589 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2590 return TryEmitResult(result, true);
2591 }
2592
2593 default:
2594 break;
2595 }
2596
2597 // Skip __extension__.
2598 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2599 if (op->getOpcode() == UO_Extension) {
2600 e = op->getSubExpr();
2601 continue;
2602 }
2603
2604 // For calls and message sends, use the retained-call logic.
2605 // Delegate inits are a special case in that they're the only
2606 // returns-retained expression that *isn't* surrounded by
2607 // a consume.
2608 } else if (isa<CallExpr>(e) ||
2609 (isa<ObjCMessageExpr>(e) &&
2610 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2611 llvm::Value *result = emitARCRetainCall(CGF, e);
2612 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2613 return TryEmitResult(result, true);
2614
2615 // Look through pseudo-object expressions.
2616 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2617 TryEmitResult result
2618 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2619 if (resultType) {
2620 llvm::Value *value = result.getPointer();
2621 value = CGF.Builder.CreateBitCast(value, resultType);
2622 result.setPointer(value);
2623 }
2624 return result;
2625 }
2626
2627 // Conservatively halt the search at any other expression kind.
2628 break;
2629 }
2630
2631 // We didn't find an obvious production, so emit what we've got and
2632 // tell the caller that we didn't manage to retain.
2633 llvm::Value *result = CGF.EmitScalarExpr(e);
2634 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2635 return TryEmitResult(result, false);
2636 }
2637
emitARCRetainLoadOfScalar(CodeGenFunction & CGF,LValue lvalue,QualType type)2638 static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2639 LValue lvalue,
2640 QualType type) {
2641 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2642 llvm::Value *value = result.getPointer();
2643 if (!result.getInt())
2644 value = CGF.EmitARCRetain(type, value);
2645 return value;
2646 }
2647
2648 /// EmitARCRetainScalarExpr - Semantically equivalent to
2649 /// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2650 /// best-effort attempt to peephole expressions that naturally produce
2651 /// retained objects.
EmitARCRetainScalarExpr(const Expr * e)2652 llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2653 // The retain needs to happen within the full-expression.
2654 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2655 enterFullExpression(cleanups);
2656 RunCleanupsScope scope(*this);
2657 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2658 }
2659
2660 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2661 llvm::Value *value = result.getPointer();
2662 if (!result.getInt())
2663 value = EmitARCRetain(e->getType(), value);
2664 return value;
2665 }
2666
2667 llvm::Value *
EmitARCRetainAutoreleaseScalarExpr(const Expr * e)2668 CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2669 // The retain needs to happen within the full-expression.
2670 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2671 enterFullExpression(cleanups);
2672 RunCleanupsScope scope(*this);
2673 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2674 }
2675
2676 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2677 llvm::Value *value = result.getPointer();
2678 if (result.getInt())
2679 value = EmitARCAutorelease(value);
2680 else
2681 value = EmitARCRetainAutorelease(e->getType(), value);
2682 return value;
2683 }
2684
EmitARCExtendBlockObject(const Expr * e)2685 llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2686 llvm::Value *result;
2687 bool doRetain;
2688
2689 if (shouldEmitSeparateBlockRetain(e)) {
2690 result = EmitScalarExpr(e);
2691 doRetain = true;
2692 } else {
2693 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2694 result = subresult.getPointer();
2695 doRetain = !subresult.getInt();
2696 }
2697
2698 if (doRetain)
2699 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2700 return EmitObjCConsumeObject(e->getType(), result);
2701 }
2702
EmitObjCThrowOperand(const Expr * expr)2703 llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2704 // In ARC, retain and autorelease the expression.
2705 if (getLangOpts().ObjCAutoRefCount) {
2706 // Do so before running any cleanups for the full-expression.
2707 // EmitARCRetainAutoreleaseScalarExpr does this for us.
2708 return EmitARCRetainAutoreleaseScalarExpr(expr);
2709 }
2710
2711 // Otherwise, use the normal scalar-expression emission. The
2712 // exception machinery doesn't do anything special with the
2713 // exception like retaining it, so there's no safety associated with
2714 // only running cleanups after the throw has started, and when it
2715 // matters it tends to be substantially inferior code.
2716 return EmitScalarExpr(expr);
2717 }
2718
2719 std::pair<LValue,llvm::Value*>
EmitARCStoreStrong(const BinaryOperator * e,bool ignored)2720 CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2721 bool ignored) {
2722 // Evaluate the RHS first.
2723 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2724 llvm::Value *value = result.getPointer();
2725
2726 bool hasImmediateRetain = result.getInt();
2727
2728 // If we didn't emit a retained object, and the l-value is of block
2729 // type, then we need to emit the block-retain immediately in case
2730 // it invalidates the l-value.
2731 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
2732 value = EmitARCRetainBlock(value, /*mandatory*/ false);
2733 hasImmediateRetain = true;
2734 }
2735
2736 LValue lvalue = EmitLValue(e->getLHS());
2737
2738 // If the RHS was emitted retained, expand this.
2739 if (hasImmediateRetain) {
2740 llvm::Value *oldValue =
2741 EmitLoadOfScalar(lvalue);
2742 EmitStoreOfScalar(value, lvalue);
2743 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
2744 } else {
2745 value = EmitARCStoreStrong(lvalue, value, ignored);
2746 }
2747
2748 return std::pair<LValue,llvm::Value*>(lvalue, value);
2749 }
2750
2751 std::pair<LValue,llvm::Value*>
EmitARCStoreAutoreleasing(const BinaryOperator * e)2752 CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2753 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2754 LValue lvalue = EmitLValue(e->getLHS());
2755
2756 EmitStoreOfScalar(value, lvalue);
2757
2758 return std::pair<LValue,llvm::Value*>(lvalue, value);
2759 }
2760
EmitObjCAutoreleasePoolStmt(const ObjCAutoreleasePoolStmt & ARPS)2761 void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
2762 const ObjCAutoreleasePoolStmt &ARPS) {
2763 const Stmt *subStmt = ARPS.getSubStmt();
2764 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2765
2766 CGDebugInfo *DI = getDebugInfo();
2767 if (DI)
2768 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
2769
2770 // Keep track of the current cleanup stack depth.
2771 RunCleanupsScope Scope(*this);
2772 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
2773 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2774 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2775 } else {
2776 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2777 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2778 }
2779
2780 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2781 E = S.body_end(); I != E; ++I)
2782 EmitStmt(*I);
2783
2784 if (DI)
2785 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
2786 }
2787
2788 /// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2789 /// make sure it survives garbage collection until this point.
EmitExtendGCLifetime(llvm::Value * object)2790 void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2791 // We just use an inline assembly.
2792 llvm::FunctionType *extenderType
2793 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
2794 llvm::Value *extender
2795 = llvm::InlineAsm::get(extenderType,
2796 /* assembly */ "",
2797 /* constraints */ "r",
2798 /* side effects */ true);
2799
2800 object = Builder.CreateBitCast(object, VoidPtrTy);
2801 EmitNounwindRuntimeCall(extender, object);
2802 }
2803
2804 /// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
2805 /// non-trivial copy assignment function, produce following helper function.
2806 /// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2807 ///
2808 llvm::Constant *
GenerateObjCAtomicSetterCopyHelperFunction(const ObjCPropertyImplDecl * PID)2809 CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2810 const ObjCPropertyImplDecl *PID) {
2811 if (!getLangOpts().CPlusPlus ||
2812 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
2813 return 0;
2814 QualType Ty = PID->getPropertyIvarDecl()->getType();
2815 if (!Ty->isRecordType())
2816 return 0;
2817 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2818 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2819 return 0;
2820 llvm::Constant * HelperFn = 0;
2821 if (hasTrivialSetExpr(PID))
2822 return 0;
2823 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2824 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2825 return HelperFn;
2826
2827 ASTContext &C = getContext();
2828 IdentifierInfo *II
2829 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
2830 FunctionDecl *FD = FunctionDecl::Create(C,
2831 C.getTranslationUnitDecl(),
2832 SourceLocation(),
2833 SourceLocation(), II, C.VoidTy, 0,
2834 SC_Static,
2835 SC_None,
2836 false,
2837 false);
2838
2839 QualType DestTy = C.getPointerType(Ty);
2840 QualType SrcTy = Ty;
2841 SrcTy.addConst();
2842 SrcTy = C.getPointerType(SrcTy);
2843
2844 FunctionArgList args;
2845 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2846 args.push_back(&dstDecl);
2847 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2848 args.push_back(&srcDecl);
2849
2850 const CGFunctionInfo &FI =
2851 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2852 FunctionType::ExtInfo(),
2853 RequiredArgs::All);
2854
2855 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2856
2857 llvm::Function *Fn =
2858 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2859 "__assign_helper_atomic_property_",
2860 &CGM.getModule());
2861
2862 // Initialize debug info if needed.
2863 maybeInitializeDebugInfo();
2864
2865 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2866
2867 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2868 VK_RValue, SourceLocation());
2869 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2870 VK_LValue, OK_Ordinary, SourceLocation());
2871
2872 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2873 VK_RValue, SourceLocation());
2874 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2875 VK_LValue, OK_Ordinary, SourceLocation());
2876
2877 Expr *Args[2] = { &DST, &SRC };
2878 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
2879 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
2880 Args, DestTy->getPointeeType(),
2881 VK_LValue, SourceLocation(), false);
2882
2883 EmitStmt(&TheCall);
2884
2885 FinishFunction();
2886 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2887 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
2888 return HelperFn;
2889 }
2890
2891 llvm::Constant *
GenerateObjCAtomicGetterCopyHelperFunction(const ObjCPropertyImplDecl * PID)2892 CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2893 const ObjCPropertyImplDecl *PID) {
2894 if (!getLangOpts().CPlusPlus ||
2895 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
2896 return 0;
2897 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2898 QualType Ty = PD->getType();
2899 if (!Ty->isRecordType())
2900 return 0;
2901 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2902 return 0;
2903 llvm::Constant * HelperFn = 0;
2904
2905 if (hasTrivialGetExpr(PID))
2906 return 0;
2907 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2908 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2909 return HelperFn;
2910
2911
2912 ASTContext &C = getContext();
2913 IdentifierInfo *II
2914 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2915 FunctionDecl *FD = FunctionDecl::Create(C,
2916 C.getTranslationUnitDecl(),
2917 SourceLocation(),
2918 SourceLocation(), II, C.VoidTy, 0,
2919 SC_Static,
2920 SC_None,
2921 false,
2922 false);
2923
2924 QualType DestTy = C.getPointerType(Ty);
2925 QualType SrcTy = Ty;
2926 SrcTy.addConst();
2927 SrcTy = C.getPointerType(SrcTy);
2928
2929 FunctionArgList args;
2930 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2931 args.push_back(&dstDecl);
2932 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2933 args.push_back(&srcDecl);
2934
2935 const CGFunctionInfo &FI =
2936 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2937 FunctionType::ExtInfo(),
2938 RequiredArgs::All);
2939
2940 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
2941
2942 llvm::Function *Fn =
2943 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2944 "__copy_helper_atomic_property_", &CGM.getModule());
2945
2946 // Initialize debug info if needed.
2947 maybeInitializeDebugInfo();
2948
2949 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2950
2951 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2952 VK_RValue, SourceLocation());
2953
2954 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2955 VK_LValue, OK_Ordinary, SourceLocation());
2956
2957 CXXConstructExpr *CXXConstExpr =
2958 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2959
2960 SmallVector<Expr*, 4> ConstructorArgs;
2961 ConstructorArgs.push_back(&SRC);
2962 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2963 ++A;
2964
2965 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2966 A != AEnd; ++A)
2967 ConstructorArgs.push_back(*A);
2968
2969 CXXConstructExpr *TheCXXConstructExpr =
2970 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2971 CXXConstExpr->getConstructor(),
2972 CXXConstExpr->isElidable(),
2973 ConstructorArgs,
2974 CXXConstExpr->hadMultipleCandidates(),
2975 CXXConstExpr->isListInitialization(),
2976 CXXConstExpr->requiresZeroInitialization(),
2977 CXXConstExpr->getConstructionKind(),
2978 SourceRange());
2979
2980 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2981 VK_RValue, SourceLocation());
2982
2983 RValue DV = EmitAnyExpr(&DstExpr);
2984 CharUnits Alignment
2985 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
2986 EmitAggExpr(TheCXXConstructExpr,
2987 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2988 AggValueSlot::IsDestructed,
2989 AggValueSlot::DoesNotNeedGCBarriers,
2990 AggValueSlot::IsNotAliased));
2991
2992 FinishFunction();
2993 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2994 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2995 return HelperFn;
2996 }
2997
2998 llvm::Value *
EmitBlockCopyAndAutorelease(llvm::Value * Block,QualType Ty)2999 CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3000 // Get selectors for retain/autorelease.
3001 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3002 Selector CopySelector =
3003 getContext().Selectors.getNullarySelector(CopyID);
3004 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3005 Selector AutoreleaseSelector =
3006 getContext().Selectors.getNullarySelector(AutoreleaseID);
3007
3008 // Emit calls to retain/autorelease.
3009 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3010 llvm::Value *Val = Block;
3011 RValue Result;
3012 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3013 Ty, CopySelector,
3014 Val, CallArgList(), 0, 0);
3015 Val = Result.getScalarVal();
3016 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3017 Ty, AutoreleaseSelector,
3018 Val, CallArgList(), 0, 0);
3019 Val = Result.getScalarVal();
3020 return Val;
3021 }
3022
3023
~CGObjCRuntime()3024 CGObjCRuntime::~CGObjCRuntime() {}
3025