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