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