CGDecl.cpp revision 0850e8d1b093cfe1fc2fdf533a0e264ef9d5412e
1221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
2221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom//
3221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom//                     The LLVM Compiler Infrastructure
4221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom//
5221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom// This file is distributed under the University of Illinois Open Source
6221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom// License. See LICENSE.TXT for details.
7221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom//
8221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom//===----------------------------------------------------------------------===//
9221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom//
10221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom// This contains code to emit Decl nodes as LLVM code.
11221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom//
12221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom//===----------------------------------------------------------------------===//
13221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
14221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "CGDebugInfo.h"
15221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "CodeGenFunction.h"
16221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "CodeGenModule.h"
17221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "clang/AST/ASTContext.h"
18221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "clang/AST/CharUnits.h"
19221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "clang/AST/Decl.h"
20221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "clang/AST/DeclObjC.h"
21221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "clang/Basic/SourceManager.h"
22221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "clang/Basic/TargetInfo.h"
23221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "clang/Frontend/CodeGenOptions.h"
24221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "llvm/GlobalVariable.h"
25221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "llvm/Intrinsics.h"
26221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "llvm/Target/TargetData.h"
27221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom#include "llvm/Type.h"
28221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstromusing namespace clang;
29221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstromusing namespace CodeGen;
30221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
31221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
32221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstromvoid CodeGenFunction::EmitDecl(const Decl &D) {
33221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  switch (D.getKind()) {
34221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::TranslationUnit:
35221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::Namespace:
36221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::UnresolvedUsingTypename:
37221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ClassTemplateSpecialization:
38221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ClassTemplatePartialSpecialization:
39221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::TemplateTypeParm:
40221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::UnresolvedUsingValue:
41221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::NonTypeTemplateParm:
42221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::CXXMethod:
43221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::CXXConstructor:
44221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::CXXDestructor:
45221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::CXXConversion:
46221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::Field:
47221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::IndirectField:
48221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCIvar:
49221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCAtDefsField:
50221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ParmVar:
51221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ImplicitParam:
52221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ClassTemplate:
53221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::FunctionTemplate:
54221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::TypeAliasTemplate:
55221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::TemplateTemplateParm:
56221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCMethod:
57221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCCategory:
58221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCProtocol:
59221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCInterface:
60221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCCategoryImpl:
61221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCImplementation:
62221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCProperty:
63221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCCompatibleAlias:
64221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::AccessSpec:
65221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::LinkageSpec:
66221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCPropertyImpl:
67221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCClass:
68221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::ObjCForwardProtocol:
69221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::FileScopeAsm:
70221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::Friend:
71221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::FriendTemplate:
72221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::Block:
73221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    assert(0 && "Declaration should not be in declstmts!");
74221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::Function:  // void X();
75221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::Record:    // struct/union/class X;
76221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::Enum:      // enum X;
77221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::EnumConstant: // enum ? { X = ? }
78221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::CXXRecord: // struct/union/class X; [C++]
79221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::Using:          // using X; [C++]
80221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::UsingShadow:
81221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::UsingDirective: // using namespace X; [C++]
82221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::NamespaceAlias:
83221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
84221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::Label:        // __label__ x;
85221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    // None of these decls require codegen support.
86221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    return;
87221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
88221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::Var: {
89221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    const VarDecl &VD = cast<VarDecl>(D);
90221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    assert(VD.isLocalVarDecl() &&
91221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom           "Should not see file-scope variables inside a function!");
92221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    return EmitVarDecl(VD);
93221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  }
94221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
95221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::Typedef:      // typedef int X;
96221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case Decl::TypeAlias: {  // using X = int; [C++0x]
97221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
98221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    QualType Ty = TD.getUnderlyingType();
99221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
100221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    if (Ty->isVariablyModifiedType())
101221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      EmitVariablyModifiedType(Ty);
102221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  }
103221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  }
104221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom}
105221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
106221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom/// EmitVarDecl - This method handles emission of any variable declaration
107221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom/// inside a function, including static vars etc.
108221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstromvoid CodeGenFunction::EmitVarDecl(const VarDecl &D) {
109221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  switch (D.getStorageClass()) {
110221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case SC_None:
111221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case SC_Auto:
112221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case SC_Register:
113221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    return EmitAutoVarDecl(D);
114221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case SC_Static: {
115221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    llvm::GlobalValue::LinkageTypes Linkage =
116221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      llvm::GlobalValue::InternalLinkage;
117221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
118221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    // If the function definition has some sort of weak linkage, its
119221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    // static variables should also be weak so that they get properly
120221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    // uniqued.  We can't do this in C, though, because there's no
121221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    // standard way to agree on which variables are the same (i.e.
122221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    // there's no mangling).
123221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    if (getContext().getLangOptions().CPlusPlus)
124221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage()))
125221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom        Linkage = CurFn->getLinkage();
126221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
127221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    return EmitStaticVarDecl(D, Linkage);
128221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  }
129221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case SC_Extern:
130221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  case SC_PrivateExtern:
131221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    // Don't emit it now, allow it to be emitted lazily on its first use.
132221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    return;
133221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  }
134221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
135221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  assert(0 && "Unknown storage class");
136221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom}
137221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
138221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstromstatic std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
139221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                                     const char *Separator) {
140221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  CodeGenModule &CGM = CGF.CGM;
141221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  if (CGF.getContext().getLangOptions().CPlusPlus) {
142221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    llvm::StringRef Name = CGM.getMangledName(&D);
143221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    return Name.str();
144221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  }
145221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
146221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  std::string ContextName;
147221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  if (!CGF.CurFuncDecl) {
148221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    // Better be in a block declared in global scope.
149221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    const NamedDecl *ND = cast<NamedDecl>(&D);
150ee7afb3c942c4eefef6ed06201eafaf8ec58e2e3Brian Carlstrom    const DeclContext *DC = ND->getDeclContext();
151ee7afb3c942c4eefef6ed06201eafaf8ec58e2e3Brian Carlstrom    if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
152221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      MangleBuffer Name;
153221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      CGM.getBlockMangledName(GlobalDecl(), Name, BD);
154221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      ContextName = Name.getString();
155221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    }
156221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    else
157221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      assert(0 && "Unknown context for block static var decl");
158221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
159221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    llvm::StringRef Name = CGM.getMangledName(FD);
160221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    ContextName = Name.str();
161221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
162221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    ContextName = CGF.CurFn->getName();
163221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  else
164221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    assert(0 && "Unknown context for static var decl");
165221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
166221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  return ContextName + Separator + D.getNameAsString();
167221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom}
168221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
169221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstromllvm::GlobalVariable *
170221304ee937bc0910948a8be1320cb8cc4eb6d36Brian CarlstromCodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
171221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                                     const char *Separator,
172221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                                     llvm::GlobalValue::LinkageTypes Linkage) {
173221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  QualType Ty = D.getType();
174221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  assert(Ty->isConstantSizeType() && "VLAs can't be static");
175221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
176221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  std::string Name = GetStaticDeclName(*this, D, Separator);
177221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
178221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
179221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  llvm::GlobalVariable *GV =
180221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    new llvm::GlobalVariable(CGM.getModule(), LTy,
181221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                             Ty.isConstant(getContext()), Linkage,
182221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                             CGM.EmitNullConstant(D.getType()), Name, 0,
183221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                             D.isThreadSpecified(),
184221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                             CGM.getContext().getTargetAddressSpace(Ty));
185221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
186221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  if (Linkage != llvm::GlobalValue::InternalLinkage)
187221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    GV->setVisibility(CurFn->getVisibility());
188221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  return GV;
189221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom}
190221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
191221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
192221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom/// global variable that has already been created for it.  If the initializer
193221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom/// has a different type than GV does, this may free GV and return a different
194221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom/// one.  Otherwise it just returns GV.
195221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstromllvm::GlobalVariable *
196221304ee937bc0910948a8be1320cb8cc4eb6d36Brian CarlstromCodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
197221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                                               llvm::GlobalVariable *GV) {
198221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this);
199221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
200221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // If constant emission failed, then this should be a C++ static
201221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // initializer.
202221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  if (!Init) {
203221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    if (!getContext().getLangOptions().CPlusPlus)
204221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
205221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    else if (Builder.GetInsertBlock()) {
206221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      // Since we have a static initializer, this global variable can't
207221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      // be constant.
208221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      GV->setConstant(false);
209221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
210221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom      EmitCXXGuardedInit(D, GV);
211221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    }
212221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    return GV;
213221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  }
214221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
215221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // The initializer may differ in type from the global. Rewrite
216221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // the global to match the initializer.  (We have to do this
217221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // because some types, like unions, can't be completely represented
218221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // in the LLVM type system.)
219221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  if (GV->getType()->getElementType() != Init->getType()) {
220221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    llvm::GlobalVariable *OldGV = GV;
221221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
222221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
223221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                                  OldGV->isConstant(),
224221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                                  OldGV->getLinkage(), Init, "",
225221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                                  /*InsertBefore*/ OldGV,
226221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                                  D.isThreadSpecified(),
227221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                           CGM.getContext().getTargetAddressSpace(D.getType()));
228221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    GV->setVisibility(OldGV->getVisibility());
229221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
230221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    // Steal the name of the old global
231221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    GV->takeName(OldGV);
232221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
233221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    // Replace all uses of the old global with the new global
234221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    llvm::Constant *NewPtrForOldDecl =
235221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
236221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    OldGV->replaceAllUsesWith(NewPtrForOldDecl);
237221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
238221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    // Erase the old global, since it is no longer used.
239221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    OldGV->eraseFromParent();
240221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  }
241221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
242221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  GV->setInitializer(Init);
243221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  return GV;
244221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom}
245221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
246221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstromvoid CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
247221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom                                      llvm::GlobalValue::LinkageTypes Linkage) {
248221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  llvm::Value *&DMEntry = LocalDeclMap[&D];
249221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
250221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
251221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage);
252221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
253221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // Store into LocalDeclMap before generating initializer to handle
254221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // circular references.
255221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  DMEntry = GV;
256221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
257221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // We can't have a VLA here, but we can have a pointer to a VLA,
258221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // even though that doesn't really make any sense.
259221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // Make sure to evaluate VLA bounds now so that we have them for later.
260221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  if (D.getType()->isVariablyModifiedType())
261221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom    EmitVariablyModifiedType(D.getType());
262221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
263221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // Local static block variables must be treated as globals as they may be
264221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // referenced in their RHS initializer block-literal expresion.
265221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  CGM.setStaticLocalDeclAddress(&D, GV);
266221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom
267221304ee937bc0910948a8be1320cb8cc4eb6d36Brian Carlstrom  // If this value has an initializer, emit it.
268  if (D.getInit())
269    GV = AddInitializerToStaticVarDecl(D, GV);
270
271  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
272
273  // FIXME: Merge attribute handling.
274  if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) {
275    SourceManager &SM = CGM.getContext().getSourceManager();
276    llvm::Constant *Ann =
277      CGM.EmitAnnotateAttr(GV, AA,
278                           SM.getInstantiationLineNumber(D.getLocation()));
279    CGM.AddAnnotation(Ann);
280  }
281
282  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
283    GV->setSection(SA->getName());
284
285  if (D.hasAttr<UsedAttr>())
286    CGM.AddUsedGlobal(GV);
287
288  // We may have to cast the constant because of the initializer
289  // mismatch above.
290  //
291  // FIXME: It is really dangerous to store this in the map; if anyone
292  // RAUW's the GV uses of this constant will be invalid.
293  const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType());
294  const llvm::Type *LPtrTy =
295    LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType()));
296  DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy);
297
298  // Emit global variable debug descriptor for static vars.
299  CGDebugInfo *DI = getDebugInfo();
300  if (DI) {
301    DI->setLocation(D.getLocation());
302    DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D);
303  }
304}
305
306namespace {
307  struct DestroyObject : EHScopeStack::Cleanup {
308    DestroyObject(llvm::Value *addr, QualType type,
309                  CodeGenFunction::Destroyer *destroyer)
310      : addr(addr), type(type), destroyer(*destroyer) {}
311
312    llvm::Value *addr;
313    QualType type;
314    CodeGenFunction::Destroyer &destroyer;
315
316    void Emit(CodeGenFunction &CGF, bool IsForEH) {
317      CGF.emitDestroy(addr, type, destroyer);
318    }
319  };
320
321  struct DestroyNRVOVariable : EHScopeStack::Cleanup {
322    DestroyNRVOVariable(llvm::Value *addr,
323                        const CXXDestructorDecl *Dtor,
324                        llvm::Value *NRVOFlag)
325      : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
326
327    const CXXDestructorDecl *Dtor;
328    llvm::Value *NRVOFlag;
329    llvm::Value *Loc;
330
331    void Emit(CodeGenFunction &CGF, bool IsForEH) {
332      // Along the exceptions path we always execute the dtor.
333      bool NRVO = !IsForEH && NRVOFlag;
334
335      llvm::BasicBlock *SkipDtorBB = 0;
336      if (NRVO) {
337        // If we exited via NRVO, we skip the destructor call.
338        llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
339        SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
340        llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
341        CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
342        CGF.EmitBlock(RunDtorBB);
343      }
344
345      CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
346                                /*ForVirtualBase=*/false, Loc);
347
348      if (NRVO) CGF.EmitBlock(SkipDtorBB);
349    }
350  };
351
352  struct CallStackRestore : EHScopeStack::Cleanup {
353    llvm::Value *Stack;
354    CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
355    void Emit(CodeGenFunction &CGF, bool IsForEH) {
356      llvm::Value *V = CGF.Builder.CreateLoad(Stack, "tmp");
357      llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
358      CGF.Builder.CreateCall(F, V);
359    }
360  };
361
362  struct ExtendGCLifetime : EHScopeStack::Cleanup {
363    const VarDecl &Var;
364    ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
365
366    void Emit(CodeGenFunction &CGF, bool forEH) {
367      // Compute the address of the local variable, in case it's a
368      // byref or something.
369      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
370                      SourceLocation());
371      llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
372      CGF.EmitExtendGCLifetime(value);
373    }
374  };
375
376  struct CallCleanupFunction : EHScopeStack::Cleanup {
377    llvm::Constant *CleanupFn;
378    const CGFunctionInfo &FnInfo;
379    const VarDecl &Var;
380
381    CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
382                        const VarDecl *Var)
383      : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
384
385    void Emit(CodeGenFunction &CGF, bool IsForEH) {
386      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue,
387                      SourceLocation());
388      // Compute the address of the local variable, in case it's a byref
389      // or something.
390      llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
391
392      // In some cases, the type of the function argument will be different from
393      // the type of the pointer. An example of this is
394      // void f(void* arg);
395      // __attribute__((cleanup(f))) void *g;
396      //
397      // To fix this we insert a bitcast here.
398      QualType ArgTy = FnInfo.arg_begin()->type;
399      llvm::Value *Arg =
400        CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
401
402      CallArgList Args;
403      Args.add(RValue::get(Arg),
404               CGF.getContext().getPointerType(Var.getType()));
405      CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
406    }
407  };
408}
409
410/// EmitAutoVarWithLifetime - Does the setup required for an automatic
411/// variable with lifetime.
412static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
413                                    llvm::Value *addr,
414                                    Qualifiers::ObjCLifetime lifetime) {
415  switch (lifetime) {
416  case Qualifiers::OCL_None:
417    llvm_unreachable("present but none");
418
419  case Qualifiers::OCL_ExplicitNone:
420    // nothing to do
421    break;
422
423  case Qualifiers::OCL_Strong: {
424    CGF.PushARCReleaseCleanup(CGF.getARCCleanupKind(),
425                              var.getType(), addr,
426                              var.hasAttr<ObjCPreciseLifetimeAttr>());
427    break;
428  }
429  case Qualifiers::OCL_Autoreleasing:
430    // nothing to do
431    break;
432
433  case Qualifiers::OCL_Weak:
434    // __weak objects always get EH cleanups; otherwise, exceptions
435    // could cause really nasty crashes instead of mere leaks.
436    CGF.PushARCWeakReleaseCleanup(NormalAndEHCleanup, var.getType(), addr);
437    break;
438  }
439}
440
441static bool isAccessedBy(const VarDecl &var, const Stmt *s) {
442  if (const Expr *e = dyn_cast<Expr>(s)) {
443    // Skip the most common kinds of expressions that make
444    // hierarchy-walking expensive.
445    s = e = e->IgnoreParenCasts();
446
447    if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
448      return (ref->getDecl() == &var);
449  }
450
451  for (Stmt::const_child_range children = s->children(); children; ++children)
452    // children might be null; as in missing decl or conditional of an if-stmt.
453    if ((*children) && isAccessedBy(var, *children))
454      return true;
455
456  return false;
457}
458
459static bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
460  if (!decl) return false;
461  if (!isa<VarDecl>(decl)) return false;
462  const VarDecl *var = cast<VarDecl>(decl);
463  return isAccessedBy(*var, e);
464}
465
466static void drillIntoBlockVariable(CodeGenFunction &CGF,
467                                   LValue &lvalue,
468                                   const VarDecl *var) {
469  lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
470}
471
472void CodeGenFunction::EmitScalarInit(const Expr *init,
473                                     const ValueDecl *D,
474                                     LValue lvalue,
475                                     bool capturedByInit) {
476  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
477  if (!lifetime) {
478    llvm::Value *value = EmitScalarExpr(init);
479    if (capturedByInit)
480      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
481    EmitStoreThroughLValue(RValue::get(value), lvalue);
482    return;
483  }
484
485  // If we're emitting a value with lifetime, we have to do the
486  // initialization *before* we leave the cleanup scopes.
487  CodeGenFunction::RunCleanupsScope Scope(*this);
488  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init))
489    init = ewc->getSubExpr();
490
491  // We have to maintain the illusion that the variable is
492  // zero-initialized.  If the variable might be accessed in its
493  // initializer, zero-initialize before running the initializer, then
494  // actually perform the initialization with an assign.
495  bool accessedByInit = false;
496  if (lifetime != Qualifiers::OCL_ExplicitNone)
497    accessedByInit = isAccessedBy(D, init);
498  if (accessedByInit) {
499    LValue tempLV = lvalue;
500    // Drill down to the __block object if necessary.
501    if (capturedByInit) {
502      // We can use a simple GEP for this because it can't have been
503      // moved yet.
504      tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
505                                   getByRefValueLLVMField(cast<VarDecl>(D))));
506    }
507
508    const llvm::PointerType *ty
509      = cast<llvm::PointerType>(tempLV.getAddress()->getType());
510    ty = cast<llvm::PointerType>(ty->getElementType());
511
512    llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
513
514    // If __weak, we want to use a barrier under certain conditions.
515    if (lifetime == Qualifiers::OCL_Weak)
516      EmitARCInitWeak(tempLV.getAddress(), zero);
517
518    // Otherwise just do a simple store.
519    else
520      EmitStoreOfScalar(zero, tempLV);
521  }
522
523  // Emit the initializer.
524  llvm::Value *value = 0;
525
526  switch (lifetime) {
527  case Qualifiers::OCL_None:
528    llvm_unreachable("present but none");
529
530  case Qualifiers::OCL_ExplicitNone:
531    // nothing to do
532    value = EmitScalarExpr(init);
533    break;
534
535  case Qualifiers::OCL_Strong: {
536    value = EmitARCRetainScalarExpr(init);
537    break;
538  }
539
540  case Qualifiers::OCL_Weak: {
541    // No way to optimize a producing initializer into this.  It's not
542    // worth optimizing for, because the value will immediately
543    // disappear in the common case.
544    value = EmitScalarExpr(init);
545
546    if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
547    if (accessedByInit)
548      EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
549    else
550      EmitARCInitWeak(lvalue.getAddress(), value);
551    return;
552  }
553
554  case Qualifiers::OCL_Autoreleasing:
555    value = EmitARCRetainAutoreleaseScalarExpr(init);
556    break;
557  }
558
559  if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
560
561  // If the variable might have been accessed by its initializer, we
562  // might have to initialize with a barrier.  We have to do this for
563  // both __weak and __strong, but __weak got filtered out above.
564  if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
565    llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
566    EmitStoreOfScalar(value, lvalue);
567    EmitARCRelease(oldValue, /*precise*/ false);
568    return;
569  }
570
571  EmitStoreOfScalar(value, lvalue);
572}
573
574/// EmitScalarInit - Initialize the given lvalue with the given object.
575void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
576  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
577  if (!lifetime)
578    return EmitStoreThroughLValue(RValue::get(init), lvalue);
579
580  switch (lifetime) {
581  case Qualifiers::OCL_None:
582    llvm_unreachable("present but none");
583
584  case Qualifiers::OCL_ExplicitNone:
585    // nothing to do
586    break;
587
588  case Qualifiers::OCL_Strong:
589    init = EmitARCRetain(lvalue.getType(), init);
590    break;
591
592  case Qualifiers::OCL_Weak:
593    // Initialize and then skip the primitive store.
594    EmitARCInitWeak(lvalue.getAddress(), init);
595    return;
596
597  case Qualifiers::OCL_Autoreleasing:
598    init = EmitARCRetainAutorelease(lvalue.getType(), init);
599    break;
600  }
601
602  EmitStoreOfScalar(init, lvalue);
603}
604
605/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
606/// non-zero parts of the specified initializer with equal or fewer than
607/// NumStores scalar stores.
608static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
609                                                unsigned &NumStores) {
610  // Zero and Undef never requires any extra stores.
611  if (isa<llvm::ConstantAggregateZero>(Init) ||
612      isa<llvm::ConstantPointerNull>(Init) ||
613      isa<llvm::UndefValue>(Init))
614    return true;
615  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
616      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
617      isa<llvm::ConstantExpr>(Init))
618    return Init->isNullValue() || NumStores--;
619
620  // See if we can emit each element.
621  if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
622    for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
623      llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
624      if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
625        return false;
626    }
627    return true;
628  }
629
630  // Anything else is hard and scary.
631  return false;
632}
633
634/// emitStoresForInitAfterMemset - For inits that
635/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
636/// stores that would be required.
637static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
638                                         bool isVolatile, CGBuilderTy &Builder) {
639  // Zero doesn't require any stores.
640  if (isa<llvm::ConstantAggregateZero>(Init) ||
641      isa<llvm::ConstantPointerNull>(Init) ||
642      isa<llvm::UndefValue>(Init))
643    return;
644
645  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
646      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
647      isa<llvm::ConstantExpr>(Init)) {
648    if (!Init->isNullValue())
649      Builder.CreateStore(Init, Loc, isVolatile);
650    return;
651  }
652
653  assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
654         "Unknown value type!");
655
656  for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
657    llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
658    if (Elt->isNullValue()) continue;
659
660    // Otherwise, get a pointer to the element and emit it.
661    emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
662                                 isVolatile, Builder);
663  }
664}
665
666
667/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
668/// plus some stores to initialize a local variable instead of using a memcpy
669/// from a constant global.  It is beneficial to use memset if the global is all
670/// zeros, or mostly zeros and large.
671static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
672                                                  uint64_t GlobalSize) {
673  // If a global is all zeros, always use a memset.
674  if (isa<llvm::ConstantAggregateZero>(Init)) return true;
675
676
677  // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
678  // do it if it will require 6 or fewer scalar stores.
679  // TODO: Should budget depends on the size?  Avoiding a large global warrants
680  // plopping in more stores.
681  unsigned StoreBudget = 6;
682  uint64_t SizeLimit = 32;
683
684  return GlobalSize > SizeLimit &&
685         canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
686}
687
688
689/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
690/// variable declaration with auto, register, or no storage class specifier.
691/// These turn into simple stack objects, or GlobalValues depending on target.
692void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
693  AutoVarEmission emission = EmitAutoVarAlloca(D);
694  EmitAutoVarInit(emission);
695  EmitAutoVarCleanups(emission);
696}
697
698/// EmitAutoVarAlloca - Emit the alloca and debug information for a
699/// local variable.  Does not emit initalization or destruction.
700CodeGenFunction::AutoVarEmission
701CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
702  QualType Ty = D.getType();
703
704  AutoVarEmission emission(D);
705
706  bool isByRef = D.hasAttr<BlocksAttr>();
707  emission.IsByRef = isByRef;
708
709  CharUnits alignment = getContext().getDeclAlign(&D);
710  emission.Alignment = alignment;
711
712  // If the type is variably-modified, emit all the VLA sizes for it.
713  if (Ty->isVariablyModifiedType())
714    EmitVariablyModifiedType(Ty);
715
716  llvm::Value *DeclPtr;
717  if (Ty->isConstantSizeType()) {
718    if (!Target.useGlobalsForAutomaticVariables()) {
719      bool NRVO = getContext().getLangOptions().ElideConstructors &&
720                  D.isNRVOVariable();
721
722      // If this value is a POD array or struct with a statically
723      // determinable constant initializer, there are optimizations we
724      // can do.
725      // TODO: we can potentially constant-evaluate non-POD structs and
726      // arrays as long as the initialization is trivial (e.g. if they
727      // have a non-trivial destructor, but not a non-trivial constructor).
728      if (D.getInit() &&
729          (Ty->isArrayType() || Ty->isRecordType()) &&
730          (Ty.isPODType(getContext()) ||
731           getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
732          D.getInit()->isConstantInitializer(getContext(), false)) {
733
734        // If the variable's a const type, and it's neither an NRVO
735        // candidate nor a __block variable, emit it as a global instead.
736        if (CGM.getCodeGenOpts().MergeAllConstants && Ty.isConstQualified() &&
737            !NRVO && !isByRef) {
738          EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
739
740          emission.Address = 0; // signal this condition to later callbacks
741          assert(emission.wasEmittedAsGlobal());
742          return emission;
743        }
744
745        // Otherwise, tell the initialization code that we're in this case.
746        emission.IsConstantAggregate = true;
747      }
748
749      // A normal fixed sized variable becomes an alloca in the entry block,
750      // unless it's an NRVO variable.
751      const llvm::Type *LTy = ConvertTypeForMem(Ty);
752
753      if (NRVO) {
754        // The named return value optimization: allocate this variable in the
755        // return slot, so that we can elide the copy when returning this
756        // variable (C++0x [class.copy]p34).
757        DeclPtr = ReturnValue;
758
759        if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
760          if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
761            // Create a flag that is used to indicate when the NRVO was applied
762            // to this variable. Set it to zero to indicate that NRVO was not
763            // applied.
764            llvm::Value *Zero = Builder.getFalse();
765            llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
766            EnsureInsertPoint();
767            Builder.CreateStore(Zero, NRVOFlag);
768
769            // Record the NRVO flag for this variable.
770            NRVOFlags[&D] = NRVOFlag;
771            emission.NRVOFlag = NRVOFlag;
772          }
773        }
774      } else {
775        if (isByRef)
776          LTy = BuildByRefType(&D);
777
778        llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
779        Alloc->setName(D.getNameAsString());
780
781        CharUnits allocaAlignment = alignment;
782        if (isByRef)
783          allocaAlignment = std::max(allocaAlignment,
784              getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
785        Alloc->setAlignment(allocaAlignment.getQuantity());
786        DeclPtr = Alloc;
787      }
788    } else {
789      // Targets that don't support recursion emit locals as globals.
790      const char *Class =
791        D.getStorageClass() == SC_Register ? ".reg." : ".auto.";
792      DeclPtr = CreateStaticVarDecl(D, Class,
793                                    llvm::GlobalValue::InternalLinkage);
794    }
795  } else {
796    EnsureInsertPoint();
797
798    if (!DidCallStackSave) {
799      // Save the stack.
800      llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
801
802      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
803      llvm::Value *V = Builder.CreateCall(F);
804
805      Builder.CreateStore(V, Stack);
806
807      DidCallStackSave = true;
808
809      // Push a cleanup block and restore the stack there.
810      // FIXME: in general circumstances, this should be an EH cleanup.
811      EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
812    }
813
814    llvm::Value *elementCount;
815    QualType elementType;
816    llvm::tie(elementCount, elementType) = getVLASize(Ty);
817
818    const llvm::Type *llvmTy = ConvertTypeForMem(elementType);
819
820    // Allocate memory for the array.
821    llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
822    vla->setAlignment(alignment.getQuantity());
823
824    DeclPtr = vla;
825  }
826
827  llvm::Value *&DMEntry = LocalDeclMap[&D];
828  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
829  DMEntry = DeclPtr;
830  emission.Address = DeclPtr;
831
832  // Emit debug info for local var declaration.
833  if (HaveInsertPoint())
834    if (CGDebugInfo *DI = getDebugInfo()) {
835      DI->setLocation(D.getLocation());
836      if (Target.useGlobalsForAutomaticVariables()) {
837        DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D);
838      } else
839        DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
840    }
841
842  return emission;
843}
844
845/// Determines whether the given __block variable is potentially
846/// captured by the given expression.
847static bool isCapturedBy(const VarDecl &var, const Expr *e) {
848  // Skip the most common kinds of expressions that make
849  // hierarchy-walking expensive.
850  e = e->IgnoreParenCasts();
851
852  if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
853    const BlockDecl *block = be->getBlockDecl();
854    for (BlockDecl::capture_const_iterator i = block->capture_begin(),
855           e = block->capture_end(); i != e; ++i) {
856      if (i->getVariable() == &var)
857        return true;
858    }
859
860    // No need to walk into the subexpressions.
861    return false;
862  }
863
864  for (Stmt::const_child_range children = e->children(); children; ++children)
865    if (isCapturedBy(var, cast<Expr>(*children)))
866      return true;
867
868  return false;
869}
870
871/// \brief Determine whether the given initializer is trivial in the sense
872/// that it requires no code to be generated.
873static bool isTrivialInitializer(const Expr *Init) {
874  if (!Init)
875    return true;
876
877  if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
878    if (CXXConstructorDecl *Constructor = Construct->getConstructor())
879      if (Constructor->isTrivial() &&
880          Constructor->isDefaultConstructor() &&
881          !Construct->requiresZeroInitialization())
882        return true;
883
884  return false;
885}
886void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
887  assert(emission.Variable && "emission was not valid!");
888
889  // If this was emitted as a global constant, we're done.
890  if (emission.wasEmittedAsGlobal()) return;
891
892  const VarDecl &D = *emission.Variable;
893  QualType type = D.getType();
894
895  // If this local has an initializer, emit it now.
896  const Expr *Init = D.getInit();
897
898  // If we are at an unreachable point, we don't need to emit the initializer
899  // unless it contains a label.
900  if (!HaveInsertPoint()) {
901    if (!Init || !ContainsLabel(Init)) return;
902    EnsureInsertPoint();
903  }
904
905  // Initialize the structure of a __block variable.
906  if (emission.IsByRef)
907    emitByrefStructureInit(emission);
908
909  if (isTrivialInitializer(Init))
910    return;
911
912
913  CharUnits alignment = emission.Alignment;
914
915  // Check whether this is a byref variable that's potentially
916  // captured and moved by its own initializer.  If so, we'll need to
917  // emit the initializer first, then copy into the variable.
918  bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
919
920  llvm::Value *Loc =
921    capturedByInit ? emission.Address : emission.getObjectAddress(*this);
922
923  if (!emission.IsConstantAggregate) {
924    LValue lv = MakeAddrLValue(Loc, type, alignment.getQuantity());
925    lv.setNonGC(true);
926    return EmitExprAsInit(Init, &D, lv, capturedByInit);
927  }
928
929  // If this is a simple aggregate initialization, we can optimize it
930  // in various ways.
931  assert(!capturedByInit && "constant init contains a capturing block?");
932
933  bool isVolatile = type.isVolatileQualified();
934
935  llvm::Constant *constant = CGM.EmitConstantExpr(D.getInit(), type, this);
936  assert(constant != 0 && "Wasn't a simple constant init?");
937
938  llvm::Value *SizeVal =
939    llvm::ConstantInt::get(IntPtrTy,
940                           getContext().getTypeSizeInChars(type).getQuantity());
941
942  const llvm::Type *BP = Int8PtrTy;
943  if (Loc->getType() != BP)
944    Loc = Builder.CreateBitCast(Loc, BP, "tmp");
945
946  // If the initializer is all or mostly zeros, codegen with memset then do
947  // a few stores afterward.
948  if (shouldUseMemSetPlusStoresToInitialize(constant,
949                CGM.getTargetData().getTypeAllocSize(constant->getType()))) {
950    Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
951                         alignment.getQuantity(), isVolatile);
952    if (!constant->isNullValue()) {
953      Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
954      emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
955    }
956  } else {
957    // Otherwise, create a temporary global with the initializer then
958    // memcpy from the global to the alloca.
959    std::string Name = GetStaticDeclName(*this, D, ".");
960    llvm::GlobalVariable *GV =
961      new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
962                               llvm::GlobalValue::InternalLinkage,
963                               constant, Name, 0, false, 0);
964    GV->setAlignment(alignment.getQuantity());
965    GV->setUnnamedAddr(true);
966
967    llvm::Value *SrcPtr = GV;
968    if (SrcPtr->getType() != BP)
969      SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp");
970
971    Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
972                         isVolatile);
973  }
974}
975
976/// Emit an expression as an initializer for a variable at the given
977/// location.  The expression is not necessarily the normal
978/// initializer for the variable, and the address is not necessarily
979/// its normal location.
980///
981/// \param init the initializing expression
982/// \param var the variable to act as if we're initializing
983/// \param loc the address to initialize; its type is a pointer
984///   to the LLVM mapping of the variable's type
985/// \param alignment the alignment of the address
986/// \param capturedByInit true if the variable is a __block variable
987///   whose address is potentially changed by the initializer
988void CodeGenFunction::EmitExprAsInit(const Expr *init,
989                                     const ValueDecl *D,
990                                     LValue lvalue,
991                                     bool capturedByInit) {
992  QualType type = D->getType();
993
994  if (type->isReferenceType()) {
995    RValue rvalue = EmitReferenceBindingToExpr(init, D);
996    if (capturedByInit)
997      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
998    EmitStoreThroughLValue(rvalue, lvalue);
999  } else if (!hasAggregateLLVMType(type)) {
1000    EmitScalarInit(init, D, lvalue, capturedByInit);
1001  } else if (type->isAnyComplexType()) {
1002    ComplexPairTy complex = EmitComplexExpr(init);
1003    if (capturedByInit)
1004      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
1005    StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile());
1006  } else {
1007    // TODO: how can we delay here if D is captured by its initializer?
1008    EmitAggExpr(init, AggValueSlot::forLValue(lvalue, true, false));
1009  }
1010}
1011
1012/// Enter a destroy cleanup for the given local variable.
1013void CodeGenFunction::emitAutoVarTypeCleanup(
1014                            const CodeGenFunction::AutoVarEmission &emission,
1015                            QualType::DestructionKind dtorKind) {
1016  assert(dtorKind != QualType::DK_none);
1017
1018  // Note that for __block variables, we want to destroy the
1019  // original stack object, not the possibly forwarded object.
1020  llvm::Value *addr = emission.getObjectAddress(*this);
1021
1022  const VarDecl *var = emission.Variable;
1023  QualType type = var->getType();
1024
1025  CleanupKind cleanupKind = NormalAndEHCleanup;
1026  CodeGenFunction::Destroyer *destroyer = 0;
1027
1028  switch (dtorKind) {
1029  case QualType::DK_none:
1030    llvm_unreachable("no cleanup for trivially-destructible variable");
1031
1032  case QualType::DK_cxx_destructor:
1033    // If there's an NRVO flag on the emission, we need a different
1034    // cleanup.
1035    if (emission.NRVOFlag) {
1036      assert(!type->isArrayType());
1037      CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1038      EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1039                                               emission.NRVOFlag);
1040      return;
1041    }
1042    break;
1043
1044  case QualType::DK_objc_strong_lifetime:
1045    // Suppress cleanups for pseudo-strong variables.
1046    if (var->isARCPseudoStrong()) return;
1047
1048    // Otherwise, consider whether to use an EH cleanup or not.
1049    cleanupKind = getARCCleanupKind();
1050
1051    // Use the imprecise destroyer by default.
1052    if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1053      destroyer = CodeGenFunction::destroyARCStrongImprecise;
1054    break;
1055
1056  case QualType::DK_objc_weak_lifetime:
1057    break;
1058  }
1059
1060  // If we haven't chosen a more specific destroyer, use the default.
1061  if (!destroyer) destroyer = &getDestroyer(dtorKind);
1062  EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer);
1063}
1064
1065void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
1066  assert(emission.Variable && "emission was not valid!");
1067
1068  // If this was emitted as a global constant, we're done.
1069  if (emission.wasEmittedAsGlobal()) return;
1070
1071  const VarDecl &D = *emission.Variable;
1072
1073  // Check the type for a cleanup.
1074  if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1075    emitAutoVarTypeCleanup(emission, dtorKind);
1076
1077  // In GC mode, honor objc_precise_lifetime.
1078  if (getLangOptions().getGCMode() != LangOptions::NonGC &&
1079      D.hasAttr<ObjCPreciseLifetimeAttr>()) {
1080    EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
1081  }
1082
1083  // Handle the cleanup attribute.
1084  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
1085    const FunctionDecl *FD = CA->getFunctionDecl();
1086
1087    llvm::Constant *F = CGM.GetAddrOfFunction(FD);
1088    assert(F && "Could not find function!");
1089
1090    const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD);
1091    EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
1092  }
1093
1094  // If this is a block variable, call _Block_object_destroy
1095  // (on the unforwarded address).
1096  if (emission.IsByRef)
1097    enterByrefCleanup(emission);
1098}
1099
1100CodeGenFunction::Destroyer &
1101CodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1102  // This is surprisingly compiler-dependent.  GCC 4.2 can't bind
1103  // references to functions directly in returns, and using '*&foo'
1104  // confuses MSVC.  Luckily, the following code pattern works in both.
1105  Destroyer *destroyer = 0;
1106  switch (kind) {
1107  case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
1108  case QualType::DK_cxx_destructor:
1109    destroyer = &destroyCXXObject;
1110    break;
1111  case QualType::DK_objc_strong_lifetime:
1112    destroyer = &destroyARCStrongPrecise;
1113    break;
1114  case QualType::DK_objc_weak_lifetime:
1115    destroyer = &destroyARCWeak;
1116    break;
1117  }
1118  return *destroyer;
1119}
1120
1121void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
1122                                  QualType type, Destroyer &destroyer) {
1123  EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer);
1124}
1125
1126void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
1127                                  Destroyer &destroyer) {
1128  const ArrayType *arrayType = getContext().getAsArrayType(type);
1129  if (!arrayType)
1130    return destroyer(*this, addr, type);
1131
1132  llvm::Value *begin = addr;
1133  llvm::Value *length = emitArrayLength(arrayType, type, begin);
1134  llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1135  emitArrayDestroy(begin, end, type, destroyer);
1136}
1137
1138void CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1139                                       llvm::Value *end,
1140                                       QualType type,
1141                                       Destroyer &destroyer) {
1142  assert(!type->isArrayType());
1143
1144  // The basic structure here is a do-while loop, because we don't
1145  // need to check for the zero-element case.
1146  llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1147  llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1148
1149  // Enter the loop body, making that address the current address.
1150  llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1151  EmitBlock(bodyBB);
1152  llvm::PHINode *elementPast =
1153    Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1154  elementPast->addIncoming(end, entryBB);
1155
1156  // Shift the address back by one element.
1157  llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1158  llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1159                                                   "arraydestroy.element");
1160
1161  // Perform the actual destruction there.
1162  destroyer(*this, element, type);
1163
1164  // Check whether we've reached the end.
1165  llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1166  Builder.CreateCondBr(done, doneBB, bodyBB);
1167  elementPast->addIncoming(element, Builder.GetInsertBlock());
1168
1169  // Done.
1170  EmitBlock(doneBB);
1171}
1172
1173namespace {
1174  class PartialArrayDestroy : public EHScopeStack::Cleanup {
1175    llvm::Value *ArrayBegin;
1176    llvm::Value *ArrayEndPointer;
1177    QualType ElementType;
1178    CodeGenFunction::Destroyer &Destroyer;
1179  public:
1180    PartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEndPointer,
1181                        QualType elementType,
1182                        CodeGenFunction::Destroyer *destroyer)
1183      : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1184        ElementType(elementType), Destroyer(*destroyer) {}
1185
1186    void Emit(CodeGenFunction &CGF, bool isForEH) {
1187      llvm::Value *arrayBegin = ArrayBegin;
1188      llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
1189
1190      // It's possible for the count to be zero here, so we're going
1191      // to need a check.  For the sake of prettier IR, we just want
1192      // to jump to the end of the array destroy loop.  This assumes
1193      // the structure of the IR generated by emitArrayDestroy, but
1194      // that assumption is pretty reliable.
1195      llvm::Value *earlyTest =
1196        CGF.Builder.CreateICmpEQ(arrayBegin, arrayEnd, "pad.isempty");
1197
1198      llvm::BasicBlock *nextBB = CGF.createBasicBlock("pad.arraydestroy");
1199
1200      // For now, use a conditional branch with both successors the
1201      // same.  We'll patch this later.
1202      llvm::BranchInst *br =
1203        CGF.Builder.CreateCondBr(earlyTest, nextBB, nextBB);
1204      CGF.EmitBlock(nextBB);
1205
1206      llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0);
1207
1208      // If the element type is itself an array, drill down.
1209      QualType type = ElementType;
1210      llvm::SmallVector<llvm::Value*,4> gepIndices;
1211      gepIndices.push_back(zero);
1212      while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
1213        // VLAs don't require a GEP index to walk into.
1214        if (!isa<VariableArrayType>(arrayType))
1215          gepIndices.push_back(zero);
1216        type = arrayType->getElementType();
1217      }
1218      if (gepIndices.size() != 1) {
1219        arrayBegin =
1220          CGF.Builder.CreateInBoundsGEP(arrayBegin, gepIndices.begin(),
1221                                        gepIndices.end(), "pad.arraybegin");
1222        arrayEnd =
1223          CGF.Builder.CreateInBoundsGEP(arrayEnd, gepIndices.begin(),
1224                                        gepIndices.end(), "pad.arrayend");
1225      }
1226
1227      CGF.emitArrayDestroy(arrayBegin, arrayEnd, type, Destroyer);
1228
1229      // Set the conditional branch's 'false' successor to doneBB.
1230      llvm::BasicBlock *doneBB = CGF.Builder.GetInsertBlock();
1231      assert(CGF.Builder.GetInsertPoint() == doneBB->begin());
1232      br->setSuccessor(1, doneBB);
1233    }
1234  };
1235}
1236
1237/// pushPartialArrayCleanup - Push a cleanup to destroy
1238/// already-constructed elements of the given array.  The cleanup
1239/// may be popped with DeactivateCleanupBlock.
1240///
1241/// \param elementType - the immediate element type of the array;
1242///   possibly still an array type
1243/// \param array - a value of type elementType*
1244/// \param destructionKind - the kind of destruction required
1245/// \param initializedElementCount - a value of type size_t* holding
1246///   the number of successfully-constructed elements
1247void CodeGenFunction::pushPartialArrayCleanup(llvm::Value *array,
1248                                              QualType elementType,
1249                                              Destroyer &destroyer,
1250                                              llvm::Value *arrayEndPointer) {
1251  // FIXME: can this be in a conditional expression?
1252  EHStack.pushCleanup<PartialArrayDestroy>(EHCleanup, array, arrayEndPointer,
1253                                           elementType, &destroyer);
1254}
1255
1256namespace {
1257  /// A cleanup to perform a release of an object at the end of a
1258  /// function.  This is used to balance out the incoming +1 of a
1259  /// ns_consumed argument when we can't reasonably do that just by
1260  /// not doing the initial retain for a __block argument.
1261  struct ConsumeARCParameter : EHScopeStack::Cleanup {
1262    ConsumeARCParameter(llvm::Value *param) : Param(param) {}
1263
1264    llvm::Value *Param;
1265
1266    void Emit(CodeGenFunction &CGF, bool IsForEH) {
1267      CGF.EmitARCRelease(Param, /*precise*/ false);
1268    }
1269  };
1270}
1271
1272/// Emit an alloca (or GlobalValue depending on target)
1273/// for the specified parameter and set up LocalDeclMap.
1274void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1275                                   unsigned ArgNo) {
1276  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
1277  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1278         "Invalid argument to EmitParmDecl");
1279
1280  Arg->setName(D.getName());
1281
1282  // Use better IR generation for certain implicit parameters.
1283  if (isa<ImplicitParamDecl>(D)) {
1284    // The only implicit argument a block has is its literal.
1285    if (BlockInfo) {
1286      LocalDeclMap[&D] = Arg;
1287
1288      if (CGDebugInfo *DI = getDebugInfo()) {
1289        DI->setLocation(D.getLocation());
1290        DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder);
1291      }
1292
1293      return;
1294    }
1295  }
1296
1297  QualType Ty = D.getType();
1298
1299  llvm::Value *DeclPtr;
1300  // If this is an aggregate or variable sized value, reuse the input pointer.
1301  if (!Ty->isConstantSizeType() ||
1302      CodeGenFunction::hasAggregateLLVMType(Ty)) {
1303    DeclPtr = Arg;
1304  } else {
1305    // Otherwise, create a temporary to hold the value.
1306    DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr");
1307
1308    bool doStore = true;
1309
1310    Qualifiers qs = Ty.getQualifiers();
1311
1312    if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1313      // We honor __attribute__((ns_consumed)) for types with lifetime.
1314      // For __strong, it's handled by just skipping the initial retain;
1315      // otherwise we have to balance out the initial +1 with an extra
1316      // cleanup to do the release at the end of the function.
1317      bool isConsumed = D.hasAttr<NSConsumedAttr>();
1318
1319      // 'self' is always formally __strong, but if this is not an
1320      // init method then we don't want to retain it.
1321      if (D.isARCPseudoStrong()) {
1322        const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1323        assert(&D == method->getSelfDecl());
1324        assert(lt == Qualifiers::OCL_Strong);
1325        assert(qs.hasConst());
1326        assert(method->getMethodFamily() != OMF_init);
1327        (void) method;
1328        lt = Qualifiers::OCL_ExplicitNone;
1329      }
1330
1331      if (lt == Qualifiers::OCL_Strong) {
1332        if (!isConsumed)
1333          // Don't use objc_retainBlock for block pointers, because we
1334          // don't want to Block_copy something just because we got it
1335          // as a parameter.
1336          Arg = EmitARCRetainNonBlock(Arg);
1337      } else {
1338        // Push the cleanup for a consumed parameter.
1339        if (isConsumed)
1340          EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg);
1341
1342        if (lt == Qualifiers::OCL_Weak) {
1343          EmitARCInitWeak(DeclPtr, Arg);
1344          doStore = false; // The weak init is a store, no need to do two
1345        }
1346      }
1347
1348      // Enter the cleanup scope.
1349      EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1350    }
1351
1352    // Store the initial value into the alloca.
1353    if (doStore) {
1354      LValue lv = MakeAddrLValue(DeclPtr, Ty,
1355                                 getContext().getDeclAlign(&D).getQuantity());
1356      EmitStoreOfScalar(Arg, lv);
1357    }
1358  }
1359
1360  llvm::Value *&DMEntry = LocalDeclMap[&D];
1361  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
1362  DMEntry = DeclPtr;
1363
1364  // Emit debug info for param declaration.
1365  if (CGDebugInfo *DI = getDebugInfo())
1366    DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1367}
1368