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