1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
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
7 //===----------------------------------------------------------------------===//
9 // This coordinates the per-module state used while generating code.
11 //===----------------------------------------------------------------------===//
13 #include "CodeGenModule.h"
15 #include "CGCUDARuntime.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/Frontend/OpenMP/OMPIRBuilder.h"
51 #include "llvm/IR/CallingConv.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/Intrinsics.h"
54 #include "llvm/IR/LLVMContext.h"
55 #include "llvm/IR/Module.h"
56 #include "llvm/IR/ProfileSummary.h"
57 #include "llvm/ProfileData/InstrProfReader.h"
58 #include "llvm/Support/CodeGen.h"
59 #include "llvm/Support/CommandLine.h"
60 #include "llvm/Support/ConvertUTF.h"
61 #include "llvm/Support/ErrorHandling.h"
62 #include "llvm/Support/MD5.h"
63 #include "llvm/Support/TimeProfiler.h"
65 using namespace clang;
66 using namespace CodeGen;
68 static llvm::cl::opt<bool> LimitedCoverage(
69 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
70 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
71 llvm::cl::init(false));
73 static const char AnnotationSection[] = "llvm.metadata";
75 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
76 switch (CGM.getTarget().getCXXABI().getKind()) {
77 case TargetCXXABI::Fuchsia:
78 case TargetCXXABI::GenericAArch64:
79 case TargetCXXABI::GenericARM:
80 case TargetCXXABI::iOS:
81 case TargetCXXABI::iOS64:
82 case TargetCXXABI::WatchOS:
83 case TargetCXXABI::GenericMIPS:
84 case TargetCXXABI::GenericItanium:
85 case TargetCXXABI::WebAssembly:
86 return CreateItaniumCXXABI(CGM);
87 case TargetCXXABI::Microsoft:
88 return CreateMicrosoftCXXABI(CGM);
91 llvm_unreachable("invalid C++ ABI kind");
94 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
95 const PreprocessorOptions &PPO,
96 const CodeGenOptions &CGO, llvm::Module &M,
97 DiagnosticsEngine &diags,
98 CoverageSourceInfo *CoverageInfo)
99 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
100 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
101 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
102 VMContext(M.getContext()), Types(*this), VTables(*this),
103 SanitizerMD(new SanitizerMetadata(*this)) {
105 // Initialize the type cache.
106 llvm::LLVMContext &LLVMContext = M.getContext();
107 VoidTy = llvm::Type::getVoidTy(LLVMContext);
108 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
109 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
110 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
111 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
112 HalfTy = llvm::Type::getHalfTy(LLVMContext);
113 FloatTy = llvm::Type::getFloatTy(LLVMContext);
114 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
115 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
116 PointerAlignInBytes =
117 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
119 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
121 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
122 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
123 IntPtrTy = llvm::IntegerType::get(LLVMContext,
124 C.getTargetInfo().getMaxPointerWidth());
125 Int8PtrTy = Int8Ty->getPointerTo(0);
126 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
127 AllocaInt8PtrTy = Int8Ty->getPointerTo(
128 M.getDataLayout().getAllocaAddrSpace());
129 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
131 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
136 createOpenCLRuntime();
138 createOpenMPRuntime();
142 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
143 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
144 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
145 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
146 getCXXABI().getMangleContext()));
148 // If debug info or coverage generation is enabled, create the CGDebugInfo
150 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
151 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
152 DebugInfo.reset(new CGDebugInfo(*this));
154 Block.GlobalUniqueCount = 0;
156 if (C.getLangOpts().ObjC)
157 ObjCData.reset(new ObjCEntrypoints());
159 if (CodeGenOpts.hasProfileClangUse()) {
160 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
161 CodeGenOpts.ProfileInstrumentUsePath, CodeGenOpts.ProfileRemappingFile);
162 if (auto E = ReaderOrErr.takeError()) {
163 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
164 "Could not read profile %0: %1");
165 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
166 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
170 PGOReader = std::move(ReaderOrErr.get());
173 // If coverage mapping generation is enabled, create the
174 // CoverageMappingModuleGen object.
175 if (CodeGenOpts.CoverageMapping)
176 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
179 CodeGenModule::~CodeGenModule() {}
181 void CodeGenModule::createObjCRuntime() {
182 // This is just isGNUFamily(), but we want to force implementors of
183 // new ABIs to decide how best to do this.
184 switch (LangOpts.ObjCRuntime.getKind()) {
185 case ObjCRuntime::GNUstep:
186 case ObjCRuntime::GCC:
187 case ObjCRuntime::ObjFW:
188 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
191 case ObjCRuntime::FragileMacOSX:
192 case ObjCRuntime::MacOSX:
193 case ObjCRuntime::iOS:
194 case ObjCRuntime::WatchOS:
195 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
198 llvm_unreachable("bad runtime kind");
201 void CodeGenModule::createOpenCLRuntime() {
202 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
205 void CodeGenModule::createOpenMPRuntime() {
206 // Select a specialized code generation class based on the target, if any.
207 // If it does not exist use the default implementation.
208 switch (getTriple().getArch()) {
209 case llvm::Triple::nvptx:
210 case llvm::Triple::nvptx64:
211 assert(getLangOpts().OpenMPIsDevice &&
212 "OpenMP NVPTX is only prepared to deal with device code.");
213 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
216 if (LangOpts.OpenMPSimd)
217 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
219 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
223 // The OpenMP-IR-Builder should eventually replace the above runtime codegens
224 // but we are not there yet so they both reside in CGModule for now and the
225 // OpenMP-IR-Builder is opt-in only.
226 if (LangOpts.OpenMPIRBuilder) {
227 OMPBuilder.reset(new llvm::OpenMPIRBuilder(TheModule));
228 OMPBuilder->initialize();
232 void CodeGenModule::createCUDARuntime() {
233 CUDARuntime.reset(CreateNVCUDARuntime(*this));
236 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
237 Replacements[Name] = C;
240 void CodeGenModule::applyReplacements() {
241 for (auto &I : Replacements) {
242 StringRef MangledName = I.first();
243 llvm::Constant *Replacement = I.second;
244 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
247 auto *OldF = cast<llvm::Function>(Entry);
248 auto *NewF = dyn_cast<llvm::Function>(Replacement);
250 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
251 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
253 auto *CE = cast<llvm::ConstantExpr>(Replacement);
254 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
255 CE->getOpcode() == llvm::Instruction::GetElementPtr);
256 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
260 // Replace old with new, but keep the old order.
261 OldF->replaceAllUsesWith(Replacement);
263 NewF->removeFromParent();
264 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
267 OldF->eraseFromParent();
271 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
272 GlobalValReplacements.push_back(std::make_pair(GV, C));
275 void CodeGenModule::applyGlobalValReplacements() {
276 for (auto &I : GlobalValReplacements) {
277 llvm::GlobalValue *GV = I.first;
278 llvm::Constant *C = I.second;
280 GV->replaceAllUsesWith(C);
281 GV->eraseFromParent();
285 // This is only used in aliases that we created and we know they have a
287 static const llvm::GlobalObject *getAliasedGlobal(
288 const llvm::GlobalIndirectSymbol &GIS) {
289 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
290 const llvm::Constant *C = &GIS;
292 C = C->stripPointerCasts();
293 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
295 // stripPointerCasts will not walk over weak aliases.
296 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
299 if (!Visited.insert(GIS2).second)
301 C = GIS2->getIndirectSymbol();
305 void CodeGenModule::checkAliases() {
306 // Check if the constructed aliases are well formed. It is really unfortunate
307 // that we have to do this in CodeGen, but we only construct mangled names
308 // and aliases during codegen.
310 DiagnosticsEngine &Diags = getDiags();
311 for (const GlobalDecl &GD : Aliases) {
312 const auto *D = cast<ValueDecl>(GD.getDecl());
313 SourceLocation Location;
314 bool IsIFunc = D->hasAttr<IFuncAttr>();
315 if (const Attr *A = D->getDefiningAttr())
316 Location = A->getLocation();
318 llvm_unreachable("Not an alias or ifunc?");
319 StringRef MangledName = getMangledName(GD);
320 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
321 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
322 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
325 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
326 } else if (GV->isDeclaration()) {
328 Diags.Report(Location, diag::err_alias_to_undefined)
329 << IsIFunc << IsIFunc;
330 } else if (IsIFunc) {
331 // Check resolver function type.
332 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
333 GV->getType()->getPointerElementType());
335 if (!FTy->getReturnType()->isPointerTy())
336 Diags.Report(Location, diag::err_ifunc_resolver_return);
339 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
340 llvm::GlobalValue *AliaseeGV;
341 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
342 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
344 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
346 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
347 StringRef AliasSection = SA->getName();
348 if (AliasSection != AliaseeGV->getSection())
349 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
350 << AliasSection << IsIFunc << IsIFunc;
353 // We have to handle alias to weak aliases in here. LLVM itself disallows
354 // this since the object semantics would not match the IL one. For
355 // compatibility with gcc we implement it by just pointing the alias
356 // to its aliasee's aliasee. We also warn, since the user is probably
357 // expecting the link to be weak.
358 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
359 if (GA->isInterposable()) {
360 Diags.Report(Location, diag::warn_alias_to_weak_alias)
361 << GV->getName() << GA->getName() << IsIFunc;
362 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
363 GA->getIndirectSymbol(), Alias->getType());
364 Alias->setIndirectSymbol(Aliasee);
371 for (const GlobalDecl &GD : Aliases) {
372 StringRef MangledName = getMangledName(GD);
373 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
374 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
375 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
376 Alias->eraseFromParent();
380 void CodeGenModule::clear() {
381 DeferredDeclsToEmit.clear();
383 OpenMPRuntime->clear();
386 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
387 StringRef MainFile) {
388 if (!hasDiagnostics())
390 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
391 if (MainFile.empty())
392 MainFile = "<stdin>";
393 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
396 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
399 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
403 void CodeGenModule::Release() {
405 EmitVTablesOpportunistically();
406 applyGlobalValReplacements();
409 emitMultiVersionFunctions();
410 EmitCXXGlobalInitFunc();
411 EmitCXXGlobalDtorFunc();
412 registerGlobalDtorsWithAtExit();
413 EmitCXXThreadLocalInitFunc();
415 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
416 AddGlobalCtor(ObjCInitFunction);
417 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
419 if (llvm::Function *CudaCtorFunction =
420 CUDARuntime->makeModuleCtorFunction())
421 AddGlobalCtor(CudaCtorFunction);
424 if (llvm::Function *OpenMPRequiresDirectiveRegFun =
425 OpenMPRuntime->emitRequiresDirectiveRegFun()) {
426 AddGlobalCtor(OpenMPRequiresDirectiveRegFun, 0);
428 OpenMPRuntime->createOffloadEntriesAndInfoMetadata();
429 OpenMPRuntime->clear();
432 getModule().setProfileSummary(
433 PGOReader->getSummary(/* UseCS */ false).getMD(VMContext),
434 llvm::ProfileSummary::PSK_Instr);
435 if (PGOStats.hasDiagnostics())
436 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
438 EmitCtorList(GlobalCtors, "llvm.global_ctors");
439 EmitCtorList(GlobalDtors, "llvm.global_dtors");
440 EmitGlobalAnnotations();
441 EmitStaticExternCAliases();
442 EmitDeferredUnusedCoverageMappings();
444 CoverageMapping->emit();
445 if (CodeGenOpts.SanitizeCfiCrossDso) {
446 CodeGenFunction(*this).EmitCfiCheckFail();
447 CodeGenFunction(*this).EmitCfiCheckStub();
449 emitAtAvailableLinkGuard();
454 if (CodeGenOpts.Autolink &&
455 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
456 EmitModuleLinkOptions();
459 // On ELF we pass the dependent library specifiers directly to the linker
460 // without manipulating them. This is in contrast to other platforms where
461 // they are mapped to a specific linker option by the compiler. This
462 // difference is a result of the greater variety of ELF linkers and the fact
463 // that ELF linkers tend to handle libraries in a more complicated fashion
464 // than on other platforms. This forces us to defer handling the dependent
465 // libs to the linker.
467 // CUDA/HIP device and host libraries are different. Currently there is no
468 // way to differentiate dependent libraries for host or device. Existing
469 // usage of #pragma comment(lib, *) is intended for host libraries on
470 // Windows. Therefore emit llvm.dependent-libraries only for host.
471 if (!ELFDependentLibraries.empty() && !Context.getLangOpts().CUDAIsDevice) {
472 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.dependent-libraries");
473 for (auto *MD : ELFDependentLibraries)
477 // Record mregparm value now so it is visible through rest of codegen.
478 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
479 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
480 CodeGenOpts.NumRegisterParameters);
482 if (CodeGenOpts.DwarfVersion) {
483 getModule().addModuleFlag(llvm::Module::Max, "Dwarf Version",
484 CodeGenOpts.DwarfVersion);
486 if (CodeGenOpts.EmitCodeView) {
487 // Indicate that we want CodeView in the metadata.
488 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
490 if (CodeGenOpts.CodeViewGHash) {
491 getModule().addModuleFlag(llvm::Module::Warning, "CodeViewGHash", 1);
493 if (CodeGenOpts.ControlFlowGuard) {
494 // Function ID tables and checks for Control Flow Guard (cfguard=2).
495 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 2);
496 } else if (CodeGenOpts.ControlFlowGuardNoChecks) {
497 // Function ID tables for Control Flow Guard (cfguard=1).
498 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
500 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
501 // We don't support LTO with 2 with different StrictVTablePointers
502 // FIXME: we could support it by stripping all the information introduced
503 // by StrictVTablePointers.
505 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
507 llvm::Metadata *Ops[2] = {
508 llvm::MDString::get(VMContext, "StrictVTablePointers"),
509 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
510 llvm::Type::getInt32Ty(VMContext), 1))};
512 getModule().addModuleFlag(llvm::Module::Require,
513 "StrictVTablePointersRequirement",
514 llvm::MDNode::get(VMContext, Ops));
517 // We support a single version in the linked module. The LLVM
518 // parser will drop debug info with a different version number
519 // (and warn about it, too).
520 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
521 llvm::DEBUG_METADATA_VERSION);
523 // We need to record the widths of enums and wchar_t, so that we can generate
524 // the correct build attributes in the ARM backend. wchar_size is also used by
525 // TargetLibraryInfo.
526 uint64_t WCharWidth =
527 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
528 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
530 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
531 if ( Arch == llvm::Triple::arm
532 || Arch == llvm::Triple::armeb
533 || Arch == llvm::Triple::thumb
534 || Arch == llvm::Triple::thumbeb) {
535 // The minimum width of an enum in bytes
536 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
537 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
540 if (Arch == llvm::Triple::riscv32 || Arch == llvm::Triple::riscv64) {
541 StringRef ABIStr = Target.getABI();
542 llvm::LLVMContext &Ctx = TheModule.getContext();
543 getModule().addModuleFlag(llvm::Module::Error, "target-abi",
544 llvm::MDString::get(Ctx, ABIStr));
547 if (CodeGenOpts.SanitizeCfiCrossDso) {
548 // Indicate that we want cross-DSO control flow integrity checks.
549 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
552 if (LangOpts.Sanitize.has(SanitizerKind::CFIICall)) {
553 getModule().addModuleFlag(llvm::Module::Override,
554 "CFI Canonical Jump Tables",
555 CodeGenOpts.SanitizeCfiCanonicalJumpTables);
558 if (CodeGenOpts.CFProtectionReturn &&
559 Target.checkCFProtectionReturnSupported(getDiags())) {
560 // Indicate that we want to instrument return control flow protection.
561 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
565 if (CodeGenOpts.CFProtectionBranch &&
566 Target.checkCFProtectionBranchSupported(getDiags())) {
567 // Indicate that we want to instrument branch control flow protection.
568 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
572 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
573 // Indicate whether __nvvm_reflect should be configured to flush denormal
574 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
576 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
577 CodeGenOpts.FlushDenorm ? 1 : 0);
580 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
581 if (LangOpts.OpenCL) {
582 EmitOpenCLMetadata();
583 // Emit SPIR version.
584 if (getTriple().isSPIR()) {
585 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
586 // opencl.spir.version named metadata.
587 // C++ is backwards compatible with OpenCL v2.0.
588 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
589 llvm::Metadata *SPIRVerElts[] = {
590 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
591 Int32Ty, Version / 100)),
592 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
593 Int32Ty, (Version / 100 > 1) ? 0 : 2))};
594 llvm::NamedMDNode *SPIRVerMD =
595 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
596 llvm::LLVMContext &Ctx = TheModule.getContext();
597 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
601 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
602 assert(PLevel < 3 && "Invalid PIC Level");
603 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
604 if (Context.getLangOpts().PIE)
605 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
608 if (getCodeGenOpts().CodeModel.size() > 0) {
609 unsigned CM = llvm::StringSwitch<unsigned>(getCodeGenOpts().CodeModel)
610 .Case("tiny", llvm::CodeModel::Tiny)
611 .Case("small", llvm::CodeModel::Small)
612 .Case("kernel", llvm::CodeModel::Kernel)
613 .Case("medium", llvm::CodeModel::Medium)
614 .Case("large", llvm::CodeModel::Large)
617 llvm::CodeModel::Model codeModel = static_cast<llvm::CodeModel::Model>(CM);
618 getModule().setCodeModel(codeModel);
622 if (CodeGenOpts.NoPLT)
623 getModule().setRtLibUseGOT();
625 SimplifyPersonality();
627 if (getCodeGenOpts().EmitDeclMetadata)
630 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
634 DebugInfo->finalize();
636 if (getCodeGenOpts().EmitVersionIdentMetadata)
637 EmitVersionIdentMetadata();
639 if (!getCodeGenOpts().RecordCommandLine.empty())
640 EmitCommandLineMetadata();
642 EmitTargetMetadata();
645 void CodeGenModule::EmitOpenCLMetadata() {
646 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
647 // opencl.ocl.version named metadata node.
648 // C++ is backwards compatible with OpenCL v2.0.
649 // FIXME: We might need to add CXX version at some point too?
650 auto Version = LangOpts.OpenCLCPlusPlus ? 200 : LangOpts.OpenCLVersion;
651 llvm::Metadata *OCLVerElts[] = {
652 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
653 Int32Ty, Version / 100)),
654 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
655 Int32Ty, (Version % 100) / 10))};
656 llvm::NamedMDNode *OCLVerMD =
657 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
658 llvm::LLVMContext &Ctx = TheModule.getContext();
659 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
662 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
663 // Make sure that this type is translated.
664 Types.UpdateCompletedType(TD);
667 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
668 // Make sure that this type is translated.
669 Types.RefreshTypeCacheForClass(RD);
672 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
675 return TBAA->getTypeInfo(QTy);
678 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
680 return TBAAAccessInfo();
681 return TBAA->getAccessInfo(AccessType);
685 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
687 return TBAAAccessInfo();
688 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
691 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
694 return TBAA->getTBAAStructInfo(QTy);
697 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
700 return TBAA->getBaseTypeInfo(QTy);
703 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
706 return TBAA->getAccessTagInfo(Info);
709 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
710 TBAAAccessInfo TargetInfo) {
712 return TBAAAccessInfo();
713 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
717 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
718 TBAAAccessInfo InfoB) {
720 return TBAAAccessInfo();
721 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
725 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
726 TBAAAccessInfo SrcInfo) {
728 return TBAAAccessInfo();
729 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
732 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
733 TBAAAccessInfo TBAAInfo) {
734 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
735 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
738 void CodeGenModule::DecorateInstructionWithInvariantGroup(
739 llvm::Instruction *I, const CXXRecordDecl *RD) {
740 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
741 llvm::MDNode::get(getLLVMContext(), {}));
744 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
745 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
746 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
749 /// ErrorUnsupported - Print out an error that codegen doesn't support the
750 /// specified stmt yet.
751 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
752 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
753 "cannot compile this %0 yet");
754 std::string Msg = Type;
755 getDiags().Report(Context.getFullLoc(S->getBeginLoc()), DiagID)
756 << Msg << S->getSourceRange();
759 /// ErrorUnsupported - Print out an error that codegen doesn't support the
760 /// specified decl yet.
761 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
762 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
763 "cannot compile this %0 yet");
764 std::string Msg = Type;
765 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
768 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
769 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
772 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
773 const NamedDecl *D) const {
774 if (GV->hasDLLImportStorageClass())
776 // Internal definitions always have default visibility.
777 if (GV->hasLocalLinkage()) {
778 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
783 // Set visibility for definitions, and for declarations if requested globally
784 // or set explicitly.
785 LinkageInfo LV = D->getLinkageAndVisibility();
786 if (LV.isVisibilityExplicit() || getLangOpts().SetVisibilityForExternDecls ||
787 !GV->isDeclarationForLinker())
788 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
791 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
792 llvm::GlobalValue *GV) {
793 if (GV->hasLocalLinkage())
796 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
799 // DLLImport explicitly marks the GV as external.
800 if (GV->hasDLLImportStorageClass())
803 const llvm::Triple &TT = CGM.getTriple();
804 if (TT.isWindowsGNUEnvironment()) {
805 // In MinGW, variables without DLLImport can still be automatically
806 // imported from a DLL by the linker; don't mark variables that
807 // potentially could come from another DLL as DSO local.
808 if (GV->isDeclarationForLinker() && isa<llvm::GlobalVariable>(GV) &&
809 !GV->isThreadLocal())
813 // On COFF, don't mark 'extern_weak' symbols as DSO local. If these symbols
814 // remain unresolved in the link, they can be resolved to zero, which is
815 // outside the current DSO.
816 if (TT.isOSBinFormatCOFF() && GV->hasExternalWeakLinkage())
819 // Every other GV is local on COFF.
820 // Make an exception for windows OS in the triple: Some firmware builds use
821 // *-win32-macho triples. This (accidentally?) produced windows relocations
822 // without GOT tables in older clang versions; Keep this behaviour.
823 // FIXME: even thread local variables?
824 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
827 // Only handle COFF and ELF for now.
828 if (!TT.isOSBinFormatELF())
831 // If this is not an executable, don't assume anything is local.
832 const auto &CGOpts = CGM.getCodeGenOpts();
833 llvm::Reloc::Model RM = CGOpts.RelocationModel;
834 const auto &LOpts = CGM.getLangOpts();
835 if (RM != llvm::Reloc::Static && !LOpts.PIE)
838 // A definition cannot be preempted from an executable.
839 if (!GV->isDeclarationForLinker())
842 // Most PIC code sequences that assume that a symbol is local cannot produce a
843 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
844 // depended, it seems worth it to handle it here.
845 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
848 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
849 llvm::Triple::ArchType Arch = TT.getArch();
850 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
851 Arch == llvm::Triple::ppc64le)
854 // If we can use copy relocations we can assume it is local.
855 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
856 if (!Var->isThreadLocal() &&
857 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
860 // If we can use a plt entry as the symbol address we can assume it
862 // FIXME: This should work for PIE, but the gold linker doesn't support it.
863 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
866 // Otherwise don't assue it is local.
870 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
871 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
874 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
875 GlobalDecl GD) const {
876 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
877 // C++ destructors have a few C++ ABI specific special cases.
878 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
879 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
882 setDLLImportDLLExport(GV, D);
885 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
886 const NamedDecl *D) const {
887 if (D && D->isExternallyVisible()) {
888 if (D->hasAttr<DLLImportAttr>())
889 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
890 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
891 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
895 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
896 GlobalDecl GD) const {
897 setDLLImportDLLExport(GV, GD);
898 setGVPropertiesAux(GV, dyn_cast<NamedDecl>(GD.getDecl()));
901 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
902 const NamedDecl *D) const {
903 setDLLImportDLLExport(GV, D);
904 setGVPropertiesAux(GV, D);
907 void CodeGenModule::setGVPropertiesAux(llvm::GlobalValue *GV,
908 const NamedDecl *D) const {
909 setGlobalVisibility(GV, D);
911 GV->setPartition(CodeGenOpts.SymbolPartition);
914 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
915 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
916 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
917 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
918 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
919 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
922 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
923 CodeGenOptions::TLSModel M) {
925 case CodeGenOptions::GeneralDynamicTLSModel:
926 return llvm::GlobalVariable::GeneralDynamicTLSModel;
927 case CodeGenOptions::LocalDynamicTLSModel:
928 return llvm::GlobalVariable::LocalDynamicTLSModel;
929 case CodeGenOptions::InitialExecTLSModel:
930 return llvm::GlobalVariable::InitialExecTLSModel;
931 case CodeGenOptions::LocalExecTLSModel:
932 return llvm::GlobalVariable::LocalExecTLSModel;
934 llvm_unreachable("Invalid TLS model!");
937 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
938 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
940 llvm::GlobalValue::ThreadLocalMode TLM;
941 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
943 // Override the TLS model if it is explicitly specified.
944 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
945 TLM = GetLLVMTLSModel(Attr->getModel());
948 GV->setThreadLocalMode(TLM);
951 static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
953 const TargetInfo &Target = CGM.getTarget();
954 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
957 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
958 const CPUSpecificAttr *Attr,
961 // cpu_specific gets the current name, dispatch gets the resolver if IFunc is
964 Out << getCPUSpecificMangling(CGM, Attr->getCPUName(CPUIndex)->getName());
965 else if (CGM.getTarget().supportsIFunc())
969 static void AppendTargetMangling(const CodeGenModule &CGM,
970 const TargetAttr *Attr, raw_ostream &Out) {
971 if (Attr->isDefaultVersion())
975 const TargetInfo &Target = CGM.getTarget();
976 ParsedTargetAttr Info =
977 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
978 // Multiversioning doesn't allow "no-${feature}", so we can
979 // only have "+" prefixes here.
980 assert(LHS.startswith("+") && RHS.startswith("+") &&
981 "Features should always have a prefix.");
982 return Target.multiVersionSortPriority(LHS.substr(1)) >
983 Target.multiVersionSortPriority(RHS.substr(1));
988 if (!Info.Architecture.empty()) {
990 Out << "arch_" << Info.Architecture;
993 for (StringRef Feat : Info.Features) {
997 Out << Feat.substr(1);
1001 static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
1002 const NamedDecl *ND,
1003 bool OmitMultiVersionMangling = false) {
1004 SmallString<256> Buffer;
1005 llvm::raw_svector_ostream Out(Buffer);
1006 MangleContext &MC = CGM.getCXXABI().getMangleContext();
1007 if (MC.shouldMangleDeclName(ND)) {
1008 llvm::raw_svector_ostream Out(Buffer);
1009 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
1010 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
1011 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
1012 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
1014 MC.mangleName(ND, Out);
1016 IdentifierInfo *II = ND->getIdentifier();
1017 assert(II && "Attempt to mangle unnamed decl.");
1018 const auto *FD = dyn_cast<FunctionDecl>(ND);
1021 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
1022 llvm::raw_svector_ostream Out(Buffer);
1023 Out << "__regcall3__" << II->getName();
1025 Out << II->getName();
1029 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
1030 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
1031 switch (FD->getMultiVersionKind()) {
1032 case MultiVersionKind::CPUDispatch:
1033 case MultiVersionKind::CPUSpecific:
1034 AppendCPUSpecificCPUDispatchMangling(CGM,
1035 FD->getAttr<CPUSpecificAttr>(),
1036 GD.getMultiVersionIndex(), Out);
1038 case MultiVersionKind::Target:
1039 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
1041 case MultiVersionKind::None:
1042 llvm_unreachable("None multiversion type isn't valid here");
1049 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
1050 const FunctionDecl *FD) {
1051 if (!FD->isMultiVersion())
1054 // Get the name of what this would be without the 'target' attribute. This
1055 // allows us to lookup the version that was emitted when this wasn't a
1056 // multiversion function.
1057 std::string NonTargetName =
1058 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
1060 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
1061 assert(OtherGD.getCanonicalDecl()
1064 ->isMultiVersion() &&
1065 "Other GD should now be a multiversioned function");
1066 // OtherFD is the version of this function that was mangled BEFORE
1067 // becoming a MultiVersion function. It potentially needs to be updated.
1068 const FunctionDecl *OtherFD = OtherGD.getCanonicalDecl()
1071 ->getMostRecentDecl();
1072 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
1073 // This is so that if the initial version was already the 'default'
1074 // version, we don't try to update it.
1075 if (OtherName != NonTargetName) {
1076 // Remove instead of erase, since others may have stored the StringRef
1078 const auto ExistingRecord = Manglings.find(NonTargetName);
1079 if (ExistingRecord != std::end(Manglings))
1080 Manglings.remove(&(*ExistingRecord));
1081 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
1082 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
1083 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
1084 Entry->setName(OtherName);
1089 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
1090 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
1092 // Some ABIs don't have constructor variants. Make sure that base and
1093 // complete constructors get mangled the same.
1094 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
1095 if (!getTarget().getCXXABI().hasConstructorVariants()) {
1096 CXXCtorType OrigCtorType = GD.getCtorType();
1097 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
1098 if (OrigCtorType == Ctor_Base)
1099 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1103 auto FoundName = MangledDeclNames.find(CanonicalGD);
1104 if (FoundName != MangledDeclNames.end())
1105 return FoundName->second;
1107 // Keep the first result in the case of a mangling collision.
1108 const auto *ND = cast<NamedDecl>(GD.getDecl());
1109 std::string MangledName = getMangledNameImpl(*this, GD, ND);
1111 // Adjust kernel stub mangling as we may need to be able to differentiate
1112 // them from the kernel itself (e.g., for HIP).
1113 if (auto *FD = dyn_cast<FunctionDecl>(GD.getDecl()))
1114 if (!getLangOpts().CUDAIsDevice && FD->hasAttr<CUDAGlobalAttr>())
1115 MangledName = getCUDARuntime().getDeviceStubName(MangledName);
1117 auto Result = Manglings.insert(std::make_pair(MangledName, GD));
1118 return MangledDeclNames[CanonicalGD] = Result.first->first();
1121 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1122 const BlockDecl *BD) {
1123 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1124 const Decl *D = GD.getDecl();
1126 SmallString<256> Buffer;
1127 llvm::raw_svector_ostream Out(Buffer);
1129 MangleCtx.mangleGlobalBlock(BD,
1130 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1131 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1132 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1133 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1134 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1136 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1138 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1139 return Result.first->first();
1142 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1143 return getModule().getNamedValue(Name);
1146 /// AddGlobalCtor - Add a function to the list that will be called before
1148 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1149 llvm::Constant *AssociatedData) {
1150 // FIXME: Type coercion of void()* types.
1151 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1154 /// AddGlobalDtor - Add a function to the list that will be called
1155 /// when the module is unloaded.
1156 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
1157 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1158 DtorsUsingAtExit[Priority].push_back(Dtor);
1162 // FIXME: Type coercion of void()* types.
1163 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1166 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1167 if (Fns.empty()) return;
1169 // Ctor function type is void()*.
1170 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1171 llvm::Type *CtorPFTy = llvm::PointerType::get(CtorFTy,
1172 TheModule.getDataLayout().getProgramAddressSpace());
1174 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1175 llvm::StructType *CtorStructTy = llvm::StructType::get(
1176 Int32Ty, CtorPFTy, VoidPtrTy);
1178 // Construct the constructor and destructor arrays.
1179 ConstantInitBuilder builder(*this);
1180 auto ctors = builder.beginArray(CtorStructTy);
1181 for (const auto &I : Fns) {
1182 auto ctor = ctors.beginStruct(CtorStructTy);
1183 ctor.addInt(Int32Ty, I.Priority);
1184 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1185 if (I.AssociatedData)
1186 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1188 ctor.addNullPointer(VoidPtrTy);
1189 ctor.finishAndAddTo(ctors);
1193 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1195 llvm::GlobalValue::AppendingLinkage);
1197 // The LTO linker doesn't seem to like it when we set an alignment
1198 // on appending variables. Take it off as a workaround.
1199 list->setAlignment(llvm::None);
1204 llvm::GlobalValue::LinkageTypes
1205 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1206 const auto *D = cast<FunctionDecl>(GD.getDecl());
1208 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1210 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1211 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1213 if (isa<CXXConstructorDecl>(D) &&
1214 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1215 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1216 // Our approach to inheriting constructors is fundamentally different from
1217 // that used by the MS ABI, so keep our inheriting constructor thunks
1218 // internal rather than trying to pick an unambiguous mangling for them.
1219 return llvm::GlobalValue::InternalLinkage;
1222 return getLLVMLinkageForDeclarator(D, Linkage, /*IsConstantVariable=*/false);
1225 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1226 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1227 if (!MDS) return nullptr;
1229 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1232 void CodeGenModule::SetLLVMFunctionAttributes(GlobalDecl GD,
1233 const CGFunctionInfo &Info,
1234 llvm::Function *F) {
1235 unsigned CallingConv;
1236 llvm::AttributeList PAL;
1237 ConstructAttributeList(F->getName(), Info, GD, PAL, CallingConv, false);
1238 F->setAttributes(PAL);
1239 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1242 static void removeImageAccessQualifier(std::string& TyName) {
1243 std::string ReadOnlyQual("__read_only");
1244 std::string::size_type ReadOnlyPos = TyName.find(ReadOnlyQual);
1245 if (ReadOnlyPos != std::string::npos)
1246 // "+ 1" for the space after access qualifier.
1247 TyName.erase(ReadOnlyPos, ReadOnlyQual.size() + 1);
1249 std::string WriteOnlyQual("__write_only");
1250 std::string::size_type WriteOnlyPos = TyName.find(WriteOnlyQual);
1251 if (WriteOnlyPos != std::string::npos)
1252 TyName.erase(WriteOnlyPos, WriteOnlyQual.size() + 1);
1254 std::string ReadWriteQual("__read_write");
1255 std::string::size_type ReadWritePos = TyName.find(ReadWriteQual);
1256 if (ReadWritePos != std::string::npos)
1257 TyName.erase(ReadWritePos, ReadWriteQual.size() + 1);
1262 // Returns the address space id that should be produced to the
1263 // kernel_arg_addr_space metadata. This is always fixed to the ids
1264 // as specified in the SPIR 2.0 specification in order to differentiate
1265 // for example in clGetKernelArgInfo() implementation between the address
1266 // spaces with targets without unique mapping to the OpenCL address spaces
1267 // (basically all single AS CPUs).
1268 static unsigned ArgInfoAddressSpace(LangAS AS) {
1270 case LangAS::opencl_global: return 1;
1271 case LangAS::opencl_constant: return 2;
1272 case LangAS::opencl_local: return 3;
1273 case LangAS::opencl_generic: return 4; // Not in SPIR 2.0 specs.
1275 return 0; // Assume private.
1279 void CodeGenModule::GenOpenCLArgMetadata(llvm::Function *Fn,
1280 const FunctionDecl *FD,
1281 CodeGenFunction *CGF) {
1282 assert(((FD && CGF) || (!FD && !CGF)) &&
1283 "Incorrect use - FD and CGF should either be both null or not!");
1284 // Create MDNodes that represent the kernel arg metadata.
1285 // Each MDNode is a list in the form of "key", N number of values which is
1286 // the same number of values as their are kernel arguments.
1288 const PrintingPolicy &Policy = Context.getPrintingPolicy();
1290 // MDNode for the kernel argument address space qualifiers.
1291 SmallVector<llvm::Metadata *, 8> addressQuals;
1293 // MDNode for the kernel argument access qualifiers (images only).
1294 SmallVector<llvm::Metadata *, 8> accessQuals;
1296 // MDNode for the kernel argument type names.
1297 SmallVector<llvm::Metadata *, 8> argTypeNames;
1299 // MDNode for the kernel argument base type names.
1300 SmallVector<llvm::Metadata *, 8> argBaseTypeNames;
1302 // MDNode for the kernel argument type qualifiers.
1303 SmallVector<llvm::Metadata *, 8> argTypeQuals;
1305 // MDNode for the kernel argument names.
1306 SmallVector<llvm::Metadata *, 8> argNames;
1309 for (unsigned i = 0, e = FD->getNumParams(); i != e; ++i) {
1310 const ParmVarDecl *parm = FD->getParamDecl(i);
1311 QualType ty = parm->getType();
1312 std::string typeQuals;
1314 if (ty->isPointerType()) {
1315 QualType pointeeTy = ty->getPointeeType();
1317 // Get address qualifier.
1318 addressQuals.push_back(
1319 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(
1320 ArgInfoAddressSpace(pointeeTy.getAddressSpace()))));
1322 // Get argument type name.
1323 std::string typeName =
1324 pointeeTy.getUnqualifiedType().getAsString(Policy) + "*";
1326 // Turn "unsigned type" to "utype"
1327 std::string::size_type pos = typeName.find("unsigned");
1328 if (pointeeTy.isCanonical() && pos != std::string::npos)
1329 typeName.erase(pos + 1, 8);
1331 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1333 std::string baseTypeName =
1334 pointeeTy.getUnqualifiedType().getCanonicalType().getAsString(
1338 // Turn "unsigned type" to "utype"
1339 pos = baseTypeName.find("unsigned");
1340 if (pos != std::string::npos)
1341 baseTypeName.erase(pos + 1, 8);
1343 argBaseTypeNames.push_back(
1344 llvm::MDString::get(VMContext, baseTypeName));
1346 // Get argument type qualifiers:
1347 if (ty.isRestrictQualified())
1348 typeQuals = "restrict";
1349 if (pointeeTy.isConstQualified() ||
1350 (pointeeTy.getAddressSpace() == LangAS::opencl_constant))
1351 typeQuals += typeQuals.empty() ? "const" : " const";
1352 if (pointeeTy.isVolatileQualified())
1353 typeQuals += typeQuals.empty() ? "volatile" : " volatile";
1355 uint32_t AddrSpc = 0;
1356 bool isPipe = ty->isPipeType();
1357 if (ty->isImageType() || isPipe)
1358 AddrSpc = ArgInfoAddressSpace(LangAS::opencl_global);
1360 addressQuals.push_back(
1361 llvm::ConstantAsMetadata::get(CGF->Builder.getInt32(AddrSpc)));
1363 // Get argument type name.
1364 std::string typeName;
1366 typeName = ty.getCanonicalType()
1369 .getAsString(Policy);
1371 typeName = ty.getUnqualifiedType().getAsString(Policy);
1373 // Turn "unsigned type" to "utype"
1374 std::string::size_type pos = typeName.find("unsigned");
1375 if (ty.isCanonical() && pos != std::string::npos)
1376 typeName.erase(pos + 1, 8);
1378 std::string baseTypeName;
1380 baseTypeName = ty.getCanonicalType()
1384 .getAsString(Policy);
1387 ty.getUnqualifiedType().getCanonicalType().getAsString(Policy);
1389 // Remove access qualifiers on images
1390 // (as they are inseparable from type in clang implementation,
1391 // but OpenCL spec provides a special query to get access qualifier
1392 // via clGetKernelArgInfo with CL_KERNEL_ARG_ACCESS_QUALIFIER):
1393 if (ty->isImageType()) {
1394 removeImageAccessQualifier(typeName);
1395 removeImageAccessQualifier(baseTypeName);
1398 argTypeNames.push_back(llvm::MDString::get(VMContext, typeName));
1400 // Turn "unsigned type" to "utype"
1401 pos = baseTypeName.find("unsigned");
1402 if (pos != std::string::npos)
1403 baseTypeName.erase(pos + 1, 8);
1405 argBaseTypeNames.push_back(
1406 llvm::MDString::get(VMContext, baseTypeName));
1412 argTypeQuals.push_back(llvm::MDString::get(VMContext, typeQuals));
1414 // Get image and pipe access qualifier:
1415 if (ty->isImageType() || ty->isPipeType()) {
1416 const Decl *PDecl = parm;
1417 if (auto *TD = dyn_cast<TypedefType>(ty))
1418 PDecl = TD->getDecl();
1419 const OpenCLAccessAttr *A = PDecl->getAttr<OpenCLAccessAttr>();
1420 if (A && A->isWriteOnly())
1421 accessQuals.push_back(llvm::MDString::get(VMContext, "write_only"));
1422 else if (A && A->isReadWrite())
1423 accessQuals.push_back(llvm::MDString::get(VMContext, "read_write"));
1425 accessQuals.push_back(llvm::MDString::get(VMContext, "read_only"));
1427 accessQuals.push_back(llvm::MDString::get(VMContext, "none"));
1429 // Get argument name.
1430 argNames.push_back(llvm::MDString::get(VMContext, parm->getName()));
1433 Fn->setMetadata("kernel_arg_addr_space",
1434 llvm::MDNode::get(VMContext, addressQuals));
1435 Fn->setMetadata("kernel_arg_access_qual",
1436 llvm::MDNode::get(VMContext, accessQuals));
1437 Fn->setMetadata("kernel_arg_type",
1438 llvm::MDNode::get(VMContext, argTypeNames));
1439 Fn->setMetadata("kernel_arg_base_type",
1440 llvm::MDNode::get(VMContext, argBaseTypeNames));
1441 Fn->setMetadata("kernel_arg_type_qual",
1442 llvm::MDNode::get(VMContext, argTypeQuals));
1443 if (getCodeGenOpts().EmitOpenCLArgMetadata)
1444 Fn->setMetadata("kernel_arg_name",
1445 llvm::MDNode::get(VMContext, argNames));
1448 /// Determines whether the language options require us to model
1449 /// unwind exceptions. We treat -fexceptions as mandating this
1450 /// except under the fragile ObjC ABI with only ObjC exceptions
1451 /// enabled. This means, for example, that C with -fexceptions
1453 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1454 // If exceptions are completely disabled, obviously this is false.
1455 if (!LangOpts.Exceptions) return false;
1457 // If C++ exceptions are enabled, this is true.
1458 if (LangOpts.CXXExceptions) return true;
1460 // If ObjC exceptions are enabled, this depends on the ABI.
1461 if (LangOpts.ObjCExceptions) {
1462 return LangOpts.ObjCRuntime.hasUnwindExceptions();
1468 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1469 const CXXMethodDecl *MD) {
1470 // Check that the type metadata can ever actually be used by a call.
1471 if (!CGM.getCodeGenOpts().LTOUnit ||
1472 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1475 // Only functions whose address can be taken with a member function pointer
1476 // need this sort of type metadata.
1477 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1478 !isa<CXXDestructorDecl>(MD);
1481 std::vector<const CXXRecordDecl *>
1482 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1483 llvm::SetVector<const CXXRecordDecl *> MostBases;
1485 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1486 CollectMostBases = [&](const CXXRecordDecl *RD) {
1487 if (RD->getNumBases() == 0)
1488 MostBases.insert(RD);
1489 for (const CXXBaseSpecifier &B : RD->bases())
1490 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1492 CollectMostBases(RD);
1493 return MostBases.takeVector();
1496 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1497 llvm::Function *F) {
1498 llvm::AttrBuilder B;
1500 if (CodeGenOpts.UnwindTables)
1501 B.addAttribute(llvm::Attribute::UWTable);
1503 if (!hasUnwindExceptions(LangOpts))
1504 B.addAttribute(llvm::Attribute::NoUnwind);
1506 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1507 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1508 B.addAttribute(llvm::Attribute::StackProtect);
1509 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1510 B.addAttribute(llvm::Attribute::StackProtectStrong);
1511 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1512 B.addAttribute(llvm::Attribute::StackProtectReq);
1516 // If we don't have a declaration to control inlining, the function isn't
1517 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1518 // disabled, mark the function as noinline.
1519 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1520 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1521 B.addAttribute(llvm::Attribute::NoInline);
1523 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1527 // Track whether we need to add the optnone LLVM attribute,
1528 // starting with the default for this optimization level.
1529 bool ShouldAddOptNone =
1530 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1531 // We can't add optnone in the following cases, it won't pass the verifier.
1532 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1533 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1535 // Add optnone, but do so only if the function isn't always_inline.
1536 if ((ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) &&
1537 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1538 B.addAttribute(llvm::Attribute::OptimizeNone);
1540 // OptimizeNone implies noinline; we should not be inlining such functions.
1541 B.addAttribute(llvm::Attribute::NoInline);
1543 // We still need to handle naked functions even though optnone subsumes
1544 // much of their semantics.
1545 if (D->hasAttr<NakedAttr>())
1546 B.addAttribute(llvm::Attribute::Naked);
1548 // OptimizeNone wins over OptimizeForSize and MinSize.
1549 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1550 F->removeFnAttr(llvm::Attribute::MinSize);
1551 } else if (D->hasAttr<NakedAttr>()) {
1552 // Naked implies noinline: we should not be inlining such functions.
1553 B.addAttribute(llvm::Attribute::Naked);
1554 B.addAttribute(llvm::Attribute::NoInline);
1555 } else if (D->hasAttr<NoDuplicateAttr>()) {
1556 B.addAttribute(llvm::Attribute::NoDuplicate);
1557 } else if (D->hasAttr<NoInlineAttr>() && !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1558 // Add noinline if the function isn't always_inline.
1559 B.addAttribute(llvm::Attribute::NoInline);
1560 } else if (D->hasAttr<AlwaysInlineAttr>() &&
1561 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1562 // (noinline wins over always_inline, and we can't specify both in IR)
1563 B.addAttribute(llvm::Attribute::AlwaysInline);
1564 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1565 // If we're not inlining, then force everything that isn't always_inline to
1566 // carry an explicit noinline attribute.
1567 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1568 B.addAttribute(llvm::Attribute::NoInline);
1570 // Otherwise, propagate the inline hint attribute and potentially use its
1571 // absence to mark things as noinline.
1572 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1573 // Search function and template pattern redeclarations for inline.
1574 auto CheckForInline = [](const FunctionDecl *FD) {
1575 auto CheckRedeclForInline = [](const FunctionDecl *Redecl) {
1576 return Redecl->isInlineSpecified();
1578 if (any_of(FD->redecls(), CheckRedeclForInline))
1580 const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern();
1583 return any_of(Pattern->redecls(), CheckRedeclForInline);
1585 if (CheckForInline(FD)) {
1586 B.addAttribute(llvm::Attribute::InlineHint);
1587 } else if (CodeGenOpts.getInlining() ==
1588 CodeGenOptions::OnlyHintInlining &&
1590 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1591 B.addAttribute(llvm::Attribute::NoInline);
1596 // Add other optimization related attributes if we are optimizing this
1598 if (!D->hasAttr<OptimizeNoneAttr>()) {
1599 if (D->hasAttr<ColdAttr>()) {
1600 if (!ShouldAddOptNone)
1601 B.addAttribute(llvm::Attribute::OptimizeForSize);
1602 B.addAttribute(llvm::Attribute::Cold);
1605 if (D->hasAttr<MinSizeAttr>())
1606 B.addAttribute(llvm::Attribute::MinSize);
1609 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1611 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1613 F->setAlignment(llvm::Align(alignment));
1615 if (!D->hasAttr<AlignedAttr>())
1616 if (LangOpts.FunctionAlignment)
1617 F->setAlignment(llvm::Align(1ull << LangOpts.FunctionAlignment));
1619 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1620 // reserve a bit for differentiating between virtual and non-virtual member
1621 // functions. If the current target's C++ ABI requires this and this is a
1622 // member function, set its alignment accordingly.
1623 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1624 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1625 F->setAlignment(llvm::Align(2));
1628 // In the cross-dso CFI mode with canonical jump tables, we want !type
1629 // attributes on definitions only.
1630 if (CodeGenOpts.SanitizeCfiCrossDso &&
1631 CodeGenOpts.SanitizeCfiCanonicalJumpTables) {
1632 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1633 // Skip available_externally functions. They won't be codegen'ed in the
1634 // current module anyway.
1635 if (getContext().GetGVALinkageForFunction(FD) != GVA_AvailableExternally)
1636 CreateFunctionTypeMetadataForIcall(FD, F);
1640 // Emit type metadata on member functions for member function pointer checks.
1641 // These are only ever necessary on definitions; we're guaranteed that the
1642 // definition will be present in the LTO unit as a result of LTO visibility.
1643 auto *MD = dyn_cast<CXXMethodDecl>(D);
1644 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1645 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1646 llvm::Metadata *Id =
1647 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1648 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1649 F->addTypeMetadata(0, Id);
1654 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1655 const Decl *D = GD.getDecl();
1656 if (dyn_cast_or_null<NamedDecl>(D))
1657 setGVProperties(GV, GD);
1659 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1661 if (D && D->hasAttr<UsedAttr>())
1664 if (CodeGenOpts.KeepStaticConsts && D && isa<VarDecl>(D)) {
1665 const auto *VD = cast<VarDecl>(D);
1666 if (VD->getType().isConstQualified() &&
1667 VD->getStorageDuration() == SD_Static)
1672 bool CodeGenModule::GetCPUAndFeaturesAttributes(GlobalDecl GD,
1673 llvm::AttrBuilder &Attrs) {
1674 // Add target-cpu and target-features attributes to functions. If
1675 // we have a decl for the function and it has a target attribute then
1676 // parse that and add it to the feature set.
1677 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1678 std::vector<std::string> Features;
1679 const auto *FD = dyn_cast_or_null<FunctionDecl>(GD.getDecl());
1680 FD = FD ? FD->getMostRecentDecl() : FD;
1681 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1682 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
1683 bool AddedAttr = false;
1685 llvm::StringMap<bool> FeatureMap;
1686 getContext().getFunctionFeatureMap(FeatureMap, GD);
1688 // Produce the canonical string for this set of features.
1689 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1690 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1692 // Now add the target-cpu and target-features to the function.
1693 // While we populated the feature map above, we still need to
1694 // get and parse the target attribute so we can get the cpu for
1697 ParsedTargetAttr ParsedAttr = TD->parse();
1698 if (ParsedAttr.Architecture != "" &&
1699 getTarget().isValidCPUName(ParsedAttr.Architecture))
1700 TargetCPU = ParsedAttr.Architecture;
1703 // Otherwise just add the existing target cpu and target features to the
1705 Features = getTarget().getTargetOpts().Features;
1708 if (TargetCPU != "") {
1709 Attrs.addAttribute("target-cpu", TargetCPU);
1712 if (!Features.empty()) {
1713 llvm::sort(Features);
1714 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1721 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
1722 llvm::GlobalObject *GO) {
1723 const Decl *D = GD.getDecl();
1724 SetCommonAttributes(GD, GO);
1727 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1728 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1729 GV->addAttribute("bss-section", SA->getName());
1730 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1731 GV->addAttribute("data-section", SA->getName());
1732 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1733 GV->addAttribute("rodata-section", SA->getName());
1734 if (auto *SA = D->getAttr<PragmaClangRelroSectionAttr>())
1735 GV->addAttribute("relro-section", SA->getName());
1738 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1739 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1740 if (!D->getAttr<SectionAttr>())
1741 F->addFnAttr("implicit-section-name", SA->getName());
1743 llvm::AttrBuilder Attrs;
1744 if (GetCPUAndFeaturesAttributes(GD, Attrs)) {
1745 // We know that GetCPUAndFeaturesAttributes will always have the
1746 // newest set, since it has the newest possible FunctionDecl, so the
1747 // new ones should replace the old.
1748 F->removeFnAttr("target-cpu");
1749 F->removeFnAttr("target-features");
1750 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1754 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1755 GO->setSection(CSA->getName());
1756 else if (const auto *SA = D->getAttr<SectionAttr>())
1757 GO->setSection(SA->getName());
1760 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1763 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
1765 const CGFunctionInfo &FI) {
1766 const Decl *D = GD.getDecl();
1767 SetLLVMFunctionAttributes(GD, FI, F);
1768 SetLLVMFunctionAttributesForDefinition(D, F);
1770 F->setLinkage(llvm::Function::InternalLinkage);
1772 setNonAliasAttributes(GD, F);
1775 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
1776 // Set linkage and visibility in case we never see a definition.
1777 LinkageInfo LV = ND->getLinkageAndVisibility();
1778 // Don't set internal linkage on declarations.
1779 // "extern_weak" is overloaded in LLVM; we probably should have
1780 // separate linkage types for this.
1781 if (isExternallyVisible(LV.getLinkage()) &&
1782 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1783 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1786 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1787 llvm::Function *F) {
1788 // Only if we are checking indirect calls.
1789 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1792 // Non-static class methods are handled via vtable or member function pointer
1793 // checks elsewhere.
1794 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1797 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1798 F->addTypeMetadata(0, MD);
1799 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
1801 // Emit a hash-based bit set entry for cross-DSO calls.
1802 if (CodeGenOpts.SanitizeCfiCrossDso)
1803 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1804 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1807 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1808 bool IsIncompleteFunction,
1811 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1812 // If this is an intrinsic function, set the function's attributes
1813 // to the intrinsic's attributes.
1814 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1818 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1820 if (!IsIncompleteFunction)
1821 SetLLVMFunctionAttributes(GD, getTypes().arrangeGlobalDeclaration(GD), F);
1823 // Add the Returned attribute for "this", except for iOS 5 and earlier
1824 // where substantial code, including the libstdc++ dylib, was compiled with
1825 // GCC and does not actually return "this".
1826 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1827 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1828 assert(!F->arg_empty() &&
1829 F->arg_begin()->getType()
1830 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1831 "unexpected this return");
1832 F->addAttribute(1, llvm::Attribute::Returned);
1835 // Only a few attributes are set on declarations; these may later be
1836 // overridden by a definition.
1838 setLinkageForGV(F, FD);
1839 setGVProperties(F, FD);
1841 // Setup target-specific attributes.
1842 if (!IsIncompleteFunction && F->isDeclaration())
1843 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
1845 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1846 F->setSection(CSA->getName());
1847 else if (const auto *SA = FD->getAttr<SectionAttr>())
1848 F->setSection(SA->getName());
1850 if (FD->isInlineBuiltinDeclaration()) {
1851 F->addAttribute(llvm::AttributeList::FunctionIndex,
1852 llvm::Attribute::NoBuiltin);
1855 if (FD->isReplaceableGlobalAllocationFunction()) {
1856 // A replaceable global allocation function does not act like a builtin by
1857 // default, only if it is invoked by a new-expression or delete-expression.
1858 F->addAttribute(llvm::AttributeList::FunctionIndex,
1859 llvm::Attribute::NoBuiltin);
1861 // A sane operator new returns a non-aliasing pointer.
1862 // FIXME: Also add NonNull attribute to the return value
1863 // for the non-nothrow forms?
1864 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1865 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1866 (Kind == OO_New || Kind == OO_Array_New))
1867 F->addAttribute(llvm::AttributeList::ReturnIndex,
1868 llvm::Attribute::NoAlias);
1871 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1872 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1873 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1874 if (MD->isVirtual())
1875 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1877 // Don't emit entries for function declarations in the cross-DSO mode. This
1878 // is handled with better precision by the receiving DSO. But if jump tables
1879 // are non-canonical then we need type metadata in order to produce the local
1881 if (!CodeGenOpts.SanitizeCfiCrossDso ||
1882 !CodeGenOpts.SanitizeCfiCanonicalJumpTables)
1883 CreateFunctionTypeMetadataForIcall(FD, F);
1885 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1886 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1888 if (const auto *CB = FD->getAttr<CallbackAttr>()) {
1889 // Annotate the callback behavior as metadata:
1890 // - The callback callee (as argument number).
1891 // - The callback payloads (as argument numbers).
1892 llvm::LLVMContext &Ctx = F->getContext();
1893 llvm::MDBuilder MDB(Ctx);
1895 // The payload indices are all but the first one in the encoding. The first
1896 // identifies the callback callee.
1897 int CalleeIdx = *CB->encoding_begin();
1898 ArrayRef<int> PayloadIndices(CB->encoding_begin() + 1, CB->encoding_end());
1899 F->addMetadata(llvm::LLVMContext::MD_callback,
1900 *llvm::MDNode::get(Ctx, {MDB.createCallbackEncoding(
1901 CalleeIdx, PayloadIndices,
1902 /* VarArgsArePassed */ false)}));
1906 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1907 assert(!GV->isDeclaration() &&
1908 "Only globals with definition can force usage.");
1909 LLVMUsed.emplace_back(GV);
1912 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1913 assert(!GV->isDeclaration() &&
1914 "Only globals with definition can force usage.");
1915 LLVMCompilerUsed.emplace_back(GV);
1918 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1919 std::vector<llvm::WeakTrackingVH> &List) {
1920 // Don't create llvm.used if there is no need.
1924 // Convert List to what ConstantArray needs.
1925 SmallVector<llvm::Constant*, 8> UsedArray;
1926 UsedArray.resize(List.size());
1927 for (unsigned i = 0, e = List.size(); i != e; ++i) {
1929 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1930 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1933 if (UsedArray.empty())
1935 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1937 auto *GV = new llvm::GlobalVariable(
1938 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1939 llvm::ConstantArray::get(ATy, UsedArray), Name);
1941 GV->setSection("llvm.metadata");
1944 void CodeGenModule::emitLLVMUsed() {
1945 emitUsed(*this, "llvm.used", LLVMUsed);
1946 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1949 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1950 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1951 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1954 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1955 llvm::SmallString<32> Opt;
1956 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1959 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1960 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1963 void CodeGenModule::AddDependentLib(StringRef Lib) {
1964 auto &C = getLLVMContext();
1965 if (getTarget().getTriple().isOSBinFormatELF()) {
1966 ELFDependentLibraries.push_back(
1967 llvm::MDNode::get(C, llvm::MDString::get(C, Lib)));
1971 llvm::SmallString<24> Opt;
1972 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1973 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1974 LinkerOptionsMetadata.push_back(llvm::MDNode::get(C, MDOpts));
1977 /// Add link options implied by the given module, including modules
1978 /// it depends on, using a postorder walk.
1979 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1980 SmallVectorImpl<llvm::MDNode *> &Metadata,
1981 llvm::SmallPtrSet<Module *, 16> &Visited) {
1982 // Import this module's parent.
1983 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1984 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1987 // Import this module's dependencies.
1988 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1989 if (Visited.insert(Mod->Imports[I - 1]).second)
1990 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1993 // Add linker options to link against the libraries/frameworks
1994 // described by this module.
1995 llvm::LLVMContext &Context = CGM.getLLVMContext();
1996 bool IsELF = CGM.getTarget().getTriple().isOSBinFormatELF();
1998 // For modules that use export_as for linking, use that module
2000 if (Mod->UseExportAsModuleLinkName)
2003 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
2004 // Link against a framework. Frameworks are currently Darwin only, so we
2005 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
2006 if (Mod->LinkLibraries[I-1].IsFramework) {
2007 llvm::Metadata *Args[2] = {
2008 llvm::MDString::get(Context, "-framework"),
2009 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
2011 Metadata.push_back(llvm::MDNode::get(Context, Args));
2015 // Link against a library.
2017 llvm::Metadata *Args[2] = {
2018 llvm::MDString::get(Context, "lib"),
2019 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library),
2021 Metadata.push_back(llvm::MDNode::get(Context, Args));
2023 llvm::SmallString<24> Opt;
2024 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
2025 Mod->LinkLibraries[I - 1].Library, Opt);
2026 auto *OptString = llvm::MDString::get(Context, Opt);
2027 Metadata.push_back(llvm::MDNode::get(Context, OptString));
2032 void CodeGenModule::EmitModuleLinkOptions() {
2033 // Collect the set of all of the modules we want to visit to emit link
2034 // options, which is essentially the imported modules and all of their
2035 // non-explicit child modules.
2036 llvm::SetVector<clang::Module *> LinkModules;
2037 llvm::SmallPtrSet<clang::Module *, 16> Visited;
2038 SmallVector<clang::Module *, 16> Stack;
2040 // Seed the stack with imported modules.
2041 for (Module *M : ImportedModules) {
2042 // Do not add any link flags when an implementation TU of a module imports
2043 // a header of that same module.
2044 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
2045 !getLangOpts().isCompilingModule())
2047 if (Visited.insert(M).second)
2051 // Find all of the modules to import, making a little effort to prune
2052 // non-leaf modules.
2053 while (!Stack.empty()) {
2054 clang::Module *Mod = Stack.pop_back_val();
2056 bool AnyChildren = false;
2058 // Visit the submodules of this module.
2059 for (const auto &SM : Mod->submodules()) {
2060 // Skip explicit children; they need to be explicitly imported to be
2065 if (Visited.insert(SM).second) {
2066 Stack.push_back(SM);
2071 // We didn't find any children, so add this module to the list of
2072 // modules to link against.
2074 LinkModules.insert(Mod);
2078 // Add link options for all of the imported modules in reverse topological
2079 // order. We don't do anything to try to order import link flags with respect
2080 // to linker options inserted by things like #pragma comment().
2081 SmallVector<llvm::MDNode *, 16> MetadataArgs;
2083 for (Module *M : LinkModules)
2084 if (Visited.insert(M).second)
2085 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
2086 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
2087 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
2089 // Add the linker options metadata flag.
2090 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
2091 for (auto *MD : LinkerOptionsMetadata)
2092 NMD->addOperand(MD);
2095 void CodeGenModule::EmitDeferred() {
2096 // Emit deferred declare target declarations.
2097 if (getLangOpts().OpenMP && !getLangOpts().OpenMPSimd)
2098 getOpenMPRuntime().emitDeferredTargetDecls();
2100 // Emit code for any potentially referenced deferred decls. Since a
2101 // previously unused static decl may become used during the generation of code
2102 // for a static function, iterate until no changes are made.
2104 if (!DeferredVTables.empty()) {
2105 EmitDeferredVTables();
2107 // Emitting a vtable doesn't directly cause more vtables to
2108 // become deferred, although it can cause functions to be
2109 // emitted that then need those vtables.
2110 assert(DeferredVTables.empty());
2113 // Stop if we're out of both deferred vtables and deferred declarations.
2114 if (DeferredDeclsToEmit.empty())
2117 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
2118 // work, it will not interfere with this.
2119 std::vector<GlobalDecl> CurDeclsToEmit;
2120 CurDeclsToEmit.swap(DeferredDeclsToEmit);
2122 for (GlobalDecl &D : CurDeclsToEmit) {
2123 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
2124 // to get GlobalValue with exactly the type we need, not something that
2125 // might had been created for another decl with the same mangled name but
2127 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
2128 GetAddrOfGlobal(D, ForDefinition));
2130 // In case of different address spaces, we may still get a cast, even with
2131 // IsForDefinition equal to true. Query mangled names table to get
2134 GV = GetGlobalValue(getMangledName(D));
2136 // Make sure GetGlobalValue returned non-null.
2139 // Check to see if we've already emitted this. This is necessary
2140 // for a couple of reasons: first, decls can end up in the
2141 // deferred-decls queue multiple times, and second, decls can end
2142 // up with definitions in unusual ways (e.g. by an extern inline
2143 // function acquiring a strong function redefinition). Just
2144 // ignore these cases.
2145 if (!GV->isDeclaration())
2148 // If this is OpenMP, check if it is legal to emit this global normally.
2149 if (LangOpts.OpenMP && OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(D))
2152 // Otherwise, emit the definition and move on to the next one.
2153 EmitGlobalDefinition(D, GV);
2155 // If we found out that we need to emit more decls, do that recursively.
2156 // This has the advantage that the decls are emitted in a DFS and related
2157 // ones are close together, which is convenient for testing.
2158 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
2160 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
2165 void CodeGenModule::EmitVTablesOpportunistically() {
2166 // Try to emit external vtables as available_externally if they have emitted
2167 // all inlined virtual functions. It runs after EmitDeferred() and therefore
2168 // is not allowed to create new references to things that need to be emitted
2169 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
2171 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
2172 && "Only emit opportunistic vtables with optimizations");
2174 for (const CXXRecordDecl *RD : OpportunisticVTables) {
2175 assert(getVTables().isVTableExternal(RD) &&
2176 "This queue should only contain external vtables");
2177 if (getCXXABI().canSpeculativelyEmitVTable(RD))
2178 VTables.GenerateClassData(RD);
2180 OpportunisticVTables.clear();
2183 void CodeGenModule::EmitGlobalAnnotations() {
2184 if (Annotations.empty())
2187 // Create a new global variable for the ConstantStruct in the Module.
2188 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
2189 Annotations[0]->getType(), Annotations.size()), Annotations);
2190 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
2191 llvm::GlobalValue::AppendingLinkage,
2192 Array, "llvm.global.annotations");
2193 gv->setSection(AnnotationSection);
2196 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
2197 llvm::Constant *&AStr = AnnotationStrings[Str];
2201 // Not found yet, create a new global.
2202 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
2204 new llvm::GlobalVariable(getModule(), s->getType(), true,
2205 llvm::GlobalValue::PrivateLinkage, s, ".str");
2206 gv->setSection(AnnotationSection);
2207 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
2212 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
2213 SourceManager &SM = getContext().getSourceManager();
2214 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
2216 return EmitAnnotationString(PLoc.getFilename());
2217 return EmitAnnotationString(SM.getBufferName(Loc));
2220 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
2221 SourceManager &SM = getContext().getSourceManager();
2222 PresumedLoc PLoc = SM.getPresumedLoc(L);
2223 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
2224 SM.getExpansionLineNumber(L);
2225 return llvm::ConstantInt::get(Int32Ty, LineNo);
2228 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
2229 const AnnotateAttr *AA,
2231 // Get the globals for file name, annotation, and the line number.
2232 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
2233 *UnitGV = EmitAnnotationUnit(L),
2234 *LineNoCst = EmitAnnotationLineNo(L);
2236 llvm::Constant *ASZeroGV = GV;
2237 if (GV->getAddressSpace() != 0) {
2238 ASZeroGV = llvm::ConstantExpr::getAddrSpaceCast(
2239 GV, GV->getValueType()->getPointerTo(0));
2242 // Create the ConstantStruct for the global annotation.
2243 llvm::Constant *Fields[4] = {
2244 llvm::ConstantExpr::getBitCast(ASZeroGV, Int8PtrTy),
2245 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
2246 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
2249 return llvm::ConstantStruct::getAnon(Fields);
2252 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
2253 llvm::GlobalValue *GV) {
2254 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
2255 // Get the struct elements for these annotations.
2256 for (const auto *I : D->specific_attrs<AnnotateAttr>())
2257 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
2260 bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
2262 SourceLocation Loc) const {
2263 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
2264 // Blacklist by function name.
2265 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
2267 // Blacklist by location.
2269 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
2270 // If location is unknown, this may be a compiler-generated function. Assume
2271 // it's located in the main file.
2272 auto &SM = Context.getSourceManager();
2273 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
2274 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
2279 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
2280 SourceLocation Loc, QualType Ty,
2281 StringRef Category) const {
2282 // For now globals can be blacklisted only in ASan and KASan.
2283 const SanitizerMask EnabledAsanMask =
2284 LangOpts.Sanitize.Mask &
2285 (SanitizerKind::Address | SanitizerKind::KernelAddress |
2286 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress |
2287 SanitizerKind::MemTag);
2288 if (!EnabledAsanMask)
2290 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
2291 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
2293 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
2295 // Check global type.
2297 // Drill down the array types: if global variable of a fixed type is
2298 // blacklisted, we also don't instrument arrays of them.
2299 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
2300 Ty = AT->getElementType();
2301 Ty = Ty.getCanonicalType().getUnqualifiedType();
2302 // We allow to blacklist only record types (classes, structs etc.)
2303 if (Ty->isRecordType()) {
2304 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
2305 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
2312 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
2313 StringRef Category) const {
2314 const auto &XRayFilter = getContext().getXRayFilter();
2315 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
2316 auto Attr = ImbueAttr::NONE;
2318 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
2319 if (Attr == ImbueAttr::NONE)
2320 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
2322 case ImbueAttr::NONE:
2324 case ImbueAttr::ALWAYS:
2325 Fn->addFnAttr("function-instrument", "xray-always");
2327 case ImbueAttr::ALWAYS_ARG1:
2328 Fn->addFnAttr("function-instrument", "xray-always");
2329 Fn->addFnAttr("xray-log-args", "1");
2331 case ImbueAttr::NEVER:
2332 Fn->addFnAttr("function-instrument", "xray-never");
2338 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
2339 // Never defer when EmitAllDecls is specified.
2340 if (LangOpts.EmitAllDecls)
2343 if (CodeGenOpts.KeepStaticConsts) {
2344 const auto *VD = dyn_cast<VarDecl>(Global);
2345 if (VD && VD->getType().isConstQualified() &&
2346 VD->getStorageDuration() == SD_Static)
2350 return getContext().DeclMustBeEmitted(Global);
2353 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
2354 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2355 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
2356 // Implicit template instantiations may change linkage if they are later
2357 // explicitly instantiated, so they should not be emitted eagerly.
2359 // In OpenMP 5.0 function may be marked as device_type(nohost) and we should
2360 // not emit them eagerly unless we sure that the function must be emitted on
2362 if (LangOpts.OpenMP >= 50 && !LangOpts.OpenMPSimd &&
2363 !LangOpts.OpenMPIsDevice &&
2364 !OMPDeclareTargetDeclAttr::getDeviceType(FD) &&
2365 !FD->isUsed(/*CheckUsedAttr=*/false) && !FD->isReferenced())
2368 if (const auto *VD = dyn_cast<VarDecl>(Global))
2369 if (Context.getInlineVariableDefinitionKind(VD) ==
2370 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
2371 // A definition of an inline constexpr static data member may change
2372 // linkage later if it's redeclared outside the class.
2374 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2375 // codegen for global variables, because they may be marked as threadprivate.
2376 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2377 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2378 !isTypeConstant(Global->getType(), false) &&
2379 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Global))
2385 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
2386 const CXXUuidofExpr* E) {
2387 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
2389 StringRef Uuid = E->getUuidStr();
2390 std::string Name = "_GUID_" + Uuid.lower();
2391 std::replace(Name.begin(), Name.end(), '-', '_');
2393 // The UUID descriptor should be pointer aligned.
2394 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2396 // Look for an existing global.
2397 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2398 return ConstantAddress(GV, Alignment);
2400 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
2401 assert(Init && "failed to initialize as constant");
2403 auto *GV = new llvm::GlobalVariable(
2404 getModule(), Init->getType(),
2405 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2406 if (supportsCOMDAT())
2407 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2409 return ConstantAddress(GV, Alignment);
2412 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2413 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2414 assert(AA && "No alias?");
2416 CharUnits Alignment = getContext().getDeclAlign(VD);
2417 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2419 // See if there is already something with the target's name in the module.
2420 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2422 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2423 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2424 return ConstantAddress(Ptr, Alignment);
2427 llvm::Constant *Aliasee;
2428 if (isa<llvm::FunctionType>(DeclTy))
2429 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2430 GlobalDecl(cast<FunctionDecl>(VD)),
2431 /*ForVTable=*/false);
2433 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2434 llvm::PointerType::getUnqual(DeclTy),
2437 auto *F = cast<llvm::GlobalValue>(Aliasee);
2438 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2439 WeakRefReferences.insert(F);
2441 return ConstantAddress(Aliasee, Alignment);
2444 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2445 const auto *Global = cast<ValueDecl>(GD.getDecl());
2447 // Weak references don't produce any output by themselves.
2448 if (Global->hasAttr<WeakRefAttr>())
2451 // If this is an alias definition (which otherwise looks like a declaration)
2453 if (Global->hasAttr<AliasAttr>())
2454 return EmitAliasDefinition(GD);
2456 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2457 if (Global->hasAttr<IFuncAttr>())
2458 return emitIFuncDefinition(GD);
2460 // If this is a cpu_dispatch multiversion function, emit the resolver.
2461 if (Global->hasAttr<CPUDispatchAttr>())
2462 return emitCPUDispatchDefinition(GD);
2464 // If this is CUDA, be selective about which declarations we emit.
2465 if (LangOpts.CUDA) {
2466 if (LangOpts.CUDAIsDevice) {
2467 if (!Global->hasAttr<CUDADeviceAttr>() &&
2468 !Global->hasAttr<CUDAGlobalAttr>() &&
2469 !Global->hasAttr<CUDAConstantAttr>() &&
2470 !Global->hasAttr<CUDASharedAttr>() &&
2471 !(LangOpts.HIP && Global->hasAttr<HIPPinnedShadowAttr>()))
2474 // We need to emit host-side 'shadows' for all global
2475 // device-side variables because the CUDA runtime needs their
2476 // size and host-side address in order to provide access to
2477 // their device-side incarnations.
2479 // So device-only functions are the only things we skip.
2480 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2481 Global->hasAttr<CUDADeviceAttr>())
2484 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2485 "Expected Variable or Function");
2489 if (LangOpts.OpenMP) {
2490 // If this is OpenMP, check if it is legal to emit this global normally.
2491 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2493 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2494 if (MustBeEmitted(Global))
2495 EmitOMPDeclareReduction(DRD);
2497 } else if (auto *DMD = dyn_cast<OMPDeclareMapperDecl>(Global)) {
2498 if (MustBeEmitted(Global))
2499 EmitOMPDeclareMapper(DMD);
2504 // Ignore declarations, they will be emitted on their first use.
2505 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2506 // Forward declarations are emitted lazily on first use.
2507 if (!FD->doesThisDeclarationHaveABody()) {
2508 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2511 StringRef MangledName = getMangledName(GD);
2513 // Compute the function info and LLVM type.
2514 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2515 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2517 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2518 /*DontDefer=*/false);
2522 const auto *VD = cast<VarDecl>(Global);
2523 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2524 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2525 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2526 if (LangOpts.OpenMP) {
2527 // Emit declaration of the must-be-emitted declare target variable.
2528 if (llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
2529 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
2530 bool UnifiedMemoryEnabled =
2531 getOpenMPRuntime().hasRequiresUnifiedSharedMemory();
2532 if (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2533 !UnifiedMemoryEnabled) {
2534 (void)GetAddrOfGlobalVar(VD);
2536 assert(((*Res == OMPDeclareTargetDeclAttr::MT_Link) ||
2537 (*Res == OMPDeclareTargetDeclAttr::MT_To &&
2538 UnifiedMemoryEnabled)) &&
2539 "Link clause or to clause with unified memory expected.");
2540 (void)getOpenMPRuntime().getAddrOfDeclareTargetVar(VD);
2546 // If this declaration may have caused an inline variable definition to
2547 // change linkage, make sure that it's emitted.
2548 if (Context.getInlineVariableDefinitionKind(VD) ==
2549 ASTContext::InlineVariableDefinitionKind::Strong)
2550 GetAddrOfGlobalVar(VD);
2555 // Defer code generation to first use when possible, e.g. if this is an inline
2556 // function. If the global must always be emitted, do it eagerly if possible
2557 // to benefit from cache locality.
2558 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2559 // Emit the definition if it can't be deferred.
2560 EmitGlobalDefinition(GD);
2564 // Check if this must be emitted as declare variant.
2565 if (LangOpts.OpenMP && isa<FunctionDecl>(Global) && OpenMPRuntime &&
2566 OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/false))
2569 // If we're deferring emission of a C++ variable with an
2570 // initializer, remember the order in which it appeared in the file.
2571 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2572 cast<VarDecl>(Global)->hasInit()) {
2573 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2574 CXXGlobalInits.push_back(nullptr);
2577 StringRef MangledName = getMangledName(GD);
2578 if (GetGlobalValue(MangledName) != nullptr) {
2579 // The value has already been used and should therefore be emitted.
2580 addDeferredDeclToEmit(GD);
2581 } else if (MustBeEmitted(Global)) {
2582 // The value must be emitted, but cannot be emitted eagerly.
2583 assert(!MayBeEmittedEagerly(Global));
2584 addDeferredDeclToEmit(GD);
2586 // Otherwise, remember that we saw a deferred decl with this name. The
2587 // first use of the mangled name will cause it to move into
2588 // DeferredDeclsToEmit.
2589 DeferredDecls[MangledName] = GD;
2593 // Check if T is a class type with a destructor that's not dllimport.
2594 static bool HasNonDllImportDtor(QualType T) {
2595 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2596 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2597 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2604 struct FunctionIsDirectlyRecursive
2605 : public ConstStmtVisitor<FunctionIsDirectlyRecursive, bool> {
2606 const StringRef Name;
2607 const Builtin::Context &BI;
2608 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C)
2611 bool VisitCallExpr(const CallExpr *E) {
2612 const FunctionDecl *FD = E->getDirectCallee();
2615 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2616 if (Attr && Name == Attr->getLabel())
2618 unsigned BuiltinID = FD->getBuiltinID();
2619 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2621 StringRef BuiltinName = BI.getName(BuiltinID);
2622 if (BuiltinName.startswith("__builtin_") &&
2623 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2629 bool VisitStmt(const Stmt *S) {
2630 for (const Stmt *Child : S->children())
2631 if (Child && this->Visit(Child))
2637 // Make sure we're not referencing non-imported vars or functions.
2638 struct DLLImportFunctionVisitor
2639 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2640 bool SafeToInline = true;
2642 bool shouldVisitImplicitCode() const { return true; }
2644 bool VisitVarDecl(VarDecl *VD) {
2645 if (VD->getTLSKind()) {
2646 // A thread-local variable cannot be imported.
2647 SafeToInline = false;
2648 return SafeToInline;
2651 // A variable definition might imply a destructor call.
2652 if (VD->isThisDeclarationADefinition())
2653 SafeToInline = !HasNonDllImportDtor(VD->getType());
2655 return SafeToInline;
2658 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2659 if (const auto *D = E->getTemporary()->getDestructor())
2660 SafeToInline = D->hasAttr<DLLImportAttr>();
2661 return SafeToInline;
2664 bool VisitDeclRefExpr(DeclRefExpr *E) {
2665 ValueDecl *VD = E->getDecl();
2666 if (isa<FunctionDecl>(VD))
2667 SafeToInline = VD->hasAttr<DLLImportAttr>();
2668 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2669 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2670 return SafeToInline;
2673 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2674 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2675 return SafeToInline;
2678 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2679 CXXMethodDecl *M = E->getMethodDecl();
2681 // Call through a pointer to member function. This is safe to inline.
2682 SafeToInline = true;
2684 SafeToInline = M->hasAttr<DLLImportAttr>();
2686 return SafeToInline;
2689 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2690 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2691 return SafeToInline;
2694 bool VisitCXXNewExpr(CXXNewExpr *E) {
2695 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2696 return SafeToInline;
2701 // isTriviallyRecursive - Check if this function calls another
2702 // decl that, because of the asm attribute or the other decl being a builtin,
2703 // ends up pointing to itself.
2705 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2707 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2708 // asm labels are a special kind of mangling we have to support.
2709 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2712 Name = Attr->getLabel();
2714 Name = FD->getName();
2717 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2718 const Stmt *Body = FD->getBody();
2719 return Body ? Walker.Visit(Body) : false;
2722 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2723 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2725 const auto *F = cast<FunctionDecl>(GD.getDecl());
2726 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2729 if (F->hasAttr<DLLImportAttr>()) {
2730 // Check whether it would be safe to inline this dllimport function.
2731 DLLImportFunctionVisitor Visitor;
2732 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2733 if (!Visitor.SafeToInline)
2736 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2737 // Implicit destructor invocations aren't captured in the AST, so the
2738 // check above can't see them. Check for them manually here.
2739 for (const Decl *Member : Dtor->getParent()->decls())
2740 if (isa<FieldDecl>(Member))
2741 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2743 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2744 if (HasNonDllImportDtor(B.getType()))
2749 // PR9614. Avoid cases where the source code is lying to us. An available
2750 // externally function should have an equivalent function somewhere else,
2751 // but a function that calls itself is clearly not equivalent to the real
2753 // This happens in glibc's btowc and in some configure checks.
2754 return !isTriviallyRecursive(F);
2757 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2758 return CodeGenOpts.OptimizationLevel > 0;
2761 void CodeGenModule::EmitMultiVersionFunctionDefinition(GlobalDecl GD,
2762 llvm::GlobalValue *GV) {
2763 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2765 if (FD->isCPUSpecificMultiVersion()) {
2766 auto *Spec = FD->getAttr<CPUSpecificAttr>();
2767 for (unsigned I = 0; I < Spec->cpus_size(); ++I)
2768 EmitGlobalFunctionDefinition(GD.getWithMultiVersionIndex(I), nullptr);
2769 // Requires multiple emits.
2771 EmitGlobalFunctionDefinition(GD, GV);
2774 void CodeGenModule::emitOpenMPDeviceFunctionRedefinition(
2775 GlobalDecl OldGD, GlobalDecl NewGD, llvm::GlobalValue *GV) {
2776 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
2777 OpenMPRuntime && "Expected OpenMP device mode.");
2778 const auto *D = cast<FunctionDecl>(OldGD.getDecl());
2780 // Compute the function info and LLVM type.
2781 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(OldGD);
2782 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2784 // Get or create the prototype for the function.
2785 if (!GV || (GV->getType()->getElementType() != Ty)) {
2786 GV = cast<llvm::GlobalValue>(GetOrCreateLLVMFunction(
2787 getMangledName(OldGD), Ty, GlobalDecl(), /*ForVTable=*/false,
2788 /*DontDefer=*/true, /*IsThunk=*/false, llvm::AttributeList(),
2790 SetFunctionAttributes(OldGD, cast<llvm::Function>(GV),
2791 /*IsIncompleteFunction=*/false,
2794 // We need to set linkage and visibility on the function before
2795 // generating code for it because various parts of IR generation
2796 // want to propagate this information down (e.g. to local static
2798 auto *Fn = cast<llvm::Function>(GV);
2799 setFunctionLinkage(OldGD, Fn);
2801 // FIXME: this is redundant with part of
2802 // setFunctionDefinitionAttributes
2803 setGVProperties(Fn, OldGD);
2805 MaybeHandleStaticInExternC(D, Fn);
2807 maybeSetTrivialComdat(*D, *Fn);
2809 CodeGenFunction(*this).GenerateCode(NewGD, Fn, FI);
2811 setNonAliasAttributes(OldGD, Fn);
2812 SetLLVMFunctionAttributesForDefinition(D, Fn);
2814 if (D->hasAttr<AnnotateAttr>())
2815 AddGlobalAnnotations(D, Fn);
2818 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
2819 const auto *D = cast<ValueDecl>(GD.getDecl());
2821 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2822 Context.getSourceManager(),
2823 "Generating code for declaration");
2825 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
2826 // At -O0, don't generate IR for functions with available_externally
2828 if (!shouldEmitFunction(GD))
2831 llvm::TimeTraceScope TimeScope("CodeGen Function", [&]() {
2833 llvm::raw_string_ostream OS(Name);
2834 FD->getNameForDiagnostic(OS, getContext().getPrintingPolicy(),
2835 /*Qualified=*/true);
2839 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2840 // Make sure to emit the definition(s) before we emit the thunks.
2841 // This is necessary for the generation of certain thunks.
2842 if (isa<CXXConstructorDecl>(Method) || isa<CXXDestructorDecl>(Method))
2843 ABI->emitCXXStructor(GD);
2844 else if (FD->isMultiVersion())
2845 EmitMultiVersionFunctionDefinition(GD, GV);
2847 EmitGlobalFunctionDefinition(GD, GV);
2849 if (Method->isVirtual())
2850 getVTables().EmitThunks(GD);
2855 if (FD->isMultiVersion())
2856 return EmitMultiVersionFunctionDefinition(GD, GV);
2857 return EmitGlobalFunctionDefinition(GD, GV);
2860 if (const auto *VD = dyn_cast<VarDecl>(D))
2861 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2863 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2866 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2867 llvm::Function *NewFn);
2870 TargetMVPriority(const TargetInfo &TI,
2871 const CodeGenFunction::MultiVersionResolverOption &RO) {
2872 unsigned Priority = 0;
2873 for (StringRef Feat : RO.Conditions.Features)
2874 Priority = std::max(Priority, TI.multiVersionSortPriority(Feat));
2876 if (!RO.Conditions.Architecture.empty())
2877 Priority = std::max(
2878 Priority, TI.multiVersionSortPriority(RO.Conditions.Architecture));
2882 void CodeGenModule::emitMultiVersionFunctions() {
2883 for (GlobalDecl GD : MultiVersionFuncs) {
2884 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2885 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2886 getContext().forEachMultiversionedFunctionVersion(
2887 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2889 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2890 StringRef MangledName = getMangledName(CurGD);
2891 llvm::Constant *Func = GetGlobalValue(MangledName);
2893 if (CurFD->isDefined()) {
2894 EmitGlobalFunctionDefinition(CurGD, nullptr);
2895 Func = GetGlobalValue(MangledName);
2897 const CGFunctionInfo &FI =
2898 getTypes().arrangeGlobalDeclaration(GD);
2899 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2900 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2901 /*DontDefer=*/false, ForDefinition);
2903 assert(Func && "This should have just been created");
2906 const auto *TA = CurFD->getAttr<TargetAttr>();
2907 llvm::SmallVector<StringRef, 8> Feats;
2908 TA->getAddedFeatures(Feats);
2910 Options.emplace_back(cast<llvm::Function>(Func),
2911 TA->getArchitecture(), Feats);
2914 llvm::Function *ResolverFunc;
2915 const TargetInfo &TI = getTarget();
2917 if (TI.supportsIFunc() || FD->isTargetMultiVersion()) {
2918 ResolverFunc = cast<llvm::Function>(
2919 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2920 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
2922 ResolverFunc = cast<llvm::Function>(GetGlobalValue(getMangledName(GD)));
2925 if (supportsCOMDAT())
2926 ResolverFunc->setComdat(
2927 getModule().getOrInsertComdat(ResolverFunc->getName()));
2930 Options, [&TI](const CodeGenFunction::MultiVersionResolverOption &LHS,
2931 const CodeGenFunction::MultiVersionResolverOption &RHS) {
2932 return TargetMVPriority(TI, LHS) > TargetMVPriority(TI, RHS);
2934 CodeGenFunction CGF(*this);
2935 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
2939 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2940 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2941 assert(FD && "Not a FunctionDecl?");
2942 const auto *DD = FD->getAttr<CPUDispatchAttr>();
2943 assert(DD && "Not a cpu_dispatch Function?");
2944 llvm::Type *DeclTy = getTypes().ConvertType(FD->getType());
2946 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
2947 const CGFunctionInfo &FInfo = getTypes().arrangeCXXMethodDeclaration(CXXFD);
2948 DeclTy = getTypes().GetFunctionType(FInfo);
2951 StringRef ResolverName = getMangledName(GD);
2953 llvm::Type *ResolverType;
2954 GlobalDecl ResolverGD;
2955 if (getTarget().supportsIFunc())
2956 ResolverType = llvm::FunctionType::get(
2957 llvm::PointerType::get(DeclTy,
2958 Context.getTargetAddressSpace(FD->getType())),
2961 ResolverType = DeclTy;
2965 auto *ResolverFunc = cast<llvm::Function>(GetOrCreateLLVMFunction(
2966 ResolverName, ResolverType, ResolverGD, /*ForVTable=*/false));
2967 ResolverFunc->setLinkage(llvm::Function::WeakODRLinkage);
2968 if (supportsCOMDAT())
2969 ResolverFunc->setComdat(
2970 getModule().getOrInsertComdat(ResolverFunc->getName()));
2972 SmallVector<CodeGenFunction::MultiVersionResolverOption, 10> Options;
2973 const TargetInfo &Target = getTarget();
2975 for (const IdentifierInfo *II : DD->cpus()) {
2976 // Get the name of the target function so we can look it up/create it.
2977 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
2978 getCPUSpecificMangling(*this, II->getName());
2980 llvm::Constant *Func = GetGlobalValue(MangledName);
2983 GlobalDecl ExistingDecl = Manglings.lookup(MangledName);
2984 if (ExistingDecl.getDecl() &&
2985 ExistingDecl.getDecl()->getAsFunction()->isDefined()) {
2986 EmitGlobalFunctionDefinition(ExistingDecl, nullptr);
2987 Func = GetGlobalValue(MangledName);
2989 if (!ExistingDecl.getDecl())
2990 ExistingDecl = GD.getWithMultiVersionIndex(Index);
2992 Func = GetOrCreateLLVMFunction(
2993 MangledName, DeclTy, ExistingDecl,
2994 /*ForVTable=*/false, /*DontDefer=*/true,
2995 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
2999 llvm::SmallVector<StringRef, 32> Features;
3000 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
3001 llvm::transform(Features, Features.begin(),
3002 [](StringRef Str) { return Str.substr(1); });
3003 Features.erase(std::remove_if(
3004 Features.begin(), Features.end(), [&Target](StringRef Feat) {
3005 return !Target.validateCpuSupports(Feat);
3006 }), Features.end());
3007 Options.emplace_back(cast<llvm::Function>(Func), StringRef{}, Features);
3012 Options, [](const CodeGenFunction::MultiVersionResolverOption &LHS,
3013 const CodeGenFunction::MultiVersionResolverOption &RHS) {
3014 return CodeGenFunction::GetX86CpuSupportsMask(LHS.Conditions.Features) >
3015 CodeGenFunction::GetX86CpuSupportsMask(RHS.Conditions.Features);
3018 // If the list contains multiple 'default' versions, such as when it contains
3019 // 'pentium' and 'generic', don't emit the call to the generic one (since we
3020 // always run on at least a 'pentium'). We do this by deleting the 'least
3021 // advanced' (read, lowest mangling letter).
3022 while (Options.size() > 1 &&
3023 CodeGenFunction::GetX86CpuSupportsMask(
3024 (Options.end() - 2)->Conditions.Features) == 0) {
3025 StringRef LHSName = (Options.end() - 2)->Function->getName();
3026 StringRef RHSName = (Options.end() - 1)->Function->getName();
3027 if (LHSName.compare(RHSName) < 0)
3028 Options.erase(Options.end() - 2);
3030 Options.erase(Options.end() - 1);
3033 CodeGenFunction CGF(*this);
3034 CGF.EmitMultiVersionResolver(ResolverFunc, Options);
3036 if (getTarget().supportsIFunc()) {
3037 std::string AliasName = getMangledNameImpl(
3038 *this, GD, FD, /*OmitMultiVersionMangling=*/true);
3039 llvm::Constant *AliasFunc = GetGlobalValue(AliasName);
3041 auto *IFunc = cast<llvm::GlobalIFunc>(GetOrCreateLLVMFunction(
3042 AliasName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/true,
3043 /*IsThunk=*/false, llvm::AttributeList(), NotForDefinition));
3044 auto *GA = llvm::GlobalAlias::create(
3045 DeclTy, 0, getFunctionLinkage(GD), AliasName, IFunc, &getModule());
3046 GA->setLinkage(llvm::Function::WeakODRLinkage);
3047 SetCommonAttributes(GD, GA);
3052 /// If a dispatcher for the specified mangled name is not in the module, create
3053 /// and return an llvm Function with the specified type.
3054 llvm::Constant *CodeGenModule::GetOrCreateMultiVersionResolver(
3055 GlobalDecl GD, llvm::Type *DeclTy, const FunctionDecl *FD) {
3056 std::string MangledName =
3057 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
3059 // Holds the name of the resolver, in ifunc mode this is the ifunc (which has
3060 // a separate resolver).
3061 std::string ResolverName = MangledName;
3062 if (getTarget().supportsIFunc())
3063 ResolverName += ".ifunc";
3064 else if (FD->isTargetMultiVersion())
3065 ResolverName += ".resolver";
3067 // If this already exists, just return that one.
3068 if (llvm::GlobalValue *ResolverGV = GetGlobalValue(ResolverName))
3071 // Since this is the first time we've created this IFunc, make sure
3072 // that we put this multiversioned function into the list to be
3073 // replaced later if necessary (target multiversioning only).
3074 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
3075 MultiVersionFuncs.push_back(GD);
3077 if (getTarget().supportsIFunc()) {
3078 llvm::Type *ResolverType = llvm::FunctionType::get(
3079 llvm::PointerType::get(
3080 DeclTy, getContext().getTargetAddressSpace(FD->getType())),
3082 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3083 MangledName + ".resolver", ResolverType, GlobalDecl{},
3084 /*ForVTable=*/false);
3085 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
3086 DeclTy, 0, llvm::Function::WeakODRLinkage, "", Resolver, &getModule());
3087 GIF->setName(ResolverName);
3088 SetCommonAttributes(FD, GIF);
3093 llvm::Constant *Resolver = GetOrCreateLLVMFunction(
3094 ResolverName, DeclTy, GlobalDecl{}, /*ForVTable=*/false);
3095 assert(isa<llvm::GlobalValue>(Resolver) &&
3096 "Resolver should be created for the first time");
3097 SetCommonAttributes(FD, cast<llvm::GlobalValue>(Resolver));
3101 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
3102 /// module, create and return an llvm Function with the specified type. If there
3103 /// is something in the module with the specified name, return it potentially
3104 /// bitcasted to the right type.
3106 /// If D is non-null, it specifies a decl that correspond to this. This is used
3107 /// to set the attributes on the function when it is first created.
3108 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
3109 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
3110 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
3111 ForDefinition_t IsForDefinition) {
3112 const Decl *D = GD.getDecl();
3114 // Any attempts to use a MultiVersion function should result in retrieving
3115 // the iFunc instead. Name Mangling will handle the rest of the changes.
3116 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
3117 // For the device mark the function as one that should be emitted.
3118 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
3119 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
3120 !DontDefer && !IsForDefinition) {
3121 if (const FunctionDecl *FDDef = FD->getDefinition()) {
3123 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
3124 GDDef = GlobalDecl(CD, GD.getCtorType());
3125 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
3126 GDDef = GlobalDecl(DD, GD.getDtorType());
3128 GDDef = GlobalDecl(FDDef);
3132 // Check if this must be emitted as declare variant and emit reference to
3133 // the the declare variant function.
3134 if (LangOpts.OpenMP && OpenMPRuntime)
3135 (void)OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/true);
3137 if (FD->isMultiVersion()) {
3138 const auto *TA = FD->getAttr<TargetAttr>();
3139 if (TA && TA->isDefaultVersion())
3140 UpdateMultiVersionNames(GD, FD);
3141 if (!IsForDefinition)
3142 return GetOrCreateMultiVersionResolver(GD, Ty, FD);
3146 // Lookup the entry, lazily creating it if necessary.
3147 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3149 if (WeakRefReferences.erase(Entry)) {
3150 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
3151 if (FD && !FD->hasAttr<WeakAttr>())
3152 Entry->setLinkage(llvm::Function::ExternalLinkage);
3155 // Handle dropped DLL attributes.
3156 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
3157 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3161 // If there are two attempts to define the same mangled name, issue an
3163 if (IsForDefinition && !Entry->isDeclaration()) {
3165 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
3166 // to make sure that we issue an error only once.
3167 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3168 (GD.getCanonicalDecl().getDecl() !=
3169 OtherGD.getCanonicalDecl().getDecl()) &&
3170 DiagnosedConflictingDefinitions.insert(GD).second) {
3171 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3173 getDiags().Report(OtherGD.getDecl()->getLocation(),
3174 diag::note_previous_definition);
3178 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
3179 (Entry->getType()->getElementType() == Ty)) {
3183 // Make sure the result is of the correct type.
3184 // (If function is requested for a definition, we always need to create a new
3185 // function, not just return a bitcast.)
3186 if (!IsForDefinition)
3187 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
3190 // This function doesn't have a complete type (for example, the return
3191 // type is an incomplete struct). Use a fake type instead, and make
3192 // sure not to try to set attributes.
3193 bool IsIncompleteFunction = false;
3195 llvm::FunctionType *FTy;
3196 if (isa<llvm::FunctionType>(Ty)) {
3197 FTy = cast<llvm::FunctionType>(Ty);
3199 FTy = llvm::FunctionType::get(VoidTy, false);
3200 IsIncompleteFunction = true;
3204 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
3205 Entry ? StringRef() : MangledName, &getModule());
3207 // If we already created a function with the same mangled name (but different
3208 // type) before, take its name and add it to the list of functions to be
3209 // replaced with F at the end of CodeGen.
3211 // This happens if there is a prototype for a function (e.g. "int f()") and
3212 // then a definition of a different type (e.g. "int f(int x)").
3216 // This might be an implementation of a function without a prototype, in
3217 // which case, try to do special replacement of calls which match the new
3218 // prototype. The really key thing here is that we also potentially drop
3219 // arguments from the call site so as to make a direct call, which makes the
3220 // inliner happier and suppresses a number of optimizer warnings (!) about
3221 // dropping arguments.
3222 if (!Entry->use_empty()) {
3223 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
3224 Entry->removeDeadConstantUsers();
3227 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
3228 F, Entry->getType()->getElementType()->getPointerTo());
3229 addGlobalValReplacement(Entry, BC);
3232 assert(F->getName() == MangledName && "name was uniqued!");
3234 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
3235 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
3236 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
3237 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
3241 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
3242 // each other bottoming out with the base dtor. Therefore we emit non-base
3243 // dtors on usage, even if there is no dtor definition in the TU.
3244 if (D && isa<CXXDestructorDecl>(D) &&
3245 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
3247 addDeferredDeclToEmit(GD);
3249 // This is the first use or definition of a mangled name. If there is a
3250 // deferred decl with this name, remember that we need to emit it at the end
3252 auto DDI = DeferredDecls.find(MangledName);
3253 if (DDI != DeferredDecls.end()) {
3254 // Move the potentially referenced deferred decl to the
3255 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
3256 // don't need it anymore).
3257 addDeferredDeclToEmit(DDI->second);
3258 DeferredDecls.erase(DDI);
3260 // Otherwise, there are cases we have to worry about where we're
3261 // using a declaration for which we must emit a definition but where
3262 // we might not find a top-level definition:
3263 // - member functions defined inline in their classes
3264 // - friend functions defined inline in some class
3265 // - special member functions with implicit definitions
3266 // If we ever change our AST traversal to walk into class methods,
3267 // this will be unnecessary.
3269 // We also don't emit a definition for a function if it's going to be an
3270 // entry in a vtable, unless it's already marked as used.
3271 } else if (getLangOpts().CPlusPlus && D) {
3272 // Look for a declaration that's lexically in a record.
3273 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
3274 FD = FD->getPreviousDecl()) {
3275 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
3276 if (FD->doesThisDeclarationHaveABody()) {
3277 addDeferredDeclToEmit(GD.getWithDecl(FD));
3285 // Make sure the result is of the requested type.
3286 if (!IsIncompleteFunction) {
3287 assert(F->getType()->getElementType() == Ty);
3291 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3292 return llvm::ConstantExpr::getBitCast(F, PTy);
3295 /// GetAddrOfFunction - Return the address of the given function. If Ty is
3296 /// non-null, then this function will use the specified type if it has to
3297 /// create it (this occurs when we see a definition of the function).
3298 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
3302 ForDefinition_t IsForDefinition) {
3303 // If there was no specific requested type, just convert it now.
3305 const auto *FD = cast<FunctionDecl>(GD.getDecl());
3306 Ty = getTypes().ConvertType(FD->getType());
3309 // Devirtualized destructor calls may come through here instead of via
3310 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
3311 // of the complete destructor when necessary.
3312 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
3313 if (getTarget().getCXXABI().isMicrosoft() &&
3314 GD.getDtorType() == Dtor_Complete &&
3315 DD->getParent()->getNumVBases() == 0)
3316 GD = GlobalDecl(DD, Dtor_Base);
3319 StringRef MangledName = getMangledName(GD);
3320 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
3321 /*IsThunk=*/false, llvm::AttributeList(),
3325 static const FunctionDecl *
3326 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
3327 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
3328 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3330 IdentifierInfo &CII = C.Idents.get(Name);
3331 for (const auto &Result : DC->lookup(&CII))
3332 if (const auto FD = dyn_cast<FunctionDecl>(Result))
3335 if (!C.getLangOpts().CPlusPlus)
3338 // Demangle the premangled name from getTerminateFn()
3339 IdentifierInfo &CXXII =
3340 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
3341 ? C.Idents.get("terminate")
3342 : C.Idents.get(Name);
3344 for (const auto &N : {"__cxxabiv1", "std"}) {
3345 IdentifierInfo &NS = C.Idents.get(N);
3346 for (const auto &Result : DC->lookup(&NS)) {
3347 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
3348 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
3349 for (const auto &Result : LSD->lookup(&NS))
3350 if ((ND = dyn_cast<NamespaceDecl>(Result)))
3354 for (const auto &Result : ND->lookup(&CXXII))
3355 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
3363 /// CreateRuntimeFunction - Create a new runtime function with the specified
3365 llvm::FunctionCallee
3366 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
3367 llvm::AttributeList ExtraAttrs, bool Local,
3368 bool AssumeConvergent) {
3369 if (AssumeConvergent) {
3371 ExtraAttrs.addAttribute(VMContext, llvm::AttributeList::FunctionIndex,
3372 llvm::Attribute::Convergent);
3376 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
3377 /*DontDefer=*/false, /*IsThunk=*/false,
3380 if (auto *F = dyn_cast<llvm::Function>(C)) {
3382 F->setCallingConv(getRuntimeCC());
3384 // In Windows Itanium environments, try to mark runtime functions
3385 // dllimport. For Mingw and MSVC, don't. We don't really know if the user
3386 // will link their standard library statically or dynamically. Marking
3387 // functions imported when they are not imported can cause linker errors
3389 if (!Local && getTriple().isWindowsItaniumEnvironment() &&
3390 !getCodeGenOpts().LTOVisibilityPublicStd) {
3391 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
3392 if (!FD || FD->hasAttr<DLLImportAttr>()) {
3393 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3394 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
3404 /// isTypeConstant - Determine whether an object of this type can be emitted
3407 /// If ExcludeCtor is true, the duration when the object's constructor runs
3408 /// will not be considered. The caller will need to verify that the object is
3409 /// not written to during its construction.
3410 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
3411 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
3414 if (Context.getLangOpts().CPlusPlus) {
3415 if (const CXXRecordDecl *Record
3416 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
3417 return ExcludeCtor && !Record->hasMutableFields() &&
3418 Record->hasTrivialDestructor();
3424 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
3425 /// create and return an llvm GlobalVariable with the specified type. If there
3426 /// is something in the module with the specified name, return it potentially
3427 /// bitcasted to the right type.
3429 /// If D is non-null, it specifies a decl that correspond to this. This is used
3430 /// to set the attributes on the global when it is first created.
3432 /// If IsForDefinition is true, it is guaranteed that an actual global with
3433 /// type Ty will be returned, not conversion of a variable with the same
3434 /// mangled name but some other type.
3436 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
3437 llvm::PointerType *Ty,
3439 ForDefinition_t IsForDefinition) {
3440 // Lookup the entry, lazily creating it if necessary.
3441 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3443 if (WeakRefReferences.erase(Entry)) {
3444 if (D && !D->hasAttr<WeakAttr>())
3445 Entry->setLinkage(llvm::Function::ExternalLinkage);
3448 // Handle dropped DLL attributes.
3449 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
3450 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
3452 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
3453 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
3455 if (Entry->getType() == Ty)
3458 // If there are two attempts to define the same mangled name, issue an
3460 if (IsForDefinition && !Entry->isDeclaration()) {
3462 const VarDecl *OtherD;
3464 // Check that D is not yet in DiagnosedConflictingDefinitions is required
3465 // to make sure that we issue an error only once.
3466 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
3467 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
3468 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
3469 OtherD->hasInit() &&
3470 DiagnosedConflictingDefinitions.insert(D).second) {
3471 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
3473 getDiags().Report(OtherGD.getDecl()->getLocation(),
3474 diag::note_previous_definition);
3478 // Make sure the result is of the correct type.
3479 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
3480 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
3482 // (If global is requested for a definition, we always need to create a new
3483 // global, not just return a bitcast.)
3484 if (!IsForDefinition)
3485 return llvm::ConstantExpr::getBitCast(Entry, Ty);
3488 auto AddrSpace = GetGlobalVarAddressSpace(D);
3489 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
3491 auto *GV = new llvm::GlobalVariable(
3492 getModule(), Ty->getElementType(), false,
3493 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
3494 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
3496 // If we already created a global with the same mangled name (but different
3497 // type) before, take its name and remove it from its parent.
3499 GV->takeName(Entry);
3501 if (!Entry->use_empty()) {
3502 llvm::Constant *NewPtrForOldDecl =
3503 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3504 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3507 Entry->eraseFromParent();
3510 // This is the first use or definition of a mangled name. If there is a
3511 // deferred decl with this name, remember that we need to emit it at the end
3513 auto DDI = DeferredDecls.find(MangledName);
3514 if (DDI != DeferredDecls.end()) {
3515 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
3516 // list, and remove it from DeferredDecls (since we don't need it anymore).
3517 addDeferredDeclToEmit(DDI->second);
3518 DeferredDecls.erase(DDI);
3521 // Handle things which are present even on external declarations.
3523 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
3524 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
3526 // FIXME: This code is overly simple and should be merged with other global
3528 GV->setConstant(isTypeConstant(D->getType(), false));
3530 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
3532 setLinkageForGV(GV, D);
3534 if (D->getTLSKind()) {
3535 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3536 CXXThreadLocals.push_back(D);
3540 setGVProperties(GV, D);
3542 // If required by the ABI, treat declarations of static data members with
3543 // inline initializers as definitions.
3544 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
3545 EmitGlobalVarDefinition(D);
3548 // Emit section information for extern variables.
3549 if (D->hasExternalStorage()) {
3550 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
3551 GV->setSection(SA->getName());
3554 // Handle XCore specific ABI requirements.
3555 if (getTriple().getArch() == llvm::Triple::xcore &&
3556 D->getLanguageLinkage() == CLanguageLinkage &&
3557 D->getType().isConstant(Context) &&
3558 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
3559 GV->setSection(".cp.rodata");
3561 // Check if we a have a const declaration with an initializer, we may be
3562 // able to emit it as available_externally to expose it's value to the
3564 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
3565 D->getType().isConstQualified() && !GV->hasInitializer() &&
3566 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
3567 const auto *Record =
3568 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
3569 bool HasMutableFields = Record && Record->hasMutableFields();
3570 if (!HasMutableFields) {
3571 const VarDecl *InitDecl;
3572 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3574 ConstantEmitter emitter(*this);
3575 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
3577 auto *InitType = Init->getType();
3578 if (GV->getType()->getElementType() != InitType) {
3579 // The type of the initializer does not match the definition.
3580 // This happens when an initializer has a different type from
3581 // the type of the global (because of padding at the end of a
3582 // structure for instance).
3583 GV->setName(StringRef());
3584 // Make a new global with the correct type, this is now guaranteed
3586 auto *NewGV = cast<llvm::GlobalVariable>(
3587 GetAddrOfGlobalVar(D, InitType, IsForDefinition)
3588 ->stripPointerCasts());
3590 // Erase the old global, since it is no longer used.
3591 GV->eraseFromParent();
3594 GV->setInitializer(Init);
3595 GV->setConstant(true);
3596 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3598 emitter.finalize(GV);
3605 if (GV->isDeclaration())
3606 getTargetCodeGenInfo().setTargetAttributes(D, GV, *this);
3609 D ? D->getType().getAddressSpace()
3610 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3611 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3612 Ty->getPointerAddressSpace());
3613 if (AddrSpace != ExpectedAS)
3614 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3621 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
3622 ForDefinition_t IsForDefinition) {
3623 const Decl *D = GD.getDecl();
3624 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
3625 return getAddrOfCXXStructor(GD, /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3626 /*DontDefer=*/false, IsForDefinition);
3627 else if (isa<CXXMethodDecl>(D)) {
3628 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
3629 cast<CXXMethodDecl>(D));
3630 auto Ty = getTypes().GetFunctionType(*FInfo);
3631 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3633 } else if (isa<FunctionDecl>(D)) {
3634 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3635 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3636 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3639 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
3643 llvm::GlobalVariable *CodeGenModule::CreateOrReplaceCXXRuntimeVariable(
3644 StringRef Name, llvm::Type *Ty, llvm::GlobalValue::LinkageTypes Linkage,
3645 unsigned Alignment) {
3646 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3647 llvm::GlobalVariable *OldGV = nullptr;
3650 // Check if the variable has the right type.
3651 if (GV->getType()->getElementType() == Ty)
3654 // Because C++ name mangling, the only way we can end up with an already
3655 // existing global with the same name is if it has been declared extern "C".
3656 assert(GV->isDeclaration() && "Declaration has wrong type!");
3660 // Create a new variable.
3661 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
3662 Linkage, nullptr, Name);
3665 // Replace occurrences of the old variable if needed.
3666 GV->takeName(OldGV);
3668 if (!OldGV->use_empty()) {
3669 llvm::Constant *NewPtrForOldDecl =
3670 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3671 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3674 OldGV->eraseFromParent();
3677 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3678 !GV->hasAvailableExternallyLinkage())
3679 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3681 GV->setAlignment(llvm::MaybeAlign(Alignment));
3686 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3687 /// given global variable. If Ty is non-null and if the global doesn't exist,
3688 /// then it will be created with the specified type instead of whatever the
3689 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
3690 /// that an actual global with type Ty will be returned, not conversion of a
3691 /// variable with the same mangled name but some other type.
3692 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
3694 ForDefinition_t IsForDefinition) {
3695 assert(D->hasGlobalStorage() && "Not a global variable");
3696 QualType ASTTy = D->getType();
3698 Ty = getTypes().ConvertTypeForMem(ASTTy);
3700 llvm::PointerType *PTy =
3701 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
3703 StringRef MangledName = getMangledName(D);
3704 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3707 /// CreateRuntimeVariable - Create a new runtime global variable with the
3708 /// specified type and name.
3710 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
3713 getContext().getLangOpts().OpenCL
3714 ? llvm::PointerType::get(
3715 Ty, getContext().getTargetAddressSpace(LangAS::opencl_global))
3716 : llvm::PointerType::getUnqual(Ty);
3717 auto *Ret = GetOrCreateLLVMGlobal(Name, PtrTy, nullptr);
3718 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3722 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3723 assert(!D->getInit() && "Cannot emit definite definitions here!");
3725 StringRef MangledName = getMangledName(D);
3726 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3728 // We already have a definition, not declaration, with the same mangled name.
3729 // Emitting of declaration is not required (and actually overwrites emitted
3731 if (GV && !GV->isDeclaration())
3734 // If we have not seen a reference to this variable yet, place it into the
3735 // deferred declarations table to be emitted if needed later.
3736 if (!MustBeEmitted(D) && !GV) {
3737 DeferredDecls[MangledName] = D;
3741 // The tentative definition is the only definition.
3742 EmitGlobalVarDefinition(D);
3745 void CodeGenModule::EmitExternalDeclaration(const VarDecl *D) {
3746 EmitExternalVarDeclaration(D);
3749 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
3750 return Context.toCharUnitsFromBits(
3751 getDataLayout().getTypeStoreSizeInBits(Ty));
3754 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3755 LangAS AddrSpace = LangAS::Default;
3756 if (LangOpts.OpenCL) {
3757 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3758 assert(AddrSpace == LangAS::opencl_global ||
3759 AddrSpace == LangAS::opencl_constant ||
3760 AddrSpace == LangAS::opencl_local ||
3761 AddrSpace >= LangAS::FirstTargetAddressSpace);
3765 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3766 if (D && D->hasAttr<CUDAConstantAttr>())
3767 return LangAS::cuda_constant;
3768 else if (D && D->hasAttr<CUDASharedAttr>())
3769 return LangAS::cuda_shared;
3770 else if (D && D->hasAttr<CUDADeviceAttr>())
3771 return LangAS::cuda_device;
3772 else if (D && D->getType().isConstQualified())
3773 return LangAS::cuda_constant;
3775 return LangAS::cuda_device;
3778 if (LangOpts.OpenMP) {
3780 if (OpenMPRuntime->hasAllocateAttributeForGlobalVar(D, AS))
3783 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3786 LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3787 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3788 if (LangOpts.OpenCL)
3789 return LangAS::opencl_constant;
3790 if (auto AS = getTarget().getConstantAddressSpace())
3791 return AS.getValue();
3792 return LangAS::Default;
3795 // In address space agnostic languages, string literals are in default address
3796 // space in AST. However, certain targets (e.g. amdgcn) request them to be
3797 // emitted in constant address space in LLVM IR. To be consistent with other
3798 // parts of AST, string literal global variables in constant address space
3799 // need to be casted to default address space before being put into address
3800 // map and referenced by other part of CodeGen.
3801 // In OpenCL, string literals are in constant address space in AST, therefore
3802 // they should not be casted to default address space.
3803 static llvm::Constant *
3804 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3805 llvm::GlobalVariable *GV) {
3806 llvm::Constant *Cast = GV;
3807 if (!CGM.getLangOpts().OpenCL) {
3808 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3809 if (AS != LangAS::Default)
3810 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3811 CGM, GV, AS.getValue(), LangAS::Default,
3812 GV->getValueType()->getPointerTo(
3813 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3819 template<typename SomeDecl>
3820 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3821 llvm::GlobalValue *GV) {
3822 if (!getLangOpts().CPlusPlus)
3825 // Must have 'used' attribute, or else inline assembly can't rely on
3826 // the name existing.
3827 if (!D->template hasAttr<UsedAttr>())
3830 // Must have internal linkage and an ordinary name.
3831 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3834 // Must be in an extern "C" context. Entities declared directly within
3835 // a record are not extern "C" even if the record is in such a context.
3836 const SomeDecl *First = D->getFirstDecl();
3837 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3840 // OK, this is an internal linkage entity inside an extern "C" linkage
3841 // specification. Make a note of that so we can give it the "expected"
3842 // mangled name if nothing else is using that name.
3843 std::pair<StaticExternCMap::iterator, bool> R =
3844 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3846 // If we have multiple internal linkage entities with the same name
3847 // in extern "C" regions, none of them gets that name.
3849 R.first->second = nullptr;
3852 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3853 if (!CGM.supportsCOMDAT())
3856 // Do not set COMDAT attribute for CUDA/HIP stub functions to prevent
3857 // them being "merged" by the COMDAT Folding linker optimization.
3858 if (D.hasAttr<CUDAGlobalAttr>())
3861 if (D.hasAttr<SelectAnyAttr>())
3865 if (auto *VD = dyn_cast<VarDecl>(&D))
3866 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3868 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3872 case GVA_AvailableExternally:
3873 case GVA_StrongExternal:
3875 case GVA_DiscardableODR:
3879 llvm_unreachable("No such linkage");
3882 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3883 llvm::GlobalObject &GO) {
3884 if (!shouldBeInCOMDAT(*this, D))
3886 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3889 /// Pass IsTentative as true if you want to create a tentative definition.
3890 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3892 // OpenCL global variables of sampler type are translated to function calls,
3893 // therefore no need to be translated.
3894 QualType ASTTy = D->getType();
3895 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3898 // If this is OpenMP device, check if it is legal to emit this global
3900 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3901 OpenMPRuntime->emitTargetGlobalVariable(D))
3904 llvm::Constant *Init = nullptr;
3905 bool NeedsGlobalCtor = false;
3906 bool NeedsGlobalDtor =
3907 D->needsDestruction(getContext()) == QualType::DK_cxx_destructor;
3909 const VarDecl *InitDecl;
3910 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3912 Optional<ConstantEmitter> emitter;
3914 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3915 // as part of their declaration." Sema has already checked for
3916 // error cases, so we just need to set Init to UndefValue.
3917 bool IsCUDASharedVar =
3918 getLangOpts().CUDAIsDevice && D->hasAttr<CUDASharedAttr>();
3919 // Shadows of initialized device-side global variables are also left
3921 bool IsCUDAShadowVar =
3922 !getLangOpts().CUDAIsDevice &&
3923 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>() ||
3924 D->hasAttr<CUDASharedAttr>());
3925 // HIP pinned shadow of initialized host-side global variables are also
3927 bool IsHIPPinnedShadowVar =
3928 getLangOpts().CUDAIsDevice && D->hasAttr<HIPPinnedShadowAttr>();
3929 if (getLangOpts().CUDA &&
3930 (IsCUDASharedVar || IsCUDAShadowVar || IsHIPPinnedShadowVar))
3931 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3932 else if (!InitExpr) {
3933 // This is a tentative definition; tentative definitions are
3934 // implicitly initialized with { 0 }.
3936 // Note that tentative definitions are only emitted at the end of
3937 // a translation unit, so they should never have incomplete
3938 // type. In addition, EmitTentativeDefinition makes sure that we
3939 // never attempt to emit a tentative definition if a real one
3940 // exists. A use may still exists, however, so we still may need
3942 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
3943 Init = EmitNullConstant(D->getType());
3945 initializedGlobalDecl = GlobalDecl(D);
3946 emitter.emplace(*this);
3947 Init = emitter->tryEmitForInitializer(*InitDecl);
3950 QualType T = InitExpr->getType();
3951 if (D->getType()->isReferenceType())
3954 if (getLangOpts().CPlusPlus) {
3955 Init = EmitNullConstant(T);
3956 NeedsGlobalCtor = true;
3958 ErrorUnsupported(D, "static initializer");
3959 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3962 // We don't need an initializer, so remove the entry for the delayed
3963 // initializer position (just in case this entry was delayed) if we
3964 // also don't need to register a destructor.
3965 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
3966 DelayedCXXInitPosition.erase(D);
3970 llvm::Type* InitType = Init->getType();
3971 llvm::Constant *Entry =
3972 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
3974 // Strip off pointer casts if we got them.
3975 Entry = Entry->stripPointerCasts();
3977 // Entry is now either a Function or GlobalVariable.
3978 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3980 // We have a definition after a declaration with the wrong type.
3981 // We must make a new GlobalVariable* and update everything that used OldGV
3982 // (a declaration or tentative definition) with the new GlobalVariable*
3983 // (which will be a definition).
3985 // This happens if there is a prototype for a global (e.g.
3986 // "extern int x[];") and then a definition of a different type (e.g.
3987 // "int x[10];"). This also happens when an initializer has a different type
3988 // from the type of the global (this happens with unions).
3989 if (!GV || GV->getType()->getElementType() != InitType ||
3990 GV->getType()->getAddressSpace() !=
3991 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
3993 // Move the old entry aside so that we'll create a new one.
3994 Entry->setName(StringRef());
3996 // Make a new global with the correct type, this is now guaranteed to work.
3997 GV = cast<llvm::GlobalVariable>(
3998 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative))
3999 ->stripPointerCasts());
4001 // Replace all uses of the old global with the new global
4002 llvm::Constant *NewPtrForOldDecl =
4003 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
4004 Entry->replaceAllUsesWith(NewPtrForOldDecl);
4006 // Erase the old global, since it is no longer used.
4007 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
4010 MaybeHandleStaticInExternC(D, GV);
4012 if (D->hasAttr<AnnotateAttr>())
4013 AddGlobalAnnotations(D, GV);
4015 // Set the llvm linkage type as appropriate.
4016 llvm::GlobalValue::LinkageTypes Linkage =
4017 getLLVMLinkageVarDefinition(D, GV->isConstant());
4019 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
4020 // the device. [...]"
4021 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
4022 // __device__, declares a variable that: [...]
4023 // Is accessible from all the threads within the grid and from the host
4024 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
4025 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
4026 if (GV && LangOpts.CUDA) {
4027 if (LangOpts.CUDAIsDevice) {
4028 if (Linkage != llvm::GlobalValue::InternalLinkage &&
4029 (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()))
4030 GV->setExternallyInitialized(true);
4032 // Host-side shadows of external declarations of device-side
4033 // global variables become internal definitions. These have to
4034 // be internal in order to prevent name conflicts with global
4035 // host variables with the same name in a different TUs.
4036 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>() ||
4037 D->hasAttr<HIPPinnedShadowAttr>()) {
4038 Linkage = llvm::GlobalValue::InternalLinkage;
4040 // Shadow variables and their properties must be registered
4041 // with CUDA runtime.
4043 if (!D->hasDefinition())
4044 Flags |= CGCUDARuntime::ExternDeviceVar;
4045 if (D->hasAttr<CUDAConstantAttr>())
4046 Flags |= CGCUDARuntime::ConstantDeviceVar;
4047 // Extern global variables will be registered in the TU where they are
4049 if (!D->hasExternalStorage())
4050 getCUDARuntime().registerDeviceVar(D, *GV, Flags);
4051 } else if (D->hasAttr<CUDASharedAttr>())
4052 // __shared__ variables are odd. Shadows do get created, but
4053 // they are not registered with the CUDA runtime, so they
4054 // can't really be used to access their device-side
4055 // counterparts. It's not clear yet whether it's nvcc's bug or
4056 // a feature, but we've got to do the same for compatibility.
4057 Linkage = llvm::GlobalValue::InternalLinkage;
4061 if (!IsHIPPinnedShadowVar)
4062 GV->setInitializer(Init);
4063 if (emitter) emitter->finalize(GV);
4065 // If it is safe to mark the global 'constant', do so now.
4066 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
4067 isTypeConstant(D->getType(), true));
4069 // If it is in a read-only section, mark it 'constant'.
4070 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
4071 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
4072 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
4073 GV->setConstant(true);
4076 GV->setAlignment(getContext().getDeclAlign(D).getAsAlign());
4078 // On Darwin, if the normal linkage of a C++ thread_local variable is
4079 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
4080 // copies within a linkage unit; otherwise, the backing variable has
4081 // internal linkage and all accesses should just be calls to the
4082 // Itanium-specified entry point, which has the normal linkage of the
4083 // variable. This is to preserve the ability to change the implementation
4084 // behind the scenes.
4085 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
4086 Context.getTargetInfo().getTriple().isOSDarwin() &&
4087 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
4088 !llvm::GlobalVariable::isWeakLinkage(Linkage))
4089 Linkage = llvm::GlobalValue::InternalLinkage;
4091 GV->setLinkage(Linkage);
4092 if (D->hasAttr<DLLImportAttr>())
4093 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
4094 else if (D->hasAttr<DLLExportAttr>())
4095 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
4097 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
4099 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
4100 // common vars aren't constant even if declared const.
4101 GV->setConstant(false);
4102 // Tentative definition of global variables may be initialized with
4103 // non-zero null pointers. In this case they should have weak linkage
4104 // since common linkage must have zero initializer and must not have
4105 // explicit section therefore cannot have non-zero initial value.
4106 if (!GV->getInitializer()->isNullValue())
4107 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
4110 setNonAliasAttributes(D, GV);
4112 if (D->getTLSKind() && !GV->isThreadLocal()) {
4113 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
4114 CXXThreadLocals.push_back(D);
4118 maybeSetTrivialComdat(*D, *GV);
4120 // Emit the initializer function if necessary.
4121 if (NeedsGlobalCtor || NeedsGlobalDtor)
4122 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
4124 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
4126 // Emit global variable debug information.
4127 if (CGDebugInfo *DI = getModuleDebugInfo())
4128 if (getCodeGenOpts().hasReducedDebugInfo())
4129 DI->EmitGlobalVariable(GV, D);
4132 void CodeGenModule::EmitExternalVarDeclaration(const VarDecl *D) {
4133 if (CGDebugInfo *DI = getModuleDebugInfo())
4134 if (getCodeGenOpts().hasReducedDebugInfo()) {
4135 QualType ASTTy = D->getType();
4136 llvm::Type *Ty = getTypes().ConvertTypeForMem(D->getType());
4137 llvm::PointerType *PTy =
4138 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
4139 llvm::Constant *GV = GetOrCreateLLVMGlobal(D->getName(), PTy, D);
4140 DI->EmitExternalVariable(
4141 cast<llvm::GlobalVariable>(GV->stripPointerCasts()), D);
4145 static bool isVarDeclStrongDefinition(const ASTContext &Context,
4146 CodeGenModule &CGM, const VarDecl *D,
4148 // Don't give variables common linkage if -fno-common was specified unless it
4149 // was overridden by a NoCommon attribute.
4150 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
4154 // A declaration of an identifier for an object that has file scope without
4155 // an initializer, and without a storage-class specifier or with the
4156 // storage-class specifier static, constitutes a tentative definition.
4157 if (D->getInit() || D->hasExternalStorage())
4160 // A variable cannot be both common and exist in a section.
4161 if (D->hasAttr<SectionAttr>())
4164 // A variable cannot be both common and exist in a section.
4165 // We don't try to determine which is the right section in the front-end.
4166 // If no specialized section name is applicable, it will resort to default.
4167 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
4168 D->hasAttr<PragmaClangDataSectionAttr>() ||
4169 D->hasAttr<PragmaClangRelroSectionAttr>() ||
4170 D->hasAttr<PragmaClangRodataSectionAttr>())
4173 // Thread local vars aren't considered common linkage.
4174 if (D->getTLSKind())
4177 // Tentative definitions marked with WeakImportAttr are true definitions.
4178 if (D->hasAttr<WeakImportAttr>())
4181 // A variable cannot be both common and exist in a comdat.
4182 if (shouldBeInCOMDAT(CGM, *D))
4185 // Declarations with a required alignment do not have common linkage in MSVC
4187 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
4188 if (D->hasAttr<AlignedAttr>())
4190 QualType VarType = D->getType();
4191 if (Context.isAlignmentRequired(VarType))
4194 if (const auto *RT = VarType->getAs<RecordType>()) {
4195 const RecordDecl *RD = RT->getDecl();
4196 for (const FieldDecl *FD : RD->fields()) {
4197 if (FD->isBitField())
4199 if (FD->hasAttr<AlignedAttr>())
4201 if (Context.isAlignmentRequired(FD->getType()))
4207 // Microsoft's link.exe doesn't support alignments greater than 32 bytes for
4208 // common symbols, so symbols with greater alignment requirements cannot be
4210 // Other COFF linkers (ld.bfd and LLD) support arbitrary power-of-two
4211 // alignments for common symbols via the aligncomm directive, so this
4212 // restriction only applies to MSVC environments.
4213 if (Context.getTargetInfo().getTriple().isKnownWindowsMSVCEnvironment() &&
4214 Context.getTypeAlignIfKnown(D->getType()) >
4215 Context.toBits(CharUnits::fromQuantity(32)))
4221 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
4222 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
4223 if (Linkage == GVA_Internal)
4224 return llvm::Function::InternalLinkage;
4226 if (D->hasAttr<WeakAttr>()) {
4227 if (IsConstantVariable)
4228 return llvm::GlobalVariable::WeakODRLinkage;
4230 return llvm::GlobalVariable::WeakAnyLinkage;
4233 if (const auto *FD = D->getAsFunction())
4234 if (FD->isMultiVersion() && Linkage == GVA_AvailableExternally)
4235 return llvm::GlobalVariable::LinkOnceAnyLinkage;
4237 // We are guaranteed to have a strong definition somewhere else,
4238 // so we can use available_externally linkage.
4239 if (Linkage == GVA_AvailableExternally)
4240 return llvm::GlobalValue::AvailableExternallyLinkage;
4242 // Note that Apple's kernel linker doesn't support symbol
4243 // coalescing, so we need to avoid linkonce and weak linkages there.
4244 // Normally, this means we just map to internal, but for explicit
4245 // instantiations we'll map to external.
4247 // In C++, the compiler has to emit a definition in every translation unit
4248 // that references the function. We should use linkonce_odr because
4249 // a) if all references in this translation unit are optimized away, we
4250 // don't need to codegen it. b) if the function persists, it needs to be
4251 // merged with other definitions. c) C++ has the ODR, so we know the
4252 // definition is dependable.
4253 if (Linkage == GVA_DiscardableODR)
4254 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
4255 : llvm::Function::InternalLinkage;
4257 // An explicit instantiation of a template has weak linkage, since
4258 // explicit instantiations can occur in multiple translation units
4259 // and must all be equivalent. However, we are not allowed to
4260 // throw away these explicit instantiations.
4262 // We don't currently support CUDA device code spread out across multiple TUs,
4263 // so say that CUDA templates are either external (for kernels) or internal.
4264 // This lets llvm perform aggressive inter-procedural optimizations.
4265 if (Linkage == GVA_StrongODR) {
4266 if (Context.getLangOpts().AppleKext)
4267 return llvm::Function::ExternalLinkage;
4268 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
4269 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
4270 : llvm::Function::InternalLinkage;
4271 return llvm::Function::WeakODRLinkage;
4274 // C++ doesn't have tentative definitions and thus cannot have common
4276 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
4277 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
4278 CodeGenOpts.NoCommon))
4279 return llvm::GlobalVariable::CommonLinkage;
4281 // selectany symbols are externally visible, so use weak instead of
4282 // linkonce. MSVC optimizes away references to const selectany globals, so
4283 // all definitions should be the same and ODR linkage should be used.
4284 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
4285 if (D->hasAttr<SelectAnyAttr>())
4286 return llvm::GlobalVariable::WeakODRLinkage;
4288 // Otherwise, we have strong external linkage.
4289 assert(Linkage == GVA_StrongExternal);
4290 return llvm::GlobalVariable::ExternalLinkage;
4293 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
4294 const VarDecl *VD, bool IsConstant) {
4295 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
4296 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
4299 /// Replace the uses of a function that was declared with a non-proto type.
4300 /// We want to silently drop extra arguments from call sites
4301 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
4302 llvm::Function *newFn) {
4304 if (old->use_empty()) return;
4306 llvm::Type *newRetTy = newFn->getReturnType();
4307 SmallVector<llvm::Value*, 4> newArgs;
4308 SmallVector<llvm::OperandBundleDef, 1> newBundles;
4310 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
4312 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
4313 llvm::User *user = use->getUser();
4315 // Recognize and replace uses of bitcasts. Most calls to
4316 // unprototyped functions will use bitcasts.
4317 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
4318 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
4319 replaceUsesOfNonProtoConstant(bitcast, newFn);
4323 // Recognize calls to the function.
4324 llvm::CallBase *callSite = dyn_cast<llvm::CallBase>(user);
4325 if (!callSite) continue;
4326 if (!callSite->isCallee(&*use))
4329 // If the return types don't match exactly, then we can't
4330 // transform this call unless it's dead.
4331 if (callSite->getType() != newRetTy && !callSite->use_empty())
4334 // Get the call site's attribute list.
4335 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
4336 llvm::AttributeList oldAttrs = callSite->getAttributes();
4338 // If the function was passed too few arguments, don't transform.
4339 unsigned newNumArgs = newFn->arg_size();
4340 if (callSite->arg_size() < newNumArgs)
4343 // If extra arguments were passed, we silently drop them.
4344 // If any of the types mismatch, we don't transform.
4346 bool dontTransform = false;
4347 for (llvm::Argument &A : newFn->args()) {
4348 if (callSite->getArgOperand(argNo)->getType() != A.getType()) {
4349 dontTransform = true;
4353 // Add any parameter attributes.
4354 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
4360 // Okay, we can transform this. Create the new call instruction and copy
4361 // over the required information.
4362 newArgs.append(callSite->arg_begin(), callSite->arg_begin() + argNo);
4364 // Copy over any operand bundles.
4365 callSite->getOperandBundlesAsDefs(newBundles);
4367 llvm::CallBase *newCall;
4368 if (dyn_cast<llvm::CallInst>(callSite)) {
4370 llvm::CallInst::Create(newFn, newArgs, newBundles, "", callSite);
4372 auto *oldInvoke = cast<llvm::InvokeInst>(callSite);
4373 newCall = llvm::InvokeInst::Create(newFn, oldInvoke->getNormalDest(),
4374 oldInvoke->getUnwindDest(), newArgs,
4375 newBundles, "", callSite);
4377 newArgs.clear(); // for the next iteration
4379 if (!newCall->getType()->isVoidTy())
4380 newCall->takeName(callSite);
4381 newCall->setAttributes(llvm::AttributeList::get(
4382 newFn->getContext(), oldAttrs.getFnAttributes(),
4383 oldAttrs.getRetAttributes(), newArgAttrs));
4384 newCall->setCallingConv(callSite->getCallingConv());
4386 // Finally, remove the old call, replacing any uses with the new one.
4387 if (!callSite->use_empty())
4388 callSite->replaceAllUsesWith(newCall);
4390 // Copy debug location attached to CI.
4391 if (callSite->getDebugLoc())
4392 newCall->setDebugLoc(callSite->getDebugLoc());
4394 callSite->eraseFromParent();
4398 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
4399 /// implement a function with no prototype, e.g. "int foo() {}". If there are
4400 /// existing call uses of the old function in the module, this adjusts them to
4401 /// call the new function directly.
4403 /// This is not just a cleanup: the always_inline pass requires direct calls to
4404 /// functions to be able to inline them. If there is a bitcast in the way, it
4405 /// won't inline them. Instcombine normally deletes these calls, but it isn't
4407 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
4408 llvm::Function *NewFn) {
4409 // If we're redefining a global as a function, don't transform it.
4410 if (!isa<llvm::Function>(Old)) return;
4412 replaceUsesOfNonProtoConstant(Old, NewFn);
4415 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
4416 auto DK = VD->isThisDeclarationADefinition();
4417 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
4420 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
4421 // If we have a definition, this might be a deferred decl. If the
4422 // instantiation is explicit, make sure we emit it at the end.
4423 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
4424 GetAddrOfGlobalVar(VD);
4426 EmitTopLevelDecl(VD);
4429 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
4430 llvm::GlobalValue *GV) {
4431 // Check if this must be emitted as declare variant.
4432 if (LangOpts.OpenMP && OpenMPRuntime &&
4433 OpenMPRuntime->emitDeclareVariant(GD, /*IsForDefinition=*/true))
4436 const auto *D = cast<FunctionDecl>(GD.getDecl());
4438 // Compute the function info and LLVM type.
4439 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
4440 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
4442 // Get or create the prototype for the function.
4443 if (!GV || (GV->getType()->getElementType() != Ty))
4444 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
4449 if (!GV->isDeclaration())
4452 // We need to set linkage and visibility on the function before
4453 // generating code for it because various parts of IR generation
4454 // want to propagate this information down (e.g. to local static
4456 auto *Fn = cast<llvm::Function>(GV);
4457 setFunctionLinkage(GD, Fn);
4459 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
4460 setGVProperties(Fn, GD);
4462 MaybeHandleStaticInExternC(D, Fn);
4465 maybeSetTrivialComdat(*D, *Fn);
4467 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
4469 setNonAliasAttributes(GD, Fn);
4470 SetLLVMFunctionAttributesForDefinition(D, Fn);
4472 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
4473 AddGlobalCtor(Fn, CA->getPriority());
4474 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
4475 AddGlobalDtor(Fn, DA->getPriority());
4476 if (D->hasAttr<AnnotateAttr>())
4477 AddGlobalAnnotations(D, Fn);
4480 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
4481 const auto *D = cast<ValueDecl>(GD.getDecl());
4482 const AliasAttr *AA = D->getAttr<AliasAttr>();
4483 assert(AA && "Not an alias?");
4485 StringRef MangledName = getMangledName(GD);
4487 if (AA->getAliasee() == MangledName) {
4488 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4492 // If there is a definition in the module, then it wins over the alias.
4493 // This is dubious, but allow it to be safe. Just ignore the alias.
4494 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4495 if (Entry && !Entry->isDeclaration())
4498 Aliases.push_back(GD);
4500 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4502 // Create a reference to the named value. This ensures that it is emitted
4503 // if a deferred decl.
4504 llvm::Constant *Aliasee;
4505 llvm::GlobalValue::LinkageTypes LT;
4506 if (isa<llvm::FunctionType>(DeclTy)) {
4507 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
4508 /*ForVTable=*/false);
4509 LT = getFunctionLinkage(GD);
4511 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
4512 llvm::PointerType::getUnqual(DeclTy),
4514 LT = getLLVMLinkageVarDefinition(cast<VarDecl>(GD.getDecl()),
4515 D->getType().isConstQualified());
4518 // Create the new alias itself, but don't set a name yet.
4520 llvm::GlobalAlias::create(DeclTy, 0, LT, "", Aliasee, &getModule());
4523 if (GA->getAliasee() == Entry) {
4524 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
4528 assert(Entry->isDeclaration());
4530 // If there is a declaration in the module, then we had an extern followed
4531 // by the alias, as in:
4532 // extern int test6();
4534 // int test6() __attribute__((alias("test7")));
4536 // Remove it and replace uses of it with the alias.
4537 GA->takeName(Entry);
4539 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
4541 Entry->eraseFromParent();
4543 GA->setName(MangledName);
4546 // Set attributes which are particular to an alias; this is a
4547 // specialization of the attributes which may be set on a global
4548 // variable/function.
4549 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
4550 D->isWeakImported()) {
4551 GA->setLinkage(llvm::Function::WeakAnyLinkage);
4554 if (const auto *VD = dyn_cast<VarDecl>(D))
4555 if (VD->getTLSKind())
4556 setTLSMode(GA, *VD);
4558 SetCommonAttributes(GD, GA);
4561 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
4562 const auto *D = cast<ValueDecl>(GD.getDecl());
4563 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
4564 assert(IFA && "Not an ifunc?");
4566 StringRef MangledName = getMangledName(GD);
4568 if (IFA->getResolver() == MangledName) {
4569 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4573 // Report an error if some definition overrides ifunc.
4574 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
4575 if (Entry && !Entry->isDeclaration()) {
4577 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
4578 DiagnosedConflictingDefinitions.insert(GD).second) {
4579 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
4581 Diags.Report(OtherGD.getDecl()->getLocation(),
4582 diag::note_previous_definition);
4587 Aliases.push_back(GD);
4589 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
4590 llvm::Constant *Resolver =
4591 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
4592 /*ForVTable=*/false);
4593 llvm::GlobalIFunc *GIF =
4594 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
4595 "", Resolver, &getModule());
4597 if (GIF->getResolver() == Entry) {
4598 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
4601 assert(Entry->isDeclaration());
4603 // If there is a declaration in the module, then we had an extern followed
4604 // by the ifunc, as in:
4605 // extern int test();
4607 // int test() __attribute__((ifunc("resolver")));
4609 // Remove it and replace uses of it with the ifunc.
4610 GIF->takeName(Entry);
4612 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
4614 Entry->eraseFromParent();
4616 GIF->setName(MangledName);
4618 SetCommonAttributes(GD, GIF);
4621 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
4622 ArrayRef<llvm::Type*> Tys) {
4623 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
4627 static llvm::StringMapEntry<llvm::GlobalVariable *> &
4628 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
4629 const StringLiteral *Literal, bool TargetIsLSB,
4630 bool &IsUTF16, unsigned &StringLength) {
4631 StringRef String = Literal->getString();
4632 unsigned NumBytes = String.size();
4634 // Check for simple case.
4635 if (!Literal->containsNonAsciiOrNull()) {
4636 StringLength = NumBytes;
4637 return *Map.insert(std::make_pair(String, nullptr)).first;
4640 // Otherwise, convert the UTF8 literals into a string of shorts.
4643 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
4644 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
4645 llvm::UTF16 *ToPtr = &ToBuf[0];
4647 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4648 ToPtr + NumBytes, llvm::strictConversion);
4650 // ConvertUTF8toUTF16 returns the length in ToPtr.
4651 StringLength = ToPtr - &ToBuf[0];
4653 // Add an explicit null.
4655 return *Map.insert(std::make_pair(
4656 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4657 (StringLength + 1) * 2),
4662 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4663 unsigned StringLength = 0;
4664 bool isUTF16 = false;
4665 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4666 GetConstantCFStringEntry(CFConstantStringMap, Literal,
4667 getDataLayout().isLittleEndian(), isUTF16,
4670 if (auto *C = Entry.second)
4671 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4673 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4674 llvm::Constant *Zeros[] = { Zero, Zero };
4676 const ASTContext &Context = getContext();
4677 const llvm::Triple &Triple = getTriple();
4679 const auto CFRuntime = getLangOpts().CFRuntime;
4680 const bool IsSwiftABI =
4681 static_cast<unsigned>(CFRuntime) >=
4682 static_cast<unsigned>(LangOptions::CoreFoundationABI::Swift);
4683 const bool IsSwift4_1 = CFRuntime == LangOptions::CoreFoundationABI::Swift4_1;
4685 // If we don't already have it, get __CFConstantStringClassReference.
4686 if (!CFConstantStringClassRef) {
4687 const char *CFConstantStringClassName = "__CFConstantStringClassReference";
4688 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
4689 Ty = llvm::ArrayType::get(Ty, 0);
4691 switch (CFRuntime) {
4693 case LangOptions::CoreFoundationABI::Swift: LLVM_FALLTHROUGH;
4694 case LangOptions::CoreFoundationABI::Swift5_0:
4695 CFConstantStringClassName =
4696 Triple.isOSDarwin() ? "$s15SwiftFoundation19_NSCFConstantStringCN"
4697 : "$s10Foundation19_NSCFConstantStringCN";
4700 case LangOptions::CoreFoundationABI::Swift4_2:
4701 CFConstantStringClassName =
4702 Triple.isOSDarwin() ? "$S15SwiftFoundation19_NSCFConstantStringCN"
4703 : "$S10Foundation19_NSCFConstantStringCN";
4706 case LangOptions::CoreFoundationABI::Swift4_1:
4707 CFConstantStringClassName =
4708 Triple.isOSDarwin() ? "__T015SwiftFoundation19_NSCFConstantStringCN"
4709 : "__T010Foundation19_NSCFConstantStringCN";
4714 llvm::Constant *C = CreateRuntimeVariable(Ty, CFConstantStringClassName);
4716 if (Triple.isOSBinFormatELF() || Triple.isOSBinFormatCOFF()) {
4717 llvm::GlobalValue *GV = nullptr;
4719 if ((GV = dyn_cast<llvm::GlobalValue>(C))) {
4720 IdentifierInfo &II = Context.Idents.get(GV->getName());
4721 TranslationUnitDecl *TUDecl = Context.getTranslationUnitDecl();
4722 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4724 const VarDecl *VD = nullptr;
4725 for (const auto &Result : DC->lookup(&II))
4726 if ((VD = dyn_cast<VarDecl>(Result)))
4729 if (Triple.isOSBinFormatELF()) {
4731 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4733 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4734 if (!VD || !VD->hasAttr<DLLExportAttr>())
4735 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4737 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4744 // Decay array -> ptr
4745 CFConstantStringClassRef =
4746 IsSwiftABI ? llvm::ConstantExpr::getPtrToInt(C, Ty)
4747 : llvm::ConstantExpr::getGetElementPtr(Ty, C, Zeros);
4750 QualType CFTy = Context.getCFConstantStringType();
4752 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4754 ConstantInitBuilder Builder(*this);
4755 auto Fields = Builder.beginStruct(STy);
4758 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4762 Fields.addInt(IntPtrTy, IsSwift4_1 ? 0x05 : 0x01);
4763 Fields.addInt(Int64Ty, isUTF16 ? 0x07d0 : 0x07c8);
4765 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4769 llvm::Constant *C = nullptr;
4771 auto Arr = llvm::makeArrayRef(
4772 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4773 Entry.first().size() / 2);
4774 C = llvm::ConstantDataArray::get(VMContext, Arr);
4776 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4779 // Note: -fwritable-strings doesn't make the backing store strings of
4780 // CFStrings writable. (See <rdar://problem/10657500>)
4782 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4783 llvm::GlobalValue::PrivateLinkage, C, ".str");
4784 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4785 // Don't enforce the target's minimum global alignment, since the only use
4786 // of the string is via this class initializer.
4787 CharUnits Align = isUTF16 ? Context.getTypeAlignInChars(Context.ShortTy)
4788 : Context.getTypeAlignInChars(Context.CharTy);
4789 GV->setAlignment(Align.getAsAlign());
4791 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4792 // Without it LLVM can merge the string with a non unnamed_addr one during
4793 // LTO. Doing that changes the section it ends in, which surprises ld64.
4794 if (Triple.isOSBinFormatMachO())
4795 GV->setSection(isUTF16 ? "__TEXT,__ustring"
4796 : "__TEXT,__cstring,cstring_literals");
4797 // Make sure the literal ends up in .rodata to allow for safe ICF and for
4798 // the static linker to adjust permissions to read-only later on.
4799 else if (Triple.isOSBinFormatELF())
4800 GV->setSection(".rodata");
4803 llvm::Constant *Str =
4804 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4807 // Cast the UTF16 string to the correct type.
4808 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4812 llvm::IntegerType *LengthTy =
4813 llvm::IntegerType::get(getModule().getContext(),
4814 Context.getTargetInfo().getLongWidth());
4816 if (CFRuntime == LangOptions::CoreFoundationABI::Swift4_1 ||
4817 CFRuntime == LangOptions::CoreFoundationABI::Swift4_2)
4820 LengthTy = IntPtrTy;
4822 Fields.addInt(LengthTy, StringLength);
4824 // Swift ABI requires 8-byte alignment to ensure that the _Atomic(uint64_t) is
4825 // properly aligned on 32-bit platforms.
4826 CharUnits Alignment =
4827 IsSwiftABI ? Context.toCharUnitsFromBits(64) : getPointerAlign();
4830 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4831 /*isConstant=*/false,
4832 llvm::GlobalVariable::PrivateLinkage);
4833 GV->addAttribute("objc_arc_inert");
4834 switch (Triple.getObjectFormat()) {
4835 case llvm::Triple::UnknownObjectFormat:
4836 llvm_unreachable("unknown file format");
4837 case llvm::Triple::XCOFF:
4838 llvm_unreachable("XCOFF is not yet implemented");
4839 case llvm::Triple::COFF:
4840 case llvm::Triple::ELF:
4841 case llvm::Triple::Wasm:
4842 GV->setSection("cfstring");
4844 case llvm::Triple::MachO:
4845 GV->setSection("__DATA,__cfstring");
4850 return ConstantAddress(GV, Alignment);
4853 bool CodeGenModule::getExpressionLocationsEnabled() const {
4854 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4857 QualType CodeGenModule::getObjCFastEnumerationStateType() {
4858 if (ObjCFastEnumerationStateType.isNull()) {
4859 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
4860 D->startDefinition();
4862 QualType FieldTypes[] = {
4863 Context.UnsignedLongTy,
4864 Context.getPointerType(Context.getObjCIdType()),
4865 Context.getPointerType(Context.UnsignedLongTy),
4866 Context.getConstantArrayType(Context.UnsignedLongTy,
4867 llvm::APInt(32, 5), nullptr, ArrayType::Normal, 0)
4870 for (size_t i = 0; i < 4; ++i) {
4871 FieldDecl *Field = FieldDecl::Create(Context,
4874 SourceLocation(), nullptr,
4875 FieldTypes[i], /*TInfo=*/nullptr,
4876 /*BitWidth=*/nullptr,
4879 Field->setAccess(AS_public);
4883 D->completeDefinition();
4884 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4887 return ObjCFastEnumerationStateType;
4891 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4892 assert(!E->getType()->isPointerType() && "Strings are always arrays");
4894 // Don't emit it as the address of the string, emit the string data itself
4895 // as an inline array.
4896 if (E->getCharByteWidth() == 1) {
4897 SmallString<64> Str(E->getString());
4899 // Resize the string to the right size, which is indicated by its type.
4900 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4901 Str.resize(CAT->getSize().getZExtValue());
4902 return llvm::ConstantDataArray::getString(VMContext, Str, false);
4905 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
4906 llvm::Type *ElemTy = AType->getElementType();
4907 unsigned NumElements = AType->getNumElements();
4909 // Wide strings have either 2-byte or 4-byte elements.
4910 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4911 SmallVector<uint16_t, 32> Elements;
4912 Elements.reserve(NumElements);
4914 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4915 Elements.push_back(E->getCodeUnit(i));
4916 Elements.resize(NumElements);
4917 return llvm::ConstantDataArray::get(VMContext, Elements);
4920 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4921 SmallVector<uint32_t, 32> Elements;
4922 Elements.reserve(NumElements);
4924 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4925 Elements.push_back(E->getCodeUnit(i));
4926 Elements.resize(NumElements);
4927 return llvm::ConstantDataArray::get(VMContext, Elements);
4930 static llvm::GlobalVariable *
4931 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4932 CodeGenModule &CGM, StringRef GlobalName,
4933 CharUnits Alignment) {
4934 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4935 CGM.getStringLiteralAddressSpace());
4937 llvm::Module &M = CGM.getModule();
4938 // Create a global variable for this string
4939 auto *GV = new llvm::GlobalVariable(
4940 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4941 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4942 GV->setAlignment(Alignment.getAsAlign());
4943 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4944 if (GV->isWeakForLinker()) {
4945 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4946 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4948 CGM.setDSOLocal(GV);
4953 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4954 /// constant array for the given string literal.
4956 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4958 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
4960 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4961 llvm::GlobalVariable **Entry = nullptr;
4962 if (!LangOpts.WritableStrings) {
4963 Entry = &ConstantStringMap[C];
4964 if (auto GV = *Entry) {
4965 if (Alignment.getQuantity() > GV->getAlignment())
4966 GV->setAlignment(Alignment.getAsAlign());
4967 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4972 SmallString<256> MangledNameBuffer;
4973 StringRef GlobalVariableName;
4974 llvm::GlobalValue::LinkageTypes LT;
4976 // Mangle the string literal if that's how the ABI merges duplicate strings.
4977 // Don't do it if they are writable, since we don't want writes in one TU to
4978 // affect strings in another.
4979 if (getCXXABI().getMangleContext().shouldMangleStringLiteral(S) &&
4980 !LangOpts.WritableStrings) {
4981 llvm::raw_svector_ostream Out(MangledNameBuffer);
4982 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
4983 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4984 GlobalVariableName = MangledNameBuffer;
4986 LT = llvm::GlobalValue::PrivateLinkage;
4987 GlobalVariableName = Name;
4990 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4994 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4997 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5001 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
5002 /// array for the given ObjCEncodeExpr node.
5004 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
5006 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
5008 return GetAddrOfConstantCString(Str);
5011 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
5012 /// the literal and a terminating '\0' character.
5013 /// The result has pointer to array type.
5014 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
5015 const std::string &Str, const char *GlobalName) {
5016 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
5017 CharUnits Alignment =
5018 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
5021 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
5023 // Don't share any string literals if strings aren't constant.
5024 llvm::GlobalVariable **Entry = nullptr;
5025 if (!LangOpts.WritableStrings) {
5026 Entry = &ConstantStringMap[C];
5027 if (auto GV = *Entry) {
5028 if (Alignment.getQuantity() > GV->getAlignment())
5029 GV->setAlignment(Alignment.getAsAlign());
5030 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5035 // Get the default prefix if a name wasn't specified.
5037 GlobalName = ".str";
5038 // Create a global variable for this.
5039 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
5040 GlobalName, Alignment);
5044 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
5048 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
5049 const MaterializeTemporaryExpr *E, const Expr *Init) {
5050 assert((E->getStorageDuration() == SD_Static ||
5051 E->getStorageDuration() == SD_Thread) && "not a global temporary");
5052 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
5054 // If we're not materializing a subobject of the temporary, keep the
5055 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
5056 QualType MaterializedType = Init->getType();
5057 if (Init == E->getSubExpr())
5058 MaterializedType = E->getType();
5060 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
5062 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
5063 return ConstantAddress(Slot, Align);
5065 // FIXME: If an externally-visible declaration extends multiple temporaries,
5066 // we need to give each temporary the same name in every translation unit (and
5067 // we also need to make the temporaries externally-visible).
5068 SmallString<256> Name;
5069 llvm::raw_svector_ostream Out(Name);
5070 getCXXABI().getMangleContext().mangleReferenceTemporary(
5071 VD, E->getManglingNumber(), Out);
5073 APValue *Value = nullptr;
5074 if (E->getStorageDuration() == SD_Static && VD && VD->evaluateValue()) {
5075 // If the initializer of the extending declaration is a constant
5076 // initializer, we should have a cached constant initializer for this
5077 // temporary. Note that this might have a different value from the value
5078 // computed by evaluating the initializer if the surrounding constant
5079 // expression modifies the temporary.
5080 Value = E->getOrCreateValue(false);
5083 // Try evaluating it now, it might have a constant initializer.
5084 Expr::EvalResult EvalResult;
5085 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
5086 !EvalResult.hasSideEffects())
5087 Value = &EvalResult.Val;
5090 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
5092 Optional<ConstantEmitter> emitter;
5093 llvm::Constant *InitialValue = nullptr;
5094 bool Constant = false;
5097 // The temporary has a constant initializer, use it.
5098 emitter.emplace(*this);
5099 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
5101 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
5102 Type = InitialValue->getType();
5104 // No initializer, the initialization will be provided when we
5105 // initialize the declaration which performed lifetime extension.
5106 Type = getTypes().ConvertTypeForMem(MaterializedType);
5109 // Create a global variable for this lifetime-extended temporary.
5110 llvm::GlobalValue::LinkageTypes Linkage =
5111 getLLVMLinkageVarDefinition(VD, Constant);
5112 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
5113 const VarDecl *InitVD;
5114 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
5115 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
5116 // Temporaries defined inside a class get linkonce_odr linkage because the
5117 // class can be defined in multiple translation units.
5118 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
5120 // There is no need for this temporary to have external linkage if the
5121 // VarDecl has external linkage.
5122 Linkage = llvm::GlobalVariable::InternalLinkage;
5125 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
5126 auto *GV = new llvm::GlobalVariable(
5127 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
5128 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
5129 if (emitter) emitter->finalize(GV);
5130 setGVProperties(GV, VD);
5131 GV->setAlignment(Align.getAsAlign());
5132 if (supportsCOMDAT() && GV->isWeakForLinker())
5133 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
5134 if (VD->getTLSKind())
5135 setTLSMode(GV, *VD);
5136 llvm::Constant *CV = GV;
5137 if (AddrSpace != LangAS::Default)
5138 CV = getTargetCodeGenInfo().performAddrSpaceCast(
5139 *this, GV, AddrSpace, LangAS::Default,
5141 getContext().getTargetAddressSpace(LangAS::Default)));
5142 MaterializedGlobalTemporaryMap[E] = CV;
5143 return ConstantAddress(CV, Align);
5146 /// EmitObjCPropertyImplementations - Emit information for synthesized
5147 /// properties for an implementation.
5148 void CodeGenModule::EmitObjCPropertyImplementations(const
5149 ObjCImplementationDecl *D) {
5150 for (const auto *PID : D->property_impls()) {
5151 // Dynamic is just for type-checking.
5152 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
5153 ObjCPropertyDecl *PD = PID->getPropertyDecl();
5155 // Determine which methods need to be implemented, some may have
5156 // been overridden. Note that ::isPropertyAccessor is not the method
5157 // we want, that just indicates if the decl came from a
5158 // property. What we want to know is if the method is defined in
5159 // this implementation.
5160 auto *Getter = PID->getGetterMethodDecl();
5161 if (!Getter || Getter->isSynthesizedAccessorStub())
5162 CodeGenFunction(*this).GenerateObjCGetter(
5163 const_cast<ObjCImplementationDecl *>(D), PID);
5164 auto *Setter = PID->getSetterMethodDecl();
5165 if (!PD->isReadOnly() && (!Setter || Setter->isSynthesizedAccessorStub()))
5166 CodeGenFunction(*this).GenerateObjCSetter(
5167 const_cast<ObjCImplementationDecl *>(D), PID);
5172 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
5173 const ObjCInterfaceDecl *iface = impl->getClassInterface();
5174 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
5175 ivar; ivar = ivar->getNextIvar())
5176 if (ivar->getType().isDestructedType())
5182 static bool AllTrivialInitializers(CodeGenModule &CGM,
5183 ObjCImplementationDecl *D) {
5184 CodeGenFunction CGF(CGM);
5185 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
5186 E = D->init_end(); B != E; ++B) {
5187 CXXCtorInitializer *CtorInitExp = *B;
5188 Expr *Init = CtorInitExp->getInit();
5189 if (!CGF.isTrivialInitializer(Init))
5195 /// EmitObjCIvarInitializations - Emit information for ivar initialization
5196 /// for an implementation.
5197 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
5198 // We might need a .cxx_destruct even if we don't have any ivar initializers.
5199 if (needsDestructMethod(D)) {
5200 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
5201 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5202 ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(
5203 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5204 getContext().VoidTy, nullptr, D,
5205 /*isInstance=*/true, /*isVariadic=*/false,
5206 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5207 /*isImplicitlyDeclared=*/true,
5208 /*isDefined=*/false, ObjCMethodDecl::Required);
5209 D->addInstanceMethod(DTORMethod);
5210 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
5211 D->setHasDestructors(true);
5214 // If the implementation doesn't have any ivar initializers, we don't need
5215 // a .cxx_construct.
5216 if (D->getNumIvarInitializers() == 0 ||
5217 AllTrivialInitializers(*this, D))
5220 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
5221 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
5222 // The constructor returns 'self'.
5223 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(
5224 getContext(), D->getLocation(), D->getLocation(), cxxSelector,
5225 getContext().getObjCIdType(), nullptr, D, /*isInstance=*/true,
5226 /*isVariadic=*/false,
5227 /*isPropertyAccessor=*/true, /*isSynthesizedAccessorStub=*/false,
5228 /*isImplicitlyDeclared=*/true,
5229 /*isDefined=*/false, ObjCMethodDecl::Required);
5230 D->addInstanceMethod(CTORMethod);
5231 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
5232 D->setHasNonZeroConstructors(true);
5235 // EmitLinkageSpec - Emit all declarations in a linkage spec.
5236 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
5237 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
5238 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
5239 ErrorUnsupported(LSD, "linkage spec");
5243 EmitDeclContext(LSD);
5246 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
5247 for (auto *I : DC->decls()) {
5248 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
5249 // are themselves considered "top-level", so EmitTopLevelDecl on an
5250 // ObjCImplDecl does not recursively visit them. We need to do that in
5251 // case they're nested inside another construct (LinkageSpecDecl /
5252 // ExportDecl) that does stop them from being considered "top-level".
5253 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
5254 for (auto *M : OID->methods())
5255 EmitTopLevelDecl(M);
5258 EmitTopLevelDecl(I);
5262 /// EmitTopLevelDecl - Emit code for a single top level declaration.
5263 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
5264 // Ignore dependent declarations.
5265 if (D->isTemplated())
5268 switch (D->getKind()) {
5269 case Decl::CXXConversion:
5270 case Decl::CXXMethod:
5271 case Decl::Function:
5272 EmitGlobal(cast<FunctionDecl>(D));
5273 // Always provide some coverage mapping
5274 // even for the functions that aren't emitted.
5275 AddDeferredUnusedCoverageMapping(D);
5278 case Decl::CXXDeductionGuide:
5279 // Function-like, but does not result in code emission.
5283 case Decl::Decomposition:
5284 case Decl::VarTemplateSpecialization:
5285 EmitGlobal(cast<VarDecl>(D));
5286 if (auto *DD = dyn_cast<DecompositionDecl>(D))
5287 for (auto *B : DD->bindings())
5288 if (auto *HD = B->getHoldingVar())
5292 // Indirect fields from global anonymous structs and unions can be
5293 // ignored; only the actual variable requires IR gen support.
5294 case Decl::IndirectField:
5298 case Decl::Namespace:
5299 EmitDeclContext(cast<NamespaceDecl>(D));
5301 case Decl::ClassTemplateSpecialization: {
5302 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
5304 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
5305 Spec->hasDefinition())
5306 DebugInfo->completeTemplateDefinition(*Spec);
5308 case Decl::CXXRecord:
5310 if (auto *ES = D->getASTContext().getExternalSource())
5311 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
5312 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
5314 // Emit any static data members, they may be definitions.
5315 for (auto *I : cast<CXXRecordDecl>(D)->decls())
5316 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
5317 EmitTopLevelDecl(I);
5319 // No code generation needed.
5320 case Decl::UsingShadow:
5321 case Decl::ClassTemplate:
5322 case Decl::VarTemplate:
5324 case Decl::VarTemplatePartialSpecialization:
5325 case Decl::FunctionTemplate:
5326 case Decl::TypeAliasTemplate:
5331 case Decl::Using: // using X; [C++]
5332 if (CGDebugInfo *DI = getModuleDebugInfo())
5333 DI->EmitUsingDecl(cast<UsingDecl>(*D));
5335 case Decl::NamespaceAlias:
5336 if (CGDebugInfo *DI = getModuleDebugInfo())
5337 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
5339 case Decl::UsingDirective: // using namespace X; [C++]
5340 if (CGDebugInfo *DI = getModuleDebugInfo())
5341 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
5343 case Decl::CXXConstructor:
5344 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
5346 case Decl::CXXDestructor:
5347 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
5350 case Decl::StaticAssert:
5354 // Objective-C Decls
5356 // Forward declarations, no (immediate) code generation.
5357 case Decl::ObjCInterface:
5358 case Decl::ObjCCategory:
5361 case Decl::ObjCProtocol: {
5362 auto *Proto = cast<ObjCProtocolDecl>(D);
5363 if (Proto->isThisDeclarationADefinition())
5364 ObjCRuntime->GenerateProtocol(Proto);
5368 case Decl::ObjCCategoryImpl:
5369 // Categories have properties but don't support synthesize so we
5370 // can ignore them here.
5371 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
5374 case Decl::ObjCImplementation: {
5375 auto *OMD = cast<ObjCImplementationDecl>(D);
5376 EmitObjCPropertyImplementations(OMD);
5377 EmitObjCIvarInitializations(OMD);
5378 ObjCRuntime->GenerateClass(OMD);
5379 // Emit global variable debug information.
5380 if (CGDebugInfo *DI = getModuleDebugInfo())
5381 if (getCodeGenOpts().hasReducedDebugInfo())
5382 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
5383 OMD->getClassInterface()), OMD->getLocation());
5386 case Decl::ObjCMethod: {
5387 auto *OMD = cast<ObjCMethodDecl>(D);
5388 // If this is not a prototype, emit the body.
5390 CodeGenFunction(*this).GenerateObjCMethod(OMD);
5393 case Decl::ObjCCompatibleAlias:
5394 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
5397 case Decl::PragmaComment: {
5398 const auto *PCD = cast<PragmaCommentDecl>(D);
5399 switch (PCD->getCommentKind()) {
5401 llvm_unreachable("unexpected pragma comment kind");
5403 AppendLinkerOptions(PCD->getArg());
5406 AddDependentLib(PCD->getArg());
5411 break; // We ignore all of these.
5416 case Decl::PragmaDetectMismatch: {
5417 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
5418 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
5422 case Decl::LinkageSpec:
5423 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
5426 case Decl::FileScopeAsm: {
5427 // File-scope asm is ignored during device-side CUDA compilation.
5428 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
5430 // File-scope asm is ignored during device-side OpenMP compilation.
5431 if (LangOpts.OpenMPIsDevice)
5433 auto *AD = cast<FileScopeAsmDecl>(D);
5434 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
5438 case Decl::Import: {
5439 auto *Import = cast<ImportDecl>(D);
5441 // If we've already imported this module, we're done.
5442 if (!ImportedModules.insert(Import->getImportedModule()))
5445 // Emit debug information for direct imports.
5446 if (!Import->getImportedOwningModule()) {
5447 if (CGDebugInfo *DI = getModuleDebugInfo())
5448 DI->EmitImportDecl(*Import);
5451 // Find all of the submodules and emit the module initializers.
5452 llvm::SmallPtrSet<clang::Module *, 16> Visited;
5453 SmallVector<clang::Module *, 16> Stack;
5454 Visited.insert(Import->getImportedModule());
5455 Stack.push_back(Import->getImportedModule());
5457 while (!Stack.empty()) {
5458 clang::Module *Mod = Stack.pop_back_val();
5459 if (!EmittedModuleInitializers.insert(Mod).second)
5462 for (auto *D : Context.getModuleInitializers(Mod))
5463 EmitTopLevelDecl(D);
5465 // Visit the submodules of this module.
5466 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
5467 SubEnd = Mod->submodule_end();
5468 Sub != SubEnd; ++Sub) {
5469 // Skip explicit children; they need to be explicitly imported to emit
5470 // the initializers.
5471 if ((*Sub)->IsExplicit)
5474 if (Visited.insert(*Sub).second)
5475 Stack.push_back(*Sub);
5482 EmitDeclContext(cast<ExportDecl>(D));
5485 case Decl::OMPThreadPrivate:
5486 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
5489 case Decl::OMPAllocate:
5492 case Decl::OMPDeclareReduction:
5493 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
5496 case Decl::OMPDeclareMapper:
5497 EmitOMPDeclareMapper(cast<OMPDeclareMapperDecl>(D));
5500 case Decl::OMPRequires:
5501 EmitOMPRequiresDecl(cast<OMPRequiresDecl>(D));
5505 // Make sure we handled everything we should, every other kind is a
5506 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
5507 // function. Need to recode Decl::Kind to do that easily.
5508 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
5513 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
5514 // Do we need to generate coverage mapping?
5515 if (!CodeGenOpts.CoverageMapping)
5517 switch (D->getKind()) {
5518 case Decl::CXXConversion:
5519 case Decl::CXXMethod:
5520 case Decl::Function:
5521 case Decl::ObjCMethod:
5522 case Decl::CXXConstructor:
5523 case Decl::CXXDestructor: {
5524 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
5526 SourceManager &SM = getContext().getSourceManager();
5527 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getBeginLoc()))
5529 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5530 if (I == DeferredEmptyCoverageMappingDecls.end())
5531 DeferredEmptyCoverageMappingDecls[D] = true;
5539 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
5540 // Do we need to generate coverage mapping?
5541 if (!CodeGenOpts.CoverageMapping)
5543 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
5544 if (Fn->isTemplateInstantiation())
5545 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
5547 auto I = DeferredEmptyCoverageMappingDecls.find(D);
5548 if (I == DeferredEmptyCoverageMappingDecls.end())
5549 DeferredEmptyCoverageMappingDecls[D] = false;
5554 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
5555 // We call takeVector() here to avoid use-after-free.
5556 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
5557 // we deserialize function bodies to emit coverage info for them, and that
5558 // deserializes more declarations. How should we handle that case?
5559 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
5562 const Decl *D = Entry.first;
5563 switch (D->getKind()) {
5564 case Decl::CXXConversion:
5565 case Decl::CXXMethod:
5566 case Decl::Function:
5567 case Decl::ObjCMethod: {
5568 CodeGenPGO PGO(*this);
5569 GlobalDecl GD(cast<FunctionDecl>(D));
5570 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5571 getFunctionLinkage(GD));
5574 case Decl::CXXConstructor: {
5575 CodeGenPGO PGO(*this);
5576 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
5577 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5578 getFunctionLinkage(GD));
5581 case Decl::CXXDestructor: {
5582 CodeGenPGO PGO(*this);
5583 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
5584 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
5585 getFunctionLinkage(GD));
5594 /// Turns the given pointer into a constant.
5595 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
5597 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
5598 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
5599 return llvm::ConstantInt::get(i64, PtrInt);
5602 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
5603 llvm::NamedMDNode *&GlobalMetadata,
5605 llvm::GlobalValue *Addr) {
5606 if (!GlobalMetadata)
5608 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
5610 // TODO: should we report variant information for ctors/dtors?
5611 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
5612 llvm::ConstantAsMetadata::get(GetPointerConstant(
5613 CGM.getLLVMContext(), D.getDecl()))};
5614 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
5617 /// For each function which is declared within an extern "C" region and marked
5618 /// as 'used', but has internal linkage, create an alias from the unmangled
5619 /// name to the mangled name if possible. People expect to be able to refer
5620 /// to such functions with an unmangled name from inline assembly within the
5621 /// same translation unit.
5622 void CodeGenModule::EmitStaticExternCAliases() {
5623 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
5625 for (auto &I : StaticExternCValues) {
5626 IdentifierInfo *Name = I.first;
5627 llvm::GlobalValue *Val = I.second;
5628 if (Val && !getModule().getNamedValue(Name->getName()))
5629 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
5633 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
5634 GlobalDecl &Result) const {
5635 auto Res = Manglings.find(MangledName);
5636 if (Res == Manglings.end())
5638 Result = Res->getValue();
5642 /// Emits metadata nodes associating all the global values in the
5643 /// current module with the Decls they came from. This is useful for
5644 /// projects using IR gen as a subroutine.
5646 /// Since there's currently no way to associate an MDNode directly
5647 /// with an llvm::GlobalValue, we create a global named metadata
5648 /// with the name 'clang.global.decl.ptrs'.
5649 void CodeGenModule::EmitDeclMetadata() {
5650 llvm::NamedMDNode *GlobalMetadata = nullptr;
5652 for (auto &I : MangledDeclNames) {
5653 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
5654 // Some mangled names don't necessarily have an associated GlobalValue
5655 // in this module, e.g. if we mangled it for DebugInfo.
5657 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
5661 /// Emits metadata nodes for all the local variables in the current
5663 void CodeGenFunction::EmitDeclMetadata() {
5664 if (LocalDeclMap.empty()) return;
5666 llvm::LLVMContext &Context = getLLVMContext();
5668 // Find the unique metadata ID for this name.
5669 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
5671 llvm::NamedMDNode *GlobalMetadata = nullptr;
5673 for (auto &I : LocalDeclMap) {
5674 const Decl *D = I.first;
5675 llvm::Value *Addr = I.second.getPointer();
5676 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
5677 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
5678 Alloca->setMetadata(
5679 DeclPtrKind, llvm::MDNode::get(
5680 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
5681 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
5682 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
5683 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
5688 void CodeGenModule::EmitVersionIdentMetadata() {
5689 llvm::NamedMDNode *IdentMetadata =
5690 TheModule.getOrInsertNamedMetadata("llvm.ident");
5691 std::string Version = getClangFullVersion();
5692 llvm::LLVMContext &Ctx = TheModule.getContext();
5694 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
5695 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
5698 void CodeGenModule::EmitCommandLineMetadata() {
5699 llvm::NamedMDNode *CommandLineMetadata =
5700 TheModule.getOrInsertNamedMetadata("llvm.commandline");
5701 std::string CommandLine = getCodeGenOpts().RecordCommandLine;
5702 llvm::LLVMContext &Ctx = TheModule.getContext();
5704 llvm::Metadata *CommandLineNode[] = {llvm::MDString::get(Ctx, CommandLine)};
5705 CommandLineMetadata->addOperand(llvm::MDNode::get(Ctx, CommandLineNode));
5708 void CodeGenModule::EmitTargetMetadata() {
5709 // Warning, new MangledDeclNames may be appended within this loop.
5710 // We rely on MapVector insertions adding new elements to the end
5711 // of the container.
5712 // FIXME: Move this loop into the one target that needs it, and only
5713 // loop over those declarations for which we couldn't emit the target
5714 // metadata when we emitted the declaration.
5715 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
5716 auto Val = *(MangledDeclNames.begin() + I);
5717 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
5718 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
5719 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
5723 void CodeGenModule::EmitCoverageFile() {
5724 if (getCodeGenOpts().CoverageDataFile.empty() &&
5725 getCodeGenOpts().CoverageNotesFile.empty())
5728 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5732 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5733 llvm::LLVMContext &Ctx = TheModule.getContext();
5734 auto *CoverageDataFile =
5735 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5736 auto *CoverageNotesFile =
5737 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5738 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5739 llvm::MDNode *CU = CUNode->getOperand(i);
5740 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5741 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5745 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
5746 // Sema has checked that all uuid strings are of the form
5747 // "12345678-1234-1234-1234-1234567890ab".
5748 assert(Uuid.size() == 36);
5749 for (unsigned i = 0; i < 36; ++i) {
5750 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5751 else assert(isHexDigit(Uuid[i]));
5754 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
5755 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
5757 llvm::Constant *Field3[8];
5758 for (unsigned Idx = 0; Idx < 8; ++Idx)
5759 Field3[Idx] = llvm::ConstantInt::get(
5760 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5762 llvm::Constant *Fields[4] = {
5763 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
5764 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
5765 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5766 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5769 return llvm::ConstantStruct::getAnon(Fields);
5772 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5774 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5775 // FIXME: should we even be calling this method if RTTI is disabled
5776 // and it's not for EH?
5777 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
5778 return llvm::Constant::getNullValue(Int8PtrTy);
5780 if (ForEH && Ty->isObjCObjectPointerType() &&
5781 LangOpts.ObjCRuntime.isGNUFamily())
5782 return ObjCRuntime->GetEHType(Ty);
5784 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
5787 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
5788 // Do not emit threadprivates in simd-only mode.
5789 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5791 for (auto RefExpr : D->varlists()) {
5792 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5794 VD->getAnyInitializer() &&
5795 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5798 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
5799 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5800 VD, Addr, RefExpr->getBeginLoc(), PerformInit))
5801 CXXGlobalInits.push_back(InitFunction);
5806 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5808 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
5812 if (isExternallyVisible(T->getLinkage())) {
5813 std::string OutName;
5814 llvm::raw_string_ostream Out(OutName);
5815 getCXXABI().getMangleContext().mangleTypeName(T, Out);
5818 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5820 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5821 llvm::ArrayRef<llvm::Metadata *>());
5827 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5828 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5832 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5833 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5836 // Generalize pointer types to a void pointer with the qualifiers of the
5837 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
5838 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
5840 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5841 if (!Ty->isPointerType())
5844 return Ctx.getPointerType(
5845 QualType(Ctx.VoidTy).withCVRQualifiers(
5846 Ty->getPointeeType().getCVRQualifiers()));
5849 // Apply type generalization to a FunctionType's return and argument types
5850 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5851 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5852 SmallVector<QualType, 8> GeneralizedParams;
5853 for (auto &Param : FnType->param_types())
5854 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5856 return Ctx.getFunctionType(
5857 GeneralizeType(Ctx, FnType->getReturnType()),
5858 GeneralizedParams, FnType->getExtProtoInfo());
5861 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5862 return Ctx.getFunctionNoProtoType(
5863 GeneralizeType(Ctx, FnType->getReturnType()));
5865 llvm_unreachable("Encountered unknown FunctionType");
5868 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
5869 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5870 GeneralizedMetadataIdMap, ".generalized");
5873 /// Returns whether this module needs the "all-vtables" type identifier.
5874 bool CodeGenModule::NeedAllVtablesTypeId() const {
5875 // Returns true if at least one of vtable-based CFI checkers is enabled and
5876 // is not in the trapping mode.
5877 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5878 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5879 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5880 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5881 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5882 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5883 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5884 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5887 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5889 const CXXRecordDecl *RD) {
5890 llvm::Metadata *MD =
5891 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5892 VTable->addTypeMetadata(Offset.getQuantity(), MD);
5894 if (CodeGenOpts.SanitizeCfiCrossDso)
5895 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5896 VTable->addTypeMetadata(Offset.getQuantity(),
5897 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5899 if (NeedAllVtablesTypeId()) {
5900 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
5901 VTable->addTypeMetadata(Offset.getQuantity(), MD);
5905 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5907 SanStats = std::make_unique<llvm::SanitizerStatReport>(&getModule());
5912 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5913 CodeGenFunction &CGF) {
5914 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
5915 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
5916 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5917 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5918 "__translate_sampler_initializer"),