1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
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 Decl nodes as LLVM code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenFunction.h"
15 #include "CGDebugInfo.h"
16 #include "CGOpenCLRuntime.h"
17 #include "CodeGenModule.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/IR/DataLayout.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Intrinsics.h"
28 #include "llvm/IR/Type.h"
29 using namespace clang;
30 using namespace CodeGen;
31 
32 
33 void CodeGenFunction::EmitDecl(const Decl &D) {
34   switch (D.getKind()) {
35   case Decl::TranslationUnit:
36   case Decl::Namespace:
37   case Decl::UnresolvedUsingTypename:
38   case Decl::ClassTemplateSpecialization:
39   case Decl::ClassTemplatePartialSpecialization:
40   case Decl::VarTemplateSpecialization:
41   case Decl::VarTemplatePartialSpecialization:
42   case Decl::TemplateTypeParm:
43   case Decl::UnresolvedUsingValue:
44   case Decl::NonTypeTemplateParm:
45   case Decl::CXXMethod:
46   case Decl::CXXConstructor:
47   case Decl::CXXDestructor:
48   case Decl::CXXConversion:
49   case Decl::Field:
50   case Decl::MSProperty:
51   case Decl::IndirectField:
52   case Decl::ObjCIvar:
53   case Decl::ObjCAtDefsField:
54   case Decl::ParmVar:
55   case Decl::ImplicitParam:
56   case Decl::ClassTemplate:
57   case Decl::VarTemplate:
58   case Decl::FunctionTemplate:
59   case Decl::TypeAliasTemplate:
60   case Decl::TemplateTemplateParm:
61   case Decl::ObjCMethod:
62   case Decl::ObjCCategory:
63   case Decl::ObjCProtocol:
64   case Decl::ObjCInterface:
65   case Decl::ObjCCategoryImpl:
66   case Decl::ObjCImplementation:
67   case Decl::ObjCProperty:
68   case Decl::ObjCCompatibleAlias:
69   case Decl::AccessSpec:
70   case Decl::LinkageSpec:
71   case Decl::ObjCPropertyImpl:
72   case Decl::FileScopeAsm:
73   case Decl::Friend:
74   case Decl::FriendTemplate:
75   case Decl::Block:
76   case Decl::Captured:
77   case Decl::ClassScopeFunctionSpecialization:
78   case Decl::UsingShadow:
79     llvm_unreachable("Declaration should not be in declstmts!");
80   case Decl::Function:  // void X();
81   case Decl::Record:    // struct/union/class X;
82   case Decl::Enum:      // enum X;
83   case Decl::EnumConstant: // enum ? { X = ? }
84   case Decl::CXXRecord: // struct/union/class X; [C++]
85   case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
86   case Decl::Label:        // __label__ x;
87   case Decl::Import:
88   case Decl::OMPThreadPrivate:
89   case Decl::Empty:
90     // None of these decls require codegen support.
91     return;
92 
93   case Decl::NamespaceAlias:
94     if (CGDebugInfo *DI = getDebugInfo())
95         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
96     return;
97   case Decl::Using:          // using X; [C++]
98     if (CGDebugInfo *DI = getDebugInfo())
99         DI->EmitUsingDecl(cast<UsingDecl>(D));
100     return;
101   case Decl::UsingDirective: // using namespace X; [C++]
102     if (CGDebugInfo *DI = getDebugInfo())
103       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
104     return;
105   case Decl::Var: {
106     const VarDecl &VD = cast<VarDecl>(D);
107     assert(VD.isLocalVarDecl() &&
108            "Should not see file-scope variables inside a function!");
109     return EmitVarDecl(VD);
110   }
111 
112   case Decl::Typedef:      // typedef int X;
113   case Decl::TypeAlias: {  // using X = int; [C++0x]
114     const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
115     QualType Ty = TD.getUnderlyingType();
116 
117     if (Ty->isVariablyModifiedType())
118       EmitVariablyModifiedType(Ty);
119   }
120   }
121 }
122 
123 /// EmitVarDecl - This method handles emission of any variable declaration
124 /// inside a function, including static vars etc.
125 void CodeGenFunction::EmitVarDecl(const VarDecl &D) {
126   if (D.isStaticLocal()) {
127     llvm::GlobalValue::LinkageTypes Linkage =
128       llvm::GlobalValue::InternalLinkage;
129 
130     // If the variable is externally visible, it must have weak linkage so it
131     // can be uniqued.
132     if (D.isExternallyVisible()) {
133       Linkage = llvm::GlobalValue::LinkOnceODRLinkage;
134 
135       // FIXME: We need to force the emission/use of a guard variable for
136       // some variables even if we can constant-evaluate them because
137       // we can't guarantee every translation unit will constant-evaluate them.
138     }
139 
140     return EmitStaticVarDecl(D, Linkage);
141   }
142 
143   if (D.hasExternalStorage())
144     // Don't emit it now, allow it to be emitted lazily on its first use.
145     return;
146 
147   if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
148     return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
149 
150   assert(D.hasLocalStorage());
151   return EmitAutoVarDecl(D);
152 }
153 
154 static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
155                                      const char *Separator) {
156   CodeGenModule &CGM = CGF.CGM;
157   if (CGF.getLangOpts().CPlusPlus) {
158     StringRef Name = CGM.getMangledName(&D);
159     return Name.str();
160   }
161 
162   std::string ContextName;
163   if (!CGF.CurFuncDecl) {
164     // Better be in a block declared in global scope.
165     const NamedDecl *ND = cast<NamedDecl>(&D);
166     const DeclContext *DC = ND->getDeclContext();
167     if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
168       MangleBuffer Name;
169       CGM.getBlockMangledName(GlobalDecl(), Name, BD);
170       ContextName = Name.getString();
171     }
172     else
173       llvm_unreachable("Unknown context for block static var decl");
174   } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
175     StringRef Name = CGM.getMangledName(FD);
176     ContextName = Name.str();
177   } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
178     ContextName = CGF.CurFn->getName();
179   else
180     llvm_unreachable("Unknown context for static var decl");
181 
182   return ContextName + Separator + D.getNameAsString();
183 }
184 
185 llvm::GlobalVariable *
186 CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
187                                      const char *Separator,
188                                      llvm::GlobalValue::LinkageTypes Linkage) {
189   QualType Ty = D.getType();
190   assert(Ty->isConstantSizeType() && "VLAs can't be static");
191 
192   // Use the label if the variable is renamed with the asm-label extension.
193   std::string Name;
194   if (D.hasAttr<AsmLabelAttr>())
195     Name = CGM.getMangledName(&D);
196   else
197     Name = GetStaticDeclName(*this, D, Separator);
198 
199   llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
200   unsigned AddrSpace =
201    CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
202   llvm::GlobalVariable *GV =
203     new llvm::GlobalVariable(CGM.getModule(), LTy,
204                              Ty.isConstant(getContext()), Linkage,
205                              CGM.EmitNullConstant(D.getType()), Name, 0,
206                              llvm::GlobalVariable::NotThreadLocal,
207                              AddrSpace);
208   GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
209   CGM.setGlobalVisibility(GV, &D);
210 
211   if (D.getTLSKind())
212     CGM.setTLSMode(GV, D);
213 
214   return GV;
215 }
216 
217 /// hasNontrivialDestruction - Determine whether a type's destruction is
218 /// non-trivial. If so, and the variable uses static initialization, we must
219 /// register its destructor to run on exit.
220 static bool hasNontrivialDestruction(QualType T) {
221   CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
222   return RD && !RD->hasTrivialDestructor();
223 }
224 
225 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
226 /// global variable that has already been created for it.  If the initializer
227 /// has a different type than GV does, this may free GV and return a different
228 /// one.  Otherwise it just returns GV.
229 llvm::GlobalVariable *
230 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
231                                                llvm::GlobalVariable *GV) {
232   llvm::Constant *Init = CGM.EmitConstantInit(D, this);
233 
234   // If constant emission failed, then this should be a C++ static
235   // initializer.
236   if (!Init) {
237     if (!getLangOpts().CPlusPlus)
238       CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
239     else if (Builder.GetInsertBlock()) {
240       // Since we have a static initializer, this global variable can't
241       // be constant.
242       GV->setConstant(false);
243 
244       EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
245     }
246     return GV;
247   }
248 
249   // The initializer may differ in type from the global. Rewrite
250   // the global to match the initializer.  (We have to do this
251   // because some types, like unions, can't be completely represented
252   // in the LLVM type system.)
253   if (GV->getType()->getElementType() != Init->getType()) {
254     llvm::GlobalVariable *OldGV = GV;
255 
256     GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
257                                   OldGV->isConstant(),
258                                   OldGV->getLinkage(), Init, "",
259                                   /*InsertBefore*/ OldGV,
260                                   OldGV->getThreadLocalMode(),
261                            CGM.getContext().getTargetAddressSpace(D.getType()));
262     GV->setVisibility(OldGV->getVisibility());
263 
264     // Steal the name of the old global
265     GV->takeName(OldGV);
266 
267     // Replace all uses of the old global with the new global
268     llvm::Constant *NewPtrForOldDecl =
269     llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
270     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
271 
272     // Erase the old global, since it is no longer used.
273     OldGV->eraseFromParent();
274   }
275 
276   GV->setConstant(CGM.isTypeConstant(D.getType(), true));
277   GV->setInitializer(Init);
278 
279   if (hasNontrivialDestruction(D.getType())) {
280     // We have a constant initializer, but a nontrivial destructor. We still
281     // need to perform a guarded "initialization" in order to register the
282     // destructor.
283     EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
284   }
285 
286   return GV;
287 }
288 
289 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
290                                       llvm::GlobalValue::LinkageTypes Linkage) {
291   llvm::Value *&DMEntry = LocalDeclMap[&D];
292   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
293 
294   // Check to see if we already have a global variable for this
295   // declaration.  This can happen when double-emitting function
296   // bodies, e.g. with complete and base constructors.
297   llvm::Constant *addr =
298     CGM.getStaticLocalDeclAddress(&D);
299 
300   llvm::GlobalVariable *var;
301   if (addr) {
302     var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
303   } else {
304     addr = var = CreateStaticVarDecl(D, ".", Linkage);
305   }
306 
307   // Store into LocalDeclMap before generating initializer to handle
308   // circular references.
309   DMEntry = addr;
310   CGM.setStaticLocalDeclAddress(&D, addr);
311 
312   // We can't have a VLA here, but we can have a pointer to a VLA,
313   // even though that doesn't really make any sense.
314   // Make sure to evaluate VLA bounds now so that we have them for later.
315   if (D.getType()->isVariablyModifiedType())
316     EmitVariablyModifiedType(D.getType());
317 
318   // Save the type in case adding the initializer forces a type change.
319   llvm::Type *expectedType = addr->getType();
320 
321   // If this value has an initializer, emit it.
322   if (D.getInit())
323     var = AddInitializerToStaticVarDecl(D, var);
324 
325   var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
326 
327   if (D.hasAttr<AnnotateAttr>())
328     CGM.AddGlobalAnnotations(&D, var);
329 
330   if (const SectionAttr *SA = D.getAttr<SectionAttr>())
331     var->setSection(SA->getName());
332 
333   if (D.hasAttr<UsedAttr>())
334     CGM.AddUsedGlobal(var);
335 
336   // We may have to cast the constant because of the initializer
337   // mismatch above.
338   //
339   // FIXME: It is really dangerous to store this in the map; if anyone
340   // RAUW's the GV uses of this constant will be invalid.
341   llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
342   DMEntry = castedAddr;
343   CGM.setStaticLocalDeclAddress(&D, castedAddr);
344 
345   // Emit global variable debug descriptor for static vars.
346   CGDebugInfo *DI = getDebugInfo();
347   if (DI &&
348       CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
349     DI->setLocation(D.getLocation());
350     DI->EmitGlobalVariable(var, &D);
351   }
352 }
353 
354 namespace {
355   struct DestroyObject : EHScopeStack::Cleanup {
356     DestroyObject(llvm::Value *addr, QualType type,
357                   CodeGenFunction::Destroyer *destroyer,
358                   bool useEHCleanupForArray)
359       : addr(addr), type(type), destroyer(destroyer),
360         useEHCleanupForArray(useEHCleanupForArray) {}
361 
362     llvm::Value *addr;
363     QualType type;
364     CodeGenFunction::Destroyer *destroyer;
365     bool useEHCleanupForArray;
366 
367     void Emit(CodeGenFunction &CGF, Flags flags) {
368       // Don't use an EH cleanup recursively from an EH cleanup.
369       bool useEHCleanupForArray =
370         flags.isForNormalCleanup() && this->useEHCleanupForArray;
371 
372       CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
373     }
374   };
375 
376   struct DestroyNRVOVariable : EHScopeStack::Cleanup {
377     DestroyNRVOVariable(llvm::Value *addr,
378                         const CXXDestructorDecl *Dtor,
379                         llvm::Value *NRVOFlag)
380       : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
381 
382     const CXXDestructorDecl *Dtor;
383     llvm::Value *NRVOFlag;
384     llvm::Value *Loc;
385 
386     void Emit(CodeGenFunction &CGF, Flags flags) {
387       // Along the exceptions path we always execute the dtor.
388       bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
389 
390       llvm::BasicBlock *SkipDtorBB = 0;
391       if (NRVO) {
392         // If we exited via NRVO, we skip the destructor call.
393         llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
394         SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
395         llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
396         CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
397         CGF.EmitBlock(RunDtorBB);
398       }
399 
400       CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
401                                 /*ForVirtualBase=*/false,
402                                 /*Delegating=*/false,
403                                 Loc);
404 
405       if (NRVO) CGF.EmitBlock(SkipDtorBB);
406     }
407   };
408 
409   struct CallStackRestore : EHScopeStack::Cleanup {
410     llvm::Value *Stack;
411     CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
412     void Emit(CodeGenFunction &CGF, Flags flags) {
413       llvm::Value *V = CGF.Builder.CreateLoad(Stack);
414       llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
415       CGF.Builder.CreateCall(F, V);
416     }
417   };
418 
419   struct ExtendGCLifetime : EHScopeStack::Cleanup {
420     const VarDecl &Var;
421     ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
422 
423     void Emit(CodeGenFunction &CGF, Flags flags) {
424       // Compute the address of the local variable, in case it's a
425       // byref or something.
426       DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
427                       Var.getType(), VK_LValue, SourceLocation());
428       llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE),
429                                                 SourceLocation());
430       CGF.EmitExtendGCLifetime(value);
431     }
432   };
433 
434   struct CallCleanupFunction : EHScopeStack::Cleanup {
435     llvm::Constant *CleanupFn;
436     const CGFunctionInfo &FnInfo;
437     const VarDecl &Var;
438 
439     CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
440                         const VarDecl *Var)
441       : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
442 
443     void Emit(CodeGenFunction &CGF, Flags flags) {
444       DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
445                       Var.getType(), VK_LValue, SourceLocation());
446       // Compute the address of the local variable, in case it's a byref
447       // or something.
448       llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
449 
450       // In some cases, the type of the function argument will be different from
451       // the type of the pointer. An example of this is
452       // void f(void* arg);
453       // __attribute__((cleanup(f))) void *g;
454       //
455       // To fix this we insert a bitcast here.
456       QualType ArgTy = FnInfo.arg_begin()->type;
457       llvm::Value *Arg =
458         CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
459 
460       CallArgList Args;
461       Args.add(RValue::get(Arg),
462                CGF.getContext().getPointerType(Var.getType()));
463       CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
464     }
465   };
466 
467   /// A cleanup to call @llvm.lifetime.end.
468   class CallLifetimeEnd : public EHScopeStack::Cleanup {
469     llvm::Value *Addr;
470     llvm::Value *Size;
471   public:
472     CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
473       : Addr(addr), Size(size) {}
474 
475     void Emit(CodeGenFunction &CGF, Flags flags) {
476       llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
477       CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
478                               Size, castAddr)
479         ->setDoesNotThrow();
480     }
481   };
482 }
483 
484 /// EmitAutoVarWithLifetime - Does the setup required for an automatic
485 /// variable with lifetime.
486 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
487                                     llvm::Value *addr,
488                                     Qualifiers::ObjCLifetime lifetime) {
489   switch (lifetime) {
490   case Qualifiers::OCL_None:
491     llvm_unreachable("present but none");
492 
493   case Qualifiers::OCL_ExplicitNone:
494     // nothing to do
495     break;
496 
497   case Qualifiers::OCL_Strong: {
498     CodeGenFunction::Destroyer *destroyer =
499       (var.hasAttr<ObjCPreciseLifetimeAttr>()
500        ? CodeGenFunction::destroyARCStrongPrecise
501        : CodeGenFunction::destroyARCStrongImprecise);
502 
503     CleanupKind cleanupKind = CGF.getARCCleanupKind();
504     CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
505                     cleanupKind & EHCleanup);
506     break;
507   }
508   case Qualifiers::OCL_Autoreleasing:
509     // nothing to do
510     break;
511 
512   case Qualifiers::OCL_Weak:
513     // __weak objects always get EH cleanups; otherwise, exceptions
514     // could cause really nasty crashes instead of mere leaks.
515     CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
516                     CodeGenFunction::destroyARCWeak,
517                     /*useEHCleanup*/ true);
518     break;
519   }
520 }
521 
522 static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
523   if (const Expr *e = dyn_cast<Expr>(s)) {
524     // Skip the most common kinds of expressions that make
525     // hierarchy-walking expensive.
526     s = e = e->IgnoreParenCasts();
527 
528     if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
529       return (ref->getDecl() == &var);
530     if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
531       const BlockDecl *block = be->getBlockDecl();
532       for (BlockDecl::capture_const_iterator i = block->capture_begin(),
533            e = block->capture_end(); i != e; ++i) {
534         if (i->getVariable() == &var)
535           return true;
536       }
537     }
538   }
539 
540   for (Stmt::const_child_range children = s->children(); children; ++children)
541     // children might be null; as in missing decl or conditional of an if-stmt.
542     if ((*children) && isAccessedBy(var, *children))
543       return true;
544 
545   return false;
546 }
547 
548 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
549   if (!decl) return false;
550   if (!isa<VarDecl>(decl)) return false;
551   const VarDecl *var = cast<VarDecl>(decl);
552   return isAccessedBy(*var, e);
553 }
554 
555 static void drillIntoBlockVariable(CodeGenFunction &CGF,
556                                    LValue &lvalue,
557                                    const VarDecl *var) {
558   lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
559 }
560 
561 void CodeGenFunction::EmitScalarInit(const Expr *init,
562                                      const ValueDecl *D,
563                                      LValue lvalue,
564                                      bool capturedByInit) {
565   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
566   if (!lifetime) {
567     llvm::Value *value = EmitScalarExpr(init);
568     if (capturedByInit)
569       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
570     EmitStoreThroughLValue(RValue::get(value), lvalue, true);
571     return;
572   }
573 
574   // If we're emitting a value with lifetime, we have to do the
575   // initialization *before* we leave the cleanup scopes.
576   if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
577     enterFullExpression(ewc);
578     init = ewc->getSubExpr();
579   }
580   CodeGenFunction::RunCleanupsScope Scope(*this);
581 
582   // We have to maintain the illusion that the variable is
583   // zero-initialized.  If the variable might be accessed in its
584   // initializer, zero-initialize before running the initializer, then
585   // actually perform the initialization with an assign.
586   bool accessedByInit = false;
587   if (lifetime != Qualifiers::OCL_ExplicitNone)
588     accessedByInit = (capturedByInit || isAccessedBy(D, init));
589   if (accessedByInit) {
590     LValue tempLV = lvalue;
591     // Drill down to the __block object if necessary.
592     if (capturedByInit) {
593       // We can use a simple GEP for this because it can't have been
594       // moved yet.
595       tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
596                                    getByRefValueLLVMField(cast<VarDecl>(D))));
597     }
598 
599     llvm::PointerType *ty
600       = cast<llvm::PointerType>(tempLV.getAddress()->getType());
601     ty = cast<llvm::PointerType>(ty->getElementType());
602 
603     llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
604 
605     // If __weak, we want to use a barrier under certain conditions.
606     if (lifetime == Qualifiers::OCL_Weak)
607       EmitARCInitWeak(tempLV.getAddress(), zero);
608 
609     // Otherwise just do a simple store.
610     else
611       EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
612   }
613 
614   // Emit the initializer.
615   llvm::Value *value = 0;
616 
617   switch (lifetime) {
618   case Qualifiers::OCL_None:
619     llvm_unreachable("present but none");
620 
621   case Qualifiers::OCL_ExplicitNone:
622     // nothing to do
623     value = EmitScalarExpr(init);
624     break;
625 
626   case Qualifiers::OCL_Strong: {
627     value = EmitARCRetainScalarExpr(init);
628     break;
629   }
630 
631   case Qualifiers::OCL_Weak: {
632     // No way to optimize a producing initializer into this.  It's not
633     // worth optimizing for, because the value will immediately
634     // disappear in the common case.
635     value = EmitScalarExpr(init);
636 
637     if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
638     if (accessedByInit)
639       EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
640     else
641       EmitARCInitWeak(lvalue.getAddress(), value);
642     return;
643   }
644 
645   case Qualifiers::OCL_Autoreleasing:
646     value = EmitARCRetainAutoreleaseScalarExpr(init);
647     break;
648   }
649 
650   if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
651 
652   // If the variable might have been accessed by its initializer, we
653   // might have to initialize with a barrier.  We have to do this for
654   // both __weak and __strong, but __weak got filtered out above.
655   if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
656     llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc());
657     EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
658     EmitARCRelease(oldValue, ARCImpreciseLifetime);
659     return;
660   }
661 
662   EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
663 }
664 
665 /// EmitScalarInit - Initialize the given lvalue with the given object.
666 void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
667   Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
668   if (!lifetime)
669     return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
670 
671   switch (lifetime) {
672   case Qualifiers::OCL_None:
673     llvm_unreachable("present but none");
674 
675   case Qualifiers::OCL_ExplicitNone:
676     // nothing to do
677     break;
678 
679   case Qualifiers::OCL_Strong:
680     init = EmitARCRetain(lvalue.getType(), init);
681     break;
682 
683   case Qualifiers::OCL_Weak:
684     // Initialize and then skip the primitive store.
685     EmitARCInitWeak(lvalue.getAddress(), init);
686     return;
687 
688   case Qualifiers::OCL_Autoreleasing:
689     init = EmitARCRetainAutorelease(lvalue.getType(), init);
690     break;
691   }
692 
693   EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
694 }
695 
696 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
697 /// non-zero parts of the specified initializer with equal or fewer than
698 /// NumStores scalar stores.
699 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
700                                                 unsigned &NumStores) {
701   // Zero and Undef never requires any extra stores.
702   if (isa<llvm::ConstantAggregateZero>(Init) ||
703       isa<llvm::ConstantPointerNull>(Init) ||
704       isa<llvm::UndefValue>(Init))
705     return true;
706   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
707       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
708       isa<llvm::ConstantExpr>(Init))
709     return Init->isNullValue() || NumStores--;
710 
711   // See if we can emit each element.
712   if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
713     for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
714       llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
715       if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
716         return false;
717     }
718     return true;
719   }
720 
721   if (llvm::ConstantDataSequential *CDS =
722         dyn_cast<llvm::ConstantDataSequential>(Init)) {
723     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
724       llvm::Constant *Elt = CDS->getElementAsConstant(i);
725       if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
726         return false;
727     }
728     return true;
729   }
730 
731   // Anything else is hard and scary.
732   return false;
733 }
734 
735 /// emitStoresForInitAfterMemset - For inits that
736 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
737 /// stores that would be required.
738 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
739                                          bool isVolatile, CGBuilderTy &Builder) {
740   assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
741          "called emitStoresForInitAfterMemset for zero or undef value.");
742 
743   if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
744       isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
745       isa<llvm::ConstantExpr>(Init)) {
746     Builder.CreateStore(Init, Loc, isVolatile);
747     return;
748   }
749 
750   if (llvm::ConstantDataSequential *CDS =
751         dyn_cast<llvm::ConstantDataSequential>(Init)) {
752     for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
753       llvm::Constant *Elt = CDS->getElementAsConstant(i);
754 
755       // If necessary, get a pointer to the element and emit it.
756       if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
757         emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
758                                      isVolatile, Builder);
759     }
760     return;
761   }
762 
763   assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
764          "Unknown value type!");
765 
766   for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
767     llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
768 
769     // If necessary, get a pointer to the element and emit it.
770     if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
771       emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
772                                    isVolatile, Builder);
773   }
774 }
775 
776 
777 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
778 /// plus some stores to initialize a local variable instead of using a memcpy
779 /// from a constant global.  It is beneficial to use memset if the global is all
780 /// zeros, or mostly zeros and large.
781 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
782                                                   uint64_t GlobalSize) {
783   // If a global is all zeros, always use a memset.
784   if (isa<llvm::ConstantAggregateZero>(Init)) return true;
785 
786   // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
787   // do it if it will require 6 or fewer scalar stores.
788   // TODO: Should budget depends on the size?  Avoiding a large global warrants
789   // plopping in more stores.
790   unsigned StoreBudget = 6;
791   uint64_t SizeLimit = 32;
792 
793   return GlobalSize > SizeLimit &&
794          canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
795 }
796 
797 /// Should we use the LLVM lifetime intrinsics for the given local variable?
798 static bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
799                                      unsigned Size) {
800   // Always emit lifetime markers in -fsanitize=use-after-scope mode.
801   if (CGF.getLangOpts().Sanitize.UseAfterScope)
802     return true;
803   // For now, only in optimized builds.
804   if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
805     return false;
806 
807   // Limit the size of marked objects to 32 bytes. We don't want to increase
808   // compile time by marking tiny objects.
809   unsigned SizeThreshold = 32;
810 
811   return Size > SizeThreshold;
812 }
813 
814 
815 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
816 /// variable declaration with auto, register, or no storage class specifier.
817 /// These turn into simple stack objects, or GlobalValues depending on target.
818 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
819   AutoVarEmission emission = EmitAutoVarAlloca(D);
820   EmitAutoVarInit(emission);
821   EmitAutoVarCleanups(emission);
822 }
823 
824 /// EmitAutoVarAlloca - Emit the alloca and debug information for a
825 /// local variable.  Does not emit initalization or destruction.
826 CodeGenFunction::AutoVarEmission
827 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
828   QualType Ty = D.getType();
829 
830   AutoVarEmission emission(D);
831 
832   bool isByRef = D.hasAttr<BlocksAttr>();
833   emission.IsByRef = isByRef;
834 
835   CharUnits alignment = getContext().getDeclAlign(&D);
836   emission.Alignment = alignment;
837 
838   // If the type is variably-modified, emit all the VLA sizes for it.
839   if (Ty->isVariablyModifiedType())
840     EmitVariablyModifiedType(Ty);
841 
842   llvm::Value *DeclPtr;
843   if (Ty->isConstantSizeType()) {
844     bool NRVO = getLangOpts().ElideConstructors &&
845       D.isNRVOVariable();
846 
847     // If this value is an array or struct with a statically determinable
848     // constant initializer, there are optimizations we can do.
849     //
850     // TODO: We should constant-evaluate the initializer of any variable,
851     // as long as it is initialized by a constant expression. Currently,
852     // isConstantInitializer produces wrong answers for structs with
853     // reference or bitfield members, and a few other cases, and checking
854     // for POD-ness protects us from some of these.
855     if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
856         (D.isConstexpr() ||
857          ((Ty.isPODType(getContext()) ||
858            getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
859           D.getInit()->isConstantInitializer(getContext(), false)))) {
860 
861       // If the variable's a const type, and it's neither an NRVO
862       // candidate nor a __block variable and has no mutable members,
863       // emit it as a global instead.
864       if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
865           CGM.isTypeConstant(Ty, true)) {
866         EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
867 
868         emission.Address = 0; // signal this condition to later callbacks
869         assert(emission.wasEmittedAsGlobal());
870         return emission;
871       }
872 
873       // Otherwise, tell the initialization code that we're in this case.
874       emission.IsConstantAggregate = true;
875     }
876 
877     // A normal fixed sized variable becomes an alloca in the entry block,
878     // unless it's an NRVO variable.
879     llvm::Type *LTy = ConvertTypeForMem(Ty);
880 
881     if (NRVO) {
882       // The named return value optimization: allocate this variable in the
883       // return slot, so that we can elide the copy when returning this
884       // variable (C++0x [class.copy]p34).
885       DeclPtr = ReturnValue;
886 
887       if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
888         if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
889           // Create a flag that is used to indicate when the NRVO was applied
890           // to this variable. Set it to zero to indicate that NRVO was not
891           // applied.
892           llvm::Value *Zero = Builder.getFalse();
893           llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
894           EnsureInsertPoint();
895           Builder.CreateStore(Zero, NRVOFlag);
896 
897           // Record the NRVO flag for this variable.
898           NRVOFlags[&D] = NRVOFlag;
899           emission.NRVOFlag = NRVOFlag;
900         }
901       }
902     } else {
903       if (isByRef)
904         LTy = BuildByRefType(&D);
905 
906       llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
907       Alloc->setName(D.getName());
908 
909       CharUnits allocaAlignment = alignment;
910       if (isByRef)
911         allocaAlignment = std::max(allocaAlignment,
912             getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
913       Alloc->setAlignment(allocaAlignment.getQuantity());
914       DeclPtr = Alloc;
915 
916       // Emit a lifetime intrinsic if meaningful.  There's no point
917       // in doing this if we don't have a valid insertion point (?).
918       uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
919       if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
920         llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
921 
922         emission.SizeForLifetimeMarkers = sizeV;
923         llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
924         Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
925           ->setDoesNotThrow();
926       } else {
927         assert(!emission.useLifetimeMarkers());
928       }
929     }
930   } else {
931     EnsureInsertPoint();
932 
933     if (!DidCallStackSave) {
934       // Save the stack.
935       llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
936 
937       llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
938       llvm::Value *V = Builder.CreateCall(F);
939 
940       Builder.CreateStore(V, Stack);
941 
942       DidCallStackSave = true;
943 
944       // Push a cleanup block and restore the stack there.
945       // FIXME: in general circumstances, this should be an EH cleanup.
946       EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
947     }
948 
949     llvm::Value *elementCount;
950     QualType elementType;
951     llvm::tie(elementCount, elementType) = getVLASize(Ty);
952 
953     llvm::Type *llvmTy = ConvertTypeForMem(elementType);
954 
955     // Allocate memory for the array.
956     llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
957     vla->setAlignment(alignment.getQuantity());
958 
959     DeclPtr = vla;
960   }
961 
962   llvm::Value *&DMEntry = LocalDeclMap[&D];
963   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
964   DMEntry = DeclPtr;
965   emission.Address = DeclPtr;
966 
967   // Emit debug info for local var declaration.
968   if (HaveInsertPoint())
969     if (CGDebugInfo *DI = getDebugInfo()) {
970       if (CGM.getCodeGenOpts().getDebugInfo()
971             >= CodeGenOptions::LimitedDebugInfo) {
972         DI->setLocation(D.getLocation());
973         DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
974       }
975     }
976 
977   if (D.hasAttr<AnnotateAttr>())
978       EmitVarAnnotations(&D, emission.Address);
979 
980   return emission;
981 }
982 
983 /// Determines whether the given __block variable is potentially
984 /// captured by the given expression.
985 static bool isCapturedBy(const VarDecl &var, const Expr *e) {
986   // Skip the most common kinds of expressions that make
987   // hierarchy-walking expensive.
988   e = e->IgnoreParenCasts();
989 
990   if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
991     const BlockDecl *block = be->getBlockDecl();
992     for (BlockDecl::capture_const_iterator i = block->capture_begin(),
993            e = block->capture_end(); i != e; ++i) {
994       if (i->getVariable() == &var)
995         return true;
996     }
997 
998     // No need to walk into the subexpressions.
999     return false;
1000   }
1001 
1002   if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
1003     const CompoundStmt *CS = SE->getSubStmt();
1004     for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1005 	   BE = CS->body_end(); BI != BE; ++BI)
1006       if (Expr *E = dyn_cast<Expr>((*BI))) {
1007         if (isCapturedBy(var, E))
1008             return true;
1009       }
1010       else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
1011           // special case declarations
1012           for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1013                I != E; ++I) {
1014               if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
1015                 Expr *Init = VD->getInit();
1016                 if (Init && isCapturedBy(var, Init))
1017                   return true;
1018               }
1019           }
1020       }
1021       else
1022         // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1023         // Later, provide code to poke into statements for capture analysis.
1024         return true;
1025     return false;
1026   }
1027 
1028   for (Stmt::const_child_range children = e->children(); children; ++children)
1029     if (isCapturedBy(var, cast<Expr>(*children)))
1030       return true;
1031 
1032   return false;
1033 }
1034 
1035 /// \brief Determine whether the given initializer is trivial in the sense
1036 /// that it requires no code to be generated.
1037 static bool isTrivialInitializer(const Expr *Init) {
1038   if (!Init)
1039     return true;
1040 
1041   if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1042     if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1043       if (Constructor->isTrivial() &&
1044           Constructor->isDefaultConstructor() &&
1045           !Construct->requiresZeroInitialization())
1046         return true;
1047 
1048   return false;
1049 }
1050 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
1051   assert(emission.Variable && "emission was not valid!");
1052 
1053   // If this was emitted as a global constant, we're done.
1054   if (emission.wasEmittedAsGlobal()) return;
1055 
1056   const VarDecl &D = *emission.Variable;
1057   QualType type = D.getType();
1058 
1059   // If this local has an initializer, emit it now.
1060   const Expr *Init = D.getInit();
1061 
1062   // If we are at an unreachable point, we don't need to emit the initializer
1063   // unless it contains a label.
1064   if (!HaveInsertPoint()) {
1065     if (!Init || !ContainsLabel(Init)) return;
1066     EnsureInsertPoint();
1067   }
1068 
1069   // Initialize the structure of a __block variable.
1070   if (emission.IsByRef)
1071     emitByrefStructureInit(emission);
1072 
1073   if (isTrivialInitializer(Init))
1074     return;
1075 
1076   CharUnits alignment = emission.Alignment;
1077 
1078   // Check whether this is a byref variable that's potentially
1079   // captured and moved by its own initializer.  If so, we'll need to
1080   // emit the initializer first, then copy into the variable.
1081   bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
1082 
1083   llvm::Value *Loc =
1084     capturedByInit ? emission.Address : emission.getObjectAddress(*this);
1085 
1086   llvm::Constant *constant = 0;
1087   if (emission.IsConstantAggregate || D.isConstexpr()) {
1088     assert(!capturedByInit && "constant init contains a capturing block?");
1089     constant = CGM.EmitConstantInit(D, this);
1090   }
1091 
1092   if (!constant) {
1093     LValue lv = MakeAddrLValue(Loc, type, alignment);
1094     lv.setNonGC(true);
1095     return EmitExprAsInit(Init, &D, lv, capturedByInit);
1096   }
1097 
1098   if (!emission.IsConstantAggregate) {
1099     // For simple scalar/complex initialization, store the value directly.
1100     LValue lv = MakeAddrLValue(Loc, type, alignment);
1101     lv.setNonGC(true);
1102     return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1103   }
1104 
1105   // If this is a simple aggregate initialization, we can optimize it
1106   // in various ways.
1107   bool isVolatile = type.isVolatileQualified();
1108 
1109   llvm::Value *SizeVal =
1110     llvm::ConstantInt::get(IntPtrTy,
1111                            getContext().getTypeSizeInChars(type).getQuantity());
1112 
1113   llvm::Type *BP = Int8PtrTy;
1114   if (Loc->getType() != BP)
1115     Loc = Builder.CreateBitCast(Loc, BP);
1116 
1117   // If the initializer is all or mostly zeros, codegen with memset then do
1118   // a few stores afterward.
1119   if (shouldUseMemSetPlusStoresToInitialize(constant,
1120                 CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
1121     Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
1122                          alignment.getQuantity(), isVolatile);
1123     // Zero and undef don't require a stores.
1124     if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
1125       Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
1126       emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
1127     }
1128   } else {
1129     // Otherwise, create a temporary global with the initializer then
1130     // memcpy from the global to the alloca.
1131     std::string Name = GetStaticDeclName(*this, D, ".");
1132     llvm::GlobalVariable *GV =
1133       new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1134                                llvm::GlobalValue::PrivateLinkage,
1135                                constant, Name);
1136     GV->setAlignment(alignment.getQuantity());
1137     GV->setUnnamedAddr(true);
1138 
1139     llvm::Value *SrcPtr = GV;
1140     if (SrcPtr->getType() != BP)
1141       SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
1142 
1143     Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
1144                          isVolatile);
1145   }
1146 }
1147 
1148 /// Emit an expression as an initializer for a variable at the given
1149 /// location.  The expression is not necessarily the normal
1150 /// initializer for the variable, and the address is not necessarily
1151 /// its normal location.
1152 ///
1153 /// \param init the initializing expression
1154 /// \param var the variable to act as if we're initializing
1155 /// \param loc the address to initialize; its type is a pointer
1156 ///   to the LLVM mapping of the variable's type
1157 /// \param alignment the alignment of the address
1158 /// \param capturedByInit true if the variable is a __block variable
1159 ///   whose address is potentially changed by the initializer
1160 void CodeGenFunction::EmitExprAsInit(const Expr *init,
1161                                      const ValueDecl *D,
1162                                      LValue lvalue,
1163                                      bool capturedByInit) {
1164   QualType type = D->getType();
1165 
1166   if (type->isReferenceType()) {
1167     RValue rvalue = EmitReferenceBindingToExpr(init);
1168     if (capturedByInit)
1169       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1170     EmitStoreThroughLValue(rvalue, lvalue, true);
1171     return;
1172   }
1173   switch (getEvaluationKind(type)) {
1174   case TEK_Scalar:
1175     EmitScalarInit(init, D, lvalue, capturedByInit);
1176     return;
1177   case TEK_Complex: {
1178     ComplexPairTy complex = EmitComplexExpr(init);
1179     if (capturedByInit)
1180       drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1181     EmitStoreOfComplex(complex, lvalue, /*init*/ true);
1182     return;
1183   }
1184   case TEK_Aggregate:
1185     if (type->isAtomicType()) {
1186       EmitAtomicInit(const_cast<Expr*>(init), lvalue);
1187     } else {
1188       // TODO: how can we delay here if D is captured by its initializer?
1189       EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1190                                               AggValueSlot::IsDestructed,
1191                                          AggValueSlot::DoesNotNeedGCBarriers,
1192                                               AggValueSlot::IsNotAliased));
1193     }
1194     return;
1195   }
1196   llvm_unreachable("bad evaluation kind");
1197 }
1198 
1199 /// Enter a destroy cleanup for the given local variable.
1200 void CodeGenFunction::emitAutoVarTypeCleanup(
1201                             const CodeGenFunction::AutoVarEmission &emission,
1202                             QualType::DestructionKind dtorKind) {
1203   assert(dtorKind != QualType::DK_none);
1204 
1205   // Note that for __block variables, we want to destroy the
1206   // original stack object, not the possibly forwarded object.
1207   llvm::Value *addr = emission.getObjectAddress(*this);
1208 
1209   const VarDecl *var = emission.Variable;
1210   QualType type = var->getType();
1211 
1212   CleanupKind cleanupKind = NormalAndEHCleanup;
1213   CodeGenFunction::Destroyer *destroyer = 0;
1214 
1215   switch (dtorKind) {
1216   case QualType::DK_none:
1217     llvm_unreachable("no cleanup for trivially-destructible variable");
1218 
1219   case QualType::DK_cxx_destructor:
1220     // If there's an NRVO flag on the emission, we need a different
1221     // cleanup.
1222     if (emission.NRVOFlag) {
1223       assert(!type->isArrayType());
1224       CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1225       EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1226                                                emission.NRVOFlag);
1227       return;
1228     }
1229     break;
1230 
1231   case QualType::DK_objc_strong_lifetime:
1232     // Suppress cleanups for pseudo-strong variables.
1233     if (var->isARCPseudoStrong()) return;
1234 
1235     // Otherwise, consider whether to use an EH cleanup or not.
1236     cleanupKind = getARCCleanupKind();
1237 
1238     // Use the imprecise destroyer by default.
1239     if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1240       destroyer = CodeGenFunction::destroyARCStrongImprecise;
1241     break;
1242 
1243   case QualType::DK_objc_weak_lifetime:
1244     break;
1245   }
1246 
1247   // If we haven't chosen a more specific destroyer, use the default.
1248   if (!destroyer) destroyer = getDestroyer(dtorKind);
1249 
1250   // Use an EH cleanup in array destructors iff the destructor itself
1251   // is being pushed as an EH cleanup.
1252   bool useEHCleanup = (cleanupKind & EHCleanup);
1253   EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
1254                                      useEHCleanup);
1255 }
1256 
1257 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1258   assert(emission.Variable && "emission was not valid!");
1259 
1260   // If this was emitted as a global constant, we're done.
1261   if (emission.wasEmittedAsGlobal()) return;
1262 
1263   // If we don't have an insertion point, we're done.  Sema prevents
1264   // us from jumping into any of these scopes anyway.
1265   if (!HaveInsertPoint()) return;
1266 
1267   const VarDecl &D = *emission.Variable;
1268 
1269   // Make sure we call @llvm.lifetime.end.  This needs to happen
1270   // *last*, so the cleanup needs to be pushed *first*.
1271   if (emission.useLifetimeMarkers()) {
1272     EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1273                                          emission.getAllocatedAddress(),
1274                                          emission.getSizeForLifetimeMarkers());
1275   }
1276 
1277   // Check the type for a cleanup.
1278   if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1279     emitAutoVarTypeCleanup(emission, dtorKind);
1280 
1281   // In GC mode, honor objc_precise_lifetime.
1282   if (getLangOpts().getGC() != LangOptions::NonGC &&
1283       D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1284     EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1285   }
1286 
1287   // Handle the cleanup attribute.
1288   if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1289     const FunctionDecl *FD = CA->getFunctionDecl();
1290 
1291     llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1292     assert(F && "Could not find function!");
1293 
1294     const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
1295     EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1296   }
1297 
1298   // If this is a block variable, call _Block_object_destroy
1299   // (on the unforwarded address).
1300   if (emission.IsByRef)
1301     enterByrefCleanup(emission);
1302 }
1303 
1304 CodeGenFunction::Destroyer *
1305 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1306   switch (kind) {
1307   case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1308   case QualType::DK_cxx_destructor:
1309     return destroyCXXObject;
1310   case QualType::DK_objc_strong_lifetime:
1311     return destroyARCStrongPrecise;
1312   case QualType::DK_objc_weak_lifetime:
1313     return destroyARCWeak;
1314   }
1315   llvm_unreachable("Unknown DestructionKind");
1316 }
1317 
1318 /// pushEHDestroy - Push the standard destructor for the given type as
1319 /// an EH-only cleanup.
1320 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1321                                   llvm::Value *addr, QualType type) {
1322   assert(dtorKind && "cannot push destructor for trivial type");
1323   assert(needsEHCleanup(dtorKind));
1324 
1325   pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1326 }
1327 
1328 /// pushDestroy - Push the standard destructor for the given type as
1329 /// at least a normal cleanup.
1330 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
1331                                   llvm::Value *addr, QualType type) {
1332   assert(dtorKind && "cannot push destructor for trivial type");
1333 
1334   CleanupKind cleanupKind = getCleanupKind(dtorKind);
1335   pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
1336               cleanupKind & EHCleanup);
1337 }
1338 
1339 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
1340                                   QualType type, Destroyer *destroyer,
1341                                   bool useEHCleanupForArray) {
1342   pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
1343                                      destroyer, useEHCleanupForArray);
1344 }
1345 
1346 void CodeGenFunction::pushLifetimeExtendedDestroy(
1347     CleanupKind cleanupKind, llvm::Value *addr, QualType type,
1348     Destroyer *destroyer, bool useEHCleanupForArray) {
1349   assert(!isInConditionalBranch() &&
1350          "performing lifetime extension from within conditional");
1351 
1352   // Push an EH-only cleanup for the object now.
1353   // FIXME: When popping normal cleanups, we need to keep this EH cleanup
1354   // around in case a temporary's destructor throws an exception.
1355   if (cleanupKind & EHCleanup)
1356     EHStack.pushCleanup<DestroyObject>(
1357         static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
1358         destroyer, useEHCleanupForArray);
1359 
1360   // Remember that we need to push a full cleanup for the object at the
1361   // end of the full-expression.
1362   pushCleanupAfterFullExpr<DestroyObject>(
1363       cleanupKind, addr, type, destroyer, useEHCleanupForArray);
1364 }
1365 
1366 /// emitDestroy - Immediately perform the destruction of the given
1367 /// object.
1368 ///
1369 /// \param addr - the address of the object; a type*
1370 /// \param type - the type of the object; if an array type, all
1371 ///   objects are destroyed in reverse order
1372 /// \param destroyer - the function to call to destroy individual
1373 ///   elements
1374 /// \param useEHCleanupForArray - whether an EH cleanup should be
1375 ///   used when destroying array elements, in case one of the
1376 ///   destructions throws an exception
1377 void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
1378                                   Destroyer *destroyer,
1379                                   bool useEHCleanupForArray) {
1380   const ArrayType *arrayType = getContext().getAsArrayType(type);
1381   if (!arrayType)
1382     return destroyer(*this, addr, type);
1383 
1384   llvm::Value *begin = addr;
1385   llvm::Value *length = emitArrayLength(arrayType, type, begin);
1386 
1387   // Normally we have to check whether the array is zero-length.
1388   bool checkZeroLength = true;
1389 
1390   // But if the array length is constant, we can suppress that.
1391   if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1392     // ...and if it's constant zero, we can just skip the entire thing.
1393     if (constLength->isZero()) return;
1394     checkZeroLength = false;
1395   }
1396 
1397   llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1398   emitArrayDestroy(begin, end, type, destroyer,
1399                    checkZeroLength, useEHCleanupForArray);
1400 }
1401 
1402 /// emitArrayDestroy - Destroys all the elements of the given array,
1403 /// beginning from last to first.  The array cannot be zero-length.
1404 ///
1405 /// \param begin - a type* denoting the first element of the array
1406 /// \param end - a type* denoting one past the end of the array
1407 /// \param type - the element type of the array
1408 /// \param destroyer - the function to call to destroy elements
1409 /// \param useEHCleanup - whether to push an EH cleanup to destroy
1410 ///   the remaining elements in case the destruction of a single
1411 ///   element throws
1412 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1413                                        llvm::Value *end,
1414                                        QualType type,
1415                                        Destroyer *destroyer,
1416                                        bool checkZeroLength,
1417                                        bool useEHCleanup) {
1418   assert(!type->isArrayType());
1419 
1420   // The basic structure here is a do-while loop, because we don't
1421   // need to check for the zero-element case.
1422   llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1423   llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1424 
1425   if (checkZeroLength) {
1426     llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1427                                                 "arraydestroy.isempty");
1428     Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1429   }
1430 
1431   // Enter the loop body, making that address the current address.
1432   llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1433   EmitBlock(bodyBB);
1434   llvm::PHINode *elementPast =
1435     Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1436   elementPast->addIncoming(end, entryBB);
1437 
1438   // Shift the address back by one element.
1439   llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1440   llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1441                                                    "arraydestroy.element");
1442 
1443   if (useEHCleanup)
1444     pushRegularPartialArrayCleanup(begin, element, type, destroyer);
1445 
1446   // Perform the actual destruction there.
1447   destroyer(*this, element, type);
1448 
1449   if (useEHCleanup)
1450     PopCleanupBlock();
1451 
1452   // Check whether we've reached the end.
1453   llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1454   Builder.CreateCondBr(done, doneBB, bodyBB);
1455   elementPast->addIncoming(element, Builder.GetInsertBlock());
1456 
1457   // Done.
1458   EmitBlock(doneBB);
1459 }
1460 
1461 /// Perform partial array destruction as if in an EH cleanup.  Unlike
1462 /// emitArrayDestroy, the element type here may still be an array type.
1463 static void emitPartialArrayDestroy(CodeGenFunction &CGF,
1464                                     llvm::Value *begin, llvm::Value *end,
1465                                     QualType type,
1466                                     CodeGenFunction::Destroyer *destroyer) {
1467   // If the element type is itself an array, drill down.
1468   unsigned arrayDepth = 0;
1469   while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1470     // VLAs don't require a GEP index to walk into.
1471     if (!isa<VariableArrayType>(arrayType))
1472       arrayDepth++;
1473     type = arrayType->getElementType();
1474   }
1475 
1476   if (arrayDepth) {
1477     llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1478 
1479     SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
1480     begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
1481     end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
1482   }
1483 
1484   // Destroy the array.  We don't ever need an EH cleanup because we
1485   // assume that we're in an EH cleanup ourselves, so a throwing
1486   // destructor causes an immediate terminate.
1487   CGF.emitArrayDestroy(begin, end, type, destroyer,
1488                        /*checkZeroLength*/ true, /*useEHCleanup*/ false);
1489 }
1490 
1491 namespace {
1492   /// RegularPartialArrayDestroy - a cleanup which performs a partial
1493   /// array destroy where the end pointer is regularly determined and
1494   /// does not need to be loaded from a local.
1495   class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
1496     llvm::Value *ArrayBegin;
1497     llvm::Value *ArrayEnd;
1498     QualType ElementType;
1499     CodeGenFunction::Destroyer *Destroyer;
1500   public:
1501     RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
1502                                QualType elementType,
1503                                CodeGenFunction::Destroyer *destroyer)
1504       : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1505         ElementType(elementType), Destroyer(destroyer) {}
1506 
1507     void Emit(CodeGenFunction &CGF, Flags flags) {
1508       emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
1509                               ElementType, Destroyer);
1510     }
1511   };
1512 
1513   /// IrregularPartialArrayDestroy - a cleanup which performs a
1514   /// partial array destroy where the end pointer is irregularly
1515   /// determined and must be loaded from a local.
1516   class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
1517     llvm::Value *ArrayBegin;
1518     llvm::Value *ArrayEndPointer;
1519     QualType ElementType;
1520     CodeGenFunction::Destroyer *Destroyer;
1521   public:
1522     IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
1523                                  llvm::Value *arrayEndPointer,
1524                                  QualType elementType,
1525                                  CodeGenFunction::Destroyer *destroyer)
1526       : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1527         ElementType(elementType), Destroyer(destroyer) {}
1528 
1529     void Emit(CodeGenFunction &CGF, Flags flags) {
1530       llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1531       emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
1532                               ElementType, Destroyer);
1533     }
1534   };
1535 }
1536 
1537 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
1538 /// already-constructed elements of the given array.  The cleanup
1539 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1540 ///
1541 /// \param elementType - the immediate element type of the array;
1542 ///   possibly still an array type
1543 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
1544                                                  llvm::Value *arrayEndPointer,
1545                                                        QualType elementType,
1546                                                        Destroyer *destroyer) {
1547   pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
1548                                                     arrayBegin, arrayEndPointer,
1549                                                     elementType, destroyer);
1550 }
1551 
1552 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1553 /// already-constructed elements of the given array.  The cleanup
1554 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1555 ///
1556 /// \param elementType - the immediate element type of the array;
1557 ///   possibly still an array type
1558 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
1559                                                      llvm::Value *arrayEnd,
1560                                                      QualType elementType,
1561                                                      Destroyer *destroyer) {
1562   pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
1563                                                   arrayBegin, arrayEnd,
1564                                                   elementType, destroyer);
1565 }
1566 
1567 /// Lazily declare the @llvm.lifetime.start intrinsic.
1568 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1569   if (LifetimeStartFn) return LifetimeStartFn;
1570   LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1571                                             llvm::Intrinsic::lifetime_start);
1572   return LifetimeStartFn;
1573 }
1574 
1575 /// Lazily declare the @llvm.lifetime.end intrinsic.
1576 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1577   if (LifetimeEndFn) return LifetimeEndFn;
1578   LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1579                                               llvm::Intrinsic::lifetime_end);
1580   return LifetimeEndFn;
1581 }
1582 
1583 namespace {
1584   /// A cleanup to perform a release of an object at the end of a
1585   /// function.  This is used to balance out the incoming +1 of a
1586   /// ns_consumed argument when we can't reasonably do that just by
1587   /// not doing the initial retain for a __block argument.
1588   struct ConsumeARCParameter : EHScopeStack::Cleanup {
1589     ConsumeARCParameter(llvm::Value *param,
1590                         ARCPreciseLifetime_t precise)
1591       : Param(param), Precise(precise) {}
1592 
1593     llvm::Value *Param;
1594     ARCPreciseLifetime_t Precise;
1595 
1596     void Emit(CodeGenFunction &CGF, Flags flags) {
1597       CGF.EmitARCRelease(Param, Precise);
1598     }
1599   };
1600 }
1601 
1602 /// Emit an alloca (or GlobalValue depending on target)
1603 /// for the specified parameter and set up LocalDeclMap.
1604 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1605                                    unsigned ArgNo) {
1606   // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1607   assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1608          "Invalid argument to EmitParmDecl");
1609 
1610   Arg->setName(D.getName());
1611 
1612   QualType Ty = D.getType();
1613 
1614   // Use better IR generation for certain implicit parameters.
1615   if (isa<ImplicitParamDecl>(D)) {
1616     // The only implicit argument a block has is its literal.
1617     if (BlockInfo) {
1618       LocalDeclMap[&D] = Arg;
1619       llvm::Value *LocalAddr = 0;
1620       if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1621         // Allocate a stack slot to let the debug info survive the RA.
1622         llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1623                                                    D.getName() + ".addr");
1624         Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1625         LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1626         EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1627         LocalAddr = Builder.CreateLoad(Alloc);
1628       }
1629 
1630       if (CGDebugInfo *DI = getDebugInfo()) {
1631         if (CGM.getCodeGenOpts().getDebugInfo()
1632               >= CodeGenOptions::LimitedDebugInfo) {
1633           DI->setLocation(D.getLocation());
1634           DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
1635         }
1636       }
1637 
1638       return;
1639     }
1640   }
1641 
1642   llvm::Value *DeclPtr;
1643   bool HasNonScalarEvalKind = !CodeGenFunction::hasScalarEvaluationKind(Ty);
1644   // If this is an aggregate or variable sized value, reuse the input pointer.
1645   if (HasNonScalarEvalKind || !Ty->isConstantSizeType()) {
1646     DeclPtr = Arg;
1647     // Push a destructor cleanup for this parameter if the ABI requires it.
1648     if (HasNonScalarEvalKind &&
1649         getTarget().getCXXABI().isArgumentDestroyedByCallee()) {
1650       if (const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl()) {
1651         if (RD->hasNonTrivialDestructor())
1652           pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
1653       }
1654     }
1655   } else {
1656     // Otherwise, create a temporary to hold the value.
1657     llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1658                                                D.getName() + ".addr");
1659     CharUnits Align = getContext().getDeclAlign(&D);
1660     Alloc->setAlignment(Align.getQuantity());
1661     DeclPtr = Alloc;
1662 
1663     bool doStore = true;
1664 
1665     Qualifiers qs = Ty.getQualifiers();
1666     LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1667     if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1668       // We honor __attribute__((ns_consumed)) for types with lifetime.
1669       // For __strong, it's handled by just skipping the initial retain;
1670       // otherwise we have to balance out the initial +1 with an extra
1671       // cleanup to do the release at the end of the function.
1672       bool isConsumed = D.hasAttr<NSConsumedAttr>();
1673 
1674       // 'self' is always formally __strong, but if this is not an
1675       // init method then we don't want to retain it.
1676       if (D.isARCPseudoStrong()) {
1677         const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1678         assert(&D == method->getSelfDecl());
1679         assert(lt == Qualifiers::OCL_Strong);
1680         assert(qs.hasConst());
1681         assert(method->getMethodFamily() != OMF_init);
1682         (void) method;
1683         lt = Qualifiers::OCL_ExplicitNone;
1684       }
1685 
1686       if (lt == Qualifiers::OCL_Strong) {
1687         if (!isConsumed) {
1688           if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1689             // use objc_storeStrong(&dest, value) for retaining the
1690             // object. But first, store a null into 'dest' because
1691             // objc_storeStrong attempts to release its old value.
1692             llvm::Value *Null = CGM.EmitNullConstant(D.getType());
1693             EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
1694             EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
1695             doStore = false;
1696           }
1697           else
1698           // Don't use objc_retainBlock for block pointers, because we
1699           // don't want to Block_copy something just because we got it
1700           // as a parameter.
1701             Arg = EmitARCRetainNonBlock(Arg);
1702         }
1703       } else {
1704         // Push the cleanup for a consumed parameter.
1705         if (isConsumed) {
1706           ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
1707                                 ? ARCPreciseLifetime : ARCImpreciseLifetime);
1708           EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
1709                                                    precise);
1710         }
1711 
1712         if (lt == Qualifiers::OCL_Weak) {
1713           EmitARCInitWeak(DeclPtr, Arg);
1714           doStore = false; // The weak init is a store, no need to do two.
1715         }
1716       }
1717 
1718       // Enter the cleanup scope.
1719       EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1720     }
1721 
1722     // Store the initial value into the alloca.
1723     if (doStore)
1724       EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1725   }
1726 
1727   llvm::Value *&DMEntry = LocalDeclMap[&D];
1728   assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1729   DMEntry = DeclPtr;
1730 
1731   // Emit debug info for param declaration.
1732   if (CGDebugInfo *DI = getDebugInfo()) {
1733     if (CGM.getCodeGenOpts().getDebugInfo()
1734           >= CodeGenOptions::LimitedDebugInfo) {
1735       DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1736     }
1737   }
1738 
1739   if (D.hasAttr<AnnotateAttr>())
1740       EmitVarAnnotations(&D, DeclPtr);
1741 }
1742