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