clang API Documentation
00001 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This contains code to emit Decl nodes as LLVM code. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "CGDebugInfo.h" 00015 #include "CodeGenFunction.h" 00016 #include "CodeGenModule.h" 00017 #include "CGOpenCLRuntime.h" 00018 #include "clang/AST/ASTContext.h" 00019 #include "clang/AST/CharUnits.h" 00020 #include "clang/AST/Decl.h" 00021 #include "clang/AST/DeclObjC.h" 00022 #include "clang/Basic/SourceManager.h" 00023 #include "clang/Basic/TargetInfo.h" 00024 #include "clang/Frontend/CodeGenOptions.h" 00025 #include "llvm/GlobalVariable.h" 00026 #include "llvm/Intrinsics.h" 00027 #include "llvm/Target/TargetData.h" 00028 #include "llvm/Type.h" 00029 using namespace clang; 00030 using namespace CodeGen; 00031 00032 00033 void CodeGenFunction::EmitDecl(const Decl &D) { 00034 switch (D.getKind()) { 00035 case Decl::TranslationUnit: 00036 case Decl::Namespace: 00037 case Decl::UnresolvedUsingTypename: 00038 case Decl::ClassTemplateSpecialization: 00039 case Decl::ClassTemplatePartialSpecialization: 00040 case Decl::TemplateTypeParm: 00041 case Decl::UnresolvedUsingValue: 00042 case Decl::NonTypeTemplateParm: 00043 case Decl::CXXMethod: 00044 case Decl::CXXConstructor: 00045 case Decl::CXXDestructor: 00046 case Decl::CXXConversion: 00047 case Decl::Field: 00048 case Decl::IndirectField: 00049 case Decl::ObjCIvar: 00050 case Decl::ObjCAtDefsField: 00051 case Decl::ParmVar: 00052 case Decl::ImplicitParam: 00053 case Decl::ClassTemplate: 00054 case Decl::FunctionTemplate: 00055 case Decl::TypeAliasTemplate: 00056 case Decl::TemplateTemplateParm: 00057 case Decl::ObjCMethod: 00058 case Decl::ObjCCategory: 00059 case Decl::ObjCProtocol: 00060 case Decl::ObjCInterface: 00061 case Decl::ObjCCategoryImpl: 00062 case Decl::ObjCImplementation: 00063 case Decl::ObjCProperty: 00064 case Decl::ObjCCompatibleAlias: 00065 case Decl::AccessSpec: 00066 case Decl::LinkageSpec: 00067 case Decl::ObjCPropertyImpl: 00068 case Decl::FileScopeAsm: 00069 case Decl::Friend: 00070 case Decl::FriendTemplate: 00071 case Decl::Block: 00072 case Decl::ClassScopeFunctionSpecialization: 00073 llvm_unreachable("Declaration should not be in declstmts!"); 00074 case Decl::Function: // void X(); 00075 case Decl::Record: // struct/union/class X; 00076 case Decl::Enum: // enum X; 00077 case Decl::EnumConstant: // enum ? { X = ? } 00078 case Decl::CXXRecord: // struct/union/class X; [C++] 00079 case Decl::Using: // using X; [C++] 00080 case Decl::UsingShadow: 00081 case Decl::UsingDirective: // using namespace X; [C++] 00082 case Decl::NamespaceAlias: 00083 case Decl::StaticAssert: // static_assert(X, ""); [C++0x] 00084 case Decl::Label: // __label__ x; 00085 case Decl::Import: 00086 // None of these decls require codegen support. 00087 return; 00088 00089 case Decl::Var: { 00090 const VarDecl &VD = cast<VarDecl>(D); 00091 assert(VD.isLocalVarDecl() && 00092 "Should not see file-scope variables inside a function!"); 00093 return EmitVarDecl(VD); 00094 } 00095 00096 case Decl::Typedef: // typedef int X; 00097 case Decl::TypeAlias: { // using X = int; [C++0x] 00098 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D); 00099 QualType Ty = TD.getUnderlyingType(); 00100 00101 if (Ty->isVariablyModifiedType()) 00102 EmitVariablyModifiedType(Ty); 00103 } 00104 } 00105 } 00106 00107 /// EmitVarDecl - This method handles emission of any variable declaration 00108 /// inside a function, including static vars etc. 00109 void CodeGenFunction::EmitVarDecl(const VarDecl &D) { 00110 switch (D.getStorageClass()) { 00111 case SC_None: 00112 case SC_Auto: 00113 case SC_Register: 00114 return EmitAutoVarDecl(D); 00115 case SC_Static: { 00116 llvm::GlobalValue::LinkageTypes Linkage = 00117 llvm::GlobalValue::InternalLinkage; 00118 00119 // If the function definition has some sort of weak linkage, its 00120 // static variables should also be weak so that they get properly 00121 // uniqued. We can't do this in C, though, because there's no 00122 // standard way to agree on which variables are the same (i.e. 00123 // there's no mangling). 00124 if (getContext().getLangOpts().CPlusPlus) 00125 if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage())) 00126 Linkage = CurFn->getLinkage(); 00127 00128 return EmitStaticVarDecl(D, Linkage); 00129 } 00130 case SC_Extern: 00131 case SC_PrivateExtern: 00132 // Don't emit it now, allow it to be emitted lazily on its first use. 00133 return; 00134 case SC_OpenCLWorkGroupLocal: 00135 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D); 00136 } 00137 00138 llvm_unreachable("Unknown storage class"); 00139 } 00140 00141 static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D, 00142 const char *Separator) { 00143 CodeGenModule &CGM = CGF.CGM; 00144 if (CGF.getContext().getLangOpts().CPlusPlus) { 00145 StringRef Name = CGM.getMangledName(&D); 00146 return Name.str(); 00147 } 00148 00149 std::string ContextName; 00150 if (!CGF.CurFuncDecl) { 00151 // Better be in a block declared in global scope. 00152 const NamedDecl *ND = cast<NamedDecl>(&D); 00153 const DeclContext *DC = ND->getDeclContext(); 00154 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) { 00155 MangleBuffer Name; 00156 CGM.getBlockMangledName(GlobalDecl(), Name, BD); 00157 ContextName = Name.getString(); 00158 } 00159 else 00160 llvm_unreachable("Unknown context for block static var decl"); 00161 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) { 00162 StringRef Name = CGM.getMangledName(FD); 00163 ContextName = Name.str(); 00164 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) 00165 ContextName = CGF.CurFn->getName(); 00166 else 00167 llvm_unreachable("Unknown context for static var decl"); 00168 00169 return ContextName + Separator + D.getNameAsString(); 00170 } 00171 00172 llvm::GlobalVariable * 00173 CodeGenFunction::CreateStaticVarDecl(const VarDecl &D, 00174 const char *Separator, 00175 llvm::GlobalValue::LinkageTypes Linkage) { 00176 QualType Ty = D.getType(); 00177 assert(Ty->isConstantSizeType() && "VLAs can't be static"); 00178 00179 // Use the label if the variable is renamed with the asm-label extension. 00180 std::string Name; 00181 if (D.hasAttr<AsmLabelAttr>()) 00182 Name = CGM.getMangledName(&D); 00183 else 00184 Name = GetStaticDeclName(*this, D, Separator); 00185 00186 llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty); 00187 llvm::GlobalVariable *GV = 00188 new llvm::GlobalVariable(CGM.getModule(), LTy, 00189 Ty.isConstant(getContext()), Linkage, 00190 CGM.EmitNullConstant(D.getType()), Name, 0, 00191 D.isThreadSpecified(), 00192 CGM.getContext().getTargetAddressSpace(Ty)); 00193 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 00194 if (Linkage != llvm::GlobalValue::InternalLinkage) 00195 GV->setVisibility(CurFn->getVisibility()); 00196 return GV; 00197 } 00198 00199 /// hasNontrivialDestruction - Determine whether a type's destruction is 00200 /// non-trivial. If so, and the variable uses static initialization, we must 00201 /// register its destructor to run on exit. 00202 static bool hasNontrivialDestruction(QualType T) { 00203 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 00204 return RD && !RD->hasTrivialDestructor(); 00205 } 00206 00207 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 00208 /// global variable that has already been created for it. If the initializer 00209 /// has a different type than GV does, this may free GV and return a different 00210 /// one. Otherwise it just returns GV. 00211 llvm::GlobalVariable * 00212 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D, 00213 llvm::GlobalVariable *GV) { 00214 llvm::Constant *Init = CGM.EmitConstantInit(D, this); 00215 00216 // If constant emission failed, then this should be a C++ static 00217 // initializer. 00218 if (!Init) { 00219 if (!getContext().getLangOpts().CPlusPlus) 00220 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression"); 00221 else if (Builder.GetInsertBlock()) { 00222 // Since we have a static initializer, this global variable can't 00223 // be constant. 00224 GV->setConstant(false); 00225 00226 EmitCXXGuardedInit(D, GV, /*PerformInit*/true); 00227 } 00228 return GV; 00229 } 00230 00231 // The initializer may differ in type from the global. Rewrite 00232 // the global to match the initializer. (We have to do this 00233 // because some types, like unions, can't be completely represented 00234 // in the LLVM type system.) 00235 if (GV->getType()->getElementType() != Init->getType()) { 00236 llvm::GlobalVariable *OldGV = GV; 00237 00238 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 00239 OldGV->isConstant(), 00240 OldGV->getLinkage(), Init, "", 00241 /*InsertBefore*/ OldGV, 00242 D.isThreadSpecified(), 00243 CGM.getContext().getTargetAddressSpace(D.getType())); 00244 GV->setVisibility(OldGV->getVisibility()); 00245 00246 // Steal the name of the old global 00247 GV->takeName(OldGV); 00248 00249 // Replace all uses of the old global with the new global 00250 llvm::Constant *NewPtrForOldDecl = 00251 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 00252 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 00253 00254 // Erase the old global, since it is no longer used. 00255 OldGV->eraseFromParent(); 00256 } 00257 00258 GV->setConstant(CGM.isTypeConstant(D.getType(), true)); 00259 GV->setInitializer(Init); 00260 00261 if (hasNontrivialDestruction(D.getType())) { 00262 // We have a constant initializer, but a nontrivial destructor. We still 00263 // need to perform a guarded "initialization" in order to register the 00264 // destructor. 00265 EmitCXXGuardedInit(D, GV, /*PerformInit*/false); 00266 } 00267 00268 return GV; 00269 } 00270 00271 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D, 00272 llvm::GlobalValue::LinkageTypes Linkage) { 00273 llvm::Value *&DMEntry = LocalDeclMap[&D]; 00274 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 00275 00276 // Check to see if we already have a global variable for this 00277 // declaration. This can happen when double-emitting function 00278 // bodies, e.g. with complete and base constructors. 00279 llvm::Constant *addr = 00280 CGM.getStaticLocalDeclAddress(&D); 00281 00282 llvm::GlobalVariable *var; 00283 if (addr) { 00284 var = cast<llvm::GlobalVariable>(addr->stripPointerCasts()); 00285 } else { 00286 addr = var = CreateStaticVarDecl(D, ".", Linkage); 00287 } 00288 00289 // Store into LocalDeclMap before generating initializer to handle 00290 // circular references. 00291 DMEntry = addr; 00292 CGM.setStaticLocalDeclAddress(&D, addr); 00293 00294 // We can't have a VLA here, but we can have a pointer to a VLA, 00295 // even though that doesn't really make any sense. 00296 // Make sure to evaluate VLA bounds now so that we have them for later. 00297 if (D.getType()->isVariablyModifiedType()) 00298 EmitVariablyModifiedType(D.getType()); 00299 00300 // Save the type in case adding the initializer forces a type change. 00301 llvm::Type *expectedType = addr->getType(); 00302 00303 // If this value has an initializer, emit it. 00304 if (D.getInit()) 00305 var = AddInitializerToStaticVarDecl(D, var); 00306 00307 var->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 00308 00309 if (D.hasAttr<AnnotateAttr>()) 00310 CGM.AddGlobalAnnotations(&D, var); 00311 00312 if (const SectionAttr *SA = D.getAttr<SectionAttr>()) 00313 var->setSection(SA->getName()); 00314 00315 if (D.hasAttr<UsedAttr>()) 00316 CGM.AddUsedGlobal(var); 00317 00318 // We may have to cast the constant because of the initializer 00319 // mismatch above. 00320 // 00321 // FIXME: It is really dangerous to store this in the map; if anyone 00322 // RAUW's the GV uses of this constant will be invalid. 00323 llvm::Constant *castedAddr = llvm::ConstantExpr::getBitCast(var, expectedType); 00324 DMEntry = castedAddr; 00325 CGM.setStaticLocalDeclAddress(&D, castedAddr); 00326 00327 // Emit global variable debug descriptor for static vars. 00328 CGDebugInfo *DI = getDebugInfo(); 00329 if (DI && 00330 CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) { 00331 DI->setLocation(D.getLocation()); 00332 DI->EmitGlobalVariable(var, &D); 00333 } 00334 } 00335 00336 namespace { 00337 struct DestroyObject : EHScopeStack::Cleanup { 00338 DestroyObject(llvm::Value *addr, QualType type, 00339 CodeGenFunction::Destroyer *destroyer, 00340 bool useEHCleanupForArray) 00341 : addr(addr), type(type), destroyer(destroyer), 00342 useEHCleanupForArray(useEHCleanupForArray) {} 00343 00344 llvm::Value *addr; 00345 QualType type; 00346 CodeGenFunction::Destroyer *destroyer; 00347 bool useEHCleanupForArray; 00348 00349 void Emit(CodeGenFunction &CGF, Flags flags) { 00350 // Don't use an EH cleanup recursively from an EH cleanup. 00351 bool useEHCleanupForArray = 00352 flags.isForNormalCleanup() && this->useEHCleanupForArray; 00353 00354 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray); 00355 } 00356 }; 00357 00358 struct DestroyNRVOVariable : EHScopeStack::Cleanup { 00359 DestroyNRVOVariable(llvm::Value *addr, 00360 const CXXDestructorDecl *Dtor, 00361 llvm::Value *NRVOFlag) 00362 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(addr) {} 00363 00364 const CXXDestructorDecl *Dtor; 00365 llvm::Value *NRVOFlag; 00366 llvm::Value *Loc; 00367 00368 void Emit(CodeGenFunction &CGF, Flags flags) { 00369 // Along the exceptions path we always execute the dtor. 00370 bool NRVO = flags.isForNormalCleanup() && NRVOFlag; 00371 00372 llvm::BasicBlock *SkipDtorBB = 0; 00373 if (NRVO) { 00374 // If we exited via NRVO, we skip the destructor call. 00375 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused"); 00376 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor"); 00377 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val"); 00378 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB); 00379 CGF.EmitBlock(RunDtorBB); 00380 } 00381 00382 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 00383 /*ForVirtualBase=*/false, Loc); 00384 00385 if (NRVO) CGF.EmitBlock(SkipDtorBB); 00386 } 00387 }; 00388 00389 struct CallStackRestore : EHScopeStack::Cleanup { 00390 llvm::Value *Stack; 00391 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {} 00392 void Emit(CodeGenFunction &CGF, Flags flags) { 00393 llvm::Value *V = CGF.Builder.CreateLoad(Stack); 00394 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 00395 CGF.Builder.CreateCall(F, V); 00396 } 00397 }; 00398 00399 struct ExtendGCLifetime : EHScopeStack::Cleanup { 00400 const VarDecl &Var; 00401 ExtendGCLifetime(const VarDecl *var) : Var(*var) {} 00402 00403 void Emit(CodeGenFunction &CGF, Flags flags) { 00404 // Compute the address of the local variable, in case it's a 00405 // byref or something. 00406 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false, 00407 Var.getType(), VK_LValue, SourceLocation()); 00408 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE)); 00409 CGF.EmitExtendGCLifetime(value); 00410 } 00411 }; 00412 00413 struct CallCleanupFunction : EHScopeStack::Cleanup { 00414 llvm::Constant *CleanupFn; 00415 const CGFunctionInfo &FnInfo; 00416 const VarDecl &Var; 00417 00418 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info, 00419 const VarDecl *Var) 00420 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {} 00421 00422 void Emit(CodeGenFunction &CGF, Flags flags) { 00423 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false, 00424 Var.getType(), VK_LValue, SourceLocation()); 00425 // Compute the address of the local variable, in case it's a byref 00426 // or something. 00427 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress(); 00428 00429 // In some cases, the type of the function argument will be different from 00430 // the type of the pointer. An example of this is 00431 // void f(void* arg); 00432 // __attribute__((cleanup(f))) void *g; 00433 // 00434 // To fix this we insert a bitcast here. 00435 QualType ArgTy = FnInfo.arg_begin()->type; 00436 llvm::Value *Arg = 00437 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy)); 00438 00439 CallArgList Args; 00440 Args.add(RValue::get(Arg), 00441 CGF.getContext().getPointerType(Var.getType())); 00442 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args); 00443 } 00444 }; 00445 } 00446 00447 /// EmitAutoVarWithLifetime - Does the setup required for an automatic 00448 /// variable with lifetime. 00449 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var, 00450 llvm::Value *addr, 00451 Qualifiers::ObjCLifetime lifetime) { 00452 switch (lifetime) { 00453 case Qualifiers::OCL_None: 00454 llvm_unreachable("present but none"); 00455 00456 case Qualifiers::OCL_ExplicitNone: 00457 // nothing to do 00458 break; 00459 00460 case Qualifiers::OCL_Strong: { 00461 CodeGenFunction::Destroyer *destroyer = 00462 (var.hasAttr<ObjCPreciseLifetimeAttr>() 00463 ? CodeGenFunction::destroyARCStrongPrecise 00464 : CodeGenFunction::destroyARCStrongImprecise); 00465 00466 CleanupKind cleanupKind = CGF.getARCCleanupKind(); 00467 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer, 00468 cleanupKind & EHCleanup); 00469 break; 00470 } 00471 case Qualifiers::OCL_Autoreleasing: 00472 // nothing to do 00473 break; 00474 00475 case Qualifiers::OCL_Weak: 00476 // __weak objects always get EH cleanups; otherwise, exceptions 00477 // could cause really nasty crashes instead of mere leaks. 00478 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(), 00479 CodeGenFunction::destroyARCWeak, 00480 /*useEHCleanup*/ true); 00481 break; 00482 } 00483 } 00484 00485 static bool isAccessedBy(const VarDecl &var, const Stmt *s) { 00486 if (const Expr *e = dyn_cast<Expr>(s)) { 00487 // Skip the most common kinds of expressions that make 00488 // hierarchy-walking expensive. 00489 s = e = e->IgnoreParenCasts(); 00490 00491 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) 00492 return (ref->getDecl() == &var); 00493 } 00494 00495 for (Stmt::const_child_range children = s->children(); children; ++children) 00496 // children might be null; as in missing decl or conditional of an if-stmt. 00497 if ((*children) && isAccessedBy(var, *children)) 00498 return true; 00499 00500 return false; 00501 } 00502 00503 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) { 00504 if (!decl) return false; 00505 if (!isa<VarDecl>(decl)) return false; 00506 const VarDecl *var = cast<VarDecl>(decl); 00507 return isAccessedBy(*var, e); 00508 } 00509 00510 static void drillIntoBlockVariable(CodeGenFunction &CGF, 00511 LValue &lvalue, 00512 const VarDecl *var) { 00513 lvalue.setAddress(CGF.BuildBlockByrefAddress(lvalue.getAddress(), var)); 00514 } 00515 00516 void CodeGenFunction::EmitScalarInit(const Expr *init, 00517 const ValueDecl *D, 00518 LValue lvalue, 00519 bool capturedByInit) { 00520 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime(); 00521 if (!lifetime) { 00522 llvm::Value *value = EmitScalarExpr(init); 00523 if (capturedByInit) 00524 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 00525 EmitStoreThroughLValue(RValue::get(value), lvalue, true); 00526 return; 00527 } 00528 00529 // If we're emitting a value with lifetime, we have to do the 00530 // initialization *before* we leave the cleanup scopes. 00531 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) { 00532 enterFullExpression(ewc); 00533 init = ewc->getSubExpr(); 00534 } 00535 CodeGenFunction::RunCleanupsScope Scope(*this); 00536 00537 // We have to maintain the illusion that the variable is 00538 // zero-initialized. If the variable might be accessed in its 00539 // initializer, zero-initialize before running the initializer, then 00540 // actually perform the initialization with an assign. 00541 bool accessedByInit = false; 00542 if (lifetime != Qualifiers::OCL_ExplicitNone) 00543 accessedByInit = (capturedByInit || isAccessedBy(D, init)); 00544 if (accessedByInit) { 00545 LValue tempLV = lvalue; 00546 // Drill down to the __block object if necessary. 00547 if (capturedByInit) { 00548 // We can use a simple GEP for this because it can't have been 00549 // moved yet. 00550 tempLV.setAddress(Builder.CreateStructGEP(tempLV.getAddress(), 00551 getByRefValueLLVMField(cast<VarDecl>(D)))); 00552 } 00553 00554 llvm::PointerType *ty 00555 = cast<llvm::PointerType>(tempLV.getAddress()->getType()); 00556 ty = cast<llvm::PointerType>(ty->getElementType()); 00557 00558 llvm::Value *zero = llvm::ConstantPointerNull::get(ty); 00559 00560 // If __weak, we want to use a barrier under certain conditions. 00561 if (lifetime == Qualifiers::OCL_Weak) 00562 EmitARCInitWeak(tempLV.getAddress(), zero); 00563 00564 // Otherwise just do a simple store. 00565 else 00566 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true); 00567 } 00568 00569 // Emit the initializer. 00570 llvm::Value *value = 0; 00571 00572 switch (lifetime) { 00573 case Qualifiers::OCL_None: 00574 llvm_unreachable("present but none"); 00575 00576 case Qualifiers::OCL_ExplicitNone: 00577 // nothing to do 00578 value = EmitScalarExpr(init); 00579 break; 00580 00581 case Qualifiers::OCL_Strong: { 00582 value = EmitARCRetainScalarExpr(init); 00583 break; 00584 } 00585 00586 case Qualifiers::OCL_Weak: { 00587 // No way to optimize a producing initializer into this. It's not 00588 // worth optimizing for, because the value will immediately 00589 // disappear in the common case. 00590 value = EmitScalarExpr(init); 00591 00592 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 00593 if (accessedByInit) 00594 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true); 00595 else 00596 EmitARCInitWeak(lvalue.getAddress(), value); 00597 return; 00598 } 00599 00600 case Qualifiers::OCL_Autoreleasing: 00601 value = EmitARCRetainAutoreleaseScalarExpr(init); 00602 break; 00603 } 00604 00605 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 00606 00607 // If the variable might have been accessed by its initializer, we 00608 // might have to initialize with a barrier. We have to do this for 00609 // both __weak and __strong, but __weak got filtered out above. 00610 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) { 00611 llvm::Value *oldValue = EmitLoadOfScalar(lvalue); 00612 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 00613 EmitARCRelease(oldValue, /*precise*/ false); 00614 return; 00615 } 00616 00617 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 00618 } 00619 00620 /// EmitScalarInit - Initialize the given lvalue with the given object. 00621 void CodeGenFunction::EmitScalarInit(llvm::Value *init, LValue lvalue) { 00622 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime(); 00623 if (!lifetime) 00624 return EmitStoreThroughLValue(RValue::get(init), lvalue, true); 00625 00626 switch (lifetime) { 00627 case Qualifiers::OCL_None: 00628 llvm_unreachable("present but none"); 00629 00630 case Qualifiers::OCL_ExplicitNone: 00631 // nothing to do 00632 break; 00633 00634 case Qualifiers::OCL_Strong: 00635 init = EmitARCRetain(lvalue.getType(), init); 00636 break; 00637 00638 case Qualifiers::OCL_Weak: 00639 // Initialize and then skip the primitive store. 00640 EmitARCInitWeak(lvalue.getAddress(), init); 00641 return; 00642 00643 case Qualifiers::OCL_Autoreleasing: 00644 init = EmitARCRetainAutorelease(lvalue.getType(), init); 00645 break; 00646 } 00647 00648 EmitStoreOfScalar(init, lvalue, /* isInitialization */ true); 00649 } 00650 00651 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the 00652 /// non-zero parts of the specified initializer with equal or fewer than 00653 /// NumStores scalar stores. 00654 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init, 00655 unsigned &NumStores) { 00656 // Zero and Undef never requires any extra stores. 00657 if (isa<llvm::ConstantAggregateZero>(Init) || 00658 isa<llvm::ConstantPointerNull>(Init) || 00659 isa<llvm::UndefValue>(Init)) 00660 return true; 00661 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 00662 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 00663 isa<llvm::ConstantExpr>(Init)) 00664 return Init->isNullValue() || NumStores--; 00665 00666 // See if we can emit each element. 00667 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) { 00668 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 00669 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 00670 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores)) 00671 return false; 00672 } 00673 return true; 00674 } 00675 00676 if (llvm::ConstantDataSequential *CDS = 00677 dyn_cast<llvm::ConstantDataSequential>(Init)) { 00678 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 00679 llvm::Constant *Elt = CDS->getElementAsConstant(i); 00680 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores)) 00681 return false; 00682 } 00683 return true; 00684 } 00685 00686 // Anything else is hard and scary. 00687 return false; 00688 } 00689 00690 /// emitStoresForInitAfterMemset - For inits that 00691 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar 00692 /// stores that would be required. 00693 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc, 00694 bool isVolatile, CGBuilderTy &Builder) { 00695 // Zero doesn't require a store. 00696 if (Init->isNullValue() || isa<llvm::UndefValue>(Init)) 00697 return; 00698 00699 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 00700 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 00701 isa<llvm::ConstantExpr>(Init)) { 00702 Builder.CreateStore(Init, Loc, isVolatile); 00703 return; 00704 } 00705 00706 if (llvm::ConstantDataSequential *CDS = 00707 dyn_cast<llvm::ConstantDataSequential>(Init)) { 00708 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 00709 llvm::Constant *Elt = CDS->getElementAsConstant(i); 00710 00711 // Get a pointer to the element and emit it. 00712 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i), 00713 isVolatile, Builder); 00714 } 00715 return; 00716 } 00717 00718 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) && 00719 "Unknown value type!"); 00720 00721 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 00722 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 00723 // Get a pointer to the element and emit it. 00724 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i), 00725 isVolatile, Builder); 00726 } 00727 } 00728 00729 00730 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset 00731 /// plus some stores to initialize a local variable instead of using a memcpy 00732 /// from a constant global. It is beneficial to use memset if the global is all 00733 /// zeros, or mostly zeros and large. 00734 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init, 00735 uint64_t GlobalSize) { 00736 // If a global is all zeros, always use a memset. 00737 if (isa<llvm::ConstantAggregateZero>(Init)) return true; 00738 00739 00740 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large, 00741 // do it if it will require 6 or fewer scalar stores. 00742 // TODO: Should budget depends on the size? Avoiding a large global warrants 00743 // plopping in more stores. 00744 unsigned StoreBudget = 6; 00745 uint64_t SizeLimit = 32; 00746 00747 return GlobalSize > SizeLimit && 00748 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget); 00749 } 00750 00751 00752 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a 00753 /// variable declaration with auto, register, or no storage class specifier. 00754 /// These turn into simple stack objects, or GlobalValues depending on target. 00755 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) { 00756 AutoVarEmission emission = EmitAutoVarAlloca(D); 00757 EmitAutoVarInit(emission); 00758 EmitAutoVarCleanups(emission); 00759 } 00760 00761 /// EmitAutoVarAlloca - Emit the alloca and debug information for a 00762 /// local variable. Does not emit initalization or destruction. 00763 CodeGenFunction::AutoVarEmission 00764 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) { 00765 QualType Ty = D.getType(); 00766 00767 AutoVarEmission emission(D); 00768 00769 bool isByRef = D.hasAttr<BlocksAttr>(); 00770 emission.IsByRef = isByRef; 00771 00772 CharUnits alignment = getContext().getDeclAlign(&D); 00773 emission.Alignment = alignment; 00774 00775 // If the type is variably-modified, emit all the VLA sizes for it. 00776 if (Ty->isVariablyModifiedType()) 00777 EmitVariablyModifiedType(Ty); 00778 00779 llvm::Value *DeclPtr; 00780 if (Ty->isConstantSizeType()) { 00781 if (!Target.useGlobalsForAutomaticVariables()) { 00782 bool NRVO = getContext().getLangOpts().ElideConstructors && 00783 D.isNRVOVariable(); 00784 00785 // If this value is a POD array or struct with a statically 00786 // determinable constant initializer, there are optimizations we can do. 00787 // 00788 // TODO: We should constant-evaluate the initializer of any variable, 00789 // as long as it is initialized by a constant expression. Currently, 00790 // isConstantInitializer produces wrong answers for structs with 00791 // reference or bitfield members, and a few other cases, and checking 00792 // for POD-ness protects us from some of these. 00793 if (D.getInit() && 00794 (Ty->isArrayType() || Ty->isRecordType()) && 00795 (Ty.isPODType(getContext()) || 00796 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) && 00797 D.getInit()->isConstantInitializer(getContext(), false)) { 00798 00799 // If the variable's a const type, and it's neither an NRVO 00800 // candidate nor a __block variable and has no mutable members, 00801 // emit it as a global instead. 00802 if (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef && 00803 CGM.isTypeConstant(Ty, true)) { 00804 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage); 00805 00806 emission.Address = 0; // signal this condition to later callbacks 00807 assert(emission.wasEmittedAsGlobal()); 00808 return emission; 00809 } 00810 00811 // Otherwise, tell the initialization code that we're in this case. 00812 emission.IsConstantAggregate = true; 00813 } 00814 00815 // A normal fixed sized variable becomes an alloca in the entry block, 00816 // unless it's an NRVO variable. 00817 llvm::Type *LTy = ConvertTypeForMem(Ty); 00818 00819 if (NRVO) { 00820 // The named return value optimization: allocate this variable in the 00821 // return slot, so that we can elide the copy when returning this 00822 // variable (C++0x [class.copy]p34). 00823 DeclPtr = ReturnValue; 00824 00825 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 00826 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) { 00827 // Create a flag that is used to indicate when the NRVO was applied 00828 // to this variable. Set it to zero to indicate that NRVO was not 00829 // applied. 00830 llvm::Value *Zero = Builder.getFalse(); 00831 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo"); 00832 EnsureInsertPoint(); 00833 Builder.CreateStore(Zero, NRVOFlag); 00834 00835 // Record the NRVO flag for this variable. 00836 NRVOFlags[&D] = NRVOFlag; 00837 emission.NRVOFlag = NRVOFlag; 00838 } 00839 } 00840 } else { 00841 if (isByRef) 00842 LTy = BuildByRefType(&D); 00843 00844 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy); 00845 Alloc->setName(D.getName()); 00846 00847 CharUnits allocaAlignment = alignment; 00848 if (isByRef) 00849 allocaAlignment = std::max(allocaAlignment, 00850 getContext().toCharUnitsFromBits(Target.getPointerAlign(0))); 00851 Alloc->setAlignment(allocaAlignment.getQuantity()); 00852 DeclPtr = Alloc; 00853 } 00854 } else { 00855 // Targets that don't support recursion emit locals as globals. 00856 const char *Class = 00857 D.getStorageClass() == SC_Register ? ".reg." : ".auto."; 00858 DeclPtr = CreateStaticVarDecl(D, Class, 00859 llvm::GlobalValue::InternalLinkage); 00860 } 00861 } else { 00862 EnsureInsertPoint(); 00863 00864 if (!DidCallStackSave) { 00865 // Save the stack. 00866 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack"); 00867 00868 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 00869 llvm::Value *V = Builder.CreateCall(F); 00870 00871 Builder.CreateStore(V, Stack); 00872 00873 DidCallStackSave = true; 00874 00875 // Push a cleanup block and restore the stack there. 00876 // FIXME: in general circumstances, this should be an EH cleanup. 00877 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack); 00878 } 00879 00880 llvm::Value *elementCount; 00881 QualType elementType; 00882 llvm::tie(elementCount, elementType) = getVLASize(Ty); 00883 00884 llvm::Type *llvmTy = ConvertTypeForMem(elementType); 00885 00886 // Allocate memory for the array. 00887 llvm::AllocaInst *vla = Builder.CreateAlloca(llvmTy, elementCount, "vla"); 00888 vla->setAlignment(alignment.getQuantity()); 00889 00890 DeclPtr = vla; 00891 } 00892 00893 llvm::Value *&DMEntry = LocalDeclMap[&D]; 00894 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 00895 DMEntry = DeclPtr; 00896 emission.Address = DeclPtr; 00897 00898 // Emit debug info for local var declaration. 00899 if (HaveInsertPoint()) 00900 if (CGDebugInfo *DI = getDebugInfo()) { 00901 if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) { 00902 DI->setLocation(D.getLocation()); 00903 if (Target.useGlobalsForAutomaticVariables()) { 00904 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), 00905 &D); 00906 } else 00907 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder); 00908 } 00909 } 00910 00911 if (D.hasAttr<AnnotateAttr>()) 00912 EmitVarAnnotations(&D, emission.Address); 00913 00914 return emission; 00915 } 00916 00917 /// Determines whether the given __block variable is potentially 00918 /// captured by the given expression. 00919 static bool isCapturedBy(const VarDecl &var, const Expr *e) { 00920 // Skip the most common kinds of expressions that make 00921 // hierarchy-walking expensive. 00922 e = e->IgnoreParenCasts(); 00923 00924 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) { 00925 const BlockDecl *block = be->getBlockDecl(); 00926 for (BlockDecl::capture_const_iterator i = block->capture_begin(), 00927 e = block->capture_end(); i != e; ++i) { 00928 if (i->getVariable() == &var) 00929 return true; 00930 } 00931 00932 // No need to walk into the subexpressions. 00933 return false; 00934 } 00935 00936 if (const StmtExpr *SE = dyn_cast<StmtExpr>(e)) { 00937 const CompoundStmt *CS = SE->getSubStmt(); 00938 for (CompoundStmt::const_body_iterator BI = CS->body_begin(), 00939 BE = CS->body_end(); BI != BE; ++BI) 00940 if (Expr *E = dyn_cast<Expr>((*BI))) { 00941 if (isCapturedBy(var, E)) 00942 return true; 00943 } 00944 else if (DeclStmt *DS = dyn_cast<DeclStmt>((*BI))) { 00945 // special case declarations 00946 for (DeclStmt::decl_iterator I = DS->decl_begin(), E = DS->decl_end(); 00947 I != E; ++I) { 00948 if (VarDecl *VD = dyn_cast<VarDecl>((*I))) { 00949 Expr *Init = VD->getInit(); 00950 if (Init && isCapturedBy(var, Init)) 00951 return true; 00952 } 00953 } 00954 } 00955 else 00956 // FIXME. Make safe assumption assuming arbitrary statements cause capturing. 00957 // Later, provide code to poke into statements for capture analysis. 00958 return true; 00959 return false; 00960 } 00961 00962 for (Stmt::const_child_range children = e->children(); children; ++children) 00963 if (isCapturedBy(var, cast<Expr>(*children))) 00964 return true; 00965 00966 return false; 00967 } 00968 00969 /// \brief Determine whether the given initializer is trivial in the sense 00970 /// that it requires no code to be generated. 00971 static bool isTrivialInitializer(const Expr *Init) { 00972 if (!Init) 00973 return true; 00974 00975 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) 00976 if (CXXConstructorDecl *Constructor = Construct->getConstructor()) 00977 if (Constructor->isTrivial() && 00978 Constructor->isDefaultConstructor() && 00979 !Construct->requiresZeroInitialization()) 00980 return true; 00981 00982 return false; 00983 } 00984 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) { 00985 assert(emission.Variable && "emission was not valid!"); 00986 00987 // If this was emitted as a global constant, we're done. 00988 if (emission.wasEmittedAsGlobal()) return; 00989 00990 const VarDecl &D = *emission.Variable; 00991 QualType type = D.getType(); 00992 00993 // If this local has an initializer, emit it now. 00994 const Expr *Init = D.getInit(); 00995 00996 // If we are at an unreachable point, we don't need to emit the initializer 00997 // unless it contains a label. 00998 if (!HaveInsertPoint()) { 00999 if (!Init || !ContainsLabel(Init)) return; 01000 EnsureInsertPoint(); 01001 } 01002 01003 // Initialize the structure of a __block variable. 01004 if (emission.IsByRef) 01005 emitByrefStructureInit(emission); 01006 01007 if (isTrivialInitializer(Init)) 01008 return; 01009 01010 CharUnits alignment = emission.Alignment; 01011 01012 // Check whether this is a byref variable that's potentially 01013 // captured and moved by its own initializer. If so, we'll need to 01014 // emit the initializer first, then copy into the variable. 01015 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init); 01016 01017 llvm::Value *Loc = 01018 capturedByInit ? emission.Address : emission.getObjectAddress(*this); 01019 01020 llvm::Constant *constant = 0; 01021 if (emission.IsConstantAggregate) { 01022 assert(!capturedByInit && "constant init contains a capturing block?"); 01023 constant = CGM.EmitConstantInit(D, this); 01024 } 01025 01026 if (!constant) { 01027 LValue lv = MakeAddrLValue(Loc, type, alignment); 01028 lv.setNonGC(true); 01029 return EmitExprAsInit(Init, &D, lv, capturedByInit); 01030 } 01031 01032 // If this is a simple aggregate initialization, we can optimize it 01033 // in various ways. 01034 bool isVolatile = type.isVolatileQualified(); 01035 01036 llvm::Value *SizeVal = 01037 llvm::ConstantInt::get(IntPtrTy, 01038 getContext().getTypeSizeInChars(type).getQuantity()); 01039 01040 llvm::Type *BP = Int8PtrTy; 01041 if (Loc->getType() != BP) 01042 Loc = Builder.CreateBitCast(Loc, BP); 01043 01044 // If the initializer is all or mostly zeros, codegen with memset then do 01045 // a few stores afterward. 01046 if (shouldUseMemSetPlusStoresToInitialize(constant, 01047 CGM.getTargetData().getTypeAllocSize(constant->getType()))) { 01048 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal, 01049 alignment.getQuantity(), isVolatile); 01050 if (!constant->isNullValue()) { 01051 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo()); 01052 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder); 01053 } 01054 } else { 01055 // Otherwise, create a temporary global with the initializer then 01056 // memcpy from the global to the alloca. 01057 std::string Name = GetStaticDeclName(*this, D, "."); 01058 llvm::GlobalVariable *GV = 01059 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true, 01060 llvm::GlobalValue::PrivateLinkage, 01061 constant, Name, 0, false, 0); 01062 GV->setAlignment(alignment.getQuantity()); 01063 GV->setUnnamedAddr(true); 01064 01065 llvm::Value *SrcPtr = GV; 01066 if (SrcPtr->getType() != BP) 01067 SrcPtr = Builder.CreateBitCast(SrcPtr, BP); 01068 01069 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(), 01070 isVolatile); 01071 } 01072 } 01073 01074 /// Emit an expression as an initializer for a variable at the given 01075 /// location. The expression is not necessarily the normal 01076 /// initializer for the variable, and the address is not necessarily 01077 /// its normal location. 01078 /// 01079 /// \param init the initializing expression 01080 /// \param var the variable to act as if we're initializing 01081 /// \param loc the address to initialize; its type is a pointer 01082 /// to the LLVM mapping of the variable's type 01083 /// \param alignment the alignment of the address 01084 /// \param capturedByInit true if the variable is a __block variable 01085 /// whose address is potentially changed by the initializer 01086 void CodeGenFunction::EmitExprAsInit(const Expr *init, 01087 const ValueDecl *D, 01088 LValue lvalue, 01089 bool capturedByInit) { 01090 QualType type = D->getType(); 01091 01092 if (type->isReferenceType()) { 01093 RValue rvalue = EmitReferenceBindingToExpr(init, D); 01094 if (capturedByInit) 01095 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 01096 EmitStoreThroughLValue(rvalue, lvalue, true); 01097 } else if (!hasAggregateLLVMType(type)) { 01098 EmitScalarInit(init, D, lvalue, capturedByInit); 01099 } else if (type->isAnyComplexType()) { 01100 ComplexPairTy complex = EmitComplexExpr(init); 01101 if (capturedByInit) 01102 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 01103 StoreComplexToAddr(complex, lvalue.getAddress(), lvalue.isVolatile()); 01104 } else { 01105 // TODO: how can we delay here if D is captured by its initializer? 01106 EmitAggExpr(init, AggValueSlot::forLValue(lvalue, 01107 AggValueSlot::IsDestructed, 01108 AggValueSlot::DoesNotNeedGCBarriers, 01109 AggValueSlot::IsNotAliased)); 01110 MaybeEmitStdInitializerListCleanup(lvalue.getAddress(), init); 01111 } 01112 } 01113 01114 /// Enter a destroy cleanup for the given local variable. 01115 void CodeGenFunction::emitAutoVarTypeCleanup( 01116 const CodeGenFunction::AutoVarEmission &emission, 01117 QualType::DestructionKind dtorKind) { 01118 assert(dtorKind != QualType::DK_none); 01119 01120 // Note that for __block variables, we want to destroy the 01121 // original stack object, not the possibly forwarded object. 01122 llvm::Value *addr = emission.getObjectAddress(*this); 01123 01124 const VarDecl *var = emission.Variable; 01125 QualType type = var->getType(); 01126 01127 CleanupKind cleanupKind = NormalAndEHCleanup; 01128 CodeGenFunction::Destroyer *destroyer = 0; 01129 01130 switch (dtorKind) { 01131 case QualType::DK_none: 01132 llvm_unreachable("no cleanup for trivially-destructible variable"); 01133 01134 case QualType::DK_cxx_destructor: 01135 // If there's an NRVO flag on the emission, we need a different 01136 // cleanup. 01137 if (emission.NRVOFlag) { 01138 assert(!type->isArrayType()); 01139 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor(); 01140 EHStack.pushCleanup<DestroyNRVOVariable>(cleanupKind, addr, dtor, 01141 emission.NRVOFlag); 01142 return; 01143 } 01144 break; 01145 01146 case QualType::DK_objc_strong_lifetime: 01147 // Suppress cleanups for pseudo-strong variables. 01148 if (var->isARCPseudoStrong()) return; 01149 01150 // Otherwise, consider whether to use an EH cleanup or not. 01151 cleanupKind = getARCCleanupKind(); 01152 01153 // Use the imprecise destroyer by default. 01154 if (!var->hasAttr<ObjCPreciseLifetimeAttr>()) 01155 destroyer = CodeGenFunction::destroyARCStrongImprecise; 01156 break; 01157 01158 case QualType::DK_objc_weak_lifetime: 01159 break; 01160 } 01161 01162 // If we haven't chosen a more specific destroyer, use the default. 01163 if (!destroyer) destroyer = getDestroyer(dtorKind); 01164 01165 // Use an EH cleanup in array destructors iff the destructor itself 01166 // is being pushed as an EH cleanup. 01167 bool useEHCleanup = (cleanupKind & EHCleanup); 01168 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer, 01169 useEHCleanup); 01170 } 01171 01172 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) { 01173 assert(emission.Variable && "emission was not valid!"); 01174 01175 // If this was emitted as a global constant, we're done. 01176 if (emission.wasEmittedAsGlobal()) return; 01177 01178 // If we don't have an insertion point, we're done. Sema prevents 01179 // us from jumping into any of these scopes anyway. 01180 if (!HaveInsertPoint()) return; 01181 01182 const VarDecl &D = *emission.Variable; 01183 01184 // Check the type for a cleanup. 01185 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType()) 01186 emitAutoVarTypeCleanup(emission, dtorKind); 01187 01188 // In GC mode, honor objc_precise_lifetime. 01189 if (getLangOpts().getGC() != LangOptions::NonGC && 01190 D.hasAttr<ObjCPreciseLifetimeAttr>()) { 01191 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D); 01192 } 01193 01194 // Handle the cleanup attribute. 01195 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 01196 const FunctionDecl *FD = CA->getFunctionDecl(); 01197 01198 llvm::Constant *F = CGM.GetAddrOfFunction(FD); 01199 assert(F && "Could not find function!"); 01200 01201 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD); 01202 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D); 01203 } 01204 01205 // If this is a block variable, call _Block_object_destroy 01206 // (on the unforwarded address). 01207 if (emission.IsByRef) 01208 enterByrefCleanup(emission); 01209 } 01210 01211 CodeGenFunction::Destroyer * 01212 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) { 01213 switch (kind) { 01214 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor"); 01215 case QualType::DK_cxx_destructor: 01216 return destroyCXXObject; 01217 case QualType::DK_objc_strong_lifetime: 01218 return destroyARCStrongPrecise; 01219 case QualType::DK_objc_weak_lifetime: 01220 return destroyARCWeak; 01221 } 01222 llvm_unreachable("Unknown DestructionKind"); 01223 } 01224 01225 /// pushDestroy - Push the standard destructor for the given type. 01226 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind, 01227 llvm::Value *addr, QualType type) { 01228 assert(dtorKind && "cannot push destructor for trivial type"); 01229 01230 CleanupKind cleanupKind = getCleanupKind(dtorKind); 01231 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind), 01232 cleanupKind & EHCleanup); 01233 } 01234 01235 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, llvm::Value *addr, 01236 QualType type, Destroyer *destroyer, 01237 bool useEHCleanupForArray) { 01238 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type, 01239 destroyer, useEHCleanupForArray); 01240 } 01241 01242 /// emitDestroy - Immediately perform the destruction of the given 01243 /// object. 01244 /// 01245 /// \param addr - the address of the object; a type* 01246 /// \param type - the type of the object; if an array type, all 01247 /// objects are destroyed in reverse order 01248 /// \param destroyer - the function to call to destroy individual 01249 /// elements 01250 /// \param useEHCleanupForArray - whether an EH cleanup should be 01251 /// used when destroying array elements, in case one of the 01252 /// destructions throws an exception 01253 void CodeGenFunction::emitDestroy(llvm::Value *addr, QualType type, 01254 Destroyer *destroyer, 01255 bool useEHCleanupForArray) { 01256 const ArrayType *arrayType = getContext().getAsArrayType(type); 01257 if (!arrayType) 01258 return destroyer(*this, addr, type); 01259 01260 llvm::Value *begin = addr; 01261 llvm::Value *length = emitArrayLength(arrayType, type, begin); 01262 01263 // Normally we have to check whether the array is zero-length. 01264 bool checkZeroLength = true; 01265 01266 // But if the array length is constant, we can suppress that. 01267 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) { 01268 // ...and if it's constant zero, we can just skip the entire thing. 01269 if (constLength->isZero()) return; 01270 checkZeroLength = false; 01271 } 01272 01273 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length); 01274 emitArrayDestroy(begin, end, type, destroyer, 01275 checkZeroLength, useEHCleanupForArray); 01276 } 01277 01278 /// emitArrayDestroy - Destroys all the elements of the given array, 01279 /// beginning from last to first. The array cannot be zero-length. 01280 /// 01281 /// \param begin - a type* denoting the first element of the array 01282 /// \param end - a type* denoting one past the end of the array 01283 /// \param type - the element type of the array 01284 /// \param destroyer - the function to call to destroy elements 01285 /// \param useEHCleanup - whether to push an EH cleanup to destroy 01286 /// the remaining elements in case the destruction of a single 01287 /// element throws 01288 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin, 01289 llvm::Value *end, 01290 QualType type, 01291 Destroyer *destroyer, 01292 bool checkZeroLength, 01293 bool useEHCleanup) { 01294 assert(!type->isArrayType()); 01295 01296 // The basic structure here is a do-while loop, because we don't 01297 // need to check for the zero-element case. 01298 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body"); 01299 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done"); 01300 01301 if (checkZeroLength) { 01302 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end, 01303 "arraydestroy.isempty"); 01304 Builder.CreateCondBr(isEmpty, doneBB, bodyBB); 01305 } 01306 01307 // Enter the loop body, making that address the current address. 01308 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 01309 EmitBlock(bodyBB); 01310 llvm::PHINode *elementPast = 01311 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast"); 01312 elementPast->addIncoming(end, entryBB); 01313 01314 // Shift the address back by one element. 01315 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true); 01316 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne, 01317 "arraydestroy.element"); 01318 01319 if (useEHCleanup) 01320 pushRegularPartialArrayCleanup(begin, element, type, destroyer); 01321 01322 // Perform the actual destruction there. 01323 destroyer(*this, element, type); 01324 01325 if (useEHCleanup) 01326 PopCleanupBlock(); 01327 01328 // Check whether we've reached the end. 01329 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done"); 01330 Builder.CreateCondBr(done, doneBB, bodyBB); 01331 elementPast->addIncoming(element, Builder.GetInsertBlock()); 01332 01333 // Done. 01334 EmitBlock(doneBB); 01335 } 01336 01337 /// Perform partial array destruction as if in an EH cleanup. Unlike 01338 /// emitArrayDestroy, the element type here may still be an array type. 01339 static void emitPartialArrayDestroy(CodeGenFunction &CGF, 01340 llvm::Value *begin, llvm::Value *end, 01341 QualType type, 01342 CodeGenFunction::Destroyer *destroyer) { 01343 // If the element type is itself an array, drill down. 01344 unsigned arrayDepth = 0; 01345 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) { 01346 // VLAs don't require a GEP index to walk into. 01347 if (!isa<VariableArrayType>(arrayType)) 01348 arrayDepth++; 01349 type = arrayType->getElementType(); 01350 } 01351 01352 if (arrayDepth) { 01353 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, arrayDepth+1); 01354 01355 SmallVector<llvm::Value*,4> gepIndices(arrayDepth, zero); 01356 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin"); 01357 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend"); 01358 } 01359 01360 // Destroy the array. We don't ever need an EH cleanup because we 01361 // assume that we're in an EH cleanup ourselves, so a throwing 01362 // destructor causes an immediate terminate. 01363 CGF.emitArrayDestroy(begin, end, type, destroyer, 01364 /*checkZeroLength*/ true, /*useEHCleanup*/ false); 01365 } 01366 01367 namespace { 01368 /// RegularPartialArrayDestroy - a cleanup which performs a partial 01369 /// array destroy where the end pointer is regularly determined and 01370 /// does not need to be loaded from a local. 01371 class RegularPartialArrayDestroy : public EHScopeStack::Cleanup { 01372 llvm::Value *ArrayBegin; 01373 llvm::Value *ArrayEnd; 01374 QualType ElementType; 01375 CodeGenFunction::Destroyer *Destroyer; 01376 public: 01377 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd, 01378 QualType elementType, 01379 CodeGenFunction::Destroyer *destroyer) 01380 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd), 01381 ElementType(elementType), Destroyer(destroyer) {} 01382 01383 void Emit(CodeGenFunction &CGF, Flags flags) { 01384 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd, 01385 ElementType, Destroyer); 01386 } 01387 }; 01388 01389 /// IrregularPartialArrayDestroy - a cleanup which performs a 01390 /// partial array destroy where the end pointer is irregularly 01391 /// determined and must be loaded from a local. 01392 class IrregularPartialArrayDestroy : public EHScopeStack::Cleanup { 01393 llvm::Value *ArrayBegin; 01394 llvm::Value *ArrayEndPointer; 01395 QualType ElementType; 01396 CodeGenFunction::Destroyer *Destroyer; 01397 public: 01398 IrregularPartialArrayDestroy(llvm::Value *arrayBegin, 01399 llvm::Value *arrayEndPointer, 01400 QualType elementType, 01401 CodeGenFunction::Destroyer *destroyer) 01402 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer), 01403 ElementType(elementType), Destroyer(destroyer) {} 01404 01405 void Emit(CodeGenFunction &CGF, Flags flags) { 01406 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer); 01407 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd, 01408 ElementType, Destroyer); 01409 } 01410 }; 01411 } 01412 01413 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy 01414 /// already-constructed elements of the given array. The cleanup 01415 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 01416 /// 01417 /// \param elementType - the immediate element type of the array; 01418 /// possibly still an array type 01419 /// \param array - a value of type elementType* 01420 /// \param destructionKind - the kind of destruction required 01421 /// \param initializedElementCount - a value of type size_t* holding 01422 /// the number of successfully-constructed elements 01423 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 01424 llvm::Value *arrayEndPointer, 01425 QualType elementType, 01426 Destroyer *destroyer) { 01427 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup, 01428 arrayBegin, arrayEndPointer, 01429 elementType, destroyer); 01430 } 01431 01432 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy 01433 /// already-constructed elements of the given array. The cleanup 01434 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 01435 /// 01436 /// \param elementType - the immediate element type of the array; 01437 /// possibly still an array type 01438 /// \param array - a value of type elementType* 01439 /// \param destructionKind - the kind of destruction required 01440 /// \param initializedElementCount - a value of type size_t* holding 01441 /// the number of successfully-constructed elements 01442 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 01443 llvm::Value *arrayEnd, 01444 QualType elementType, 01445 Destroyer *destroyer) { 01446 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup, 01447 arrayBegin, arrayEnd, 01448 elementType, destroyer); 01449 } 01450 01451 namespace { 01452 /// A cleanup to perform a release of an object at the end of a 01453 /// function. This is used to balance out the incoming +1 of a 01454 /// ns_consumed argument when we can't reasonably do that just by 01455 /// not doing the initial retain for a __block argument. 01456 struct ConsumeARCParameter : EHScopeStack::Cleanup { 01457 ConsumeARCParameter(llvm::Value *param) : Param(param) {} 01458 01459 llvm::Value *Param; 01460 01461 void Emit(CodeGenFunction &CGF, Flags flags) { 01462 CGF.EmitARCRelease(Param, /*precise*/ false); 01463 } 01464 }; 01465 } 01466 01467 /// Emit an alloca (or GlobalValue depending on target) 01468 /// for the specified parameter and set up LocalDeclMap. 01469 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg, 01470 unsigned ArgNo) { 01471 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 01472 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 01473 "Invalid argument to EmitParmDecl"); 01474 01475 Arg->setName(D.getName()); 01476 01477 // Use better IR generation for certain implicit parameters. 01478 if (isa<ImplicitParamDecl>(D)) { 01479 // The only implicit argument a block has is its literal. 01480 if (BlockInfo) { 01481 LocalDeclMap[&D] = Arg; 01482 01483 if (CGDebugInfo *DI = getDebugInfo()) { 01484 if (CGM.getCodeGenOpts().DebugInfo >= 01485 CodeGenOptions::LimitedDebugInfo) { 01486 DI->setLocation(D.getLocation()); 01487 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder); 01488 } 01489 } 01490 01491 return; 01492 } 01493 } 01494 01495 QualType Ty = D.getType(); 01496 01497 llvm::Value *DeclPtr; 01498 // If this is an aggregate or variable sized value, reuse the input pointer. 01499 if (!Ty->isConstantSizeType() || 01500 CodeGenFunction::hasAggregateLLVMType(Ty)) { 01501 DeclPtr = Arg; 01502 } else { 01503 // Otherwise, create a temporary to hold the value. 01504 llvm::AllocaInst *Alloc = CreateTempAlloca(ConvertTypeForMem(Ty), 01505 D.getName() + ".addr"); 01506 Alloc->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 01507 DeclPtr = Alloc; 01508 01509 bool doStore = true; 01510 01511 Qualifiers qs = Ty.getQualifiers(); 01512 01513 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) { 01514 // We honor __attribute__((ns_consumed)) for types with lifetime. 01515 // For __strong, it's handled by just skipping the initial retain; 01516 // otherwise we have to balance out the initial +1 with an extra 01517 // cleanup to do the release at the end of the function. 01518 bool isConsumed = D.hasAttr<NSConsumedAttr>(); 01519 01520 // 'self' is always formally __strong, but if this is not an 01521 // init method then we don't want to retain it. 01522 if (D.isARCPseudoStrong()) { 01523 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl); 01524 assert(&D == method->getSelfDecl()); 01525 assert(lt == Qualifiers::OCL_Strong); 01526 assert(qs.hasConst()); 01527 assert(method->getMethodFamily() != OMF_init); 01528 (void) method; 01529 lt = Qualifiers::OCL_ExplicitNone; 01530 } 01531 01532 if (lt == Qualifiers::OCL_Strong) { 01533 if (!isConsumed) 01534 // Don't use objc_retainBlock for block pointers, because we 01535 // don't want to Block_copy something just because we got it 01536 // as a parameter. 01537 Arg = EmitARCRetainNonBlock(Arg); 01538 } else { 01539 // Push the cleanup for a consumed parameter. 01540 if (isConsumed) 01541 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), Arg); 01542 01543 if (lt == Qualifiers::OCL_Weak) { 01544 EmitARCInitWeak(DeclPtr, Arg); 01545 doStore = false; // The weak init is a store, no need to do two. 01546 } 01547 } 01548 01549 // Enter the cleanup scope. 01550 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt); 01551 } 01552 01553 // Store the initial value into the alloca. 01554 if (doStore) { 01555 LValue lv = MakeAddrLValue(DeclPtr, Ty, 01556 getContext().getDeclAlign(&D)); 01557 EmitStoreOfScalar(Arg, lv, /* isInitialization */ true); 01558 } 01559 } 01560 01561 llvm::Value *&DMEntry = LocalDeclMap[&D]; 01562 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 01563 DMEntry = DeclPtr; 01564 01565 // Emit debug info for param declaration. 01566 if (CGDebugInfo *DI = getDebugInfo()) { 01567 if (CGM.getCodeGenOpts().DebugInfo >= CodeGenOptions::LimitedDebugInfo) { 01568 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder); 01569 } 01570 } 01571 01572 if (D.hasAttr<AnnotateAttr>()) 01573 EmitVarAnnotations(&D, DeclPtr); 01574 }