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