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