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