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