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 "CGBlocks.h" 15 #include "CGCXXABI.h" 16 #include "CGCleanup.h" 17 #include "CGDebugInfo.h" 18 #include "CGOpenCLRuntime.h" 19 #include "CGOpenMPRuntime.h" 20 #include "CodeGenFunction.h" 21 #include "CodeGenModule.h" 22 #include "ConstantEmitter.h" 23 #include "TargetInfo.h" 24 #include "clang/AST/ASTContext.h" 25 #include "clang/AST/CharUnits.h" 26 #include "clang/AST/Decl.h" 27 #include "clang/AST/DeclObjC.h" 28 #include "clang/AST/DeclOpenMP.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "clang/CodeGen/CGFunctionInfo.h" 32 #include "clang/Frontend/CodeGenOptions.h" 33 #include "llvm/Analysis/ValueTracking.h" 34 #include "llvm/IR/DataLayout.h" 35 #include "llvm/IR/GlobalVariable.h" 36 #include "llvm/IR/Intrinsics.h" 37 #include "llvm/IR/Type.h" 38 39 using namespace clang; 40 using namespace CodeGen; 41 42 void CodeGenFunction::EmitDecl(const Decl &D) { 43 switch (D.getKind()) { 44 case Decl::BuiltinTemplate: 45 case Decl::TranslationUnit: 46 case Decl::ExternCContext: 47 case Decl::Namespace: 48 case Decl::UnresolvedUsingTypename: 49 case Decl::ClassTemplateSpecialization: 50 case Decl::ClassTemplatePartialSpecialization: 51 case Decl::VarTemplateSpecialization: 52 case Decl::VarTemplatePartialSpecialization: 53 case Decl::TemplateTypeParm: 54 case Decl::UnresolvedUsingValue: 55 case Decl::NonTypeTemplateParm: 56 case Decl::CXXDeductionGuide: 57 case Decl::CXXMethod: 58 case Decl::CXXConstructor: 59 case Decl::CXXDestructor: 60 case Decl::CXXConversion: 61 case Decl::Field: 62 case Decl::MSProperty: 63 case Decl::IndirectField: 64 case Decl::ObjCIvar: 65 case Decl::ObjCAtDefsField: 66 case Decl::ParmVar: 67 case Decl::ImplicitParam: 68 case Decl::ClassTemplate: 69 case Decl::VarTemplate: 70 case Decl::FunctionTemplate: 71 case Decl::TypeAliasTemplate: 72 case Decl::TemplateTemplateParm: 73 case Decl::ObjCMethod: 74 case Decl::ObjCCategory: 75 case Decl::ObjCProtocol: 76 case Decl::ObjCInterface: 77 case Decl::ObjCCategoryImpl: 78 case Decl::ObjCImplementation: 79 case Decl::ObjCProperty: 80 case Decl::ObjCCompatibleAlias: 81 case Decl::PragmaComment: 82 case Decl::PragmaDetectMismatch: 83 case Decl::AccessSpec: 84 case Decl::LinkageSpec: 85 case Decl::Export: 86 case Decl::ObjCPropertyImpl: 87 case Decl::FileScopeAsm: 88 case Decl::Friend: 89 case Decl::FriendTemplate: 90 case Decl::Block: 91 case Decl::Captured: 92 case Decl::ClassScopeFunctionSpecialization: 93 case Decl::UsingShadow: 94 case Decl::ConstructorUsingShadow: 95 case Decl::ObjCTypeParam: 96 case Decl::Binding: 97 llvm_unreachable("Declaration should not be in declstmts!"); 98 case Decl::Function: // void X(); 99 case Decl::Record: // struct/union/class X; 100 case Decl::Enum: // enum X; 101 case Decl::EnumConstant: // enum ? { X = ? } 102 case Decl::CXXRecord: // struct/union/class X; [C++] 103 case Decl::StaticAssert: // static_assert(X, ""); [C++0x] 104 case Decl::Label: // __label__ x; 105 case Decl::Import: 106 case Decl::OMPThreadPrivate: 107 case Decl::OMPCapturedExpr: 108 case Decl::Empty: 109 // None of these decls require codegen support. 110 return; 111 112 case Decl::NamespaceAlias: 113 if (CGDebugInfo *DI = getDebugInfo()) 114 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(D)); 115 return; 116 case Decl::Using: // using X; [C++] 117 if (CGDebugInfo *DI = getDebugInfo()) 118 DI->EmitUsingDecl(cast<UsingDecl>(D)); 119 return; 120 case Decl::UsingPack: 121 for (auto *Using : cast<UsingPackDecl>(D).expansions()) 122 EmitDecl(*Using); 123 return; 124 case Decl::UsingDirective: // using namespace X; [C++] 125 if (CGDebugInfo *DI = getDebugInfo()) 126 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D)); 127 return; 128 case Decl::Var: 129 case Decl::Decomposition: { 130 const VarDecl &VD = cast<VarDecl>(D); 131 assert(VD.isLocalVarDecl() && 132 "Should not see file-scope variables inside a function!"); 133 EmitVarDecl(VD); 134 if (auto *DD = dyn_cast<DecompositionDecl>(&VD)) 135 for (auto *B : DD->bindings()) 136 if (auto *HD = B->getHoldingVar()) 137 EmitVarDecl(*HD); 138 return; 139 } 140 141 case Decl::OMPDeclareReduction: 142 return CGM.EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(&D), this); 143 144 case Decl::Typedef: // typedef int X; 145 case Decl::TypeAlias: { // using X = int; [C++0x] 146 const TypedefNameDecl &TD = cast<TypedefNameDecl>(D); 147 QualType Ty = TD.getUnderlyingType(); 148 149 if (Ty->isVariablyModifiedType()) 150 EmitVariablyModifiedType(Ty); 151 } 152 } 153 } 154 155 /// EmitVarDecl - This method handles emission of any variable declaration 156 /// inside a function, including static vars etc. 157 void CodeGenFunction::EmitVarDecl(const VarDecl &D) { 158 if (D.hasExternalStorage()) 159 // Don't emit it now, allow it to be emitted lazily on its first use. 160 return; 161 162 // Some function-scope variable does not have static storage but still 163 // needs to be emitted like a static variable, e.g. a function-scope 164 // variable in constant address space in OpenCL. 165 if (D.getStorageDuration() != SD_Automatic) { 166 // Static sampler variables translated to function calls. 167 if (D.getType()->isSamplerT()) 168 return; 169 170 llvm::GlobalValue::LinkageTypes Linkage = 171 CGM.getLLVMLinkageVarDefinition(&D, /*isConstant=*/false); 172 173 // FIXME: We need to force the emission/use of a guard variable for 174 // some variables even if we can constant-evaluate them because 175 // we can't guarantee every translation unit will constant-evaluate them. 176 177 return EmitStaticVarDecl(D, Linkage); 178 } 179 180 if (D.getType().getAddressSpace() == LangAS::opencl_local) 181 return CGM.getOpenCLRuntime().EmitWorkGroupLocalVarDecl(*this, D); 182 183 assert(D.hasLocalStorage()); 184 return EmitAutoVarDecl(D); 185 } 186 187 static std::string getStaticDeclName(CodeGenModule &CGM, const VarDecl &D) { 188 if (CGM.getLangOpts().CPlusPlus) 189 return CGM.getMangledName(&D).str(); 190 191 // If this isn't C++, we don't need a mangled name, just a pretty one. 192 assert(!D.isExternallyVisible() && "name shouldn't matter"); 193 std::string ContextName; 194 const DeclContext *DC = D.getDeclContext(); 195 if (auto *CD = dyn_cast<CapturedDecl>(DC)) 196 DC = cast<DeclContext>(CD->getNonClosureContext()); 197 if (const auto *FD = dyn_cast<FunctionDecl>(DC)) 198 ContextName = CGM.getMangledName(FD); 199 else if (const auto *BD = dyn_cast<BlockDecl>(DC)) 200 ContextName = CGM.getBlockMangledName(GlobalDecl(), BD); 201 else if (const auto *OMD = dyn_cast<ObjCMethodDecl>(DC)) 202 ContextName = OMD->getSelector().getAsString(); 203 else 204 llvm_unreachable("Unknown context for static var decl"); 205 206 ContextName += "." + D.getNameAsString(); 207 return ContextName; 208 } 209 210 llvm::Constant *CodeGenModule::getOrCreateStaticVarDecl( 211 const VarDecl &D, llvm::GlobalValue::LinkageTypes Linkage) { 212 // In general, we don't always emit static var decls once before we reference 213 // them. It is possible to reference them before emitting the function that 214 // contains them, and it is possible to emit the containing function multiple 215 // times. 216 if (llvm::Constant *ExistingGV = StaticLocalDeclMap[&D]) 217 return ExistingGV; 218 219 QualType Ty = D.getType(); 220 assert(Ty->isConstantSizeType() && "VLAs can't be static"); 221 222 // Use the label if the variable is renamed with the asm-label extension. 223 std::string Name; 224 if (D.hasAttr<AsmLabelAttr>()) 225 Name = getMangledName(&D); 226 else 227 Name = getStaticDeclName(*this, D); 228 229 llvm::Type *LTy = getTypes().ConvertTypeForMem(Ty); 230 LangAS AS = GetGlobalVarAddressSpace(&D); 231 unsigned TargetAS = getContext().getTargetAddressSpace(AS); 232 233 // OpenCL variables in local address space and CUDA shared 234 // variables cannot have an initializer. 235 llvm::Constant *Init = nullptr; 236 if (Ty.getAddressSpace() == LangAS::opencl_local || 237 D.hasAttr<CUDASharedAttr>()) 238 Init = llvm::UndefValue::get(LTy); 239 else 240 Init = EmitNullConstant(Ty); 241 242 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 243 getModule(), LTy, Ty.isConstant(getContext()), Linkage, Init, Name, 244 nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 245 GV->setAlignment(getContext().getDeclAlign(&D).getQuantity()); 246 247 if (supportsCOMDAT() && GV->isWeakForLinker()) 248 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 249 250 if (D.getTLSKind()) 251 setTLSMode(GV, D); 252 253 setGVProperties(GV, &D); 254 255 // Make sure the result is of the correct type. 256 LangAS ExpectedAS = Ty.getAddressSpace(); 257 llvm::Constant *Addr = GV; 258 if (AS != ExpectedAS) { 259 Addr = getTargetCodeGenInfo().performAddrSpaceCast( 260 *this, GV, AS, ExpectedAS, 261 LTy->getPointerTo(getContext().getTargetAddressSpace(ExpectedAS))); 262 } 263 264 setStaticLocalDeclAddress(&D, Addr); 265 266 // Ensure that the static local gets initialized by making sure the parent 267 // function gets emitted eventually. 268 const Decl *DC = cast<Decl>(D.getDeclContext()); 269 270 // We can't name blocks or captured statements directly, so try to emit their 271 // parents. 272 if (isa<BlockDecl>(DC) || isa<CapturedDecl>(DC)) { 273 DC = DC->getNonClosureContext(); 274 // FIXME: Ensure that global blocks get emitted. 275 if (!DC) 276 return Addr; 277 } 278 279 GlobalDecl GD; 280 if (const auto *CD = dyn_cast<CXXConstructorDecl>(DC)) 281 GD = GlobalDecl(CD, Ctor_Base); 282 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(DC)) 283 GD = GlobalDecl(DD, Dtor_Base); 284 else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) 285 GD = GlobalDecl(FD); 286 else { 287 // Don't do anything for Obj-C method decls or global closures. We should 288 // never defer them. 289 assert(isa<ObjCMethodDecl>(DC) && "unexpected parent code decl"); 290 } 291 if (GD.getDecl()) { 292 // Disable emission of the parent function for the OpenMP device codegen. 293 CGOpenMPRuntime::DisableAutoDeclareTargetRAII NoDeclTarget(*this); 294 (void)GetAddrOfGlobal(GD); 295 } 296 297 return Addr; 298 } 299 300 /// hasNontrivialDestruction - Determine whether a type's destruction is 301 /// non-trivial. If so, and the variable uses static initialization, we must 302 /// register its destructor to run on exit. 303 static bool hasNontrivialDestruction(QualType T) { 304 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl(); 305 return RD && !RD->hasTrivialDestructor(); 306 } 307 308 /// AddInitializerToStaticVarDecl - Add the initializer for 'D' to the 309 /// global variable that has already been created for it. If the initializer 310 /// has a different type than GV does, this may free GV and return a different 311 /// one. Otherwise it just returns GV. 312 llvm::GlobalVariable * 313 CodeGenFunction::AddInitializerToStaticVarDecl(const VarDecl &D, 314 llvm::GlobalVariable *GV) { 315 ConstantEmitter emitter(*this); 316 llvm::Constant *Init = emitter.tryEmitForInitializer(D); 317 318 // If constant emission failed, then this should be a C++ static 319 // initializer. 320 if (!Init) { 321 if (!getLangOpts().CPlusPlus) 322 CGM.ErrorUnsupported(D.getInit(), "constant l-value expression"); 323 else if (HaveInsertPoint()) { 324 // Since we have a static initializer, this global variable can't 325 // be constant. 326 GV->setConstant(false); 327 328 EmitCXXGuardedInit(D, GV, /*PerformInit*/true); 329 } 330 return GV; 331 } 332 333 // The initializer may differ in type from the global. Rewrite 334 // the global to match the initializer. (We have to do this 335 // because some types, like unions, can't be completely represented 336 // in the LLVM type system.) 337 if (GV->getType()->getElementType() != Init->getType()) { 338 llvm::GlobalVariable *OldGV = GV; 339 340 GV = new llvm::GlobalVariable(CGM.getModule(), Init->getType(), 341 OldGV->isConstant(), 342 OldGV->getLinkage(), Init, "", 343 /*InsertBefore*/ OldGV, 344 OldGV->getThreadLocalMode(), 345 CGM.getContext().getTargetAddressSpace(D.getType())); 346 GV->setVisibility(OldGV->getVisibility()); 347 GV->setDSOLocal(OldGV->isDSOLocal()); 348 GV->setComdat(OldGV->getComdat()); 349 350 // Steal the name of the old global 351 GV->takeName(OldGV); 352 353 // Replace all uses of the old global with the new global 354 llvm::Constant *NewPtrForOldDecl = 355 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 356 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 357 358 // Erase the old global, since it is no longer used. 359 OldGV->eraseFromParent(); 360 } 361 362 GV->setConstant(CGM.isTypeConstant(D.getType(), true)); 363 GV->setInitializer(Init); 364 365 emitter.finalize(GV); 366 367 if (hasNontrivialDestruction(D.getType()) && HaveInsertPoint()) { 368 // We have a constant initializer, but a nontrivial destructor. We still 369 // need to perform a guarded "initialization" in order to register the 370 // destructor. 371 EmitCXXGuardedInit(D, GV, /*PerformInit*/false); 372 } 373 374 return GV; 375 } 376 377 void CodeGenFunction::EmitStaticVarDecl(const VarDecl &D, 378 llvm::GlobalValue::LinkageTypes Linkage) { 379 // Check to see if we already have a global variable for this 380 // declaration. This can happen when double-emitting function 381 // bodies, e.g. with complete and base constructors. 382 llvm::Constant *addr = CGM.getOrCreateStaticVarDecl(D, Linkage); 383 CharUnits alignment = getContext().getDeclAlign(&D); 384 385 // Store into LocalDeclMap before generating initializer to handle 386 // circular references. 387 setAddrOfLocalVar(&D, Address(addr, alignment)); 388 389 // We can't have a VLA here, but we can have a pointer to a VLA, 390 // even though that doesn't really make any sense. 391 // Make sure to evaluate VLA bounds now so that we have them for later. 392 if (D.getType()->isVariablyModifiedType()) 393 EmitVariablyModifiedType(D.getType()); 394 395 // Save the type in case adding the initializer forces a type change. 396 llvm::Type *expectedType = addr->getType(); 397 398 llvm::GlobalVariable *var = 399 cast<llvm::GlobalVariable>(addr->stripPointerCasts()); 400 401 // CUDA's local and local static __shared__ variables should not 402 // have any non-empty initializers. This is ensured by Sema. 403 // Whatever initializer such variable may have when it gets here is 404 // a no-op and should not be emitted. 405 bool isCudaSharedVar = getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 406 D.hasAttr<CUDASharedAttr>(); 407 // If this value has an initializer, emit it. 408 if (D.getInit() && !isCudaSharedVar) 409 var = AddInitializerToStaticVarDecl(D, var); 410 411 var->setAlignment(alignment.getQuantity()); 412 413 if (D.hasAttr<AnnotateAttr>()) 414 CGM.AddGlobalAnnotations(&D, var); 415 416 if (auto *SA = D.getAttr<PragmaClangBSSSectionAttr>()) 417 var->addAttribute("bss-section", SA->getName()); 418 if (auto *SA = D.getAttr<PragmaClangDataSectionAttr>()) 419 var->addAttribute("data-section", SA->getName()); 420 if (auto *SA = D.getAttr<PragmaClangRodataSectionAttr>()) 421 var->addAttribute("rodata-section", SA->getName()); 422 423 if (const SectionAttr *SA = D.getAttr<SectionAttr>()) 424 var->setSection(SA->getName()); 425 426 if (D.hasAttr<UsedAttr>()) 427 CGM.addUsedGlobal(var); 428 429 // We may have to cast the constant because of the initializer 430 // mismatch above. 431 // 432 // FIXME: It is really dangerous to store this in the map; if anyone 433 // RAUW's the GV uses of this constant will be invalid. 434 llvm::Constant *castedAddr = 435 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(var, expectedType); 436 if (var != castedAddr) 437 LocalDeclMap.find(&D)->second = Address(castedAddr, alignment); 438 CGM.setStaticLocalDeclAddress(&D, castedAddr); 439 440 CGM.getSanitizerMetadata()->reportGlobalToASan(var, D); 441 442 // Emit global variable debug descriptor for static vars. 443 CGDebugInfo *DI = getDebugInfo(); 444 if (DI && 445 CGM.getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) { 446 DI->setLocation(D.getLocation()); 447 DI->EmitGlobalVariable(var, &D); 448 } 449 } 450 451 namespace { 452 struct DestroyObject final : EHScopeStack::Cleanup { 453 DestroyObject(Address addr, QualType type, 454 CodeGenFunction::Destroyer *destroyer, 455 bool useEHCleanupForArray) 456 : addr(addr), type(type), destroyer(destroyer), 457 useEHCleanupForArray(useEHCleanupForArray) {} 458 459 Address addr; 460 QualType type; 461 CodeGenFunction::Destroyer *destroyer; 462 bool useEHCleanupForArray; 463 464 void Emit(CodeGenFunction &CGF, Flags flags) override { 465 // Don't use an EH cleanup recursively from an EH cleanup. 466 bool useEHCleanupForArray = 467 flags.isForNormalCleanup() && this->useEHCleanupForArray; 468 469 CGF.emitDestroy(addr, type, destroyer, useEHCleanupForArray); 470 } 471 }; 472 473 template <class Derived> 474 struct DestroyNRVOVariable : EHScopeStack::Cleanup { 475 DestroyNRVOVariable(Address addr, llvm::Value *NRVOFlag) 476 : NRVOFlag(NRVOFlag), Loc(addr) {} 477 478 llvm::Value *NRVOFlag; 479 Address Loc; 480 481 void Emit(CodeGenFunction &CGF, Flags flags) override { 482 // Along the exceptions path we always execute the dtor. 483 bool NRVO = flags.isForNormalCleanup() && NRVOFlag; 484 485 llvm::BasicBlock *SkipDtorBB = nullptr; 486 if (NRVO) { 487 // If we exited via NRVO, we skip the destructor call. 488 llvm::BasicBlock *RunDtorBB = CGF.createBasicBlock("nrvo.unused"); 489 SkipDtorBB = CGF.createBasicBlock("nrvo.skipdtor"); 490 llvm::Value *DidNRVO = 491 CGF.Builder.CreateFlagLoad(NRVOFlag, "nrvo.val"); 492 CGF.Builder.CreateCondBr(DidNRVO, SkipDtorBB, RunDtorBB); 493 CGF.EmitBlock(RunDtorBB); 494 } 495 496 static_cast<Derived *>(this)->emitDestructorCall(CGF); 497 498 if (NRVO) CGF.EmitBlock(SkipDtorBB); 499 } 500 501 virtual ~DestroyNRVOVariable() = default; 502 }; 503 504 struct DestroyNRVOVariableCXX final 505 : DestroyNRVOVariable<DestroyNRVOVariableCXX> { 506 DestroyNRVOVariableCXX(Address addr, const CXXDestructorDecl *Dtor, 507 llvm::Value *NRVOFlag) 508 : DestroyNRVOVariable<DestroyNRVOVariableCXX>(addr, NRVOFlag), 509 Dtor(Dtor) {} 510 511 const CXXDestructorDecl *Dtor; 512 513 void emitDestructorCall(CodeGenFunction &CGF) { 514 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 515 /*ForVirtualBase=*/false, 516 /*Delegating=*/false, Loc); 517 } 518 }; 519 520 struct DestroyNRVOVariableC final 521 : DestroyNRVOVariable<DestroyNRVOVariableC> { 522 DestroyNRVOVariableC(Address addr, llvm::Value *NRVOFlag, QualType Ty) 523 : DestroyNRVOVariable<DestroyNRVOVariableC>(addr, NRVOFlag), Ty(Ty) {} 524 525 QualType Ty; 526 527 void emitDestructorCall(CodeGenFunction &CGF) { 528 CGF.destroyNonTrivialCStruct(CGF, Loc, Ty); 529 } 530 }; 531 532 struct CallStackRestore final : EHScopeStack::Cleanup { 533 Address Stack; 534 CallStackRestore(Address Stack) : Stack(Stack) {} 535 void Emit(CodeGenFunction &CGF, Flags flags) override { 536 llvm::Value *V = CGF.Builder.CreateLoad(Stack); 537 llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore); 538 CGF.Builder.CreateCall(F, V); 539 } 540 }; 541 542 struct ExtendGCLifetime final : EHScopeStack::Cleanup { 543 const VarDecl &Var; 544 ExtendGCLifetime(const VarDecl *var) : Var(*var) {} 545 546 void Emit(CodeGenFunction &CGF, Flags flags) override { 547 // Compute the address of the local variable, in case it's a 548 // byref or something. 549 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false, 550 Var.getType(), VK_LValue, SourceLocation()); 551 llvm::Value *value = CGF.EmitLoadOfScalar(CGF.EmitDeclRefLValue(&DRE), 552 SourceLocation()); 553 CGF.EmitExtendGCLifetime(value); 554 } 555 }; 556 557 struct CallCleanupFunction final : EHScopeStack::Cleanup { 558 llvm::Constant *CleanupFn; 559 const CGFunctionInfo &FnInfo; 560 const VarDecl &Var; 561 562 CallCleanupFunction(llvm::Constant *CleanupFn, const CGFunctionInfo *Info, 563 const VarDecl *Var) 564 : CleanupFn(CleanupFn), FnInfo(*Info), Var(*Var) {} 565 566 void Emit(CodeGenFunction &CGF, Flags flags) override { 567 DeclRefExpr DRE(const_cast<VarDecl*>(&Var), false, 568 Var.getType(), VK_LValue, SourceLocation()); 569 // Compute the address of the local variable, in case it's a byref 570 // or something. 571 llvm::Value *Addr = CGF.EmitDeclRefLValue(&DRE).getPointer(); 572 573 // In some cases, the type of the function argument will be different from 574 // the type of the pointer. An example of this is 575 // void f(void* arg); 576 // __attribute__((cleanup(f))) void *g; 577 // 578 // To fix this we insert a bitcast here. 579 QualType ArgTy = FnInfo.arg_begin()->type; 580 llvm::Value *Arg = 581 CGF.Builder.CreateBitCast(Addr, CGF.ConvertType(ArgTy)); 582 583 CallArgList Args; 584 Args.add(RValue::get(Arg), 585 CGF.getContext().getPointerType(Var.getType())); 586 auto Callee = CGCallee::forDirect(CleanupFn); 587 CGF.EmitCall(FnInfo, Callee, ReturnValueSlot(), Args); 588 } 589 }; 590 } // end anonymous namespace 591 592 /// EmitAutoVarWithLifetime - Does the setup required for an automatic 593 /// variable with lifetime. 594 static void EmitAutoVarWithLifetime(CodeGenFunction &CGF, const VarDecl &var, 595 Address addr, 596 Qualifiers::ObjCLifetime lifetime) { 597 switch (lifetime) { 598 case Qualifiers::OCL_None: 599 llvm_unreachable("present but none"); 600 601 case Qualifiers::OCL_ExplicitNone: 602 // nothing to do 603 break; 604 605 case Qualifiers::OCL_Strong: { 606 CodeGenFunction::Destroyer *destroyer = 607 (var.hasAttr<ObjCPreciseLifetimeAttr>() 608 ? CodeGenFunction::destroyARCStrongPrecise 609 : CodeGenFunction::destroyARCStrongImprecise); 610 611 CleanupKind cleanupKind = CGF.getARCCleanupKind(); 612 CGF.pushDestroy(cleanupKind, addr, var.getType(), destroyer, 613 cleanupKind & EHCleanup); 614 break; 615 } 616 case Qualifiers::OCL_Autoreleasing: 617 // nothing to do 618 break; 619 620 case Qualifiers::OCL_Weak: 621 // __weak objects always get EH cleanups; otherwise, exceptions 622 // could cause really nasty crashes instead of mere leaks. 623 CGF.pushDestroy(NormalAndEHCleanup, addr, var.getType(), 624 CodeGenFunction::destroyARCWeak, 625 /*useEHCleanup*/ true); 626 break; 627 } 628 } 629 630 static bool isAccessedBy(const VarDecl &var, const Stmt *s) { 631 if (const Expr *e = dyn_cast<Expr>(s)) { 632 // Skip the most common kinds of expressions that make 633 // hierarchy-walking expensive. 634 s = e = e->IgnoreParenCasts(); 635 636 if (const DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) 637 return (ref->getDecl() == &var); 638 if (const BlockExpr *be = dyn_cast<BlockExpr>(e)) { 639 const BlockDecl *block = be->getBlockDecl(); 640 for (const auto &I : block->captures()) { 641 if (I.getVariable() == &var) 642 return true; 643 } 644 } 645 } 646 647 for (const Stmt *SubStmt : s->children()) 648 // SubStmt might be null; as in missing decl or conditional of an if-stmt. 649 if (SubStmt && isAccessedBy(var, SubStmt)) 650 return true; 651 652 return false; 653 } 654 655 static bool isAccessedBy(const ValueDecl *decl, const Expr *e) { 656 if (!decl) return false; 657 if (!isa<VarDecl>(decl)) return false; 658 const VarDecl *var = cast<VarDecl>(decl); 659 return isAccessedBy(*var, e); 660 } 661 662 static bool tryEmitARCCopyWeakInit(CodeGenFunction &CGF, 663 const LValue &destLV, const Expr *init) { 664 bool needsCast = false; 665 666 while (auto castExpr = dyn_cast<CastExpr>(init->IgnoreParens())) { 667 switch (castExpr->getCastKind()) { 668 // Look through casts that don't require representation changes. 669 case CK_NoOp: 670 case CK_BitCast: 671 case CK_BlockPointerToObjCPointerCast: 672 needsCast = true; 673 break; 674 675 // If we find an l-value to r-value cast from a __weak variable, 676 // emit this operation as a copy or move. 677 case CK_LValueToRValue: { 678 const Expr *srcExpr = castExpr->getSubExpr(); 679 if (srcExpr->getType().getObjCLifetime() != Qualifiers::OCL_Weak) 680 return false; 681 682 // Emit the source l-value. 683 LValue srcLV = CGF.EmitLValue(srcExpr); 684 685 // Handle a formal type change to avoid asserting. 686 auto srcAddr = srcLV.getAddress(); 687 if (needsCast) { 688 srcAddr = CGF.Builder.CreateElementBitCast(srcAddr, 689 destLV.getAddress().getElementType()); 690 } 691 692 // If it was an l-value, use objc_copyWeak. 693 if (srcExpr->getValueKind() == VK_LValue) { 694 CGF.EmitARCCopyWeak(destLV.getAddress(), srcAddr); 695 } else { 696 assert(srcExpr->getValueKind() == VK_XValue); 697 CGF.EmitARCMoveWeak(destLV.getAddress(), srcAddr); 698 } 699 return true; 700 } 701 702 // Stop at anything else. 703 default: 704 return false; 705 } 706 707 init = castExpr->getSubExpr(); 708 } 709 return false; 710 } 711 712 static void drillIntoBlockVariable(CodeGenFunction &CGF, 713 LValue &lvalue, 714 const VarDecl *var) { 715 lvalue.setAddress(CGF.emitBlockByrefAddress(lvalue.getAddress(), var)); 716 } 717 718 void CodeGenFunction::EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, 719 SourceLocation Loc) { 720 if (!SanOpts.has(SanitizerKind::NullabilityAssign)) 721 return; 722 723 auto Nullability = LHS.getType()->getNullability(getContext()); 724 if (!Nullability || *Nullability != NullabilityKind::NonNull) 725 return; 726 727 // Check if the right hand side of the assignment is nonnull, if the left 728 // hand side must be nonnull. 729 SanitizerScope SanScope(this); 730 llvm::Value *IsNotNull = Builder.CreateIsNotNull(RHS); 731 llvm::Constant *StaticData[] = { 732 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(LHS.getType()), 733 llvm::ConstantInt::get(Int8Ty, 0), // The LogAlignment info is unused. 734 llvm::ConstantInt::get(Int8Ty, TCK_NonnullAssign)}; 735 EmitCheck({{IsNotNull, SanitizerKind::NullabilityAssign}}, 736 SanitizerHandler::TypeMismatch, StaticData, RHS); 737 } 738 739 void CodeGenFunction::EmitScalarInit(const Expr *init, const ValueDecl *D, 740 LValue lvalue, bool capturedByInit) { 741 Qualifiers::ObjCLifetime lifetime = lvalue.getObjCLifetime(); 742 if (!lifetime) { 743 llvm::Value *value = EmitScalarExpr(init); 744 if (capturedByInit) 745 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 746 EmitNullabilityCheck(lvalue, value, init->getExprLoc()); 747 EmitStoreThroughLValue(RValue::get(value), lvalue, true); 748 return; 749 } 750 751 if (const CXXDefaultInitExpr *DIE = dyn_cast<CXXDefaultInitExpr>(init)) 752 init = DIE->getExpr(); 753 754 // If we're emitting a value with lifetime, we have to do the 755 // initialization *before* we leave the cleanup scopes. 756 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(init)) { 757 enterFullExpression(ewc); 758 init = ewc->getSubExpr(); 759 } 760 CodeGenFunction::RunCleanupsScope Scope(*this); 761 762 // We have to maintain the illusion that the variable is 763 // zero-initialized. If the variable might be accessed in its 764 // initializer, zero-initialize before running the initializer, then 765 // actually perform the initialization with an assign. 766 bool accessedByInit = false; 767 if (lifetime != Qualifiers::OCL_ExplicitNone) 768 accessedByInit = (capturedByInit || isAccessedBy(D, init)); 769 if (accessedByInit) { 770 LValue tempLV = lvalue; 771 // Drill down to the __block object if necessary. 772 if (capturedByInit) { 773 // We can use a simple GEP for this because it can't have been 774 // moved yet. 775 tempLV.setAddress(emitBlockByrefAddress(tempLV.getAddress(), 776 cast<VarDecl>(D), 777 /*follow*/ false)); 778 } 779 780 auto ty = cast<llvm::PointerType>(tempLV.getAddress().getElementType()); 781 llvm::Value *zero = CGM.getNullPointer(ty, tempLV.getType()); 782 783 // If __weak, we want to use a barrier under certain conditions. 784 if (lifetime == Qualifiers::OCL_Weak) 785 EmitARCInitWeak(tempLV.getAddress(), zero); 786 787 // Otherwise just do a simple store. 788 else 789 EmitStoreOfScalar(zero, tempLV, /* isInitialization */ true); 790 } 791 792 // Emit the initializer. 793 llvm::Value *value = nullptr; 794 795 switch (lifetime) { 796 case Qualifiers::OCL_None: 797 llvm_unreachable("present but none"); 798 799 case Qualifiers::OCL_ExplicitNone: 800 value = EmitARCUnsafeUnretainedScalarExpr(init); 801 break; 802 803 case Qualifiers::OCL_Strong: { 804 value = EmitARCRetainScalarExpr(init); 805 break; 806 } 807 808 case Qualifiers::OCL_Weak: { 809 // If it's not accessed by the initializer, try to emit the 810 // initialization with a copy or move. 811 if (!accessedByInit && tryEmitARCCopyWeakInit(*this, lvalue, init)) { 812 return; 813 } 814 815 // No way to optimize a producing initializer into this. It's not 816 // worth optimizing for, because the value will immediately 817 // disappear in the common case. 818 value = EmitScalarExpr(init); 819 820 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 821 if (accessedByInit) 822 EmitARCStoreWeak(lvalue.getAddress(), value, /*ignored*/ true); 823 else 824 EmitARCInitWeak(lvalue.getAddress(), value); 825 return; 826 } 827 828 case Qualifiers::OCL_Autoreleasing: 829 value = EmitARCRetainAutoreleaseScalarExpr(init); 830 break; 831 } 832 833 if (capturedByInit) drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 834 835 EmitNullabilityCheck(lvalue, value, init->getExprLoc()); 836 837 // If the variable might have been accessed by its initializer, we 838 // might have to initialize with a barrier. We have to do this for 839 // both __weak and __strong, but __weak got filtered out above. 840 if (accessedByInit && lifetime == Qualifiers::OCL_Strong) { 841 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, init->getExprLoc()); 842 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 843 EmitARCRelease(oldValue, ARCImpreciseLifetime); 844 return; 845 } 846 847 EmitStoreOfScalar(value, lvalue, /* isInitialization */ true); 848 } 849 850 /// Decide whether we can emit the non-zero parts of the specified initializer 851 /// with equal or fewer than NumStores scalar stores. 852 static bool canEmitInitWithFewStoresAfterBZero(llvm::Constant *Init, 853 unsigned &NumStores) { 854 // Zero and Undef never requires any extra stores. 855 if (isa<llvm::ConstantAggregateZero>(Init) || 856 isa<llvm::ConstantPointerNull>(Init) || 857 isa<llvm::UndefValue>(Init)) 858 return true; 859 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 860 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 861 isa<llvm::ConstantExpr>(Init)) 862 return Init->isNullValue() || NumStores--; 863 864 // See if we can emit each element. 865 if (isa<llvm::ConstantArray>(Init) || isa<llvm::ConstantStruct>(Init)) { 866 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 867 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 868 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores)) 869 return false; 870 } 871 return true; 872 } 873 874 if (llvm::ConstantDataSequential *CDS = 875 dyn_cast<llvm::ConstantDataSequential>(Init)) { 876 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 877 llvm::Constant *Elt = CDS->getElementAsConstant(i); 878 if (!canEmitInitWithFewStoresAfterBZero(Elt, NumStores)) 879 return false; 880 } 881 return true; 882 } 883 884 // Anything else is hard and scary. 885 return false; 886 } 887 888 /// For inits that canEmitInitWithFewStoresAfterBZero returned true for, emit 889 /// the scalar stores that would be required. 890 static void emitStoresForInitAfterBZero(CodeGenModule &CGM, 891 llvm::Constant *Init, Address Loc, 892 bool isVolatile, CGBuilderTy &Builder) { 893 assert(!Init->isNullValue() && !isa<llvm::UndefValue>(Init) && 894 "called emitStoresForInitAfterBZero for zero or undef value."); 895 896 if (isa<llvm::ConstantInt>(Init) || isa<llvm::ConstantFP>(Init) || 897 isa<llvm::ConstantVector>(Init) || isa<llvm::BlockAddress>(Init) || 898 isa<llvm::ConstantExpr>(Init)) { 899 Builder.CreateStore(Init, Loc, isVolatile); 900 return; 901 } 902 903 if (llvm::ConstantDataSequential *CDS = 904 dyn_cast<llvm::ConstantDataSequential>(Init)) { 905 for (unsigned i = 0, e = CDS->getNumElements(); i != e; ++i) { 906 llvm::Constant *Elt = CDS->getElementAsConstant(i); 907 908 // If necessary, get a pointer to the element and emit it. 909 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 910 emitStoresForInitAfterBZero( 911 CGM, Elt, 912 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()), 913 isVolatile, Builder); 914 } 915 return; 916 } 917 918 assert((isa<llvm::ConstantStruct>(Init) || isa<llvm::ConstantArray>(Init)) && 919 "Unknown value type!"); 920 921 for (unsigned i = 0, e = Init->getNumOperands(); i != e; ++i) { 922 llvm::Constant *Elt = cast<llvm::Constant>(Init->getOperand(i)); 923 924 // If necessary, get a pointer to the element and emit it. 925 if (!Elt->isNullValue() && !isa<llvm::UndefValue>(Elt)) 926 emitStoresForInitAfterBZero( 927 CGM, Elt, 928 Builder.CreateConstInBoundsGEP2_32(Loc, 0, i, CGM.getDataLayout()), 929 isVolatile, Builder); 930 } 931 } 932 933 /// Decide whether we should use bzero plus some stores to initialize a local 934 /// variable instead of using a memcpy from a constant global. It is beneficial 935 /// to use bzero if the global is all zeros, or mostly zeros and large. 936 static bool shouldUseBZeroPlusStoresToInitialize(llvm::Constant *Init, 937 uint64_t GlobalSize) { 938 // If a global is all zeros, always use a bzero. 939 if (isa<llvm::ConstantAggregateZero>(Init)) return true; 940 941 // If a non-zero global is <= 32 bytes, always use a memcpy. If it is large, 942 // do it if it will require 6 or fewer scalar stores. 943 // TODO: Should budget depends on the size? Avoiding a large global warrants 944 // plopping in more stores. 945 unsigned StoreBudget = 6; 946 uint64_t SizeLimit = 32; 947 948 return GlobalSize > SizeLimit && 949 canEmitInitWithFewStoresAfterBZero(Init, StoreBudget); 950 } 951 952 /// Decide whether we should use memset to initialize a local variable instead 953 /// of using a memcpy from a constant global. Assumes we've already decided to 954 /// not user bzero. 955 /// FIXME We could be more clever, as we are for bzero above, and generate 956 /// memset followed by stores. It's unclear that's worth the effort. 957 static llvm::Value *shouldUseMemSetToInitialize(llvm::Constant *Init, 958 uint64_t GlobalSize) { 959 uint64_t SizeLimit = 32; 960 if (GlobalSize <= SizeLimit) 961 return nullptr; 962 return llvm::isBytewiseValue(Init); 963 } 964 965 static void emitStoresForConstant(CodeGenModule &CGM, const VarDecl &D, 966 Address Loc, bool isVolatile, 967 CGBuilderTy &Builder, 968 llvm::Constant *constant) { 969 auto *Int8Ty = llvm::IntegerType::getInt8Ty(CGM.getLLVMContext()); 970 auto *IntPtrTy = CGM.getDataLayout().getIntPtrType(CGM.getLLVMContext()); 971 972 // If the initializer is all or mostly the same, codegen with bzero / memset 973 // then do a few stores afterward. 974 uint64_t ConstantSize = 975 CGM.getDataLayout().getTypeAllocSize(constant->getType()); 976 auto *SizeVal = llvm::ConstantInt::get(IntPtrTy, ConstantSize); 977 if (shouldUseBZeroPlusStoresToInitialize(constant, ConstantSize)) { 978 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, 0), SizeVal, 979 isVolatile); 980 981 bool valueAlreadyCorrect = 982 constant->isNullValue() || isa<llvm::UndefValue>(constant); 983 if (!valueAlreadyCorrect) { 984 Loc = Builder.CreateBitCast( 985 Loc, constant->getType()->getPointerTo(Loc.getAddressSpace())); 986 emitStoresForInitAfterBZero(CGM, constant, Loc, isVolatile, Builder); 987 } 988 return; 989 } 990 991 llvm::Value *Pattern = shouldUseMemSetToInitialize(constant, ConstantSize); 992 if (Pattern) { 993 uint64_t Value = 0x00; 994 if (!isa<llvm::UndefValue>(Pattern)) { 995 const llvm::APInt &AP = cast<llvm::ConstantInt>(Pattern)->getValue(); 996 assert(AP.getBitWidth() <= 8); 997 Value = AP.getLimitedValue(); 998 } 999 Builder.CreateMemSet(Loc, llvm::ConstantInt::get(Int8Ty, Value), SizeVal, 1000 isVolatile); 1001 return; 1002 } 1003 1004 // Otherwise, create a temporary global with the initializer then memcpy from 1005 // the global to the alloca. 1006 std::string Name = getStaticDeclName(CGM, D); 1007 unsigned AS = CGM.getContext().getTargetAddressSpace( 1008 CGM.getStringLiteralAddressSpace()); 1009 llvm::Type *BP = llvm::PointerType::getInt8PtrTy(CGM.getLLVMContext(), AS); 1010 1011 llvm::GlobalVariable *GV = new llvm::GlobalVariable( 1012 CGM.getModule(), constant->getType(), true, 1013 llvm::GlobalValue::PrivateLinkage, constant, Name, nullptr, 1014 llvm::GlobalValue::NotThreadLocal, AS); 1015 GV->setAlignment(Loc.getAlignment().getQuantity()); 1016 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 1017 1018 Address SrcPtr = Address(GV, Loc.getAlignment()); 1019 if (SrcPtr.getType() != BP) 1020 SrcPtr = Builder.CreateBitCast(SrcPtr, BP); 1021 1022 Builder.CreateMemCpy(Loc, SrcPtr, SizeVal, isVolatile); 1023 } 1024 1025 /// EmitAutoVarDecl - Emit code and set up an entry in LocalDeclMap for a 1026 /// variable declaration with auto, register, or no storage class specifier. 1027 /// These turn into simple stack objects, or GlobalValues depending on target. 1028 void CodeGenFunction::EmitAutoVarDecl(const VarDecl &D) { 1029 AutoVarEmission emission = EmitAutoVarAlloca(D); 1030 EmitAutoVarInit(emission); 1031 EmitAutoVarCleanups(emission); 1032 } 1033 1034 /// Emit a lifetime.begin marker if some criteria are satisfied. 1035 /// \return a pointer to the temporary size Value if a marker was emitted, null 1036 /// otherwise 1037 llvm::Value *CodeGenFunction::EmitLifetimeStart(uint64_t Size, 1038 llvm::Value *Addr) { 1039 if (!ShouldEmitLifetimeMarkers) 1040 return nullptr; 1041 1042 assert(Addr->getType()->getPointerAddressSpace() == 1043 CGM.getDataLayout().getAllocaAddrSpace() && 1044 "Pointer should be in alloca address space"); 1045 llvm::Value *SizeV = llvm::ConstantInt::get(Int64Ty, Size); 1046 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy); 1047 llvm::CallInst *C = 1048 Builder.CreateCall(CGM.getLLVMLifetimeStartFn(), {SizeV, Addr}); 1049 C->setDoesNotThrow(); 1050 return SizeV; 1051 } 1052 1053 void CodeGenFunction::EmitLifetimeEnd(llvm::Value *Size, llvm::Value *Addr) { 1054 assert(Addr->getType()->getPointerAddressSpace() == 1055 CGM.getDataLayout().getAllocaAddrSpace() && 1056 "Pointer should be in alloca address space"); 1057 Addr = Builder.CreateBitCast(Addr, AllocaInt8PtrTy); 1058 llvm::CallInst *C = 1059 Builder.CreateCall(CGM.getLLVMLifetimeEndFn(), {Size, Addr}); 1060 C->setDoesNotThrow(); 1061 } 1062 1063 void CodeGenFunction::EmitAndRegisterVariableArrayDimensions( 1064 CGDebugInfo *DI, const VarDecl &D, bool EmitDebugInfo) { 1065 // For each dimension stores its QualType and corresponding 1066 // size-expression Value. 1067 SmallVector<CodeGenFunction::VlaSizePair, 4> Dimensions; 1068 1069 // Break down the array into individual dimensions. 1070 QualType Type1D = D.getType(); 1071 while (getContext().getAsVariableArrayType(Type1D)) { 1072 auto VlaSize = getVLAElements1D(Type1D); 1073 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts)) 1074 Dimensions.emplace_back(C, Type1D.getUnqualifiedType()); 1075 else { 1076 auto SizeExprAddr = CreateDefaultAlignTempAlloca( 1077 VlaSize.NumElts->getType(), "__vla_expr"); 1078 Builder.CreateStore(VlaSize.NumElts, SizeExprAddr); 1079 Dimensions.emplace_back(SizeExprAddr.getPointer(), 1080 Type1D.getUnqualifiedType()); 1081 } 1082 Type1D = VlaSize.Type; 1083 } 1084 1085 if (!EmitDebugInfo) 1086 return; 1087 1088 // Register each dimension's size-expression with a DILocalVariable, 1089 // so that it can be used by CGDebugInfo when instantiating a DISubrange 1090 // to describe this array. 1091 for (auto &VlaSize : Dimensions) { 1092 llvm::Metadata *MD; 1093 if (auto *C = dyn_cast<llvm::ConstantInt>(VlaSize.NumElts)) 1094 MD = llvm::ConstantAsMetadata::get(C); 1095 else { 1096 // Create an artificial VarDecl to generate debug info for. 1097 IdentifierInfo &NameIdent = getContext().Idents.getOwn( 1098 cast<llvm::AllocaInst>(VlaSize.NumElts)->getName()); 1099 auto VlaExprTy = VlaSize.NumElts->getType()->getPointerElementType(); 1100 auto QT = getContext().getIntTypeForBitwidth( 1101 VlaExprTy->getScalarSizeInBits(), false); 1102 auto *ArtificialDecl = VarDecl::Create( 1103 getContext(), const_cast<DeclContext *>(D.getDeclContext()), 1104 D.getLocation(), D.getLocation(), &NameIdent, QT, 1105 getContext().CreateTypeSourceInfo(QT), SC_Auto); 1106 ArtificialDecl->setImplicit(); 1107 1108 MD = DI->EmitDeclareOfAutoVariable(ArtificialDecl, VlaSize.NumElts, 1109 Builder); 1110 } 1111 assert(MD && "No Size expression debug node created"); 1112 DI->registerVLASizeExpression(VlaSize.Type, MD); 1113 } 1114 } 1115 1116 /// EmitAutoVarAlloca - Emit the alloca and debug information for a 1117 /// local variable. Does not emit initialization or destruction. 1118 CodeGenFunction::AutoVarEmission 1119 CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) { 1120 QualType Ty = D.getType(); 1121 assert( 1122 Ty.getAddressSpace() == LangAS::Default || 1123 (Ty.getAddressSpace() == LangAS::opencl_private && getLangOpts().OpenCL)); 1124 1125 AutoVarEmission emission(D); 1126 1127 bool isByRef = D.hasAttr<BlocksAttr>(); 1128 emission.IsByRef = isByRef; 1129 1130 CharUnits alignment = getContext().getDeclAlign(&D); 1131 1132 // If the type is variably-modified, emit all the VLA sizes for it. 1133 if (Ty->isVariablyModifiedType()) 1134 EmitVariablyModifiedType(Ty); 1135 1136 auto *DI = getDebugInfo(); 1137 bool EmitDebugInfo = DI && CGM.getCodeGenOpts().getDebugInfo() >= 1138 codegenoptions::LimitedDebugInfo; 1139 1140 Address address = Address::invalid(); 1141 Address AllocaAddr = Address::invalid(); 1142 if (Ty->isConstantSizeType()) { 1143 bool NRVO = getLangOpts().ElideConstructors && 1144 D.isNRVOVariable(); 1145 1146 // If this value is an array or struct with a statically determinable 1147 // constant initializer, there are optimizations we can do. 1148 // 1149 // TODO: We should constant-evaluate the initializer of any variable, 1150 // as long as it is initialized by a constant expression. Currently, 1151 // isConstantInitializer produces wrong answers for structs with 1152 // reference or bitfield members, and a few other cases, and checking 1153 // for POD-ness protects us from some of these. 1154 if (D.getInit() && (Ty->isArrayType() || Ty->isRecordType()) && 1155 (D.isConstexpr() || 1156 ((Ty.isPODType(getContext()) || 1157 getContext().getBaseElementType(Ty)->isObjCObjectPointerType()) && 1158 D.getInit()->isConstantInitializer(getContext(), false)))) { 1159 1160 // If the variable's a const type, and it's neither an NRVO 1161 // candidate nor a __block variable and has no mutable members, 1162 // emit it as a global instead. 1163 // Exception is if a variable is located in non-constant address space 1164 // in OpenCL. 1165 if ((!getLangOpts().OpenCL || 1166 Ty.getAddressSpace() == LangAS::opencl_constant) && 1167 (CGM.getCodeGenOpts().MergeAllConstants && !NRVO && !isByRef && 1168 CGM.isTypeConstant(Ty, true))) { 1169 EmitStaticVarDecl(D, llvm::GlobalValue::InternalLinkage); 1170 1171 // Signal this condition to later callbacks. 1172 emission.Addr = Address::invalid(); 1173 assert(emission.wasEmittedAsGlobal()); 1174 return emission; 1175 } 1176 1177 // Otherwise, tell the initialization code that we're in this case. 1178 emission.IsConstantAggregate = true; 1179 } 1180 1181 // A normal fixed sized variable becomes an alloca in the entry block, 1182 // unless: 1183 // - it's an NRVO variable. 1184 // - we are compiling OpenMP and it's an OpenMP local variable. 1185 1186 Address OpenMPLocalAddr = 1187 getLangOpts().OpenMP 1188 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D) 1189 : Address::invalid(); 1190 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) { 1191 address = OpenMPLocalAddr; 1192 } else if (NRVO) { 1193 // The named return value optimization: allocate this variable in the 1194 // return slot, so that we can elide the copy when returning this 1195 // variable (C++0x [class.copy]p34). 1196 address = ReturnValue; 1197 1198 if (const RecordType *RecordTy = Ty->getAs<RecordType>()) { 1199 const auto *RD = RecordTy->getDecl(); 1200 const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 1201 if ((CXXRD && !CXXRD->hasTrivialDestructor()) || 1202 RD->isNonTrivialToPrimitiveDestroy()) { 1203 // Create a flag that is used to indicate when the NRVO was applied 1204 // to this variable. Set it to zero to indicate that NRVO was not 1205 // applied. 1206 llvm::Value *Zero = Builder.getFalse(); 1207 Address NRVOFlag = 1208 CreateTempAlloca(Zero->getType(), CharUnits::One(), "nrvo"); 1209 EnsureInsertPoint(); 1210 Builder.CreateStore(Zero, NRVOFlag); 1211 1212 // Record the NRVO flag for this variable. 1213 NRVOFlags[&D] = NRVOFlag.getPointer(); 1214 emission.NRVOFlag = NRVOFlag.getPointer(); 1215 } 1216 } 1217 } else { 1218 CharUnits allocaAlignment; 1219 llvm::Type *allocaTy; 1220 if (isByRef) { 1221 auto &byrefInfo = getBlockByrefInfo(&D); 1222 allocaTy = byrefInfo.Type; 1223 allocaAlignment = byrefInfo.ByrefAlignment; 1224 } else { 1225 allocaTy = ConvertTypeForMem(Ty); 1226 allocaAlignment = alignment; 1227 } 1228 1229 // Create the alloca. Note that we set the name separately from 1230 // building the instruction so that it's there even in no-asserts 1231 // builds. 1232 address = CreateTempAlloca(allocaTy, allocaAlignment, D.getName(), 1233 /*ArraySize=*/nullptr, &AllocaAddr); 1234 1235 // Don't emit lifetime markers for MSVC catch parameters. The lifetime of 1236 // the catch parameter starts in the catchpad instruction, and we can't 1237 // insert code in those basic blocks. 1238 bool IsMSCatchParam = 1239 D.isExceptionVariable() && getTarget().getCXXABI().isMicrosoft(); 1240 1241 // Emit a lifetime intrinsic if meaningful. There's no point in doing this 1242 // if we don't have a valid insertion point (?). 1243 if (HaveInsertPoint() && !IsMSCatchParam) { 1244 // If there's a jump into the lifetime of this variable, its lifetime 1245 // gets broken up into several regions in IR, which requires more work 1246 // to handle correctly. For now, just omit the intrinsics; this is a 1247 // rare case, and it's better to just be conservatively correct. 1248 // PR28267. 1249 // 1250 // We have to do this in all language modes if there's a jump past the 1251 // declaration. We also have to do it in C if there's a jump to an 1252 // earlier point in the current block because non-VLA lifetimes begin as 1253 // soon as the containing block is entered, not when its variables 1254 // actually come into scope; suppressing the lifetime annotations 1255 // completely in this case is unnecessarily pessimistic, but again, this 1256 // is rare. 1257 if (!Bypasses.IsBypassed(&D) && 1258 !(!getLangOpts().CPlusPlus && hasLabelBeenSeenInCurrentScope())) { 1259 uint64_t size = CGM.getDataLayout().getTypeAllocSize(allocaTy); 1260 emission.SizeForLifetimeMarkers = 1261 EmitLifetimeStart(size, AllocaAddr.getPointer()); 1262 } 1263 } else { 1264 assert(!emission.useLifetimeMarkers()); 1265 } 1266 } 1267 } else { 1268 EnsureInsertPoint(); 1269 1270 if (!DidCallStackSave) { 1271 // Save the stack. 1272 Address Stack = 1273 CreateTempAlloca(Int8PtrTy, getPointerAlign(), "saved_stack"); 1274 1275 llvm::Value *F = CGM.getIntrinsic(llvm::Intrinsic::stacksave); 1276 llvm::Value *V = Builder.CreateCall(F); 1277 Builder.CreateStore(V, Stack); 1278 1279 DidCallStackSave = true; 1280 1281 // Push a cleanup block and restore the stack there. 1282 // FIXME: in general circumstances, this should be an EH cleanup. 1283 pushStackRestore(NormalCleanup, Stack); 1284 } 1285 1286 auto VlaSize = getVLASize(Ty); 1287 llvm::Type *llvmTy = ConvertTypeForMem(VlaSize.Type); 1288 1289 // Allocate memory for the array. 1290 address = CreateTempAlloca(llvmTy, alignment, "vla", VlaSize.NumElts, 1291 &AllocaAddr); 1292 1293 // If we have debug info enabled, properly describe the VLA dimensions for 1294 // this type by registering the vla size expression for each of the 1295 // dimensions. 1296 EmitAndRegisterVariableArrayDimensions(DI, D, EmitDebugInfo); 1297 } 1298 1299 setAddrOfLocalVar(&D, address); 1300 emission.Addr = address; 1301 emission.AllocaAddr = AllocaAddr; 1302 1303 // Emit debug info for local var declaration. 1304 if (EmitDebugInfo && HaveInsertPoint()) { 1305 DI->setLocation(D.getLocation()); 1306 (void)DI->EmitDeclareOfAutoVariable(&D, address.getPointer(), Builder); 1307 } 1308 1309 if (D.hasAttr<AnnotateAttr>()) 1310 EmitVarAnnotations(&D, address.getPointer()); 1311 1312 // Make sure we call @llvm.lifetime.end. 1313 if (emission.useLifetimeMarkers()) 1314 EHStack.pushCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, 1315 emission.getOriginalAllocatedAddress(), 1316 emission.getSizeForLifetimeMarkers()); 1317 1318 return emission; 1319 } 1320 1321 static bool isCapturedBy(const VarDecl &, const Expr *); 1322 1323 /// Determines whether the given __block variable is potentially 1324 /// captured by the given statement. 1325 static bool isCapturedBy(const VarDecl &Var, const Stmt *S) { 1326 if (const Expr *E = dyn_cast<Expr>(S)) 1327 return isCapturedBy(Var, E); 1328 for (const Stmt *SubStmt : S->children()) 1329 if (isCapturedBy(Var, SubStmt)) 1330 return true; 1331 return false; 1332 } 1333 1334 /// Determines whether the given __block variable is potentially 1335 /// captured by the given expression. 1336 static bool isCapturedBy(const VarDecl &Var, const Expr *E) { 1337 // Skip the most common kinds of expressions that make 1338 // hierarchy-walking expensive. 1339 E = E->IgnoreParenCasts(); 1340 1341 if (const BlockExpr *BE = dyn_cast<BlockExpr>(E)) { 1342 const BlockDecl *Block = BE->getBlockDecl(); 1343 for (const auto &I : Block->captures()) { 1344 if (I.getVariable() == &Var) 1345 return true; 1346 } 1347 1348 // No need to walk into the subexpressions. 1349 return false; 1350 } 1351 1352 if (const StmtExpr *SE = dyn_cast<StmtExpr>(E)) { 1353 const CompoundStmt *CS = SE->getSubStmt(); 1354 for (const auto *BI : CS->body()) 1355 if (const auto *BIE = dyn_cast<Expr>(BI)) { 1356 if (isCapturedBy(Var, BIE)) 1357 return true; 1358 } 1359 else if (const auto *DS = dyn_cast<DeclStmt>(BI)) { 1360 // special case declarations 1361 for (const auto *I : DS->decls()) { 1362 if (const auto *VD = dyn_cast<VarDecl>((I))) { 1363 const Expr *Init = VD->getInit(); 1364 if (Init && isCapturedBy(Var, Init)) 1365 return true; 1366 } 1367 } 1368 } 1369 else 1370 // FIXME. Make safe assumption assuming arbitrary statements cause capturing. 1371 // Later, provide code to poke into statements for capture analysis. 1372 return true; 1373 return false; 1374 } 1375 1376 for (const Stmt *SubStmt : E->children()) 1377 if (isCapturedBy(Var, SubStmt)) 1378 return true; 1379 1380 return false; 1381 } 1382 1383 /// Determine whether the given initializer is trivial in the sense 1384 /// that it requires no code to be generated. 1385 bool CodeGenFunction::isTrivialInitializer(const Expr *Init) { 1386 if (!Init) 1387 return true; 1388 1389 if (const CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init)) 1390 if (CXXConstructorDecl *Constructor = Construct->getConstructor()) 1391 if (Constructor->isTrivial() && 1392 Constructor->isDefaultConstructor() && 1393 !Construct->requiresZeroInitialization()) 1394 return true; 1395 1396 return false; 1397 } 1398 1399 void CodeGenFunction::EmitAutoVarInit(const AutoVarEmission &emission) { 1400 assert(emission.Variable && "emission was not valid!"); 1401 1402 // If this was emitted as a global constant, we're done. 1403 if (emission.wasEmittedAsGlobal()) return; 1404 1405 const VarDecl &D = *emission.Variable; 1406 auto DL = ApplyDebugLocation::CreateDefaultArtificial(*this, D.getLocation()); 1407 QualType type = D.getType(); 1408 1409 // If this local has an initializer, emit it now. 1410 const Expr *Init = D.getInit(); 1411 1412 // If we are at an unreachable point, we don't need to emit the initializer 1413 // unless it contains a label. 1414 if (!HaveInsertPoint()) { 1415 if (!Init || !ContainsLabel(Init)) return; 1416 EnsureInsertPoint(); 1417 } 1418 1419 // Initialize the structure of a __block variable. 1420 if (emission.IsByRef) 1421 emitByrefStructureInit(emission); 1422 1423 // Initialize the variable here if it doesn't have a initializer and it is a 1424 // C struct that is non-trivial to initialize or an array containing such a 1425 // struct. 1426 if (!Init && 1427 type.isNonTrivialToPrimitiveDefaultInitialize() == 1428 QualType::PDIK_Struct) { 1429 LValue Dst = MakeAddrLValue(emission.getAllocatedAddress(), type); 1430 if (emission.IsByRef) 1431 drillIntoBlockVariable(*this, Dst, &D); 1432 defaultInitNonTrivialCStructVar(Dst); 1433 return; 1434 } 1435 1436 if (isTrivialInitializer(Init)) 1437 return; 1438 1439 // Check whether this is a byref variable that's potentially 1440 // captured and moved by its own initializer. If so, we'll need to 1441 // emit the initializer first, then copy into the variable. 1442 bool capturedByInit = emission.IsByRef && isCapturedBy(D, Init); 1443 1444 Address Loc = 1445 capturedByInit ? emission.Addr : emission.getObjectAddress(*this); 1446 1447 llvm::Constant *constant = nullptr; 1448 if (emission.IsConstantAggregate || D.isConstexpr()) { 1449 assert(!capturedByInit && "constant init contains a capturing block?"); 1450 constant = ConstantEmitter(*this).tryEmitAbstractForInitializer(D); 1451 } 1452 1453 if (!constant) { 1454 LValue lv = MakeAddrLValue(Loc, type); 1455 lv.setNonGC(true); 1456 return EmitExprAsInit(Init, &D, lv, capturedByInit); 1457 } 1458 1459 if (!emission.IsConstantAggregate) { 1460 // For simple scalar/complex initialization, store the value directly. 1461 LValue lv = MakeAddrLValue(Loc, type); 1462 lv.setNonGC(true); 1463 return EmitStoreThroughLValue(RValue::get(constant), lv, true); 1464 } 1465 1466 // If this is a simple aggregate initialization, we can optimize it 1467 // in various ways. 1468 bool isVolatile = type.isVolatileQualified(); 1469 1470 llvm::Type *BP = CGM.Int8Ty->getPointerTo(Loc.getAddressSpace()); 1471 if (Loc.getType() != BP) 1472 Loc = Builder.CreateBitCast(Loc, BP); 1473 1474 emitStoresForConstant(CGM, D, Loc, isVolatile, Builder, constant); 1475 } 1476 1477 /// Emit an expression as an initializer for an object (variable, field, etc.) 1478 /// at the given location. The expression is not necessarily the normal 1479 /// initializer for the object, and the address is not necessarily 1480 /// its normal location. 1481 /// 1482 /// \param init the initializing expression 1483 /// \param D the object to act as if we're initializing 1484 /// \param loc the address to initialize; its type is a pointer 1485 /// to the LLVM mapping of the object's type 1486 /// \param alignment the alignment of the address 1487 /// \param capturedByInit true if \p D is a __block variable 1488 /// whose address is potentially changed by the initializer 1489 void CodeGenFunction::EmitExprAsInit(const Expr *init, const ValueDecl *D, 1490 LValue lvalue, bool capturedByInit) { 1491 QualType type = D->getType(); 1492 1493 if (type->isReferenceType()) { 1494 RValue rvalue = EmitReferenceBindingToExpr(init); 1495 if (capturedByInit) 1496 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 1497 EmitStoreThroughLValue(rvalue, lvalue, true); 1498 return; 1499 } 1500 switch (getEvaluationKind(type)) { 1501 case TEK_Scalar: 1502 EmitScalarInit(init, D, lvalue, capturedByInit); 1503 return; 1504 case TEK_Complex: { 1505 ComplexPairTy complex = EmitComplexExpr(init); 1506 if (capturedByInit) 1507 drillIntoBlockVariable(*this, lvalue, cast<VarDecl>(D)); 1508 EmitStoreOfComplex(complex, lvalue, /*init*/ true); 1509 return; 1510 } 1511 case TEK_Aggregate: 1512 if (type->isAtomicType()) { 1513 EmitAtomicInit(const_cast<Expr*>(init), lvalue); 1514 } else { 1515 AggValueSlot::Overlap_t Overlap = AggValueSlot::MayOverlap; 1516 if (isa<VarDecl>(D)) 1517 Overlap = AggValueSlot::DoesNotOverlap; 1518 else if (auto *FD = dyn_cast<FieldDecl>(D)) 1519 Overlap = overlapForFieldInit(FD); 1520 // TODO: how can we delay here if D is captured by its initializer? 1521 EmitAggExpr(init, AggValueSlot::forLValue(lvalue, 1522 AggValueSlot::IsDestructed, 1523 AggValueSlot::DoesNotNeedGCBarriers, 1524 AggValueSlot::IsNotAliased, 1525 Overlap)); 1526 } 1527 return; 1528 } 1529 llvm_unreachable("bad evaluation kind"); 1530 } 1531 1532 /// Enter a destroy cleanup for the given local variable. 1533 void CodeGenFunction::emitAutoVarTypeCleanup( 1534 const CodeGenFunction::AutoVarEmission &emission, 1535 QualType::DestructionKind dtorKind) { 1536 assert(dtorKind != QualType::DK_none); 1537 1538 // Note that for __block variables, we want to destroy the 1539 // original stack object, not the possibly forwarded object. 1540 Address addr = emission.getObjectAddress(*this); 1541 1542 const VarDecl *var = emission.Variable; 1543 QualType type = var->getType(); 1544 1545 CleanupKind cleanupKind = NormalAndEHCleanup; 1546 CodeGenFunction::Destroyer *destroyer = nullptr; 1547 1548 switch (dtorKind) { 1549 case QualType::DK_none: 1550 llvm_unreachable("no cleanup for trivially-destructible variable"); 1551 1552 case QualType::DK_cxx_destructor: 1553 // If there's an NRVO flag on the emission, we need a different 1554 // cleanup. 1555 if (emission.NRVOFlag) { 1556 assert(!type->isArrayType()); 1557 CXXDestructorDecl *dtor = type->getAsCXXRecordDecl()->getDestructor(); 1558 EHStack.pushCleanup<DestroyNRVOVariableCXX>(cleanupKind, addr, dtor, 1559 emission.NRVOFlag); 1560 return; 1561 } 1562 break; 1563 1564 case QualType::DK_objc_strong_lifetime: 1565 // Suppress cleanups for pseudo-strong variables. 1566 if (var->isARCPseudoStrong()) return; 1567 1568 // Otherwise, consider whether to use an EH cleanup or not. 1569 cleanupKind = getARCCleanupKind(); 1570 1571 // Use the imprecise destroyer by default. 1572 if (!var->hasAttr<ObjCPreciseLifetimeAttr>()) 1573 destroyer = CodeGenFunction::destroyARCStrongImprecise; 1574 break; 1575 1576 case QualType::DK_objc_weak_lifetime: 1577 break; 1578 1579 case QualType::DK_nontrivial_c_struct: 1580 destroyer = CodeGenFunction::destroyNonTrivialCStruct; 1581 if (emission.NRVOFlag) { 1582 assert(!type->isArrayType()); 1583 EHStack.pushCleanup<DestroyNRVOVariableC>(cleanupKind, addr, 1584 emission.NRVOFlag, type); 1585 return; 1586 } 1587 break; 1588 } 1589 1590 // If we haven't chosen a more specific destroyer, use the default. 1591 if (!destroyer) destroyer = getDestroyer(dtorKind); 1592 1593 // Use an EH cleanup in array destructors iff the destructor itself 1594 // is being pushed as an EH cleanup. 1595 bool useEHCleanup = (cleanupKind & EHCleanup); 1596 EHStack.pushCleanup<DestroyObject>(cleanupKind, addr, type, destroyer, 1597 useEHCleanup); 1598 } 1599 1600 void CodeGenFunction::EmitAutoVarCleanups(const AutoVarEmission &emission) { 1601 assert(emission.Variable && "emission was not valid!"); 1602 1603 // If this was emitted as a global constant, we're done. 1604 if (emission.wasEmittedAsGlobal()) return; 1605 1606 // If we don't have an insertion point, we're done. Sema prevents 1607 // us from jumping into any of these scopes anyway. 1608 if (!HaveInsertPoint()) return; 1609 1610 const VarDecl &D = *emission.Variable; 1611 1612 // Check the type for a cleanup. 1613 if (QualType::DestructionKind dtorKind = D.getType().isDestructedType()) 1614 emitAutoVarTypeCleanup(emission, dtorKind); 1615 1616 // In GC mode, honor objc_precise_lifetime. 1617 if (getLangOpts().getGC() != LangOptions::NonGC && 1618 D.hasAttr<ObjCPreciseLifetimeAttr>()) { 1619 EHStack.pushCleanup<ExtendGCLifetime>(NormalCleanup, &D); 1620 } 1621 1622 // Handle the cleanup attribute. 1623 if (const CleanupAttr *CA = D.getAttr<CleanupAttr>()) { 1624 const FunctionDecl *FD = CA->getFunctionDecl(); 1625 1626 llvm::Constant *F = CGM.GetAddrOfFunction(FD); 1627 assert(F && "Could not find function!"); 1628 1629 const CGFunctionInfo &Info = CGM.getTypes().arrangeFunctionDeclaration(FD); 1630 EHStack.pushCleanup<CallCleanupFunction>(NormalAndEHCleanup, F, &Info, &D); 1631 } 1632 1633 // If this is a block variable, call _Block_object_destroy 1634 // (on the unforwarded address). Don't enter this cleanup if we're in pure-GC 1635 // mode. 1636 if (emission.IsByRef && CGM.getLangOpts().getGC() != LangOptions::GCOnly) { 1637 BlockFieldFlags Flags = BLOCK_FIELD_IS_BYREF; 1638 if (emission.Variable->getType().isObjCGCWeak()) 1639 Flags |= BLOCK_FIELD_IS_WEAK; 1640 enterByrefCleanup(NormalAndEHCleanup, emission.Addr, Flags, 1641 /*LoadBlockVarAddr*/ false, 1642 cxxDestructorCanThrow(emission.Variable->getType())); 1643 } 1644 } 1645 1646 CodeGenFunction::Destroyer * 1647 CodeGenFunction::getDestroyer(QualType::DestructionKind kind) { 1648 switch (kind) { 1649 case QualType::DK_none: llvm_unreachable("no destroyer for trivial dtor"); 1650 case QualType::DK_cxx_destructor: 1651 return destroyCXXObject; 1652 case QualType::DK_objc_strong_lifetime: 1653 return destroyARCStrongPrecise; 1654 case QualType::DK_objc_weak_lifetime: 1655 return destroyARCWeak; 1656 case QualType::DK_nontrivial_c_struct: 1657 return destroyNonTrivialCStruct; 1658 } 1659 llvm_unreachable("Unknown DestructionKind"); 1660 } 1661 1662 /// pushEHDestroy - Push the standard destructor for the given type as 1663 /// an EH-only cleanup. 1664 void CodeGenFunction::pushEHDestroy(QualType::DestructionKind dtorKind, 1665 Address addr, QualType type) { 1666 assert(dtorKind && "cannot push destructor for trivial type"); 1667 assert(needsEHCleanup(dtorKind)); 1668 1669 pushDestroy(EHCleanup, addr, type, getDestroyer(dtorKind), true); 1670 } 1671 1672 /// pushDestroy - Push the standard destructor for the given type as 1673 /// at least a normal cleanup. 1674 void CodeGenFunction::pushDestroy(QualType::DestructionKind dtorKind, 1675 Address addr, QualType type) { 1676 assert(dtorKind && "cannot push destructor for trivial type"); 1677 1678 CleanupKind cleanupKind = getCleanupKind(dtorKind); 1679 pushDestroy(cleanupKind, addr, type, getDestroyer(dtorKind), 1680 cleanupKind & EHCleanup); 1681 } 1682 1683 void CodeGenFunction::pushDestroy(CleanupKind cleanupKind, Address addr, 1684 QualType type, Destroyer *destroyer, 1685 bool useEHCleanupForArray) { 1686 pushFullExprCleanup<DestroyObject>(cleanupKind, addr, type, 1687 destroyer, useEHCleanupForArray); 1688 } 1689 1690 void CodeGenFunction::pushStackRestore(CleanupKind Kind, Address SPMem) { 1691 EHStack.pushCleanup<CallStackRestore>(Kind, SPMem); 1692 } 1693 1694 void CodeGenFunction::pushLifetimeExtendedDestroy( 1695 CleanupKind cleanupKind, Address addr, QualType type, 1696 Destroyer *destroyer, bool useEHCleanupForArray) { 1697 // Push an EH-only cleanup for the object now. 1698 // FIXME: When popping normal cleanups, we need to keep this EH cleanup 1699 // around in case a temporary's destructor throws an exception. 1700 if (cleanupKind & EHCleanup) 1701 EHStack.pushCleanup<DestroyObject>( 1702 static_cast<CleanupKind>(cleanupKind & ~NormalCleanup), addr, type, 1703 destroyer, useEHCleanupForArray); 1704 1705 // Remember that we need to push a full cleanup for the object at the 1706 // end of the full-expression. 1707 pushCleanupAfterFullExpr<DestroyObject>( 1708 cleanupKind, addr, type, destroyer, useEHCleanupForArray); 1709 } 1710 1711 /// emitDestroy - Immediately perform the destruction of the given 1712 /// object. 1713 /// 1714 /// \param addr - the address of the object; a type* 1715 /// \param type - the type of the object; if an array type, all 1716 /// objects are destroyed in reverse order 1717 /// \param destroyer - the function to call to destroy individual 1718 /// elements 1719 /// \param useEHCleanupForArray - whether an EH cleanup should be 1720 /// used when destroying array elements, in case one of the 1721 /// destructions throws an exception 1722 void CodeGenFunction::emitDestroy(Address addr, QualType type, 1723 Destroyer *destroyer, 1724 bool useEHCleanupForArray) { 1725 const ArrayType *arrayType = getContext().getAsArrayType(type); 1726 if (!arrayType) 1727 return destroyer(*this, addr, type); 1728 1729 llvm::Value *length = emitArrayLength(arrayType, type, addr); 1730 1731 CharUnits elementAlign = 1732 addr.getAlignment() 1733 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type)); 1734 1735 // Normally we have to check whether the array is zero-length. 1736 bool checkZeroLength = true; 1737 1738 // But if the array length is constant, we can suppress that. 1739 if (llvm::ConstantInt *constLength = dyn_cast<llvm::ConstantInt>(length)) { 1740 // ...and if it's constant zero, we can just skip the entire thing. 1741 if (constLength->isZero()) return; 1742 checkZeroLength = false; 1743 } 1744 1745 llvm::Value *begin = addr.getPointer(); 1746 llvm::Value *end = Builder.CreateInBoundsGEP(begin, length); 1747 emitArrayDestroy(begin, end, type, elementAlign, destroyer, 1748 checkZeroLength, useEHCleanupForArray); 1749 } 1750 1751 /// emitArrayDestroy - Destroys all the elements of the given array, 1752 /// beginning from last to first. The array cannot be zero-length. 1753 /// 1754 /// \param begin - a type* denoting the first element of the array 1755 /// \param end - a type* denoting one past the end of the array 1756 /// \param elementType - the element type of the array 1757 /// \param destroyer - the function to call to destroy elements 1758 /// \param useEHCleanup - whether to push an EH cleanup to destroy 1759 /// the remaining elements in case the destruction of a single 1760 /// element throws 1761 void CodeGenFunction::emitArrayDestroy(llvm::Value *begin, 1762 llvm::Value *end, 1763 QualType elementType, 1764 CharUnits elementAlign, 1765 Destroyer *destroyer, 1766 bool checkZeroLength, 1767 bool useEHCleanup) { 1768 assert(!elementType->isArrayType()); 1769 1770 // The basic structure here is a do-while loop, because we don't 1771 // need to check for the zero-element case. 1772 llvm::BasicBlock *bodyBB = createBasicBlock("arraydestroy.body"); 1773 llvm::BasicBlock *doneBB = createBasicBlock("arraydestroy.done"); 1774 1775 if (checkZeroLength) { 1776 llvm::Value *isEmpty = Builder.CreateICmpEQ(begin, end, 1777 "arraydestroy.isempty"); 1778 Builder.CreateCondBr(isEmpty, doneBB, bodyBB); 1779 } 1780 1781 // Enter the loop body, making that address the current address. 1782 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1783 EmitBlock(bodyBB); 1784 llvm::PHINode *elementPast = 1785 Builder.CreatePHI(begin->getType(), 2, "arraydestroy.elementPast"); 1786 elementPast->addIncoming(end, entryBB); 1787 1788 // Shift the address back by one element. 1789 llvm::Value *negativeOne = llvm::ConstantInt::get(SizeTy, -1, true); 1790 llvm::Value *element = Builder.CreateInBoundsGEP(elementPast, negativeOne, 1791 "arraydestroy.element"); 1792 1793 if (useEHCleanup) 1794 pushRegularPartialArrayCleanup(begin, element, elementType, elementAlign, 1795 destroyer); 1796 1797 // Perform the actual destruction there. 1798 destroyer(*this, Address(element, elementAlign), elementType); 1799 1800 if (useEHCleanup) 1801 PopCleanupBlock(); 1802 1803 // Check whether we've reached the end. 1804 llvm::Value *done = Builder.CreateICmpEQ(element, begin, "arraydestroy.done"); 1805 Builder.CreateCondBr(done, doneBB, bodyBB); 1806 elementPast->addIncoming(element, Builder.GetInsertBlock()); 1807 1808 // Done. 1809 EmitBlock(doneBB); 1810 } 1811 1812 /// Perform partial array destruction as if in an EH cleanup. Unlike 1813 /// emitArrayDestroy, the element type here may still be an array type. 1814 static void emitPartialArrayDestroy(CodeGenFunction &CGF, 1815 llvm::Value *begin, llvm::Value *end, 1816 QualType type, CharUnits elementAlign, 1817 CodeGenFunction::Destroyer *destroyer) { 1818 // If the element type is itself an array, drill down. 1819 unsigned arrayDepth = 0; 1820 while (const ArrayType *arrayType = CGF.getContext().getAsArrayType(type)) { 1821 // VLAs don't require a GEP index to walk into. 1822 if (!isa<VariableArrayType>(arrayType)) 1823 arrayDepth++; 1824 type = arrayType->getElementType(); 1825 } 1826 1827 if (arrayDepth) { 1828 llvm::Value *zero = llvm::ConstantInt::get(CGF.SizeTy, 0); 1829 1830 SmallVector<llvm::Value*,4> gepIndices(arrayDepth+1, zero); 1831 begin = CGF.Builder.CreateInBoundsGEP(begin, gepIndices, "pad.arraybegin"); 1832 end = CGF.Builder.CreateInBoundsGEP(end, gepIndices, "pad.arrayend"); 1833 } 1834 1835 // Destroy the array. We don't ever need an EH cleanup because we 1836 // assume that we're in an EH cleanup ourselves, so a throwing 1837 // destructor causes an immediate terminate. 1838 CGF.emitArrayDestroy(begin, end, type, elementAlign, destroyer, 1839 /*checkZeroLength*/ true, /*useEHCleanup*/ false); 1840 } 1841 1842 namespace { 1843 /// RegularPartialArrayDestroy - a cleanup which performs a partial 1844 /// array destroy where the end pointer is regularly determined and 1845 /// does not need to be loaded from a local. 1846 class RegularPartialArrayDestroy final : public EHScopeStack::Cleanup { 1847 llvm::Value *ArrayBegin; 1848 llvm::Value *ArrayEnd; 1849 QualType ElementType; 1850 CodeGenFunction::Destroyer *Destroyer; 1851 CharUnits ElementAlign; 1852 public: 1853 RegularPartialArrayDestroy(llvm::Value *arrayBegin, llvm::Value *arrayEnd, 1854 QualType elementType, CharUnits elementAlign, 1855 CodeGenFunction::Destroyer *destroyer) 1856 : ArrayBegin(arrayBegin), ArrayEnd(arrayEnd), 1857 ElementType(elementType), Destroyer(destroyer), 1858 ElementAlign(elementAlign) {} 1859 1860 void Emit(CodeGenFunction &CGF, Flags flags) override { 1861 emitPartialArrayDestroy(CGF, ArrayBegin, ArrayEnd, 1862 ElementType, ElementAlign, Destroyer); 1863 } 1864 }; 1865 1866 /// IrregularPartialArrayDestroy - a cleanup which performs a 1867 /// partial array destroy where the end pointer is irregularly 1868 /// determined and must be loaded from a local. 1869 class IrregularPartialArrayDestroy final : public EHScopeStack::Cleanup { 1870 llvm::Value *ArrayBegin; 1871 Address ArrayEndPointer; 1872 QualType ElementType; 1873 CodeGenFunction::Destroyer *Destroyer; 1874 CharUnits ElementAlign; 1875 public: 1876 IrregularPartialArrayDestroy(llvm::Value *arrayBegin, 1877 Address arrayEndPointer, 1878 QualType elementType, 1879 CharUnits elementAlign, 1880 CodeGenFunction::Destroyer *destroyer) 1881 : ArrayBegin(arrayBegin), ArrayEndPointer(arrayEndPointer), 1882 ElementType(elementType), Destroyer(destroyer), 1883 ElementAlign(elementAlign) {} 1884 1885 void Emit(CodeGenFunction &CGF, Flags flags) override { 1886 llvm::Value *arrayEnd = CGF.Builder.CreateLoad(ArrayEndPointer); 1887 emitPartialArrayDestroy(CGF, ArrayBegin, arrayEnd, 1888 ElementType, ElementAlign, Destroyer); 1889 } 1890 }; 1891 } // end anonymous namespace 1892 1893 /// pushIrregularPartialArrayCleanup - Push an EH cleanup to destroy 1894 /// already-constructed elements of the given array. The cleanup 1895 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 1896 /// 1897 /// \param elementType - the immediate element type of the array; 1898 /// possibly still an array type 1899 void CodeGenFunction::pushIrregularPartialArrayCleanup(llvm::Value *arrayBegin, 1900 Address arrayEndPointer, 1901 QualType elementType, 1902 CharUnits elementAlign, 1903 Destroyer *destroyer) { 1904 pushFullExprCleanup<IrregularPartialArrayDestroy>(EHCleanup, 1905 arrayBegin, arrayEndPointer, 1906 elementType, elementAlign, 1907 destroyer); 1908 } 1909 1910 /// pushRegularPartialArrayCleanup - Push an EH cleanup to destroy 1911 /// already-constructed elements of the given array. The cleanup 1912 /// may be popped with DeactivateCleanupBlock or PopCleanupBlock. 1913 /// 1914 /// \param elementType - the immediate element type of the array; 1915 /// possibly still an array type 1916 void CodeGenFunction::pushRegularPartialArrayCleanup(llvm::Value *arrayBegin, 1917 llvm::Value *arrayEnd, 1918 QualType elementType, 1919 CharUnits elementAlign, 1920 Destroyer *destroyer) { 1921 pushFullExprCleanup<RegularPartialArrayDestroy>(EHCleanup, 1922 arrayBegin, arrayEnd, 1923 elementType, elementAlign, 1924 destroyer); 1925 } 1926 1927 /// Lazily declare the @llvm.lifetime.start intrinsic. 1928 llvm::Constant *CodeGenModule::getLLVMLifetimeStartFn() { 1929 if (LifetimeStartFn) 1930 return LifetimeStartFn; 1931 LifetimeStartFn = llvm::Intrinsic::getDeclaration(&getModule(), 1932 llvm::Intrinsic::lifetime_start, AllocaInt8PtrTy); 1933 return LifetimeStartFn; 1934 } 1935 1936 /// Lazily declare the @llvm.lifetime.end intrinsic. 1937 llvm::Constant *CodeGenModule::getLLVMLifetimeEndFn() { 1938 if (LifetimeEndFn) 1939 return LifetimeEndFn; 1940 LifetimeEndFn = llvm::Intrinsic::getDeclaration(&getModule(), 1941 llvm::Intrinsic::lifetime_end, AllocaInt8PtrTy); 1942 return LifetimeEndFn; 1943 } 1944 1945 namespace { 1946 /// A cleanup to perform a release of an object at the end of a 1947 /// function. This is used to balance out the incoming +1 of a 1948 /// ns_consumed argument when we can't reasonably do that just by 1949 /// not doing the initial retain for a __block argument. 1950 struct ConsumeARCParameter final : EHScopeStack::Cleanup { 1951 ConsumeARCParameter(llvm::Value *param, 1952 ARCPreciseLifetime_t precise) 1953 : Param(param), Precise(precise) {} 1954 1955 llvm::Value *Param; 1956 ARCPreciseLifetime_t Precise; 1957 1958 void Emit(CodeGenFunction &CGF, Flags flags) override { 1959 CGF.EmitARCRelease(Param, Precise); 1960 } 1961 }; 1962 } // end anonymous namespace 1963 1964 /// Emit an alloca (or GlobalValue depending on target) 1965 /// for the specified parameter and set up LocalDeclMap. 1966 void CodeGenFunction::EmitParmDecl(const VarDecl &D, ParamValue Arg, 1967 unsigned ArgNo) { 1968 // FIXME: Why isn't ImplicitParamDecl a ParmVarDecl? 1969 assert((isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D)) && 1970 "Invalid argument to EmitParmDecl"); 1971 1972 Arg.getAnyValue()->setName(D.getName()); 1973 1974 QualType Ty = D.getType(); 1975 1976 // Use better IR generation for certain implicit parameters. 1977 if (auto IPD = dyn_cast<ImplicitParamDecl>(&D)) { 1978 // The only implicit argument a block has is its literal. 1979 // This may be passed as an inalloca'ed value on Windows x86. 1980 if (BlockInfo) { 1981 llvm::Value *V = Arg.isIndirect() 1982 ? Builder.CreateLoad(Arg.getIndirectAddress()) 1983 : Arg.getDirectValue(); 1984 setBlockContextParameter(IPD, ArgNo, V); 1985 return; 1986 } 1987 } 1988 1989 Address DeclPtr = Address::invalid(); 1990 bool DoStore = false; 1991 bool IsScalar = hasScalarEvaluationKind(Ty); 1992 // If we already have a pointer to the argument, reuse the input pointer. 1993 if (Arg.isIndirect()) { 1994 DeclPtr = Arg.getIndirectAddress(); 1995 // If we have a prettier pointer type at this point, bitcast to that. 1996 unsigned AS = DeclPtr.getType()->getAddressSpace(); 1997 llvm::Type *IRTy = ConvertTypeForMem(Ty)->getPointerTo(AS); 1998 if (DeclPtr.getType() != IRTy) 1999 DeclPtr = Builder.CreateBitCast(DeclPtr, IRTy, D.getName()); 2000 // Indirect argument is in alloca address space, which may be different 2001 // from the default address space. 2002 auto AllocaAS = CGM.getASTAllocaAddressSpace(); 2003 auto *V = DeclPtr.getPointer(); 2004 auto SrcLangAS = getLangOpts().OpenCL ? LangAS::opencl_private : AllocaAS; 2005 auto DestLangAS = 2006 getLangOpts().OpenCL ? LangAS::opencl_private : LangAS::Default; 2007 if (SrcLangAS != DestLangAS) { 2008 assert(getContext().getTargetAddressSpace(SrcLangAS) == 2009 CGM.getDataLayout().getAllocaAddrSpace()); 2010 auto DestAS = getContext().getTargetAddressSpace(DestLangAS); 2011 auto *T = V->getType()->getPointerElementType()->getPointerTo(DestAS); 2012 DeclPtr = Address(getTargetHooks().performAddrSpaceCast( 2013 *this, V, SrcLangAS, DestLangAS, T, true), 2014 DeclPtr.getAlignment()); 2015 } 2016 2017 // Push a destructor cleanup for this parameter if the ABI requires it. 2018 // Don't push a cleanup in a thunk for a method that will also emit a 2019 // cleanup. 2020 if (hasAggregateEvaluationKind(Ty) && !CurFuncIsThunk && 2021 Ty->getAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) { 2022 if (QualType::DestructionKind DtorKind = Ty.isDestructedType()) { 2023 assert((DtorKind == QualType::DK_cxx_destructor || 2024 DtorKind == QualType::DK_nontrivial_c_struct) && 2025 "unexpected destructor type"); 2026 pushDestroy(DtorKind, DeclPtr, Ty); 2027 CalleeDestructedParamCleanups[cast<ParmVarDecl>(&D)] = 2028 EHStack.stable_begin(); 2029 } 2030 } 2031 } else { 2032 // Check if the parameter address is controlled by OpenMP runtime. 2033 Address OpenMPLocalAddr = 2034 getLangOpts().OpenMP 2035 ? CGM.getOpenMPRuntime().getAddressOfLocalVariable(*this, &D) 2036 : Address::invalid(); 2037 if (getLangOpts().OpenMP && OpenMPLocalAddr.isValid()) { 2038 DeclPtr = OpenMPLocalAddr; 2039 } else { 2040 // Otherwise, create a temporary to hold the value. 2041 DeclPtr = CreateMemTemp(Ty, getContext().getDeclAlign(&D), 2042 D.getName() + ".addr"); 2043 } 2044 DoStore = true; 2045 } 2046 2047 llvm::Value *ArgVal = (DoStore ? Arg.getDirectValue() : nullptr); 2048 2049 LValue lv = MakeAddrLValue(DeclPtr, Ty); 2050 if (IsScalar) { 2051 Qualifiers qs = Ty.getQualifiers(); 2052 if (Qualifiers::ObjCLifetime lt = qs.getObjCLifetime()) { 2053 // We honor __attribute__((ns_consumed)) for types with lifetime. 2054 // For __strong, it's handled by just skipping the initial retain; 2055 // otherwise we have to balance out the initial +1 with an extra 2056 // cleanup to do the release at the end of the function. 2057 bool isConsumed = D.hasAttr<NSConsumedAttr>(); 2058 2059 // 'self' is always formally __strong, but if this is not an 2060 // init method then we don't want to retain it. 2061 if (D.isARCPseudoStrong()) { 2062 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CurCodeDecl); 2063 assert(&D == method->getSelfDecl()); 2064 assert(lt == Qualifiers::OCL_Strong); 2065 assert(qs.hasConst()); 2066 assert(method->getMethodFamily() != OMF_init); 2067 (void) method; 2068 lt = Qualifiers::OCL_ExplicitNone; 2069 } 2070 2071 // Load objects passed indirectly. 2072 if (Arg.isIndirect() && !ArgVal) 2073 ArgVal = Builder.CreateLoad(DeclPtr); 2074 2075 if (lt == Qualifiers::OCL_Strong) { 2076 if (!isConsumed) { 2077 if (CGM.getCodeGenOpts().OptimizationLevel == 0) { 2078 // use objc_storeStrong(&dest, value) for retaining the 2079 // object. But first, store a null into 'dest' because 2080 // objc_storeStrong attempts to release its old value. 2081 llvm::Value *Null = CGM.EmitNullConstant(D.getType()); 2082 EmitStoreOfScalar(Null, lv, /* isInitialization */ true); 2083 EmitARCStoreStrongCall(lv.getAddress(), ArgVal, true); 2084 DoStore = false; 2085 } 2086 else 2087 // Don't use objc_retainBlock for block pointers, because we 2088 // don't want to Block_copy something just because we got it 2089 // as a parameter. 2090 ArgVal = EmitARCRetainNonBlock(ArgVal); 2091 } 2092 } else { 2093 // Push the cleanup for a consumed parameter. 2094 if (isConsumed) { 2095 ARCPreciseLifetime_t precise = (D.hasAttr<ObjCPreciseLifetimeAttr>() 2096 ? ARCPreciseLifetime : ARCImpreciseLifetime); 2097 EHStack.pushCleanup<ConsumeARCParameter>(getARCCleanupKind(), ArgVal, 2098 precise); 2099 } 2100 2101 if (lt == Qualifiers::OCL_Weak) { 2102 EmitARCInitWeak(DeclPtr, ArgVal); 2103 DoStore = false; // The weak init is a store, no need to do two. 2104 } 2105 } 2106 2107 // Enter the cleanup scope. 2108 EmitAutoVarWithLifetime(*this, D, DeclPtr, lt); 2109 } 2110 } 2111 2112 // Store the initial value into the alloca. 2113 if (DoStore) 2114 EmitStoreOfScalar(ArgVal, lv, /* isInitialization */ true); 2115 2116 setAddrOfLocalVar(&D, DeclPtr); 2117 2118 // Emit debug info for param declaration. 2119 if (CGDebugInfo *DI = getDebugInfo()) { 2120 if (CGM.getCodeGenOpts().getDebugInfo() >= 2121 codegenoptions::LimitedDebugInfo) { 2122 DI->EmitDeclareOfArgVariable(&D, DeclPtr.getPointer(), ArgNo, Builder); 2123 } 2124 } 2125 2126 if (D.hasAttr<AnnotateAttr>()) 2127 EmitVarAnnotations(&D, DeclPtr.getPointer()); 2128 2129 // We can only check return value nullability if all arguments to the 2130 // function satisfy their nullability preconditions. This makes it necessary 2131 // to emit null checks for args in the function body itself. 2132 if (requiresReturnValueNullabilityCheck()) { 2133 auto Nullability = Ty->getNullability(getContext()); 2134 if (Nullability && *Nullability == NullabilityKind::NonNull) { 2135 SanitizerScope SanScope(this); 2136 RetValNullabilityPrecondition = 2137 Builder.CreateAnd(RetValNullabilityPrecondition, 2138 Builder.CreateIsNotNull(Arg.getAnyValue())); 2139 } 2140 } 2141 } 2142 2143 void CodeGenModule::EmitOMPDeclareReduction(const OMPDeclareReductionDecl *D, 2144 CodeGenFunction *CGF) { 2145 if (!LangOpts.OpenMP || (!LangOpts.EmitAllDecls && !D->isUsed())) 2146 return; 2147 getOpenMPRuntime().emitUserDefinedReduction(CGF, D); 2148 } 2149