1 //===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code to emit Decl nodes as LLVM code. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGDebugInfo.h" 15 #include "CodeGenFunction.h" 16 #include "CodeGenModule.h" 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/CharUnits.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclObjC.h" 21 #include "clang/Basic/SourceManager.h" 22 #include "clang/Basic/TargetInfo.h" 23 #include "clang/Frontend/CodeGenOptions.h" 24 #include "llvm/GlobalVariable.h" 25 #include "llvm/Intrinsics.h" 26 #include "llvm/Target/TargetData.h" 27 #include "llvm/Type.h" 28 using namespace clang; 29 using namespace CodeGen; 30 31 32 void CodeGenFunction::EmitDecl(const Decl &D) { 33 switch (D.getKind()) { 34 case Decl::TranslationUnit: 35 case Decl::Namespace: 36 case Decl::UnresolvedUsingTypename: 37 case Decl::ClassTemplateSpecialization: 38 case Decl::ClassTemplatePartialSpecialization: 39 case Decl::TemplateTypeParm: 40 case Decl::UnresolvedUsingValue: 41 case Decl::NonTypeTemplateParm: 42 case Decl::CXXMethod: 43 case Decl::CXXConstructor: 44 case Decl::CXXDestructor: 45 case Decl::CXXConversion: 46 case Decl::Field: 47 case Decl::IndirectField: 48 case Decl::ObjCIvar: 49 case Decl::ObjCAtDefsField: 50 case Decl::ParmVar: 51 case Decl::ImplicitParam: 52 case Decl::ClassTemplate: 53 case Decl::FunctionTemplate: 54 case Decl::TemplateTemplateParm: 55 case Decl::ObjCMethod: 56 case Decl::ObjCCategory: 57 case Decl::ObjCProtocol: 58 case Decl::ObjCInterface: 59 case Decl::ObjCCategoryImpl: 60 case Decl::ObjCImplementation: 61 case Decl::ObjCProperty: 62 case Decl::ObjCCompatibleAlias: 63 case Decl::AccessSpec: 64 case Decl::LinkageSpec: 65 case Decl::ObjCPropertyImpl: 66 case Decl::ObjCClass: 67 case Decl::ObjCForwardProtocol: 68 case Decl::FileScopeAsm: 69 case Decl::Friend: 70 case Decl::FriendTemplate: 71 case Decl::Block: 72 assert(0 && "Declaration should not be in declstmts!"); 73 case Decl::Function: // void X(); 74 case Decl::Record: // struct/union/class X; 75 case Decl::Enum: // enum X; 76 case Decl::EnumConstant: // enum ? { X = ? } 77 case Decl::CXXRecord: // struct/union/class X; [C++] 78 case Decl::Using: // using X; [C++] 79 case Decl::UsingShadow: 80 case Decl::UsingDirective: // using namespace X; [C++] 81 case Decl::NamespaceAlias: 82 case Decl::StaticAssert: // static_assert(X, ""); [C++0x] 83 case Decl::Label: // __label__ x; 84 // None of these decls require codegen support. 85 return; 86 87 case Decl::Var: { 88 const VarDecl &VD = cast<VarDecl>(D); 89 assert(VD.isLocalVarDecl() && 90 "Should not see file-scope variables inside a function!"); 91 return EmitVarDecl(VD); 92 } 93 94 case Decl::Typedef: // typedef int X; 95 case Decl::TypeAlias: { // using X = int; [C++0x] 96 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D); 97 QualType Ty = TD.getUnderlyingType(); 98 99 if (Ty->isVariablyModifiedType()) 100 EmitVLASize(Ty); 101 } 102 } 103 } 104 105 /// EmitVarDecl - This method handles emission of any variable declaration 106 /// inside a function, including static vars etc. 107 void CodeGenFunction::EmitVarDecl(const VarDecl &D) { 108 switch (D.getStorageClass()) { 109 case SC_None: 110 case SC_Auto: 111 case SC_Register: 112 return EmitAutoVarDecl(D); 113 case SC_Static: { 114 llvm::GlobalValue::LinkageTypes Linkage = 115 llvm::GlobalValue::InternalLinkage; 116 117 // If the function definition has some sort of weak linkage, its 118 // static variables should also be weak so that they get properly 119 // uniqued. We can't do this in C, though, because there's no 120 // standard way to agree on which variables are the same (i.e. 121 // there's no mangling). 122 if (getContext().getLangOptions().CPlusPlus) 123 if (llvm::GlobalValue::isWeakForLinker(CurFn->getLinkage())) 124 Linkage = CurFn->getLinkage(); 125 126 return EmitStaticVarDecl(D, Linkage); 127 } 128 case SC_Extern: 129 case SC_PrivateExtern: 130 // Don't emit it now, allow it to be emitted lazily on its first use. 131 return; 132 } 133 134 assert(0 && "Unknown storage class"); 135 } 136 137 static std::string GetStaticDeclName(CodeGenFunction &CGF, const VarDecl &D, 138 const char *Separator) { 139 CodeGenModule &CGM = CGF.CGM; 140 if (CGF.getContext().getLangOptions().CPlusPlus) { 141 llvm::StringRef Name = CGM.getMangledName(&D); 142 return Name.str(); 143 } 144 145 std::string ContextName; 146 if (!CGF.CurFuncDecl) { 147 // Better be in a block declared in global scope. 148 const NamedDecl *ND = cast<NamedDecl>(&D); 149 const DeclContext *DC = ND->getDeclContext(); 150 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) { 151 MangleBuffer Name; 152 CGM.getBlockMangledName(GlobalDecl(), Name, BD); 153 ContextName = Name.getString(); 154 } 155 else 156 assert(0 && "Unknown context for block static var decl"); 157 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CGF.CurFuncDecl)) { 158 llvm::StringRef Name = CGM.getMangledName(FD); 159 ContextName = Name.str(); 160 } else if (isa<ObjCMethodDecl>(CGF.CurFuncDecl)) 161 ContextName = CGF.CurFn->getName(); 162 else 163 assert(0 && "Unknown context for static var decl"); 164 165 return ContextName + Separator + D.getNameAsString(); 166 } 167 168 llvm::GlobalVariable * 169 CodeGenFunction::CreateStaticVarDecl(const VarDecl &D, 170 const char *Separator, 171 llvm::GlobalValue::LinkageTypes Linkage) { 172 QualType Ty = D.getType(); 173 assert(Ty->isConstantSizeType() && "VLAs can't be static"); 174 175 std::string Name = GetStaticDeclName(*this, D, Separator); 176 177 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(Ty); 178 llvm::GlobalVariable *GV = 179 new llvm::GlobalVariable(CGM.getModule(), LTy, 180 Ty.isConstant(getContext()), Linkage, 181 CGM.EmitNullConstant(D.getType()), Name, 0, 182 D.isThreadSpecified(), 183 CGM.getContext().getTargetAddressSpace(Ty)); 184 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 185 if (Linkage != llvm::GlobalValue::InternalLinkage) 186 GV->setVisibility(CurFn->getVisibility()); 187 return GV; 188 } 189 190 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 191 /// global variable that has already been created for it. If the initializer 192 /// has a different type than GV does, this may free GV and return a different 193 /// one. Otherwise it just returns GV. 194 llvm::GlobalVariable * 195 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D, 196 llvm::GlobalVariable *GV) { 197 llvm::Constant *Init = CGM.EmitConstantExpr(D.getInit(), D.getType(), this); 198 199 // If constant emission failed, then this should be a C++ static 200 // initializer. 201 if (!Init) { 202 if (!getContext().getLangOptions().CPlusPlus) 203 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression"); 204 else if (Builder.GetInsertBlock()) { 205 // Since we have a static initializer, this global variable can't 206 // be constant. 207 GV->setConstant(false); 208 209 EmitCXXGuardedInit(D, GV); 210 } 211 return GV; 212 } 213 214 // The initializer may differ in type from the global. Rewrite 215 // the global to match the initializer. (We have to do this 216 // because some types, like unions, can't be completely represented 217 // in the LLVM type system.) 218 if (GV->getType()->getElementType() != Init->getType()) { 219 llvm::GlobalVariable *OldGV = GV; 220 221 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 222 OldGV->isConstant(), 223 OldGV->getLinkage(), Init, "", 224 /*InsertBefore*/ OldGV, 225 D.isThreadSpecified(), 226 CGM.getContext().getTargetAddressSpace(D.getType())); 227 GV->setVisibility(OldGV->getVisibility()); 228 229 // Steal the name of the old global 230 GV->takeName(OldGV); 231 232 // Replace all uses of the old global with the new global 233 llvm::Constant *NewPtrForOldDecl = 234 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 235 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 236 237 // Erase the old global, since it is no longer used. 238 OldGV->eraseFromParent(); 239 } 240 241 GV->setInitializer(Init); 242 return GV; 243 } 244 245 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D, 246 llvm::GlobalValue::LinkageTypes Linkage) { 247 llvm::Value *&DMEntry = LocalDeclMap[&D]; 248 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 249 250 llvm::GlobalVariable *GV = CreateStaticVarDecl(D, ".", Linkage); 251 252 // Store into LocalDeclMap before generating initializer to handle 253 // circular references. 254 DMEntry = GV; 255 256 // We can't have a VLA here, but we can have a pointer to a VLA, 257 // even though that doesn't really make any sense. 258 // Make sure to evaluate VLA bounds now so that we have them for later. 259 if (D.getType()->isVariablyModifiedType()) 260 EmitVLASize(D.getType()); 261 262 // Local static block variables must be treated as globals as they may be 263 // referenced in their RHS initializer block-literal expresion. 264 CGM.setStaticLocalDeclAddress(&D, GV); 265 266 // If this value has an initializer, emit it. 267 if (D.getInit()) 268 GV = AddInitializerToStaticVarDecl(D, GV); 269 270 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 271 272 // FIXME: Merge attribute handling. 273 if (const AnnotateAttr *AA = D.getAttr<AnnotateAttr>()) { 274 SourceManager &SM = CGM.getContext().getSourceManager(); 275 llvm::Constant *Ann = 276 CGM.EmitAnnotateAttr(GV, AA, 277 SM.getInstantiationLineNumber(D.getLocation())); 278 CGM.AddAnnotation(Ann); 279 } 280 281 if (const SectionAttr *SA = D.getAttr<SectionAttr>()) 282 GV->setSection(SA->getName()); 283 284 if (D.hasAttr<UsedAttr>()) 285 CGM.AddUsedGlobal(GV); 286 287 // We may have to cast the constant because of the initializer 288 // mismatch above. 289 // 290 // FIXME: It is really dangerous to store this in the map; if anyone 291 // RAUW's the GV uses of this constant will be invalid. 292 const llvm::Type *LTy = CGM.getTypes().ConvertTypeForMem(D.getType()); 293 const llvm::Type *LPtrTy = 294 LTy->getPointerTo(CGM.getContext().getTargetAddressSpace(D.getType())); 295 DMEntry = llvm::ConstantExpr::getBitCast(GV, LPtrTy); 296 297 // Emit global variable debug descriptor for static vars. 298 CGDebugInfo *DI = getDebugInfo(); 299 if (DI) { 300 DI->setLocation(D.getLocation()); 301 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(GV), &D); 302 } 303 } 304 305 namespace { 306 struct CallArrayDtor : EHScopeStack::Cleanup { 307 CallArrayDtor(const CXXDestructorDecl *Dtor, 308 const ConstantArrayType *Type, 309 llvm::Value *Loc) 310 : Dtor(Dtor), Type(Type), Loc(Loc) {} 311 312 const CXXDestructorDecl *Dtor; 313 const ConstantArrayType *Type; 314 llvm::Value *Loc; 315 316 void Emit(CodeGenFunction &CGF, bool IsForEH) { 317 QualType BaseElementTy = CGF.getContext().getBaseElementType(Type); 318 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy); 319 BasePtr = llvm::PointerType::getUnqual(BasePtr); 320 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(Loc, BasePtr); 321 CGF.EmitCXXAggrDestructorCall(Dtor, Type, BaseAddrPtr); 322 } 323 }; 324 325 struct CallVarDtor : EHScopeStack::Cleanup { 326 CallVarDtor(const CXXDestructorDecl *Dtor, 327 llvm::Value *NRVOFlag, 328 llvm::Value *Loc) 329 : Dtor(Dtor), NRVOFlag(NRVOFlag), Loc(Loc) {} 330 331 const CXXDestructorDecl *Dtor; 332 llvm::Value *NRVOFlag; 333 llvm::Value *Loc; 334 335 void Emit(CodeGenFunction &CGF, bool IsForEH) { 336 // Along the exceptions path we always execute the dtor. 337 bool NRVO = !IsForEH && NRVOFlag; 338 339 llvm::BasicBlock *SkipDtorBB = 0; 340 if (NRVO) { 341 // If we exited via NRVO, we skip the destructor call. 342 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused"); 343 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor"); 344 llvm::Value *DidNRVO = CGF.Builder.CreateLoad(NRVOFlag, "nrvo.val"); 345 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB); 346 CGF.EmitBlock(RunDtorBB); 347 } 348 349 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 350 /*ForVirtualBase=*/false, Loc); 351 352 if (NRVO) CGF.EmitBlock(SkipDtorBB); 353 } 354 }; 355 } 356 357 namespace { 358 struct CallStackRestore : EHScopeStack::Cleanup { 359 llvm::Value *Stack; 360 CallStackRestore(llvm::Value *Stack) : Stack(Stack) {} 361 void Emit(CodeGenFunction &CGF, bool IsForEH) { 362 llvm::Value *V = CGF.Builder.CreateLoad(Stack, "tmp"); 363 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 364 CGF.Builder.CreateCall(F, V); 365 } 366 }; 367 368 struct CallCleanupFunction : EHScopeStack::Cleanup { 369 llvm::Constant *CleanupFn; 370 const CGFunctionInfo &FnInfo; 371 const VarDecl &Var; 372 373 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info, 374 const VarDecl *Var) 375 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {} 376 377 void Emit(CodeGenFunction &CGF, bool IsForEH) { 378 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), Var.getType(), VK_LValue, 379 SourceLocation()); 380 // Compute the address of the local variable, in case it's a byref 381 // or something. 382 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getAddress(); 383 384 // In some cases, the type of the function argument will be different from 385 // the type of the pointer. An example of this is 386 // void f(void* arg); 387 // __attribute__((cleanup(f))) void *g; 388 // 389 // To fix this we insert a bitcast here. 390 QualType ArgTy = FnInfo.arg_begin()->type; 391 llvm::Value *Arg = 392 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy)); 393 394 CallArgList Args; 395 Args.push_back(std::make_pair(RValue::get(Arg), 396 CGF.getContext().getPointerType(Var.getType()))); 397 CGF.EmitCall(FnInfo, CleanupFn, ReturnValueSlot(), Args); 398 } 399 }; 400 } 401 402 403 /// canEmitInitWithFewStoresAfterMemset - Decide whether we can emit the 404 /// non-zero parts of the specified initializer with equal or fewer than 405 /// NumStores scalar stores. 406 static bool canEmitInitWithFewStoresAfterMemset(llvm::Constant *Init, 407 unsigned &NumStores) { 408 // Zero and Undef never requires any extra stores. 409 if (isa<llvm::ConstantAggregateZero>(Init) || 410 isa<llvm::ConstantPointerNull>(Init) || 411 isa<llvm::UndefValue>(Init)) 412 return true; 413 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 414 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 415 isa<llvm::ConstantExpr>(Init)) 416 return Init->isNullValue() || NumStores--; 417 418 // See if we can emit each element. 419 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) { 420 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 421 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 422 if (!canEmitInitWithFewStoresAfterMemset(Elt, NumStores)) 423 return false; 424 } 425 return true; 426 } 427 428 // Anything else is hard and scary. 429 return false; 430 } 431 432 /// emitStoresForInitAfterMemset - For inits that 433 /// canEmitInitWithFewStoresAfterMemset returned true for, emit the scalar 434 /// stores that would be required. 435 static void emitStoresForInitAfterMemset(llvm::Constant *Init, llvm::Value *Loc, 436 bool isVolatile, CGBuilderTy &Builder) { 437 // Zero doesn't require any stores. 438 if (isa<llvm::ConstantAggregateZero>(Init) || 439 isa<llvm::ConstantPointerNull>(Init) || 440 isa<llvm::UndefValue>(Init)) 441 return; 442 443 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 444 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 445 isa<llvm::ConstantExpr>(Init)) { 446 if (!Init->isNullValue()) 447 Builder.CreateStore(Init, Loc, isVolatile); 448 return; 449 } 450 451 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) && 452 "Unknown value type!"); 453 454 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 455 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 456 if (Elt->isNullValue()) continue; 457 458 // Otherwise, get a pointer to the element and emit it. 459 emitStoresForInitAfterMemset(Elt, Builder.CreateConstGEP2_32(Loc, 0, i), 460 isVolatile, Builder); 461 } 462 } 463 464 465 /// shouldUseMemSetPlusStoresToInitialize - Decide whether we should use memset 466 /// plus some stores to initialize a local variable instead of using a memcpy 467 /// from a constant global. It is beneficial to use memset if the global is all 468 /// zeros, or mostly zeros and large. 469 static bool shouldUseMemSetPlusStoresToInitialize(llvm::Constant *Init, 470 uint64_t GlobalSize) { 471 // If a global is all zeros, always use a memset. 472 if (isa<llvm::ConstantAggregateZero>(Init)) return true; 473 474 475 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large, 476 // do it if it will require 6 or fewer scalar stores. 477 // TODO: Should budget depends on the size? Avoiding a large global warrants 478 // plopping in more stores. 479 unsigned StoreBudget = 6; 480 uint64_t SizeLimit = 32; 481 482 return GlobalSize > SizeLimit && 483 canEmitInitWithFewStoresAfterMemset(Init, StoreBudget); 484 } 485 486 487 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a 488 /// variable declaration with auto, register, or no storage class specifier. 489 /// These turn into simple stack objects, or GlobalValues depending on target. 490 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) { 491 AutoVarEmission emission = EmitAutoVarAlloca(D); 492 EmitAutoVarInit(emission); 493 EmitAutoVarCleanups(emission); 494 } 495 496 /// EmitAutoVarAlloca - Emit the alloca and debug information for a 497 /// local variable. Does not emit initalization or destruction. 498 CodeGenFunction::AutoVarEmission 499 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) { 500 QualType Ty = D.getType(); 501 502 AutoVarEmission emission(D); 503 504 bool isByRef = D.hasAttr<BlocksAttr>(); 505 emission.IsByRef = isByRef; 506 507 CharUnits alignment = getContext().getDeclAlign(&D); 508 emission.Alignment = alignment; 509 510 llvm::Value *DeclPtr; 511 if (Ty->isConstantSizeType()) { 512 if (!Target.useGlobalsForAutomaticVariables()) { 513 bool NRVO = getContext().getLangOptions().ElideConstructors && 514 D.isNRVOVariable(); 515 516 // If this value is a POD array or struct with a statically 517 // determinable constant initializer, there are optimizations we 518 // can do. 519 // TODO: we can potentially constant-evaluate non-POD structs and 520 // arrays as long as the initialization is trivial (e.g. if they 521 // have a non-trivial destructor, but not a non-trivial constructor). 522 if (D.getInit() && 523 (Ty->isArrayType() || Ty->isRecordType()) && Ty->isPODType() && 524 D.getInit()->isConstantInitializer(getContext(), false)) { 525 526 // If the variable's a const type, and it's neither an NRVO 527 // candidate nor a __block variable, emit it as a global instead. 528 if (CGM.getCodeGenOpts().MergeAllConstants && Ty.isConstQualified() && 529 !NRVO && !isByRef) { 530 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage); 531 532 emission.Address = 0; // signal this condition to later callbacks 533 assert(emission.wasEmittedAsGlobal()); 534 return emission; 535 } 536 537 // Otherwise, tell the initialization code that we're in this case. 538 emission.IsConstantAggregate = true; 539 } 540 541 // A normal fixed sized variable becomes an alloca in the entry block, 542 // unless it's an NRVO variable. 543 const llvm::Type *LTy = ConvertTypeForMem(Ty); 544 545 if (NRVO) { 546 // The named return value optimization: allocate this variable in the 547 // return slot, so that we can elide the copy when returning this 548 // variable (C++0x [class.copy]p34). 549 DeclPtr = ReturnValue; 550 551 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 552 if (!cast<CXXRecordDecl>(RecordTy->getDecl())->hasTrivialDestructor()) { 553 // Create a flag that is used to indicate when the NRVO was applied 554 // to this variable. Set it to zero to indicate that NRVO was not 555 // applied. 556 llvm::Value *Zero = Builder.getFalse(); 557 llvm::Value *NRVOFlag = CreateTempAlloca(Zero->getType(), "nrvo"); 558 EnsureInsertPoint(); 559 Builder.CreateStore(Zero, NRVOFlag); 560 561 // Record the NRVO flag for this variable. 562 NRVOFlags[&D] = NRVOFlag; 563 emission.NRVOFlag = NRVOFlag; 564 } 565 } 566 } else { 567 if (isByRef) 568 LTy = BuildByRefType(&D); 569 570 llvm::AllocaInst *Alloc = CreateTempAlloca(LTy); 571 Alloc->setName(D.getNameAsString()); 572 573 CharUnits allocaAlignment = alignment; 574 if (isByRef) 575 allocaAlignment = std::max(allocaAlignment, 576 getContext().toCharUnitsFromBits(Target.getPointerAlign(0))); 577 Alloc->setAlignment(allocaAlignment.getQuantity()); 578 DeclPtr = Alloc; 579 } 580 } else { 581 // Targets that don't support recursion emit locals as globals. 582 const char *Class = 583 D.getStorageClass() == SC_Register ? ".reg." : ".auto."; 584 DeclPtr = CreateStaticVarDecl(D, Class, 585 llvm::GlobalValue::InternalLinkage); 586 } 587 588 // FIXME: Can this happen? 589 if (Ty->isVariablyModifiedType()) 590 EmitVLASize(Ty); 591 } else { 592 EnsureInsertPoint(); 593 594 if (!DidCallStackSave) { 595 // Save the stack. 596 llvm::Value *Stack = CreateTempAlloca(Int8PtrTy, "saved_stack"); 597 598 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 599 llvm::Value *V = Builder.CreateCall(F); 600 601 Builder.CreateStore(V, Stack); 602 603 DidCallStackSave = true; 604 605 // Push a cleanup block and restore the stack there. 606 // FIXME: in general circumstances, this should be an EH cleanup. 607 EHStack.pushCleanup<CallStackRestore>(NormalCleanup, Stack); 608 } 609 610 // Get the element type. 611 const llvm::Type *LElemTy = ConvertTypeForMem(Ty); 612 const llvm::Type *LElemPtrTy = 613 LElemTy->getPointerTo(CGM.getContext().getTargetAddressSpace(Ty)); 614 615 llvm::Value *VLASize = EmitVLASize(Ty); 616 617 // Allocate memory for the array. 618 llvm::AllocaInst *VLA = 619 Builder.CreateAlloca(llvm::Type::getInt8Ty(getLLVMContext()), VLASize, "vla"); 620 VLA->setAlignment(alignment.getQuantity()); 621 622 DeclPtr = Builder.CreateBitCast(VLA, LElemPtrTy, "tmp"); 623 } 624 625 llvm::Value *&DMEntry = LocalDeclMap[&D]; 626 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 627 DMEntry = DeclPtr; 628 emission.Address = DeclPtr; 629 630 // Emit debug info for local var declaration. 631 if (CGDebugInfo *DI = getDebugInfo()) { 632 assert(HaveInsertPoint() && "Unexpected unreachable point!"); 633 634 DI->setLocation(D.getLocation()); 635 if (Target.useGlobalsForAutomaticVariables()) { 636 DI->EmitGlobalVariable(static_cast<llvm::GlobalVariable *>(DeclPtr), &D); 637 } else 638 DI->EmitDeclareOfAutoVariable(&D, DeclPtr, Builder); 639 } 640 641 return emission; 642 } 643 644 /// Determines whether the given __block variable is potentially 645 /// captured by the given expression. 646 static bool isCapturedBy(const VarDecl &var, const Expr *e) { 647 // Skip the most common kinds of expressions that make 648 // hierarchy-walking expensive. 649 e = e->IgnoreParenCasts(); 650 651 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) { 652 const BlockDecl *block = be->getBlockDecl(); 653 for (BlockDecl::capture_const_iterator i = block->capture_begin(), 654 e = block->capture_end(); i != e; ++i) { 655 if (i->getVariable() == &var) 656 return true; 657 } 658 659 // No need to walk into the subexpressions. 660 return false; 661 } 662 663 for (Stmt::const_child_range children = e->children(); children; ++children) 664 if (isCapturedBy(var, cast<Expr>(*children))) 665 return true; 666 667 return false; 668 } 669 670 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) { 671 assert(emission.Variable && "emission was not valid!"); 672 673 // If this was emitted as a global constant, we're done. 674 if (emission.wasEmittedAsGlobal()) return; 675 676 const VarDecl &D = *emission.Variable; 677 QualType type = D.getType(); 678 679 // If this local has an initializer, emit it now. 680 const Expr *Init = D.getInit(); 681 682 // If we are at an unreachable point, we don't need to emit the initializer 683 // unless it contains a label. 684 if (!HaveInsertPoint()) { 685 if (!Init || !ContainsLabel(Init)) return; 686 EnsureInsertPoint(); 687 } 688 689 // Initialize the structure of a __block variable. 690 if (emission.IsByRef) 691 emitByrefStructureInit(emission); 692 693 if (!Init) return; 694 695 CharUnits alignment = emission.Alignment; 696 697 // Check whether this is a byref variable that's potentially 698 // captured and moved by its own initializer. If so, we'll need to 699 // emit the initializer first, then copy into the variable. 700 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init); 701 702 llvm::Value *Loc = 703 capturedByInit ? emission.Address : emission.getObjectAddress(*this); 704 705 if (!emission.IsConstantAggregate) 706 return EmitExprAsInit(Init, &D, Loc, alignment, capturedByInit); 707 708 // If this is a simple aggregate initialization, we can optimize it 709 // in various ways. 710 assert(!capturedByInit && "constant init contains a capturing block?"); 711 712 bool isVolatile = type.isVolatileQualified(); 713 714 llvm::Constant *constant = CGM.EmitConstantExpr(D.getInit(), type, this); 715 assert(constant != 0 && "Wasn't a simple constant init?"); 716 717 llvm::Value *SizeVal = 718 llvm::ConstantInt::get(IntPtrTy, 719 getContext().getTypeSizeInChars(type).getQuantity()); 720 721 const llvm::Type *BP = Int8PtrTy; 722 if (Loc->getType() != BP) 723 Loc = Builder.CreateBitCast(Loc, BP, "tmp"); 724 725 // If the initializer is all or mostly zeros, codegen with memset then do 726 // a few stores afterward. 727 if (shouldUseMemSetPlusStoresToInitialize(constant, 728 CGM.getTargetData().getTypeAllocSize(constant->getType()))) { 729 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal, 730 alignment.getQuantity(), isVolatile); 731 if (!constant->isNullValue()) { 732 Loc = Builder.CreateBitCast(Loc, constant->getType()->getPointerTo()); 733 emitStoresForInitAfterMemset(constant, Loc, isVolatile, Builder); 734 } 735 } else { 736 // Otherwise, create a temporary global with the initializer then 737 // memcpy from the global to the alloca. 738 std::string Name = GetStaticDeclName(*this, D, "."); 739 llvm::GlobalVariable *GV = 740 new llvm::GlobalVariable(CGM.getModule(), constant->getType(), true, 741 llvm::GlobalValue::InternalLinkage, 742 constant, Name, 0, false, 0); 743 GV->setAlignment(alignment.getQuantity()); 744 745 llvm::Value *SrcPtr = GV; 746 if (SrcPtr->getType() != BP) 747 SrcPtr = Builder.CreateBitCast(SrcPtr, BP, "tmp"); 748 749 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, alignment.getQuantity(), 750 isVolatile); 751 } 752 } 753 754 /// Emit an expression as an initializer for a variable at the given 755 /// location. The expression is not necessarily the normal 756 /// initializer for the variable, and the address is not necessarily 757 /// its normal location. 758 /// 759 /// \param init the initializing expression 760 /// \param var the variable to act as if we're initializing 761 /// \param loc the address to initialize; its type is a pointer 762 /// to the LLVM mapping of the variable's type 763 /// \param alignment the alignment of the address 764 /// \param capturedByInit true if the variable is a __block variable 765 /// whose address is potentially changed by the initializer 766 void CodeGenFunction::EmitExprAsInit(const Expr *init, 767 const VarDecl *var, 768 llvm::Value *loc, 769 CharUnits alignment, 770 bool capturedByInit) { 771 QualType type = var->getType(); 772 bool isVolatile = type.isVolatileQualified(); 773 774 if (type->isReferenceType()) { 775 RValue RV = EmitReferenceBindingToExpr(init, var); 776 if (capturedByInit) loc = BuildBlockByrefAddress(loc, var); 777 EmitStoreOfScalar(RV.getScalarVal(), loc, false, 778 alignment.getQuantity(), type); 779 } else if (!hasAggregateLLVMType(type)) { 780 llvm::Value *V = EmitScalarExpr(init); 781 if (capturedByInit) loc = BuildBlockByrefAddress(loc, var); 782 EmitStoreOfScalar(V, loc, isVolatile, alignment.getQuantity(), type); 783 } else if (type->isAnyComplexType()) { 784 ComplexPairTy complex = EmitComplexExpr(init); 785 if (capturedByInit) loc = BuildBlockByrefAddress(loc, var); 786 StoreComplexToAddr(complex, loc, isVolatile); 787 } else { 788 // TODO: how can we delay here if D is captured by its initializer? 789 EmitAggExpr(init, AggValueSlot::forAddr(loc, isVolatile, true, false)); 790 } 791 } 792 793 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) { 794 assert(emission.Variable && "emission was not valid!"); 795 796 // If this was emitted as a global constant, we're done. 797 if (emission.wasEmittedAsGlobal()) return; 798 799 const VarDecl &D = *emission.Variable; 800 801 // Handle C++ destruction of variables. 802 if (getLangOptions().CPlusPlus) { 803 QualType type = D.getType(); 804 QualType baseType = getContext().getBaseElementType(type); 805 if (const RecordType *RT = baseType->getAs<RecordType>()) { 806 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 807 if (!ClassDecl->hasTrivialDestructor()) { 808 // Note: We suppress the destructor call when the corresponding NRVO 809 // flag has been set. 810 811 // Note that for __block variables, we want to destroy the 812 // original stack object, not the possible forwarded object. 813 llvm::Value *Loc = emission.getObjectAddress(*this); 814 815 const CXXDestructorDecl *D = ClassDecl->getDestructor(); 816 assert(D && "EmitLocalBlockVarDecl - destructor is nul"); 817 818 if (type != baseType) { 819 const ConstantArrayType *Array = 820 getContext().getAsConstantArrayType(type); 821 assert(Array && "types changed without array?"); 822 EHStack.pushCleanup<CallArrayDtor>(NormalAndEHCleanup, 823 D, Array, Loc); 824 } else { 825 EHStack.pushCleanup<CallVarDtor>(NormalAndEHCleanup, 826 D, emission.NRVOFlag, Loc); 827 } 828 } 829 } 830 } 831 832 // Handle the cleanup attribute. 833 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 834 const FunctionDecl *FD = CA->getFunctionDecl(); 835 836 llvm::Constant *F = CGM.GetAddrOfFunction(FD); 837 assert(F && "Could not find function!"); 838 839 const CGFunctionInfo &Info = CGM.getTypes().getFunctionInfo(FD); 840 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D); 841 } 842 843 // If this is a block variable, call _Block_object_destroy 844 // (on the unforwarded address). 845 if (emission.IsByRef) 846 enterByrefCleanup(emission); 847 } 848 849 /// Emit an alloca (or GlobalValue depending on target) 850 /// for the specified parameter and set up LocalDeclMap. 851 void CodeGenFunction::EmitParmDecl(const VarDecl &D, llvm::Value *Arg, 852 unsigned ArgNo) { 853 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 854 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 855 "Invalid argument to EmitParmDecl"); 856 857 Arg->setName(D.getName()); 858 859 // Use better IR generation for certain implicit parameters. 860 if (isa<ImplicitParamDecl>(D)) { 861 // The only implicit argument a block has is its literal. 862 if (BlockInfo) { 863 LocalDeclMap[&D] = Arg; 864 865 if (CGDebugInfo *DI = getDebugInfo()) { 866 DI->setLocation(D.getLocation()); 867 DI->EmitDeclareOfBlockLiteralArgVariable(*BlockInfo, Arg, Builder); 868 } 869 870 return; 871 } 872 } 873 874 QualType Ty = D.getType(); 875 876 llvm::Value *DeclPtr; 877 // If this is an aggregate or variable sized value, reuse the input pointer. 878 if (!Ty->isConstantSizeType() || 879 CodeGenFunction::hasAggregateLLVMType(Ty)) { 880 DeclPtr = Arg; 881 } else { 882 // Otherwise, create a temporary to hold the value. 883 DeclPtr = CreateMemTemp(Ty, D.getName() + ".addr"); 884 885 // Store the initial value into the alloca. 886 EmitStoreOfScalar(Arg, DeclPtr, Ty.isVolatileQualified(), 887 getContext().getDeclAlign(&D).getQuantity(), Ty, 888 CGM.getTBAAInfo(Ty)); 889 } 890 891 llvm::Value *&DMEntry = LocalDeclMap[&D]; 892 assert(DMEntry == 0 && "Decl already exists in localdeclmap!"); 893 DMEntry = DeclPtr; 894 895 // Emit debug info for param declaration. 896 if (CGDebugInfo *DI = getDebugInfo()) { 897 DI->setLocation(D.getLocation()); 898 DI->EmitDeclareOfArgVariable(&D, DeclPtr, ArgNo, Builder); 899 } 900 } 901