15f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===//
25f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
35f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//                     The LLVM Compiler Infrastructure
45f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
50bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// This file is distributed under the University of Illinois Open Source
60bc735ffcfb223c0186419547abaa5c84482663eChris Lattner// License. See LICENSE.TXT for details.
75f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
85f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
95f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
105f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer// This contains code to emit Decl nodes as LLVM code.
115f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//
125f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer//===----------------------------------------------------------------------===//
135f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
145f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer#include "CodeGenFunction.h"
1555fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "CGDebugInfo.h"
168c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne#include "CGOpenCLRuntime.h"
1755fc873017f10f6f566b182b70f6fc22aefa3464Chandler Carruth#include "CodeGenModule.h"
18de7fb8413b13651fd85b7125d08b3c9ac2816d9dDaniel Dunbar#include "clang/AST/ASTContext.h"
19bdc601b196c48d4cd56a5ceb45d41ae4e87371abKen Dyck#include "clang/AST/CharUnits.h"
20c4a1dea2dc56bd1357ec91b829a0b9e68229a13eDaniel Dunbar#include "clang/AST/Decl.h"
2119567ee4314ad1bb5144efbb23442f6bc54cd16cAnders Carlsson#include "clang/AST/DeclObjC.h"
228bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman#include "clang/Basic/SourceManager.h"
232621fd1d6d3c5eadcae246859f62738645df7540Chris Lattner#include "clang/Basic/TargetInfo.h"
2406057cef0bcd7804e80f3ce2bbe352178396c715Chandler Carruth#include "clang/Frontend/CodeGenOptions.h"
253b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/DataLayout.h"
263b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/GlobalVariable.h"
273b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/Intrinsics.h"
283b844ba7d5be205a9b4f5f0b0d1b7978977f4b8cChandler Carruth#include "llvm/IR/Type.h"
295f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace clang;
305f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencerusing namespace CodeGen;
315f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
325f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
335f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencervoid CodeGenFunction::EmitDecl(const Decl &D) {
345f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  switch (D.getKind()) {
3508688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::TranslationUnit:
3608688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::Namespace:
3708688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::UnresolvedUsingTypename:
3808688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ClassTemplateSpecialization:
3908688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ClassTemplatePartialSpecialization:
40ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  case Decl::VarTemplateSpecialization:
41ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  case Decl::VarTemplatePartialSpecialization:
4208688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::TemplateTypeParm:
4308688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::UnresolvedUsingValue:
449a55591af3e5506b95a9718e15380129fbfc5ebcSean Hunt  case Decl::NonTypeTemplateParm:
4508688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::CXXMethod:
4608688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::CXXConstructor:
4708688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::CXXDestructor:
4808688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::CXXConversion:
4908688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::Field:
5076da55d3a49e1805f51b1ced7c5da5bcd7f759d8John McCall  case Decl::MSProperty:
5141f5e66d44ae1142df82f40d4445c4a5710fa423Francois Pichet  case Decl::IndirectField:
5208688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ObjCIvar:
53e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher  case Decl::ObjCAtDefsField:
54aa9fc46c6a797c86ae004092ab4f2b1bed6c4616Chris Lattner  case Decl::ParmVar:
5508688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ImplicitParam:
5608688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ClassTemplate:
57ef4579cda09b73e3d4d98af48201da25adc29326Larisse Voufo  case Decl::VarTemplate:
5808688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::FunctionTemplate:
593e4c6c4c79a03f5cb0c4671d7c282d623c6dc35eRichard Smith  case Decl::TypeAliasTemplate:
6008688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::TemplateTemplateParm:
6108688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ObjCMethod:
6208688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ObjCCategory:
6308688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ObjCProtocol:
6408688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ObjCInterface:
6508688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ObjCCategoryImpl:
6608688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ObjCImplementation:
6708688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ObjCProperty:
6808688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ObjCCompatibleAlias:
696206d53f67613958ae1b023aba337ebb46f11a8bAbramo Bagnara  case Decl::AccessSpec:
7008688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::LinkageSpec:
7108688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::ObjCPropertyImpl:
7208688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::FileScopeAsm:
7308688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::Friend:
7408688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::FriendTemplate:
7508688ac8aaf02b565619181903319d32b546bcf5Douglas Gregor  case Decl::Block:
766afcf8875d4e447645cd7bf3733dd8e2eb8455dcTareq A. Siraj  case Decl::Captured:
77af0f4d0b2e38c810effc8b024ad2fb6604eec5d3Francois Pichet  case Decl::ClassScopeFunctionSpecialization:
789faebd23fd69ac1591520e811dfa5b25f73012f3David Blaikie  case Decl::UsingShadow:
79b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie    llvm_unreachable("Declaration should not be in declstmts!");
805f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  case Decl::Function:  // void X();
8135bc0821c4f80041724cd4c5c4889b2581546a41Argyrios Kyrtzidis  case Decl::Record:    // struct/union/class X;
825f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  case Decl::Enum:      // enum X;
831eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump  case Decl::EnumConstant: // enum ? { X = ? }
8435bc0821c4f80041724cd4c5c4889b2581546a41Argyrios Kyrtzidis  case Decl::CXXRecord: // struct/union/class X; [C++]
857b0ca3fa6f9e89d81db96fe51d4d73bf69d17edcAnders Carlsson  case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
864ae493cccbfbf122ec6ebac0e330232c22fa8489Chris Lattner  case Decl::Label:        // __label__ x;
8715de72cf580840c61e5704c2f8a2b56f9d0638e1Douglas Gregor  case Decl::Import:
88c640058aa7f224a71ce3b1d2601d84e1b57f82d3Alexey Bataev  case Decl::OMPThreadPrivate:
89684aa73192d92850a926870be62a1787eb5b7ed9Michael Han  case Decl::Empty:
905f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer    // None of these decls require codegen support.
915f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer    return;
92c8c24277a8cce39db95b0e05b79cbdf7e7558355David Blaikie
93fc46ebc2b1345723a894ae352cfb206c1d930295David Blaikie  case Decl::NamespaceAlias:
94fc46ebc2b1345723a894ae352cfb206c1d930295David Blaikie    if (CGDebugInfo *DI = getDebugInfo())
95fc46ebc2b1345723a894ae352cfb206c1d930295David Blaikie        DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D));
96fc46ebc2b1345723a894ae352cfb206c1d930295David Blaikie    return;
979faebd23fd69ac1591520e811dfa5b25f73012f3David Blaikie  case Decl::Using:          // using X; [C++]
989faebd23fd69ac1591520e811dfa5b25f73012f3David Blaikie    if (CGDebugInfo *DI = getDebugInfo())
999faebd23fd69ac1591520e811dfa5b25f73012f3David Blaikie        DI->EmitUsingDecl(cast<UsingDecl>(D));
1009faebd23fd69ac1591520e811dfa5b25f73012f3David Blaikie    return;
101957dac5b6d826bc0c10011c8b5c3f1b8007fda41David Blaikie  case Decl::UsingDirective: // using namespace X; [C++]
102957dac5b6d826bc0c10011c8b5c3f1b8007fda41David Blaikie    if (CGDebugInfo *DI = getDebugInfo())
103957dac5b6d826bc0c10011c8b5c3f1b8007fda41David Blaikie      DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
104957dac5b6d826bc0c10011c8b5c3f1b8007fda41David Blaikie    return;
105662174c82ef46b19a2329c7d37208e1d12dfb7b3Daniel Dunbar  case Decl::Var: {
106662174c82ef46b19a2329c7d37208e1d12dfb7b3Daniel Dunbar    const VarDecl &VD = cast<VarDecl>(D);
107b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCall    assert(VD.isLocalVarDecl() &&
108662174c82ef46b19a2329c7d37208e1d12dfb7b3Daniel Dunbar           "Should not see file-scope variables inside a function!");
109b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCall    return EmitVarDecl(VD);
110662174c82ef46b19a2329c7d37208e1d12dfb7b3Daniel Dunbar  }
1111eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
112162e1c1b487352434552147967c3dd296ebee2f7Richard Smith  case Decl::Typedef:      // typedef int X;
113162e1c1b487352434552147967c3dd296ebee2f7Richard Smith  case Decl::TypeAlias: {  // using X = int; [C++0x]
114162e1c1b487352434552147967c3dd296ebee2f7Richard Smith    const TypedefNameDecl &TD = cast<TypedefNameDecl>(D);
115fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson    QualType Ty = TD.getUnderlyingType();
1161eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
117fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson    if (Ty->isVariablyModifiedType())
118bc8d40d85f3fa1e34569834916f18fecaa635152John McCall      EmitVariablyModifiedType(Ty);
119fcdbb93749ed69aa9022437052c390522355ec3dAnders Carlsson  }
1205f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
1215f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
1225f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
123b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCall/// EmitVarDecl - This method handles emission of any variable declaration
1245f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer/// inside a function, including static vars etc.
125b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCallvoid CodeGenFunction::EmitVarDecl(const VarDecl &D) {
126713e3f25636736fe798c8603ebca56ae8d5372e8Enea Zaffanella  if (D.isStaticLocal()) {
127e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher    llvm::GlobalValue::LinkageTypes Linkage =
128f6b89a173827457c28ac77b7cf091a24ef484e8aAnders Carlsson      llvm::GlobalValue::InternalLinkage;
129f6b89a173827457c28ac77b7cf091a24ef484e8aAnders Carlsson
1307a36a5913f045bfaf6d26ed874e39a3e7c1ad9aeEli Friedman    // If the variable is externally visible, it must have weak linkage so it
1317a36a5913f045bfaf6d26ed874e39a3e7c1ad9aeEli Friedman    // can be uniqued.
1329610d77508bdca13e0475783ff404428611c9683Rafael Espindola    if (D.isExternallyVisible()) {
1337a36a5913f045bfaf6d26ed874e39a3e7c1ad9aeEli Friedman      Linkage = llvm::GlobalValue::LinkOnceODRLinkage;
13407369dde9d72213bf8a48288cd8b29999af9a40cEli Friedman
13507369dde9d72213bf8a48288cd8b29999af9a40cEli Friedman      // FIXME: We need to force the emission/use of a guard variable for
13607369dde9d72213bf8a48288cd8b29999af9a40cEli Friedman      // some variables even if we can constant-evaluate them because
13707369dde9d72213bf8a48288cd8b29999af9a40cEli Friedman      // we can't guarantee every translation unit will constant-evaluate them.
138678eca456bc62900dc7407bdbc9fa282da9d2f8fEli Friedman    }
139e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
140b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCall    return EmitStaticVarDecl(D, Linkage);
141f6b89a173827457c28ac77b7cf091a24ef484e8aAnders Carlsson  }
142713e3f25636736fe798c8603ebca56ae8d5372e8Enea Zaffanella
143713e3f25636736fe798c8603ebca56ae8d5372e8Enea Zaffanella  if (D.hasExternalStorage())
144fea90b89482aa12168b0a874775255bad89e4013Lauro Ramos Venancio    // Don't emit it now, allow it to be emitted lazily on its first use.
145fea90b89482aa12168b0a874775255bad89e4013Lauro Ramos Venancio    return;
146713e3f25636736fe798c8603ebca56ae8d5372e8Enea Zaffanella
147713e3f25636736fe798c8603ebca56ae8d5372e8Enea Zaffanella  if (D.getStorageClass() == SC_OpenCLWorkGroupLocal)
1488c25fc584ce27d59df9923f153e8a132dde58d04Peter Collingbourne    return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D);
1495466c7b0ca8ce662e2c0bc295cecba2b78d6957dDaniel Dunbar
150713e3f25636736fe798c8603ebca56ae8d5372e8Enea Zaffanella  assert(D.hasLocalStorage());
151713e3f25636736fe798c8603ebca56ae8d5372e8Enea Zaffanella  return EmitAutoVarDecl(D);
1525f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
1535f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
154761acc19d966a67f2175783d09412d6ac9463400Chris Lattnerstatic std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D,
155761acc19d966a67f2175783d09412d6ac9463400Chris Lattner                                     const char *Separator) {
156761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  CodeGenModule &CGM = CGF.CGM;
1577edf9e38b91917b661277601c0e448eef0eb2b56Richard Smith  if (CGF.getLangOpts().CPlusPlus) {
1585f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef Name = CGM.getMangledName(&D);
1599a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson    return Name.str();
160f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  }
161e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
162761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  std::string ContextName;
163faa5bfcaaf6fc5a21ae112919d368f2636c58768Fariborz Jahanian  if (!CGF.CurFuncDecl) {
164faa5bfcaaf6fc5a21ae112919d368f2636c58768Fariborz Jahanian    // Better be in a block declared in global scope.
165faa5bfcaaf6fc5a21ae112919d368f2636c58768Fariborz Jahanian    const NamedDecl *ND = cast<NamedDecl>(&D);
166faa5bfcaaf6fc5a21ae112919d368f2636c58768Fariborz Jahanian    const DeclContext *DC = ND->getDeclContext();
167faa5bfcaaf6fc5a21ae112919d368f2636c58768Fariborz Jahanian    if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
168faa5bfcaaf6fc5a21ae112919d368f2636c58768Fariborz Jahanian      MangleBuffer Name;
16914110477887e3dc168ffc6c191e72d705051f99ePeter Collingbourne      CGM.getBlockMangledName(GlobalDecl(), Name, BD);
170faa5bfcaaf6fc5a21ae112919d368f2636c58768Fariborz Jahanian      ContextName = Name.getString();
171faa5bfcaaf6fc5a21ae112919d368f2636c58768Fariborz Jahanian    }
172faa5bfcaaf6fc5a21ae112919d368f2636c58768Fariborz Jahanian    else
173b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie      llvm_unreachable("Unknown context for block static var decl");
174faa5bfcaaf6fc5a21ae112919d368f2636c58768Fariborz Jahanian  } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) {
1755f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    StringRef Name = CGM.getMangledName(FD);
1769a20d55807cc2f6534a9c51a46cc8143ed16786dAnders Carlsson    ContextName = Name.str();
177f746aa6a8f538be914173a4aef2d9a2fd9f99d17John McCall  } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl))
178761acc19d966a67f2175783d09412d6ac9463400Chris Lattner    ContextName = CGF.CurFn->getName();
179761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  else
180b219cfc4d75f0a03630b7c4509ef791b7e97b2c8David Blaikie    llvm_unreachable("Unknown context for static var decl");
181e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
182761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  return ContextName + Separator + D.getNameAsString();
183761acc19d966a67f2175783d09412d6ac9463400Chris Lattner}
184761acc19d966a67f2175783d09412d6ac9463400Chris Lattner
1850f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruthllvm::GlobalVariable *
186b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCallCodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
187b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCall                                     const char *Separator,
188b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCall                                     llvm::GlobalValue::LinkageTypes Linkage) {
1890096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbar  QualType Ty = D.getType();
1900096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbar  assert(Ty->isConstantSizeType() && "VLAs can't be static");
1910096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbar
1925c247db14566f4668efb63cf5184e62dd40039b5Benjamin Kramer  // Use the label if the variable is renamed with the asm-label extension.
1935c247db14566f4668efb63cf5184e62dd40039b5Benjamin Kramer  std::string Name;
194c3c8f2225dfb3a162020fb6a5ae61904ee5b4f5cBenjamin Kramer  if (D.hasAttr<AsmLabelAttr>())
195c3c8f2225dfb3a162020fb6a5ae61904ee5b4f5cBenjamin Kramer    Name = CGM.getMangledName(&D);
196c3c8f2225dfb3a162020fb6a5ae61904ee5b4f5cBenjamin Kramer  else
1975c247db14566f4668efb63cf5184e62dd40039b5Benjamin Kramer    Name = GetStaticDeclName(*this, D, Separator);
1980096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbar
1992acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty);
2001aba7783ad8fe326f10f5aa494721db23bdd593ePeter Collingbourne  unsigned AddrSpace =
2011aba7783ad8fe326f10f5aa494721db23bdd593ePeter Collingbourne   CGM.GetGlobalVarAddressSpace(&D, CGM.getContext().getTargetAddressSpace(Ty));
20241f8a13ac7fa734faef2d8a36feebc3c9a1eed77Anders Carlsson  llvm::GlobalVariable *GV =
20341f8a13ac7fa734faef2d8a36feebc3c9a1eed77Anders Carlsson    new llvm::GlobalVariable(CGM.getModule(), LTy,
20441f8a13ac7fa734faef2d8a36feebc3c9a1eed77Anders Carlsson                             Ty.isConstant(getContext()), Linkage,
205de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg                             CGM.EmitNullConstant(D.getType()), Name, 0,
206de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg                             llvm::GlobalVariable::NotThreadLocal,
2071aba7783ad8fe326f10f5aa494721db23bdd593ePeter Collingbourne                             AddrSpace);
2088b752f10c394b140f9ef89e049cbad1a7676fc25Ken Dyck  GV->setAlignment(getContext().getDeclAlign(&D).getQuantity());
20993cc515d3b99dca18d287d200e19355a2e9c02b2Eli Friedman  CGM.setGlobalVisibility(GV, &D);
210de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
21138afbc7361d861968232defaeaf8e302af75b5eeRichard Smith  if (D.getTLSKind())
212de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg    CGM.setTLSMode(GV, D);
213de981f3ff163bc9ec69e4c5e7316e94276412993Hans Wennborg
21441f8a13ac7fa734faef2d8a36feebc3c9a1eed77Anders Carlsson  return GV;
2150096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbar}
2160096acf421c4609ce7f43e8b05f8c5ca866d4611Daniel Dunbar
2177ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith/// hasNontrivialDestruction - Determine whether a type's destruction is
2187ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith/// non-trivial. If so, and the variable uses static initialization, we must
2197ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith/// register its destructor to run on exit.
2207ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smithstatic bool hasNontrivialDestruction(QualType T) {
2217ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2227ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  return RD && !RD->hasTrivialDestructor();
2237ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith}
2247ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith
2250f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth/// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the
2260f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth/// global variable that has already been created for it.  If the initializer
2270f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth/// has a different type than GV does, this may free GV and return a different
2280f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth/// one.  Otherwise it just returns GV.
2290f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruthllvm::GlobalVariable *
230b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCallCodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D,
2310f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth                                               llvm::GlobalVariable *GV) {
2320f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  llvm::Constant *Init = CGM.EmitConstantInit(D, this);
233bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall
234761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  // If constant emission failed, then this should be a C++ static
235761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  // initializer.
2360f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  if (!Init) {
2377edf9e38b91917b661277601c0e448eef0eb2b56Richard Smith    if (!getLangOpts().CPlusPlus)
238761acc19d966a67f2175783d09412d6ac9463400Chris Lattner      CGM.ErrorUnsupported(D.getInit(), "constant l-value expression");
2395cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall    else if (Builder.GetInsertBlock()) {
240e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher      // Since we have a static initializer, this global variable can't
241071c81065a282edba989bcf7c260b5838a59db50Anders Carlsson      // be constant.
2420f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth      GV->setConstant(false);
2435cd91b513455fd7753e8815b54f0a49bbca6602dJohn McCall
2440f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth      EmitCXXGuardedInit(D, GV, /*PerformInit*/true);
245071c81065a282edba989bcf7c260b5838a59db50Anders Carlsson    }
2460f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth    return GV;
247761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  }
248bf40cb518312dde1c07e44fcae59bc4eec65589cJohn McCall
249761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  // The initializer may differ in type from the global. Rewrite
250761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  // the global to match the initializer.  (We have to do this
251761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  // because some types, like unions, can't be completely represented
252761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  // in the LLVM type system.)
2530f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  if (GV->getType()->getElementType() != Init->getType()) {
2540f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth    llvm::GlobalVariable *OldGV = GV;
2550f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth
2560f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth    GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
2570f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth                                  OldGV->isConstant(),
2580f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth                                  OldGV->getLinkage(), Init, "",
2590f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth                                  /*InsertBefore*/ OldGV,
2605e2d5dec7736f6f9292d4212dec67295909f1328Hans Wennborg                                  OldGV->getThreadLocalMode(),
2610f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth                           CGM.getContext().getTargetAddressSpace(D.getType()));
2620f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth    GV->setVisibility(OldGV->getVisibility());
263e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
264761acc19d966a67f2175783d09412d6ac9463400Chris Lattner    // Steal the name of the old global
2650f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth    GV->takeName(OldGV);
266e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
267761acc19d966a67f2175783d09412d6ac9463400Chris Lattner    // Replace all uses of the old global with the new global
2680f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth    llvm::Constant *NewPtrForOldDecl =
2690f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth    llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2700f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth    OldGV->replaceAllUsesWith(NewPtrForOldDecl);
271e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
272761acc19d966a67f2175783d09412d6ac9463400Chris Lattner    // Erase the old global, since it is no longer used.
2730f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth    OldGV->eraseFromParent();
274761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  }
275e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
2760f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  GV->setConstant(CGM.isTypeConstant(D.getType(), true));
2770f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  GV->setInitializer(Init);
2787ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith
2797ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  if (hasNontrivialDestruction(D.getType())) {
2807ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith    // We have a constant initializer, but a nontrivial destructor. We still
2817ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith    // need to perform a guarded "initialization" in order to register the
282a9b21d22bb9337649723a8477b5cb15f83451e7dRichard Smith    // destructor.
2830f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth    EmitCXXGuardedInit(D, GV, /*PerformInit*/false);
2847ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith  }
2857ca4850a3e3530fa6c93b64b740446e32c97f992Richard Smith
2860f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  return GV;
287761acc19d966a67f2175783d09412d6ac9463400Chris Lattner}
288761acc19d966a67f2175783d09412d6ac9463400Chris Lattner
289b6bbcc9995186799a60ce17d0c1acff31601653aJohn McCallvoid CodeGenFunction::EmitStaticVarDecl(const VarDecl &D,
290f6b89a173827457c28ac77b7cf091a24ef484e8aAnders Carlsson                                      llvm::GlobalValue::LinkageTypes Linkage) {
2910f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  llvm::Value *&DMEntry = LocalDeclMap[&D];
2920f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
2931eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
294355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  // Check to see if we already have a global variable for this
295355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  // declaration.  This can happen when double-emitting function
296355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  // bodies, e.g. with complete and base constructors.
297355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  llvm::Constant *addr =
298355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall    CGM.getStaticLocalDeclAddress(&D);
299355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall
300355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  llvm::GlobalVariable *var;
301355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  if (addr) {
302355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall    var = cast<llvm::GlobalVariable>(addr->stripPointerCasts());
303355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  } else {
304355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall    addr = var = CreateStaticVarDecl(D, ".", Linkage);
305355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  }
306a985b31fc36aa22859983b4a5e7385796c627bdcDaniel Dunbar
307e5731f81497d11f95027a500a3ee118f4fc9e1beDaniel Dunbar  // Store into LocalDeclMap before generating initializer to handle
308e5731f81497d11f95027a500a3ee118f4fc9e1beDaniel Dunbar  // circular references.
309355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  DMEntry = addr;
310355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  CGM.setStaticLocalDeclAddress(&D, addr);
311e5731f81497d11f95027a500a3ee118f4fc9e1beDaniel Dunbar
312fe67f3bfc09caa66ab1398c03418c35bea77caf4John McCall  // We can't have a VLA here, but we can have a pointer to a VLA,
313fe67f3bfc09caa66ab1398c03418c35bea77caf4John McCall  // even though that doesn't really make any sense.
314c62aad8f45ec3dd893376bd1c51e5e8019a76d8eEli Friedman  // Make sure to evaluate VLA bounds now so that we have them for later.
315c62aad8f45ec3dd893376bd1c51e5e8019a76d8eEli Friedman  if (D.getType()->isVariablyModifiedType())
316bc8d40d85f3fa1e34569834916f18fecaa635152John McCall    EmitVariablyModifiedType(D.getType());
317e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
318355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  // Save the type in case adding the initializer forces a type change.
319355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  llvm::Type *expectedType = addr->getType();
320c62aad8f45ec3dd893376bd1c51e5e8019a76d8eEli Friedman
321761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  // If this value has an initializer, emit it.
322761acc19d966a67f2175783d09412d6ac9463400Chris Lattner  if (D.getInit())
323355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall    var = AddInitializerToStaticVarDecl(D, var);
3248bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
325355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  var->setAlignment(getContext().getDeclAlign(&D).getQuantity());
3260af9523607754a945b49d8a1ebae6631fc927921Chris Lattner
32777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D.hasAttr<AnnotateAttr>())
328355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall    CGM.AddGlobalAnnotations(&D, var);
3298bd4afeb876fd0015bb808eb2f3de1fe709658a7Nate Begeman
33040b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const SectionAttr *SA = D.getAttr<SectionAttr>())
331355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall    var->setSection(SA->getName());
3321eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
33340b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (D.hasAttr<UsedAttr>())
334355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall    CGM.AddUsedGlobal(var);
3350f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth
3360f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  // We may have to cast the constant because of the initializer
3370f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  // mismatch above.
3380f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  //
3390f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  // FIXME: It is really dangerous to store this in the map; if anyone
3400f30a12ce7b3d4d86c9ca9072f587da77c8eef34Chandler Carruth  // RAUW's the GV uses of this constant will be invalid.
341355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType);
342355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  DMEntry = castedAddr;
343355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall  CGM.setStaticLocalDeclAddress(&D, castedAddr);
344686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta
345686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  // Emit global variable debug descriptor for static vars.
346e896d98548b02223c7740d807a0aa6e20fba7079Anders Carlsson  CGDebugInfo *DI = getDebugInfo();
347fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov  if (DI &&
3484cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor      CGM.getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
34966031a5594bc9a7dc0dc5137c3e7955f835e4639Daniel Dunbar    DI->setLocation(D.getLocation());
350355bba72ca52c4a70ca3c3802412c03a6ec31f24John McCall    DI->EmitGlobalVariable(var, &D);
351686226b538e72c5059ab7c9a8f87eb883193b645Sanjiv Gupta  }
3521a86b33c1870fee08d281c9f07ac1280195a7faeAnders Carlsson}
3531eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
354da65ea86482bc116906edfb9ba1d7124f76cc867John McCallnamespace {
355bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  struct DestroyObject : EHScopeStack::Cleanup {
356bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    DestroyObject(llvm::Value *addr, QualType type,
3572673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                  CodeGenFunction::Destroyer *destroyer,
3582673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                  bool useEHCleanupForArray)
359516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne      : addr(addr), type(type), destroyer(destroyer),
3602673c68aa58e277ebc755b71d81aca618cdedbf9John McCall        useEHCleanupForArray(useEHCleanupForArray) {}
361da65ea86482bc116906edfb9ba1d7124f76cc867John McCall
362bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    llvm::Value *addr;
363bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    QualType type;
364516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne    CodeGenFunction::Destroyer *destroyer;
3652673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    bool useEHCleanupForArray;
366da65ea86482bc116906edfb9ba1d7124f76cc867John McCall
367ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall    void Emit(CodeGenFunction &CGF, Flags flags) {
3682673c68aa58e277ebc755b71d81aca618cdedbf9John McCall      // Don't use an EH cleanup recursively from an EH cleanup.
369ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall      bool useEHCleanupForArray =
370ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall        flags.isForNormalCleanup() && this->useEHCleanupForArray;
3712673c68aa58e277ebc755b71d81aca618cdedbf9John McCall
3722673c68aa58e277ebc755b71d81aca618cdedbf9John McCall      CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray);
373da65ea86482bc116906edfb9ba1d7124f76cc867John McCall    }
374da65ea86482bc116906edfb9ba1d7124f76cc867John McCall  };
375da65ea86482bc116906edfb9ba1d7124f76cc867John McCall
376bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  struct DestroyNRVOVariable : EHScopeStack::Cleanup {
377bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    DestroyNRVOVariable(llvm::Value *addr,
378bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall                        const CXXDestructorDecl *Dtor,
379bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall                        llvm::Value *NRVOFlag)
380bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall      : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {}
381da65ea86482bc116906edfb9ba1d7124f76cc867John McCall
382da65ea86482bc116906edfb9ba1d7124f76cc867John McCall    const CXXDestructorDecl *Dtor;
383da65ea86482bc116906edfb9ba1d7124f76cc867John McCall    llvm::Value *NRVOFlag;
384da65ea86482bc116906edfb9ba1d7124f76cc867John McCall    llvm::Value *Loc;
385da65ea86482bc116906edfb9ba1d7124f76cc867John McCall
386ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall    void Emit(CodeGenFunction &CGF, Flags flags) {
387da65ea86482bc116906edfb9ba1d7124f76cc867John McCall      // Along the exceptions path we always execute the dtor.
388ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall      bool NRVO = flags.isForNormalCleanup() && NRVOFlag;
389da65ea86482bc116906edfb9ba1d7124f76cc867John McCall
390da65ea86482bc116906edfb9ba1d7124f76cc867John McCall      llvm::BasicBlock *SkipDtorBB = 0;
391da65ea86482bc116906edfb9ba1d7124f76cc867John McCall      if (NRVO) {
392da65ea86482bc116906edfb9ba1d7124f76cc867John McCall        // If we exited via NRVO, we skip the destructor call.
393da65ea86482bc116906edfb9ba1d7124f76cc867John McCall        llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused");
394da65ea86482bc116906edfb9ba1d7124f76cc867John McCall        SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor");
395da65ea86482bc116906edfb9ba1d7124f76cc867John McCall        llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val");
396da65ea86482bc116906edfb9ba1d7124f76cc867John McCall        CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB);
397da65ea86482bc116906edfb9ba1d7124f76cc867John McCall        CGF.EmitBlock(RunDtorBB);
398da65ea86482bc116906edfb9ba1d7124f76cc867John McCall      }
399e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
400da65ea86482bc116906edfb9ba1d7124f76cc867John McCall      CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete,
401378e1e739aed97e9b278beeb20e9f5bbe34c0232Douglas Gregor                                /*ForVirtualBase=*/false,
402378e1e739aed97e9b278beeb20e9f5bbe34c0232Douglas Gregor                                /*Delegating=*/false,
403378e1e739aed97e9b278beeb20e9f5bbe34c0232Douglas Gregor                                Loc);
404da65ea86482bc116906edfb9ba1d7124f76cc867John McCall
405da65ea86482bc116906edfb9ba1d7124f76cc867John McCall      if (NRVO) CGF.EmitBlock(SkipDtorBB);
406da65ea86482bc116906edfb9ba1d7124f76cc867John McCall    }
407da65ea86482bc116906edfb9ba1d7124f76cc867John McCall  };
408da65ea86482bc116906edfb9ba1d7124f76cc867John McCall
4091f0fca54676cfa8616e7f3cd7a26788ab937e3cdJohn McCall  struct CallStackRestore : EHScopeStack::Cleanup {
410d87150999833d756269d84ca6e4127dc99fdcf63John McCall    llvm::Value *Stack;
411d87150999833d756269d84ca6e4127dc99fdcf63John McCall    CallStackRestore(llvm::Value *Stack) : Stack(Stack) {}
412ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall    void Emit(CodeGenFunction &CGF, Flags flags) {
413578faa837b552403e2002b97fdfbfde14f2448e5Benjamin Kramer      llvm::Value *V = CGF.Builder.CreateLoad(Stack);
414d87150999833d756269d84ca6e4127dc99fdcf63John McCall      llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
415d87150999833d756269d84ca6e4127dc99fdcf63John McCall      CGF.Builder.CreateCall(F, V);
416d87150999833d756269d84ca6e4127dc99fdcf63John McCall    }
417d87150999833d756269d84ca6e4127dc99fdcf63John McCall  };
418d87150999833d756269d84ca6e4127dc99fdcf63John McCall
4190c24c808e4dce43e88abf2d5f98546b901bd4315John McCall  struct ExtendGCLifetime : EHScopeStack::Cleanup {
4200c24c808e4dce43e88abf2d5f98546b901bd4315John McCall    const VarDecl &Var;
4210c24c808e4dce43e88abf2d5f98546b901bd4315John McCall    ExtendGCLifetime(const VarDecl *var) : Var(*var) {}
4220c24c808e4dce43e88abf2d5f98546b901bd4315John McCall
423ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall    void Emit(CodeGenFunction &CGF, Flags flags) {
4240c24c808e4dce43e88abf2d5f98546b901bd4315John McCall      // Compute the address of the local variable, in case it's a
4250c24c808e4dce43e88abf2d5f98546b901bd4315John McCall      // byref or something.
426f4b88a45902af1802a1cb42ba48b1c474474f228John McCall      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
427f4b88a45902af1802a1cb42ba48b1c474474f228John McCall                      Var.getType(), VK_LValue, SourceLocation());
4280c24c808e4dce43e88abf2d5f98546b901bd4315John McCall      llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE));
4290c24c808e4dce43e88abf2d5f98546b901bd4315John McCall      CGF.EmitExtendGCLifetime(value);
4300c24c808e4dce43e88abf2d5f98546b901bd4315John McCall    }
4310c24c808e4dce43e88abf2d5f98546b901bd4315John McCall  };
4320c24c808e4dce43e88abf2d5f98546b901bd4315John McCall
4331f0fca54676cfa8616e7f3cd7a26788ab937e3cdJohn McCall  struct CallCleanupFunction : EHScopeStack::Cleanup {
434d87150999833d756269d84ca6e4127dc99fdcf63John McCall    llvm::Constant *CleanupFn;
435d87150999833d756269d84ca6e4127dc99fdcf63John McCall    const CGFunctionInfo &FnInfo;
436d87150999833d756269d84ca6e4127dc99fdcf63John McCall    const VarDecl &Var;
437e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
438d87150999833d756269d84ca6e4127dc99fdcf63John McCall    CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info,
43934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall                        const VarDecl *Var)
44034695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall      : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {}
441d87150999833d756269d84ca6e4127dc99fdcf63John McCall
442ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall    void Emit(CodeGenFunction &CGF, Flags flags) {
443f4b88a45902af1802a1cb42ba48b1c474474f228John McCall      DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false,
444f4b88a45902af1802a1cb42ba48b1c474474f228John McCall                      Var.getType(), VK_LValue, SourceLocation());
44534695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall      // Compute the address of the local variable, in case it's a byref
44634695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall      // or something.
44734695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall      llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress();
44834695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
449d87150999833d756269d84ca6e4127dc99fdcf63John McCall      // In some cases, the type of the function argument will be different from
450d87150999833d756269d84ca6e4127dc99fdcf63John McCall      // the type of the pointer. An example of this is
451d87150999833d756269d84ca6e4127dc99fdcf63John McCall      // void f(void* arg);
452d87150999833d756269d84ca6e4127dc99fdcf63John McCall      // __attribute__((cleanup(f))) void *g;
453d87150999833d756269d84ca6e4127dc99fdcf63John McCall      //
454d87150999833d756269d84ca6e4127dc99fdcf63John McCall      // To fix this we insert a bitcast here.
455d87150999833d756269d84ca6e4127dc99fdcf63John McCall      QualType ArgTy = FnInfo.arg_begin()->type;
456d87150999833d756269d84ca6e4127dc99fdcf63John McCall      llvm::Value *Arg =
457d87150999833d756269d84ca6e4127dc99fdcf63John McCall        CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy));
458d87150999833d756269d84ca6e4127dc99fdcf63John McCall
459d87150999833d756269d84ca6e4127dc99fdcf63John McCall      CallArgList Args;
46004c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman      Args.add(RValue::get(Arg),
46104c9a49ee251424b11d7c4e8b1c23637684cecb6Eli Friedman               CGF.getContext().getPointerType(Var.getType()));
462d87150999833d756269d84ca6e4127dc99fdcf63John McCall      CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args);
463d87150999833d756269d84ca6e4127dc99fdcf63John McCall    }
464d87150999833d756269d84ca6e4127dc99fdcf63John McCall  };
465495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem
466495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  /// A cleanup to call @llvm.lifetime.end.
467495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  class CallLifetimeEnd : public EHScopeStack::Cleanup {
468495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem    llvm::Value *Addr;
469495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem    llvm::Value *Size;
470495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  public:
471495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem    CallLifetimeEnd(llvm::Value *addr, llvm::Value *size)
472495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem      : Addr(addr), Size(size) {}
473495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem
474495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem    void Emit(CodeGenFunction &CGF, Flags flags) {
475495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem      llvm::Value *castAddr = CGF.Builder.CreateBitCast(Addr, CGF.Int8PtrTy);
476495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem      CGF.Builder.CreateCall2(CGF.CGM.getLLVMLifetimeEndFn(),
477495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem                              Size, castAddr)
478495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem        ->setDoesNotThrow();
479495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem    }
480495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  };
481d87150999833d756269d84ca6e4127dc99fdcf63John McCall}
482d87150999833d756269d84ca6e4127dc99fdcf63John McCall
483f85e193739c953358c865005855253af4f68a497John McCall/// EmitAutoVarWithLifetime - Does the setup required for an automatic
484f85e193739c953358c865005855253af4f68a497John McCall/// variable with lifetime.
485f85e193739c953358c865005855253af4f68a497John McCallstatic void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var,
486f85e193739c953358c865005855253af4f68a497John McCall                                    llvm::Value *addr,
487f85e193739c953358c865005855253af4f68a497John McCall                                    Qualifiers::ObjCLifetime lifetime) {
488f85e193739c953358c865005855253af4f68a497John McCall  switch (lifetime) {
489f85e193739c953358c865005855253af4f68a497John McCall  case Qualifiers::OCL_None:
490f85e193739c953358c865005855253af4f68a497John McCall    llvm_unreachable("present but none");
491f85e193739c953358c865005855253af4f68a497John McCall
492f85e193739c953358c865005855253af4f68a497John McCall  case Qualifiers::OCL_ExplicitNone:
493f85e193739c953358c865005855253af4f68a497John McCall    // nothing to do
494f85e193739c953358c865005855253af4f68a497John McCall    break;
495f85e193739c953358c865005855253af4f68a497John McCall
496f85e193739c953358c865005855253af4f68a497John McCall  case Qualifiers::OCL_Strong: {
497516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne    CodeGenFunction::Destroyer *destroyer =
4989928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall      (var.hasAttr<ObjCPreciseLifetimeAttr>()
4999928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall       ? CodeGenFunction::destroyARCStrongPrecise
5009928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall       : CodeGenFunction::destroyARCStrongImprecise);
5019928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall
5029928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall    CleanupKind cleanupKind = CGF.getARCCleanupKind();
5039928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall    CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer,
5049928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall                    cleanupKind & EHCleanup);
505f85e193739c953358c865005855253af4f68a497John McCall    break;
506f85e193739c953358c865005855253af4f68a497John McCall  }
507f85e193739c953358c865005855253af4f68a497John McCall  case Qualifiers::OCL_Autoreleasing:
508f85e193739c953358c865005855253af4f68a497John McCall    // nothing to do
509f85e193739c953358c865005855253af4f68a497John McCall    break;
510e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
511f85e193739c953358c865005855253af4f68a497John McCall  case Qualifiers::OCL_Weak:
512f85e193739c953358c865005855253af4f68a497John McCall    // __weak objects always get EH cleanups; otherwise, exceptions
513f85e193739c953358c865005855253af4f68a497John McCall    // could cause really nasty crashes instead of mere leaks.
5149928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall    CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(),
5159928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall                    CodeGenFunction::destroyARCWeak,
5169928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall                    /*useEHCleanup*/ true);
517f85e193739c953358c865005855253af4f68a497John McCall    break;
518f85e193739c953358c865005855253af4f68a497John McCall  }
519f85e193739c953358c865005855253af4f68a497John McCall}
520f85e193739c953358c865005855253af4f68a497John McCall
521f85e193739c953358c865005855253af4f68a497John McCallstatic bool isAccessedBy(const VarDecl &var, const Stmt *s) {
522f85e193739c953358c865005855253af4f68a497John McCall  if (const Expr *e = dyn_cast<Expr>(s)) {
523f85e193739c953358c865005855253af4f68a497John McCall    // Skip the most common kinds of expressions that make
524f85e193739c953358c865005855253af4f68a497John McCall    // hierarchy-walking expensive.
525f85e193739c953358c865005855253af4f68a497John McCall    s = e = e->IgnoreParenCasts();
526f85e193739c953358c865005855253af4f68a497John McCall
527f85e193739c953358c865005855253af4f68a497John McCall    if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e))
528f85e193739c953358c865005855253af4f68a497John McCall      return (ref->getDecl() == &var);
529ddfc8a1e68ac67d748ca918acac8f1c78a51395cFariborz Jahanian    if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
530ddfc8a1e68ac67d748ca918acac8f1c78a51395cFariborz Jahanian      const BlockDecl *block = be->getBlockDecl();
531ddfc8a1e68ac67d748ca918acac8f1c78a51395cFariborz Jahanian      for (BlockDecl::capture_const_iterator i = block->capture_begin(),
532ddfc8a1e68ac67d748ca918acac8f1c78a51395cFariborz Jahanian           e = block->capture_end(); i != e; ++i) {
533ddfc8a1e68ac67d748ca918acac8f1c78a51395cFariborz Jahanian        if (i->getVariable() == &var)
534ddfc8a1e68ac67d748ca918acac8f1c78a51395cFariborz Jahanian          return true;
535ddfc8a1e68ac67d748ca918acac8f1c78a51395cFariborz Jahanian      }
536ddfc8a1e68ac67d748ca918acac8f1c78a51395cFariborz Jahanian    }
537f85e193739c953358c865005855253af4f68a497John McCall  }
538f85e193739c953358c865005855253af4f68a497John McCall
539f85e193739c953358c865005855253af4f68a497John McCall  for (Stmt::const_child_range children = s->children(); children; ++children)
5408fefc8e245c47daacae7a7fb218677fdcb85d122Fariborz Jahanian    // children might be null; as in missing decl or conditional of an if-stmt.
5418fefc8e245c47daacae7a7fb218677fdcb85d122Fariborz Jahanian    if ((*children) && isAccessedBy(var, *children))
542f85e193739c953358c865005855253af4f68a497John McCall      return true;
543f85e193739c953358c865005855253af4f68a497John McCall
544f85e193739c953358c865005855253af4f68a497John McCall  return false;
545f85e193739c953358c865005855253af4f68a497John McCall}
546f85e193739c953358c865005855253af4f68a497John McCall
547f85e193739c953358c865005855253af4f68a497John McCallstatic bool isAccessedBy(const ValueDecl *decl, const Expr *e) {
548f85e193739c953358c865005855253af4f68a497John McCall  if (!decl) return false;
549f85e193739c953358c865005855253af4f68a497John McCall  if (!isa<VarDecl>(decl)) return false;
550f85e193739c953358c865005855253af4f68a497John McCall  const VarDecl *var = cast<VarDecl>(decl);
551f85e193739c953358c865005855253af4f68a497John McCall  return isAccessedBy(*var, e);
552f85e193739c953358c865005855253af4f68a497John McCall}
553f85e193739c953358c865005855253af4f68a497John McCall
554a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCallstatic void drillIntoBlockVariable(CodeGenFunction &CGF,
555a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall                                   LValue &lvalue,
556a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall                                   const VarDecl *var) {
557a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall  lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var));
558a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall}
559a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall
560f85e193739c953358c865005855253af4f68a497John McCallvoid CodeGenFunction::EmitScalarInit(const Expr *init,
561f85e193739c953358c865005855253af4f68a497John McCall                                     const ValueDecl *D,
562a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall                                     LValue lvalue,
563a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall                                     bool capturedByInit) {
564a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
565f85e193739c953358c865005855253af4f68a497John McCall  if (!lifetime) {
566f85e193739c953358c865005855253af4f68a497John McCall    llvm::Value *value = EmitScalarExpr(init);
567a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall    if (capturedByInit)
568a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
5697a7ee3033e44b45630981355460ef89efa0bdcc4David Chisnall    EmitStoreThroughLValue(RValue::get(value), lvalue, true);
570f85e193739c953358c865005855253af4f68a497John McCall    return;
571f85e193739c953358c865005855253af4f68a497John McCall  }
572f85e193739c953358c865005855253af4f68a497John McCall
573f85e193739c953358c865005855253af4f68a497John McCall  // If we're emitting a value with lifetime, we have to do the
574f85e193739c953358c865005855253af4f68a497John McCall  // initialization *before* we leave the cleanup scopes.
5751a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) {
5761a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall    enterFullExpression(ewc);
577f85e193739c953358c865005855253af4f68a497John McCall    init = ewc->getSubExpr();
5781a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  }
5791a343ebbf413e8eae6b2737b2b2d79cbf5765571John McCall  CodeGenFunction::RunCleanupsScope Scope(*this);
580f85e193739c953358c865005855253af4f68a497John McCall
581f85e193739c953358c865005855253af4f68a497John McCall  // We have to maintain the illusion that the variable is
582f85e193739c953358c865005855253af4f68a497John McCall  // zero-initialized.  If the variable might be accessed in its
583f85e193739c953358c865005855253af4f68a497John McCall  // initializer, zero-initialize before running the initializer, then
584f85e193739c953358c865005855253af4f68a497John McCall  // actually perform the initialization with an assign.
585f85e193739c953358c865005855253af4f68a497John McCall  bool accessedByInit = false;
586f85e193739c953358c865005855253af4f68a497John McCall  if (lifetime != Qualifiers::OCL_ExplicitNone)
587fb7208119a60f68c87e7d4b6e4b87371871abb49John McCall    accessedByInit = (capturedByInit || isAccessedBy(D, init));
588f85e193739c953358c865005855253af4f68a497John McCall  if (accessedByInit) {
589a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall    LValue tempLV = lvalue;
590f85e193739c953358c865005855253af4f68a497John McCall    // Drill down to the __block object if necessary.
591f85e193739c953358c865005855253af4f68a497John McCall    if (capturedByInit) {
592f85e193739c953358c865005855253af4f68a497John McCall      // We can use a simple GEP for this because it can't have been
593f85e193739c953358c865005855253af4f68a497John McCall      // moved yet.
594a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall      tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(),
595a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall                                   getByRefValueLLVMField(cast<VarDecl>(D))));
596f85e193739c953358c865005855253af4f68a497John McCall    }
597f85e193739c953358c865005855253af4f68a497John McCall
5982acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::PointerType *ty
599a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall      = cast<llvm::PointerType>(tempLV.getAddress()->getType());
600f85e193739c953358c865005855253af4f68a497John McCall    ty = cast<llvm::PointerType>(ty->getElementType());
601f85e193739c953358c865005855253af4f68a497John McCall
602f85e193739c953358c865005855253af4f68a497John McCall    llvm::Value *zero = llvm::ConstantPointerNull::get(ty);
603e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
604f85e193739c953358c865005855253af4f68a497John McCall    // If __weak, we want to use a barrier under certain conditions.
605f85e193739c953358c865005855253af4f68a497John McCall    if (lifetime == Qualifiers::OCL_Weak)
606a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall      EmitARCInitWeak(tempLV.getAddress(), zero);
607f85e193739c953358c865005855253af4f68a497John McCall
608f85e193739c953358c865005855253af4f68a497John McCall    // Otherwise just do a simple store.
609f85e193739c953358c865005855253af4f68a497John McCall    else
6107a7ee3033e44b45630981355460ef89efa0bdcc4David Chisnall      EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true);
611f85e193739c953358c865005855253af4f68a497John McCall  }
612f85e193739c953358c865005855253af4f68a497John McCall
613f85e193739c953358c865005855253af4f68a497John McCall  // Emit the initializer.
614f85e193739c953358c865005855253af4f68a497John McCall  llvm::Value *value = 0;
615f85e193739c953358c865005855253af4f68a497John McCall
616f85e193739c953358c865005855253af4f68a497John McCall  switch (lifetime) {
617f85e193739c953358c865005855253af4f68a497John McCall  case Qualifiers::OCL_None:
618f85e193739c953358c865005855253af4f68a497John McCall    llvm_unreachable("present but none");
619f85e193739c953358c865005855253af4f68a497John McCall
620f85e193739c953358c865005855253af4f68a497John McCall  case Qualifiers::OCL_ExplicitNone:
621f85e193739c953358c865005855253af4f68a497John McCall    // nothing to do
622f85e193739c953358c865005855253af4f68a497John McCall    value = EmitScalarExpr(init);
623f85e193739c953358c865005855253af4f68a497John McCall    break;
624f85e193739c953358c865005855253af4f68a497John McCall
625f85e193739c953358c865005855253af4f68a497John McCall  case Qualifiers::OCL_Strong: {
626f85e193739c953358c865005855253af4f68a497John McCall    value = EmitARCRetainScalarExpr(init);
627f85e193739c953358c865005855253af4f68a497John McCall    break;
628f85e193739c953358c865005855253af4f68a497John McCall  }
629f85e193739c953358c865005855253af4f68a497John McCall
630f85e193739c953358c865005855253af4f68a497John McCall  case Qualifiers::OCL_Weak: {
631f85e193739c953358c865005855253af4f68a497John McCall    // No way to optimize a producing initializer into this.  It's not
632f85e193739c953358c865005855253af4f68a497John McCall    // worth optimizing for, because the value will immediately
633f85e193739c953358c865005855253af4f68a497John McCall    // disappear in the common case.
634f85e193739c953358c865005855253af4f68a497John McCall    value = EmitScalarExpr(init);
635f85e193739c953358c865005855253af4f68a497John McCall
636a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall    if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
637f85e193739c953358c865005855253af4f68a497John McCall    if (accessedByInit)
638a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall      EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true);
639f85e193739c953358c865005855253af4f68a497John McCall    else
640a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall      EmitARCInitWeak(lvalue.getAddress(), value);
641f85e193739c953358c865005855253af4f68a497John McCall    return;
642f85e193739c953358c865005855253af4f68a497John McCall  }
643f85e193739c953358c865005855253af4f68a497John McCall
644f85e193739c953358c865005855253af4f68a497John McCall  case Qualifiers::OCL_Autoreleasing:
645f85e193739c953358c865005855253af4f68a497John McCall    value = EmitARCRetainAutoreleaseScalarExpr(init);
646f85e193739c953358c865005855253af4f68a497John McCall    break;
647f85e193739c953358c865005855253af4f68a497John McCall  }
648f85e193739c953358c865005855253af4f68a497John McCall
649a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall  if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
650f85e193739c953358c865005855253af4f68a497John McCall
651f85e193739c953358c865005855253af4f68a497John McCall  // If the variable might have been accessed by its initializer, we
652f85e193739c953358c865005855253af4f68a497John McCall  // might have to initialize with a barrier.  We have to do this for
653f85e193739c953358c865005855253af4f68a497John McCall  // both __weak and __strong, but __weak got filtered out above.
654f85e193739c953358c865005855253af4f68a497John McCall  if (accessedByInit && lifetime == Qualifiers::OCL_Strong) {
655a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall    llvm::Value *oldValue = EmitLoadOfScalar(lvalue);
6567a7ee3033e44b45630981355460ef89efa0bdcc4David Chisnall    EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
6575b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall    EmitARCRelease(oldValue, ARCImpreciseLifetime);
658f85e193739c953358c865005855253af4f68a497John McCall    return;
659f85e193739c953358c865005855253af4f68a497John McCall  }
660f85e193739c953358c865005855253af4f68a497John McCall
6617a7ee3033e44b45630981355460ef89efa0bdcc4David Chisnall  EmitStoreOfScalar(value, lvalue, /* isInitialization */ true);
662f85e193739c953358c865005855253af4f68a497John McCall}
66394cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner
6647acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall/// EmitScalarInit - Initialize the given lvalue with the given object.
6657acddacc921cd0b3f813443a8641eeddb82dfbd4John McCallvoid CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) {
6667acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime();
6677acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  if (!lifetime)
6687a7ee3033e44b45630981355460ef89efa0bdcc4David Chisnall    return EmitStoreThroughLValue(RValue::get(init), lvalue, true);
6697acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall
6707acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  switch (lifetime) {
6717acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  case Qualifiers::OCL_None:
6727acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    llvm_unreachable("present but none");
6737acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall
6747acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  case Qualifiers::OCL_ExplicitNone:
6757acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    // nothing to do
6767acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    break;
6777acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall
6787acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  case Qualifiers::OCL_Strong:
6797acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    init = EmitARCRetain(lvalue.getType(), init);
6807acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    break;
6817acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall
6827acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  case Qualifiers::OCL_Weak:
6837acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    // Initialize and then skip the primitive store.
6847acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    EmitARCInitWeak(lvalue.getAddress(), init);
6857acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    return;
6867acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall
6877acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  case Qualifiers::OCL_Autoreleasing:
6887acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    init = EmitARCRetainAutorelease(lvalue.getType(), init);
6897acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall    break;
6907acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall  }
6917acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall
6927a7ee3033e44b45630981355460ef89efa0bdcc4David Chisnall  EmitStoreOfScalar(init, lvalue, /* isInitialization */ true);
6937acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall}
6947acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall
69594cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner/// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the
69694cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner/// non-zero parts of the specified initializer with equal or fewer than
69794cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner/// NumStores scalar stores.
69894cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattnerstatic bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init,
69994cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner                                                unsigned &NumStores) {
70070b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner  // Zero and Undef never requires any extra stores.
70170b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner  if (isa<llvm::ConstantAggregateZero>(Init) ||
70270b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner      isa<llvm::ConstantPointerNull>(Init) ||
70370b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner      isa<llvm::UndefValue>(Init))
70470b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner    return true;
70570b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
70670b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
70770b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner      isa<llvm::ConstantExpr>(Init))
70870b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner    return Init->isNullValue() || NumStores--;
70970b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner
71070b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner  // See if we can emit each element.
71170b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner  if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) {
71270b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner    for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
71370b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner      llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
71470b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner      if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
71570b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner        return false;
71670b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner    }
71770b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner    return true;
71870b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner  }
719f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner
720f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner  if (llvm::ConstantDataSequential *CDS =
721f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner        dyn_cast<llvm::ConstantDataSequential>(Init)) {
722f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner    for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
723f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner      llvm::Constant *Elt = CDS->getElementAsConstant(i);
724f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner      if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores))
725f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner        return false;
726f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner    }
727f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner    return true;
728f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner  }
729e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
73094cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner  // Anything else is hard and scary.
73194cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner  return false;
73294cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner}
73394cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner
73494cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner/// emitStoresForInitAfterMemset - For inits that
73594cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner/// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar
73694cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner/// stores that would be required.
73794cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattnerstatic void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc,
73834695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall                                         bool isVolatile, CGBuilderTy &Builder) {
73906d43684289bfcf3b2dbaf081aa861f76933d891Benjamin Kramer  assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) &&
74006d43684289bfcf3b2dbaf081aa861f76933d891Benjamin Kramer         "called emitStoresForInitAfterMemset for zero or undef value.");
741e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
74270b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner  if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) ||
74370b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner      isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) ||
74470b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner      isa<llvm::ConstantExpr>(Init)) {
745f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner    Builder.CreateStore(Init, Loc, isVolatile);
746f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner    return;
747f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner  }
748f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner
749f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner  if (llvm::ConstantDataSequential *CDS =
750f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner        dyn_cast<llvm::ConstantDataSequential>(Init)) {
751f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner    for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) {
752f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner      llvm::Constant *Elt = CDS->getElementAsConstant(i);
753cfa07e3519cff1c69cd39d02c80263fd6469c3dbBenjamin Kramer
754cfa07e3519cff1c69cd39d02c80263fd6469c3dbBenjamin Kramer      // If necessary, get a pointer to the element and emit it.
755cfa07e3519cff1c69cd39d02c80263fd6469c3dbBenjamin Kramer      if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
756cfa07e3519cff1c69cd39d02c80263fd6469c3dbBenjamin Kramer        emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
757cfa07e3519cff1c69cd39d02c80263fd6469c3dbBenjamin Kramer                                     isVolatile, Builder);
758f492cb1b62b9113d80d85d32515566d6c2a8cdb3Chris Lattner    }
75970b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner    return;
76070b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner  }
761e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
76270b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner  assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) &&
76370b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner         "Unknown value type!");
764e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
76570b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner  for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) {
76670b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner    llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i));
767cfa07e3519cff1c69cd39d02c80263fd6469c3dbBenjamin Kramer
768cfa07e3519cff1c69cd39d02c80263fd6469c3dbBenjamin Kramer    // If necessary, get a pointer to the element and emit it.
769cfa07e3519cff1c69cd39d02c80263fd6469c3dbBenjamin Kramer    if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt))
770cfa07e3519cff1c69cd39d02c80263fd6469c3dbBenjamin Kramer      emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i),
771cfa07e3519cff1c69cd39d02c80263fd6469c3dbBenjamin Kramer                                   isVolatile, Builder);
77270b02943ddee9ee31e9641ab3f5eb0dc874b7e03Chris Lattner  }
77394cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner}
77494cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner
77594cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner
77694cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner/// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset
77794cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner/// plus some stores to initialize a local variable instead of using a memcpy
77894cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner/// from a constant global.  It is beneficial to use memset if the global is all
77994cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner/// zeros, or mostly zeros and large.
78094cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattnerstatic bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init,
78194cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner                                                  uint64_t GlobalSize) {
78294cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner  // If a global is all zeros, always use a memset.
78394cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner  if (isa<llvm::ConstantAggregateZero>(Init)) return true;
78494cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner
78594cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner  // If a non-zero global is <= 32 bytes, always use a memcpy.  If it is large,
78694cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner  // do it if it will require 6 or fewer scalar stores.
78794cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner  // TODO: Should budget depends on the size?  Avoiding a large global warrants
78894cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner  // plopping in more stores.
78994cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner  unsigned StoreBudget = 6;
79094cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner  uint64_t SizeLimit = 32;
791e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
792e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher  return GlobalSize > SizeLimit &&
79394cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner         canEmitInitWithFewStoresAfterMemset(Init, StoreBudget);
79494cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner}
79594cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner
796495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem/// Should we use the LLVM lifetime intrinsics for the given local variable?
797495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotemstatic bool shouldUseLifetimeMarkers(CodeGenFunction &CGF, const VarDecl &D,
798495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem                                     unsigned Size) {
7994f01ed4205a7189520f6a481fe2113856833421fAlexey Samsonov  // Always emit lifetime markers in -fsanitize=use-after-scope mode.
8004f01ed4205a7189520f6a481fe2113856833421fAlexey Samsonov  if (CGF.getLangOpts().Sanitize.UseAfterScope)
8014f01ed4205a7189520f6a481fe2113856833421fAlexey Samsonov    return true;
802495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  // For now, only in optimized builds.
803495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  if (CGF.CGM.getCodeGenOpts().OptimizationLevel == 0)
804495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem    return false;
805495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem
806495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  // Limit the size of marked objects to 32 bytes. We don't want to increase
807495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  // compile time by marking tiny objects.
808495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  unsigned SizeThreshold = 32;
809495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem
810495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  return Size > SizeThreshold;
811495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem}
812495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem
81394cd011edcffdabd3cbc520830ccf8e793e08b62Chris Lattner
814a9de3fa8a9c22dd419eda9be53e8c7c428cce1c0Nick Lewycky/// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a
8155f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer/// variable declaration with auto, register, or no storage class specifier.
8162621fd1d6d3c5eadcae246859f62738645df7540Chris Lattner/// These turn into simple stack objects, or GlobalValues depending on target.
81734695856c0e67b3765b46304cc71b5d2cd5b71c7John McCallvoid CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) {
81834695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  AutoVarEmission emission = EmitAutoVarAlloca(D);
81934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  EmitAutoVarInit(emission);
82034695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  EmitAutoVarCleanups(emission);
82134695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall}
82234695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
82334695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall/// EmitAutoVarAlloca - Emit the alloca and debug information for a
82434695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall/// local variable.  Does not emit initalization or destruction.
82534695856c0e67b3765b46304cc71b5d2cd5b71c7John McCallCodeGenFunction::AutoVarEmission
82634695856c0e67b3765b46304cc71b5d2cd5b71c7John McCallCodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
8278bcfc5bef434d7052e28d0ce45182855659ebd3dChris Lattner  QualType Ty = D.getType();
82834695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
82934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  AutoVarEmission emission(D);
83034695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
83140b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  bool isByRef = D.hasAttr<BlocksAttr>();
83234695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  emission.IsByRef = isByRef;
83334695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
83434695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  CharUnits alignment = getContext().getDeclAlign(&D);
83534695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  emission.Alignment = alignment;
8365f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
837bc8d40d85f3fa1e34569834916f18fecaa635152John McCall  // If the type is variably-modified, emit all the VLA sizes for it.
838bc8d40d85f3fa1e34569834916f18fecaa635152John McCall  if (Ty->isVariablyModifiedType())
839bc8d40d85f3fa1e34569834916f18fecaa635152John McCall    EmitVariablyModifiedType(Ty);
840bc8d40d85f3fa1e34569834916f18fecaa635152John McCall
8415f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  llvm::Value *DeclPtr;
8423c2b3170041f69a92904e3bab9b6d654eaf260acEli Friedman  if (Ty->isConstantSizeType()) {
8436c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    bool NRVO = getLangOpts().ElideConstructors &&
8446c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      D.isNRVOVariable();
8456c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola
846e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith    // If this value is an array or struct with a statically determinable
847e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith    // constant initializer, there are optimizations we can do.
8486c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    //
8496c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    // TODO: We should constant-evaluate the initializer of any variable,
8506c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    // as long as it is initialized by a constant expression. Currently,
8516c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    // isConstantInitializer produces wrong answers for structs with
8526c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    // reference or bitfield members, and a few other cases, and checking
8536c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    // for POD-ness protects us from some of these.
854e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith    if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) &&
855e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith        (D.isConstexpr() ||
856e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith         ((Ty.isPODType(getContext()) ||
857e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith           getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) &&
858e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith          D.getInit()->isConstantInitializer(getContext(), false)))) {
8596c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola
8606c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      // If the variable's a const type, and it's neither an NRVO
8616c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      // candidate nor a __block variable and has no mutable members,
8626c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      // emit it as a global instead.
8636c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef &&
8646c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          CGM.isTypeConstant(Ty, true)) {
8656c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage);
8666c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola
8676c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        emission.Address = 0; // signal this condition to later callbacks
8686c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        assert(emission.wasEmittedAsGlobal());
8696c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        return emission;
87059876c2713683d1538ca45bb14c2f415862fb716Tanya Lattner      }
871e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
8726c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      // Otherwise, tell the initialization code that we're in this case.
8736c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      emission.IsConstantAggregate = true;
8746c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    }
875e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
8766c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    // A normal fixed sized variable becomes an alloca in the entry block,
8776c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    // unless it's an NRVO variable.
8786c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    llvm::Type *LTy = ConvertTypeForMem(Ty);
8796c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola
8806c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola    if (NRVO) {
8816c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      // The named return value optimization: allocate this variable in the
8826c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      // return slot, so that we can elide the copy when returning this
8836c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      // variable (C++0x [class.copy]p34).
8846c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      DeclPtr = ReturnValue;
8856c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola
8866c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      if (const RecordType *RecordTy = Ty->getAs<RecordType>()) {
8876c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) {
8886c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          // Create a flag that is used to indicate when the NRVO was applied
8896c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          // to this variable. Set it to zero to indicate that NRVO was not
8906c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          // applied.
8916c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          llvm::Value *Zero = Builder.getFalse();
8926c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo");
8936c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          EnsureInsertPoint();
8946c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          Builder.CreateStore(Zero, NRVOFlag);
8956c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola
8966c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          // Record the NRVO flag for this variable.
8976c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          NRVOFlags[&D] = NRVOFlag;
8986c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          emission.NRVOFlag = NRVOFlag;
899495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem        }
900d86c477fb5d3fc34864afecbbb5443da9355e8fbDouglas Gregor      }
9012621fd1d6d3c5eadcae246859f62738645df7540Chris Lattner    } else {
9026c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      if (isByRef)
9036c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        LTy = BuildByRefType(&D);
9046c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola
9056c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      llvm::AllocaInst *Alloc = CreateTempAlloca(LTy);
9066c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      Alloc->setName(D.getName());
9076c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola
9086c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      CharUnits allocaAlignment = alignment;
9096c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      if (isByRef)
9106c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        allocaAlignment = std::max(allocaAlignment,
91164aa4b3ec7e62288e2e66c1935487ece995ca94bJohn McCall            getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
9126c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      Alloc->setAlignment(allocaAlignment.getQuantity());
9136c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      DeclPtr = Alloc;
9146c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola
9156c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      // Emit a lifetime intrinsic if meaningful.  There's no point
9166c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      // in doing this if we don't have a valid insertion point (?).
9176c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      uint64_t size = CGM.getDataLayout().getTypeAllocSize(LTy);
9186c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      if (HaveInsertPoint() && shouldUseLifetimeMarkers(*this, D, size)) {
9196c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        llvm::Value *sizeV = llvm::ConstantInt::get(Int64Ty, size);
9206c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola
9216c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        emission.SizeForLifetimeMarkers = sizeV;
9226c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        llvm::Value *castAddr = Builder.CreateBitCast(Alloc, Int8PtrTy);
9236c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        Builder.CreateCall2(CGM.getLLVMLifetimeStartFn(), sizeV, castAddr)
9246c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola          ->setDoesNotThrow();
9256c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      } else {
9266c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        assert(!emission.useLifetimeMarkers());
9276c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola      }
9282621fd1d6d3c5eadcae246859f62738645df7540Chris Lattner    }
9295f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  } else {
930d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbar    EnsureInsertPoint();
931d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbar
9325ecb1b9377a6408486df5a10538bdc932706e053Anders Carlsson    if (!DidCallStackSave) {
9335d46315ca3cbbfe0d0f5f65520b618fb05dd4446Anders Carlsson      // Save the stack.
934d16c2cf1cafa413709aa487cbbd5dc392f1ba1ffJohn McCall      llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack");
9351eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
9365d46315ca3cbbfe0d0f5f65520b618fb05dd4446Anders Carlsson      llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave);
9375d46315ca3cbbfe0d0f5f65520b618fb05dd4446Anders Carlsson      llvm::Value *V = Builder.CreateCall(F);
9381eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
9395d46315ca3cbbfe0d0f5f65520b618fb05dd4446Anders Carlsson      Builder.CreateStore(V, Stack);
9405ecb1b9377a6408486df5a10538bdc932706e053Anders Carlsson
9415ecb1b9377a6408486df5a10538bdc932706e053Anders Carlsson      DidCallStackSave = true;
9421eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
943d87150999833d756269d84ca6e4127dc99fdcf63John McCall      // Push a cleanup block and restore the stack there.
9443ad32c8d93eb65d1d4943d7df567fc9b4f55d137John McCall      // FIXME: in general circumstances, this should be an EH cleanup.
9451f0fca54676cfa8616e7f3cd7a26788ab937e3cdJohn McCall      EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack);
9465d46315ca3cbbfe0d0f5f65520b618fb05dd4446Anders Carlsson    }
9471eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
948bc8d40d85f3fa1e34569834916f18fecaa635152John McCall    llvm::Value *elementCount;
949bc8d40d85f3fa1e34569834916f18fecaa635152John McCall    QualType elementType;
950bc8d40d85f3fa1e34569834916f18fecaa635152John McCall    llvm::tie(elementCount, elementType) = getVLASize(Ty);
9515d46315ca3cbbfe0d0f5f65520b618fb05dd4446Anders Carlsson
9522acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner    llvm::Type *llvmTy = ConvertTypeForMem(elementType);
9535d46315ca3cbbfe0d0f5f65520b618fb05dd4446Anders Carlsson
9545d46315ca3cbbfe0d0f5f65520b618fb05dd4446Anders Carlsson    // Allocate memory for the array.
955bc8d40d85f3fa1e34569834916f18fecaa635152John McCall    llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla");
956bc8d40d85f3fa1e34569834916f18fecaa635152John McCall    vla->setAlignment(alignment.getQuantity());
95741f8a13ac7fa734faef2d8a36feebc3c9a1eed77Anders Carlsson
958bc8d40d85f3fa1e34569834916f18fecaa635152John McCall    DeclPtr = vla;
9595f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
9608f39f5e96ce4a5f401f431f61db7df1cf05dce6fEli Friedman
9615f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  llvm::Value *&DMEntry = LocalDeclMap[&D];
9625f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
9635f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  DMEntry = DeclPtr;
96434695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  emission.Address = DeclPtr;
965cc9b16394fe6c9245dc4f8661a63d0c3937b62f0Sanjiv Gupta
966cc9b16394fe6c9245dc4f8661a63d0c3937b62f0Sanjiv Gupta  // Emit debug info for local var declaration.
967c594abdb78b67d477c9bdd24c3600aec3dc2eda4Devang Patel  if (HaveInsertPoint())
968c594abdb78b67d477c9bdd24c3600aec3dc2eda4Devang Patel    if (CGDebugInfo *DI = getDebugInfo()) {
9694cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor      if (CGM.getCodeGenOpts().getDebugInfo()
9704cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor            >= CodeGenOptions::LimitedDebugInfo) {
971fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov        DI->setLocation(D.getLocation());
9726c82fc65e45c668a36b06536e66563fe937a3096Rafael Espindola        DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder);
973fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov      }
974c594abdb78b67d477c9bdd24c3600aec3dc2eda4Devang Patel    }
975cc9b16394fe6c9245dc4f8661a63d0c3937b62f0Sanjiv Gupta
97677f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D.hasAttr<AnnotateAttr>())
97777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      EmitVarAnnotations(&D, emission.Address);
97877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
97934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  return emission;
98034695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall}
98134695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
98234695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall/// Determines whether the given __block variable is potentially
98334695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall/// captured by the given expression.
98434695856c0e67b3765b46304cc71b5d2cd5b71c7John McCallstatic bool isCapturedBy(const VarDecl &var, const Expr *e) {
98534695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // Skip the most common kinds of expressions that make
98634695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // hierarchy-walking expensive.
98734695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  e = e->IgnoreParenCasts();
98834695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
98934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) {
99034695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    const BlockDecl *block = be->getBlockDecl();
99134695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    for (BlockDecl::capture_const_iterator i = block->capture_begin(),
99234695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall           e = block->capture_end(); i != e; ++i) {
99334695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall      if (i->getVariable() == &var)
99434695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall        return true;
99534695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    }
99634695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
99734695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    // No need to walk into the subexpressions.
99834695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    return false;
99934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  }
100034695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
10015033be1b3a6f1d1c1ab9b2d284267c8f6f531f2eFariborz Jahanian  if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) {
10025033be1b3a6f1d1c1ab9b2d284267c8f6f531f2eFariborz Jahanian    const CompoundStmt *CS = SE->getSubStmt();
1003c6fad60801ff271d425ff8f635b66998008ffd7aEric Christopher    for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
1004c6fad60801ff271d425ff8f635b66998008ffd7aEric Christopher	   BE = CS->body_end(); BI != BE; ++BI)
1005045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian      if (Expr *E = dyn_cast<Expr>((*BI))) {
10065033be1b3a6f1d1c1ab9b2d284267c8f6f531f2eFariborz Jahanian        if (isCapturedBy(var, E))
10075033be1b3a6f1d1c1ab9b2d284267c8f6f531f2eFariborz Jahanian            return true;
1008045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian      }
1009045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian      else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) {
1010045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian          // special case declarations
1011045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian          for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end();
1012045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian               I != E; ++I) {
1013045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian              if (VarDecl *VD = dyn_cast<VarDecl>((*I))) {
1014045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian                Expr *Init = VD->getInit();
1015045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian                if (Init && isCapturedBy(var, Init))
1016045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian                  return true;
1017045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian              }
1018045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian          }
1019045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian      }
1020045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian      else
1021045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian        // FIXME. Make safe assumption assuming arbitrary statements cause capturing.
1022045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian        // Later, provide code to poke into statements for capture analysis.
1023045c84264f7c9d5b166e9a93d8fe62c777d3039cFariborz Jahanian        return true;
10245033be1b3a6f1d1c1ab9b2d284267c8f6f531f2eFariborz Jahanian    return false;
10255033be1b3a6f1d1c1ab9b2d284267c8f6f531f2eFariborz Jahanian  }
1026e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
102734695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  for (Stmt::const_child_range children = e->children(); children; ++children)
102834695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    if (isCapturedBy(var, cast<Expr>(*children)))
102934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall      return true;
103034695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
103134695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  return false;
103234695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall}
103334695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
1034bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor/// \brief Determine whether the given initializer is trivial in the sense
1035bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor/// that it requires no code to be generated.
1036bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregorstatic bool isTrivialInitializer(const Expr *Init) {
1037bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor  if (!Init)
1038bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor    return true;
1039e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
1040bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor  if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init))
1041bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor    if (CXXConstructorDecl *Constructor = Construct->getConstructor())
1042bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor      if (Constructor->isTrivial() &&
1043bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor          Constructor->isDefaultConstructor() &&
1044bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor          !Construct->requiresZeroInitialization())
1045bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor        return true;
1046e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
1047bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor  return false;
1048bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor}
104934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCallvoid CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) {
105057b3b6a60856eaec30fd876a8a3face8f7e3ad7bJohn McCall  assert(emission.Variable && "emission was not valid!");
105157b3b6a60856eaec30fd876a8a3face8f7e3ad7bJohn McCall
105234695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // If this was emitted as a global constant, we're done.
105334695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  if (emission.wasEmittedAsGlobal()) return;
105434695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
105557b3b6a60856eaec30fd876a8a3face8f7e3ad7bJohn McCall  const VarDecl &D = *emission.Variable;
105634695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  QualType type = D.getType();
105734695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
10581978596a6f490e674369634900ffb773bdb49e94Chris Lattner  // If this local has an initializer, emit it now.
1059d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbar  const Expr *Init = D.getInit();
1060d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbar
1061d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbar  // If we are at an unreachable point, we don't need to emit the initializer
1062d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbar  // unless it contains a label.
1063d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbar  if (!HaveInsertPoint()) {
106434695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    if (!Init || !ContainsLabel(Init)) return;
106534695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    EnsureInsertPoint();
1066d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbar  }
1067d286f05f1234bac289173f0eed88d7ecbaea0099Daniel Dunbar
10685af02db5a48476e0748f135369663080eae87c64John McCall  // Initialize the structure of a __block variable.
10695af02db5a48476e0748f135369663080eae87c64John McCall  if (emission.IsByRef)
10705af02db5a48476e0748f135369663080eae87c64John McCall    emitByrefStructureInit(emission);
107169c68b7454dc7f47def4ebf593a584d0f02c1ddbAnders Carlsson
1072bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor  if (isTrivialInitializer(Init))
1073bcc3e660a1fdc19722157ef3e2f133418856ca3dDouglas Gregor    return;
1074e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
10755af02db5a48476e0748f135369663080eae87c64John McCall  CharUnits alignment = emission.Alignment;
10765af02db5a48476e0748f135369663080eae87c64John McCall
107734695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // Check whether this is a byref variable that's potentially
107834695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // captured and moved by its own initializer.  If so, we'll need to
107934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // emit the initializer first, then copy into the variable.
108034695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init);
108134695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
108234695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  llvm::Value *Loc =
108334695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    capturedByInit ? emission.Address : emission.getObjectAddress(*this);
108434695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
108551201882382fb40c9456a06c7f93d6ddd4a57712Richard Smith  llvm::Constant *constant = 0;
1086e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith  if (emission.IsConstantAggregate || D.isConstexpr()) {
108751201882382fb40c9456a06c7f93d6ddd4a57712Richard Smith    assert(!capturedByInit && "constant init contains a capturing block?");
10882d6a5670465cb3f1d811695a9f23e372508240d2Richard Smith    constant = CGM.EmitConstantInit(D, this);
108951201882382fb40c9456a06c7f93d6ddd4a57712Richard Smith  }
109051201882382fb40c9456a06c7f93d6ddd4a57712Richard Smith
109151201882382fb40c9456a06c7f93d6ddd4a57712Richard Smith  if (!constant) {
10926da2c716017d5c8530ec99779524491ebc5dadb8Eli Friedman    LValue lv = MakeAddrLValue(Loc, type, alignment);
1093a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall    lv.setNonGC(true);
1094a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall    return EmitExprAsInit(Init, &D, lv, capturedByInit);
1095a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall  }
109660d3365b46eb826fba44483583c0051ac5c41fe3John McCall
1097e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith  if (!emission.IsConstantAggregate) {
1098e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith    // For simple scalar/complex initialization, store the value directly.
1099e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith    LValue lv = MakeAddrLValue(Loc, type, alignment);
1100e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith    lv.setNonGC(true);
1101e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith    return EmitStoreThroughLValue(RValue::get(constant), lv, true);
1102e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith  }
1103e67ca5803ac9e39cc31ed1ad9576e1626c8141ebRichard Smith
110434695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // If this is a simple aggregate initialization, we can optimize it
110534695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // in various ways.
110660d3365b46eb826fba44483583c0051ac5c41fe3John McCall  bool isVolatile = type.isVolatileQualified();
11073ecd785aff34381f3704d9cb28fe3ef85af759deMon P Wang
110860d3365b46eb826fba44483583c0051ac5c41fe3John McCall  llvm::Value *SizeVal =
1109e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher    llvm::ConstantInt::get(IntPtrTy,
111060d3365b46eb826fba44483583c0051ac5c41fe3John McCall                           getContext().getTypeSizeInChars(type).getQuantity());
111160d3365b46eb826fba44483583c0051ac5c41fe3John McCall
11122acc6e3feda5e4f7d9009bdcf8b1cd777fecfe2dChris Lattner  llvm::Type *BP = Int8PtrTy;
111360d3365b46eb826fba44483583c0051ac5c41fe3John McCall  if (Loc->getType() != BP)
1114578faa837b552403e2002b97fdfbfde14f2448e5Benjamin Kramer    Loc = Builder.CreateBitCast(Loc, BP);
111560d3365b46eb826fba44483583c0051ac5c41fe3John McCall
111660d3365b46eb826fba44483583c0051ac5c41fe3John McCall  // If the initializer is all or mostly zeros, codegen with memset then do
111760d3365b46eb826fba44483583c0051ac5c41fe3John McCall  // a few stores afterward.
1118e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher  if (shouldUseMemSetPlusStoresToInitialize(constant,
111925a6a84cf5067b32c271e3ba078676dee838798dMicah Villmow                CGM.getDataLayout().getTypeAllocSize(constant->getType()))) {
112060d3365b46eb826fba44483583c0051ac5c41fe3John McCall    Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal,
112160d3365b46eb826fba44483583c0051ac5c41fe3John McCall                         alignment.getQuantity(), isVolatile);
112206d43684289bfcf3b2dbaf081aa861f76933d891Benjamin Kramer    // Zero and undef don't require a stores.
112306d43684289bfcf3b2dbaf081aa861f76933d891Benjamin Kramer    if (!constant->isNullValue() && !isa<llvm::UndefValue>(constant)) {
112460d3365b46eb826fba44483583c0051ac5c41fe3John McCall      Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo());
112560d3365b46eb826fba44483583c0051ac5c41fe3John McCall      emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder);
112620e1c7ea56103b7de26e5ab4086739bdc3a3d850Fariborz Jahanian    }
112760d3365b46eb826fba44483583c0051ac5c41fe3John McCall  } else {
1128e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher    // Otherwise, create a temporary global with the initializer then
112960d3365b46eb826fba44483583c0051ac5c41fe3John McCall    // memcpy from the global to the alloca.
113060d3365b46eb826fba44483583c0051ac5c41fe3John McCall    std::string Name = GetStaticDeclName(*this, D, ".");
113160d3365b46eb826fba44483583c0051ac5c41fe3John McCall    llvm::GlobalVariable *GV =
113260d3365b46eb826fba44483583c0051ac5c41fe3John McCall      new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true,
1133736a9c211c065784f7a7889ade55aa569a89520eEric Christopher                               llvm::GlobalValue::PrivateLinkage,
11345e2d5dec7736f6f9292d4212dec67295909f1328Hans Wennborg                               constant, Name);
113560d3365b46eb826fba44483583c0051ac5c41fe3John McCall    GV->setAlignment(alignment.getQuantity());
1136460980d3b9d045288041bf8b826899795c60ca1dEli Friedman    GV->setUnnamedAddr(true);
1137e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
113860d3365b46eb826fba44483583c0051ac5c41fe3John McCall    llvm::Value *SrcPtr = GV;
113960d3365b46eb826fba44483583c0051ac5c41fe3John McCall    if (SrcPtr->getType() != BP)
1140578faa837b552403e2002b97fdfbfde14f2448e5Benjamin Kramer      SrcPtr = Builder.CreateBitCast(SrcPtr, BP);
114160d3365b46eb826fba44483583c0051ac5c41fe3John McCall
114260d3365b46eb826fba44483583c0051ac5c41fe3John McCall    Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(),
114360d3365b46eb826fba44483583c0051ac5c41fe3John McCall                         isVolatile);
114460d3365b46eb826fba44483583c0051ac5c41fe3John McCall  }
114560d3365b46eb826fba44483583c0051ac5c41fe3John McCall}
114660d3365b46eb826fba44483583c0051ac5c41fe3John McCall
114760d3365b46eb826fba44483583c0051ac5c41fe3John McCall/// Emit an expression as an initializer for a variable at the given
114860d3365b46eb826fba44483583c0051ac5c41fe3John McCall/// location.  The expression is not necessarily the normal
114960d3365b46eb826fba44483583c0051ac5c41fe3John McCall/// initializer for the variable, and the address is not necessarily
115060d3365b46eb826fba44483583c0051ac5c41fe3John McCall/// its normal location.
115160d3365b46eb826fba44483583c0051ac5c41fe3John McCall///
115260d3365b46eb826fba44483583c0051ac5c41fe3John McCall/// \param init the initializing expression
115360d3365b46eb826fba44483583c0051ac5c41fe3John McCall/// \param var the variable to act as if we're initializing
115460d3365b46eb826fba44483583c0051ac5c41fe3John McCall/// \param loc the address to initialize; its type is a pointer
115560d3365b46eb826fba44483583c0051ac5c41fe3John McCall///   to the LLVM mapping of the variable's type
115660d3365b46eb826fba44483583c0051ac5c41fe3John McCall/// \param alignment the alignment of the address
115760d3365b46eb826fba44483583c0051ac5c41fe3John McCall/// \param capturedByInit true if the variable is a __block variable
115860d3365b46eb826fba44483583c0051ac5c41fe3John McCall///   whose address is potentially changed by the initializer
115960d3365b46eb826fba44483583c0051ac5c41fe3John McCallvoid CodeGenFunction::EmitExprAsInit(const Expr *init,
1160f85e193739c953358c865005855253af4f68a497John McCall                                     const ValueDecl *D,
1161a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall                                     LValue lvalue,
116260d3365b46eb826fba44483583c0051ac5c41fe3John McCall                                     bool capturedByInit) {
1163f85e193739c953358c865005855253af4f68a497John McCall  QualType type = D->getType();
116460d3365b46eb826fba44483583c0051ac5c41fe3John McCall
116560d3365b46eb826fba44483583c0051ac5c41fe3John McCall  if (type->isReferenceType()) {
1166d4ec562b3aaf50ea9015f82c96ebfd05a35fc7efRichard Smith    RValue rvalue = EmitReferenceBindingToExpr(init);
1167e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher    if (capturedByInit)
1168a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
11697a7ee3033e44b45630981355460ef89efa0bdcc4David Chisnall    EmitStoreThroughLValue(rvalue, lvalue, true);
11709d232c884ea9872d6555df0fd7359699819bc1f1John McCall    return;
11719d232c884ea9872d6555df0fd7359699819bc1f1John McCall  }
11729d232c884ea9872d6555df0fd7359699819bc1f1John McCall  switch (getEvaluationKind(type)) {
11739d232c884ea9872d6555df0fd7359699819bc1f1John McCall  case TEK_Scalar:
1174a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall    EmitScalarInit(init, D, lvalue, capturedByInit);
11759d232c884ea9872d6555df0fd7359699819bc1f1John McCall    return;
11769d232c884ea9872d6555df0fd7359699819bc1f1John McCall  case TEK_Complex: {
117760d3365b46eb826fba44483583c0051ac5c41fe3John McCall    ComplexPairTy complex = EmitComplexExpr(init);
1178a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall    if (capturedByInit)
1179a07398ed98ea2b55ad7a505a3aab18aed93b149fJohn McCall      drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D));
11809d232c884ea9872d6555df0fd7359699819bc1f1John McCall    EmitStoreOfComplex(complex, lvalue, /*init*/ true);
11819d232c884ea9872d6555df0fd7359699819bc1f1John McCall    return;
11829d232c884ea9872d6555df0fd7359699819bc1f1John McCall  }
11839d232c884ea9872d6555df0fd7359699819bc1f1John McCall  case TEK_Aggregate:
11849eda3abe7e183b05834947391c0cdc291f4ee0d8John McCall    if (type->isAtomicType()) {
11859eda3abe7e183b05834947391c0cdc291f4ee0d8John McCall      EmitAtomicInit(const_cast<Expr*>(init), lvalue);
11869eda3abe7e183b05834947391c0cdc291f4ee0d8John McCall    } else {
11879eda3abe7e183b05834947391c0cdc291f4ee0d8John McCall      // TODO: how can we delay here if D is captured by its initializer?
11889eda3abe7e183b05834947391c0cdc291f4ee0d8John McCall      EmitAggExpr(init, AggValueSlot::forLValue(lvalue,
1189649b4a1a9b5e6f768ca0cb84bd97b00f51083e15Chad Rosier                                              AggValueSlot::IsDestructed,
1190410ffb2bc5f072d58a73c14560345bcf77dec1ccJohn McCall                                         AggValueSlot::DoesNotNeedGCBarriers,
1191649b4a1a9b5e6f768ca0cb84bd97b00f51083e15Chad Rosier                                              AggValueSlot::IsNotAliased));
11929eda3abe7e183b05834947391c0cdc291f4ee0d8John McCall    }
11939d232c884ea9872d6555df0fd7359699819bc1f1John McCall    return;
119420e1c7ea56103b7de26e5ab4086739bdc3a3d850Fariborz Jahanian  }
11959d232c884ea9872d6555df0fd7359699819bc1f1John McCall  llvm_unreachable("bad evaluation kind");
119634695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall}
119734695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
1198bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall/// Enter a destroy cleanup for the given local variable.
1199bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCallvoid CodeGenFunction::emitAutoVarTypeCleanup(
1200bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall                            const CodeGenFunction::AutoVarEmission &emission,
1201bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall                            QualType::DestructionKind dtorKind) {
1202bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  assert(dtorKind != QualType::DK_none);
1203bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1204bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  // Note that for __block variables, we want to destroy the
1205bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  // original stack object, not the possibly forwarded object.
1206bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  llvm::Value *addr = emission.getObjectAddress(*this);
1207bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1208bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  const VarDecl *var = emission.Variable;
1209bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  QualType type = var->getType();
1210bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1211bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  CleanupKind cleanupKind = NormalAndEHCleanup;
1212bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  CodeGenFunction::Destroyer *destroyer = 0;
1213bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1214bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  switch (dtorKind) {
1215bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  case QualType::DK_none:
1216bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    llvm_unreachable("no cleanup for trivially-destructible variable");
1217bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1218bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  case QualType::DK_cxx_destructor:
1219bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    // If there's an NRVO flag on the emission, we need a different
1220bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    // cleanup.
1221bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    if (emission.NRVOFlag) {
1222bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall      assert(!type->isArrayType());
1223bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall      CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor();
1224bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall      EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor,
1225bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall                                               emission.NRVOFlag);
1226bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall      return;
1227bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    }
1228bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    break;
1229bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1230bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  case QualType::DK_objc_strong_lifetime:
1231bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    // Suppress cleanups for pseudo-strong variables.
1232bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    if (var->isARCPseudoStrong()) return;
1233e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher
1234bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    // Otherwise, consider whether to use an EH cleanup or not.
1235bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    cleanupKind = getARCCleanupKind();
1236bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1237bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    // Use the imprecise destroyer by default.
1238bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    if (!var->hasAttr<ObjCPreciseLifetimeAttr>())
1239bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall      destroyer = CodeGenFunction::destroyARCStrongImprecise;
1240bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    break;
1241bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1242bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  case QualType::DK_objc_weak_lifetime:
1243bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    break;
1244bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  }
1245bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1246bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  // If we haven't chosen a more specific destroyer, use the default.
1247516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne  if (!destroyer) destroyer = getDestroyer(dtorKind);
12482673c68aa58e277ebc755b71d81aca618cdedbf9John McCall
1249f3477c13eeaf11b32a41f181398fb5deffd0dd73Sylvestre Ledru  // Use an EH cleanup in array destructors iff the destructor itself
12502673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  // is being pushed as an EH cleanup.
12512673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  bool useEHCleanup = (cleanupKind & EHCleanup);
12522673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer,
12532673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                     useEHCleanup);
1254bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall}
1255bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
125634695856c0e67b3765b46304cc71b5d2cd5b71c7John McCallvoid CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) {
125757b3b6a60856eaec30fd876a8a3face8f7e3ad7bJohn McCall  assert(emission.Variable && "emission was not valid!");
125857b3b6a60856eaec30fd876a8a3face8f7e3ad7bJohn McCall
125934695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // If this was emitted as a global constant, we're done.
126034695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  if (emission.wasEmittedAsGlobal()) return;
126134695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall
126238baeabb253f3e04d5b54bf834dbd9f5ebdc9e5cJohn McCall  // If we don't have an insertion point, we're done.  Sema prevents
126338baeabb253f3e04d5b54bf834dbd9f5ebdc9e5cJohn McCall  // us from jumping into any of these scopes anyway.
126438baeabb253f3e04d5b54bf834dbd9f5ebdc9e5cJohn McCall  if (!HaveInsertPoint()) return;
126538baeabb253f3e04d5b54bf834dbd9f5ebdc9e5cJohn McCall
126657b3b6a60856eaec30fd876a8a3face8f7e3ad7bJohn McCall  const VarDecl &D = *emission.Variable;
1267f1549f66a8216a78112286e3978cea2c29d6334cJohn McCall
1268495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  // Make sure we call @llvm.lifetime.end.  This needs to happen
1269495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  // *last*, so the cleanup needs to be pushed *first*.
1270495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  if (emission.useLifetimeMarkers()) {
1271495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem    EHStack.pushCleanup<CallLifetimeEnd>(NormalCleanup,
1272495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem                                         emission.getAllocatedAddress(),
1273495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem                                         emission.getSizeForLifetimeMarkers());
1274495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  }
1275495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem
1276bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  // Check the type for a cleanup.
1277bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  if (QualType::DestructionKind dtorKind = D.getType().isDestructedType())
1278bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    emitAutoVarTypeCleanup(emission, dtorKind);
1279f85e193739c953358c865005855253af4f68a497John McCall
12800c24c808e4dce43e88abf2d5f98546b901bd4315John McCall  // In GC mode, honor objc_precise_lifetime.
12814e4d08403ca5cfd4d558fa2936215d3a4e5a528dDavid Blaikie  if (getLangOpts().getGC() != LangOptions::NonGC &&
12820c24c808e4dce43e88abf2d5f98546b901bd4315John McCall      D.hasAttr<ObjCPreciseLifetimeAttr>()) {
12830c24c808e4dce43e88abf2d5f98546b901bd4315John McCall    EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D);
12840c24c808e4dce43e88abf2d5f98546b901bd4315John McCall  }
12850c24c808e4dce43e88abf2d5f98546b901bd4315John McCall
128634695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // Handle the cleanup attribute.
128740b598eea1310ec9ed554d56ce3e25b34c585458Argyrios Kyrtzidis  if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) {
128869c68b7454dc7f47def4ebf593a584d0f02c1ddbAnders Carlsson    const FunctionDecl *FD = CA->getFunctionDecl();
12891eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
129034695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    llvm::Constant *F = CGM.GetAddrOfFunction(FD);
129169c68b7454dc7f47def4ebf593a584d0f02c1ddbAnders Carlsson    assert(F && "Could not find function!");
12921eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump
1293de5d3c717684f3821b8db58037bc7140acf134aaJohn McCall    const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD);
129434695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall    EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D);
129569c68b7454dc7f47def4ebf593a584d0f02c1ddbAnders Carlsson  }
1296797b6327571f9d7b1c45404a56ddcbf9b9298ae8Mike Stump
129734695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // If this is a block variable, call _Block_object_destroy
129834695856c0e67b3765b46304cc71b5d2cd5b71c7John McCall  // (on the unforwarded address).
12995af02db5a48476e0748f135369663080eae87c64John McCall  if (emission.IsByRef)
13005af02db5a48476e0748f135369663080eae87c64John McCall    enterByrefCleanup(emission);
13015f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
13025f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
1303516bbd42e62d709013824d6fb8445a0cfda3129aPeter CollingbourneCodeGenFunction::Destroyer *
1304bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCallCodeGenFunction::getDestroyer(QualType::DestructionKind kind) {
1305bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  switch (kind) {
1306bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor");
13070850e8d1b093cfe1fc2fdf533a0e264ef9d5412eJohn McCall  case QualType::DK_cxx_destructor:
1308516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne    return destroyCXXObject;
13090850e8d1b093cfe1fc2fdf533a0e264ef9d5412eJohn McCall  case QualType::DK_objc_strong_lifetime:
1310516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne    return destroyARCStrongPrecise;
13110850e8d1b093cfe1fc2fdf533a0e264ef9d5412eJohn McCall  case QualType::DK_objc_weak_lifetime:
1312516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne    return destroyARCWeak;
1313bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  }
1314ba4be25c90566f5f214c2ad0364840c5a04ba651Matt Beaumont-Gay  llvm_unreachable("Unknown DestructionKind");
1315bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall}
1316bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1317074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCall/// pushEHDestroy - Push the standard destructor for the given type as
1318074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCall/// an EH-only cleanup.
1319074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCallvoid CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind,
1320074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCall                                  llvm::Value *addr, QualType type) {
1321074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCall  assert(dtorKind && "cannot push destructor for trivial type");
1322074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCall  assert(needsEHCleanup(dtorKind));
1323074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCall
1324074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCall  pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true);
1325074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCall}
1326074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCall
1327074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCall/// pushDestroy - Push the standard destructor for the given type as
1328074cae0861a87bf96d8ea56d02e34839d9ccbd0aJohn McCall/// at least a normal cleanup.
13299928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCallvoid CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind,
13309928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall                                  llvm::Value *addr, QualType type) {
13319928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall  assert(dtorKind && "cannot push destructor for trivial type");
13329928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall
13339928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall  CleanupKind cleanupKind = getCleanupKind(dtorKind);
13349928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall  pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind),
13359928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall              cleanupKind & EHCleanup);
13369928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall}
13379928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall
1338bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCallvoid CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr,
1339516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne                                  QualType type, Destroyer *destroyer,
13402673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                  bool useEHCleanupForArray) {
13419928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall  pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type,
13429928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall                                     destroyer, useEHCleanupForArray);
1343bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall}
1344bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
13458a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smithvoid CodeGenFunction::pushLifetimeExtendedDestroy(
13468a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith    CleanupKind cleanupKind, llvm::Value *addr, QualType type,
13478a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith    Destroyer *destroyer, bool useEHCleanupForArray) {
13488a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith  assert(!isInConditionalBranch() &&
13498a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith         "performing lifetime extension from within conditional");
13508a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith
13518a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith  // Push an EH-only cleanup for the object now.
13528a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith  // FIXME: When popping normal cleanups, we need to keep this EH cleanup
13538a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith  // around in case a temporary's destructor throws an exception.
13548a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith  if (cleanupKind & EHCleanup)
13558a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith    EHStack.pushCleanup<DestroyObject>(
13568a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith        static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type,
13578a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith        destroyer, useEHCleanupForArray);
13588a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith
13598a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith  // Remember that we need to push a full cleanup for the object at the
13608a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith  // end of the full-expression.
13618a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith  pushCleanupAfterFullExpr<DestroyObject>(
13628a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith      cleanupKind, addr, type, destroyer, useEHCleanupForArray);
13638a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith}
13648a07cd3f59a0ede54906bdc8ed21724815db27adRichard Smith
13652673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// emitDestroy - Immediately perform the destruction of the given
13662673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// object.
13672673c68aa58e277ebc755b71d81aca618cdedbf9John McCall///
13682673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// \param addr - the address of the object; a type*
13692673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// \param type - the type of the object; if an array type, all
13702673c68aa58e277ebc755b71d81aca618cdedbf9John McCall///   objects are destroyed in reverse order
13712673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// \param destroyer - the function to call to destroy individual
13722673c68aa58e277ebc755b71d81aca618cdedbf9John McCall///   elements
13732673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// \param useEHCleanupForArray - whether an EH cleanup should be
13742673c68aa58e277ebc755b71d81aca618cdedbf9John McCall///   used when destroying array elements, in case one of the
13752673c68aa58e277ebc755b71d81aca618cdedbf9John McCall///   destructions throws an exception
1376bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCallvoid CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type,
1377516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne                                  Destroyer *destroyer,
13782673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                  bool useEHCleanupForArray) {
1379bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  const ArrayType *arrayType = getContext().getAsArrayType(type);
1380bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  if (!arrayType)
1381bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    return destroyer(*this, addr, type);
1382bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1383bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  llvm::Value *begin = addr;
1384bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  llvm::Value *length = emitArrayLength(arrayType, type, begin);
1385fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall
1386fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  // Normally we have to check whether the array is zero-length.
1387fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  bool checkZeroLength = true;
1388fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall
1389fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  // But if the array length is constant, we can suppress that.
1390fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) {
1391fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall    // ...and if it's constant zero, we can just skip the entire thing.
1392fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall    if (constLength->isZero()) return;
1393fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall    checkZeroLength = false;
1394fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  }
1395fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall
1396bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  llvm::Value *end = Builder.CreateInBoundsGEP(begin, length);
1397fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  emitArrayDestroy(begin, end, type, destroyer,
1398fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall                   checkZeroLength, useEHCleanupForArray);
1399bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall}
1400bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
14012673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// emitArrayDestroy - Destroys all the elements of the given array,
14022673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// beginning from last to first.  The array cannot be zero-length.
14032673c68aa58e277ebc755b71d81aca618cdedbf9John McCall///
14042673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// \param begin - a type* denoting the first element of the array
14052673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// \param end - a type* denoting one past the end of the array
14062673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// \param type - the element type of the array
14072673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// \param destroyer - the function to call to destroy elements
14082673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// \param useEHCleanup - whether to push an EH cleanup to destroy
14092673c68aa58e277ebc755b71d81aca618cdedbf9John McCall///   the remaining elements in case the destruction of a single
14102673c68aa58e277ebc755b71d81aca618cdedbf9John McCall///   element throws
1411bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCallvoid CodeGenFunction::emitArrayDestroy(llvm::Value *begin,
1412bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall                                       llvm::Value *end,
1413bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall                                       QualType type,
1414516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne                                       Destroyer *destroyer,
1415fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall                                       bool checkZeroLength,
14162673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                       bool useEHCleanup) {
1417bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  assert(!type->isArrayType());
1418bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1419bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  // The basic structure here is a do-while loop, because we don't
1420bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  // need to check for the zero-element case.
1421bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body");
1422bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done");
1423bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1424fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  if (checkZeroLength) {
1425fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall    llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end,
1426fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall                                                "arraydestroy.isempty");
1427fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall    Builder.CreateCondBr(isEmpty, doneBB, bodyBB);
1428fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  }
1429fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall
1430bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  // Enter the loop body, making that address the current address.
1431bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  llvm::BasicBlock *entryBB = Builder.GetInsertBlock();
1432bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  EmitBlock(bodyBB);
1433bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  llvm::PHINode *elementPast =
1434bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast");
1435bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  elementPast->addIncoming(end, entryBB);
1436bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1437bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  // Shift the address back by one element.
1438bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true);
1439bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne,
1440bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall                                                   "arraydestroy.element");
1441bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
14422673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  if (useEHCleanup)
14432673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    pushRegularPartialArrayCleanup(begin, element, type, destroyer);
14442673c68aa58e277ebc755b71d81aca618cdedbf9John McCall
1445bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  // Perform the actual destruction there.
1446bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  destroyer(*this, element, type);
1447bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
14482673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  if (useEHCleanup)
14492673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    PopCleanupBlock();
14502673c68aa58e277ebc755b71d81aca618cdedbf9John McCall
1451bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  // Check whether we've reached the end.
1452bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done");
1453bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  Builder.CreateCondBr(done, doneBB, bodyBB);
1454bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  elementPast->addIncoming(element, Builder.GetInsertBlock());
1455bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1456bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  // Done.
1457bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  EmitBlock(doneBB);
1458bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall}
1459bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
14602673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// Perform partial array destruction as if in an EH cleanup.  Unlike
14612673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// emitArrayDestroy, the element type here may still be an array type.
14622673c68aa58e277ebc755b71d81aca618cdedbf9John McCallstatic void emitPartialArrayDestroy(CodeGenFunction &CGF,
14632673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                    llvm::Value *begin, llvm::Value *end,
14642673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                    QualType type,
1465516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne                                    CodeGenFunction::Destroyer *destroyer) {
14662673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  // If the element type is itself an array, drill down.
1467fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  unsigned arrayDepth = 0;
14682673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) {
14692673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    // VLAs don't require a GEP index to walk into.
14702673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    if (!isa<VariableArrayType>(arrayType))
1471fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall      arrayDepth++;
14722673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    type = arrayType->getElementType();
14732673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  }
1474fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall
1475fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  if (arrayDepth) {
1476fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall    llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1);
1477fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall
14785f9e272e632e951b1efe824cd16acb4d96077930Chris Lattner    SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero);
14790f6ac7cf7bc6a02c1a5c19d2c90ec0d1dd7786e7Jay Foad    begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin");
14800f6ac7cf7bc6a02c1a5c19d2c90ec0d1dd7786e7Jay Foad    end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend");
14812673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  }
14822673c68aa58e277ebc755b71d81aca618cdedbf9John McCall
1483fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  // Destroy the array.  We don't ever need an EH cleanup because we
1484fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  // assume that we're in an EH cleanup ourselves, so a throwing
1485fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  // destructor causes an immediate terminate.
1486fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall  CGF.emitArrayDestroy(begin, end, type, destroyer,
1487fbf780a9d1dbb191fc40c8af967c590e08724b74John McCall                       /*checkZeroLength*/ true, /*useEHCleanup*/ false);
14882673c68aa58e277ebc755b71d81aca618cdedbf9John McCall}
14892673c68aa58e277ebc755b71d81aca618cdedbf9John McCall
1490bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCallnamespace {
14912673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  /// RegularPartialArrayDestroy - a cleanup which performs a partial
14922673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  /// array destroy where the end pointer is regularly determined and
14932673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  /// does not need to be loaded from a local.
14942673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  class RegularPartialArrayDestroy : public EHScopeStack::Cleanup {
14952673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    llvm::Value *ArrayBegin;
14962673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    llvm::Value *ArrayEnd;
14972673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    QualType ElementType;
1498516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne    CodeGenFunction::Destroyer *Destroyer;
14992673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  public:
15002673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd,
15012673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                               QualType elementType,
15022673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                               CodeGenFunction::Destroyer *destroyer)
15032673c68aa58e277ebc755b71d81aca618cdedbf9John McCall      : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd),
1504516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne        ElementType(elementType), Destroyer(destroyer) {}
15052673c68aa58e277ebc755b71d81aca618cdedbf9John McCall
1506ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall    void Emit(CodeGenFunction &CGF, Flags flags) {
15072673c68aa58e277ebc755b71d81aca618cdedbf9John McCall      emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd,
15082673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                              ElementType, Destroyer);
15092673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    }
15102673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  };
15112673c68aa58e277ebc755b71d81aca618cdedbf9John McCall
15122673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  /// IrregularPartialArrayDestroy - a cleanup which performs a
15132673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  /// partial array destroy where the end pointer is irregularly
15142673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  /// determined and must be loaded from a local.
15152673c68aa58e277ebc755b71d81aca618cdedbf9John McCall  class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup {
1516bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    llvm::Value *ArrayBegin;
1517bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    llvm::Value *ArrayEndPointer;
1518bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    QualType ElementType;
1519516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne    CodeGenFunction::Destroyer *Destroyer;
1520bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  public:
15212673c68aa58e277ebc755b71d81aca618cdedbf9John McCall    IrregularPartialArrayDestroy(llvm::Value *arrayBegin,
15222673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                 llvm::Value *arrayEndPointer,
15232673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                 QualType elementType,
15242673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                 CodeGenFunction::Destroyer *destroyer)
1525bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall      : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer),
1526516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne        ElementType(elementType), Destroyer(destroyer) {}
1527bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1528ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall    void Emit(CodeGenFunction &CGF, Flags flags) {
1529bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall      llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer);
15302673c68aa58e277ebc755b71d81aca618cdedbf9John McCall      emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd,
15312673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                              ElementType, Destroyer);
1532bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall    }
1533bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall  };
1534bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall}
1535bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
15362673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy
15372673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// already-constructed elements of the given array.  The cleanup
15382673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1539e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher///
15402673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// \param elementType - the immediate element type of the array;
15412673c68aa58e277ebc755b71d81aca618cdedbf9John McCall///   possibly still an array type
15429928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCallvoid CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin,
15432673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                                 llvm::Value *arrayEndPointer,
15442673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                                       QualType elementType,
1545516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne                                                       Destroyer *destroyer) {
15469928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall  pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup,
15479928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall                                                    arrayBegin, arrayEndPointer,
1548516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne                                                    elementType, destroyer);
15492673c68aa58e277ebc755b71d81aca618cdedbf9John McCall}
15502673c68aa58e277ebc755b71d81aca618cdedbf9John McCall
15512673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy
1552bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall/// already-constructed elements of the given array.  The cleanup
15532673c68aa58e277ebc755b71d81aca618cdedbf9John McCall/// may be popped with DeactivateCleanupBlock or PopCleanupBlock.
1554e1f549028bd6850e7d85ab6bce7626050d2e8aceEric Christopher///
1555bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall/// \param elementType - the immediate element type of the array;
1556bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall///   possibly still an array type
15572673c68aa58e277ebc755b71d81aca618cdedbf9John McCallvoid CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin,
15582673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                                     llvm::Value *arrayEnd,
15592673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                                     QualType elementType,
1560516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne                                                     Destroyer *destroyer) {
15619928c4805aa8d5fabd488d0d0c5aeb64fd50f0e3John McCall  pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup,
15622673c68aa58e277ebc755b71d81aca618cdedbf9John McCall                                                  arrayBegin, arrayEnd,
1563516bbd42e62d709013824d6fb8445a0cfda3129aPeter Collingbourne                                                  elementType, destroyer);
1564bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall}
1565bdc4d80956c83a486e58d3df6bb524a1f66ff574John McCall
1566495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem/// Lazily declare the @llvm.lifetime.start intrinsic.
1567495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotemllvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() {
1568495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  if (LifetimeStartFn) return LifetimeStartFn;
1569495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(),
1570495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem                                            llvm::Intrinsic::lifetime_start);
1571495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  return LifetimeStartFn;
1572495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem}
1573495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem
1574495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem/// Lazily declare the @llvm.lifetime.end intrinsic.
1575495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotemllvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() {
1576495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  if (LifetimeEndFn) return LifetimeEndFn;
1577495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(),
1578495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem                                              llvm::Intrinsic::lifetime_end);
1579495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem  return LifetimeEndFn;
1580495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem}
1581495cfa46300979642acde8d93a1f21c9291dac98Nadav Rotem
1582f85e193739c953358c865005855253af4f68a497John McCallnamespace {
1583f85e193739c953358c865005855253af4f68a497John McCall  /// A cleanup to perform a release of an object at the end of a
1584f85e193739c953358c865005855253af4f68a497John McCall  /// function.  This is used to balance out the incoming +1 of a
1585f85e193739c953358c865005855253af4f68a497John McCall  /// ns_consumed argument when we can't reasonably do that just by
1586f85e193739c953358c865005855253af4f68a497John McCall  /// not doing the initial retain for a __block argument.
1587f85e193739c953358c865005855253af4f68a497John McCall  struct ConsumeARCParameter : EHScopeStack::Cleanup {
15885b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall    ConsumeARCParameter(llvm::Value *param,
15895b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall                        ARCPreciseLifetime_t precise)
15905b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall      : Param(param), Precise(precise) {}
1591f85e193739c953358c865005855253af4f68a497John McCall
1592f85e193739c953358c865005855253af4f68a497John McCall    llvm::Value *Param;
15935b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall    ARCPreciseLifetime_t Precise;
1594f85e193739c953358c865005855253af4f68a497John McCall
1595ad346f4f678ab1c3222425641d851dc63e9dfa1aJohn McCall    void Emit(CodeGenFunction &CGF, Flags flags) {
15965b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall      CGF.EmitARCRelease(Param, Precise);
1597f85e193739c953358c865005855253af4f68a497John McCall    }
1598f85e193739c953358c865005855253af4f68a497John McCall  };
1599f85e193739c953358c865005855253af4f68a497John McCall}
1600f85e193739c953358c865005855253af4f68a497John McCall
16011eb4433ac451dc16f4133a88af2d002ac26c58efMike Stump/// Emit an alloca (or GlobalValue depending on target)
16022621fd1d6d3c5eadcae246859f62738645df7540Chris Lattner/// for the specified parameter and set up LocalDeclMap.
1603093ac461b37a573dcf226fa55faed96f318169b9Devang Patelvoid CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg,
1604093ac461b37a573dcf226fa55faed96f318169b9Devang Patel                                   unsigned ArgNo) {
1605b7ec246872b412f0e7bb9e93eacfd78cfa6adfb3Daniel Dunbar  // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl?
160631fc07df7f0fc89ebf83ca05a20b29de45a7598dSanjiv Gupta  assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) &&
1607b7ec246872b412f0e7bb9e93eacfd78cfa6adfb3Daniel Dunbar         "Invalid argument to EmitParmDecl");
16088178df3b39ab923ff5d24538812628abee33df79John McCall
16098178df3b39ab923ff5d24538812628abee33df79John McCall  Arg->setName(D.getName());
16108178df3b39ab923ff5d24538812628abee33df79John McCall
1611836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl  QualType Ty = D.getType();
1612836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl
16138178df3b39ab923ff5d24538812628abee33df79John McCall  // Use better IR generation for certain implicit parameters.
16148178df3b39ab923ff5d24538812628abee33df79John McCall  if (isa<ImplicitParamDecl>(D)) {
16158178df3b39ab923ff5d24538812628abee33df79John McCall    // The only implicit argument a block has is its literal.
16168178df3b39ab923ff5d24538812628abee33df79John McCall    if (BlockInfo) {
16178178df3b39ab923ff5d24538812628abee33df79John McCall      LocalDeclMap[&D] = Arg;
1618836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl      llvm::Value *LocalAddr = 0;
1619836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl      if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
16209b97adfb770c3b55c1a45049d53b624bbc6f62e1Adrian Prantl        // Allocate a stack slot to let the debug info survive the RA.
1621836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl        llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1622836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl                                                   D.getName() + ".addr");
1623836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl        Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity());
1624836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl        LValue lv = MakeAddrLValue(Alloc, Ty, getContext().getDeclAlign(&D));
1625836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl        EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
1626836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl        LocalAddr = Builder.CreateLoad(Alloc);
1627836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl      }
16288178df3b39ab923ff5d24538812628abee33df79John McCall
16298178df3b39ab923ff5d24538812628abee33df79John McCall      if (CGDebugInfo *DI = getDebugInfo()) {
16304cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor        if (CGM.getCodeGenOpts().getDebugInfo()
16314cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor              >= CodeGenOptions::LimitedDebugInfo) {
1632fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov          DI->setLocation(D.getLocation());
1633836e7c9357b312fd1ee5c90898ce2c81bb384997Adrian Prantl          DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, LocalAddr, Builder);
1634fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov        }
16358178df3b39ab923ff5d24538812628abee33df79John McCall      }
16368178df3b39ab923ff5d24538812628abee33df79John McCall
16378178df3b39ab923ff5d24538812628abee33df79John McCall      return;
16388178df3b39ab923ff5d24538812628abee33df79John McCall    }
16398178df3b39ab923ff5d24538812628abee33df79John McCall  }
16408178df3b39ab923ff5d24538812628abee33df79John McCall
16415f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  llvm::Value *DeclPtr;
16429b60195ad4843c9e2e231673a0dbc0d5c8c6eb2bReid Kleckner  bool HasNonScalarEvalKind = !CodeGenFunction::hasScalarEvaluationKind(Ty);
1643e86bcf0d9ea62cc75e545787896083f8a6bc81a1Daniel Dunbar  // If this is an aggregate or variable sized value, reuse the input pointer.
16449b60195ad4843c9e2e231673a0dbc0d5c8c6eb2bReid Kleckner  if (HasNonScalarEvalKind || !Ty->isConstantSizeType()) {
16455f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer    DeclPtr = Arg;
16469b60195ad4843c9e2e231673a0dbc0d5c8c6eb2bReid Kleckner    // Push a destructor cleanup for this parameter if the ABI requires it.
16479b60195ad4843c9e2e231673a0dbc0d5c8c6eb2bReid Kleckner    if (HasNonScalarEvalKind &&
16489b60195ad4843c9e2e231673a0dbc0d5c8c6eb2bReid Kleckner        getTarget().getCXXABI().isArgumentDestroyedByCallee()) {
16499b60195ad4843c9e2e231673a0dbc0d5c8c6eb2bReid Kleckner      if (const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl()) {
16509b60195ad4843c9e2e231673a0dbc0d5c8c6eb2bReid Kleckner        if (RD->hasNonTrivialDestructor())
16519b60195ad4843c9e2e231673a0dbc0d5c8c6eb2bReid Kleckner          pushDestroy(QualType::DK_cxx_destructor, DeclPtr, Ty);
16529b60195ad4843c9e2e231673a0dbc0d5c8c6eb2bReid Kleckner      }
16539b60195ad4843c9e2e231673a0dbc0d5c8c6eb2bReid Kleckner    }
16545f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  } else {
1655e86bcf0d9ea62cc75e545787896083f8a6bc81a1Daniel Dunbar    // Otherwise, create a temporary to hold the value.
1656ddfb8d1026d8f9001d8111bd8a96d89301aa11cdEli Friedman    llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty),
1657ddfb8d1026d8f9001d8111bd8a96d89301aa11cdEli Friedman                                               D.getName() + ".addr");
165841a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian    CharUnits Align = getContext().getDeclAlign(&D);
165941a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian    Alloc->setAlignment(Align.getQuantity());
1660ddfb8d1026d8f9001d8111bd8a96d89301aa11cdEli Friedman    DeclPtr = Alloc;
1661e86bcf0d9ea62cc75e545787896083f8a6bc81a1Daniel Dunbar
1662f85e193739c953358c865005855253af4f68a497John McCall    bool doStore = true;
1663f85e193739c953358c865005855253af4f68a497John McCall
1664f85e193739c953358c865005855253af4f68a497John McCall    Qualifiers qs = Ty.getQualifiers();
166541a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian    LValue lv = MakeAddrLValue(DeclPtr, Ty, Align);
1666f85e193739c953358c865005855253af4f68a497John McCall    if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) {
1667f85e193739c953358c865005855253af4f68a497John McCall      // We honor __attribute__((ns_consumed)) for types with lifetime.
1668f85e193739c953358c865005855253af4f68a497John McCall      // For __strong, it's handled by just skipping the initial retain;
1669f85e193739c953358c865005855253af4f68a497John McCall      // otherwise we have to balance out the initial +1 with an extra
1670f85e193739c953358c865005855253af4f68a497John McCall      // cleanup to do the release at the end of the function.
1671f85e193739c953358c865005855253af4f68a497John McCall      bool isConsumed = D.hasAttr<NSConsumedAttr>();
1672f85e193739c953358c865005855253af4f68a497John McCall
1673f85e193739c953358c865005855253af4f68a497John McCall      // 'self' is always formally __strong, but if this is not an
1674f85e193739c953358c865005855253af4f68a497John McCall      // init method then we don't want to retain it.
16757acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall      if (D.isARCPseudoStrong()) {
1676f85e193739c953358c865005855253af4f68a497John McCall        const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl);
1677f85e193739c953358c865005855253af4f68a497John McCall        assert(&D == method->getSelfDecl());
16787acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall        assert(lt == Qualifiers::OCL_Strong);
16797acddacc921cd0b3f813443a8641eeddb82dfbd4John McCall        assert(qs.hasConst());
1680f85e193739c953358c865005855253af4f68a497John McCall        assert(method->getMethodFamily() != OMF_init);
1681175d6596a53508d8ac2ff844672bab0dd0bd7c91John McCall        (void) method;
1682f85e193739c953358c865005855253af4f68a497John McCall        lt = Qualifiers::OCL_ExplicitNone;
1683f85e193739c953358c865005855253af4f68a497John McCall      }
1684f85e193739c953358c865005855253af4f68a497John McCall
1685f85e193739c953358c865005855253af4f68a497John McCall      if (lt == Qualifiers::OCL_Strong) {
168641a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian        if (!isConsumed) {
168741a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian          if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
168841a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian            // use objc_storeStrong(&dest, value) for retaining the
168941a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian            // object. But first, store a null into 'dest' because
169041a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian            // objc_storeStrong attempts to release its old value.
169141a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian            llvm::Value * Null = CGM.EmitNullConstant(D.getType());
169241a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian            EmitStoreOfScalar(Null, lv, /* isInitialization */ true);
169341a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian            EmitARCStoreStrongCall(lv.getAddress(), Arg, true);
169441a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian            doStore = false;
169541a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian          }
169641a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian          else
1697f85e193739c953358c865005855253af4f68a497John McCall          // Don't use objc_retainBlock for block pointers, because we
1698f85e193739c953358c865005855253af4f68a497John McCall          // don't want to Block_copy something just because we got it
1699f85e193739c953358c865005855253af4f68a497John McCall          // as a parameter.
170041a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian            Arg = EmitARCRetainNonBlock(Arg);
170141a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian        }
1702f85e193739c953358c865005855253af4f68a497John McCall      } else {
1703f85e193739c953358c865005855253af4f68a497John McCall        // Push the cleanup for a consumed parameter.
17045b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall        if (isConsumed) {
17055b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall          ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>()
17065b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall                                ? ARCPreciseLifetime : ARCImpreciseLifetime);
17075b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall          EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg,
17085b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall                                                   precise);
17095b07e8077a20b80fee90bd76c43c6150c676e4a8John McCall        }
1710f85e193739c953358c865005855253af4f68a497John McCall
1711f85e193739c953358c865005855253af4f68a497John McCall        if (lt == Qualifiers::OCL_Weak) {
1712f85e193739c953358c865005855253af4f68a497John McCall          EmitARCInitWeak(DeclPtr, Arg);
17137acebfb71f16a8bb15add402ab915d23c64d912fChad Rosier          doStore = false; // The weak init is a store, no need to do two.
1714f85e193739c953358c865005855253af4f68a497John McCall        }
1715f85e193739c953358c865005855253af4f68a497John McCall      }
1716f85e193739c953358c865005855253af4f68a497John McCall
1717f85e193739c953358c865005855253af4f68a497John McCall      // Enter the cleanup scope.
1718f85e193739c953358c865005855253af4f68a497John McCall      EmitAutoVarWithLifetime(*this, D, DeclPtr, lt);
1719f85e193739c953358c865005855253af4f68a497John McCall    }
1720f85e193739c953358c865005855253af4f68a497John McCall
1721e86bcf0d9ea62cc75e545787896083f8a6bc81a1Daniel Dunbar    // Store the initial value into the alloca.
172241a6a3e064192e98a48f5fabccf262412fe37d10Fariborz Jahanian    if (doStore)
17237a7ee3033e44b45630981355460ef89efa0bdcc4David Chisnall      EmitStoreOfScalar(Arg, lv, /* isInitialization */ true);
17245f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  }
17255f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer
17265f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  llvm::Value *&DMEntry = LocalDeclMap[&D];
17275f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  assert(DMEntry == 0 && "Decl already exists in localdeclmap!");
17285f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer  DMEntry = DeclPtr;
1729cc9b16394fe6c9245dc4f8661a63d0c3937b62f0Sanjiv Gupta
1730cc9b16394fe6c9245dc4f8661a63d0c3937b62f0Sanjiv Gupta  // Emit debug info for param declaration.
1731fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov  if (CGDebugInfo *DI = getDebugInfo()) {
17324cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor    if (CGM.getCodeGenOpts().getDebugInfo()
17334cdad3151bfb2075c6bdbfe89fbb08f31a90a45bDouglas Gregor          >= CodeGenOptions::LimitedDebugInfo) {
1734fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov      DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder);
1735fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov    }
1736fd00eecad6fa5400cf37269d84361a0551d0e6d3Alexey Samsonov  }
173777f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge
173877f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge  if (D.hasAttr<AnnotateAttr>())
173977f68bb90af93b95045fb994e7cd68137adcc132Julien Lerouge      EmitVarAnnotations(&D, DeclPtr);
17405f016e2cb5d11daeb237544de1c5d59f20fe1a6eReid Spencer}
1741