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