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