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