1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// 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 coordinates the per-module state used while generating code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CodeGenModule.h" 14 #include "CGBlocks.h" 15 #include "CGCUDARuntime.h" 16 #include "CGCXXABI.h" 17 #include "CGCall.h" 18 #include "CGDebugInfo.h" 19 #include "CGObjCRuntime.h" 20 #include "CGOpenCLRuntime.h" 21 #include "CGOpenMPRuntime.h" 22 #include "CGOpenMPRuntimeAMDGCN.h" 23 #include "CGOpenMPRuntimeNVPTX.h" 24 #include "CodeGenFunction.h" 25 #include "CodeGenPGO.h" 26 #include "ConstantEmitter.h" 27 #include "CoverageMappingGen.h" 28 #include "TargetInfo.h" 29 #include "clang/AST/ASTContext.h" 30 #include "clang/AST/CharUnits.h" 31 #include "clang/AST/DeclCXX.h" 32 #include "clang/AST/DeclObjC.h" 33 #include "clang/AST/DeclTemplate.h" 34 #include "clang/AST/Mangle.h" 35 #include "clang/AST/RecordLayout.h" 36 #include "clang/AST/RecursiveASTVisitor.h" 37 #include "clang/AST/StmtVisitor.h" 38 #include "clang/Basic/Builtins.h" 39 #include "clang/Basic/CharInfo.h" 40 #include "clang/Basic/CodeGenOptions.h" 41 #include "clang/Basic/Diagnostic.h" 42 #include "clang/Basic/FileManager.h" 43 #include "clang/Basic/Module.h" 44 #include "clang/Basic/SourceManager.h" 45 #include "clang/Basic/TargetInfo.h" 46 #include "clang/Basic/Version.h" 47 #include "clang/CodeGen/ConstantInitBuilder.h" 48 #include "clang/Frontend/FrontendDiagnostic.h" 49 #include "llvm/ADT/StringSwitch.h" 50 #include "llvm/ADT/Triple.h" 51 #include "llvm/Analysis/TargetLibraryInfo.h" 52 #include "llvm/Frontend/OpenMP/OMPIRBuilder.h" 53 #include "llvm/IR/CallingConv.h" 54 #include "llvm/IR/DataLayout.h" 55 #include "llvm/IR/Intrinsics.h" 56 #include "llvm/IR/LLVMContext.h" 57 #include "llvm/IR/Module.h" 58 #include "llvm/IR/ProfileSummary.h" 59 #include "llvm/ProfileData/InstrProfReader.h" 60 #include "llvm/Support/CodeGen.h" 61 #include "llvm/Support/CommandLine.h" 62 #include "llvm/Support/ConvertUTF.h" 63 #include "llvm/Support/ErrorHandling.h" 64 #include "llvm/Support/MD5.h" 65 #include "llvm/Support/TimeProfiler.h" 66 67 using namespace clang; 68 using namespace CodeGen; 69 70 static llvm::cl::opt<bool> LimitedCoverage( 71 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden, 72 llvm::cl::desc("Emit limited coverage mapping information (experimental)"), 73 llvm::cl::init(false)); 74 75 static const char AnnotationSection[] = "llvm.metadata"; 76 77 static CGCXXABI *createCXXABI(CodeGenModule &CGM) { 78 switch (CGM.getTarget().getCXXABI().getKind()) { 79 case TargetCXXABI::AppleARM64: 80 case TargetCXXABI::Fuchsia: 81 case TargetCXXABI::GenericAArch64: 82 case TargetCXXABI::GenericARM: 83 case TargetCXXABI::iOS: 84 case TargetCXXABI::WatchOS: 85 case TargetCXXABI::GenericMIPS: 86 case TargetCXXABI::GenericItanium: 87 case TargetCXXABI::WebAssembly: 88 case TargetCXXABI::XL: 89 return CreateItaniumCXXABI(CGM); 90 case TargetCXXABI::Microsoft: 91 return CreateMicrosoftCXXABI(CGM); 92 } 93 94 llvm_unreachable("invalid C++ ABI kind"); 95 } 96 97 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO, 98 const PreprocessorOptions &PPO, 99 const CodeGenOptions &CGO, llvm::Module &M, 100 DiagnosticsEngine &diags, 101 CoverageSourceInfo *CoverageInfo) 102 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO), 103 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags), 104 Target(C.getTargetInfo()), ABI(createCXXABI(*this)), 105 VMContext(M.getContext()), Types(*this), VTables(*this), 106 SanitizerMD(new SanitizerMetadata(*this)) { 107 108 // Initialize the type cache. 109 llvm::LLVMContext &LLVMContext = M.getContext(); 110 VoidTy = llvm::Type::getVoidTy(LLVMContext); 111 Int8Ty = llvm::Type::getInt8Ty(LLVMContext); 112 Int16Ty = llvm::Type::getInt16Ty(LLVMContext); 113 Int32Ty = llvm::Type::getInt32Ty(LLVMContext); 114 Int64Ty = llvm::Type::getInt64Ty(LLVMContext); 115 HalfTy = llvm::Type::getHalfTy(LLVMContext); 116 BFloatTy = llvm::Type::getBFloatTy(LLVMContext); 117 FloatTy = llvm::Type::getFloatTy(LLVMContext); 118 DoubleTy = llvm::Type::getDoubleTy(LLVMContext); 119 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0); 120 PointerAlignInBytes = 121 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity(); 122 SizeSizeInBytes = 123 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity(); 124 IntAlignInBytes = 125 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity(); 126 CharTy = 127 llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getCharWidth()); 128 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth()); 129 IntPtrTy = llvm::IntegerType::get(LLVMContext, 130 C.getTargetInfo().getMaxPointerWidth()); 131 Int8PtrTy = Int8Ty->getPointerTo(0); 132 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0); 133 AllocaInt8PtrTy = Int8Ty->getPointerTo( 134 M.getDataLayout().getAllocaAddrSpace()); 135 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace(); 136 137 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC(); 138 139 if (LangOpts.ObjC) 140 createObjCRuntime(); 141 if (LangOpts.OpenCL) 142 createOpenCLRuntime(); 143 if (LangOpts.OpenMP) 144 createOpenMPRuntime(); 145 if (LangOpts.CUDA) 146 createCUDARuntime(); 147 148 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0. 149 if (LangOpts.Sanitize.has(SanitizerKind::Thread) || 150 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0)) 151 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(), 152 getCXXABI().getMangleContext())); 153 154 // If debug info or coverage generation is enabled, create the CGDebugInfo 155 // object. 156 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo || 157 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes) 158 DebugInfo.reset(new CGDebugInfo(*this)); 159 160 Block.GlobalUniqueCount = 0; 161 162 if (C.getLangOpts().ObjC) 163 ObjCData.reset(new ObjCEntrypoints()); 164 165 if (CodeGenOpts.hasProfileClangUse()) { 166 auto ReaderOrErr = llvm::IndexedInstrProfReader::create( 167 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile); 168 if (auto E = ReaderOrErr.takeError()) { 169 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 170 "Could not read profile %0: %1"); 171 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) { 172 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath 173 << EI.message(); 174 }); 175 } else 176 PGOReader = std::move(ReaderOrErr.get()); 177 } 178 179 // If coverage mapping generation is enabled, create the 180 // CoverageMappingModuleGen object. 181 if (CodeGenOpts.CoverageMapping) 182 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo)); 183 } 184 185 CodeGenModule::~CodeGenModule() {} 186 187 void CodeGenModule::createObjCRuntime() { 188 // This is just isGNUFamily(), but we want to force implementors of 189 // new ABIs to decide how best to do this. 190 switch (LangOpts.ObjCRuntime.getKind()) { 191 case ObjCRuntime::GNUstep: 192 case ObjCRuntime::GCC: 193 case ObjCRuntime::ObjFW: 194 ObjCRuntime.reset(CreateGNUObjCRuntime(*this)); 195 return; 196 197 case ObjCRuntime::FragileMacOSX: 198 case ObjCRuntime::MacOSX: 199 case ObjCRuntime::iOS: 200 case ObjCRuntime::WatchOS: 201 ObjCRuntime.reset(CreateMacObjCRuntime(*this)); 202 return; 203 } 204 llvm_unreachable("bad runtime kind"); 205 } 206 207 void CodeGenModule::createOpenCLRuntime() { 208 OpenCLRuntime.reset(new CGOpenCLRuntime(*this)); 209 } 210 211 void CodeGenModule::createOpenMPRuntime() { 212 // Select a specialized code generation class based on the target, if any. 213 // If it does not exist use the default implementation. 214 switch (getTriple().getArch()) { 215 case llvm::Triple::nvptx: 216 case llvm::Triple::nvptx64: 217 assert(getLangOpts().OpenMPIsDevice && 218 "OpenMP NVPTX is only prepared to deal with device code."); 219 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this)); 220 break; 221 case llvm::Triple::amdgcn: 222 assert(getLangOpts().OpenMPIsDevice && 223 "OpenMP AMDGCN is only prepared to deal with device code."); 224 OpenMPRuntime.reset(new CGOpenMPRuntimeAMDGCN(*this)); 225 break; 226 default: 227 if (LangOpts.OpenMPSimd) 228 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this)); 229 else 230 OpenMPRuntime.reset(new CGOpenMPRuntime(*this)); 231 break; 232 } 233 } 234 235 void CodeGenModule::createCUDARuntime() { 236 CUDARuntime.reset(CreateNVCUDARuntime(*this)); 237 } 238 239 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) { 240 Replacements[Name] = C; 241 } 242 243 void CodeGenModule::applyReplacements() { 244 for (auto &I : Replacements) { 245 StringRef MangledName = I.first(); 246 llvm::Constant *Replacement = I.second; 247 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 248 if (!Entry) 249 continue; 250 auto *OldF = cast<llvm::Function>(Entry); 251 auto *NewF = dyn_cast<llvm::Function>(Replacement); 252 if (!NewF) { 253 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) { 254 NewF = dyn_cast<llvm::Function>(Alias->getAliasee()); 255 } else { 256 auto *CE = cast<llvm::ConstantExpr>(Replacement); 257 assert(CE->getOpcode() == llvm::Instruction::BitCast || 258 CE->getOpcode() == llvm::Instruction::GetElementPtr); 259 NewF = dyn_cast<llvm::Function>(CE->getOperand(0)); 260 } 261 } 262 263 // Replace old with new, but keep the old order. 264 OldF->replaceAllUsesWith(Replacement); 265 if (NewF) { 266 NewF->removeFromParent(); 267 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(), 268 NewF); 269 } 270 OldF->eraseFromParent(); 271 } 272 } 273 274 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) { 275 GlobalValReplacements.push_back(std::make_pair(GV, C)); 276 } 277 278 void CodeGenModule::applyGlobalValReplacements() { 279 for (auto &I : GlobalValReplacements) { 280 llvm::GlobalValue *GV = I.first; 281 llvm::Constant *C = I.second; 282 283 GV->replaceAllUsesWith(C); 284 GV->eraseFromParent(); 285 } 286 } 287 288 // This is only used in aliases that we created and we know they have a 289 // linear structure. 290 static const llvm::GlobalObject *getAliasedGlobal( 291 const llvm::GlobalIndirectSymbol &GIS) { 292 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited; 293 const llvm::Constant *C = &GIS; 294 for (;;) { 295 C = C->stripPointerCasts(); 296 if (auto *GO = dyn_cast<llvm::GlobalObject>(C)) 297 return GO; 298 // stripPointerCasts will not walk over weak aliases. 299 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C); 300 if (!GIS2) 301 return nullptr; 302 if (!Visited.insert(GIS2).second) 303 return nullptr; 304 C = GIS2->getIndirectSymbol(); 305 } 306 } 307 308 void CodeGenModule::checkAliases() { 309 // Check if the constructed aliases are well formed. It is really unfortunate 310 // that we have to do this in CodeGen, but we only construct mangled names 311 // and aliases during codegen. 312 bool Error = false; 313 DiagnosticsEngine &Diags = getDiags(); 314 for (const GlobalDecl &GD : Aliases) { 315 const auto *D = cast<ValueDecl>(GD.getDecl()); 316 SourceLocation Location; 317 bool IsIFunc = D->hasAttr<IFuncAttr>(); 318 if (const Attr *A = D->getDefiningAttr()) 319 Location = A->getLocation(); 320 else 321 llvm_unreachable("Not an alias or ifunc?"); 322 StringRef MangledName = getMangledName(GD); 323 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 324 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 325 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias); 326 if (!GV) { 327 Error = true; 328 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc; 329 } else if (GV->isDeclaration()) { 330 Error = true; 331 Diags.Report(Location, diag::err_alias_to_undefined) 332 << IsIFunc << IsIFunc; 333 } else if (IsIFunc) { 334 // Check resolver function type. 335 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>( 336 GV->getType()->getPointerElementType()); 337 assert(FTy); 338 if (!FTy->getReturnType()->isPointerTy()) 339 Diags.Report(Location, diag::err_ifunc_resolver_return); 340 } 341 342 llvm::Constant *Aliasee = Alias->getIndirectSymbol(); 343 llvm::GlobalValue *AliaseeGV; 344 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee)) 345 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0)); 346 else 347 AliaseeGV = cast<llvm::GlobalValue>(Aliasee); 348 349 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 350 StringRef AliasSection = SA->getName(); 351 if (AliasSection != AliaseeGV->getSection()) 352 Diags.Report(SA->getLocation(), diag::warn_alias_with_section) 353 << AliasSection << IsIFunc << IsIFunc; 354 } 355 356 // We have to handle alias to weak aliases in here. LLVM itself disallows 357 // this since the object semantics would not match the IL one. For 358 // compatibility with gcc we implement it by just pointing the alias 359 // to its aliasee's aliasee. We also warn, since the user is probably 360 // expecting the link to be weak. 361 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) { 362 if (GA->isInterposable()) { 363 Diags.Report(Location, diag::warn_alias_to_weak_alias) 364 << GV->getName() << GA->getName() << IsIFunc; 365 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 366 GA->getIndirectSymbol(), Alias->getType()); 367 Alias->setIndirectSymbol(Aliasee); 368 } 369 } 370 } 371 if (!Error) 372 return; 373 374 for (const GlobalDecl &GD : Aliases) { 375 StringRef MangledName = getMangledName(GD); 376 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 377 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry); 378 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType())); 379 Alias->eraseFromParent(); 380 } 381 } 382 383 void CodeGenModule::clear() { 384 DeferredDeclsToEmit.clear(); 385 if (OpenMPRuntime) 386 OpenMPRuntime->clear(); 387 } 388 389 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags, 390 StringRef MainFile) { 391 if (!hasDiagnostics()) 392 return; 393 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) { 394 if (MainFile.empty()) 395 MainFile = "<stdin>"; 396 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile; 397 } else { 398 if (Mismatched > 0) 399 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched; 400 401 if (Missing > 0) 402 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing; 403 } 404 } 405 406 static void setVisibilityFromDLLStorageClass(const clang::LangOptions &LO, 407 llvm::Module &M) { 408 if (!LO.VisibilityFromDLLStorageClass) 409 return; 410 411 llvm::GlobalValue::VisibilityTypes DLLExportVisibility = 412 CodeGenModule::GetLLVMVisibility(LO.getDLLExportVisibility()); 413 llvm::GlobalValue::VisibilityTypes NoDLLStorageClassVisibility = 414 CodeGenModule::GetLLVMVisibility(LO.getNoDLLStorageClassVisibility()); 415 llvm::GlobalValue::VisibilityTypes ExternDeclDLLImportVisibility = 416 CodeGenModule::GetLLVMVisibility(LO.getExternDeclDLLImportVisibility()); 417 llvm::GlobalValue::VisibilityTypes ExternDeclNoDLLStorageClassVisibility = 418 CodeGenModule::GetLLVMVisibility( 419 LO.getExternDeclNoDLLStorageClassVisibility()); 420 421 for (llvm::GlobalValue &GV : M.global_values()) { 422 if (GV.hasAppendingLinkage() || GV.hasLocalLinkage()) 423 continue; 424 425 // Reset DSO locality before setting the visibility. This removes 426 // any effects that visibility options and annotations may have 427 // had on the DSO locality. Setting the visibility will implicitly set 428 // appropriate globals to DSO Local; however, this will be pessimistic 429 // w.r.t. to the normal compiler IRGen. 430 GV.setDSOLocal(false); 431 432 if (GV.isDeclarationForLinker()) { 433 GV.setVisibility(GV.getDLLStorageClass() == 434 llvm::GlobalValue::DLLImportStorageClass 435 ? ExternDeclDLLImportVisibility 436 : ExternDeclNoDLLStorageClassVisibility); 437 } else { 438 GV.setVisibility(GV.getDLLStorageClass() == 439 llvm::GlobalValue::DLLExportStorageClass 440 ? DLLExportVisibility 441 : NoDLLStorageClassVisibility); 442 } 443 444 GV.setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 445 } 446 } 447 448 void CodeGenModule::Release() { 449 EmitDeferred(); 450 EmitVTablesOpportunistically(); 451 applyGlobalValReplacements(); 452 applyReplacements(); 453 checkAliases(); 454 emitMultiVersionFunctions(); 455 EmitCXXGlobalInitFunc(); 456 EmitCXXGlobalCleanUpFunc(); 457 registerGlobalDtorsWithAtExit(); 458 EmitCXXThreadLocalInitFunc(); 459 if (ObjCRuntime) 460 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction()) 461 AddGlobalCtor(ObjCInitFunction); 462 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice && 463 CUDARuntime) { 464 if (llvm::Function *CudaCtorFunction = 465 CUDARuntime->makeModuleCtorFunction()) 466 AddGlobalCtor(CudaCtorFunction); 467 } 468 if (OpenMPRuntime) { 469 if (llvm::Function *OpenMPRequiresDirectiveRegFun = 470 OpenMPRuntime->emitRequiresDirectiveRegFun()) { 471 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0); 472 } 473 OpenMPRuntime->createOffloadEntriesAndInfoMetadata(); 474 OpenMPRuntime->clear(); 475 } 476 if (PGOReader) { 477 getModule().setProfileSummary( 478 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext), 479 llvm::ProfileSummary::PSK_Instr); 480 if (PGOStats.hasDiagnostics()) 481 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName); 482 } 483 EmitCtorList(GlobalCtors, "llvm.global_ctors"); 484 EmitCtorList(GlobalDtors, "llvm.global_dtors"); 485 EmitGlobalAnnotations(); 486 EmitStaticExternCAliases(); 487 EmitDeferredUnusedCoverageMappings(); 488 if (CoverageMapping) 489 CoverageMapping->emit(); 490 if (CodeGenOpts.SanitizeCfiCrossDso) { 491 CodeGenFunction(*this).EmitCfiCheckFail(); 492 CodeGenFunction(*this).EmitCfiCheckStub(); 493 } 494 emitAtAvailableLinkGuard(); 495 if (Context.getTargetInfo().getTriple().isWasm() && 496 !Context.getTargetInfo().getTriple().isOSEmscripten()) { 497 EmitMainVoidAlias(); 498 } 499 emitLLVMUsed(); 500 if (SanStats) 501 SanStats->finish(); 502 503 if (CodeGenOpts.Autolink && 504 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) { 505 EmitModuleLinkOptions(); 506 } 507 508 // On ELF we pass the dependent library specifiers directly to the linker 509 // without manipulating them. This is in contrast to other platforms where 510 // they are mapped to a specific linker option by the compiler. This 511 // difference is a result of the greater variety of ELF linkers and the fact 512 // that ELF linkers tend to handle libraries in a more complicated fashion 513 // than on other platforms. This forces us to defer handling the dependent 514 // libs to the linker. 515 // 516 // CUDA/HIP device and host libraries are different. Currently there is no 517 // way to differentiate dependent libraries for host or device. Existing 518 // usage of #pragma comment(lib, *) is intended for host libraries on 519 // Windows. Therefore emit llvm.dependent-libraries only for host. 520 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) { 521 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries"); 522 for (auto *MD : ELFDependentLibraries) 523 NMD->addOperand(MD); 524 } 525 526 // Record mregparm value now so it is visible through rest of codegen. 527 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86) 528 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters", 529 CodeGenOpts.NumRegisterParameters); 530 531 if (CodeGenOpts.DwarfVersion) { 532 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version", 533 CodeGenOpts.DwarfVersion); 534 } 535 536 if (Context.getLangOpts().SemanticInterposition) 537 // Require various optimization to respect semantic interposition. 538 getModule().setSemanticInterposition(1); 539 540 if (CodeGenOpts.EmitCodeView) { 541 // Indicate that we want CodeView in the metadata. 542 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1); 543 } 544 if (CodeGenOpts.CodeViewGHash) { 545 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1); 546 } 547 if (CodeGenOpts.ControlFlowGuard) { 548 // Function ID tables and checks for Control Flow Guard (cfguard=2). 549 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2); 550 } else if (CodeGenOpts.ControlFlowGuardNoChecks) { 551 // Function ID tables for Control Flow Guard (cfguard=1). 552 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1); 553 } 554 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) { 555 // We don't support LTO with 2 with different StrictVTablePointers 556 // FIXME: we could support it by stripping all the information introduced 557 // by StrictVTablePointers. 558 559 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1); 560 561 llvm::Metadata *Ops[2] = { 562 llvm::MDString::get(VMContext, "StrictVTablePointers"), 563 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 564 llvm::Type::getInt32Ty(VMContext), 1))}; 565 566 getModule().addModuleFlag(llvm::Module::Require, 567 "StrictVTablePointersRequirement", 568 llvm::MDNode::get(VMContext, Ops)); 569 } 570 if (getModuleDebugInfo()) 571 // We support a single version in the linked module. The LLVM 572 // parser will drop debug info with a different version number 573 // (and warn about it, too). 574 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version", 575 llvm::DEBUG_METADATA_VERSION); 576 577 // We need to record the widths of enums and wchar_t, so that we can generate 578 // the correct build attributes in the ARM backend. wchar_size is also used by 579 // TargetLibraryInfo. 580 uint64_t WCharWidth = 581 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity(); 582 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth); 583 584 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch(); 585 if ( Arch == llvm::Triple::arm 586 || Arch == llvm::Triple::armeb 587 || Arch == llvm::Triple::thumb 588 || Arch == llvm::Triple::thumbeb) { 589 // The minimum width of an enum in bytes 590 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4; 591 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth); 592 } 593 594 if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) { 595 StringRef ABIStr = Target.getABI(); 596 llvm::LLVMContext &Ctx = TheModule.getContext(); 597 getModule().addModuleFlag(llvm::Module::Error, "target-abi", 598 llvm::MDString::get(Ctx, ABIStr)); 599 } 600 601 if (CodeGenOpts.SanitizeCfiCrossDso) { 602 // Indicate that we want cross-DSO control flow integrity checks. 603 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1); 604 } 605 606 if (CodeGenOpts.WholeProgramVTables) { 607 // Indicate whether VFE was enabled for this module, so that the 608 // vcall_visibility metadata added under whole program vtables is handled 609 // appropriately in the optimizer. 610 getModule().addModuleFlag(llvm::Module::Error, "Virtual Function Elim", 611 CodeGenOpts.VirtualFunctionElimination); 612 } 613 614 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) { 615 getModule().addModuleFlag(llvm::Module::Override, 616 "CFI Canonical Jump Tables", 617 CodeGenOpts.SanitizeCfiCanonicalJumpTables); 618 } 619 620 if (CodeGenOpts.CFProtectionReturn && 621 Target.checkCFProtectionReturnSupported(getDiags())) { 622 // Indicate that we want to instrument return control flow protection. 623 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return", 624 1); 625 } 626 627 if (CodeGenOpts.CFProtectionBranch && 628 Target.checkCFProtectionBranchSupported(getDiags())) { 629 // Indicate that we want to instrument branch control flow protection. 630 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch", 631 1); 632 } 633 634 if (Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_32 || 635 Arch == llvm::Triple::aarch64_be) { 636 getModule().addModuleFlag(llvm::Module::Error, 637 "branch-target-enforcement", 638 LangOpts.BranchTargetEnforcement); 639 640 getModule().addModuleFlag(llvm::Module::Error, "sign-return-address", 641 LangOpts.hasSignReturnAddress()); 642 643 getModule().addModuleFlag(llvm::Module::Error, "sign-return-address-all", 644 LangOpts.isSignReturnAddressScopeAll()); 645 646 getModule().addModuleFlag(llvm::Module::Error, 647 "sign-return-address-with-bkey", 648 !LangOpts.isSignReturnAddressWithAKey()); 649 } 650 651 if (!CodeGenOpts.MemoryProfileOutput.empty()) { 652 llvm::LLVMContext &Ctx = TheModule.getContext(); 653 getModule().addModuleFlag( 654 llvm::Module::Error, "MemProfProfileFilename", 655 llvm::MDString::get(Ctx, CodeGenOpts.MemoryProfileOutput)); 656 } 657 658 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) { 659 // Indicate whether __nvvm_reflect should be configured to flush denormal 660 // floating point values to 0. (This corresponds to its "__CUDA_FTZ" 661 // property.) 662 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz", 663 CodeGenOpts.FP32DenormalMode.Output != 664 llvm::DenormalMode::IEEE); 665 } 666 667 // Emit OpenCL specific module metadata: OpenCL/SPIR version. 668 if (LangOpts.OpenCL) { 669 EmitOpenCLMetadata(); 670 // Emit SPIR version. 671 if (getTriple().isSPIR()) { 672 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the 673 // opencl.spir.version named metadata. 674 // C++ is backwards compatible with OpenCL v2.0. 675 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion; 676 llvm::Metadata *SPIRVerElts[] = { 677 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 678 Int32Ty, Version / 100)), 679 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 680 Int32Ty, (Version / 100 > 1) ? 0 : 2))}; 681 llvm::NamedMDNode *SPIRVerMD = 682 TheModule.getOrInsertNamedMetadata("opencl.spir.version"); 683 llvm::LLVMContext &Ctx = TheModule.getContext(); 684 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts)); 685 } 686 } 687 688 if (uint32_t PLevel = Context.getLangOpts().PICLevel) { 689 assert(PLevel < 3 && "Invalid PIC Level"); 690 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel)); 691 if (Context.getLangOpts().PIE) 692 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel)); 693 } 694 695 if (getCodeGenOpts().CodeModel.size() > 0) { 696 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel) 697 .Case("tiny", llvm::CodeModel::Tiny) 698 .Case("small", llvm::CodeModel::Small) 699 .Case("kernel", llvm::CodeModel::Kernel) 700 .Case("medium", llvm::CodeModel::Medium) 701 .Case("large", llvm::CodeModel::Large) 702 .Default(~0u); 703 if (CM != ~0u) { 704 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM); 705 getModule().setCodeModel(codeModel); 706 } 707 } 708 709 if (CodeGenOpts.NoPLT) 710 getModule().setRtLibUseGOT(); 711 712 SimplifyPersonality(); 713 714 if (getCodeGenOpts().EmitDeclMetadata) 715 EmitDeclMetadata(); 716 717 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes) 718 EmitCoverageFile(); 719 720 if (CGDebugInfo *DI = getModuleDebugInfo()) 721 DI->finalize(); 722 723 if (getCodeGenOpts().EmitVersionIdentMetadata) 724 EmitVersionIdentMetadata(); 725 726 if (!getCodeGenOpts().RecordCommandLine.empty()) 727 EmitCommandLineMetadata(); 728 729 getTargetCodeGenInfo().emitTargetMetadata(*this, MangledDeclNames); 730 731 EmitBackendOptionsMetadata(getCodeGenOpts()); 732 733 // Set visibility from DLL storage class 734 // We do this at the end of LLVM IR generation; after any operation 735 // that might affect the DLL storage class or the visibility, and 736 // before anything that might act on these. 737 setVisibilityFromDLLStorageClass(LangOpts, getModule()); 738 } 739 740 void CodeGenModule::EmitOpenCLMetadata() { 741 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the 742 // opencl.ocl.version named metadata node. 743 // C++ is backwards compatible with OpenCL v2.0. 744 // FIXME: We might need to add CXX version at some point too? 745 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion; 746 llvm::Metadata *OCLVerElts[] = { 747 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 748 Int32Ty, Version / 100)), 749 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get( 750 Int32Ty, (Version % 100) / 10))}; 751 llvm::NamedMDNode *OCLVerMD = 752 TheModule.getOrInsertNamedMetadata("opencl.ocl.version"); 753 llvm::LLVMContext &Ctx = TheModule.getContext(); 754 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts)); 755 } 756 757 void CodeGenModule::EmitBackendOptionsMetadata( 758 const CodeGenOptions CodeGenOpts) { 759 switch (getTriple().getArch()) { 760 default: 761 break; 762 case llvm::Triple::riscv32: 763 case llvm::Triple::riscv64: 764 getModule().addModuleFlag(llvm::Module::Error, "SmallDataLimit", 765 CodeGenOpts.SmallDataLimit); 766 break; 767 } 768 } 769 770 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) { 771 // Make sure that this type is translated. 772 Types.UpdateCompletedType(TD); 773 } 774 775 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) { 776 // Make sure that this type is translated. 777 Types.RefreshTypeCacheForClass(RD); 778 } 779 780 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) { 781 if (!TBAA) 782 return nullptr; 783 return TBAA->getTypeInfo(QTy); 784 } 785 786 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) { 787 if (!TBAA) 788 return TBAAAccessInfo(); 789 if (getLangOpts().CUDAIsDevice) { 790 // As CUDA builtin surface/texture types are replaced, skip generating TBAA 791 // access info. 792 if (AccessType->isCUDADeviceBuiltinSurfaceType()) { 793 if (getTargetCodeGenInfo().getCUDADeviceBuiltinSurfaceDeviceType() != 794 nullptr) 795 return TBAAAccessInfo(); 796 } else if (AccessType->isCUDADeviceBuiltinTextureType()) { 797 if (getTargetCodeGenInfo().getCUDADeviceBuiltinTextureDeviceType() != 798 nullptr) 799 return TBAAAccessInfo(); 800 } 801 } 802 return TBAA->getAccessInfo(AccessType); 803 } 804 805 TBAAAccessInfo 806 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) { 807 if (!TBAA) 808 return TBAAAccessInfo(); 809 return TBAA->getVTablePtrAccessInfo(VTablePtrType); 810 } 811 812 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) { 813 if (!TBAA) 814 return nullptr; 815 return TBAA->getTBAAStructInfo(QTy); 816 } 817 818 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) { 819 if (!TBAA) 820 return nullptr; 821 return TBAA->getBaseTypeInfo(QTy); 822 } 823 824 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) { 825 if (!TBAA) 826 return nullptr; 827 return TBAA->getAccessTagInfo(Info); 828 } 829 830 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo, 831 TBAAAccessInfo TargetInfo) { 832 if (!TBAA) 833 return TBAAAccessInfo(); 834 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo); 835 } 836 837 TBAAAccessInfo 838 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA, 839 TBAAAccessInfo InfoB) { 840 if (!TBAA) 841 return TBAAAccessInfo(); 842 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB); 843 } 844 845 TBAAAccessInfo 846 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo, 847 TBAAAccessInfo SrcInfo) { 848 if (!TBAA) 849 return TBAAAccessInfo(); 850 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo); 851 } 852 853 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst, 854 TBAAAccessInfo TBAAInfo) { 855 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo)) 856 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag); 857 } 858 859 void CodeGenModule::DecorateInstructionWithInvariantGroup( 860 llvm::Instruction *I, const CXXRecordDecl *RD) { 861 I->setMetadata(llvm::LLVMContext::MD_invariant_group, 862 llvm::MDNode::get(getLLVMContext(), {})); 863 } 864 865 void CodeGenModule::Error(SourceLocation loc, StringRef message) { 866 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0"); 867 getDiags().Report(Context.getFullLoc(loc), diagID) << message; 868 } 869 870 /// ErrorUnsupported - Print out an error that codegen doesn't support the 871 /// specified stmt yet. 872 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) { 873 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 874 "cannot compile this %0 yet"); 875 std::string Msg = Type; 876 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID) 877 << Msg << S->getSourceRange(); 878 } 879 880 /// ErrorUnsupported - Print out an error that codegen doesn't support the 881 /// specified decl yet. 882 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) { 883 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, 884 "cannot compile this %0 yet"); 885 std::string Msg = Type; 886 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg; 887 } 888 889 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) { 890 return llvm::ConstantInt::get(SizeTy, size.getQuantity()); 891 } 892 893 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV, 894 const NamedDecl *D) const { 895 if (GV->hasDLLImportStorageClass()) 896 return; 897 // Internal definitions always have default visibility. 898 if (GV->hasLocalLinkage()) { 899 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 900 return; 901 } 902 if (!D) 903 return; 904 // Set visibility for definitions, and for declarations if requested globally 905 // or set explicitly. 906 LinkageInfo LV = D->getLinkageAndVisibility(); 907 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls || 908 !GV->isDeclarationForLinker()) 909 GV->setVisibility(GetLLVMVisibility(LV.getVisibility())); 910 } 911 912 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM, 913 llvm::GlobalValue *GV) { 914 if (GV->hasLocalLinkage()) 915 return true; 916 917 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage()) 918 return true; 919 920 // DLLImport explicitly marks the GV as external. 921 if (GV->hasDLLImportStorageClass()) 922 return false; 923 924 const llvm::Triple &TT = CGM.getTriple(); 925 if (TT.isWindowsGNUEnvironment()) { 926 // In MinGW, variables without DLLImport can still be automatically 927 // imported from a DLL by the linker; don't mark variables that 928 // potentially could come from another DLL as DSO local. 929 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) && 930 !GV->isThreadLocal()) 931 return false; 932 } 933 934 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols 935 // remain unresolved in the link, they can be resolved to zero, which is 936 // outside the current DSO. 937 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage()) 938 return false; 939 940 // Every other GV is local on COFF. 941 // Make an exception for windows OS in the triple: Some firmware builds use 942 // *-win32-macho triples. This (accidentally?) produced windows relocations 943 // without GOT tables in older clang versions; Keep this behaviour. 944 // FIXME: even thread local variables? 945 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO())) 946 return true; 947 948 const auto &CGOpts = CGM.getCodeGenOpts(); 949 llvm::Reloc::Model RM = CGOpts.RelocationModel; 950 const auto &LOpts = CGM.getLangOpts(); 951 952 if (TT.isOSBinFormatMachO()) { 953 if (RM == llvm::Reloc::Static) 954 return true; 955 return GV->isStrongDefinitionForLinker(); 956 } 957 958 // Only handle COFF and ELF for now. 959 if (!TT.isOSBinFormatELF()) 960 return false; 961 962 if (RM != llvm::Reloc::Static && !LOpts.PIE) { 963 // On ELF, if -fno-semantic-interposition is specified and the target 964 // supports local aliases, there will be neither CC1 965 // -fsemantic-interposition nor -fhalf-no-semantic-interposition. Set 966 // dso_local if using a local alias is preferable (can avoid GOT 967 // indirection). 968 if (!GV->canBenefitFromLocalAlias()) 969 return false; 970 return !(CGM.getLangOpts().SemanticInterposition || 971 CGM.getLangOpts().HalfNoSemanticInterposition); 972 } 973 974 // A definition cannot be preempted from an executable. 975 if (!GV->isDeclarationForLinker()) 976 return true; 977 978 // Most PIC code sequences that assume that a symbol is local cannot produce a 979 // 0 if it turns out the symbol is undefined. While this is ABI and relocation 980 // depended, it seems worth it to handle it here. 981 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage()) 982 return false; 983 984 // PowerPC64 prefers TOC indirection to avoid copy relocations. 985 if (TT.isPPC64()) 986 return false; 987 988 if (CGOpts.DirectAccessExternalData) { 989 // If -fdirect-access-external-data (default for -fno-pic), set dso_local 990 // for non-thread-local variables. If the symbol is not defined in the 991 // executable, a copy relocation will be needed at link time. dso_local is 992 // excluded for thread-local variables because they generally don't support 993 // copy relocations. 994 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV)) 995 if (!Var->isThreadLocal()) 996 return true; 997 998 // -fno-pic sets dso_local on a function declaration to allow direct 999 // accesses when taking its address (similar to a data symbol). If the 1000 // function is not defined in the executable, a canonical PLT entry will be 1001 // needed at link time. -fno-direct-access-external-data can avoid the 1002 // canonical PLT entry. We don't generalize this condition to -fpie/-fpic as 1003 // it could just cause trouble without providing perceptible benefits. 1004 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static) 1005 return true; 1006 } 1007 1008 // If we can use copy relocations we can assume it is local. 1009 1010 // Otherwise don't assume it is local. 1011 return false; 1012 } 1013 1014 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const { 1015 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV)); 1016 } 1017 1018 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1019 GlobalDecl GD) const { 1020 const auto *D = dyn_cast<NamedDecl>(GD.getDecl()); 1021 // C++ destructors have a few C++ ABI specific special cases. 1022 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) { 1023 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType()); 1024 return; 1025 } 1026 setDLLImportDLLExport(GV, D); 1027 } 1028 1029 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV, 1030 const NamedDecl *D) const { 1031 if (D && D->isExternallyVisible()) { 1032 if (D->hasAttr<DLLImportAttr>()) 1033 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 1034 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker()) 1035 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 1036 } 1037 } 1038 1039 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1040 GlobalDecl GD) const { 1041 setDLLImportDLLExport(GV, GD); 1042 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl())); 1043 } 1044 1045 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV, 1046 const NamedDecl *D) const { 1047 setDLLImportDLLExport(GV, D); 1048 setGVPropertiesAux(GV, D); 1049 } 1050 1051 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV, 1052 const NamedDecl *D) const { 1053 setGlobalVisibility(GV, D); 1054 setDSOLocal(GV); 1055 GV->setPartition(CodeGenOpts.SymbolPartition); 1056 } 1057 1058 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) { 1059 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S) 1060 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel) 1061 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel) 1062 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel) 1063 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel); 1064 } 1065 1066 llvm::GlobalVariable::ThreadLocalMode 1067 CodeGenModule::GetDefaultLLVMTLSModel() const { 1068 switch (CodeGenOpts.getDefaultTLSModel()) { 1069 case CodeGenOptions::GeneralDynamicTLSModel: 1070 return llvm::GlobalVariable::GeneralDynamicTLSModel; 1071 case CodeGenOptions::LocalDynamicTLSModel: 1072 return llvm::GlobalVariable::LocalDynamicTLSModel; 1073 case CodeGenOptions::InitialExecTLSModel: 1074 return llvm::GlobalVariable::InitialExecTLSModel; 1075 case CodeGenOptions::LocalExecTLSModel: 1076 return llvm::GlobalVariable::LocalExecTLSModel; 1077 } 1078 llvm_unreachable("Invalid TLS model!"); 1079 } 1080 1081 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const { 1082 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!"); 1083 1084 llvm::GlobalValue::ThreadLocalMode TLM; 1085 TLM = GetDefaultLLVMTLSModel(); 1086 1087 // Override the TLS model if it is explicitly specified. 1088 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) { 1089 TLM = GetLLVMTLSModel(Attr->getModel()); 1090 } 1091 1092 GV->setThreadLocalMode(TLM); 1093 } 1094 1095 static std::string getCPUSpecificMangling(const CodeGenModule &CGM, 1096 StringRef Name) { 1097 const TargetInfo &Target = CGM.getTarget(); 1098 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str(); 1099 } 1100 1101 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM, 1102 const CPUSpecificAttr *Attr, 1103 unsigned CPUIndex, 1104 raw_ostream &Out) { 1105 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is 1106 // supported. 1107 if (Attr) 1108 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName()); 1109 else if (CGM.getTarget().supportsIFunc()) 1110 Out << ".resolver"; 1111 } 1112 1113 static void AppendTargetMangling(const CodeGenModule &CGM, 1114 const TargetAttr *Attr, raw_ostream &Out) { 1115 if (Attr->isDefaultVersion()) 1116 return; 1117 1118 Out << '.'; 1119 const TargetInfo &Target = CGM.getTarget(); 1120 ParsedTargetAttr Info = 1121 Attr->parse([&Target](StringRef LHS, StringRef RHS) { 1122 // Multiversioning doesn't allow "no-${feature}", so we can 1123 // only have "+" prefixes here. 1124 assert(LHS.startswith("+") && RHS.startswith("+") && 1125 "Features should always have a prefix."); 1126 return Target.multiVersionSortPriority(LHS.substr(1)) > 1127 Target.multiVersionSortPriority(RHS.substr(1)); 1128 }); 1129 1130 bool IsFirst = true; 1131 1132 if (!Info.Architecture.empty()) { 1133 IsFirst = false; 1134 Out << "arch_" << Info.Architecture; 1135 } 1136 1137 for (StringRef Feat : Info.Features) { 1138 if (!IsFirst) 1139 Out << '_'; 1140 IsFirst = false; 1141 Out << Feat.substr(1); 1142 } 1143 } 1144 1145 static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD, 1146 const NamedDecl *ND, 1147 bool OmitMultiVersionMangling = false) { 1148 SmallString<256> Buffer; 1149 llvm::raw_svector_ostream Out(Buffer); 1150 MangleContext &MC = CGM.getCXXABI().getMangleContext(); 1151 if (MC.shouldMangleDeclName(ND)) 1152 MC.mangleName(GD.getWithDecl(ND), Out); 1153 else { 1154 IdentifierInfo *II = ND->getIdentifier(); 1155 assert(II && "Attempt to mangle unnamed decl."); 1156 const auto *FD = dyn_cast<FunctionDecl>(ND); 1157 1158 if (FD && 1159 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) { 1160 Out << "__regcall3__" << II->getName(); 1161 } else if (FD && FD->hasAttr<CUDAGlobalAttr>() && 1162 GD.getKernelReferenceKind() == KernelReferenceKind::Stub) { 1163 Out << "__device_stub__" << II->getName(); 1164 } else { 1165 Out << II->getName(); 1166 } 1167 } 1168 1169 if (const auto *FD = dyn_cast<FunctionDecl>(ND)) 1170 if (FD->isMultiVersion() && !OmitMultiVersionMangling) { 1171 switch (FD->getMultiVersionKind()) { 1172 case MultiVersionKind::CPUDispatch: 1173 case MultiVersionKind::CPUSpecific: 1174 AppendCPUSpecificCPUDispatchMangling(CGM, 1175 FD->getAttr<CPUSpecificAttr>(), 1176 GD.getMultiVersionIndex(), Out); 1177 break; 1178 case MultiVersionKind::Target: 1179 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out); 1180 break; 1181 case MultiVersionKind::None: 1182 llvm_unreachable("None multiversion type isn't valid here"); 1183 } 1184 } 1185 1186 return std::string(Out.str()); 1187 } 1188 1189 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD, 1190 const FunctionDecl *FD) { 1191 if (!FD->isMultiVersion()) 1192 return; 1193 1194 // Get the name of what this would be without the 'target' attribute. This 1195 // allows us to lookup the version that was emitted when this wasn't a 1196 // multiversion function. 1197 std::string NonTargetName = 1198 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 1199 GlobalDecl OtherGD; 1200 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) { 1201 assert(OtherGD.getCanonicalDecl() 1202 .getDecl() 1203 ->getAsFunction() 1204 ->isMultiVersion() && 1205 "Other GD should now be a multiversioned function"); 1206 // OtherFD is the version of this function that was mangled BEFORE 1207 // becoming a MultiVersion function. It potentially needs to be updated. 1208 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl() 1209 .getDecl() 1210 ->getAsFunction() 1211 ->getMostRecentDecl(); 1212 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD); 1213 // This is so that if the initial version was already the 'default' 1214 // version, we don't try to update it. 1215 if (OtherName != NonTargetName) { 1216 // Remove instead of erase, since others may have stored the StringRef 1217 // to this. 1218 const auto ExistingRecord = Manglings.find(NonTargetName); 1219 if (ExistingRecord != std::end(Manglings)) 1220 Manglings.remove(&(*ExistingRecord)); 1221 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD)); 1222 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first(); 1223 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName)) 1224 Entry->setName(OtherName); 1225 } 1226 } 1227 } 1228 1229 StringRef CodeGenModule::getMangledName(GlobalDecl GD) { 1230 GlobalDecl CanonicalGD = GD.getCanonicalDecl(); 1231 1232 // Some ABIs don't have constructor variants. Make sure that base and 1233 // complete constructors get mangled the same. 1234 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) { 1235 if (!getTarget().getCXXABI().hasConstructorVariants()) { 1236 CXXCtorType OrigCtorType = GD.getCtorType(); 1237 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete); 1238 if (OrigCtorType == Ctor_Base) 1239 CanonicalGD = GlobalDecl(CD, Ctor_Complete); 1240 } 1241 } 1242 1243 auto FoundName = MangledDeclNames.find(CanonicalGD); 1244 if (FoundName != MangledDeclNames.end()) 1245 return FoundName->second; 1246 1247 // Keep the first result in the case of a mangling collision. 1248 const auto *ND = cast<NamedDecl>(GD.getDecl()); 1249 std::string MangledName = getMangledNameImpl(*this, GD, ND); 1250 1251 // Ensure either we have different ABIs between host and device compilations, 1252 // says host compilation following MSVC ABI but device compilation follows 1253 // Itanium C++ ABI or, if they follow the same ABI, kernel names after 1254 // mangling should be the same after name stubbing. The later checking is 1255 // very important as the device kernel name being mangled in host-compilation 1256 // is used to resolve the device binaries to be executed. Inconsistent naming 1257 // result in undefined behavior. Even though we cannot check that naming 1258 // directly between host- and device-compilations, the host- and 1259 // device-mangling in host compilation could help catching certain ones. 1260 assert(!isa<FunctionDecl>(ND) || !ND->hasAttr<CUDAGlobalAttr>() || 1261 getLangOpts().CUDAIsDevice || 1262 (getContext().getAuxTargetInfo() && 1263 (getContext().getAuxTargetInfo()->getCXXABI() != 1264 getContext().getTargetInfo().getCXXABI())) || 1265 getCUDARuntime().getDeviceSideName(ND) == 1266 getMangledNameImpl( 1267 *this, 1268 GD.getWithKernelReferenceKind(KernelReferenceKind::Kernel), 1269 ND)); 1270 1271 auto Result = Manglings.insert(std::make_pair(MangledName, GD)); 1272 return MangledDeclNames[CanonicalGD] = Result.first->first(); 1273 } 1274 1275 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD, 1276 const BlockDecl *BD) { 1277 MangleContext &MangleCtx = getCXXABI().getMangleContext(); 1278 const Decl *D = GD.getDecl(); 1279 1280 SmallString<256> Buffer; 1281 llvm::raw_svector_ostream Out(Buffer); 1282 if (!D) 1283 MangleCtx.mangleGlobalBlock(BD, 1284 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out); 1285 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D)) 1286 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out); 1287 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D)) 1288 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out); 1289 else 1290 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out); 1291 1292 auto Result = Manglings.insert(std::make_pair(Out.str(), BD)); 1293 return Result.first->first(); 1294 } 1295 1296 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) { 1297 return getModule().getNamedValue(Name); 1298 } 1299 1300 /// AddGlobalCtor - Add a function to the list that will be called before 1301 /// main() runs. 1302 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority, 1303 llvm::Constant *AssociatedData) { 1304 // FIXME: Type coercion of void()* types. 1305 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData)); 1306 } 1307 1308 /// AddGlobalDtor - Add a function to the list that will be called 1309 /// when the module is unloaded. 1310 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority, 1311 bool IsDtorAttrFunc) { 1312 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit && 1313 (!getContext().getTargetInfo().getTriple().isOSAIX() || IsDtorAttrFunc)) { 1314 DtorsUsingAtExit[Priority].push_back(Dtor); 1315 return; 1316 } 1317 1318 // FIXME: Type coercion of void()* types. 1319 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr)); 1320 } 1321 1322 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) { 1323 if (Fns.empty()) return; 1324 1325 // Ctor function type is void()*. 1326 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false); 1327 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy, 1328 TheModule.getDataLayout().getProgramAddressSpace()); 1329 1330 // Get the type of a ctor entry, { i32, void ()*, i8* }. 1331 llvm::StructType *CtorStructTy = llvm::StructType::get( 1332 Int32Ty, CtorPFTy, VoidPtrTy); 1333 1334 // Construct the constructor and destructor arrays. 1335 ConstantInitBuilder builder(*this); 1336 auto ctors = builder.beginArray(CtorStructTy); 1337 for (const auto &I : Fns) { 1338 auto ctor = ctors.beginStruct(CtorStructTy); 1339 ctor.addInt(Int32Ty, I.Priority); 1340 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy)); 1341 if (I.AssociatedData) 1342 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)); 1343 else 1344 ctor.addNullPointer(VoidPtrTy); 1345 ctor.finishAndAddTo(ctors); 1346 } 1347 1348 auto list = 1349 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(), 1350 /*constant*/ false, 1351 llvm::GlobalValue::AppendingLinkage); 1352 1353 // The LTO linker doesn't seem to like it when we set an alignment 1354 // on appending variables. Take it off as a workaround. 1355 list->setAlignment(llvm::None); 1356 1357 Fns.clear(); 1358 } 1359 1360 llvm::GlobalValue::LinkageTypes 1361 CodeGenModule::getFunctionLinkage(GlobalDecl GD) { 1362 const auto *D = cast<FunctionDecl>(GD.getDecl()); 1363 1364 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D); 1365 1366 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D)) 1367 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType()); 1368 1369 if (isa<CXXConstructorDecl>(D) && 1370 cast<CXXConstructorDecl>(D)->isInheritingConstructor() && 1371 Context.getTargetInfo().getCXXABI().isMicrosoft()) { 1372 // Our approach to inheriting constructors is fundamentally different from 1373 // that used by the MS ABI, so keep our inheriting constructor thunks 1374 // internal rather than trying to pick an unambiguous mangling for them. 1375 return llvm::GlobalValue::InternalLinkage; 1376 } 1377 1378 return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false); 1379 } 1380 1381 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) { 1382 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD); 1383 if (!MDS) return nullptr; 1384 1385 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString())); 1386 } 1387 1388 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD, 1389 const CGFunctionInfo &Info, 1390 llvm::Function *F) { 1391 unsigned CallingConv; 1392 llvm::AttributeList PAL; 1393 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false); 1394 F->setAttributes(PAL); 1395 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv)); 1396 } 1397 1398 static void removeImageAccessQualifier(std::string& TyName) { 1399 std::string ReadOnlyQual("__read_only"); 1400 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual); 1401 if (ReadOnlyPos != std::string::npos) 1402 // "+ 1" for the space after access qualifier. 1403 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1); 1404 else { 1405 std::string WriteOnlyQual("__write_only"); 1406 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual); 1407 if (WriteOnlyPos != std::string::npos) 1408 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1); 1409 else { 1410 std::string ReadWriteQual("__read_write"); 1411 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual); 1412 if (ReadWritePos != std::string::npos) 1413 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1); 1414 } 1415 } 1416 } 1417 1418 // Returns the address space id that should be produced to the 1419 // kernel_arg_addr_space metadata. This is always fixed to the ids 1420 // as specified in the SPIR 2.0 specification in order to differentiate 1421 // for example in clGetKernelArgInfo() implementation between the address 1422 // spaces with targets without unique mapping to the OpenCL address spaces 1423 // (basically all single AS CPUs). 1424 static unsigned ArgInfoAddressSpace(LangAS AS) { 1425 switch (AS) { 1426 case LangAS::opencl_global: 1427 return 1; 1428 case LangAS::opencl_constant: 1429 return 2; 1430 case LangAS::opencl_local: 1431 return 3; 1432 case LangAS::opencl_generic: 1433 return 4; // Not in SPIR 2.0 specs. 1434 case LangAS::opencl_global_device: 1435 return 5; 1436 case LangAS::opencl_global_host: 1437 return 6; 1438 default: 1439 return 0; // Assume private. 1440 } 1441 } 1442 1443 void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn, 1444 const FunctionDecl *FD, 1445 CodeGenFunction *CGF) { 1446 assert(((FD && CGF) || (!FD && !CGF)) && 1447 "Incorrect use - FD and CGF should either be both null or not!"); 1448 // Create MDNodes that represent the kernel arg metadata. 1449 // Each MDNode is a list in the form of "key", N number of values which is 1450 // the same number of values as their are kernel arguments. 1451 1452 const PrintingPolicy &Policy = Context.getPrintingPolicy(); 1453 1454 // MDNode for the kernel argument address space qualifiers. 1455 SmallVector<llvm::Metadata *, 8> addressQuals; 1456 1457 // MDNode for the kernel argument access qualifiers (images only). 1458 SmallVector<llvm::Metadata *, 8> accessQuals; 1459 1460 // MDNode for the kernel argument type names. 1461 SmallVector<llvm::Metadata *, 8> argTypeNames; 1462 1463 // MDNode for the kernel argument base type names. 1464 SmallVector<llvm::Metadata *, 8> argBaseTypeNames; 1465 1466 // MDNode for the kernel argument type qualifiers. 1467 SmallVector<llvm::Metadata *, 8> argTypeQuals; 1468 1469 // MDNode for the kernel argument names. 1470 SmallVector<llvm::Metadata *, 8> argNames; 1471 1472 if (FD && CGF) 1473 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) { 1474 const ParmVarDecl *parm = FD->getParamDecl(i); 1475 QualType ty = parm->getType(); 1476 std::string typeQuals; 1477 1478 // Get image and pipe access qualifier: 1479 if (ty->isImageType() || ty->isPipeType()) { 1480 const Decl *PDecl = parm; 1481 if (auto *TD = dyn_cast<TypedefType>(ty)) 1482 PDecl = TD->getDecl(); 1483 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>(); 1484 if (A && A->isWriteOnly()) 1485 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only")); 1486 else if (A && A->isReadWrite()) 1487 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write")); 1488 else 1489 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only")); 1490 } else 1491 accessQuals.push_back(llvm::MDString::get(VMContext, "none")); 1492 1493 // Get argument name. 1494 argNames.push_back(llvm::MDString::get(VMContext, parm->getName())); 1495 1496 auto getTypeSpelling = [&](QualType Ty) { 1497 auto typeName = Ty.getUnqualifiedType().getAsString(Policy); 1498 1499 if (Ty.isCanonical()) { 1500 StringRef typeNameRef = typeName; 1501 // Turn "unsigned type" to "utype" 1502 if (typeNameRef.consume_front("unsigned ")) 1503 return std::string("u") + typeNameRef.str(); 1504 } 1505 1506 return typeName; 1507 }; 1508 1509 if (ty->isPointerType()) { 1510 QualType pointeeTy = ty->getPointeeType(); 1511 1512 // Get address qualifier. 1513 addressQuals.push_back( 1514 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32( 1515 ArgInfoAddressSpace(pointeeTy.getAddressSpace())))); 1516 1517 // Get argument type name. 1518 std::string typeName = getTypeSpelling(pointeeTy) + "*"; 1519 std::string baseTypeName = 1520 getTypeSpelling(pointeeTy.getCanonicalType()) + "*"; 1521 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1522 argBaseTypeNames.push_back( 1523 llvm::MDString::get(VMContext, baseTypeName)); 1524 1525 // Get argument type qualifiers: 1526 if (ty.isRestrictQualified()) 1527 typeQuals = "restrict"; 1528 if (pointeeTy.isConstQualified() || 1529 (pointeeTy.getAddressSpace() == LangAS::opencl_constant)) 1530 typeQuals += typeQuals.empty() ? "const" : " const"; 1531 if (pointeeTy.isVolatileQualified()) 1532 typeQuals += typeQuals.empty() ? "volatile" : " volatile"; 1533 } else { 1534 uint32_t AddrSpc = 0; 1535 bool isPipe = ty->isPipeType(); 1536 if (ty->isImageType() || isPipe) 1537 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global); 1538 1539 addressQuals.push_back( 1540 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc))); 1541 1542 // Get argument type name. 1543 ty = isPipe ? ty->castAs<PipeType>()->getElementType() : ty; 1544 std::string typeName = getTypeSpelling(ty); 1545 std::string baseTypeName = getTypeSpelling(ty.getCanonicalType()); 1546 1547 // Remove access qualifiers on images 1548 // (as they are inseparable from type in clang implementation, 1549 // but OpenCL spec provides a special query to get access qualifier 1550 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER): 1551 if (ty->isImageType()) { 1552 removeImageAccessQualifier(typeName); 1553 removeImageAccessQualifier(baseTypeName); 1554 } 1555 1556 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName)); 1557 argBaseTypeNames.push_back( 1558 llvm::MDString::get(VMContext, baseTypeName)); 1559 1560 if (isPipe) 1561 typeQuals = "pipe"; 1562 } 1563 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals)); 1564 } 1565 1566 Fn->setMetadata("kernel_arg_addr_space", 1567 llvm::MDNode::get(VMContext, addressQuals)); 1568 Fn->setMetadata("kernel_arg_access_qual", 1569 llvm::MDNode::get(VMContext, accessQuals)); 1570 Fn->setMetadata("kernel_arg_type", 1571 llvm::MDNode::get(VMContext, argTypeNames)); 1572 Fn->setMetadata("kernel_arg_base_type", 1573 llvm::MDNode::get(VMContext, argBaseTypeNames)); 1574 Fn->setMetadata("kernel_arg_type_qual", 1575 llvm::MDNode::get(VMContext, argTypeQuals)); 1576 if (getCodeGenOpts().EmitOpenCLArgMetadata) 1577 Fn->setMetadata("kernel_arg_name", 1578 llvm::MDNode::get(VMContext, argNames)); 1579 } 1580 1581 /// Determines whether the language options require us to model 1582 /// unwind exceptions. We treat -fexceptions as mandating this 1583 /// except under the fragile ObjC ABI with only ObjC exceptions 1584 /// enabled. This means, for example, that C with -fexceptions 1585 /// enables this. 1586 static bool hasUnwindExceptions(const LangOptions &LangOpts) { 1587 // If exceptions are completely disabled, obviously this is false. 1588 if (!LangOpts.Exceptions) return false; 1589 1590 // If C++ exceptions are enabled, this is true. 1591 if (LangOpts.CXXExceptions) return true; 1592 1593 // If ObjC exceptions are enabled, this depends on the ABI. 1594 if (LangOpts.ObjCExceptions) { 1595 return LangOpts.ObjCRuntime.hasUnwindExceptions(); 1596 } 1597 1598 return true; 1599 } 1600 1601 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM, 1602 const CXXMethodDecl *MD) { 1603 // Check that the type metadata can ever actually be used by a call. 1604 if (!CGM.getCodeGenOpts().LTOUnit || 1605 !CGM.HasHiddenLTOVisibility(MD->getParent())) 1606 return false; 1607 1608 // Only functions whose address can be taken with a member function pointer 1609 // need this sort of type metadata. 1610 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) && 1611 !isa<CXXDestructorDecl>(MD); 1612 } 1613 1614 std::vector<const CXXRecordDecl *> 1615 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) { 1616 llvm::SetVector<const CXXRecordDecl *> MostBases; 1617 1618 std::function<void (const CXXRecordDecl *)> CollectMostBases; 1619 CollectMostBases = [&](const CXXRecordDecl *RD) { 1620 if (RD->getNumBases() == 0) 1621 MostBases.insert(RD); 1622 for (const CXXBaseSpecifier &B : RD->bases()) 1623 CollectMostBases(B.getType()->getAsCXXRecordDecl()); 1624 }; 1625 CollectMostBases(RD); 1626 return MostBases.takeVector(); 1627 } 1628 1629 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D, 1630 llvm::Function *F) { 1631 llvm::AttrBuilder B; 1632 1633 if (CodeGenOpts.UnwindTables) 1634 B.addAttribute(llvm::Attribute::UWTable); 1635 1636 if (CodeGenOpts.StackClashProtector) 1637 B.addAttribute("probe-stack", "inline-asm"); 1638 1639 if (!hasUnwindExceptions(LangOpts)) 1640 B.addAttribute(llvm::Attribute::NoUnwind); 1641 1642 if (!D || !D->hasAttr<NoStackProtectorAttr>()) { 1643 if (LangOpts.getStackProtector() == LangOptions::SSPOn) 1644 B.addAttribute(llvm::Attribute::StackProtect); 1645 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong) 1646 B.addAttribute(llvm::Attribute::StackProtectStrong); 1647 else if (LangOpts.getStackProtector() == LangOptions::SSPReq) 1648 B.addAttribute(llvm::Attribute::StackProtectReq); 1649 } 1650 1651 if (!D) { 1652 // If we don't have a declaration to control inlining, the function isn't 1653 // explicitly marked as alwaysinline for semantic reasons, and inlining is 1654 // disabled, mark the function as noinline. 1655 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) && 1656 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) 1657 B.addAttribute(llvm::Attribute::NoInline); 1658 1659 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 1660 return; 1661 } 1662 1663 // Track whether we need to add the optnone LLVM attribute, 1664 // starting with the default for this optimization level. 1665 bool ShouldAddOptNone = 1666 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0; 1667 // We can't add optnone in the following cases, it won't pass the verifier. 1668 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>(); 1669 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>(); 1670 1671 // Add optnone, but do so only if the function isn't always_inline. 1672 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) && 1673 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1674 B.addAttribute(llvm::Attribute::OptimizeNone); 1675 1676 // OptimizeNone implies noinline; we should not be inlining such functions. 1677 B.addAttribute(llvm::Attribute::NoInline); 1678 1679 // We still need to handle naked functions even though optnone subsumes 1680 // much of their semantics. 1681 if (D->hasAttr<NakedAttr>()) 1682 B.addAttribute(llvm::Attribute::Naked); 1683 1684 // OptimizeNone wins over OptimizeForSize and MinSize. 1685 F->removeFnAttr(llvm::Attribute::OptimizeForSize); 1686 F->removeFnAttr(llvm::Attribute::MinSize); 1687 } else if (D->hasAttr<NakedAttr>()) { 1688 // Naked implies noinline: we should not be inlining such functions. 1689 B.addAttribute(llvm::Attribute::Naked); 1690 B.addAttribute(llvm::Attribute::NoInline); 1691 } else if (D->hasAttr<NoDuplicateAttr>()) { 1692 B.addAttribute(llvm::Attribute::NoDuplicate); 1693 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1694 // Add noinline if the function isn't always_inline. 1695 B.addAttribute(llvm::Attribute::NoInline); 1696 } else if (D->hasAttr<AlwaysInlineAttr>() && 1697 !F->hasFnAttribute(llvm::Attribute::NoInline)) { 1698 // (noinline wins over always_inline, and we can't specify both in IR) 1699 B.addAttribute(llvm::Attribute::AlwaysInline); 1700 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) { 1701 // If we're not inlining, then force everything that isn't always_inline to 1702 // carry an explicit noinline attribute. 1703 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline)) 1704 B.addAttribute(llvm::Attribute::NoInline); 1705 } else { 1706 // Otherwise, propagate the inline hint attribute and potentially use its 1707 // absence to mark things as noinline. 1708 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1709 // Search function and template pattern redeclarations for inline. 1710 auto CheckForInline = [](const FunctionDecl *FD) { 1711 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) { 1712 return Redecl->isInlineSpecified(); 1713 }; 1714 if (any_of(FD->redecls(), CheckRedeclForInline)) 1715 return true; 1716 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern(); 1717 if (!Pattern) 1718 return false; 1719 return any_of(Pattern->redecls(), CheckRedeclForInline); 1720 }; 1721 if (CheckForInline(FD)) { 1722 B.addAttribute(llvm::Attribute::InlineHint); 1723 } else if (CodeGenOpts.getInlining() == 1724 CodeGenOptions::OnlyHintInlining && 1725 !FD->isInlined() && 1726 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) { 1727 B.addAttribute(llvm::Attribute::NoInline); 1728 } 1729 } 1730 } 1731 1732 // Add other optimization related attributes if we are optimizing this 1733 // function. 1734 if (!D->hasAttr<OptimizeNoneAttr>()) { 1735 if (D->hasAttr<ColdAttr>()) { 1736 if (!ShouldAddOptNone) 1737 B.addAttribute(llvm::Attribute::OptimizeForSize); 1738 B.addAttribute(llvm::Attribute::Cold); 1739 } 1740 if (D->hasAttr<HotAttr>()) 1741 B.addAttribute(llvm::Attribute::Hot); 1742 if (D->hasAttr<MinSizeAttr>()) 1743 B.addAttribute(llvm::Attribute::MinSize); 1744 } 1745 1746 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 1747 1748 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth(); 1749 if (alignment) 1750 F->setAlignment(llvm::Align(alignment)); 1751 1752 if (!D->hasAttr<AlignedAttr>()) 1753 if (LangOpts.FunctionAlignment) 1754 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment)); 1755 1756 // Some C++ ABIs require 2-byte alignment for member functions, in order to 1757 // reserve a bit for differentiating between virtual and non-virtual member 1758 // functions. If the current target's C++ ABI requires this and this is a 1759 // member function, set its alignment accordingly. 1760 if (getTarget().getCXXABI().areMemberFunctionsAligned()) { 1761 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D)) 1762 F->setAlignment(llvm::Align(2)); 1763 } 1764 1765 // In the cross-dso CFI mode with canonical jump tables, we want !type 1766 // attributes on definitions only. 1767 if (CodeGenOpts.SanitizeCfiCrossDso && 1768 CodeGenOpts.SanitizeCfiCanonicalJumpTables) { 1769 if (auto *FD = dyn_cast<FunctionDecl>(D)) { 1770 // Skip available_externally functions. They won't be codegen'ed in the 1771 // current module anyway. 1772 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally) 1773 CreateFunctionTypeMetadataForIcall(FD, F); 1774 } 1775 } 1776 1777 // Emit type metadata on member functions for member function pointer checks. 1778 // These are only ever necessary on definitions; we're guaranteed that the 1779 // definition will be present in the LTO unit as a result of LTO visibility. 1780 auto *MD = dyn_cast<CXXMethodDecl>(D); 1781 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) { 1782 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) { 1783 llvm::Metadata *Id = 1784 CreateMetadataIdentifierForType(Context.getMemberPointerType( 1785 MD->getType(), Context.getRecordType(Base).getTypePtr())); 1786 F->addTypeMetadata(0, Id); 1787 } 1788 } 1789 } 1790 1791 void CodeGenModule::setLLVMFunctionFEnvAttributes(const FunctionDecl *D, 1792 llvm::Function *F) { 1793 if (D->hasAttr<StrictFPAttr>()) { 1794 llvm::AttrBuilder FuncAttrs; 1795 FuncAttrs.addAttribute("strictfp"); 1796 F->addAttributes(llvm::AttributeList::FunctionIndex, FuncAttrs); 1797 } 1798 } 1799 1800 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) { 1801 const Decl *D = GD.getDecl(); 1802 if (dyn_cast_or_null<NamedDecl>(D)) 1803 setGVProperties(GV, GD); 1804 else 1805 GV->setVisibility(llvm::GlobalValue::DefaultVisibility); 1806 1807 if (D && D->hasAttr<UsedAttr>()) 1808 addUsedGlobal(GV); 1809 1810 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) { 1811 const auto *VD = cast<VarDecl>(D); 1812 if (VD->getType().isConstQualified() && 1813 VD->getStorageDuration() == SD_Static) 1814 addUsedGlobal(GV); 1815 } 1816 } 1817 1818 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD, 1819 llvm::AttrBuilder &Attrs) { 1820 // Add target-cpu and target-features attributes to functions. If 1821 // we have a decl for the function and it has a target attribute then 1822 // parse that and add it to the feature set. 1823 StringRef TargetCPU = getTarget().getTargetOpts().CPU; 1824 StringRef TuneCPU = getTarget().getTargetOpts().TuneCPU; 1825 std::vector<std::string> Features; 1826 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl()); 1827 FD = FD ? FD->getMostRecentDecl() : FD; 1828 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr; 1829 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr; 1830 bool AddedAttr = false; 1831 if (TD || SD) { 1832 llvm::StringMap<bool> FeatureMap; 1833 getContext().getFunctionFeatureMap(FeatureMap, GD); 1834 1835 // Produce the canonical string for this set of features. 1836 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap) 1837 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str()); 1838 1839 // Now add the target-cpu and target-features to the function. 1840 // While we populated the feature map above, we still need to 1841 // get and parse the target attribute so we can get the cpu for 1842 // the function. 1843 if (TD) { 1844 ParsedTargetAttr ParsedAttr = TD->parse(); 1845 if (!ParsedAttr.Architecture.empty() && 1846 getTarget().isValidCPUName(ParsedAttr.Architecture)) { 1847 TargetCPU = ParsedAttr.Architecture; 1848 TuneCPU = ""; // Clear the tune CPU. 1849 } 1850 if (!ParsedAttr.Tune.empty() && 1851 getTarget().isValidCPUName(ParsedAttr.Tune)) 1852 TuneCPU = ParsedAttr.Tune; 1853 } 1854 } else { 1855 // Otherwise just add the existing target cpu and target features to the 1856 // function. 1857 Features = getTarget().getTargetOpts().Features; 1858 } 1859 1860 if (!TargetCPU.empty()) { 1861 Attrs.addAttribute("target-cpu", TargetCPU); 1862 AddedAttr = true; 1863 } 1864 if (!TuneCPU.empty()) { 1865 Attrs.addAttribute("tune-cpu", TuneCPU); 1866 AddedAttr = true; 1867 } 1868 if (!Features.empty()) { 1869 llvm::sort(Features); 1870 Attrs.addAttribute("target-features", llvm::join(Features, ",")); 1871 AddedAttr = true; 1872 } 1873 1874 return AddedAttr; 1875 } 1876 1877 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD, 1878 llvm::GlobalObject *GO) { 1879 const Decl *D = GD.getDecl(); 1880 SetCommonAttributes(GD, GO); 1881 1882 if (D) { 1883 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) { 1884 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>()) 1885 GV->addAttribute("bss-section", SA->getName()); 1886 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>()) 1887 GV->addAttribute("data-section", SA->getName()); 1888 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>()) 1889 GV->addAttribute("rodata-section", SA->getName()); 1890 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>()) 1891 GV->addAttribute("relro-section", SA->getName()); 1892 } 1893 1894 if (auto *F = dyn_cast<llvm::Function>(GO)) { 1895 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>()) 1896 if (!D->getAttr<SectionAttr>()) 1897 F->addFnAttr("implicit-section-name", SA->getName()); 1898 1899 llvm::AttrBuilder Attrs; 1900 if (GetCPUAndFeaturesAttributes(GD, Attrs)) { 1901 // We know that GetCPUAndFeaturesAttributes will always have the 1902 // newest set, since it has the newest possible FunctionDecl, so the 1903 // new ones should replace the old. 1904 llvm::AttrBuilder RemoveAttrs; 1905 RemoveAttrs.addAttribute("target-cpu"); 1906 RemoveAttrs.addAttribute("target-features"); 1907 RemoveAttrs.addAttribute("tune-cpu"); 1908 F->removeAttributes(llvm::AttributeList::FunctionIndex, RemoveAttrs); 1909 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs); 1910 } 1911 } 1912 1913 if (const auto *CSA = D->getAttr<CodeSegAttr>()) 1914 GO->setSection(CSA->getName()); 1915 else if (const auto *SA = D->getAttr<SectionAttr>()) 1916 GO->setSection(SA->getName()); 1917 } 1918 1919 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this); 1920 } 1921 1922 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD, 1923 llvm::Function *F, 1924 const CGFunctionInfo &FI) { 1925 const Decl *D = GD.getDecl(); 1926 SetLLVMFunctionAttributes(GD, FI, F); 1927 SetLLVMFunctionAttributesForDefinition(D, F); 1928 1929 F->setLinkage(llvm::Function::InternalLinkage); 1930 1931 setNonAliasAttributes(GD, F); 1932 } 1933 1934 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) { 1935 // Set linkage and visibility in case we never see a definition. 1936 LinkageInfo LV = ND->getLinkageAndVisibility(); 1937 // Don't set internal linkage on declarations. 1938 // "extern_weak" is overloaded in LLVM; we probably should have 1939 // separate linkage types for this. 1940 if (isExternallyVisible(LV.getLinkage()) && 1941 (ND->hasAttr<WeakAttr>() || ND->isWeakImported())) 1942 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); 1943 } 1944 1945 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD, 1946 llvm::Function *F) { 1947 // Only if we are checking indirect calls. 1948 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall)) 1949 return; 1950 1951 // Non-static class methods are handled via vtable or member function pointer 1952 // checks elsewhere. 1953 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic()) 1954 return; 1955 1956 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType()); 1957 F->addTypeMetadata(0, MD); 1958 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType())); 1959 1960 // Emit a hash-based bit set entry for cross-DSO calls. 1961 if (CodeGenOpts.SanitizeCfiCrossDso) 1962 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 1963 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 1964 } 1965 1966 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F, 1967 bool IsIncompleteFunction, 1968 bool IsThunk) { 1969 1970 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) { 1971 // If this is an intrinsic function, set the function's attributes 1972 // to the intrinsic's attributes. 1973 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID)); 1974 return; 1975 } 1976 1977 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 1978 1979 if (!IsIncompleteFunction) 1980 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F); 1981 1982 // Add the Returned attribute for "this", except for iOS 5 and earlier 1983 // where substantial code, including the libstdc++ dylib, was compiled with 1984 // GCC and does not actually return "this". 1985 if (!IsThunk && getCXXABI().HasThisReturn(GD) && 1986 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) { 1987 assert(!F->arg_empty() && 1988 F->arg_begin()->getType() 1989 ->canLosslesslyBitCastTo(F->getReturnType()) && 1990 "unexpected this return"); 1991 F->addAttribute(1, llvm::Attribute::Returned); 1992 } 1993 1994 // Only a few attributes are set on declarations; these may later be 1995 // overridden by a definition. 1996 1997 setLinkageForGV(F, FD); 1998 setGVProperties(F, FD); 1999 2000 // Setup target-specific attributes. 2001 if (!IsIncompleteFunction && F->isDeclaration()) 2002 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this); 2003 2004 if (const auto *CSA = FD->getAttr<CodeSegAttr>()) 2005 F->setSection(CSA->getName()); 2006 else if (const auto *SA = FD->getAttr<SectionAttr>()) 2007 F->setSection(SA->getName()); 2008 2009 // If we plan on emitting this inline builtin, we can't treat it as a builtin. 2010 if (FD->isInlineBuiltinDeclaration()) { 2011 const FunctionDecl *FDBody; 2012 bool HasBody = FD->hasBody(FDBody); 2013 (void)HasBody; 2014 assert(HasBody && "Inline builtin declarations should always have an " 2015 "available body!"); 2016 if (shouldEmitFunction(FDBody)) 2017 F->addAttribute(llvm::AttributeList::FunctionIndex, 2018 llvm::Attribute::NoBuiltin); 2019 } 2020 2021 if (FD->isReplaceableGlobalAllocationFunction()) { 2022 // A replaceable global allocation function does not act like a builtin by 2023 // default, only if it is invoked by a new-expression or delete-expression. 2024 F->addAttribute(llvm::AttributeList::FunctionIndex, 2025 llvm::Attribute::NoBuiltin); 2026 } 2027 2028 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD)) 2029 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2030 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD)) 2031 if (MD->isVirtual()) 2032 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2033 2034 // Don't emit entries for function declarations in the cross-DSO mode. This 2035 // is handled with better precision by the receiving DSO. But if jump tables 2036 // are non-canonical then we need type metadata in order to produce the local 2037 // jump table. 2038 if (!CodeGenOpts.SanitizeCfiCrossDso || 2039 !CodeGenOpts.SanitizeCfiCanonicalJumpTables) 2040 CreateFunctionTypeMetadataForIcall(FD, F); 2041 2042 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>()) 2043 getOpenMPRuntime().emitDeclareSimdFunction(FD, F); 2044 2045 if (const auto *CB = FD->getAttr<CallbackAttr>()) { 2046 // Annotate the callback behavior as metadata: 2047 // - The callback callee (as argument number). 2048 // - The callback payloads (as argument numbers). 2049 llvm::LLVMContext &Ctx = F->getContext(); 2050 llvm::MDBuilder MDB(Ctx); 2051 2052 // The payload indices are all but the first one in the encoding. The first 2053 // identifies the callback callee. 2054 int CalleeIdx = *CB->encoding_begin(); 2055 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end()); 2056 F->addMetadata(llvm::LLVMContext::MD_callback, 2057 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding( 2058 CalleeIdx, PayloadIndices, 2059 /* VarArgsArePassed */ false)})); 2060 } 2061 } 2062 2063 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) { 2064 assert((isa<llvm::Function>(GV) || !GV->isDeclaration()) && 2065 "Only globals with definition can force usage."); 2066 LLVMUsed.emplace_back(GV); 2067 } 2068 2069 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) { 2070 assert(!GV->isDeclaration() && 2071 "Only globals with definition can force usage."); 2072 LLVMCompilerUsed.emplace_back(GV); 2073 } 2074 2075 static void emitUsed(CodeGenModule &CGM, StringRef Name, 2076 std::vector<llvm::WeakTrackingVH> &List) { 2077 // Don't create llvm.used if there is no need. 2078 if (List.empty()) 2079 return; 2080 2081 // Convert List to what ConstantArray needs. 2082 SmallVector<llvm::Constant*, 8> UsedArray; 2083 UsedArray.resize(List.size()); 2084 for (unsigned i = 0, e = List.size(); i != e; ++i) { 2085 UsedArray[i] = 2086 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast( 2087 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy); 2088 } 2089 2090 if (UsedArray.empty()) 2091 return; 2092 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size()); 2093 2094 auto *GV = new llvm::GlobalVariable( 2095 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage, 2096 llvm::ConstantArray::get(ATy, UsedArray), Name); 2097 2098 GV->setSection("llvm.metadata"); 2099 } 2100 2101 void CodeGenModule::emitLLVMUsed() { 2102 emitUsed(*this, "llvm.used", LLVMUsed); 2103 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed); 2104 } 2105 2106 void CodeGenModule::AppendLinkerOptions(StringRef Opts) { 2107 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts); 2108 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2109 } 2110 2111 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) { 2112 llvm::SmallString<32> Opt; 2113 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt); 2114 if (Opt.empty()) 2115 return; 2116 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2117 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts)); 2118 } 2119 2120 void CodeGenModule::AddDependentLib(StringRef Lib) { 2121 auto &C = getLLVMContext(); 2122 if (getTarget().getTriple().isOSBinFormatELF()) { 2123 ELFDependentLibraries.push_back( 2124 llvm::MDNode::get(C, llvm::MDString::get(C, Lib))); 2125 return; 2126 } 2127 2128 llvm::SmallString<24> Opt; 2129 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt); 2130 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt); 2131 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts)); 2132 } 2133 2134 /// Add link options implied by the given module, including modules 2135 /// it depends on, using a postorder walk. 2136 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod, 2137 SmallVectorImpl<llvm::MDNode *> &Metadata, 2138 llvm::SmallPtrSet<Module *, 16> &Visited) { 2139 // Import this module's parent. 2140 if (Mod->Parent && Visited.insert(Mod->Parent).second) { 2141 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited); 2142 } 2143 2144 // Import this module's dependencies. 2145 for (unsigned I = Mod->Imports.size(); I > 0; --I) { 2146 if (Visited.insert(Mod->Imports[I - 1]).second) 2147 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited); 2148 } 2149 2150 // Add linker options to link against the libraries/frameworks 2151 // described by this module. 2152 llvm::LLVMContext &Context = CGM.getLLVMContext(); 2153 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF(); 2154 2155 // For modules that use export_as for linking, use that module 2156 // name instead. 2157 if (Mod->UseExportAsModuleLinkName) 2158 return; 2159 2160 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) { 2161 // Link against a framework. Frameworks are currently Darwin only, so we 2162 // don't to ask TargetCodeGenInfo for the spelling of the linker option. 2163 if (Mod->LinkLibraries[I-1].IsFramework) { 2164 llvm::Metadata *Args[2] = { 2165 llvm::MDString::get(Context, "-framework"), 2166 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)}; 2167 2168 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2169 continue; 2170 } 2171 2172 // Link against a library. 2173 if (IsELF) { 2174 llvm::Metadata *Args[2] = { 2175 llvm::MDString::get(Context, "lib"), 2176 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library), 2177 }; 2178 Metadata.push_back(llvm::MDNode::get(Context, Args)); 2179 } else { 2180 llvm::SmallString<24> Opt; 2181 CGM.getTargetCodeGenInfo().getDependentLibraryOption( 2182 Mod->LinkLibraries[I - 1].Library, Opt); 2183 auto *OptString = llvm::MDString::get(Context, Opt); 2184 Metadata.push_back(llvm::MDNode::get(Context, OptString)); 2185 } 2186 } 2187 } 2188 2189 void CodeGenModule::EmitModuleLinkOptions() { 2190 // Collect the set of all of the modules we want to visit to emit link 2191 // options, which is essentially the imported modules and all of their 2192 // non-explicit child modules. 2193 llvm::SetVector<clang::Module *> LinkModules; 2194 llvm::SmallPtrSet<clang::Module *, 16> Visited; 2195 SmallVector<clang::Module *, 16> Stack; 2196 2197 // Seed the stack with imported modules. 2198 for (Module *M : ImportedModules) { 2199 // Do not add any link flags when an implementation TU of a module imports 2200 // a header of that same module. 2201 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule && 2202 !getLangOpts().isCompilingModule()) 2203 continue; 2204 if (Visited.insert(M).second) 2205 Stack.push_back(M); 2206 } 2207 2208 // Find all of the modules to import, making a little effort to prune 2209 // non-leaf modules. 2210 while (!Stack.empty()) { 2211 clang::Module *Mod = Stack.pop_back_val(); 2212 2213 bool AnyChildren = false; 2214 2215 // Visit the submodules of this module. 2216 for (const auto &SM : Mod->submodules()) { 2217 // Skip explicit children; they need to be explicitly imported to be 2218 // linked against. 2219 if (SM->IsExplicit) 2220 continue; 2221 2222 if (Visited.insert(SM).second) { 2223 Stack.push_back(SM); 2224 AnyChildren = true; 2225 } 2226 } 2227 2228 // We didn't find any children, so add this module to the list of 2229 // modules to link against. 2230 if (!AnyChildren) { 2231 LinkModules.insert(Mod); 2232 } 2233 } 2234 2235 // Add link options for all of the imported modules in reverse topological 2236 // order. We don't do anything to try to order import link flags with respect 2237 // to linker options inserted by things like #pragma comment(). 2238 SmallVector<llvm::MDNode *, 16> MetadataArgs; 2239 Visited.clear(); 2240 for (Module *M : LinkModules) 2241 if (Visited.insert(M).second) 2242 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited); 2243 std::reverse(MetadataArgs.begin(), MetadataArgs.end()); 2244 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end()); 2245 2246 // Add the linker options metadata flag. 2247 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options"); 2248 for (auto *MD : LinkerOptionsMetadata) 2249 NMD->addOperand(MD); 2250 } 2251 2252 void CodeGenModule::EmitDeferred() { 2253 // Emit deferred declare target declarations. 2254 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd) 2255 getOpenMPRuntime().emitDeferredTargetDecls(); 2256 2257 // Emit code for any potentially referenced deferred decls. Since a 2258 // previously unused static decl may become used during the generation of code 2259 // for a static function, iterate until no changes are made. 2260 2261 if (!DeferredVTables.empty()) { 2262 EmitDeferredVTables(); 2263 2264 // Emitting a vtable doesn't directly cause more vtables to 2265 // become deferred, although it can cause functions to be 2266 // emitted that then need those vtables. 2267 assert(DeferredVTables.empty()); 2268 } 2269 2270 // Emit CUDA/HIP static device variables referenced by host code only. 2271 if (getLangOpts().CUDA) 2272 for (auto V : getContext().CUDAStaticDeviceVarReferencedByHost) 2273 DeferredDeclsToEmit.push_back(V); 2274 2275 // Stop if we're out of both deferred vtables and deferred declarations. 2276 if (DeferredDeclsToEmit.empty()) 2277 return; 2278 2279 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more 2280 // work, it will not interfere with this. 2281 std::vector<GlobalDecl> CurDeclsToEmit; 2282 CurDeclsToEmit.swap(DeferredDeclsToEmit); 2283 2284 for (GlobalDecl &D : CurDeclsToEmit) { 2285 // We should call GetAddrOfGlobal with IsForDefinition set to true in order 2286 // to get GlobalValue with exactly the type we need, not something that 2287 // might had been created for another decl with the same mangled name but 2288 // different type. 2289 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>( 2290 GetAddrOfGlobal(D, ForDefinition)); 2291 2292 // In case of different address spaces, we may still get a cast, even with 2293 // IsForDefinition equal to true. Query mangled names table to get 2294 // GlobalValue. 2295 if (!GV) 2296 GV = GetGlobalValue(getMangledName(D)); 2297 2298 // Make sure GetGlobalValue returned non-null. 2299 assert(GV); 2300 2301 // Check to see if we've already emitted this. This is necessary 2302 // for a couple of reasons: first, decls can end up in the 2303 // deferred-decls queue multiple times, and second, decls can end 2304 // up with definitions in unusual ways (e.g. by an extern inline 2305 // function acquiring a strong function redefinition). Just 2306 // ignore these cases. 2307 if (!GV->isDeclaration()) 2308 continue; 2309 2310 // If this is OpenMP, check if it is legal to emit this global normally. 2311 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D)) 2312 continue; 2313 2314 // Otherwise, emit the definition and move on to the next one. 2315 EmitGlobalDefinition(D, GV); 2316 2317 // If we found out that we need to emit more decls, do that recursively. 2318 // This has the advantage that the decls are emitted in a DFS and related 2319 // ones are close together, which is convenient for testing. 2320 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) { 2321 EmitDeferred(); 2322 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty()); 2323 } 2324 } 2325 } 2326 2327 void CodeGenModule::EmitVTablesOpportunistically() { 2328 // Try to emit external vtables as available_externally if they have emitted 2329 // all inlined virtual functions. It runs after EmitDeferred() and therefore 2330 // is not allowed to create new references to things that need to be emitted 2331 // lazily. Note that it also uses fact that we eagerly emitting RTTI. 2332 2333 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables()) 2334 && "Only emit opportunistic vtables with optimizations"); 2335 2336 for (const CXXRecordDecl *RD : OpportunisticVTables) { 2337 assert(getVTables().isVTableExternal(RD) && 2338 "This queue should only contain external vtables"); 2339 if (getCXXABI().canSpeculativelyEmitVTable(RD)) 2340 VTables.GenerateClassData(RD); 2341 } 2342 OpportunisticVTables.clear(); 2343 } 2344 2345 void CodeGenModule::EmitGlobalAnnotations() { 2346 if (Annotations.empty()) 2347 return; 2348 2349 // Create a new global variable for the ConstantStruct in the Module. 2350 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get( 2351 Annotations[0]->getType(), Annotations.size()), Annotations); 2352 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false, 2353 llvm::GlobalValue::AppendingLinkage, 2354 Array, "llvm.global.annotations"); 2355 gv->setSection(AnnotationSection); 2356 } 2357 2358 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) { 2359 llvm::Constant *&AStr = AnnotationStrings[Str]; 2360 if (AStr) 2361 return AStr; 2362 2363 // Not found yet, create a new global. 2364 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str); 2365 auto *gv = 2366 new llvm::GlobalVariable(getModule(), s->getType(), true, 2367 llvm::GlobalValue::PrivateLinkage, s, ".str"); 2368 gv->setSection(AnnotationSection); 2369 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2370 AStr = gv; 2371 return gv; 2372 } 2373 2374 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) { 2375 SourceManager &SM = getContext().getSourceManager(); 2376 PresumedLoc PLoc = SM.getPresumedLoc(Loc); 2377 if (PLoc.isValid()) 2378 return EmitAnnotationString(PLoc.getFilename()); 2379 return EmitAnnotationString(SM.getBufferName(Loc)); 2380 } 2381 2382 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) { 2383 SourceManager &SM = getContext().getSourceManager(); 2384 PresumedLoc PLoc = SM.getPresumedLoc(L); 2385 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() : 2386 SM.getExpansionLineNumber(L); 2387 return llvm::ConstantInt::get(Int32Ty, LineNo); 2388 } 2389 2390 llvm::Constant *CodeGenModule::EmitAnnotationArgs(const AnnotateAttr *Attr) { 2391 ArrayRef<Expr *> Exprs = {Attr->args_begin(), Attr->args_size()}; 2392 if (Exprs.empty()) 2393 return llvm::ConstantPointerNull::get(Int8PtrTy); 2394 2395 llvm::FoldingSetNodeID ID; 2396 for (Expr *E : Exprs) { 2397 ID.Add(cast<clang::ConstantExpr>(E)->getAPValueResult()); 2398 } 2399 llvm::Constant *&Lookup = AnnotationArgs[ID.ComputeHash()]; 2400 if (Lookup) 2401 return Lookup; 2402 2403 llvm::SmallVector<llvm::Constant *, 4> LLVMArgs; 2404 LLVMArgs.reserve(Exprs.size()); 2405 ConstantEmitter ConstEmiter(*this); 2406 llvm::transform(Exprs, std::back_inserter(LLVMArgs), [&](const Expr *E) { 2407 const auto *CE = cast<clang::ConstantExpr>(E); 2408 return ConstEmiter.emitAbstract(CE->getBeginLoc(), CE->getAPValueResult(), 2409 CE->getType()); 2410 }); 2411 auto *Struct = llvm::ConstantStruct::getAnon(LLVMArgs); 2412 auto *GV = new llvm::GlobalVariable(getModule(), Struct->getType(), true, 2413 llvm::GlobalValue::PrivateLinkage, Struct, 2414 ".args"); 2415 GV->setSection(AnnotationSection); 2416 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 2417 auto *Bitcasted = llvm::ConstantExpr::getBitCast(GV, Int8PtrTy); 2418 2419 Lookup = Bitcasted; 2420 return Bitcasted; 2421 } 2422 2423 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV, 2424 const AnnotateAttr *AA, 2425 SourceLocation L) { 2426 // Get the globals for file name, annotation, and the line number. 2427 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()), 2428 *UnitGV = EmitAnnotationUnit(L), 2429 *LineNoCst = EmitAnnotationLineNo(L), 2430 *Args = EmitAnnotationArgs(AA); 2431 2432 llvm::Constant *ASZeroGV = GV; 2433 if (GV->getAddressSpace() != 0) { 2434 ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast( 2435 GV, GV->getValueType()->getPointerTo(0)); 2436 } 2437 2438 // Create the ConstantStruct for the global annotation. 2439 llvm::Constant *Fields[] = { 2440 llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy), 2441 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy), 2442 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy), 2443 LineNoCst, 2444 Args, 2445 }; 2446 return llvm::ConstantStruct::getAnon(Fields); 2447 } 2448 2449 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D, 2450 llvm::GlobalValue *GV) { 2451 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute"); 2452 // Get the struct elements for these annotations. 2453 for (const auto *I : D->specific_attrs<AnnotateAttr>()) 2454 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation())); 2455 } 2456 2457 bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind, 2458 llvm::Function *Fn, 2459 SourceLocation Loc) const { 2460 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 2461 // Blacklist by function name. 2462 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName())) 2463 return true; 2464 // Blacklist by location. 2465 if (Loc.isValid()) 2466 return SanitizerBL.isBlacklistedLocation(Kind, Loc); 2467 // If location is unknown, this may be a compiler-generated function. Assume 2468 // it's located in the main file. 2469 auto &SM = Context.getSourceManager(); 2470 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2471 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName()); 2472 } 2473 return false; 2474 } 2475 2476 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV, 2477 SourceLocation Loc, QualType Ty, 2478 StringRef Category) const { 2479 // For now globals can be blacklisted only in ASan and KASan. 2480 const SanitizerMask EnabledAsanMask = 2481 LangOpts.Sanitize.Mask & 2482 (SanitizerKind::Address | SanitizerKind::KernelAddress | 2483 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress | 2484 SanitizerKind::MemTag); 2485 if (!EnabledAsanMask) 2486 return false; 2487 const auto &SanitizerBL = getContext().getSanitizerBlacklist(); 2488 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category)) 2489 return true; 2490 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category)) 2491 return true; 2492 // Check global type. 2493 if (!Ty.isNull()) { 2494 // Drill down the array types: if global variable of a fixed type is 2495 // blacklisted, we also don't instrument arrays of them. 2496 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr())) 2497 Ty = AT->getElementType(); 2498 Ty = Ty.getCanonicalType().getUnqualifiedType(); 2499 // We allow to blacklist only record types (classes, structs etc.) 2500 if (Ty->isRecordType()) { 2501 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy()); 2502 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category)) 2503 return true; 2504 } 2505 } 2506 return false; 2507 } 2508 2509 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc, 2510 StringRef Category) const { 2511 const auto &XRayFilter = getContext().getXRayFilter(); 2512 using ImbueAttr = XRayFunctionFilter::ImbueAttribute; 2513 auto Attr = ImbueAttr::NONE; 2514 if (Loc.isValid()) 2515 Attr = XRayFilter.shouldImbueLocation(Loc, Category); 2516 if (Attr == ImbueAttr::NONE) 2517 Attr = XRayFilter.shouldImbueFunction(Fn->getName()); 2518 switch (Attr) { 2519 case ImbueAttr::NONE: 2520 return false; 2521 case ImbueAttr::ALWAYS: 2522 Fn->addFnAttr("function-instrument", "xray-always"); 2523 break; 2524 case ImbueAttr::ALWAYS_ARG1: 2525 Fn->addFnAttr("function-instrument", "xray-always"); 2526 Fn->addFnAttr("xray-log-args", "1"); 2527 break; 2528 case ImbueAttr::NEVER: 2529 Fn->addFnAttr("function-instrument", "xray-never"); 2530 break; 2531 } 2532 return true; 2533 } 2534 2535 bool CodeGenModule::isProfileInstrExcluded(llvm::Function *Fn, 2536 SourceLocation Loc) const { 2537 const auto &ProfileList = getContext().getProfileList(); 2538 // If the profile list is empty, then instrument everything. 2539 if (ProfileList.isEmpty()) 2540 return false; 2541 CodeGenOptions::ProfileInstrKind Kind = getCodeGenOpts().getProfileInstr(); 2542 // First, check the function name. 2543 Optional<bool> V = ProfileList.isFunctionExcluded(Fn->getName(), Kind); 2544 if (V.hasValue()) 2545 return *V; 2546 // Next, check the source location. 2547 if (Loc.isValid()) { 2548 Optional<bool> V = ProfileList.isLocationExcluded(Loc, Kind); 2549 if (V.hasValue()) 2550 return *V; 2551 } 2552 // If location is unknown, this may be a compiler-generated function. Assume 2553 // it's located in the main file. 2554 auto &SM = Context.getSourceManager(); 2555 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) { 2556 Optional<bool> V = ProfileList.isFileExcluded(MainFile->getName(), Kind); 2557 if (V.hasValue()) 2558 return *V; 2559 } 2560 return ProfileList.getDefault(); 2561 } 2562 2563 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) { 2564 // Never defer when EmitAllDecls is specified. 2565 if (LangOpts.EmitAllDecls) 2566 return true; 2567 2568 if (CodeGenOpts.KeepStaticConsts) { 2569 const auto *VD = dyn_cast<VarDecl>(Global); 2570 if (VD && VD->getType().isConstQualified() && 2571 VD->getStorageDuration() == SD_Static) 2572 return true; 2573 } 2574 2575 return getContext().DeclMustBeEmitted(Global); 2576 } 2577 2578 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) { 2579 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2580 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation) 2581 // Implicit template instantiations may change linkage if they are later 2582 // explicitly instantiated, so they should not be emitted eagerly. 2583 return false; 2584 // In OpenMP 5.0 function may be marked as device_type(nohost) and we should 2585 // not emit them eagerly unless we sure that the function must be emitted on 2586 // the host. 2587 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd && 2588 !LangOpts.OpenMPIsDevice && 2589 !OMPDeclareTargetDeclAttr::getDeviceType(FD) && 2590 !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced()) 2591 return false; 2592 } 2593 if (const auto *VD = dyn_cast<VarDecl>(Global)) 2594 if (Context.getInlineVariableDefinitionKind(VD) == 2595 ASTContext::InlineVariableDefinitionKind::WeakUnknown) 2596 // A definition of an inline constexpr static data member may change 2597 // linkage later if it's redeclared outside the class. 2598 return false; 2599 // If OpenMP is enabled and threadprivates must be generated like TLS, delay 2600 // codegen for global variables, because they may be marked as threadprivate. 2601 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS && 2602 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) && 2603 !isTypeConstant(Global->getType(), false) && 2604 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global)) 2605 return false; 2606 2607 return true; 2608 } 2609 2610 ConstantAddress CodeGenModule::GetAddrOfMSGuidDecl(const MSGuidDecl *GD) { 2611 StringRef Name = getMangledName(GD); 2612 2613 // The UUID descriptor should be pointer aligned. 2614 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes); 2615 2616 // Look for an existing global. 2617 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 2618 return ConstantAddress(GV, Alignment); 2619 2620 ConstantEmitter Emitter(*this); 2621 llvm::Constant *Init; 2622 2623 APValue &V = GD->getAsAPValue(); 2624 if (!V.isAbsent()) { 2625 // If possible, emit the APValue version of the initializer. In particular, 2626 // this gets the type of the constant right. 2627 Init = Emitter.emitForInitializer( 2628 GD->getAsAPValue(), GD->getType().getAddressSpace(), GD->getType()); 2629 } else { 2630 // As a fallback, directly construct the constant. 2631 // FIXME: This may get padding wrong under esoteric struct layout rules. 2632 // MSVC appears to create a complete type 'struct __s_GUID' that it 2633 // presumably uses to represent these constants. 2634 MSGuidDecl::Parts Parts = GD->getParts(); 2635 llvm::Constant *Fields[4] = { 2636 llvm::ConstantInt::get(Int32Ty, Parts.Part1), 2637 llvm::ConstantInt::get(Int16Ty, Parts.Part2), 2638 llvm::ConstantInt::get(Int16Ty, Parts.Part3), 2639 llvm::ConstantDataArray::getRaw( 2640 StringRef(reinterpret_cast<char *>(Parts.Part4And5), 8), 8, 2641 Int8Ty)}; 2642 Init = llvm::ConstantStruct::getAnon(Fields); 2643 } 2644 2645 auto *GV = new llvm::GlobalVariable( 2646 getModule(), Init->getType(), 2647 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2648 if (supportsCOMDAT()) 2649 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2650 setDSOLocal(GV); 2651 2652 llvm::Constant *Addr = GV; 2653 if (!V.isAbsent()) { 2654 Emitter.finalize(GV); 2655 } else { 2656 llvm::Type *Ty = getTypes().ConvertTypeForMem(GD->getType()); 2657 Addr = llvm::ConstantExpr::getBitCast( 2658 GV, Ty->getPointerTo(GV->getAddressSpace())); 2659 } 2660 return ConstantAddress(Addr, Alignment); 2661 } 2662 2663 ConstantAddress CodeGenModule::GetAddrOfTemplateParamObject( 2664 const TemplateParamObjectDecl *TPO) { 2665 StringRef Name = getMangledName(TPO); 2666 CharUnits Alignment = getNaturalTypeAlignment(TPO->getType()); 2667 2668 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name)) 2669 return ConstantAddress(GV, Alignment); 2670 2671 ConstantEmitter Emitter(*this); 2672 llvm::Constant *Init = Emitter.emitForInitializer( 2673 TPO->getValue(), TPO->getType().getAddressSpace(), TPO->getType()); 2674 2675 if (!Init) { 2676 ErrorUnsupported(TPO, "template parameter object"); 2677 return ConstantAddress::invalid(); 2678 } 2679 2680 auto *GV = new llvm::GlobalVariable( 2681 getModule(), Init->getType(), 2682 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name); 2683 if (supportsCOMDAT()) 2684 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 2685 Emitter.finalize(GV); 2686 2687 return ConstantAddress(GV, Alignment); 2688 } 2689 2690 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) { 2691 const AliasAttr *AA = VD->getAttr<AliasAttr>(); 2692 assert(AA && "No alias?"); 2693 2694 CharUnits Alignment = getContext().getDeclAlign(VD); 2695 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType()); 2696 2697 // See if there is already something with the target's name in the module. 2698 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee()); 2699 if (Entry) { 2700 unsigned AS = getContext().getTargetAddressSpace(VD->getType()); 2701 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS)); 2702 return ConstantAddress(Ptr, Alignment); 2703 } 2704 2705 llvm::Constant *Aliasee; 2706 if (isa<llvm::FunctionType>(DeclTy)) 2707 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, 2708 GlobalDecl(cast<FunctionDecl>(VD)), 2709 /*ForVTable=*/false); 2710 else 2711 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 2712 llvm::PointerType::getUnqual(DeclTy), 2713 nullptr); 2714 2715 auto *F = cast<llvm::GlobalValue>(Aliasee); 2716 F->setLinkage(llvm::Function::ExternalWeakLinkage); 2717 WeakRefReferences.insert(F); 2718 2719 return ConstantAddress(Aliasee, Alignment); 2720 } 2721 2722 void CodeGenModule::EmitGlobal(GlobalDecl GD) { 2723 const auto *Global = cast<ValueDecl>(GD.getDecl()); 2724 2725 // Weak references don't produce any output by themselves. 2726 if (Global->hasAttr<WeakRefAttr>()) 2727 return; 2728 2729 // If this is an alias definition (which otherwise looks like a declaration) 2730 // emit it now. 2731 if (Global->hasAttr<AliasAttr>()) 2732 return EmitAliasDefinition(GD); 2733 2734 // IFunc like an alias whose value is resolved at runtime by calling resolver. 2735 if (Global->hasAttr<IFuncAttr>()) 2736 return emitIFuncDefinition(GD); 2737 2738 // If this is a cpu_dispatch multiversion function, emit the resolver. 2739 if (Global->hasAttr<CPUDispatchAttr>()) 2740 return emitCPUDispatchDefinition(GD); 2741 2742 // If this is CUDA, be selective about which declarations we emit. 2743 if (LangOpts.CUDA) { 2744 if (LangOpts.CUDAIsDevice) { 2745 if (!Global->hasAttr<CUDADeviceAttr>() && 2746 !Global->hasAttr<CUDAGlobalAttr>() && 2747 !Global->hasAttr<CUDAConstantAttr>() && 2748 !Global->hasAttr<CUDASharedAttr>() && 2749 !Global->getType()->isCUDADeviceBuiltinSurfaceType() && 2750 !Global->getType()->isCUDADeviceBuiltinTextureType()) 2751 return; 2752 } else { 2753 // We need to emit host-side 'shadows' for all global 2754 // device-side variables because the CUDA runtime needs their 2755 // size and host-side address in order to provide access to 2756 // their device-side incarnations. 2757 2758 // So device-only functions are the only things we skip. 2759 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() && 2760 Global->hasAttr<CUDADeviceAttr>()) 2761 return; 2762 2763 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) && 2764 "Expected Variable or Function"); 2765 } 2766 } 2767 2768 if (LangOpts.OpenMP) { 2769 // If this is OpenMP, check if it is legal to emit this global normally. 2770 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD)) 2771 return; 2772 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) { 2773 if (MustBeEmitted(Global)) 2774 EmitOMPDeclareReduction(DRD); 2775 return; 2776 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) { 2777 if (MustBeEmitted(Global)) 2778 EmitOMPDeclareMapper(DMD); 2779 return; 2780 } 2781 } 2782 2783 // Ignore declarations, they will be emitted on their first use. 2784 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) { 2785 // Forward declarations are emitted lazily on first use. 2786 if (!FD->doesThisDeclarationHaveABody()) { 2787 if (!FD->doesDeclarationForceExternallyVisibleDefinition()) 2788 return; 2789 2790 StringRef MangledName = getMangledName(GD); 2791 2792 // Compute the function info and LLVM type. 2793 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 2794 llvm::Type *Ty = getTypes().GetFunctionType(FI); 2795 2796 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false, 2797 /*DontDefer=*/false); 2798 return; 2799 } 2800 } else { 2801 const auto *VD = cast<VarDecl>(Global); 2802 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global."); 2803 if (VD->isThisDeclarationADefinition() != VarDecl::Definition && 2804 !Context.isMSStaticDataMemberInlineDefinition(VD)) { 2805 if (LangOpts.OpenMP) { 2806 // Emit declaration of the must-be-emitted declare target variable. 2807 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res = 2808 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) { 2809 bool UnifiedMemoryEnabled = 2810 getOpenMPRuntime().hasRequiresUnifiedSharedMemory(); 2811 if (*Res == OMPDeclareTargetDeclAttr::MT_To && 2812 !UnifiedMemoryEnabled) { 2813 (void)GetAddrOfGlobalVar(VD); 2814 } else { 2815 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) || 2816 (*Res == OMPDeclareTargetDeclAttr::MT_To && 2817 UnifiedMemoryEnabled)) && 2818 "Link clause or to clause with unified memory expected."); 2819 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD); 2820 } 2821 2822 return; 2823 } 2824 } 2825 // If this declaration may have caused an inline variable definition to 2826 // change linkage, make sure that it's emitted. 2827 if (Context.getInlineVariableDefinitionKind(VD) == 2828 ASTContext::InlineVariableDefinitionKind::Strong) 2829 GetAddrOfGlobalVar(VD); 2830 return; 2831 } 2832 } 2833 2834 // Defer code generation to first use when possible, e.g. if this is an inline 2835 // function. If the global must always be emitted, do it eagerly if possible 2836 // to benefit from cache locality. 2837 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) { 2838 // Emit the definition if it can't be deferred. 2839 EmitGlobalDefinition(GD); 2840 return; 2841 } 2842 2843 // If we're deferring emission of a C++ variable with an 2844 // initializer, remember the order in which it appeared in the file. 2845 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) && 2846 cast<VarDecl>(Global)->hasInit()) { 2847 DelayedCXXInitPosition[Global] = CXXGlobalInits.size(); 2848 CXXGlobalInits.push_back(nullptr); 2849 } 2850 2851 StringRef MangledName = getMangledName(GD); 2852 if (GetGlobalValue(MangledName) != nullptr) { 2853 // The value has already been used and should therefore be emitted. 2854 addDeferredDeclToEmit(GD); 2855 } else if (MustBeEmitted(Global)) { 2856 // The value must be emitted, but cannot be emitted eagerly. 2857 assert(!MayBeEmittedEagerly(Global)); 2858 addDeferredDeclToEmit(GD); 2859 } else { 2860 // Otherwise, remember that we saw a deferred decl with this name. The 2861 // first use of the mangled name will cause it to move into 2862 // DeferredDeclsToEmit. 2863 DeferredDecls[MangledName] = GD; 2864 } 2865 } 2866 2867 // Check if T is a class type with a destructor that's not dllimport. 2868 static bool HasNonDllImportDtor(QualType T) { 2869 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>()) 2870 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) 2871 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>()) 2872 return true; 2873 2874 return false; 2875 } 2876 2877 namespace { 2878 struct FunctionIsDirectlyRecursive 2879 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> { 2880 const StringRef Name; 2881 const Builtin::Context &BI; 2882 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) 2883 : Name(N), BI(C) {} 2884 2885 bool VisitCallExpr(const CallExpr *E) { 2886 const FunctionDecl *FD = E->getDirectCallee(); 2887 if (!FD) 2888 return false; 2889 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 2890 if (Attr && Name == Attr->getLabel()) 2891 return true; 2892 unsigned BuiltinID = FD->getBuiltinID(); 2893 if (!BuiltinID || !BI.isLibFunction(BuiltinID)) 2894 return false; 2895 StringRef BuiltinName = BI.getName(BuiltinID); 2896 if (BuiltinName.startswith("__builtin_") && 2897 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) { 2898 return true; 2899 } 2900 return false; 2901 } 2902 2903 bool VisitStmt(const Stmt *S) { 2904 for (const Stmt *Child : S->children()) 2905 if (Child && this->Visit(Child)) 2906 return true; 2907 return false; 2908 } 2909 }; 2910 2911 // Make sure we're not referencing non-imported vars or functions. 2912 struct DLLImportFunctionVisitor 2913 : public RecursiveASTVisitor<DLLImportFunctionVisitor> { 2914 bool SafeToInline = true; 2915 2916 bool shouldVisitImplicitCode() const { return true; } 2917 2918 bool VisitVarDecl(VarDecl *VD) { 2919 if (VD->getTLSKind()) { 2920 // A thread-local variable cannot be imported. 2921 SafeToInline = false; 2922 return SafeToInline; 2923 } 2924 2925 // A variable definition might imply a destructor call. 2926 if (VD->isThisDeclarationADefinition()) 2927 SafeToInline = !HasNonDllImportDtor(VD->getType()); 2928 2929 return SafeToInline; 2930 } 2931 2932 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 2933 if (const auto *D = E->getTemporary()->getDestructor()) 2934 SafeToInline = D->hasAttr<DLLImportAttr>(); 2935 return SafeToInline; 2936 } 2937 2938 bool VisitDeclRefExpr(DeclRefExpr *E) { 2939 ValueDecl *VD = E->getDecl(); 2940 if (isa<FunctionDecl>(VD)) 2941 SafeToInline = VD->hasAttr<DLLImportAttr>(); 2942 else if (VarDecl *V = dyn_cast<VarDecl>(VD)) 2943 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>(); 2944 return SafeToInline; 2945 } 2946 2947 bool VisitCXXConstructExpr(CXXConstructExpr *E) { 2948 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>(); 2949 return SafeToInline; 2950 } 2951 2952 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 2953 CXXMethodDecl *M = E->getMethodDecl(); 2954 if (!M) { 2955 // Call through a pointer to member function. This is safe to inline. 2956 SafeToInline = true; 2957 } else { 2958 SafeToInline = M->hasAttr<DLLImportAttr>(); 2959 } 2960 return SafeToInline; 2961 } 2962 2963 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) { 2964 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>(); 2965 return SafeToInline; 2966 } 2967 2968 bool VisitCXXNewExpr(CXXNewExpr *E) { 2969 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>(); 2970 return SafeToInline; 2971 } 2972 }; 2973 } 2974 2975 // isTriviallyRecursive - Check if this function calls another 2976 // decl that, because of the asm attribute or the other decl being a builtin, 2977 // ends up pointing to itself. 2978 bool 2979 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) { 2980 StringRef Name; 2981 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) { 2982 // asm labels are a special kind of mangling we have to support. 2983 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>(); 2984 if (!Attr) 2985 return false; 2986 Name = Attr->getLabel(); 2987 } else { 2988 Name = FD->getName(); 2989 } 2990 2991 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo); 2992 const Stmt *Body = FD->getBody(); 2993 return Body ? Walker.Visit(Body) : false; 2994 } 2995 2996 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) { 2997 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage) 2998 return true; 2999 const auto *F = cast<FunctionDecl>(GD.getDecl()); 3000 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>()) 3001 return false; 3002 3003 if (F->hasAttr<DLLImportAttr>() && !F->hasAttr<AlwaysInlineAttr>()) { 3004 // Check whether it would be safe to inline this dllimport function. 3005 DLLImportFunctionVisitor Visitor; 3006 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F)); 3007 if (!Visitor.SafeToInline) 3008 return false; 3009 3010 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) { 3011 // Implicit destructor invocations aren't captured in the AST, so the 3012 // check above can't see them. Check for them manually here. 3013 for (const Decl *Member : Dtor->getParent()->decls()) 3014 if (isa<FieldDecl>(Member)) 3015 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType())) 3016 return false; 3017 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases()) 3018 if (HasNonDllImportDtor(B.getType())) 3019 return false; 3020 } 3021 } 3022 3023 // PR9614. Avoid cases where the source code is lying to us. An available 3024 // externally function should have an equivalent function somewhere else, 3025 // but a function that calls itself through asm label/`__builtin_` trickery is 3026 // clearly not equivalent to the real implementation. 3027 // This happens in glibc's btowc and in some configure checks. 3028 return !isTriviallyRecursive(F); 3029 } 3030 3031 bool CodeGenModule::shouldOpportunisticallyEmitVTables() { 3032 return CodeGenOpts.OptimizationLevel > 0; 3033 } 3034 3035 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD, 3036 llvm::GlobalValue *GV) { 3037 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3038 3039 if (FD->isCPUSpecificMultiVersion()) { 3040 auto *Spec = FD->getAttr<CPUSpecificAttr>(); 3041 for (unsigned I = 0; I < Spec->cpus_size(); ++I) 3042 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr); 3043 // Requires multiple emits. 3044 } else 3045 EmitGlobalFunctionDefinition(GD, GV); 3046 } 3047 3048 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) { 3049 const auto *D = cast<ValueDecl>(GD.getDecl()); 3050 3051 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(), 3052 Context.getSourceManager(), 3053 "Generating code for declaration"); 3054 3055 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 3056 // At -O0, don't generate IR for functions with available_externally 3057 // linkage. 3058 if (!shouldEmitFunction(GD)) 3059 return; 3060 3061 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() { 3062 std::string Name; 3063 llvm::raw_string_ostream OS(Name); 3064 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(), 3065 /*Qualified=*/true); 3066 return Name; 3067 }); 3068 3069 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) { 3070 // Make sure to emit the definition(s) before we emit the thunks. 3071 // This is necessary for the generation of certain thunks. 3072 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method)) 3073 ABI->emitCXXStructor(GD); 3074 else if (FD->isMultiVersion()) 3075 EmitMultiVersionFunctionDefinition(GD, GV); 3076 else 3077 EmitGlobalFunctionDefinition(GD, GV); 3078 3079 if (Method->isVirtual()) 3080 getVTables().EmitThunks(GD); 3081 3082 return; 3083 } 3084 3085 if (FD->isMultiVersion()) 3086 return EmitMultiVersionFunctionDefinition(GD, GV); 3087 return EmitGlobalFunctionDefinition(GD, GV); 3088 } 3089 3090 if (const auto *VD = dyn_cast<VarDecl>(D)) 3091 return EmitGlobalVarDefinition(VD, !VD->hasDefinition()); 3092 3093 llvm_unreachable("Invalid argument to EmitGlobalDefinition()"); 3094 } 3095 3096 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 3097 llvm::Function *NewFn); 3098 3099 static unsigned 3100 TargetMVPriority(const TargetInfo &TI, 3101 const CodeGenFunction::MultiVersionResolverOption &RO) { 3102 unsigned Priority = 0; 3103 for (StringRef Feat : RO.Conditions.Features) 3104 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat)); 3105 3106 if (!RO.Conditions.Architecture.empty()) 3107 Priority = std::max( 3108 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture)); 3109 return Priority; 3110 } 3111 3112 void CodeGenModule::emitMultiVersionFunctions() { 3113 for (GlobalDecl GD : MultiVersionFuncs) { 3114 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3115 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 3116 getContext().forEachMultiversionedFunctionVersion( 3117 FD, [this, &GD, &Options](const FunctionDecl *CurFD) { 3118 GlobalDecl CurGD{ 3119 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)}; 3120 StringRef MangledName = getMangledName(CurGD); 3121 llvm::Constant *Func = GetGlobalValue(MangledName); 3122 if (!Func) { 3123 if (CurFD->isDefined()) { 3124 EmitGlobalFunctionDefinition(CurGD, nullptr); 3125 Func = GetGlobalValue(MangledName); 3126 } else { 3127 const CGFunctionInfo &FI = 3128 getTypes().arrangeGlobalDeclaration(GD); 3129 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3130 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false, 3131 /*DontDefer=*/false, ForDefinition); 3132 } 3133 assert(Func && "This should have just been created"); 3134 } 3135 3136 const auto *TA = CurFD->getAttr<TargetAttr>(); 3137 llvm::SmallVector<StringRef, 8> Feats; 3138 TA->getAddedFeatures(Feats); 3139 3140 Options.emplace_back(cast<llvm::Function>(Func), 3141 TA->getArchitecture(), Feats); 3142 }); 3143 3144 llvm::Function *ResolverFunc; 3145 const TargetInfo &TI = getTarget(); 3146 3147 if (TI.supportsIFunc() || FD->isTargetMultiVersion()) { 3148 ResolverFunc = cast<llvm::Function>( 3149 GetGlobalValue((getMangledName(GD) + ".resolver").str())); 3150 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage); 3151 } else { 3152 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD))); 3153 } 3154 3155 if (supportsCOMDAT()) 3156 ResolverFunc->setComdat( 3157 getModule().getOrInsertComdat(ResolverFunc->getName())); 3158 3159 llvm::stable_sort( 3160 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS, 3161 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3162 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS); 3163 }); 3164 CodeGenFunction CGF(*this); 3165 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3166 } 3167 } 3168 3169 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) { 3170 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3171 assert(FD && "Not a FunctionDecl?"); 3172 const auto *DD = FD->getAttr<CPUDispatchAttr>(); 3173 assert(DD && "Not a cpu_dispatch Function?"); 3174 llvm::Type *DeclTy = getTypes().ConvertType(FD->getType()); 3175 3176 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) { 3177 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD); 3178 DeclTy = getTypes().GetFunctionType(FInfo); 3179 } 3180 3181 StringRef ResolverName = getMangledName(GD); 3182 3183 llvm::Type *ResolverType; 3184 GlobalDecl ResolverGD; 3185 if (getTarget().supportsIFunc()) 3186 ResolverType = llvm::FunctionType::get( 3187 llvm::PointerType::get(DeclTy, 3188 Context.getTargetAddressSpace(FD->getType())), 3189 false); 3190 else { 3191 ResolverType = DeclTy; 3192 ResolverGD = GD; 3193 } 3194 3195 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction( 3196 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false)); 3197 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage); 3198 if (supportsCOMDAT()) 3199 ResolverFunc->setComdat( 3200 getModule().getOrInsertComdat(ResolverFunc->getName())); 3201 3202 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options; 3203 const TargetInfo &Target = getTarget(); 3204 unsigned Index = 0; 3205 for (const IdentifierInfo *II : DD->cpus()) { 3206 // Get the name of the target function so we can look it up/create it. 3207 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) + 3208 getCPUSpecificMangling(*this, II->getName()); 3209 3210 llvm::Constant *Func = GetGlobalValue(MangledName); 3211 3212 if (!Func) { 3213 GlobalDecl ExistingDecl = Manglings.lookup(MangledName); 3214 if (ExistingDecl.getDecl() && 3215 ExistingDecl.getDecl()->getAsFunction()->isDefined()) { 3216 EmitGlobalFunctionDefinition(ExistingDecl, nullptr); 3217 Func = GetGlobalValue(MangledName); 3218 } else { 3219 if (!ExistingDecl.getDecl()) 3220 ExistingDecl = GD.getWithMultiVersionIndex(Index); 3221 3222 Func = GetOrCreateLLVMFunction( 3223 MangledName, DeclTy, ExistingDecl, 3224 /*ForVTable=*/false, /*DontDefer=*/true, 3225 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition); 3226 } 3227 } 3228 3229 llvm::SmallVector<StringRef, 32> Features; 3230 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features); 3231 llvm::transform(Features, Features.begin(), 3232 [](StringRef Str) { return Str.substr(1); }); 3233 Features.erase(std::remove_if( 3234 Features.begin(), Features.end(), [&Target](StringRef Feat) { 3235 return !Target.validateCpuSupports(Feat); 3236 }), Features.end()); 3237 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features); 3238 ++Index; 3239 } 3240 3241 llvm::sort( 3242 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS, 3243 const CodeGenFunction::MultiVersionResolverOption &RHS) { 3244 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) > 3245 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features); 3246 }); 3247 3248 // If the list contains multiple 'default' versions, such as when it contains 3249 // 'pentium' and 'generic', don't emit the call to the generic one (since we 3250 // always run on at least a 'pentium'). We do this by deleting the 'least 3251 // advanced' (read, lowest mangling letter). 3252 while (Options.size() > 1 && 3253 CodeGenFunction::GetX86CpuSupportsMask( 3254 (Options.end() - 2)->Conditions.Features) == 0) { 3255 StringRef LHSName = (Options.end() - 2)->Function->getName(); 3256 StringRef RHSName = (Options.end() - 1)->Function->getName(); 3257 if (LHSName.compare(RHSName) < 0) 3258 Options.erase(Options.end() - 2); 3259 else 3260 Options.erase(Options.end() - 1); 3261 } 3262 3263 CodeGenFunction CGF(*this); 3264 CGF.EmitMultiVersionResolver(ResolverFunc, Options); 3265 3266 if (getTarget().supportsIFunc()) { 3267 std::string AliasName = getMangledNameImpl( 3268 *this, GD, FD, /*OmitMultiVersionMangling=*/true); 3269 llvm::Constant *AliasFunc = GetGlobalValue(AliasName); 3270 if (!AliasFunc) { 3271 auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction( 3272 AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true, 3273 /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition)); 3274 auto *GA = llvm::GlobalAlias::create( 3275 DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule()); 3276 GA->setLinkage(llvm::Function::WeakODRLinkage); 3277 SetCommonAttributes(GD, GA); 3278 } 3279 } 3280 } 3281 3282 /// If a dispatcher for the specified mangled name is not in the module, create 3283 /// and return an llvm Function with the specified type. 3284 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver( 3285 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) { 3286 std::string MangledName = 3287 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true); 3288 3289 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has 3290 // a separate resolver). 3291 std::string ResolverName = MangledName; 3292 if (getTarget().supportsIFunc()) 3293 ResolverName += ".ifunc"; 3294 else if (FD->isTargetMultiVersion()) 3295 ResolverName += ".resolver"; 3296 3297 // If this already exists, just return that one. 3298 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName)) 3299 return ResolverGV; 3300 3301 // Since this is the first time we've created this IFunc, make sure 3302 // that we put this multiversioned function into the list to be 3303 // replaced later if necessary (target multiversioning only). 3304 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion()) 3305 MultiVersionFuncs.push_back(GD); 3306 3307 if (getTarget().supportsIFunc()) { 3308 llvm::Type *ResolverType = llvm::FunctionType::get( 3309 llvm::PointerType::get( 3310 DeclTy, getContext().getTargetAddressSpace(FD->getType())), 3311 false); 3312 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3313 MangledName + ".resolver", ResolverType, GlobalDecl{}, 3314 /*ForVTable=*/false); 3315 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create( 3316 DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule()); 3317 GIF->setName(ResolverName); 3318 SetCommonAttributes(FD, GIF); 3319 3320 return GIF; 3321 } 3322 3323 llvm::Constant *Resolver = GetOrCreateLLVMFunction( 3324 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false); 3325 assert(isa<llvm::GlobalValue>(Resolver) && 3326 "Resolver should be created for the first time"); 3327 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver)); 3328 return Resolver; 3329 } 3330 3331 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the 3332 /// module, create and return an llvm Function with the specified type. If there 3333 /// is something in the module with the specified name, return it potentially 3334 /// bitcasted to the right type. 3335 /// 3336 /// If D is non-null, it specifies a decl that correspond to this. This is used 3337 /// to set the attributes on the function when it is first created. 3338 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction( 3339 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable, 3340 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs, 3341 ForDefinition_t IsForDefinition) { 3342 const Decl *D = GD.getDecl(); 3343 3344 // Any attempts to use a MultiVersion function should result in retrieving 3345 // the iFunc instead. Name Mangling will handle the rest of the changes. 3346 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) { 3347 // For the device mark the function as one that should be emitted. 3348 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime && 3349 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() && 3350 !DontDefer && !IsForDefinition) { 3351 if (const FunctionDecl *FDDef = FD->getDefinition()) { 3352 GlobalDecl GDDef; 3353 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef)) 3354 GDDef = GlobalDecl(CD, GD.getCtorType()); 3355 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef)) 3356 GDDef = GlobalDecl(DD, GD.getDtorType()); 3357 else 3358 GDDef = GlobalDecl(FDDef); 3359 EmitGlobal(GDDef); 3360 } 3361 } 3362 3363 if (FD->isMultiVersion()) { 3364 if (FD->hasAttr<TargetAttr>()) 3365 UpdateMultiVersionNames(GD, FD); 3366 if (!IsForDefinition) 3367 return GetOrCreateMultiVersionResolver(GD, Ty, FD); 3368 } 3369 } 3370 3371 // Lookup the entry, lazily creating it if necessary. 3372 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3373 if (Entry) { 3374 if (WeakRefReferences.erase(Entry)) { 3375 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D); 3376 if (FD && !FD->hasAttr<WeakAttr>()) 3377 Entry->setLinkage(llvm::Function::ExternalLinkage); 3378 } 3379 3380 // Handle dropped DLL attributes. 3381 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) { 3382 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3383 setDSOLocal(Entry); 3384 } 3385 3386 // If there are two attempts to define the same mangled name, issue an 3387 // error. 3388 if (IsForDefinition && !Entry->isDeclaration()) { 3389 GlobalDecl OtherGD; 3390 // Check that GD is not yet in DiagnosedConflictingDefinitions is required 3391 // to make sure that we issue an error only once. 3392 if (lookupRepresentativeDecl(MangledName, OtherGD) && 3393 (GD.getCanonicalDecl().getDecl() != 3394 OtherGD.getCanonicalDecl().getDecl()) && 3395 DiagnosedConflictingDefinitions.insert(GD).second) { 3396 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3397 << MangledName; 3398 getDiags().Report(OtherGD.getDecl()->getLocation(), 3399 diag::note_previous_definition); 3400 } 3401 } 3402 3403 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) && 3404 (Entry->getValueType() == Ty)) { 3405 return Entry; 3406 } 3407 3408 // Make sure the result is of the correct type. 3409 // (If function is requested for a definition, we always need to create a new 3410 // function, not just return a bitcast.) 3411 if (!IsForDefinition) 3412 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo()); 3413 } 3414 3415 // This function doesn't have a complete type (for example, the return 3416 // type is an incomplete struct). Use a fake type instead, and make 3417 // sure not to try to set attributes. 3418 bool IsIncompleteFunction = false; 3419 3420 llvm::FunctionType *FTy; 3421 if (isa<llvm::FunctionType>(Ty)) { 3422 FTy = cast<llvm::FunctionType>(Ty); 3423 } else { 3424 FTy = llvm::FunctionType::get(VoidTy, false); 3425 IsIncompleteFunction = true; 3426 } 3427 3428 llvm::Function *F = 3429 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage, 3430 Entry ? StringRef() : MangledName, &getModule()); 3431 3432 // If we already created a function with the same mangled name (but different 3433 // type) before, take its name and add it to the list of functions to be 3434 // replaced with F at the end of CodeGen. 3435 // 3436 // This happens if there is a prototype for a function (e.g. "int f()") and 3437 // then a definition of a different type (e.g. "int f(int x)"). 3438 if (Entry) { 3439 F->takeName(Entry); 3440 3441 // This might be an implementation of a function without a prototype, in 3442 // which case, try to do special replacement of calls which match the new 3443 // prototype. The really key thing here is that we also potentially drop 3444 // arguments from the call site so as to make a direct call, which makes the 3445 // inliner happier and suppresses a number of optimizer warnings (!) about 3446 // dropping arguments. 3447 if (!Entry->use_empty()) { 3448 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F); 3449 Entry->removeDeadConstantUsers(); 3450 } 3451 3452 llvm::Constant *BC = llvm::ConstantExpr::getBitCast( 3453 F, Entry->getValueType()->getPointerTo()); 3454 addGlobalValReplacement(Entry, BC); 3455 } 3456 3457 assert(F->getName() == MangledName && "name was uniqued!"); 3458 if (D) 3459 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk); 3460 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) { 3461 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex); 3462 F->addAttributes(llvm::AttributeList::FunctionIndex, B); 3463 } 3464 3465 if (!DontDefer) { 3466 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to 3467 // each other bottoming out with the base dtor. Therefore we emit non-base 3468 // dtors on usage, even if there is no dtor definition in the TU. 3469 if (D && isa<CXXDestructorDecl>(D) && 3470 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D), 3471 GD.getDtorType())) 3472 addDeferredDeclToEmit(GD); 3473 3474 // This is the first use or definition of a mangled name. If there is a 3475 // deferred decl with this name, remember that we need to emit it at the end 3476 // of the file. 3477 auto DDI = DeferredDecls.find(MangledName); 3478 if (DDI != DeferredDecls.end()) { 3479 // Move the potentially referenced deferred decl to the 3480 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we 3481 // don't need it anymore). 3482 addDeferredDeclToEmit(DDI->second); 3483 DeferredDecls.erase(DDI); 3484 3485 // Otherwise, there are cases we have to worry about where we're 3486 // using a declaration for which we must emit a definition but where 3487 // we might not find a top-level definition: 3488 // - member functions defined inline in their classes 3489 // - friend functions defined inline in some class 3490 // - special member functions with implicit definitions 3491 // If we ever change our AST traversal to walk into class methods, 3492 // this will be unnecessary. 3493 // 3494 // We also don't emit a definition for a function if it's going to be an 3495 // entry in a vtable, unless it's already marked as used. 3496 } else if (getLangOpts().CPlusPlus && D) { 3497 // Look for a declaration that's lexically in a record. 3498 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD; 3499 FD = FD->getPreviousDecl()) { 3500 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) { 3501 if (FD->doesThisDeclarationHaveABody()) { 3502 addDeferredDeclToEmit(GD.getWithDecl(FD)); 3503 break; 3504 } 3505 } 3506 } 3507 } 3508 } 3509 3510 // Make sure the result is of the requested type. 3511 if (!IsIncompleteFunction) { 3512 assert(F->getFunctionType() == Ty); 3513 return F; 3514 } 3515 3516 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty); 3517 return llvm::ConstantExpr::getBitCast(F, PTy); 3518 } 3519 3520 /// GetAddrOfFunction - Return the address of the given function. If Ty is 3521 /// non-null, then this function will use the specified type if it has to 3522 /// create it (this occurs when we see a definition of the function). 3523 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD, 3524 llvm::Type *Ty, 3525 bool ForVTable, 3526 bool DontDefer, 3527 ForDefinition_t IsForDefinition) { 3528 assert(!cast<FunctionDecl>(GD.getDecl())->isConsteval() && 3529 "consteval function should never be emitted"); 3530 // If there was no specific requested type, just convert it now. 3531 if (!Ty) { 3532 const auto *FD = cast<FunctionDecl>(GD.getDecl()); 3533 Ty = getTypes().ConvertType(FD->getType()); 3534 } 3535 3536 // Devirtualized destructor calls may come through here instead of via 3537 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead 3538 // of the complete destructor when necessary. 3539 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) { 3540 if (getTarget().getCXXABI().isMicrosoft() && 3541 GD.getDtorType() == Dtor_Complete && 3542 DD->getParent()->getNumVBases() == 0) 3543 GD = GlobalDecl(DD, Dtor_Base); 3544 } 3545 3546 StringRef MangledName = getMangledName(GD); 3547 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer, 3548 /*IsThunk=*/false, llvm::AttributeList(), 3549 IsForDefinition); 3550 } 3551 3552 static const FunctionDecl * 3553 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) { 3554 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl(); 3555 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 3556 3557 IdentifierInfo &CII = C.Idents.get(Name); 3558 for (const auto &Result : DC->lookup(&CII)) 3559 if (const auto FD = dyn_cast<FunctionDecl>(Result)) 3560 return FD; 3561 3562 if (!C.getLangOpts().CPlusPlus) 3563 return nullptr; 3564 3565 // Demangle the premangled name from getTerminateFn() 3566 IdentifierInfo &CXXII = 3567 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ") 3568 ? C.Idents.get("terminate") 3569 : C.Idents.get(Name); 3570 3571 for (const auto &N : {"__cxxabiv1", "std"}) { 3572 IdentifierInfo &NS = C.Idents.get(N); 3573 for (const auto &Result : DC->lookup(&NS)) { 3574 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result); 3575 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result)) 3576 for (const auto &Result : LSD->lookup(&NS)) 3577 if ((ND = dyn_cast<NamespaceDecl>(Result))) 3578 break; 3579 3580 if (ND) 3581 for (const auto &Result : ND->lookup(&CXXII)) 3582 if (const auto *FD = dyn_cast<FunctionDecl>(Result)) 3583 return FD; 3584 } 3585 } 3586 3587 return nullptr; 3588 } 3589 3590 /// CreateRuntimeFunction - Create a new runtime function with the specified 3591 /// type and name. 3592 llvm::FunctionCallee 3593 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name, 3594 llvm::AttributeList ExtraAttrs, bool Local, 3595 bool AssumeConvergent) { 3596 if (AssumeConvergent) { 3597 ExtraAttrs = 3598 ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex, 3599 llvm::Attribute::Convergent); 3600 } 3601 3602 llvm::Constant *C = 3603 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false, 3604 /*DontDefer=*/false, /*IsThunk=*/false, 3605 ExtraAttrs); 3606 3607 if (auto *F = dyn_cast<llvm::Function>(C)) { 3608 if (F->empty()) { 3609 F->setCallingConv(getRuntimeCC()); 3610 3611 // In Windows Itanium environments, try to mark runtime functions 3612 // dllimport. For Mingw and MSVC, don't. We don't really know if the user 3613 // will link their standard library statically or dynamically. Marking 3614 // functions imported when they are not imported can cause linker errors 3615 // and warnings. 3616 if (!Local && getTriple().isWindowsItaniumEnvironment() && 3617 !getCodeGenOpts().LTOVisibilityPublicStd) { 3618 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name); 3619 if (!FD || FD->hasAttr<DLLImportAttr>()) { 3620 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 3621 F->setLinkage(llvm::GlobalValue::ExternalLinkage); 3622 } 3623 } 3624 setDSOLocal(F); 3625 } 3626 } 3627 3628 return {FTy, C}; 3629 } 3630 3631 /// isTypeConstant - Determine whether an object of this type can be emitted 3632 /// as a constant. 3633 /// 3634 /// If ExcludeCtor is true, the duration when the object's constructor runs 3635 /// will not be considered. The caller will need to verify that the object is 3636 /// not written to during its construction. 3637 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) { 3638 if (!Ty.isConstant(Context) && !Ty->isReferenceType()) 3639 return false; 3640 3641 if (Context.getLangOpts().CPlusPlus) { 3642 if (const CXXRecordDecl *Record 3643 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl()) 3644 return ExcludeCtor && !Record->hasMutableFields() && 3645 Record->hasTrivialDestructor(); 3646 } 3647 3648 return true; 3649 } 3650 3651 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module, 3652 /// create and return an llvm GlobalVariable with the specified type. If there 3653 /// is something in the module with the specified name, return it potentially 3654 /// bitcasted to the right type. 3655 /// 3656 /// If D is non-null, it specifies a decl that correspond to this. This is used 3657 /// to set the attributes on the global when it is first created. 3658 /// 3659 /// If IsForDefinition is true, it is guaranteed that an actual global with 3660 /// type Ty will be returned, not conversion of a variable with the same 3661 /// mangled name but some other type. 3662 llvm::Constant * 3663 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName, 3664 llvm::PointerType *Ty, 3665 const VarDecl *D, 3666 ForDefinition_t IsForDefinition) { 3667 // Lookup the entry, lazily creating it if necessary. 3668 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 3669 if (Entry) { 3670 if (WeakRefReferences.erase(Entry)) { 3671 if (D && !D->hasAttr<WeakAttr>()) 3672 Entry->setLinkage(llvm::Function::ExternalLinkage); 3673 } 3674 3675 // Handle dropped DLL attributes. 3676 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) 3677 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass); 3678 3679 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D) 3680 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry); 3681 3682 if (Entry->getType() == Ty) 3683 return Entry; 3684 3685 // If there are two attempts to define the same mangled name, issue an 3686 // error. 3687 if (IsForDefinition && !Entry->isDeclaration()) { 3688 GlobalDecl OtherGD; 3689 const VarDecl *OtherD; 3690 3691 // Check that D is not yet in DiagnosedConflictingDefinitions is required 3692 // to make sure that we issue an error only once. 3693 if (D && lookupRepresentativeDecl(MangledName, OtherGD) && 3694 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) && 3695 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) && 3696 OtherD->hasInit() && 3697 DiagnosedConflictingDefinitions.insert(D).second) { 3698 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name) 3699 << MangledName; 3700 getDiags().Report(OtherGD.getDecl()->getLocation(), 3701 diag::note_previous_definition); 3702 } 3703 } 3704 3705 // Make sure the result is of the correct type. 3706 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace()) 3707 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty); 3708 3709 // (If global is requested for a definition, we always need to create a new 3710 // global, not just return a bitcast.) 3711 if (!IsForDefinition) 3712 return llvm::ConstantExpr::getBitCast(Entry, Ty); 3713 } 3714 3715 auto AddrSpace = GetGlobalVarAddressSpace(D); 3716 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace); 3717 3718 auto *GV = new llvm::GlobalVariable( 3719 getModule(), Ty->getElementType(), false, 3720 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr, 3721 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace); 3722 3723 // If we already created a global with the same mangled name (but different 3724 // type) before, take its name and remove it from its parent. 3725 if (Entry) { 3726 GV->takeName(Entry); 3727 3728 if (!Entry->use_empty()) { 3729 llvm::Constant *NewPtrForOldDecl = 3730 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 3731 Entry->replaceAllUsesWith(NewPtrForOldDecl); 3732 } 3733 3734 Entry->eraseFromParent(); 3735 } 3736 3737 // This is the first use or definition of a mangled name. If there is a 3738 // deferred decl with this name, remember that we need to emit it at the end 3739 // of the file. 3740 auto DDI = DeferredDecls.find(MangledName); 3741 if (DDI != DeferredDecls.end()) { 3742 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit 3743 // list, and remove it from DeferredDecls (since we don't need it anymore). 3744 addDeferredDeclToEmit(DDI->second); 3745 DeferredDecls.erase(DDI); 3746 } 3747 3748 // Handle things which are present even on external declarations. 3749 if (D) { 3750 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd) 3751 getOpenMPRuntime().registerTargetGlobalVariable(D, GV); 3752 3753 // FIXME: This code is overly simple and should be merged with other global 3754 // handling. 3755 GV->setConstant(isTypeConstant(D->getType(), false)); 3756 3757 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 3758 3759 setLinkageForGV(GV, D); 3760 3761 if (D->getTLSKind()) { 3762 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 3763 CXXThreadLocals.push_back(D); 3764 setTLSMode(GV, *D); 3765 } 3766 3767 setGVProperties(GV, D); 3768 3769 // If required by the ABI, treat declarations of static data members with 3770 // inline initializers as definitions. 3771 if (getContext().isMSStaticDataMemberInlineDefinition(D)) { 3772 EmitGlobalVarDefinition(D); 3773 } 3774 3775 // Emit section information for extern variables. 3776 if (D->hasExternalStorage()) { 3777 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) 3778 GV->setSection(SA->getName()); 3779 } 3780 3781 // Handle XCore specific ABI requirements. 3782 if (getTriple().getArch() == llvm::Triple::xcore && 3783 D->getLanguageLinkage() == CLanguageLinkage && 3784 D->getType().isConstant(Context) && 3785 isExternallyVisible(D->getLinkageAndVisibility().getLinkage())) 3786 GV->setSection(".cp.rodata"); 3787 3788 // Check if we a have a const declaration with an initializer, we may be 3789 // able to emit it as available_externally to expose it's value to the 3790 // optimizer. 3791 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() && 3792 D->getType().isConstQualified() && !GV->hasInitializer() && 3793 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) { 3794 const auto *Record = 3795 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl(); 3796 bool HasMutableFields = Record && Record->hasMutableFields(); 3797 if (!HasMutableFields) { 3798 const VarDecl *InitDecl; 3799 const Expr *InitExpr = D->getAnyInitializer(InitDecl); 3800 if (InitExpr) { 3801 ConstantEmitter emitter(*this); 3802 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl); 3803 if (Init) { 3804 auto *InitType = Init->getType(); 3805 if (GV->getValueType() != InitType) { 3806 // The type of the initializer does not match the definition. 3807 // This happens when an initializer has a different type from 3808 // the type of the global (because of padding at the end of a 3809 // structure for instance). 3810 GV->setName(StringRef()); 3811 // Make a new global with the correct type, this is now guaranteed 3812 // to work. 3813 auto *NewGV = cast<llvm::GlobalVariable>( 3814 GetAddrOfGlobalVar(D, InitType, IsForDefinition) 3815 ->stripPointerCasts()); 3816 3817 // Erase the old global, since it is no longer used. 3818 GV->eraseFromParent(); 3819 GV = NewGV; 3820 } else { 3821 GV->setInitializer(Init); 3822 GV->setConstant(true); 3823 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage); 3824 } 3825 emitter.finalize(GV); 3826 } 3827 } 3828 } 3829 } 3830 } 3831 3832 if (GV->isDeclaration()) 3833 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this); 3834 3835 LangAS ExpectedAS = 3836 D ? D->getType().getAddressSpace() 3837 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default); 3838 assert(getContext().getTargetAddressSpace(ExpectedAS) == 3839 Ty->getPointerAddressSpace()); 3840 if (AddrSpace != ExpectedAS) 3841 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace, 3842 ExpectedAS, Ty); 3843 3844 return GV; 3845 } 3846 3847 llvm::Constant * 3848 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition) { 3849 const Decl *D = GD.getDecl(); 3850 3851 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D)) 3852 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr, 3853 /*DontDefer=*/false, IsForDefinition); 3854 3855 if (isa<CXXMethodDecl>(D)) { 3856 auto FInfo = 3857 &getTypes().arrangeCXXMethodDeclaration(cast<CXXMethodDecl>(D)); 3858 auto Ty = getTypes().GetFunctionType(*FInfo); 3859 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 3860 IsForDefinition); 3861 } 3862 3863 if (isa<FunctionDecl>(D)) { 3864 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 3865 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 3866 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false, 3867 IsForDefinition); 3868 } 3869 3870 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr, IsForDefinition); 3871 } 3872 3873 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable( 3874 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage, 3875 unsigned Alignment) { 3876 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name); 3877 llvm::GlobalVariable *OldGV = nullptr; 3878 3879 if (GV) { 3880 // Check if the variable has the right type. 3881 if (GV->getValueType() == Ty) 3882 return GV; 3883 3884 // Because C++ name mangling, the only way we can end up with an already 3885 // existing global with the same name is if it has been declared extern "C". 3886 assert(GV->isDeclaration() && "Declaration has wrong type!"); 3887 OldGV = GV; 3888 } 3889 3890 // Create a new variable. 3891 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true, 3892 Linkage, nullptr, Name); 3893 3894 if (OldGV) { 3895 // Replace occurrences of the old variable if needed. 3896 GV->takeName(OldGV); 3897 3898 if (!OldGV->use_empty()) { 3899 llvm::Constant *NewPtrForOldDecl = 3900 llvm::ConstantExpr::getBitCast(GV, OldGV->getType()); 3901 OldGV->replaceAllUsesWith(NewPtrForOldDecl); 3902 } 3903 3904 OldGV->eraseFromParent(); 3905 } 3906 3907 if (supportsCOMDAT() && GV->isWeakForLinker() && 3908 !GV->hasAvailableExternallyLinkage()) 3909 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 3910 3911 GV->setAlignment(llvm::MaybeAlign(Alignment)); 3912 3913 return GV; 3914 } 3915 3916 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the 3917 /// given global variable. If Ty is non-null and if the global doesn't exist, 3918 /// then it will be created with the specified type instead of whatever the 3919 /// normal requested type would be. If IsForDefinition is true, it is guaranteed 3920 /// that an actual global with type Ty will be returned, not conversion of a 3921 /// variable with the same mangled name but some other type. 3922 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D, 3923 llvm::Type *Ty, 3924 ForDefinition_t IsForDefinition) { 3925 assert(D->hasGlobalStorage() && "Not a global variable"); 3926 QualType ASTTy = D->getType(); 3927 if (!Ty) 3928 Ty = getTypes().ConvertTypeForMem(ASTTy); 3929 3930 llvm::PointerType *PTy = 3931 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 3932 3933 StringRef MangledName = getMangledName(D); 3934 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition); 3935 } 3936 3937 /// CreateRuntimeVariable - Create a new runtime global variable with the 3938 /// specified type and name. 3939 llvm::Constant * 3940 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty, 3941 StringRef Name) { 3942 auto PtrTy = 3943 getContext().getLangOpts().OpenCL 3944 ? llvm::PointerType::get( 3945 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global)) 3946 : llvm::PointerType::getUnqual(Ty); 3947 auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr); 3948 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts())); 3949 return Ret; 3950 } 3951 3952 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) { 3953 assert(!D->getInit() && "Cannot emit definite definitions here!"); 3954 3955 StringRef MangledName = getMangledName(D); 3956 llvm::GlobalValue *GV = GetGlobalValue(MangledName); 3957 3958 // We already have a definition, not declaration, with the same mangled name. 3959 // Emitting of declaration is not required (and actually overwrites emitted 3960 // definition). 3961 if (GV && !GV->isDeclaration()) 3962 return; 3963 3964 // If we have not seen a reference to this variable yet, place it into the 3965 // deferred declarations table to be emitted if needed later. 3966 if (!MustBeEmitted(D) && !GV) { 3967 DeferredDecls[MangledName] = D; 3968 return; 3969 } 3970 3971 // The tentative definition is the only definition. 3972 EmitGlobalVarDefinition(D); 3973 } 3974 3975 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) { 3976 EmitExternalVarDeclaration(D); 3977 } 3978 3979 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const { 3980 return Context.toCharUnitsFromBits( 3981 getDataLayout().getTypeStoreSizeInBits(Ty)); 3982 } 3983 3984 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) { 3985 LangAS AddrSpace = LangAS::Default; 3986 if (LangOpts.OpenCL) { 3987 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global; 3988 assert(AddrSpace == LangAS::opencl_global || 3989 AddrSpace == LangAS::opencl_global_device || 3990 AddrSpace == LangAS::opencl_global_host || 3991 AddrSpace == LangAS::opencl_constant || 3992 AddrSpace == LangAS::opencl_local || 3993 AddrSpace >= LangAS::FirstTargetAddressSpace); 3994 return AddrSpace; 3995 } 3996 3997 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) { 3998 if (D && D->hasAttr<CUDAConstantAttr>()) 3999 return LangAS::cuda_constant; 4000 else if (D && D->hasAttr<CUDASharedAttr>()) 4001 return LangAS::cuda_shared; 4002 else if (D && D->hasAttr<CUDADeviceAttr>()) 4003 return LangAS::cuda_device; 4004 else if (D && D->getType().isConstQualified()) 4005 return LangAS::cuda_constant; 4006 else 4007 return LangAS::cuda_device; 4008 } 4009 4010 if (LangOpts.OpenMP) { 4011 LangAS AS; 4012 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS)) 4013 return AS; 4014 } 4015 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D); 4016 } 4017 4018 LangAS CodeGenModule::getStringLiteralAddressSpace() const { 4019 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space. 4020 if (LangOpts.OpenCL) 4021 return LangAS::opencl_constant; 4022 if (auto AS = getTarget().getConstantAddressSpace()) 4023 return AS.getValue(); 4024 return LangAS::Default; 4025 } 4026 4027 // In address space agnostic languages, string literals are in default address 4028 // space in AST. However, certain targets (e.g. amdgcn) request them to be 4029 // emitted in constant address space in LLVM IR. To be consistent with other 4030 // parts of AST, string literal global variables in constant address space 4031 // need to be casted to default address space before being put into address 4032 // map and referenced by other part of CodeGen. 4033 // In OpenCL, string literals are in constant address space in AST, therefore 4034 // they should not be casted to default address space. 4035 static llvm::Constant * 4036 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM, 4037 llvm::GlobalVariable *GV) { 4038 llvm::Constant *Cast = GV; 4039 if (!CGM.getLangOpts().OpenCL) { 4040 if (auto AS = CGM.getTarget().getConstantAddressSpace()) { 4041 if (AS != LangAS::Default) 4042 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast( 4043 CGM, GV, AS.getValue(), LangAS::Default, 4044 GV->getValueType()->getPointerTo( 4045 CGM.getContext().getTargetAddressSpace(LangAS::Default))); 4046 } 4047 } 4048 return Cast; 4049 } 4050 4051 template<typename SomeDecl> 4052 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D, 4053 llvm::GlobalValue *GV) { 4054 if (!getLangOpts().CPlusPlus) 4055 return; 4056 4057 // Must have 'used' attribute, or else inline assembly can't rely on 4058 // the name existing. 4059 if (!D->template hasAttr<UsedAttr>()) 4060 return; 4061 4062 // Must have internal linkage and an ordinary name. 4063 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage) 4064 return; 4065 4066 // Must be in an extern "C" context. Entities declared directly within 4067 // a record are not extern "C" even if the record is in such a context. 4068 const SomeDecl *First = D->getFirstDecl(); 4069 if (First->getDeclContext()->isRecord() || !First->isInExternCContext()) 4070 return; 4071 4072 // OK, this is an internal linkage entity inside an extern "C" linkage 4073 // specification. Make a note of that so we can give it the "expected" 4074 // mangled name if nothing else is using that name. 4075 std::pair<StaticExternCMap::iterator, bool> R = 4076 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV)); 4077 4078 // If we have multiple internal linkage entities with the same name 4079 // in extern "C" regions, none of them gets that name. 4080 if (!R.second) 4081 R.first->second = nullptr; 4082 } 4083 4084 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) { 4085 if (!CGM.supportsCOMDAT()) 4086 return false; 4087 4088 // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent 4089 // them being "merged" by the COMDAT Folding linker optimization. 4090 if (D.hasAttr<CUDAGlobalAttr>()) 4091 return false; 4092 4093 if (D.hasAttr<SelectAnyAttr>()) 4094 return true; 4095 4096 GVALinkage Linkage; 4097 if (auto *VD = dyn_cast<VarDecl>(&D)) 4098 Linkage = CGM.getContext().GetGVALinkageForVariable(VD); 4099 else 4100 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D)); 4101 4102 switch (Linkage) { 4103 case GVA_Internal: 4104 case GVA_AvailableExternally: 4105 case GVA_StrongExternal: 4106 return false; 4107 case GVA_DiscardableODR: 4108 case GVA_StrongODR: 4109 return true; 4110 } 4111 llvm_unreachable("No such linkage"); 4112 } 4113 4114 void CodeGenModule::maybeSetTrivialComdat(const Decl &D, 4115 llvm::GlobalObject &GO) { 4116 if (!shouldBeInCOMDAT(*this, D)) 4117 return; 4118 GO.setComdat(TheModule.getOrInsertComdat(GO.getName())); 4119 } 4120 4121 /// Pass IsTentative as true if you want to create a tentative definition. 4122 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D, 4123 bool IsTentative) { 4124 // OpenCL global variables of sampler type are translated to function calls, 4125 // therefore no need to be translated. 4126 QualType ASTTy = D->getType(); 4127 if (getLangOpts().OpenCL && ASTTy->isSamplerT()) 4128 return; 4129 4130 // If this is OpenMP device, check if it is legal to emit this global 4131 // normally. 4132 if (LangOpts.OpenMPIsDevice && OpenMPRuntime && 4133 OpenMPRuntime->emitTargetGlobalVariable(D)) 4134 return; 4135 4136 llvm::Constant *Init = nullptr; 4137 bool NeedsGlobalCtor = false; 4138 bool NeedsGlobalDtor = 4139 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor; 4140 4141 bool IsHIPManagedVarOnDevice = 4142 getLangOpts().CUDAIsDevice && D->hasAttr<HIPManagedAttr>(); 4143 4144 const VarDecl *InitDecl; 4145 const Expr *InitExpr = 4146 IsHIPManagedVarOnDevice ? nullptr : D->getAnyInitializer(InitDecl); 4147 4148 Optional<ConstantEmitter> emitter; 4149 4150 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization 4151 // as part of their declaration." Sema has already checked for 4152 // error cases, so we just need to set Init to UndefValue. 4153 bool IsCUDASharedVar = 4154 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>(); 4155 // Shadows of initialized device-side global variables are also left 4156 // undefined. 4157 bool IsCUDAShadowVar = 4158 !getLangOpts().CUDAIsDevice && !D->hasAttr<HIPManagedAttr>() && 4159 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() || 4160 D->hasAttr<CUDASharedAttr>()); 4161 bool IsCUDADeviceShadowVar = 4162 getLangOpts().CUDAIsDevice && 4163 (D->getType()->isCUDADeviceBuiltinSurfaceType() || 4164 D->getType()->isCUDADeviceBuiltinTextureType() || 4165 D->hasAttr<HIPManagedAttr>()); 4166 if (getLangOpts().CUDA && 4167 (IsCUDASharedVar || IsCUDAShadowVar || IsCUDADeviceShadowVar)) 4168 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 4169 else if (D->hasAttr<LoaderUninitializedAttr>()) 4170 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy)); 4171 else if (!InitExpr) { 4172 // This is a tentative definition; tentative definitions are 4173 // implicitly initialized with { 0 }. 4174 // 4175 // Note that tentative definitions are only emitted at the end of 4176 // a translation unit, so they should never have incomplete 4177 // type. In addition, EmitTentativeDefinition makes sure that we 4178 // never attempt to emit a tentative definition if a real one 4179 // exists. A use may still exists, however, so we still may need 4180 // to do a RAUW. 4181 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type"); 4182 Init = EmitNullConstant(D->getType()); 4183 } else { 4184 initializedGlobalDecl = GlobalDecl(D); 4185 emitter.emplace(*this); 4186 Init = emitter->tryEmitForInitializer(*InitDecl); 4187 4188 if (!Init) { 4189 QualType T = InitExpr->getType(); 4190 if (D->getType()->isReferenceType()) 4191 T = D->getType(); 4192 4193 if (getLangOpts().CPlusPlus) { 4194 Init = EmitNullConstant(T); 4195 NeedsGlobalCtor = true; 4196 } else { 4197 ErrorUnsupported(D, "static initializer"); 4198 Init = llvm::UndefValue::get(getTypes().ConvertType(T)); 4199 } 4200 } else { 4201 // We don't need an initializer, so remove the entry for the delayed 4202 // initializer position (just in case this entry was delayed) if we 4203 // also don't need to register a destructor. 4204 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor) 4205 DelayedCXXInitPosition.erase(D); 4206 } 4207 } 4208 4209 llvm::Type* InitType = Init->getType(); 4210 llvm::Constant *Entry = 4211 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)); 4212 4213 // Strip off pointer casts if we got them. 4214 Entry = Entry->stripPointerCasts(); 4215 4216 // Entry is now either a Function or GlobalVariable. 4217 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry); 4218 4219 // We have a definition after a declaration with the wrong type. 4220 // We must make a new GlobalVariable* and update everything that used OldGV 4221 // (a declaration or tentative definition) with the new GlobalVariable* 4222 // (which will be a definition). 4223 // 4224 // This happens if there is a prototype for a global (e.g. 4225 // "extern int x[];") and then a definition of a different type (e.g. 4226 // "int x[10];"). This also happens when an initializer has a different type 4227 // from the type of the global (this happens with unions). 4228 if (!GV || GV->getValueType() != InitType || 4229 GV->getType()->getAddressSpace() != 4230 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) { 4231 4232 // Move the old entry aside so that we'll create a new one. 4233 Entry->setName(StringRef()); 4234 4235 // Make a new global with the correct type, this is now guaranteed to work. 4236 GV = cast<llvm::GlobalVariable>( 4237 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)) 4238 ->stripPointerCasts()); 4239 4240 // Replace all uses of the old global with the new global 4241 llvm::Constant *NewPtrForOldDecl = 4242 llvm::ConstantExpr::getBitCast(GV, Entry->getType()); 4243 Entry->replaceAllUsesWith(NewPtrForOldDecl); 4244 4245 // Erase the old global, since it is no longer used. 4246 cast<llvm::GlobalValue>(Entry)->eraseFromParent(); 4247 } 4248 4249 MaybeHandleStaticInExternC(D, GV); 4250 4251 if (D->hasAttr<AnnotateAttr>()) 4252 AddGlobalAnnotations(D, GV); 4253 4254 // Set the llvm linkage type as appropriate. 4255 llvm::GlobalValue::LinkageTypes Linkage = 4256 getLLVMLinkageVarDefinition(D, GV->isConstant()); 4257 4258 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on 4259 // the device. [...]" 4260 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with 4261 // __device__, declares a variable that: [...] 4262 // Is accessible from all the threads within the grid and from the host 4263 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize() 4264 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())." 4265 if (GV && LangOpts.CUDA) { 4266 if (LangOpts.CUDAIsDevice) { 4267 if (Linkage != llvm::GlobalValue::InternalLinkage && 4268 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())) 4269 GV->setExternallyInitialized(true); 4270 } else { 4271 getCUDARuntime().internalizeDeviceSideVar(D, Linkage); 4272 getCUDARuntime().handleVarRegistration(D, *GV); 4273 } 4274 } 4275 4276 // HIP managed variables need to be emitted as declarations in device 4277 // compilation. 4278 if (!IsHIPManagedVarOnDevice) 4279 GV->setInitializer(Init); 4280 if (emitter) 4281 emitter->finalize(GV); 4282 4283 // If it is safe to mark the global 'constant', do so now. 4284 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor && 4285 isTypeConstant(D->getType(), true)); 4286 4287 // If it is in a read-only section, mark it 'constant'. 4288 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) { 4289 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()]; 4290 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0) 4291 GV->setConstant(true); 4292 } 4293 4294 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign()); 4295 4296 // On Darwin, unlike other Itanium C++ ABI platforms, the thread-wrapper 4297 // function is only defined alongside the variable, not also alongside 4298 // callers. Normally, all accesses to a thread_local go through the 4299 // thread-wrapper in order to ensure initialization has occurred, underlying 4300 // variable will never be used other than the thread-wrapper, so it can be 4301 // converted to internal linkage. 4302 // 4303 // However, if the variable has the 'constinit' attribute, it _can_ be 4304 // referenced directly, without calling the thread-wrapper, so the linkage 4305 // must not be changed. 4306 // 4307 // Additionally, if the variable isn't plain external linkage, e.g. if it's 4308 // weak or linkonce, the de-duplication semantics are important to preserve, 4309 // so we don't change the linkage. 4310 if (D->getTLSKind() == VarDecl::TLS_Dynamic && 4311 Linkage == llvm::GlobalValue::ExternalLinkage && 4312 Context.getTargetInfo().getTriple().isOSDarwin() && 4313 !D->hasAttr<ConstInitAttr>()) 4314 Linkage = llvm::GlobalValue::InternalLinkage; 4315 4316 GV->setLinkage(Linkage); 4317 if (D->hasAttr<DLLImportAttr>()) 4318 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass); 4319 else if (D->hasAttr<DLLExportAttr>()) 4320 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass); 4321 else 4322 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass); 4323 4324 if (Linkage == llvm::GlobalVariable::CommonLinkage) { 4325 // common vars aren't constant even if declared const. 4326 GV->setConstant(false); 4327 // Tentative definition of global variables may be initialized with 4328 // non-zero null pointers. In this case they should have weak linkage 4329 // since common linkage must have zero initializer and must not have 4330 // explicit section therefore cannot have non-zero initial value. 4331 if (!GV->getInitializer()->isNullValue()) 4332 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage); 4333 } 4334 4335 setNonAliasAttributes(D, GV); 4336 4337 if (D->getTLSKind() && !GV->isThreadLocal()) { 4338 if (D->getTLSKind() == VarDecl::TLS_Dynamic) 4339 CXXThreadLocals.push_back(D); 4340 setTLSMode(GV, *D); 4341 } 4342 4343 maybeSetTrivialComdat(*D, *GV); 4344 4345 // Emit the initializer function if necessary. 4346 if (NeedsGlobalCtor || NeedsGlobalDtor) 4347 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor); 4348 4349 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor); 4350 4351 // Emit global variable debug information. 4352 if (CGDebugInfo *DI = getModuleDebugInfo()) 4353 if (getCodeGenOpts().hasReducedDebugInfo()) 4354 DI->EmitGlobalVariable(GV, D); 4355 } 4356 4357 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) { 4358 if (CGDebugInfo *DI = getModuleDebugInfo()) 4359 if (getCodeGenOpts().hasReducedDebugInfo()) { 4360 QualType ASTTy = D->getType(); 4361 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType()); 4362 llvm::PointerType *PTy = 4363 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy)); 4364 llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D); 4365 DI->EmitExternalVariable( 4366 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D); 4367 } 4368 } 4369 4370 static bool isVarDeclStrongDefinition(const ASTContext &Context, 4371 CodeGenModule &CGM, const VarDecl *D, 4372 bool NoCommon) { 4373 // Don't give variables common linkage if -fno-common was specified unless it 4374 // was overridden by a NoCommon attribute. 4375 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>()) 4376 return true; 4377 4378 // C11 6.9.2/2: 4379 // A declaration of an identifier for an object that has file scope without 4380 // an initializer, and without a storage-class specifier or with the 4381 // storage-class specifier static, constitutes a tentative definition. 4382 if (D->getInit() || D->hasExternalStorage()) 4383 return true; 4384 4385 // A variable cannot be both common and exist in a section. 4386 if (D->hasAttr<SectionAttr>()) 4387 return true; 4388 4389 // A variable cannot be both common and exist in a section. 4390 // We don't try to determine which is the right section in the front-end. 4391 // If no specialized section name is applicable, it will resort to default. 4392 if (D->hasAttr<PragmaClangBSSSectionAttr>() || 4393 D->hasAttr<PragmaClangDataSectionAttr>() || 4394 D->hasAttr<PragmaClangRelroSectionAttr>() || 4395 D->hasAttr<PragmaClangRodataSectionAttr>()) 4396 return true; 4397 4398 // Thread local vars aren't considered common linkage. 4399 if (D->getTLSKind()) 4400 return true; 4401 4402 // Tentative definitions marked with WeakImportAttr are true definitions. 4403 if (D->hasAttr<WeakImportAttr>()) 4404 return true; 4405 4406 // A variable cannot be both common and exist in a comdat. 4407 if (shouldBeInCOMDAT(CGM, *D)) 4408 return true; 4409 4410 // Declarations with a required alignment do not have common linkage in MSVC 4411 // mode. 4412 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) { 4413 if (D->hasAttr<AlignedAttr>()) 4414 return true; 4415 QualType VarType = D->getType(); 4416 if (Context.isAlignmentRequired(VarType)) 4417 return true; 4418 4419 if (const auto *RT = VarType->getAs<RecordType>()) { 4420 const RecordDecl *RD = RT->getDecl(); 4421 for (const FieldDecl *FD : RD->fields()) { 4422 if (FD->isBitField()) 4423 continue; 4424 if (FD->hasAttr<AlignedAttr>()) 4425 return true; 4426 if (Context.isAlignmentRequired(FD->getType())) 4427 return true; 4428 } 4429 } 4430 } 4431 4432 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for 4433 // common symbols, so symbols with greater alignment requirements cannot be 4434 // common. 4435 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two 4436 // alignments for common symbols via the aligncomm directive, so this 4437 // restriction only applies to MSVC environments. 4438 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() && 4439 Context.getTypeAlignIfKnown(D->getType()) > 4440 Context.toBits(CharUnits::fromQuantity(32))) 4441 return true; 4442 4443 return false; 4444 } 4445 4446 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator( 4447 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) { 4448 if (Linkage == GVA_Internal) 4449 return llvm::Function::InternalLinkage; 4450 4451 if (D->hasAttr<WeakAttr>()) { 4452 if (IsConstantVariable) 4453 return llvm::GlobalVariable::WeakODRLinkage; 4454 else 4455 return llvm::GlobalVariable::WeakAnyLinkage; 4456 } 4457 4458 if (const auto *FD = D->getAsFunction()) 4459 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally) 4460 return llvm::GlobalVariable::LinkOnceAnyLinkage; 4461 4462 // We are guaranteed to have a strong definition somewhere else, 4463 // so we can use available_externally linkage. 4464 if (Linkage == GVA_AvailableExternally) 4465 return llvm::GlobalValue::AvailableExternallyLinkage; 4466 4467 // Note that Apple's kernel linker doesn't support symbol 4468 // coalescing, so we need to avoid linkonce and weak linkages there. 4469 // Normally, this means we just map to internal, but for explicit 4470 // instantiations we'll map to external. 4471 4472 // In C++, the compiler has to emit a definition in every translation unit 4473 // that references the function. We should use linkonce_odr because 4474 // a) if all references in this translation unit are optimized away, we 4475 // don't need to codegen it. b) if the function persists, it needs to be 4476 // merged with other definitions. c) C++ has the ODR, so we know the 4477 // definition is dependable. 4478 if (Linkage == GVA_DiscardableODR) 4479 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage 4480 : llvm::Function::InternalLinkage; 4481 4482 // An explicit instantiation of a template has weak linkage, since 4483 // explicit instantiations can occur in multiple translation units 4484 // and must all be equivalent. However, we are not allowed to 4485 // throw away these explicit instantiations. 4486 // 4487 // CUDA/HIP: For -fno-gpu-rdc case, device code is limited to one TU, 4488 // so say that CUDA templates are either external (for kernels) or internal. 4489 // This lets llvm perform aggressive inter-procedural optimizations. For 4490 // -fgpu-rdc case, device function calls across multiple TU's are allowed, 4491 // therefore we need to follow the normal linkage paradigm. 4492 if (Linkage == GVA_StrongODR) { 4493 if (getLangOpts().AppleKext) 4494 return llvm::Function::ExternalLinkage; 4495 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice && 4496 !getLangOpts().GPURelocatableDeviceCode) 4497 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage 4498 : llvm::Function::InternalLinkage; 4499 return llvm::Function::WeakODRLinkage; 4500 } 4501 4502 // C++ doesn't have tentative definitions and thus cannot have common 4503 // linkage. 4504 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) && 4505 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D), 4506 CodeGenOpts.NoCommon)) 4507 return llvm::GlobalVariable::CommonLinkage; 4508 4509 // selectany symbols are externally visible, so use weak instead of 4510 // linkonce. MSVC optimizes away references to const selectany globals, so 4511 // all definitions should be the same and ODR linkage should be used. 4512 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx 4513 if (D->hasAttr<SelectAnyAttr>()) 4514 return llvm::GlobalVariable::WeakODRLinkage; 4515 4516 // Otherwise, we have strong external linkage. 4517 assert(Linkage == GVA_StrongExternal); 4518 return llvm::GlobalVariable::ExternalLinkage; 4519 } 4520 4521 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition( 4522 const VarDecl *VD, bool IsConstant) { 4523 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD); 4524 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant); 4525 } 4526 4527 /// Replace the uses of a function that was declared with a non-proto type. 4528 /// We want to silently drop extra arguments from call sites 4529 static void replaceUsesOfNonProtoConstant(llvm::Constant *old, 4530 llvm::Function *newFn) { 4531 // Fast path. 4532 if (old->use_empty()) return; 4533 4534 llvm::Type *newRetTy = newFn->getReturnType(); 4535 SmallVector<llvm::Value*, 4> newArgs; 4536 SmallVector<llvm::OperandBundleDef, 1> newBundles; 4537 4538 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end(); 4539 ui != ue; ) { 4540 llvm::Value::use_iterator use = ui++; // Increment before the use is erased. 4541 llvm::User *user = use->getUser(); 4542 4543 // Recognize and replace uses of bitcasts. Most calls to 4544 // unprototyped functions will use bitcasts. 4545 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) { 4546 if (bitcast->getOpcode() == llvm::Instruction::BitCast) 4547 replaceUsesOfNonProtoConstant(bitcast, newFn); 4548 continue; 4549 } 4550 4551 // Recognize calls to the function. 4552 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user); 4553 if (!callSite) continue; 4554 if (!callSite->isCallee(&*use)) 4555 continue; 4556 4557 // If the return types don't match exactly, then we can't 4558 // transform this call unless it's dead. 4559 if (callSite->getType() != newRetTy && !callSite->use_empty()) 4560 continue; 4561 4562 // Get the call site's attribute list. 4563 SmallVector<llvm::AttributeSet, 8> newArgAttrs; 4564 llvm::AttributeList oldAttrs = callSite->getAttributes(); 4565 4566 // If the function was passed too few arguments, don't transform. 4567 unsigned newNumArgs = newFn->arg_size(); 4568 if (callSite->arg_size() < newNumArgs) 4569 continue; 4570 4571 // If extra arguments were passed, we silently drop them. 4572 // If any of the types mismatch, we don't transform. 4573 unsigned argNo = 0; 4574 bool dontTransform = false; 4575 for (llvm::Argument &A : newFn->args()) { 4576 if (callSite->getArgOperand(argNo)->getType() != A.getType()) { 4577 dontTransform = true; 4578 break; 4579 } 4580 4581 // Add any parameter attributes. 4582 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo)); 4583 argNo++; 4584 } 4585 if (dontTransform) 4586 continue; 4587 4588 // Okay, we can transform this. Create the new call instruction and copy 4589 // over the required information. 4590 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo); 4591 4592 // Copy over any operand bundles. 4593 callSite->getOperandBundlesAsDefs(newBundles); 4594 4595 llvm::CallBase *newCall; 4596 if (dyn_cast<llvm::CallInst>(callSite)) { 4597 newCall = 4598 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite); 4599 } else { 4600 auto *oldInvoke = cast<llvm::InvokeInst>(callSite); 4601 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(), 4602 oldInvoke->getUnwindDest(), newArgs, 4603 newBundles, "", callSite); 4604 } 4605 newArgs.clear(); // for the next iteration 4606 4607 if (!newCall->getType()->isVoidTy()) 4608 newCall->takeName(callSite); 4609 newCall->setAttributes(llvm::AttributeList::get( 4610 newFn->getContext(), oldAttrs.getFnAttributes(), 4611 oldAttrs.getRetAttributes(), newArgAttrs)); 4612 newCall->setCallingConv(callSite->getCallingConv()); 4613 4614 // Finally, remove the old call, replacing any uses with the new one. 4615 if (!callSite->use_empty()) 4616 callSite->replaceAllUsesWith(newCall); 4617 4618 // Copy debug location attached to CI. 4619 if (callSite->getDebugLoc()) 4620 newCall->setDebugLoc(callSite->getDebugLoc()); 4621 4622 callSite->eraseFromParent(); 4623 } 4624 } 4625 4626 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we 4627 /// implement a function with no prototype, e.g. "int foo() {}". If there are 4628 /// existing call uses of the old function in the module, this adjusts them to 4629 /// call the new function directly. 4630 /// 4631 /// This is not just a cleanup: the always_inline pass requires direct calls to 4632 /// functions to be able to inline them. If there is a bitcast in the way, it 4633 /// won't inline them. Instcombine normally deletes these calls, but it isn't 4634 /// run at -O0. 4635 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old, 4636 llvm::Function *NewFn) { 4637 // If we're redefining a global as a function, don't transform it. 4638 if (!isa<llvm::Function>(Old)) return; 4639 4640 replaceUsesOfNonProtoConstant(Old, NewFn); 4641 } 4642 4643 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) { 4644 auto DK = VD->isThisDeclarationADefinition(); 4645 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>()) 4646 return; 4647 4648 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind(); 4649 // If we have a definition, this might be a deferred decl. If the 4650 // instantiation is explicit, make sure we emit it at the end. 4651 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition) 4652 GetAddrOfGlobalVar(VD); 4653 4654 EmitTopLevelDecl(VD); 4655 } 4656 4657 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD, 4658 llvm::GlobalValue *GV) { 4659 const auto *D = cast<FunctionDecl>(GD.getDecl()); 4660 4661 // Compute the function info and LLVM type. 4662 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD); 4663 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI); 4664 4665 // Get or create the prototype for the function. 4666 if (!GV || (GV->getValueType() != Ty)) 4667 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, 4668 /*DontDefer=*/true, 4669 ForDefinition)); 4670 4671 // Already emitted. 4672 if (!GV->isDeclaration()) 4673 return; 4674 4675 // We need to set linkage and visibility on the function before 4676 // generating code for it because various parts of IR generation 4677 // want to propagate this information down (e.g. to local static 4678 // declarations). 4679 auto *Fn = cast<llvm::Function>(GV); 4680 setFunctionLinkage(GD, Fn); 4681 4682 // FIXME: this is redundant with part of setFunctionDefinitionAttributes 4683 setGVProperties(Fn, GD); 4684 4685 MaybeHandleStaticInExternC(D, Fn); 4686 4687 maybeSetTrivialComdat(*D, *Fn); 4688 4689 // Set CodeGen attributes that represent floating point environment. 4690 setLLVMFunctionFEnvAttributes(D, Fn); 4691 4692 CodeGenFunction(*this).GenerateCode(GD, Fn, FI); 4693 4694 setNonAliasAttributes(GD, Fn); 4695 SetLLVMFunctionAttributesForDefinition(D, Fn); 4696 4697 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) 4698 AddGlobalCtor(Fn, CA->getPriority()); 4699 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) 4700 AddGlobalDtor(Fn, DA->getPriority(), true); 4701 if (D->hasAttr<AnnotateAttr>()) 4702 AddGlobalAnnotations(D, Fn); 4703 } 4704 4705 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) { 4706 const auto *D = cast<ValueDecl>(GD.getDecl()); 4707 const AliasAttr *AA = D->getAttr<AliasAttr>(); 4708 assert(AA && "Not an alias?"); 4709 4710 StringRef MangledName = getMangledName(GD); 4711 4712 if (AA->getAliasee() == MangledName) { 4713 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 4714 return; 4715 } 4716 4717 // If there is a definition in the module, then it wins over the alias. 4718 // This is dubious, but allow it to be safe. Just ignore the alias. 4719 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4720 if (Entry && !Entry->isDeclaration()) 4721 return; 4722 4723 Aliases.push_back(GD); 4724 4725 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 4726 4727 // Create a reference to the named value. This ensures that it is emitted 4728 // if a deferred decl. 4729 llvm::Constant *Aliasee; 4730 llvm::GlobalValue::LinkageTypes LT; 4731 if (isa<llvm::FunctionType>(DeclTy)) { 4732 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD, 4733 /*ForVTable=*/false); 4734 LT = getFunctionLinkage(GD); 4735 } else { 4736 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(), 4737 llvm::PointerType::getUnqual(DeclTy), 4738 /*D=*/nullptr); 4739 if (const auto *VD = dyn_cast<VarDecl>(GD.getDecl())) 4740 LT = getLLVMLinkageVarDefinition(VD, D->getType().isConstQualified()); 4741 else 4742 LT = getFunctionLinkage(GD); 4743 } 4744 4745 // Create the new alias itself, but don't set a name yet. 4746 unsigned AS = Aliasee->getType()->getPointerAddressSpace(); 4747 auto *GA = 4748 llvm::GlobalAlias::create(DeclTy, AS, LT, "", Aliasee, &getModule()); 4749 4750 if (Entry) { 4751 if (GA->getAliasee() == Entry) { 4752 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0; 4753 return; 4754 } 4755 4756 assert(Entry->isDeclaration()); 4757 4758 // If there is a declaration in the module, then we had an extern followed 4759 // by the alias, as in: 4760 // extern int test6(); 4761 // ... 4762 // int test6() __attribute__((alias("test7"))); 4763 // 4764 // Remove it and replace uses of it with the alias. 4765 GA->takeName(Entry); 4766 4767 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA, 4768 Entry->getType())); 4769 Entry->eraseFromParent(); 4770 } else { 4771 GA->setName(MangledName); 4772 } 4773 4774 // Set attributes which are particular to an alias; this is a 4775 // specialization of the attributes which may be set on a global 4776 // variable/function. 4777 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() || 4778 D->isWeakImported()) { 4779 GA->setLinkage(llvm::Function::WeakAnyLinkage); 4780 } 4781 4782 if (const auto *VD = dyn_cast<VarDecl>(D)) 4783 if (VD->getTLSKind()) 4784 setTLSMode(GA, *VD); 4785 4786 SetCommonAttributes(GD, GA); 4787 } 4788 4789 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) { 4790 const auto *D = cast<ValueDecl>(GD.getDecl()); 4791 const IFuncAttr *IFA = D->getAttr<IFuncAttr>(); 4792 assert(IFA && "Not an ifunc?"); 4793 4794 StringRef MangledName = getMangledName(GD); 4795 4796 if (IFA->getResolver() == MangledName) { 4797 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 4798 return; 4799 } 4800 4801 // Report an error if some definition overrides ifunc. 4802 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 4803 if (Entry && !Entry->isDeclaration()) { 4804 GlobalDecl OtherGD; 4805 if (lookupRepresentativeDecl(MangledName, OtherGD) && 4806 DiagnosedConflictingDefinitions.insert(GD).second) { 4807 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name) 4808 << MangledName; 4809 Diags.Report(OtherGD.getDecl()->getLocation(), 4810 diag::note_previous_definition); 4811 } 4812 return; 4813 } 4814 4815 Aliases.push_back(GD); 4816 4817 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType()); 4818 llvm::Constant *Resolver = 4819 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD, 4820 /*ForVTable=*/false); 4821 llvm::GlobalIFunc *GIF = 4822 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage, 4823 "", Resolver, &getModule()); 4824 if (Entry) { 4825 if (GIF->getResolver() == Entry) { 4826 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1; 4827 return; 4828 } 4829 assert(Entry->isDeclaration()); 4830 4831 // If there is a declaration in the module, then we had an extern followed 4832 // by the ifunc, as in: 4833 // extern int test(); 4834 // ... 4835 // int test() __attribute__((ifunc("resolver"))); 4836 // 4837 // Remove it and replace uses of it with the ifunc. 4838 GIF->takeName(Entry); 4839 4840 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF, 4841 Entry->getType())); 4842 Entry->eraseFromParent(); 4843 } else 4844 GIF->setName(MangledName); 4845 4846 SetCommonAttributes(GD, GIF); 4847 } 4848 4849 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID, 4850 ArrayRef<llvm::Type*> Tys) { 4851 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID, 4852 Tys); 4853 } 4854 4855 static llvm::StringMapEntry<llvm::GlobalVariable *> & 4856 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map, 4857 const StringLiteral *Literal, bool TargetIsLSB, 4858 bool &IsUTF16, unsigned &StringLength) { 4859 StringRef String = Literal->getString(); 4860 unsigned NumBytes = String.size(); 4861 4862 // Check for simple case. 4863 if (!Literal->containsNonAsciiOrNull()) { 4864 StringLength = NumBytes; 4865 return *Map.insert(std::make_pair(String, nullptr)).first; 4866 } 4867 4868 // Otherwise, convert the UTF8 literals into a string of shorts. 4869 IsUTF16 = true; 4870 4871 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls. 4872 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data(); 4873 llvm::UTF16 *ToPtr = &ToBuf[0]; 4874 4875 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr, 4876 ToPtr + NumBytes, llvm::strictConversion); 4877 4878 // ConvertUTF8toUTF16 returns the length in ToPtr. 4879 StringLength = ToPtr - &ToBuf[0]; 4880 4881 // Add an explicit null. 4882 *ToPtr = 0; 4883 return *Map.insert(std::make_pair( 4884 StringRef(reinterpret_cast<const char *>(ToBuf.data()), 4885 (StringLength + 1) * 2), 4886 nullptr)).first; 4887 } 4888 4889 ConstantAddress 4890 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) { 4891 unsigned StringLength = 0; 4892 bool isUTF16 = false; 4893 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry = 4894 GetConstantCFStringEntry(CFConstantStringMap, Literal, 4895 getDataLayout().isLittleEndian(), isUTF16, 4896 StringLength); 4897 4898 if (auto *C = Entry.second) 4899 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment())); 4900 4901 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty); 4902 llvm::Constant *Zeros[] = { Zero, Zero }; 4903 4904 const ASTContext &Context = getContext(); 4905 const llvm::Triple &Triple = getTriple(); 4906 4907 const auto CFRuntime = getLangOpts().CFRuntime; 4908 const bool IsSwiftABI = 4909 static_cast<unsigned>(CFRuntime) >= 4910 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift); 4911 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1; 4912 4913 // If we don't already have it, get __CFConstantStringClassReference. 4914 if (!CFConstantStringClassRef) { 4915 const char *CFConstantStringClassName = "__CFConstantStringClassReference"; 4916 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); 4917 Ty = llvm::ArrayType::get(Ty, 0); 4918 4919 switch (CFRuntime) { 4920 default: break; 4921 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH; 4922 case LangOptions::CoreFoundationABI::Swift5_0: 4923 CFConstantStringClassName = 4924 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN" 4925 : "$s10Foundation19_NSCFConstantStringCN"; 4926 Ty = IntPtrTy; 4927 break; 4928 case LangOptions::CoreFoundationABI::Swift4_2: 4929 CFConstantStringClassName = 4930 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN" 4931 : "$S10Foundation19_NSCFConstantStringCN"; 4932 Ty = IntPtrTy; 4933 break; 4934 case LangOptions::CoreFoundationABI::Swift4_1: 4935 CFConstantStringClassName = 4936 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN" 4937 : "__T010Foundation19_NSCFConstantStringCN"; 4938 Ty = IntPtrTy; 4939 break; 4940 } 4941 4942 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName); 4943 4944 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) { 4945 llvm::GlobalValue *GV = nullptr; 4946 4947 if ((GV = dyn_cast<llvm::GlobalValue>(C))) { 4948 IdentifierInfo &II = Context.Idents.get(GV->getName()); 4949 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl(); 4950 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl); 4951 4952 const VarDecl *VD = nullptr; 4953 for (const auto &Result : DC->lookup(&II)) 4954 if ((VD = dyn_cast<VarDecl>(Result))) 4955 break; 4956 4957 if (Triple.isOSBinFormatELF()) { 4958 if (!VD) 4959 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 4960 } else { 4961 GV->setLinkage(llvm::GlobalValue::ExternalLinkage); 4962 if (!VD || !VD->hasAttr<DLLExportAttr>()) 4963 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); 4964 else 4965 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass); 4966 } 4967 4968 setDSOLocal(GV); 4969 } 4970 } 4971 4972 // Decay array -> ptr 4973 CFConstantStringClassRef = 4974 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty) 4975 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros); 4976 } 4977 4978 QualType CFTy = Context.getCFConstantStringType(); 4979 4980 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy)); 4981 4982 ConstantInitBuilder Builder(*this); 4983 auto Fields = Builder.beginStruct(STy); 4984 4985 // Class pointer. 4986 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef)); 4987 4988 // Flags. 4989 if (IsSwiftABI) { 4990 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01); 4991 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8); 4992 } else { 4993 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8); 4994 } 4995 4996 // String pointer. 4997 llvm::Constant *C = nullptr; 4998 if (isUTF16) { 4999 auto Arr = llvm::makeArrayRef( 5000 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())), 5001 Entry.first().size() / 2); 5002 C = llvm::ConstantDataArray::get(VMContext, Arr); 5003 } else { 5004 C = llvm::ConstantDataArray::getString(VMContext, Entry.first()); 5005 } 5006 5007 // Note: -fwritable-strings doesn't make the backing store strings of 5008 // CFStrings writable. (See <rdar://problem/10657500>) 5009 auto *GV = 5010 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true, 5011 llvm::GlobalValue::PrivateLinkage, C, ".str"); 5012 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5013 // Don't enforce the target's minimum global alignment, since the only use 5014 // of the string is via this class initializer. 5015 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy) 5016 : Context.getTypeAlignInChars(Context.CharTy); 5017 GV->setAlignment(Align.getAsAlign()); 5018 5019 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. 5020 // Without it LLVM can merge the string with a non unnamed_addr one during 5021 // LTO. Doing that changes the section it ends in, which surprises ld64. 5022 if (Triple.isOSBinFormatMachO()) 5023 GV->setSection(isUTF16 ? "__TEXT,__ustring" 5024 : "__TEXT,__cstring,cstring_literals"); 5025 // Make sure the literal ends up in .rodata to allow for safe ICF and for 5026 // the static linker to adjust permissions to read-only later on. 5027 else if (Triple.isOSBinFormatELF()) 5028 GV->setSection(".rodata"); 5029 5030 // String. 5031 llvm::Constant *Str = 5032 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros); 5033 5034 if (isUTF16) 5035 // Cast the UTF16 string to the correct type. 5036 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy); 5037 Fields.add(Str); 5038 5039 // String length. 5040 llvm::IntegerType *LengthTy = 5041 llvm::IntegerType::get(getModule().getContext(), 5042 Context.getTargetInfo().getLongWidth()); 5043 if (IsSwiftABI) { 5044 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 || 5045 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2) 5046 LengthTy = Int32Ty; 5047 else 5048 LengthTy = IntPtrTy; 5049 } 5050 Fields.addInt(LengthTy, StringLength); 5051 5052 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is 5053 // properly aligned on 32-bit platforms. 5054 CharUnits Alignment = 5055 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign(); 5056 5057 // The struct. 5058 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment, 5059 /*isConstant=*/false, 5060 llvm::GlobalVariable::PrivateLinkage); 5061 GV->addAttribute("objc_arc_inert"); 5062 switch (Triple.getObjectFormat()) { 5063 case llvm::Triple::UnknownObjectFormat: 5064 llvm_unreachable("unknown file format"); 5065 case llvm::Triple::GOFF: 5066 llvm_unreachable("GOFF is not yet implemented"); 5067 case llvm::Triple::XCOFF: 5068 llvm_unreachable("XCOFF is not yet implemented"); 5069 case llvm::Triple::COFF: 5070 case llvm::Triple::ELF: 5071 case llvm::Triple::Wasm: 5072 GV->setSection("cfstring"); 5073 break; 5074 case llvm::Triple::MachO: 5075 GV->setSection("__DATA,__cfstring"); 5076 break; 5077 } 5078 Entry.second = GV; 5079 5080 return ConstantAddress(GV, Alignment); 5081 } 5082 5083 bool CodeGenModule::getExpressionLocationsEnabled() const { 5084 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo; 5085 } 5086 5087 QualType CodeGenModule::getObjCFastEnumerationStateType() { 5088 if (ObjCFastEnumerationStateType.isNull()) { 5089 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState"); 5090 D->startDefinition(); 5091 5092 QualType FieldTypes[] = { 5093 Context.UnsignedLongTy, 5094 Context.getPointerType(Context.getObjCIdType()), 5095 Context.getPointerType(Context.UnsignedLongTy), 5096 Context.getConstantArrayType(Context.UnsignedLongTy, 5097 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0) 5098 }; 5099 5100 for (size_t i = 0; i < 4; ++i) { 5101 FieldDecl *Field = FieldDecl::Create(Context, 5102 D, 5103 SourceLocation(), 5104 SourceLocation(), nullptr, 5105 FieldTypes[i], /*TInfo=*/nullptr, 5106 /*BitWidth=*/nullptr, 5107 /*Mutable=*/false, 5108 ICIS_NoInit); 5109 Field->setAccess(AS_public); 5110 D->addDecl(Field); 5111 } 5112 5113 D->completeDefinition(); 5114 ObjCFastEnumerationStateType = Context.getTagDeclType(D); 5115 } 5116 5117 return ObjCFastEnumerationStateType; 5118 } 5119 5120 llvm::Constant * 5121 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) { 5122 assert(!E->getType()->isPointerType() && "Strings are always arrays"); 5123 5124 // Don't emit it as the address of the string, emit the string data itself 5125 // as an inline array. 5126 if (E->getCharByteWidth() == 1) { 5127 SmallString<64> Str(E->getString()); 5128 5129 // Resize the string to the right size, which is indicated by its type. 5130 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType()); 5131 Str.resize(CAT->getSize().getZExtValue()); 5132 return llvm::ConstantDataArray::getString(VMContext, Str, false); 5133 } 5134 5135 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType())); 5136 llvm::Type *ElemTy = AType->getElementType(); 5137 unsigned NumElements = AType->getNumElements(); 5138 5139 // Wide strings have either 2-byte or 4-byte elements. 5140 if (ElemTy->getPrimitiveSizeInBits() == 16) { 5141 SmallVector<uint16_t, 32> Elements; 5142 Elements.reserve(NumElements); 5143 5144 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5145 Elements.push_back(E->getCodeUnit(i)); 5146 Elements.resize(NumElements); 5147 return llvm::ConstantDataArray::get(VMContext, Elements); 5148 } 5149 5150 assert(ElemTy->getPrimitiveSizeInBits() == 32); 5151 SmallVector<uint32_t, 32> Elements; 5152 Elements.reserve(NumElements); 5153 5154 for(unsigned i = 0, e = E->getLength(); i != e; ++i) 5155 Elements.push_back(E->getCodeUnit(i)); 5156 Elements.resize(NumElements); 5157 return llvm::ConstantDataArray::get(VMContext, Elements); 5158 } 5159 5160 static llvm::GlobalVariable * 5161 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT, 5162 CodeGenModule &CGM, StringRef GlobalName, 5163 CharUnits Alignment) { 5164 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace( 5165 CGM.getStringLiteralAddressSpace()); 5166 5167 llvm::Module &M = CGM.getModule(); 5168 // Create a global variable for this string 5169 auto *GV = new llvm::GlobalVariable( 5170 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName, 5171 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace); 5172 GV->setAlignment(Alignment.getAsAlign()); 5173 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global); 5174 if (GV->isWeakForLinker()) { 5175 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals"); 5176 GV->setComdat(M.getOrInsertComdat(GV->getName())); 5177 } 5178 CGM.setDSOLocal(GV); 5179 5180 return GV; 5181 } 5182 5183 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a 5184 /// constant array for the given string literal. 5185 ConstantAddress 5186 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S, 5187 StringRef Name) { 5188 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType()); 5189 5190 llvm::Constant *C = GetConstantArrayFromStringLiteral(S); 5191 llvm::GlobalVariable **Entry = nullptr; 5192 if (!LangOpts.WritableStrings) { 5193 Entry = &ConstantStringMap[C]; 5194 if (auto GV = *Entry) { 5195 if (Alignment.getQuantity() > GV->getAlignment()) 5196 GV->setAlignment(Alignment.getAsAlign()); 5197 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5198 Alignment); 5199 } 5200 } 5201 5202 SmallString<256> MangledNameBuffer; 5203 StringRef GlobalVariableName; 5204 llvm::GlobalValue::LinkageTypes LT; 5205 5206 // Mangle the string literal if that's how the ABI merges duplicate strings. 5207 // Don't do it if they are writable, since we don't want writes in one TU to 5208 // affect strings in another. 5209 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) && 5210 !LangOpts.WritableStrings) { 5211 llvm::raw_svector_ostream Out(MangledNameBuffer); 5212 getCXXABI().getMangleContext().mangleStringLiteral(S, Out); 5213 LT = llvm::GlobalValue::LinkOnceODRLinkage; 5214 GlobalVariableName = MangledNameBuffer; 5215 } else { 5216 LT = llvm::GlobalValue::PrivateLinkage; 5217 GlobalVariableName = Name; 5218 } 5219 5220 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment); 5221 if (Entry) 5222 *Entry = GV; 5223 5224 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>", 5225 QualType()); 5226 5227 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5228 Alignment); 5229 } 5230 5231 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant 5232 /// array for the given ObjCEncodeExpr node. 5233 ConstantAddress 5234 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) { 5235 std::string Str; 5236 getContext().getObjCEncodingForType(E->getEncodedType(), Str); 5237 5238 return GetAddrOfConstantCString(Str); 5239 } 5240 5241 /// GetAddrOfConstantCString - Returns a pointer to a character array containing 5242 /// the literal and a terminating '\0' character. 5243 /// The result has pointer to array type. 5244 ConstantAddress CodeGenModule::GetAddrOfConstantCString( 5245 const std::string &Str, const char *GlobalName) { 5246 StringRef StrWithNull(Str.c_str(), Str.size() + 1); 5247 CharUnits Alignment = 5248 getContext().getAlignOfGlobalVarInChars(getContext().CharTy); 5249 5250 llvm::Constant *C = 5251 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false); 5252 5253 // Don't share any string literals if strings aren't constant. 5254 llvm::GlobalVariable **Entry = nullptr; 5255 if (!LangOpts.WritableStrings) { 5256 Entry = &ConstantStringMap[C]; 5257 if (auto GV = *Entry) { 5258 if (Alignment.getQuantity() > GV->getAlignment()) 5259 GV->setAlignment(Alignment.getAsAlign()); 5260 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5261 Alignment); 5262 } 5263 } 5264 5265 // Get the default prefix if a name wasn't specified. 5266 if (!GlobalName) 5267 GlobalName = ".str"; 5268 // Create a global variable for this. 5269 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this, 5270 GlobalName, Alignment); 5271 if (Entry) 5272 *Entry = GV; 5273 5274 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV), 5275 Alignment); 5276 } 5277 5278 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary( 5279 const MaterializeTemporaryExpr *E, const Expr *Init) { 5280 assert((E->getStorageDuration() == SD_Static || 5281 E->getStorageDuration() == SD_Thread) && "not a global temporary"); 5282 const auto *VD = cast<VarDecl>(E->getExtendingDecl()); 5283 5284 // If we're not materializing a subobject of the temporary, keep the 5285 // cv-qualifiers from the type of the MaterializeTemporaryExpr. 5286 QualType MaterializedType = Init->getType(); 5287 if (Init == E->getSubExpr()) 5288 MaterializedType = E->getType(); 5289 5290 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType); 5291 5292 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E]) 5293 return ConstantAddress(Slot, Align); 5294 5295 // FIXME: If an externally-visible declaration extends multiple temporaries, 5296 // we need to give each temporary the same name in every translation unit (and 5297 // we also need to make the temporaries externally-visible). 5298 SmallString<256> Name; 5299 llvm::raw_svector_ostream Out(Name); 5300 getCXXABI().getMangleContext().mangleReferenceTemporary( 5301 VD, E->getManglingNumber(), Out); 5302 5303 APValue *Value = nullptr; 5304 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) { 5305 // If the initializer of the extending declaration is a constant 5306 // initializer, we should have a cached constant initializer for this 5307 // temporary. Note that this might have a different value from the value 5308 // computed by evaluating the initializer if the surrounding constant 5309 // expression modifies the temporary. 5310 Value = E->getOrCreateValue(false); 5311 } 5312 5313 // Try evaluating it now, it might have a constant initializer. 5314 Expr::EvalResult EvalResult; 5315 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) && 5316 !EvalResult.hasSideEffects()) 5317 Value = &EvalResult.Val; 5318 5319 LangAS AddrSpace = 5320 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace(); 5321 5322 Optional<ConstantEmitter> emitter; 5323 llvm::Constant *InitialValue = nullptr; 5324 bool Constant = false; 5325 llvm::Type *Type; 5326 if (Value) { 5327 // The temporary has a constant initializer, use it. 5328 emitter.emplace(*this); 5329 InitialValue = emitter->emitForInitializer(*Value, AddrSpace, 5330 MaterializedType); 5331 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value); 5332 Type = InitialValue->getType(); 5333 } else { 5334 // No initializer, the initialization will be provided when we 5335 // initialize the declaration which performed lifetime extension. 5336 Type = getTypes().ConvertTypeForMem(MaterializedType); 5337 } 5338 5339 // Create a global variable for this lifetime-extended temporary. 5340 llvm::GlobalValue::LinkageTypes Linkage = 5341 getLLVMLinkageVarDefinition(VD, Constant); 5342 if (Linkage == llvm::GlobalVariable::ExternalLinkage) { 5343 const VarDecl *InitVD; 5344 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) && 5345 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) { 5346 // Temporaries defined inside a class get linkonce_odr linkage because the 5347 // class can be defined in multiple translation units. 5348 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage; 5349 } else { 5350 // There is no need for this temporary to have external linkage if the 5351 // VarDecl has external linkage. 5352 Linkage = llvm::GlobalVariable::InternalLinkage; 5353 } 5354 } 5355 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace); 5356 auto *GV = new llvm::GlobalVariable( 5357 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(), 5358 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS); 5359 if (emitter) emitter->finalize(GV); 5360 setGVProperties(GV, VD); 5361 GV->setAlignment(Align.getAsAlign()); 5362 if (supportsCOMDAT() && GV->isWeakForLinker()) 5363 GV->setComdat(TheModule.getOrInsertComdat(GV->getName())); 5364 if (VD->getTLSKind()) 5365 setTLSMode(GV, *VD); 5366 llvm::Constant *CV = GV; 5367 if (AddrSpace != LangAS::Default) 5368 CV = getTargetCodeGenInfo().performAddrSpaceCast( 5369 *this, GV, AddrSpace, LangAS::Default, 5370 Type->getPointerTo( 5371 getContext().getTargetAddressSpace(LangAS::Default))); 5372 MaterializedGlobalTemporaryMap[E] = CV; 5373 return ConstantAddress(CV, Align); 5374 } 5375 5376 /// EmitObjCPropertyImplementations - Emit information for synthesized 5377 /// properties for an implementation. 5378 void CodeGenModule::EmitObjCPropertyImplementations(const 5379 ObjCImplementationDecl *D) { 5380 for (const auto *PID : D->property_impls()) { 5381 // Dynamic is just for type-checking. 5382 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) { 5383 ObjCPropertyDecl *PD = PID->getPropertyDecl(); 5384 5385 // Determine which methods need to be implemented, some may have 5386 // been overridden. Note that ::isPropertyAccessor is not the method 5387 // we want, that just indicates if the decl came from a 5388 // property. What we want to know is if the method is defined in 5389 // this implementation. 5390 auto *Getter = PID->getGetterMethodDecl(); 5391 if (!Getter || Getter->isSynthesizedAccessorStub()) 5392 CodeGenFunction(*this).GenerateObjCGetter( 5393 const_cast<ObjCImplementationDecl *>(D), PID); 5394 auto *Setter = PID->getSetterMethodDecl(); 5395 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub())) 5396 CodeGenFunction(*this).GenerateObjCSetter( 5397 const_cast<ObjCImplementationDecl *>(D), PID); 5398 } 5399 } 5400 } 5401 5402 static bool needsDestructMethod(ObjCImplementationDecl *impl) { 5403 const ObjCInterfaceDecl *iface = impl->getClassInterface(); 5404 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin(); 5405 ivar; ivar = ivar->getNextIvar()) 5406 if (ivar->getType().isDestructedType()) 5407 return true; 5408 5409 return false; 5410 } 5411 5412 static bool AllTrivialInitializers(CodeGenModule &CGM, 5413 ObjCImplementationDecl *D) { 5414 CodeGenFunction CGF(CGM); 5415 for (ObjCImplementationDecl::init_iterator B = D->init_begin(), 5416 E = D->init_end(); B != E; ++B) { 5417 CXXCtorInitializer *CtorInitExp = *B; 5418 Expr *Init = CtorInitExp->getInit(); 5419 if (!CGF.isTrivialInitializer(Init)) 5420 return false; 5421 } 5422 return true; 5423 } 5424 5425 /// EmitObjCIvarInitializations - Emit information for ivar initialization 5426 /// for an implementation. 5427 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) { 5428 // We might need a .cxx_destruct even if we don't have any ivar initializers. 5429 if (needsDestructMethod(D)) { 5430 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct"); 5431 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5432 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create( 5433 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5434 getContext().VoidTy, nullptr, D, 5435 /*isInstance=*/true, /*isVariadic=*/false, 5436 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5437 /*isImplicitlyDeclared=*/true, 5438 /*isDefined=*/false, ObjCMethodDecl::Required); 5439 D->addInstanceMethod(DTORMethod); 5440 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false); 5441 D->setHasDestructors(true); 5442 } 5443 5444 // If the implementation doesn't have any ivar initializers, we don't need 5445 // a .cxx_construct. 5446 if (D->getNumIvarInitializers() == 0 || 5447 AllTrivialInitializers(*this, D)) 5448 return; 5449 5450 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct"); 5451 Selector cxxSelector = getContext().Selectors.getSelector(0, &II); 5452 // The constructor returns 'self'. 5453 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create( 5454 getContext(), D->getLocation(), D->getLocation(), cxxSelector, 5455 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true, 5456 /*isVariadic=*/false, 5457 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false, 5458 /*isImplicitlyDeclared=*/true, 5459 /*isDefined=*/false, ObjCMethodDecl::Required); 5460 D->addInstanceMethod(CTORMethod); 5461 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true); 5462 D->setHasNonZeroConstructors(true); 5463 } 5464 5465 // EmitLinkageSpec - Emit all declarations in a linkage spec. 5466 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) { 5467 if (LSD->getLanguage() != LinkageSpecDecl::lang_c && 5468 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) { 5469 ErrorUnsupported(LSD, "linkage spec"); 5470 return; 5471 } 5472 5473 EmitDeclContext(LSD); 5474 } 5475 5476 void CodeGenModule::EmitDeclContext(const DeclContext *DC) { 5477 for (auto *I : DC->decls()) { 5478 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope 5479 // are themselves considered "top-level", so EmitTopLevelDecl on an 5480 // ObjCImplDecl does not recursively visit them. We need to do that in 5481 // case they're nested inside another construct (LinkageSpecDecl / 5482 // ExportDecl) that does stop them from being considered "top-level". 5483 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) { 5484 for (auto *M : OID->methods()) 5485 EmitTopLevelDecl(M); 5486 } 5487 5488 EmitTopLevelDecl(I); 5489 } 5490 } 5491 5492 /// EmitTopLevelDecl - Emit code for a single top level declaration. 5493 void CodeGenModule::EmitTopLevelDecl(Decl *D) { 5494 // Ignore dependent declarations. 5495 if (D->isTemplated()) 5496 return; 5497 5498 // Consteval function shouldn't be emitted. 5499 if (auto *FD = dyn_cast<FunctionDecl>(D)) 5500 if (FD->isConsteval()) 5501 return; 5502 5503 switch (D->getKind()) { 5504 case Decl::CXXConversion: 5505 case Decl::CXXMethod: 5506 case Decl::Function: 5507 EmitGlobal(cast<FunctionDecl>(D)); 5508 // Always provide some coverage mapping 5509 // even for the functions that aren't emitted. 5510 AddDeferredUnusedCoverageMapping(D); 5511 break; 5512 5513 case Decl::CXXDeductionGuide: 5514 // Function-like, but does not result in code emission. 5515 break; 5516 5517 case Decl::Var: 5518 case Decl::Decomposition: 5519 case Decl::VarTemplateSpecialization: 5520 EmitGlobal(cast<VarDecl>(D)); 5521 if (auto *DD = dyn_cast<DecompositionDecl>(D)) 5522 for (auto *B : DD->bindings()) 5523 if (auto *HD = B->getHoldingVar()) 5524 EmitGlobal(HD); 5525 break; 5526 5527 // Indirect fields from global anonymous structs and unions can be 5528 // ignored; only the actual variable requires IR gen support. 5529 case Decl::IndirectField: 5530 break; 5531 5532 // C++ Decls 5533 case Decl::Namespace: 5534 EmitDeclContext(cast<NamespaceDecl>(D)); 5535 break; 5536 case Decl::ClassTemplateSpecialization: { 5537 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D); 5538 if (CGDebugInfo *DI = getModuleDebugInfo()) 5539 if (Spec->getSpecializationKind() == 5540 TSK_ExplicitInstantiationDefinition && 5541 Spec->hasDefinition()) 5542 DI->completeTemplateDefinition(*Spec); 5543 } LLVM_FALLTHROUGH; 5544 case Decl::CXXRecord: { 5545 CXXRecordDecl *CRD = cast<CXXRecordDecl>(D); 5546 if (CGDebugInfo *DI = getModuleDebugInfo()) { 5547 if (CRD->hasDefinition()) 5548 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 5549 if (auto *ES = D->getASTContext().getExternalSource()) 5550 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never) 5551 DI->completeUnusedClass(*CRD); 5552 } 5553 // Emit any static data members, they may be definitions. 5554 for (auto *I : CRD->decls()) 5555 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I)) 5556 EmitTopLevelDecl(I); 5557 break; 5558 } 5559 // No code generation needed. 5560 case Decl::UsingShadow: 5561 case Decl::ClassTemplate: 5562 case Decl::VarTemplate: 5563 case Decl::Concept: 5564 case Decl::VarTemplatePartialSpecialization: 5565 case Decl::FunctionTemplate: 5566 case Decl::TypeAliasTemplate: 5567 case Decl::Block: 5568 case Decl::Empty: 5569 case Decl::Binding: 5570 break; 5571 case Decl::Using: // using X; [C++] 5572 if (CGDebugInfo *DI = getModuleDebugInfo()) 5573 DI->EmitUsingDecl(cast<UsingDecl>(*D)); 5574 break; 5575 case Decl::NamespaceAlias: 5576 if (CGDebugInfo *DI = getModuleDebugInfo()) 5577 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D)); 5578 break; 5579 case Decl::UsingDirective: // using namespace X; [C++] 5580 if (CGDebugInfo *DI = getModuleDebugInfo()) 5581 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D)); 5582 break; 5583 case Decl::CXXConstructor: 5584 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D)); 5585 break; 5586 case Decl::CXXDestructor: 5587 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D)); 5588 break; 5589 5590 case Decl::StaticAssert: 5591 // Nothing to do. 5592 break; 5593 5594 // Objective-C Decls 5595 5596 // Forward declarations, no (immediate) code generation. 5597 case Decl::ObjCInterface: 5598 case Decl::ObjCCategory: 5599 break; 5600 5601 case Decl::ObjCProtocol: { 5602 auto *Proto = cast<ObjCProtocolDecl>(D); 5603 if (Proto->isThisDeclarationADefinition()) 5604 ObjCRuntime->GenerateProtocol(Proto); 5605 break; 5606 } 5607 5608 case Decl::ObjCCategoryImpl: 5609 // Categories have properties but don't support synthesize so we 5610 // can ignore them here. 5611 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D)); 5612 break; 5613 5614 case Decl::ObjCImplementation: { 5615 auto *OMD = cast<ObjCImplementationDecl>(D); 5616 EmitObjCPropertyImplementations(OMD); 5617 EmitObjCIvarInitializations(OMD); 5618 ObjCRuntime->GenerateClass(OMD); 5619 // Emit global variable debug information. 5620 if (CGDebugInfo *DI = getModuleDebugInfo()) 5621 if (getCodeGenOpts().hasReducedDebugInfo()) 5622 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType( 5623 OMD->getClassInterface()), OMD->getLocation()); 5624 break; 5625 } 5626 case Decl::ObjCMethod: { 5627 auto *OMD = cast<ObjCMethodDecl>(D); 5628 // If this is not a prototype, emit the body. 5629 if (OMD->getBody()) 5630 CodeGenFunction(*this).GenerateObjCMethod(OMD); 5631 break; 5632 } 5633 case Decl::ObjCCompatibleAlias: 5634 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D)); 5635 break; 5636 5637 case Decl::PragmaComment: { 5638 const auto *PCD = cast<PragmaCommentDecl>(D); 5639 switch (PCD->getCommentKind()) { 5640 case PCK_Unknown: 5641 llvm_unreachable("unexpected pragma comment kind"); 5642 case PCK_Linker: 5643 AppendLinkerOptions(PCD->getArg()); 5644 break; 5645 case PCK_Lib: 5646 AddDependentLib(PCD->getArg()); 5647 break; 5648 case PCK_Compiler: 5649 case PCK_ExeStr: 5650 case PCK_User: 5651 break; // We ignore all of these. 5652 } 5653 break; 5654 } 5655 5656 case Decl::PragmaDetectMismatch: { 5657 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D); 5658 AddDetectMismatch(PDMD->getName(), PDMD->getValue()); 5659 break; 5660 } 5661 5662 case Decl::LinkageSpec: 5663 EmitLinkageSpec(cast<LinkageSpecDecl>(D)); 5664 break; 5665 5666 case Decl::FileScopeAsm: { 5667 // File-scope asm is ignored during device-side CUDA compilation. 5668 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) 5669 break; 5670 // File-scope asm is ignored during device-side OpenMP compilation. 5671 if (LangOpts.OpenMPIsDevice) 5672 break; 5673 auto *AD = cast<FileScopeAsmDecl>(D); 5674 getModule().appendModuleInlineAsm(AD->getAsmString()->getString()); 5675 break; 5676 } 5677 5678 case Decl::Import: { 5679 auto *Import = cast<ImportDecl>(D); 5680 5681 // If we've already imported this module, we're done. 5682 if (!ImportedModules.insert(Import->getImportedModule())) 5683 break; 5684 5685 // Emit debug information for direct imports. 5686 if (!Import->getImportedOwningModule()) { 5687 if (CGDebugInfo *DI = getModuleDebugInfo()) 5688 DI->EmitImportDecl(*Import); 5689 } 5690 5691 // Find all of the submodules and emit the module initializers. 5692 llvm::SmallPtrSet<clang::Module *, 16> Visited; 5693 SmallVector<clang::Module *, 16> Stack; 5694 Visited.insert(Import->getImportedModule()); 5695 Stack.push_back(Import->getImportedModule()); 5696 5697 while (!Stack.empty()) { 5698 clang::Module *Mod = Stack.pop_back_val(); 5699 if (!EmittedModuleInitializers.insert(Mod).second) 5700 continue; 5701 5702 for (auto *D : Context.getModuleInitializers(Mod)) 5703 EmitTopLevelDecl(D); 5704 5705 // Visit the submodules of this module. 5706 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(), 5707 SubEnd = Mod->submodule_end(); 5708 Sub != SubEnd; ++Sub) { 5709 // Skip explicit children; they need to be explicitly imported to emit 5710 // the initializers. 5711 if ((*Sub)->IsExplicit) 5712 continue; 5713 5714 if (Visited.insert(*Sub).second) 5715 Stack.push_back(*Sub); 5716 } 5717 } 5718 break; 5719 } 5720 5721 case Decl::Export: 5722 EmitDeclContext(cast<ExportDecl>(D)); 5723 break; 5724 5725 case Decl::OMPThreadPrivate: 5726 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D)); 5727 break; 5728 5729 case Decl::OMPAllocate: 5730 break; 5731 5732 case Decl::OMPDeclareReduction: 5733 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D)); 5734 break; 5735 5736 case Decl::OMPDeclareMapper: 5737 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D)); 5738 break; 5739 5740 case Decl::OMPRequires: 5741 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D)); 5742 break; 5743 5744 case Decl::Typedef: 5745 case Decl::TypeAlias: // using foo = bar; [C++11] 5746 if (CGDebugInfo *DI = getModuleDebugInfo()) 5747 DI->EmitAndRetainType( 5748 getContext().getTypedefType(cast<TypedefNameDecl>(D))); 5749 break; 5750 5751 case Decl::Record: 5752 if (CGDebugInfo *DI = getModuleDebugInfo()) 5753 if (cast<RecordDecl>(D)->getDefinition()) 5754 DI->EmitAndRetainType(getContext().getRecordType(cast<RecordDecl>(D))); 5755 break; 5756 5757 case Decl::Enum: 5758 if (CGDebugInfo *DI = getModuleDebugInfo()) 5759 if (cast<EnumDecl>(D)->getDefinition()) 5760 DI->EmitAndRetainType(getContext().getEnumType(cast<EnumDecl>(D))); 5761 break; 5762 5763 default: 5764 // Make sure we handled everything we should, every other kind is a 5765 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind 5766 // function. Need to recode Decl::Kind to do that easily. 5767 assert(isa<TypeDecl>(D) && "Unsupported decl kind"); 5768 break; 5769 } 5770 } 5771 5772 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) { 5773 // Do we need to generate coverage mapping? 5774 if (!CodeGenOpts.CoverageMapping) 5775 return; 5776 switch (D->getKind()) { 5777 case Decl::CXXConversion: 5778 case Decl::CXXMethod: 5779 case Decl::Function: 5780 case Decl::ObjCMethod: 5781 case Decl::CXXConstructor: 5782 case Decl::CXXDestructor: { 5783 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody()) 5784 break; 5785 SourceManager &SM = getContext().getSourceManager(); 5786 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc())) 5787 break; 5788 auto I = DeferredEmptyCoverageMappingDecls.find(D); 5789 if (I == DeferredEmptyCoverageMappingDecls.end()) 5790 DeferredEmptyCoverageMappingDecls[D] = true; 5791 break; 5792 } 5793 default: 5794 break; 5795 }; 5796 } 5797 5798 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) { 5799 // Do we need to generate coverage mapping? 5800 if (!CodeGenOpts.CoverageMapping) 5801 return; 5802 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) { 5803 if (Fn->isTemplateInstantiation()) 5804 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern()); 5805 } 5806 auto I = DeferredEmptyCoverageMappingDecls.find(D); 5807 if (I == DeferredEmptyCoverageMappingDecls.end()) 5808 DeferredEmptyCoverageMappingDecls[D] = false; 5809 else 5810 I->second = false; 5811 } 5812 5813 void CodeGenModule::EmitDeferredUnusedCoverageMappings() { 5814 // We call takeVector() here to avoid use-after-free. 5815 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because 5816 // we deserialize function bodies to emit coverage info for them, and that 5817 // deserializes more declarations. How should we handle that case? 5818 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) { 5819 if (!Entry.second) 5820 continue; 5821 const Decl *D = Entry.first; 5822 switch (D->getKind()) { 5823 case Decl::CXXConversion: 5824 case Decl::CXXMethod: 5825 case Decl::Function: 5826 case Decl::ObjCMethod: { 5827 CodeGenPGO PGO(*this); 5828 GlobalDecl GD(cast<FunctionDecl>(D)); 5829 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5830 getFunctionLinkage(GD)); 5831 break; 5832 } 5833 case Decl::CXXConstructor: { 5834 CodeGenPGO PGO(*this); 5835 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base); 5836 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5837 getFunctionLinkage(GD)); 5838 break; 5839 } 5840 case Decl::CXXDestructor: { 5841 CodeGenPGO PGO(*this); 5842 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base); 5843 PGO.emitEmptyCounterMapping(D, getMangledName(GD), 5844 getFunctionLinkage(GD)); 5845 break; 5846 } 5847 default: 5848 break; 5849 }; 5850 } 5851 } 5852 5853 void CodeGenModule::EmitMainVoidAlias() { 5854 // In order to transition away from "__original_main" gracefully, emit an 5855 // alias for "main" in the no-argument case so that libc can detect when 5856 // new-style no-argument main is in used. 5857 if (llvm::Function *F = getModule().getFunction("main")) { 5858 if (!F->isDeclaration() && F->arg_size() == 0 && !F->isVarArg() && 5859 F->getReturnType()->isIntegerTy(Context.getTargetInfo().getIntWidth())) 5860 addUsedGlobal(llvm::GlobalAlias::create("__main_void", F)); 5861 } 5862 } 5863 5864 /// Turns the given pointer into a constant. 5865 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context, 5866 const void *Ptr) { 5867 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr); 5868 llvm::Type *i64 = llvm::Type::getInt64Ty(Context); 5869 return llvm::ConstantInt::get(i64, PtrInt); 5870 } 5871 5872 static void EmitGlobalDeclMetadata(CodeGenModule &CGM, 5873 llvm::NamedMDNode *&GlobalMetadata, 5874 GlobalDecl D, 5875 llvm::GlobalValue *Addr) { 5876 if (!GlobalMetadata) 5877 GlobalMetadata = 5878 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs"); 5879 5880 // TODO: should we report variant information for ctors/dtors? 5881 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr), 5882 llvm::ConstantAsMetadata::get(GetPointerConstant( 5883 CGM.getLLVMContext(), D.getDecl()))}; 5884 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops)); 5885 } 5886 5887 /// For each function which is declared within an extern "C" region and marked 5888 /// as 'used', but has internal linkage, create an alias from the unmangled 5889 /// name to the mangled name if possible. People expect to be able to refer 5890 /// to such functions with an unmangled name from inline assembly within the 5891 /// same translation unit. 5892 void CodeGenModule::EmitStaticExternCAliases() { 5893 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases()) 5894 return; 5895 for (auto &I : StaticExternCValues) { 5896 IdentifierInfo *Name = I.first; 5897 llvm::GlobalValue *Val = I.second; 5898 if (Val && !getModule().getNamedValue(Name->getName())) 5899 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val)); 5900 } 5901 } 5902 5903 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName, 5904 GlobalDecl &Result) const { 5905 auto Res = Manglings.find(MangledName); 5906 if (Res == Manglings.end()) 5907 return false; 5908 Result = Res->getValue(); 5909 return true; 5910 } 5911 5912 /// Emits metadata nodes associating all the global values in the 5913 /// current module with the Decls they came from. This is useful for 5914 /// projects using IR gen as a subroutine. 5915 /// 5916 /// Since there's currently no way to associate an MDNode directly 5917 /// with an llvm::GlobalValue, we create a global named metadata 5918 /// with the name 'clang.global.decl.ptrs'. 5919 void CodeGenModule::EmitDeclMetadata() { 5920 llvm::NamedMDNode *GlobalMetadata = nullptr; 5921 5922 for (auto &I : MangledDeclNames) { 5923 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second); 5924 // Some mangled names don't necessarily have an associated GlobalValue 5925 // in this module, e.g. if we mangled it for DebugInfo. 5926 if (Addr) 5927 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr); 5928 } 5929 } 5930 5931 /// Emits metadata nodes for all the local variables in the current 5932 /// function. 5933 void CodeGenFunction::EmitDeclMetadata() { 5934 if (LocalDeclMap.empty()) return; 5935 5936 llvm::LLVMContext &Context = getLLVMContext(); 5937 5938 // Find the unique metadata ID for this name. 5939 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr"); 5940 5941 llvm::NamedMDNode *GlobalMetadata = nullptr; 5942 5943 for (auto &I : LocalDeclMap) { 5944 const Decl *D = I.first; 5945 llvm::Value *Addr = I.second.getPointer(); 5946 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) { 5947 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D); 5948 Alloca->setMetadata( 5949 DeclPtrKind, llvm::MDNode::get( 5950 Context, llvm::ValueAsMetadata::getConstant(DAddr))); 5951 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) { 5952 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D)); 5953 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV); 5954 } 5955 } 5956 } 5957 5958 void CodeGenModule::EmitVersionIdentMetadata() { 5959 llvm::NamedMDNode *IdentMetadata = 5960 TheModule.getOrInsertNamedMetadata("llvm.ident"); 5961 std::string Version = getClangFullVersion(); 5962 llvm::LLVMContext &Ctx = TheModule.getContext(); 5963 5964 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)}; 5965 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode)); 5966 } 5967 5968 void CodeGenModule::EmitCommandLineMetadata() { 5969 llvm::NamedMDNode *CommandLineMetadata = 5970 TheModule.getOrInsertNamedMetadata("llvm.commandline"); 5971 std::string CommandLine = getCodeGenOpts().RecordCommandLine; 5972 llvm::LLVMContext &Ctx = TheModule.getContext(); 5973 5974 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)}; 5975 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode)); 5976 } 5977 5978 void CodeGenModule::EmitCoverageFile() { 5979 if (getCodeGenOpts().CoverageDataFile.empty() && 5980 getCodeGenOpts().CoverageNotesFile.empty()) 5981 return; 5982 5983 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu"); 5984 if (!CUNode) 5985 return; 5986 5987 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov"); 5988 llvm::LLVMContext &Ctx = TheModule.getContext(); 5989 auto *CoverageDataFile = 5990 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile); 5991 auto *CoverageNotesFile = 5992 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile); 5993 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) { 5994 llvm::MDNode *CU = CUNode->getOperand(i); 5995 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU}; 5996 GCov->addOperand(llvm::MDNode::get(Ctx, Elts)); 5997 } 5998 } 5999 6000 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty, 6001 bool ForEH) { 6002 // Return a bogus pointer if RTTI is disabled, unless it's for EH. 6003 // FIXME: should we even be calling this method if RTTI is disabled 6004 // and it's not for EH? 6005 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice || 6006 (getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice && 6007 getTriple().isNVPTX())) 6008 return llvm::Constant::getNullValue(Int8PtrTy); 6009 6010 if (ForEH && Ty->isObjCObjectPointerType() && 6011 LangOpts.ObjCRuntime.isGNUFamily()) 6012 return ObjCRuntime->GetEHType(Ty); 6013 6014 return getCXXABI().getAddrOfRTTIDescriptor(Ty); 6015 } 6016 6017 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) { 6018 // Do not emit threadprivates in simd-only mode. 6019 if (LangOpts.OpenMP && LangOpts.OpenMPSimd) 6020 return; 6021 for (auto RefExpr : D->varlists()) { 6022 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl()); 6023 bool PerformInit = 6024 VD->getAnyInitializer() && 6025 !VD->getAnyInitializer()->isConstantInitializer(getContext(), 6026 /*ForRef=*/false); 6027 6028 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD)); 6029 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition( 6030 VD, Addr, RefExpr->getBeginLoc(), PerformInit)) 6031 CXXGlobalInits.push_back(InitFunction); 6032 } 6033 } 6034 6035 llvm::Metadata * 6036 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map, 6037 StringRef Suffix) { 6038 llvm::Metadata *&InternalId = Map[T.getCanonicalType()]; 6039 if (InternalId) 6040 return InternalId; 6041 6042 if (isExternallyVisible(T->getLinkage())) { 6043 std::string OutName; 6044 llvm::raw_string_ostream Out(OutName); 6045 getCXXABI().getMangleContext().mangleTypeName(T, Out); 6046 Out << Suffix; 6047 6048 InternalId = llvm::MDString::get(getLLVMContext(), Out.str()); 6049 } else { 6050 InternalId = llvm::MDNode::getDistinct(getLLVMContext(), 6051 llvm::ArrayRef<llvm::Metadata *>()); 6052 } 6053 6054 return InternalId; 6055 } 6056 6057 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) { 6058 return CreateMetadataIdentifierImpl(T, MetadataIdMap, ""); 6059 } 6060 6061 llvm::Metadata * 6062 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) { 6063 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual"); 6064 } 6065 6066 // Generalize pointer types to a void pointer with the qualifiers of the 6067 // originally pointed-to type, e.g. 'const char *' and 'char * const *' 6068 // generalize to 'const void *' while 'char *' and 'const char **' generalize to 6069 // 'void *'. 6070 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) { 6071 if (!Ty->isPointerType()) 6072 return Ty; 6073 6074 return Ctx.getPointerType( 6075 QualType(Ctx.VoidTy).withCVRQualifiers( 6076 Ty->getPointeeType().getCVRQualifiers())); 6077 } 6078 6079 // Apply type generalization to a FunctionType's return and argument types 6080 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) { 6081 if (auto *FnType = Ty->getAs<FunctionProtoType>()) { 6082 SmallVector<QualType, 8> GeneralizedParams; 6083 for (auto &Param : FnType->param_types()) 6084 GeneralizedParams.push_back(GeneralizeType(Ctx, Param)); 6085 6086 return Ctx.getFunctionType( 6087 GeneralizeType(Ctx, FnType->getReturnType()), 6088 GeneralizedParams, FnType->getExtProtoInfo()); 6089 } 6090 6091 if (auto *FnType = Ty->getAs<FunctionNoProtoType>()) 6092 return Ctx.getFunctionNoProtoType( 6093 GeneralizeType(Ctx, FnType->getReturnType())); 6094 6095 llvm_unreachable("Encountered unknown FunctionType"); 6096 } 6097 6098 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) { 6099 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T), 6100 GeneralizedMetadataIdMap, ".generalized"); 6101 } 6102 6103 /// Returns whether this module needs the "all-vtables" type identifier. 6104 bool CodeGenModule::NeedAllVtablesTypeId() const { 6105 // Returns true if at least one of vtable-based CFI checkers is enabled and 6106 // is not in the trapping mode. 6107 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) && 6108 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) || 6109 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) && 6110 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) || 6111 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) && 6112 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) || 6113 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) && 6114 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast))); 6115 } 6116 6117 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable, 6118 CharUnits Offset, 6119 const CXXRecordDecl *RD) { 6120 llvm::Metadata *MD = 6121 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 6122 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6123 6124 if (CodeGenOpts.SanitizeCfiCrossDso) 6125 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD)) 6126 VTable->addTypeMetadata(Offset.getQuantity(), 6127 llvm::ConstantAsMetadata::get(CrossDsoTypeId)); 6128 6129 if (NeedAllVtablesTypeId()) { 6130 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables"); 6131 VTable->addTypeMetadata(Offset.getQuantity(), MD); 6132 } 6133 } 6134 6135 llvm::SanitizerStatReport &CodeGenModule::getSanStats() { 6136 if (!SanStats) 6137 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule()); 6138 6139 return *SanStats; 6140 } 6141 llvm::Value * 6142 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E, 6143 CodeGenFunction &CGF) { 6144 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType()); 6145 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr()); 6146 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false); 6147 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy, 6148 "__translate_sampler_initializer"), 6149 {C}); 6150 } 6151 6152 CharUnits CodeGenModule::getNaturalPointeeTypeAlignment( 6153 QualType T, LValueBaseInfo *BaseInfo, TBAAAccessInfo *TBAAInfo) { 6154 return getNaturalTypeAlignment(T->getPointeeType(), BaseInfo, TBAAInfo, 6155 /* forPointeeType= */ true); 6156 } 6157 6158 CharUnits CodeGenModule::getNaturalTypeAlignment(QualType T, 6159 LValueBaseInfo *BaseInfo, 6160 TBAAAccessInfo *TBAAInfo, 6161 bool forPointeeType) { 6162 if (TBAAInfo) 6163 *TBAAInfo = getTBAAAccessInfo(T); 6164 6165 // FIXME: This duplicates logic in ASTContext::getTypeAlignIfKnown. But 6166 // that doesn't return the information we need to compute BaseInfo. 6167 6168 // Honor alignment typedef attributes even on incomplete types. 6169 // We also honor them straight for C++ class types, even as pointees; 6170 // there's an expressivity gap here. 6171 if (auto TT = T->getAs<TypedefType>()) { 6172 if (auto Align = TT->getDecl()->getMaxAlignment()) { 6173 if (BaseInfo) 6174 *BaseInfo = LValueBaseInfo(AlignmentSource::AttributedType); 6175 return getContext().toCharUnitsFromBits(Align); 6176 } 6177 } 6178 6179 bool AlignForArray = T->isArrayType(); 6180 6181 // Analyze the base element type, so we don't get confused by incomplete 6182 // array types. 6183 T = getContext().getBaseElementType(T); 6184 6185 if (T->isIncompleteType()) { 6186 // We could try to replicate the logic from 6187 // ASTContext::getTypeAlignIfKnown, but nothing uses the alignment if the 6188 // type is incomplete, so it's impossible to test. We could try to reuse 6189 // getTypeAlignIfKnown, but that doesn't return the information we need 6190 // to set BaseInfo. So just ignore the possibility that the alignment is 6191 // greater than one. 6192 if (BaseInfo) 6193 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6194 return CharUnits::One(); 6195 } 6196 6197 if (BaseInfo) 6198 *BaseInfo = LValueBaseInfo(AlignmentSource::Type); 6199 6200 CharUnits Alignment; 6201 const CXXRecordDecl *RD; 6202 if (T.getQualifiers().hasUnaligned()) { 6203 Alignment = CharUnits::One(); 6204 } else if (forPointeeType && !AlignForArray && 6205 (RD = T->getAsCXXRecordDecl())) { 6206 // For C++ class pointees, we don't know whether we're pointing at a 6207 // base or a complete object, so we generally need to use the 6208 // non-virtual alignment. 6209 Alignment = getClassPointerAlignment(RD); 6210 } else { 6211 Alignment = getContext().getTypeAlignInChars(T); 6212 } 6213 6214 // Cap to the global maximum type alignment unless the alignment 6215 // was somehow explicit on the type. 6216 if (unsigned MaxAlign = getLangOpts().MaxTypeAlign) { 6217 if (Alignment.getQuantity() > MaxAlign && 6218 !getContext().isAlignmentRequired(T)) 6219 Alignment = CharUnits::fromQuantity(MaxAlign); 6220 } 6221 return Alignment; 6222 } 6223 6224 bool CodeGenModule::stopAutoInit() { 6225 unsigned StopAfter = getContext().getLangOpts().TrivialAutoVarInitStopAfter; 6226 if (StopAfter) { 6227 // This number is positive only when -ftrivial-auto-var-init-stop-after=* is 6228 // used 6229 if (NumAutoVarInit >= StopAfter) { 6230 return true; 6231 } 6232 if (!NumAutoVarInit) { 6233 unsigned DiagID = getDiags().getCustomDiagID( 6234 DiagnosticsEngine::Warning, 6235 "-ftrivial-auto-var-init-stop-after=%0 has been enabled to limit the " 6236 "number of times ftrivial-auto-var-init=%1 gets applied."); 6237 getDiags().Report(DiagID) 6238 << StopAfter 6239 << (getContext().getLangOpts().getTrivialAutoVarInit() == 6240 LangOptions::TrivialAutoVarInitKind::Zero 6241 ? "zero" 6242 : "pattern"); 6243 } 6244 ++NumAutoVarInit; 6245 } 6246 return false; 6247 } 6248