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