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