1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the per-module state used while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenModule.h"
16 #include "CGCUDARuntime.h"
19 #include "CGDebugInfo.h"
20 #include "CGObjCRuntime.h"
21 #include "CGOpenCLRuntime.h"
22 #include "CGOpenMPRuntime.h"
23 #include "CGOpenMPRuntimeNVPTX.h"
24 #include "CodeGenFunction.h"
25 #include "CodeGenPGO.h"
26 #include "ConstantEmitter.h"
27 #include "CoverageMappingGen.h"
28 #include "TargetInfo.h"
29 #include "clang/AST/ASTContext.h"
30 #include "clang/AST/CharUnits.h"
31 #include "clang/AST/DeclCXX.h"
32 #include "clang/AST/DeclObjC.h"
33 #include "clang/AST/DeclTemplate.h"
34 #include "clang/AST/Mangle.h"
35 #include "clang/AST/RecordLayout.h"
36 #include "clang/AST/RecursiveASTVisitor.h"
37 #include "clang/Basic/Builtins.h"
38 #include "clang/Basic/CharInfo.h"
39 #include "clang/Basic/Diagnostic.h"
40 #include "clang/Basic/Module.h"
41 #include "clang/Basic/SourceManager.h"
42 #include "clang/Basic/TargetInfo.h"
43 #include "clang/Basic/Version.h"
44 #include "clang/CodeGen/ConstantInitBuilder.h"
45 #include "clang/Frontend/CodeGenOptions.h"
46 #include "clang/Sema/SemaDiagnostic.h"
47 #include "llvm/ADT/Triple.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/IR/CallSite.h"
50 #include "llvm/IR/CallingConv.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/ProfileData/InstrProfReader.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/MD5.h"
60 using namespace clang;
61 using namespace CodeGen;
63 static llvm::cl::opt<bool> LimitedCoverage(
64 "limited-coverage-experimental", llvm::cl::ZeroOrMore, llvm::cl::Hidden,
65 llvm::cl::desc("Emit limited coverage mapping information (experimental)"),
66 llvm::cl::init(false));
68 static const char AnnotationSection[] = "llvm.metadata";
70 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
71 switch (CGM.getTarget().getCXXABI().getKind()) {
72 case TargetCXXABI::GenericAArch64:
73 case TargetCXXABI::GenericARM:
74 case TargetCXXABI::iOS:
75 case TargetCXXABI::iOS64:
76 case TargetCXXABI::WatchOS:
77 case TargetCXXABI::GenericMIPS:
78 case TargetCXXABI::GenericItanium:
79 case TargetCXXABI::WebAssembly:
80 return CreateItaniumCXXABI(CGM);
81 case TargetCXXABI::Microsoft:
82 return CreateMicrosoftCXXABI(CGM);
85 llvm_unreachable("invalid C++ ABI kind");
88 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
89 const PreprocessorOptions &PPO,
90 const CodeGenOptions &CGO, llvm::Module &M,
91 DiagnosticsEngine &diags,
92 CoverageSourceInfo *CoverageInfo)
93 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
94 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
95 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
96 VMContext(M.getContext()), Types(*this), VTables(*this),
97 SanitizerMD(new SanitizerMetadata(*this)) {
99 // Initialize the type cache.
100 llvm::LLVMContext &LLVMContext = M.getContext();
101 VoidTy = llvm::Type::getVoidTy(LLVMContext);
102 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
103 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
104 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
105 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
106 HalfTy = llvm::Type::getHalfTy(LLVMContext);
107 FloatTy = llvm::Type::getFloatTy(LLVMContext);
108 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
109 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
110 PointerAlignInBytes =
111 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
113 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
115 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
116 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
117 IntPtrTy = llvm::IntegerType::get(LLVMContext,
118 C.getTargetInfo().getMaxPointerWidth());
119 Int8PtrTy = Int8Ty->getPointerTo(0);
120 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
121 AllocaInt8PtrTy = Int8Ty->getPointerTo(
122 M.getDataLayout().getAllocaAddrSpace());
123 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
125 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
130 createOpenCLRuntime();
132 createOpenMPRuntime();
136 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
137 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
138 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
139 TBAA.reset(new CodeGenTBAA(Context, TheModule, CodeGenOpts, getLangOpts(),
140 getCXXABI().getMangleContext()));
142 // If debug info or coverage generation is enabled, create the CGDebugInfo
144 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
145 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
146 DebugInfo.reset(new CGDebugInfo(*this));
148 Block.GlobalUniqueCount = 0;
150 if (C.getLangOpts().ObjC1)
151 ObjCData.reset(new ObjCEntrypoints());
153 if (CodeGenOpts.hasProfileClangUse()) {
154 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
155 CodeGenOpts.ProfileInstrumentUsePath);
156 if (auto E = ReaderOrErr.takeError()) {
157 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
158 "Could not read profile %0: %1");
159 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
160 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
164 PGOReader = std::move(ReaderOrErr.get());
167 // If coverage mapping generation is enabled, create the
168 // CoverageMappingModuleGen object.
169 if (CodeGenOpts.CoverageMapping)
170 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
173 CodeGenModule::~CodeGenModule() {}
175 void CodeGenModule::createObjCRuntime() {
176 // This is just isGNUFamily(), but we want to force implementors of
177 // new ABIs to decide how best to do this.
178 switch (LangOpts.ObjCRuntime.getKind()) {
179 case ObjCRuntime::GNUstep:
180 case ObjCRuntime::GCC:
181 case ObjCRuntime::ObjFW:
182 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
185 case ObjCRuntime::FragileMacOSX:
186 case ObjCRuntime::MacOSX:
187 case ObjCRuntime::iOS:
188 case ObjCRuntime::WatchOS:
189 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
192 llvm_unreachable("bad runtime kind");
195 void CodeGenModule::createOpenCLRuntime() {
196 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
199 void CodeGenModule::createOpenMPRuntime() {
200 // Select a specialized code generation class based on the target, if any.
201 // If it does not exist use the default implementation.
202 switch (getTriple().getArch()) {
203 case llvm::Triple::nvptx:
204 case llvm::Triple::nvptx64:
205 assert(getLangOpts().OpenMPIsDevice &&
206 "OpenMP NVPTX is only prepared to deal with device code.");
207 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
210 if (LangOpts.OpenMPSimd)
211 OpenMPRuntime.reset(new CGOpenMPSIMDRuntime(*this));
213 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
218 void CodeGenModule::createCUDARuntime() {
219 CUDARuntime.reset(CreateNVCUDARuntime(*this));
222 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
223 Replacements[Name] = C;
226 void CodeGenModule::applyReplacements() {
227 for (auto &I : Replacements) {
228 StringRef MangledName = I.first();
229 llvm::Constant *Replacement = I.second;
230 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
233 auto *OldF = cast<llvm::Function>(Entry);
234 auto *NewF = dyn_cast<llvm::Function>(Replacement);
236 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
237 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
239 auto *CE = cast<llvm::ConstantExpr>(Replacement);
240 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
241 CE->getOpcode() == llvm::Instruction::GetElementPtr);
242 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
246 // Replace old with new, but keep the old order.
247 OldF->replaceAllUsesWith(Replacement);
249 NewF->removeFromParent();
250 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
253 OldF->eraseFromParent();
257 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
258 GlobalValReplacements.push_back(std::make_pair(GV, C));
261 void CodeGenModule::applyGlobalValReplacements() {
262 for (auto &I : GlobalValReplacements) {
263 llvm::GlobalValue *GV = I.first;
264 llvm::Constant *C = I.second;
266 GV->replaceAllUsesWith(C);
267 GV->eraseFromParent();
271 // This is only used in aliases that we created and we know they have a
273 static const llvm::GlobalObject *getAliasedGlobal(
274 const llvm::GlobalIndirectSymbol &GIS) {
275 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
276 const llvm::Constant *C = &GIS;
278 C = C->stripPointerCasts();
279 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
281 // stripPointerCasts will not walk over weak aliases.
282 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
285 if (!Visited.insert(GIS2).second)
287 C = GIS2->getIndirectSymbol();
291 void CodeGenModule::checkAliases() {
292 // Check if the constructed aliases are well formed. It is really unfortunate
293 // that we have to do this in CodeGen, but we only construct mangled names
294 // and aliases during codegen.
296 DiagnosticsEngine &Diags = getDiags();
297 for (const GlobalDecl &GD : Aliases) {
298 const auto *D = cast<ValueDecl>(GD.getDecl());
299 SourceLocation Location;
300 bool IsIFunc = D->hasAttr<IFuncAttr>();
301 if (const Attr *A = D->getDefiningAttr())
302 Location = A->getLocation();
304 llvm_unreachable("Not an alias or ifunc?");
305 StringRef MangledName = getMangledName(GD);
306 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
307 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
308 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
311 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
312 } else if (GV->isDeclaration()) {
314 Diags.Report(Location, diag::err_alias_to_undefined)
315 << IsIFunc << IsIFunc;
316 } else if (IsIFunc) {
317 // Check resolver function type.
318 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
319 GV->getType()->getPointerElementType());
321 if (!FTy->getReturnType()->isPointerTy())
322 Diags.Report(Location, diag::err_ifunc_resolver_return);
323 if (FTy->getNumParams())
324 Diags.Report(Location, diag::err_ifunc_resolver_params);
327 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
328 llvm::GlobalValue *AliaseeGV;
329 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
330 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
332 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
334 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
335 StringRef AliasSection = SA->getName();
336 if (AliasSection != AliaseeGV->getSection())
337 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
338 << AliasSection << IsIFunc << IsIFunc;
341 // We have to handle alias to weak aliases in here. LLVM itself disallows
342 // this since the object semantics would not match the IL one. For
343 // compatibility with gcc we implement it by just pointing the alias
344 // to its aliasee's aliasee. We also warn, since the user is probably
345 // expecting the link to be weak.
346 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
347 if (GA->isInterposable()) {
348 Diags.Report(Location, diag::warn_alias_to_weak_alias)
349 << GV->getName() << GA->getName() << IsIFunc;
350 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
351 GA->getIndirectSymbol(), Alias->getType());
352 Alias->setIndirectSymbol(Aliasee);
359 for (const GlobalDecl &GD : Aliases) {
360 StringRef MangledName = getMangledName(GD);
361 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
362 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
363 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
364 Alias->eraseFromParent();
368 void CodeGenModule::clear() {
369 DeferredDeclsToEmit.clear();
371 OpenMPRuntime->clear();
374 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
375 StringRef MainFile) {
376 if (!hasDiagnostics())
378 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
379 if (MainFile.empty())
380 MainFile = "<stdin>";
381 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
384 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
387 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
391 void CodeGenModule::Release() {
393 EmitVTablesOpportunistically();
394 applyGlobalValReplacements();
397 emitMultiVersionFunctions();
398 EmitCXXGlobalInitFunc();
399 EmitCXXGlobalDtorFunc();
400 registerGlobalDtorsWithAtExit();
401 EmitCXXThreadLocalInitFunc();
403 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
404 AddGlobalCtor(ObjCInitFunction);
405 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
407 if (llvm::Function *CudaCtorFunction =
408 CUDARuntime->makeModuleCtorFunction())
409 AddGlobalCtor(CudaCtorFunction);
412 if (llvm::Function *OpenMPRegistrationFunction =
413 OpenMPRuntime->emitRegistrationFunction()) {
414 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
415 OpenMPRegistrationFunction : nullptr;
416 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
418 OpenMPRuntime->clear();
421 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
422 if (PGOStats.hasDiagnostics())
423 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
425 EmitCtorList(GlobalCtors, "llvm.global_ctors");
426 EmitCtorList(GlobalDtors, "llvm.global_dtors");
427 EmitGlobalAnnotations();
428 EmitStaticExternCAliases();
429 EmitDeferredUnusedCoverageMappings();
431 CoverageMapping->emit();
432 if (CodeGenOpts.SanitizeCfiCrossDso) {
433 CodeGenFunction(*this).EmitCfiCheckFail();
434 CodeGenFunction(*this).EmitCfiCheckStub();
436 emitAtAvailableLinkGuard();
441 if (CodeGenOpts.Autolink &&
442 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
443 EmitModuleLinkOptions();
446 // Record mregparm value now so it is visible through rest of codegen.
447 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
448 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
449 CodeGenOpts.NumRegisterParameters);
451 if (CodeGenOpts.DwarfVersion) {
452 // We actually want the latest version when there are conflicts.
453 // We can change from Warning to Latest if such mode is supported.
454 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
455 CodeGenOpts.DwarfVersion);
457 if (CodeGenOpts.EmitCodeView) {
458 // Indicate that we want CodeView in the metadata.
459 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
461 if (CodeGenOpts.ControlFlowGuard) {
462 // We want function ID tables for Control Flow Guard.
463 getModule().addModuleFlag(llvm::Module::Warning, "cfguard", 1);
465 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
466 // We don't support LTO with 2 with different StrictVTablePointers
467 // FIXME: we could support it by stripping all the information introduced
468 // by StrictVTablePointers.
470 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
472 llvm::Metadata *Ops[2] = {
473 llvm::MDString::get(VMContext, "StrictVTablePointers"),
474 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
475 llvm::Type::getInt32Ty(VMContext), 1))};
477 getModule().addModuleFlag(llvm::Module::Require,
478 "StrictVTablePointersRequirement",
479 llvm::MDNode::get(VMContext, Ops));
482 // We support a single version in the linked module. The LLVM
483 // parser will drop debug info with a different version number
484 // (and warn about it, too).
485 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
486 llvm::DEBUG_METADATA_VERSION);
488 // We need to record the widths of enums and wchar_t, so that we can generate
489 // the correct build attributes in the ARM backend. wchar_size is also used by
490 // TargetLibraryInfo.
491 uint64_t WCharWidth =
492 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
493 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
495 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
496 if ( Arch == llvm::Triple::arm
497 || Arch == llvm::Triple::armeb
498 || Arch == llvm::Triple::thumb
499 || Arch == llvm::Triple::thumbeb) {
500 // The minimum width of an enum in bytes
501 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
502 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
505 if (CodeGenOpts.SanitizeCfiCrossDso) {
506 // Indicate that we want cross-DSO control flow integrity checks.
507 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
510 if (CodeGenOpts.CFProtectionReturn &&
511 Target.checkCFProtectionReturnSupported(getDiags())) {
512 // Indicate that we want to instrument return control flow protection.
513 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-return",
517 if (CodeGenOpts.CFProtectionBranch &&
518 Target.checkCFProtectionBranchSupported(getDiags())) {
519 // Indicate that we want to instrument branch control flow protection.
520 getModule().addModuleFlag(llvm::Module::Override, "cf-protection-branch",
524 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
525 // Indicate whether __nvvm_reflect should be configured to flush denormal
526 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
528 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
529 CodeGenOpts.FlushDenorm ? 1 : 0);
532 // Emit OpenCL specific module metadata: OpenCL/SPIR version.
533 if (LangOpts.OpenCL) {
534 EmitOpenCLMetadata();
535 // Emit SPIR version.
536 if (getTriple().getArch() == llvm::Triple::spir ||
537 getTriple().getArch() == llvm::Triple::spir64) {
538 // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
539 // opencl.spir.version named metadata.
540 llvm::Metadata *SPIRVerElts[] = {
541 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
542 Int32Ty, LangOpts.OpenCLVersion / 100)),
543 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
544 Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
545 llvm::NamedMDNode *SPIRVerMD =
546 TheModule.getOrInsertNamedMetadata("opencl.spir.version");
547 llvm::LLVMContext &Ctx = TheModule.getContext();
548 SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
552 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
553 assert(PLevel < 3 && "Invalid PIC Level");
554 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
555 if (Context.getLangOpts().PIE)
556 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
559 if (CodeGenOpts.NoPLT)
560 getModule().setRtLibUseGOT();
562 SimplifyPersonality();
564 if (getCodeGenOpts().EmitDeclMetadata)
567 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
571 DebugInfo->finalize();
573 if (getCodeGenOpts().EmitVersionIdentMetadata)
574 EmitVersionIdentMetadata();
576 EmitTargetMetadata();
579 void CodeGenModule::EmitOpenCLMetadata() {
580 // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
581 // opencl.ocl.version named metadata node.
582 llvm::Metadata *OCLVerElts[] = {
583 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
584 Int32Ty, LangOpts.OpenCLVersion / 100)),
585 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
586 Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
587 llvm::NamedMDNode *OCLVerMD =
588 TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
589 llvm::LLVMContext &Ctx = TheModule.getContext();
590 OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
593 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
594 // Make sure that this type is translated.
595 Types.UpdateCompletedType(TD);
598 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
599 // Make sure that this type is translated.
600 Types.RefreshTypeCacheForClass(RD);
603 llvm::MDNode *CodeGenModule::getTBAATypeInfo(QualType QTy) {
606 return TBAA->getTypeInfo(QTy);
609 TBAAAccessInfo CodeGenModule::getTBAAAccessInfo(QualType AccessType) {
611 return TBAAAccessInfo();
612 return TBAA->getAccessInfo(AccessType);
616 CodeGenModule::getTBAAVTablePtrAccessInfo(llvm::Type *VTablePtrType) {
618 return TBAAAccessInfo();
619 return TBAA->getVTablePtrAccessInfo(VTablePtrType);
622 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
625 return TBAA->getTBAAStructInfo(QTy);
628 llvm::MDNode *CodeGenModule::getTBAABaseTypeInfo(QualType QTy) {
631 return TBAA->getBaseTypeInfo(QTy);
634 llvm::MDNode *CodeGenModule::getTBAAAccessTagInfo(TBAAAccessInfo Info) {
637 return TBAA->getAccessTagInfo(Info);
640 TBAAAccessInfo CodeGenModule::mergeTBAAInfoForCast(TBAAAccessInfo SourceInfo,
641 TBAAAccessInfo TargetInfo) {
643 return TBAAAccessInfo();
644 return TBAA->mergeTBAAInfoForCast(SourceInfo, TargetInfo);
648 CodeGenModule::mergeTBAAInfoForConditionalOperator(TBAAAccessInfo InfoA,
649 TBAAAccessInfo InfoB) {
651 return TBAAAccessInfo();
652 return TBAA->mergeTBAAInfoForConditionalOperator(InfoA, InfoB);
656 CodeGenModule::mergeTBAAInfoForMemoryTransfer(TBAAAccessInfo DestInfo,
657 TBAAAccessInfo SrcInfo) {
659 return TBAAAccessInfo();
660 return TBAA->mergeTBAAInfoForConditionalOperator(DestInfo, SrcInfo);
663 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
664 TBAAAccessInfo TBAAInfo) {
665 if (llvm::MDNode *Tag = getTBAAAccessTagInfo(TBAAInfo))
666 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, Tag);
669 void CodeGenModule::DecorateInstructionWithInvariantGroup(
670 llvm::Instruction *I, const CXXRecordDecl *RD) {
671 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
672 llvm::MDNode::get(getLLVMContext(), {}));
675 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
676 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
677 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
680 /// ErrorUnsupported - Print out an error that codegen doesn't support the
681 /// specified stmt yet.
682 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
683 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
684 "cannot compile this %0 yet");
685 std::string Msg = Type;
686 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
687 << Msg << S->getSourceRange();
690 /// ErrorUnsupported - Print out an error that codegen doesn't support the
691 /// specified decl yet.
692 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
693 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
694 "cannot compile this %0 yet");
695 std::string Msg = Type;
696 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
699 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
700 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
703 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
704 const NamedDecl *D) const {
705 if (GV->hasDLLImportStorageClass())
707 // Internal definitions always have default visibility.
708 if (GV->hasLocalLinkage()) {
709 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
714 // Set visibility for definitions.
715 LinkageInfo LV = D->getLinkageAndVisibility();
716 if (LV.isVisibilityExplicit() || !GV->isDeclarationForLinker())
717 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
720 static bool shouldAssumeDSOLocal(const CodeGenModule &CGM,
721 llvm::GlobalValue *GV) {
722 if (GV->hasLocalLinkage())
725 if (!GV->hasDefaultVisibility() && !GV->hasExternalWeakLinkage())
728 // DLLImport explicitly marks the GV as external.
729 if (GV->hasDLLImportStorageClass())
732 const llvm::Triple &TT = CGM.getTriple();
733 // Every other GV is local on COFF.
734 // Make an exception for windows OS in the triple: Some firmware builds use
735 // *-win32-macho triples. This (accidentally?) produced windows relocations
736 // without GOT tables in older clang versions; Keep this behaviour.
737 // FIXME: even thread local variables?
738 if (TT.isOSBinFormatCOFF() || (TT.isOSWindows() && TT.isOSBinFormatMachO()))
741 // Only handle COFF and ELF for now.
742 if (!TT.isOSBinFormatELF())
745 // If this is not an executable, don't assume anything is local.
746 const auto &CGOpts = CGM.getCodeGenOpts();
747 llvm::Reloc::Model RM = CGOpts.RelocationModel;
748 const auto &LOpts = CGM.getLangOpts();
749 if (RM != llvm::Reloc::Static && !LOpts.PIE)
752 // A definition cannot be preempted from an executable.
753 if (!GV->isDeclarationForLinker())
756 // Most PIC code sequences that assume that a symbol is local cannot produce a
757 // 0 if it turns out the symbol is undefined. While this is ABI and relocation
758 // depended, it seems worth it to handle it here.
759 if (RM == llvm::Reloc::PIC_ && GV->hasExternalWeakLinkage())
762 // PPC has no copy relocations and cannot use a plt entry as a symbol address.
763 llvm::Triple::ArchType Arch = TT.getArch();
764 if (Arch == llvm::Triple::ppc || Arch == llvm::Triple::ppc64 ||
765 Arch == llvm::Triple::ppc64le)
768 // If we can use copy relocations we can assume it is local.
769 if (auto *Var = dyn_cast<llvm::GlobalVariable>(GV))
770 if (!Var->isThreadLocal() &&
771 (RM == llvm::Reloc::Static || CGOpts.PIECopyRelocations))
774 // If we can use a plt entry as the symbol address we can assume it
776 // FIXME: This should work for PIE, but the gold linker doesn't support it.
777 if (isa<llvm::Function>(GV) && !CGOpts.NoPLT && RM == llvm::Reloc::Static)
780 // Otherwise don't assue it is local.
784 void CodeGenModule::setDSOLocal(llvm::GlobalValue *GV) const {
785 GV->setDSOLocal(shouldAssumeDSOLocal(*this, GV));
788 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
789 GlobalDecl GD) const {
790 const auto *D = dyn_cast<NamedDecl>(GD.getDecl());
791 // C++ destructors have a few C++ ABI specific special cases.
792 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(D)) {
793 getCXXABI().setCXXDestructorDLLStorage(GV, Dtor, GD.getDtorType());
796 setDLLImportDLLExport(GV, D);
799 void CodeGenModule::setDLLImportDLLExport(llvm::GlobalValue *GV,
800 const NamedDecl *D) const {
801 if (D && D->isExternallyVisible()) {
802 if (D->hasAttr<DLLImportAttr>())
803 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
804 else if (D->hasAttr<DLLExportAttr>() && !GV->isDeclarationForLinker())
805 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
809 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
810 GlobalDecl GD) const {
811 setDLLImportDLLExport(GV, GD);
812 setGlobalVisibilityAndLocal(GV, dyn_cast<NamedDecl>(GD.getDecl()));
815 void CodeGenModule::setGVProperties(llvm::GlobalValue *GV,
816 const NamedDecl *D) const {
817 setDLLImportDLLExport(GV, D);
818 setGlobalVisibilityAndLocal(GV, D);
821 void CodeGenModule::setGlobalVisibilityAndLocal(llvm::GlobalValue *GV,
822 const NamedDecl *D) const {
823 setGlobalVisibility(GV, D);
827 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
828 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
829 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
830 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
831 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
832 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
835 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
836 CodeGenOptions::TLSModel M) {
838 case CodeGenOptions::GeneralDynamicTLSModel:
839 return llvm::GlobalVariable::GeneralDynamicTLSModel;
840 case CodeGenOptions::LocalDynamicTLSModel:
841 return llvm::GlobalVariable::LocalDynamicTLSModel;
842 case CodeGenOptions::InitialExecTLSModel:
843 return llvm::GlobalVariable::InitialExecTLSModel;
844 case CodeGenOptions::LocalExecTLSModel:
845 return llvm::GlobalVariable::LocalExecTLSModel;
847 llvm_unreachable("Invalid TLS model!");
850 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
851 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
853 llvm::GlobalValue::ThreadLocalMode TLM;
854 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
856 // Override the TLS model if it is explicitly specified.
857 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
858 TLM = GetLLVMTLSModel(Attr->getModel());
861 GV->setThreadLocalMode(TLM);
864 static std::string getCPUSpecificMangling(const CodeGenModule &CGM,
866 const TargetInfo &Target = CGM.getTarget();
867 return (Twine('.') + Twine(Target.CPUSpecificManglingCharacter(Name))).str();
870 static void AppendCPUSpecificCPUDispatchMangling(const CodeGenModule &CGM,
871 const CPUSpecificAttr *Attr,
873 // cpu_specific gets the current name, dispatch gets the resolver.
875 Out << getCPUSpecificMangling(CGM, Attr->getCurCPUName()->getName());
880 static void AppendTargetMangling(const CodeGenModule &CGM,
881 const TargetAttr *Attr, raw_ostream &Out) {
882 if (Attr->isDefaultVersion())
886 const TargetInfo &Target = CGM.getTarget();
887 TargetAttr::ParsedTargetAttr Info =
888 Attr->parse([&Target](StringRef LHS, StringRef RHS) {
889 // Multiversioning doesn't allow "no-${feature}", so we can
890 // only have "+" prefixes here.
891 assert(LHS.startswith("+") && RHS.startswith("+") &&
892 "Features should always have a prefix.");
893 return Target.multiVersionSortPriority(LHS.substr(1)) >
894 Target.multiVersionSortPriority(RHS.substr(1));
899 if (!Info.Architecture.empty()) {
901 Out << "arch_" << Info.Architecture;
904 for (StringRef Feat : Info.Features) {
908 Out << Feat.substr(1);
912 static std::string getMangledNameImpl(const CodeGenModule &CGM, GlobalDecl GD,
914 bool OmitMultiVersionMangling = false) {
915 SmallString<256> Buffer;
916 llvm::raw_svector_ostream Out(Buffer);
917 MangleContext &MC = CGM.getCXXABI().getMangleContext();
918 if (MC.shouldMangleDeclName(ND)) {
919 llvm::raw_svector_ostream Out(Buffer);
920 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
921 MC.mangleCXXCtor(D, GD.getCtorType(), Out);
922 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
923 MC.mangleCXXDtor(D, GD.getDtorType(), Out);
925 MC.mangleName(ND, Out);
927 IdentifierInfo *II = ND->getIdentifier();
928 assert(II && "Attempt to mangle unnamed decl.");
929 const auto *FD = dyn_cast<FunctionDecl>(ND);
932 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
933 llvm::raw_svector_ostream Out(Buffer);
934 Out << "__regcall3__" << II->getName();
936 Out << II->getName();
940 if (const auto *FD = dyn_cast<FunctionDecl>(ND))
941 if (FD->isMultiVersion() && !OmitMultiVersionMangling) {
942 if (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())
943 AppendCPUSpecificCPUDispatchMangling(
944 CGM, FD->getAttr<CPUSpecificAttr>(), Out);
946 AppendTargetMangling(CGM, FD->getAttr<TargetAttr>(), Out);
952 void CodeGenModule::UpdateMultiVersionNames(GlobalDecl GD,
953 const FunctionDecl *FD) {
954 if (!FD->isMultiVersion())
957 // Get the name of what this would be without the 'target' attribute. This
958 // allows us to lookup the version that was emitted when this wasn't a
959 // multiversion function.
960 std::string NonTargetName =
961 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
963 if (lookupRepresentativeDecl(NonTargetName, OtherGD)) {
964 assert(OtherGD.getCanonicalDecl()
967 ->isMultiVersion() &&
968 "Other GD should now be a multiversioned function");
969 // OtherFD is the version of this function that was mangled BEFORE
970 // becoming a MultiVersion function. It potentially needs to be updated.
971 const FunctionDecl *OtherFD =
972 OtherGD.getCanonicalDecl().getDecl()->getAsFunction();
973 std::string OtherName = getMangledNameImpl(*this, OtherGD, OtherFD);
974 // This is so that if the initial version was already the 'default'
975 // version, we don't try to update it.
976 if (OtherName != NonTargetName) {
977 // Remove instead of erase, since others may have stored the StringRef
979 const auto ExistingRecord = Manglings.find(NonTargetName);
980 if (ExistingRecord != std::end(Manglings))
981 Manglings.remove(&(*ExistingRecord));
982 auto Result = Manglings.insert(std::make_pair(OtherName, OtherGD));
983 MangledDeclNames[OtherGD.getCanonicalDecl()] = Result.first->first();
984 if (llvm::GlobalValue *Entry = GetGlobalValue(NonTargetName))
985 Entry->setName(OtherName);
990 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
991 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
993 // Some ABIs don't have constructor variants. Make sure that base and
994 // complete constructors get mangled the same.
995 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
996 if (!getTarget().getCXXABI().hasConstructorVariants()) {
997 CXXCtorType OrigCtorType = GD.getCtorType();
998 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
999 if (OrigCtorType == Ctor_Base)
1000 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
1004 const auto *FD = dyn_cast<FunctionDecl>(GD.getDecl());
1005 // Since CPUSpecific can require multiple emits per decl, store the manglings
1008 (FD->isCPUDispatchMultiVersion() || FD->isCPUSpecificMultiVersion())) {
1009 const auto *SD = FD->getAttr<CPUSpecificAttr>();
1011 std::pair<GlobalDecl, unsigned> SpecCanonicalGD{
1013 SD ? SD->ActiveArgIndex : std::numeric_limits<unsigned>::max()};
1015 auto FoundName = CPUSpecificMangledDeclNames.find(SpecCanonicalGD);
1016 if (FoundName != CPUSpecificMangledDeclNames.end())
1017 return FoundName->second;
1019 auto Result = CPUSpecificManglings.insert(
1020 std::make_pair(getMangledNameImpl(*this, GD, FD), SpecCanonicalGD));
1021 return CPUSpecificMangledDeclNames[SpecCanonicalGD] = Result.first->first();
1024 auto FoundName = MangledDeclNames.find(CanonicalGD);
1025 if (FoundName != MangledDeclNames.end())
1026 return FoundName->second;
1028 // Keep the first result in the case of a mangling collision.
1029 const auto *ND = cast<NamedDecl>(GD.getDecl());
1031 Manglings.insert(std::make_pair(getMangledNameImpl(*this, GD, ND), GD));
1032 return MangledDeclNames[CanonicalGD] = Result.first->first();
1035 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
1036 const BlockDecl *BD) {
1037 MangleContext &MangleCtx = getCXXABI().getMangleContext();
1038 const Decl *D = GD.getDecl();
1040 SmallString<256> Buffer;
1041 llvm::raw_svector_ostream Out(Buffer);
1043 MangleCtx.mangleGlobalBlock(BD,
1044 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
1045 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
1046 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
1047 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
1048 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
1050 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
1052 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
1053 return Result.first->first();
1056 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
1057 return getModule().getNamedValue(Name);
1060 /// AddGlobalCtor - Add a function to the list that will be called before
1062 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
1063 llvm::Constant *AssociatedData) {
1064 // FIXME: Type coercion of void()* types.
1065 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
1068 /// AddGlobalDtor - Add a function to the list that will be called
1069 /// when the module is unloaded.
1070 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
1071 if (CodeGenOpts.RegisterGlobalDtorsWithAtExit) {
1072 DtorsUsingAtExit[Priority].push_back(Dtor);
1076 // FIXME: Type coercion of void()* types.
1077 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
1080 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
1081 if (Fns.empty()) return;
1083 // Ctor function type is void()*.
1084 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
1085 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
1087 // Get the type of a ctor entry, { i32, void ()*, i8* }.
1088 llvm::StructType *CtorStructTy = llvm::StructType::get(
1089 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
1091 // Construct the constructor and destructor arrays.
1092 ConstantInitBuilder builder(*this);
1093 auto ctors = builder.beginArray(CtorStructTy);
1094 for (const auto &I : Fns) {
1095 auto ctor = ctors.beginStruct(CtorStructTy);
1096 ctor.addInt(Int32Ty, I.Priority);
1097 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
1098 if (I.AssociatedData)
1099 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
1101 ctor.addNullPointer(VoidPtrTy);
1102 ctor.finishAndAddTo(ctors);
1106 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
1108 llvm::GlobalValue::AppendingLinkage);
1110 // The LTO linker doesn't seem to like it when we set an alignment
1111 // on appending variables. Take it off as a workaround.
1112 list->setAlignment(0);
1117 llvm::GlobalValue::LinkageTypes
1118 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
1119 const auto *D = cast<FunctionDecl>(GD.getDecl());
1121 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
1123 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(D))
1124 return getCXXABI().getCXXDestructorLinkage(Linkage, Dtor, GD.getDtorType());
1126 if (isa<CXXConstructorDecl>(D) &&
1127 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
1128 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1129 // Our approach to inheriting constructors is fundamentally different from
1130 // that used by the MS ABI, so keep our inheriting constructor thunks
1131 // internal rather than trying to pick an unambiguous mangling for them.
1132 return llvm::GlobalValue::InternalLinkage;
1135 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
1138 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
1139 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
1140 if (!MDS) return nullptr;
1142 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
1145 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
1146 const CGFunctionInfo &Info,
1147 llvm::Function *F) {
1148 unsigned CallingConv;
1149 llvm::AttributeList PAL;
1150 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
1151 F->setAttributes(PAL);
1152 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
1155 /// Determines whether the language options require us to model
1156 /// unwind exceptions. We treat -fexceptions as mandating this
1157 /// except under the fragile ObjC ABI with only ObjC exceptions
1158 /// enabled. This means, for example, that C with -fexceptions
1160 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
1161 // If exceptions are completely disabled, obviously this is false.
1162 if (!LangOpts.Exceptions) return false;
1164 // If C++ exceptions are enabled, this is true.
1165 if (LangOpts.CXXExceptions) return true;
1167 // If ObjC exceptions are enabled, this depends on the ABI.
1168 if (LangOpts.ObjCExceptions) {
1169 return LangOpts.ObjCRuntime.hasUnwindExceptions();
1175 static bool requiresMemberFunctionPointerTypeMetadata(CodeGenModule &CGM,
1176 const CXXMethodDecl *MD) {
1177 // Check that the type metadata can ever actually be used by a call.
1178 if (!CGM.getCodeGenOpts().LTOUnit ||
1179 !CGM.HasHiddenLTOVisibility(MD->getParent()))
1182 // Only functions whose address can be taken with a member function pointer
1183 // need this sort of type metadata.
1184 return !MD->isStatic() && !MD->isVirtual() && !isa<CXXConstructorDecl>(MD) &&
1185 !isa<CXXDestructorDecl>(MD);
1188 std::vector<const CXXRecordDecl *>
1189 CodeGenModule::getMostBaseClasses(const CXXRecordDecl *RD) {
1190 llvm::SetVector<const CXXRecordDecl *> MostBases;
1192 std::function<void (const CXXRecordDecl *)> CollectMostBases;
1193 CollectMostBases = [&](const CXXRecordDecl *RD) {
1194 if (RD->getNumBases() == 0)
1195 MostBases.insert(RD);
1196 for (const CXXBaseSpecifier &B : RD->bases())
1197 CollectMostBases(B.getType()->getAsCXXRecordDecl());
1199 CollectMostBases(RD);
1200 return MostBases.takeVector();
1203 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
1204 llvm::Function *F) {
1205 llvm::AttrBuilder B;
1207 if (CodeGenOpts.UnwindTables)
1208 B.addAttribute(llvm::Attribute::UWTable);
1210 if (!hasUnwindExceptions(LangOpts))
1211 B.addAttribute(llvm::Attribute::NoUnwind);
1213 if (!D || !D->hasAttr<NoStackProtectorAttr>()) {
1214 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
1215 B.addAttribute(llvm::Attribute::StackProtect);
1216 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
1217 B.addAttribute(llvm::Attribute::StackProtectStrong);
1218 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
1219 B.addAttribute(llvm::Attribute::StackProtectReq);
1223 // If we don't have a declaration to control inlining, the function isn't
1224 // explicitly marked as alwaysinline for semantic reasons, and inlining is
1225 // disabled, mark the function as noinline.
1226 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1227 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
1228 B.addAttribute(llvm::Attribute::NoInline);
1230 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1234 // Track whether we need to add the optnone LLVM attribute,
1235 // starting with the default for this optimization level.
1236 bool ShouldAddOptNone =
1237 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
1238 // We can't add optnone in the following cases, it won't pass the verifier.
1239 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
1240 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
1241 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
1243 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
1244 B.addAttribute(llvm::Attribute::OptimizeNone);
1246 // OptimizeNone implies noinline; we should not be inlining such functions.
1247 B.addAttribute(llvm::Attribute::NoInline);
1248 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
1249 "OptimizeNone and AlwaysInline on same function!");
1251 // We still need to handle naked functions even though optnone subsumes
1252 // much of their semantics.
1253 if (D->hasAttr<NakedAttr>())
1254 B.addAttribute(llvm::Attribute::Naked);
1256 // OptimizeNone wins over OptimizeForSize and MinSize.
1257 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
1258 F->removeFnAttr(llvm::Attribute::MinSize);
1259 } else if (D->hasAttr<NakedAttr>()) {
1260 // Naked implies noinline: we should not be inlining such functions.
1261 B.addAttribute(llvm::Attribute::Naked);
1262 B.addAttribute(llvm::Attribute::NoInline);
1263 } else if (D->hasAttr<NoDuplicateAttr>()) {
1264 B.addAttribute(llvm::Attribute::NoDuplicate);
1265 } else if (D->hasAttr<NoInlineAttr>()) {
1266 B.addAttribute(llvm::Attribute::NoInline);
1267 } else if (D->hasAttr<AlwaysInlineAttr>() &&
1268 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
1269 // (noinline wins over always_inline, and we can't specify both in IR)
1270 B.addAttribute(llvm::Attribute::AlwaysInline);
1271 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
1272 // If we're not inlining, then force everything that isn't always_inline to
1273 // carry an explicit noinline attribute.
1274 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
1275 B.addAttribute(llvm::Attribute::NoInline);
1277 // Otherwise, propagate the inline hint attribute and potentially use its
1278 // absence to mark things as noinline.
1279 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
1280 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
1281 return Redecl->isInlineSpecified();
1283 B.addAttribute(llvm::Attribute::InlineHint);
1284 } else if (CodeGenOpts.getInlining() ==
1285 CodeGenOptions::OnlyHintInlining &&
1287 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
1288 B.addAttribute(llvm::Attribute::NoInline);
1293 // Add other optimization related attributes if we are optimizing this
1295 if (!D->hasAttr<OptimizeNoneAttr>()) {
1296 if (D->hasAttr<ColdAttr>()) {
1297 if (!ShouldAddOptNone)
1298 B.addAttribute(llvm::Attribute::OptimizeForSize);
1299 B.addAttribute(llvm::Attribute::Cold);
1302 if (D->hasAttr<MinSizeAttr>())
1303 B.addAttribute(llvm::Attribute::MinSize);
1306 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1308 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1310 F->setAlignment(alignment);
1312 if (!D->hasAttr<AlignedAttr>())
1313 if (LangOpts.FunctionAlignment)
1314 F->setAlignment(1 << LangOpts.FunctionAlignment);
1316 // Some C++ ABIs require 2-byte alignment for member functions, in order to
1317 // reserve a bit for differentiating between virtual and non-virtual member
1318 // functions. If the current target's C++ ABI requires this and this is a
1319 // member function, set its alignment accordingly.
1320 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1321 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1325 // In the cross-dso CFI mode, we want !type attributes on definitions only.
1326 if (CodeGenOpts.SanitizeCfiCrossDso)
1327 if (auto *FD = dyn_cast<FunctionDecl>(D))
1328 CreateFunctionTypeMetadataForIcall(FD, F);
1330 // Emit type metadata on member functions for member function pointer checks.
1331 // These are only ever necessary on definitions; we're guaranteed that the
1332 // definition will be present in the LTO unit as a result of LTO visibility.
1333 auto *MD = dyn_cast<CXXMethodDecl>(D);
1334 if (MD && requiresMemberFunctionPointerTypeMetadata(*this, MD)) {
1335 for (const CXXRecordDecl *Base : getMostBaseClasses(MD->getParent())) {
1336 llvm::Metadata *Id =
1337 CreateMetadataIdentifierForType(Context.getMemberPointerType(
1338 MD->getType(), Context.getRecordType(Base).getTypePtr()));
1339 F->addTypeMetadata(0, Id);
1344 void CodeGenModule::SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV) {
1345 const Decl *D = GD.getDecl();
1346 if (dyn_cast_or_null<NamedDecl>(D))
1347 setGVProperties(GV, GD);
1349 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1351 if (D && D->hasAttr<UsedAttr>())
1355 bool CodeGenModule::GetCPUAndFeaturesAttributes(const Decl *D,
1356 llvm::AttrBuilder &Attrs) {
1357 // Add target-cpu and target-features attributes to functions. If
1358 // we have a decl for the function and it has a target attribute then
1359 // parse that and add it to the feature set.
1360 StringRef TargetCPU = getTarget().getTargetOpts().CPU;
1361 std::vector<std::string> Features;
1362 const auto *FD = dyn_cast_or_null<FunctionDecl>(D);
1363 FD = FD ? FD->getMostRecentDecl() : FD;
1364 const auto *TD = FD ? FD->getAttr<TargetAttr>() : nullptr;
1365 const auto *SD = FD ? FD->getAttr<CPUSpecificAttr>() : nullptr;
1366 bool AddedAttr = false;
1368 llvm::StringMap<bool> FeatureMap;
1369 getFunctionFeatureMap(FeatureMap, FD);
1371 // Produce the canonical string for this set of features.
1372 for (const llvm::StringMap<bool>::value_type &Entry : FeatureMap)
1373 Features.push_back((Entry.getValue() ? "+" : "-") + Entry.getKey().str());
1375 // Now add the target-cpu and target-features to the function.
1376 // While we populated the feature map above, we still need to
1377 // get and parse the target attribute so we can get the cpu for
1380 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
1381 if (ParsedAttr.Architecture != "" &&
1382 getTarget().isValidCPUName(ParsedAttr.Architecture))
1383 TargetCPU = ParsedAttr.Architecture;
1386 // Otherwise just add the existing target cpu and target features to the
1388 Features = getTarget().getTargetOpts().Features;
1391 if (TargetCPU != "") {
1392 Attrs.addAttribute("target-cpu", TargetCPU);
1395 if (!Features.empty()) {
1396 llvm::sort(Features.begin(), Features.end());
1397 Attrs.addAttribute("target-features", llvm::join(Features, ","));
1404 void CodeGenModule::setNonAliasAttributes(GlobalDecl GD,
1405 llvm::GlobalObject *GO) {
1406 const Decl *D = GD.getDecl();
1407 SetCommonAttributes(GD, GO);
1410 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1411 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1412 GV->addAttribute("bss-section", SA->getName());
1413 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1414 GV->addAttribute("data-section", SA->getName());
1415 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1416 GV->addAttribute("rodata-section", SA->getName());
1419 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1420 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1421 if (!D->getAttr<SectionAttr>())
1422 F->addFnAttr("implicit-section-name", SA->getName());
1424 llvm::AttrBuilder Attrs;
1425 if (GetCPUAndFeaturesAttributes(D, Attrs)) {
1426 // We know that GetCPUAndFeaturesAttributes will always have the
1427 // newest set, since it has the newest possible FunctionDecl, so the
1428 // new ones should replace the old.
1429 F->removeFnAttr("target-cpu");
1430 F->removeFnAttr("target-features");
1431 F->addAttributes(llvm::AttributeList::FunctionIndex, Attrs);
1435 if (const auto *CSA = D->getAttr<CodeSegAttr>())
1436 GO->setSection(CSA->getName());
1437 else if (const auto *SA = D->getAttr<SectionAttr>())
1438 GO->setSection(SA->getName());
1441 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1444 void CodeGenModule::SetInternalFunctionAttributes(GlobalDecl GD,
1446 const CGFunctionInfo &FI) {
1447 const Decl *D = GD.getDecl();
1448 SetLLVMFunctionAttributes(D, FI, F);
1449 SetLLVMFunctionAttributesForDefinition(D, F);
1451 F->setLinkage(llvm::Function::InternalLinkage);
1453 setNonAliasAttributes(GD, F);
1456 static void setLinkageForGV(llvm::GlobalValue *GV, const NamedDecl *ND) {
1457 // Set linkage and visibility in case we never see a definition.
1458 LinkageInfo LV = ND->getLinkageAndVisibility();
1459 // Don't set internal linkage on declarations.
1460 // "extern_weak" is overloaded in LLVM; we probably should have
1461 // separate linkage types for this.
1462 if (isExternallyVisible(LV.getLinkage()) &&
1463 (ND->hasAttr<WeakAttr>() || ND->isWeakImported()))
1464 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1467 void CodeGenModule::CreateFunctionTypeMetadataForIcall(const FunctionDecl *FD,
1468 llvm::Function *F) {
1469 // Only if we are checking indirect calls.
1470 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1473 // Non-static class methods are handled via vtable or member function pointer
1474 // checks elsewhere.
1475 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1478 // Additionally, if building with cross-DSO support...
1479 if (CodeGenOpts.SanitizeCfiCrossDso) {
1480 // Skip available_externally functions. They won't be codegen'ed in the
1481 // current module anyway.
1482 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1486 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1487 F->addTypeMetadata(0, MD);
1488 F->addTypeMetadata(0, CreateMetadataIdentifierGeneralized(FD->getType()));
1490 // Emit a hash-based bit set entry for cross-DSO calls.
1491 if (CodeGenOpts.SanitizeCfiCrossDso)
1492 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1493 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1496 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1497 bool IsIncompleteFunction,
1500 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1501 // If this is an intrinsic function, set the function's attributes
1502 // to the intrinsic's attributes.
1503 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1507 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1509 if (!IsIncompleteFunction) {
1510 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1511 // Setup target-specific attributes.
1512 if (F->isDeclaration())
1513 getTargetCodeGenInfo().setTargetAttributes(FD, F, *this);
1516 // Add the Returned attribute for "this", except for iOS 5 and earlier
1517 // where substantial code, including the libstdc++ dylib, was compiled with
1518 // GCC and does not actually return "this".
1519 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1520 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1521 assert(!F->arg_empty() &&
1522 F->arg_begin()->getType()
1523 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1524 "unexpected this return");
1525 F->addAttribute(1, llvm::Attribute::Returned);
1528 // Only a few attributes are set on declarations; these may later be
1529 // overridden by a definition.
1531 setLinkageForGV(F, FD);
1532 setGVProperties(F, FD);
1534 if (const auto *CSA = FD->getAttr<CodeSegAttr>())
1535 F->setSection(CSA->getName());
1536 else if (const auto *SA = FD->getAttr<SectionAttr>())
1537 F->setSection(SA->getName());
1539 if (FD->isReplaceableGlobalAllocationFunction()) {
1540 // A replaceable global allocation function does not act like a builtin by
1541 // default, only if it is invoked by a new-expression or delete-expression.
1542 F->addAttribute(llvm::AttributeList::FunctionIndex,
1543 llvm::Attribute::NoBuiltin);
1545 // A sane operator new returns a non-aliasing pointer.
1546 // FIXME: Also add NonNull attribute to the return value
1547 // for the non-nothrow forms?
1548 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1549 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1550 (Kind == OO_New || Kind == OO_Array_New))
1551 F->addAttribute(llvm::AttributeList::ReturnIndex,
1552 llvm::Attribute::NoAlias);
1555 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1556 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1557 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1558 if (MD->isVirtual())
1559 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1561 // Don't emit entries for function declarations in the cross-DSO mode. This
1562 // is handled with better precision by the receiving DSO.
1563 if (!CodeGenOpts.SanitizeCfiCrossDso)
1564 CreateFunctionTypeMetadataForIcall(FD, F);
1566 if (getLangOpts().OpenMP && FD->hasAttr<OMPDeclareSimdDeclAttr>())
1567 getOpenMPRuntime().emitDeclareSimdFunction(FD, F);
1570 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1571 assert(!GV->isDeclaration() &&
1572 "Only globals with definition can force usage.");
1573 LLVMUsed.emplace_back(GV);
1576 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1577 assert(!GV->isDeclaration() &&
1578 "Only globals with definition can force usage.");
1579 LLVMCompilerUsed.emplace_back(GV);
1582 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1583 std::vector<llvm::WeakTrackingVH> &List) {
1584 // Don't create llvm.used if there is no need.
1588 // Convert List to what ConstantArray needs.
1589 SmallVector<llvm::Constant*, 8> UsedArray;
1590 UsedArray.resize(List.size());
1591 for (unsigned i = 0, e = List.size(); i != e; ++i) {
1593 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1594 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1597 if (UsedArray.empty())
1599 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1601 auto *GV = new llvm::GlobalVariable(
1602 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1603 llvm::ConstantArray::get(ATy, UsedArray), Name);
1605 GV->setSection("llvm.metadata");
1608 void CodeGenModule::emitLLVMUsed() {
1609 emitUsed(*this, "llvm.used", LLVMUsed);
1610 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1613 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1614 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1615 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1618 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1619 llvm::SmallString<32> Opt;
1620 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1621 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1622 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1625 void CodeGenModule::AddELFLibDirective(StringRef Lib) {
1626 auto &C = getLLVMContext();
1627 LinkerOptionsMetadata.push_back(llvm::MDNode::get(
1628 C, {llvm::MDString::get(C, "lib"), llvm::MDString::get(C, Lib)}));
1631 void CodeGenModule::AddDependentLib(StringRef Lib) {
1632 llvm::SmallString<24> Opt;
1633 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1634 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1635 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1638 /// Add link options implied by the given module, including modules
1639 /// it depends on, using a postorder walk.
1640 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1641 SmallVectorImpl<llvm::MDNode *> &Metadata,
1642 llvm::SmallPtrSet<Module *, 16> &Visited) {
1643 // Import this module's parent.
1644 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1645 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1648 // Import this module's dependencies.
1649 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1650 if (Visited.insert(Mod->Imports[I - 1]).second)
1651 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1654 // Add linker options to link against the libraries/frameworks
1655 // described by this module.
1656 llvm::LLVMContext &Context = CGM.getLLVMContext();
1658 // For modules that use export_as for linking, use that module
1660 if (Mod->UseExportAsModuleLinkName)
1663 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1664 // Link against a framework. Frameworks are currently Darwin only, so we
1665 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1666 if (Mod->LinkLibraries[I-1].IsFramework) {
1667 llvm::Metadata *Args[2] = {
1668 llvm::MDString::get(Context, "-framework"),
1669 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1671 Metadata.push_back(llvm::MDNode::get(Context, Args));
1675 // Link against a library.
1676 llvm::SmallString<24> Opt;
1677 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1678 Mod->LinkLibraries[I-1].Library, Opt);
1679 auto *OptString = llvm::MDString::get(Context, Opt);
1680 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1684 void CodeGenModule::EmitModuleLinkOptions() {
1685 // Collect the set of all of the modules we want to visit to emit link
1686 // options, which is essentially the imported modules and all of their
1687 // non-explicit child modules.
1688 llvm::SetVector<clang::Module *> LinkModules;
1689 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1690 SmallVector<clang::Module *, 16> Stack;
1692 // Seed the stack with imported modules.
1693 for (Module *M : ImportedModules) {
1694 // Do not add any link flags when an implementation TU of a module imports
1695 // a header of that same module.
1696 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1697 !getLangOpts().isCompilingModule())
1699 if (Visited.insert(M).second)
1703 // Find all of the modules to import, making a little effort to prune
1704 // non-leaf modules.
1705 while (!Stack.empty()) {
1706 clang::Module *Mod = Stack.pop_back_val();
1708 bool AnyChildren = false;
1710 // Visit the submodules of this module.
1711 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1712 SubEnd = Mod->submodule_end();
1713 Sub != SubEnd; ++Sub) {
1714 // Skip explicit children; they need to be explicitly imported to be
1716 if ((*Sub)->IsExplicit)
1719 if (Visited.insert(*Sub).second) {
1720 Stack.push_back(*Sub);
1725 // We didn't find any children, so add this module to the list of
1726 // modules to link against.
1728 LinkModules.insert(Mod);
1732 // Add link options for all of the imported modules in reverse topological
1733 // order. We don't do anything to try to order import link flags with respect
1734 // to linker options inserted by things like #pragma comment().
1735 SmallVector<llvm::MDNode *, 16> MetadataArgs;
1737 for (Module *M : LinkModules)
1738 if (Visited.insert(M).second)
1739 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1740 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1741 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1743 // Add the linker options metadata flag.
1744 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1745 for (auto *MD : LinkerOptionsMetadata)
1746 NMD->addOperand(MD);
1749 void CodeGenModule::EmitDeferred() {
1750 // Emit code for any potentially referenced deferred decls. Since a
1751 // previously unused static decl may become used during the generation of code
1752 // for a static function, iterate until no changes are made.
1754 if (!DeferredVTables.empty()) {
1755 EmitDeferredVTables();
1757 // Emitting a vtable doesn't directly cause more vtables to
1758 // become deferred, although it can cause functions to be
1759 // emitted that then need those vtables.
1760 assert(DeferredVTables.empty());
1763 // Stop if we're out of both deferred vtables and deferred declarations.
1764 if (DeferredDeclsToEmit.empty())
1767 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1768 // work, it will not interfere with this.
1769 std::vector<GlobalDecl> CurDeclsToEmit;
1770 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1772 for (GlobalDecl &D : CurDeclsToEmit) {
1773 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1774 // to get GlobalValue with exactly the type we need, not something that
1775 // might had been created for another decl with the same mangled name but
1777 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1778 GetAddrOfGlobal(D, ForDefinition));
1780 // In case of different address spaces, we may still get a cast, even with
1781 // IsForDefinition equal to true. Query mangled names table to get
1784 GV = GetGlobalValue(getMangledName(D));
1786 // Make sure GetGlobalValue returned non-null.
1789 // Check to see if we've already emitted this. This is necessary
1790 // for a couple of reasons: first, decls can end up in the
1791 // deferred-decls queue multiple times, and second, decls can end
1792 // up with definitions in unusual ways (e.g. by an extern inline
1793 // function acquiring a strong function redefinition). Just
1794 // ignore these cases.
1795 if (!GV->isDeclaration())
1798 // Otherwise, emit the definition and move on to the next one.
1799 EmitGlobalDefinition(D, GV);
1801 // If we found out that we need to emit more decls, do that recursively.
1802 // This has the advantage that the decls are emitted in a DFS and related
1803 // ones are close together, which is convenient for testing.
1804 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1806 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1811 void CodeGenModule::EmitVTablesOpportunistically() {
1812 // Try to emit external vtables as available_externally if they have emitted
1813 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1814 // is not allowed to create new references to things that need to be emitted
1815 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1817 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1818 && "Only emit opportunistic vtables with optimizations");
1820 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1821 assert(getVTables().isVTableExternal(RD) &&
1822 "This queue should only contain external vtables");
1823 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1824 VTables.GenerateClassData(RD);
1826 OpportunisticVTables.clear();
1829 void CodeGenModule::EmitGlobalAnnotations() {
1830 if (Annotations.empty())
1833 // Create a new global variable for the ConstantStruct in the Module.
1834 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1835 Annotations[0]->getType(), Annotations.size()), Annotations);
1836 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1837 llvm::GlobalValue::AppendingLinkage,
1838 Array, "llvm.global.annotations");
1839 gv->setSection(AnnotationSection);
1842 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1843 llvm::Constant *&AStr = AnnotationStrings[Str];
1847 // Not found yet, create a new global.
1848 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1850 new llvm::GlobalVariable(getModule(), s->getType(), true,
1851 llvm::GlobalValue::PrivateLinkage, s, ".str");
1852 gv->setSection(AnnotationSection);
1853 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1858 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1859 SourceManager &SM = getContext().getSourceManager();
1860 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1862 return EmitAnnotationString(PLoc.getFilename());
1863 return EmitAnnotationString(SM.getBufferName(Loc));
1866 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1867 SourceManager &SM = getContext().getSourceManager();
1868 PresumedLoc PLoc = SM.getPresumedLoc(L);
1869 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1870 SM.getExpansionLineNumber(L);
1871 return llvm::ConstantInt::get(Int32Ty, LineNo);
1874 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1875 const AnnotateAttr *AA,
1877 // Get the globals for file name, annotation, and the line number.
1878 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1879 *UnitGV = EmitAnnotationUnit(L),
1880 *LineNoCst = EmitAnnotationLineNo(L);
1882 // Create the ConstantStruct for the global annotation.
1883 llvm::Constant *Fields[4] = {
1884 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1885 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1886 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1889 return llvm::ConstantStruct::getAnon(Fields);
1892 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1893 llvm::GlobalValue *GV) {
1894 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1895 // Get the struct elements for these annotations.
1896 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1897 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1900 bool CodeGenModule::isInSanitizerBlacklist(SanitizerMask Kind,
1902 SourceLocation Loc) const {
1903 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1904 // Blacklist by function name.
1905 if (SanitizerBL.isBlacklistedFunction(Kind, Fn->getName()))
1907 // Blacklist by location.
1909 return SanitizerBL.isBlacklistedLocation(Kind, Loc);
1910 // If location is unknown, this may be a compiler-generated function. Assume
1911 // it's located in the main file.
1912 auto &SM = Context.getSourceManager();
1913 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1914 return SanitizerBL.isBlacklistedFile(Kind, MainFile->getName());
1919 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1920 SourceLocation Loc, QualType Ty,
1921 StringRef Category) const {
1922 // For now globals can be blacklisted only in ASan and KASan.
1923 const SanitizerMask EnabledAsanMask = LangOpts.Sanitize.Mask &
1924 (SanitizerKind::Address | SanitizerKind::KernelAddress |
1925 SanitizerKind::HWAddress | SanitizerKind::KernelHWAddress);
1926 if (!EnabledAsanMask)
1928 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1929 if (SanitizerBL.isBlacklistedGlobal(EnabledAsanMask, GV->getName(), Category))
1931 if (SanitizerBL.isBlacklistedLocation(EnabledAsanMask, Loc, Category))
1933 // Check global type.
1935 // Drill down the array types: if global variable of a fixed type is
1936 // blacklisted, we also don't instrument arrays of them.
1937 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1938 Ty = AT->getElementType();
1939 Ty = Ty.getCanonicalType().getUnqualifiedType();
1940 // We allow to blacklist only record types (classes, structs etc.)
1941 if (Ty->isRecordType()) {
1942 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1943 if (SanitizerBL.isBlacklistedType(EnabledAsanMask, TypeStr, Category))
1950 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1951 StringRef Category) const {
1952 if (!LangOpts.XRayInstrument)
1955 const auto &XRayFilter = getContext().getXRayFilter();
1956 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1957 auto Attr = ImbueAttr::NONE;
1959 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1960 if (Attr == ImbueAttr::NONE)
1961 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1963 case ImbueAttr::NONE:
1965 case ImbueAttr::ALWAYS:
1966 Fn->addFnAttr("function-instrument", "xray-always");
1968 case ImbueAttr::ALWAYS_ARG1:
1969 Fn->addFnAttr("function-instrument", "xray-always");
1970 Fn->addFnAttr("xray-log-args", "1");
1972 case ImbueAttr::NEVER:
1973 Fn->addFnAttr("function-instrument", "xray-never");
1979 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1980 // Never defer when EmitAllDecls is specified.
1981 if (LangOpts.EmitAllDecls)
1984 return getContext().DeclMustBeEmitted(Global);
1987 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1988 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1989 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1990 // Implicit template instantiations may change linkage if they are later
1991 // explicitly instantiated, so they should not be emitted eagerly.
1993 if (const auto *VD = dyn_cast<VarDecl>(Global))
1994 if (Context.getInlineVariableDefinitionKind(VD) ==
1995 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1996 // A definition of an inline constexpr static data member may change
1997 // linkage later if it's redeclared outside the class.
1999 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
2000 // codegen for global variables, because they may be marked as threadprivate.
2001 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
2002 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global) &&
2003 !isTypeConstant(Global->getType(), false))
2009 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
2010 const CXXUuidofExpr* E) {
2011 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
2013 StringRef Uuid = E->getUuidStr();
2014 std::string Name = "_GUID_" + Uuid.lower();
2015 std::replace(Name.begin(), Name.end(), '-', '_');
2017 // The UUID descriptor should be pointer aligned.
2018 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
2020 // Look for an existing global.
2021 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
2022 return ConstantAddress(GV, Alignment);
2024 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
2025 assert(Init && "failed to initialize as constant");
2027 auto *GV = new llvm::GlobalVariable(
2028 getModule(), Init->getType(),
2029 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
2030 if (supportsCOMDAT())
2031 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2033 return ConstantAddress(GV, Alignment);
2036 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
2037 const AliasAttr *AA = VD->getAttr<AliasAttr>();
2038 assert(AA && "No alias?");
2040 CharUnits Alignment = getContext().getDeclAlign(VD);
2041 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
2043 // See if there is already something with the target's name in the module.
2044 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
2046 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
2047 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
2048 return ConstantAddress(Ptr, Alignment);
2051 llvm::Constant *Aliasee;
2052 if (isa<llvm::FunctionType>(DeclTy))
2053 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
2054 GlobalDecl(cast<FunctionDecl>(VD)),
2055 /*ForVTable=*/false);
2057 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2058 llvm::PointerType::getUnqual(DeclTy),
2061 auto *F = cast<llvm::GlobalValue>(Aliasee);
2062 F->setLinkage(llvm::Function::ExternalWeakLinkage);
2063 WeakRefReferences.insert(F);
2065 return ConstantAddress(Aliasee, Alignment);
2068 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
2069 const auto *Global = cast<ValueDecl>(GD.getDecl());
2071 // Weak references don't produce any output by themselves.
2072 if (Global->hasAttr<WeakRefAttr>())
2075 // If this is an alias definition (which otherwise looks like a declaration)
2077 if (Global->hasAttr<AliasAttr>())
2078 return EmitAliasDefinition(GD);
2080 // IFunc like an alias whose value is resolved at runtime by calling resolver.
2081 if (Global->hasAttr<IFuncAttr>())
2082 return emitIFuncDefinition(GD);
2084 // If this is a cpu_dispatch multiversion function, emit the resolver.
2085 if (Global->hasAttr<CPUDispatchAttr>())
2086 return emitCPUDispatchDefinition(GD);
2088 // If this is CUDA, be selective about which declarations we emit.
2089 if (LangOpts.CUDA) {
2090 if (LangOpts.CUDAIsDevice) {
2091 if (!Global->hasAttr<CUDADeviceAttr>() &&
2092 !Global->hasAttr<CUDAGlobalAttr>() &&
2093 !Global->hasAttr<CUDAConstantAttr>() &&
2094 !Global->hasAttr<CUDASharedAttr>())
2097 // We need to emit host-side 'shadows' for all global
2098 // device-side variables because the CUDA runtime needs their
2099 // size and host-side address in order to provide access to
2100 // their device-side incarnations.
2102 // So device-only functions are the only things we skip.
2103 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
2104 Global->hasAttr<CUDADeviceAttr>())
2107 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
2108 "Expected Variable or Function");
2112 if (LangOpts.OpenMP) {
2113 // If this is OpenMP device, check if it is legal to emit this global
2115 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
2117 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
2118 if (MustBeEmitted(Global))
2119 EmitOMPDeclareReduction(DRD);
2124 // Ignore declarations, they will be emitted on their first use.
2125 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
2126 // Forward declarations are emitted lazily on first use.
2127 if (!FD->doesThisDeclarationHaveABody()) {
2128 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
2131 StringRef MangledName = getMangledName(GD);
2133 // Compute the function info and LLVM type.
2134 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2135 llvm::Type *Ty = getTypes().GetFunctionType(FI);
2137 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
2138 /*DontDefer=*/false);
2142 const auto *VD = cast<VarDecl>(Global);
2143 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
2144 // We need to emit device-side global CUDA variables even if a
2145 // variable does not have a definition -- we still need to define
2146 // host-side shadow for it.
2147 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
2148 !VD->hasDefinition() &&
2149 (VD->hasAttr<CUDAConstantAttr>() ||
2150 VD->hasAttr<CUDADeviceAttr>());
2151 if (!MustEmitForCuda &&
2152 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
2153 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
2154 // If this declaration may have caused an inline variable definition to
2155 // change linkage, make sure that it's emitted.
2156 if (Context.getInlineVariableDefinitionKind(VD) ==
2157 ASTContext::InlineVariableDefinitionKind::Strong)
2158 GetAddrOfGlobalVar(VD);
2163 // Defer code generation to first use when possible, e.g. if this is an inline
2164 // function. If the global must always be emitted, do it eagerly if possible
2165 // to benefit from cache locality.
2166 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
2167 // Emit the definition if it can't be deferred.
2168 EmitGlobalDefinition(GD);
2172 // If we're deferring emission of a C++ variable with an
2173 // initializer, remember the order in which it appeared in the file.
2174 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
2175 cast<VarDecl>(Global)->hasInit()) {
2176 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
2177 CXXGlobalInits.push_back(nullptr);
2180 StringRef MangledName = getMangledName(GD);
2181 if (GetGlobalValue(MangledName) != nullptr) {
2182 // The value has already been used and should therefore be emitted.
2183 addDeferredDeclToEmit(GD);
2184 } else if (MustBeEmitted(Global)) {
2185 // The value must be emitted, but cannot be emitted eagerly.
2186 assert(!MayBeEmittedEagerly(Global));
2187 addDeferredDeclToEmit(GD);
2189 // Otherwise, remember that we saw a deferred decl with this name. The
2190 // first use of the mangled name will cause it to move into
2191 // DeferredDeclsToEmit.
2192 DeferredDecls[MangledName] = GD;
2196 // Check if T is a class type with a destructor that's not dllimport.
2197 static bool HasNonDllImportDtor(QualType T) {
2198 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
2199 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
2200 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
2207 struct FunctionIsDirectlyRecursive :
2208 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
2209 const StringRef Name;
2210 const Builtin::Context &BI;
2212 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
2213 Name(N), BI(C), Result(false) {
2215 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
2217 bool TraverseCallExpr(CallExpr *E) {
2218 const FunctionDecl *FD = E->getDirectCallee();
2221 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2222 if (Attr && Name == Attr->getLabel()) {
2226 unsigned BuiltinID = FD->getBuiltinID();
2227 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
2229 StringRef BuiltinName = BI.getName(BuiltinID);
2230 if (BuiltinName.startswith("__builtin_") &&
2231 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
2239 // Make sure we're not referencing non-imported vars or functions.
2240 struct DLLImportFunctionVisitor
2241 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
2242 bool SafeToInline = true;
2244 bool shouldVisitImplicitCode() const { return true; }
2246 bool VisitVarDecl(VarDecl *VD) {
2247 if (VD->getTLSKind()) {
2248 // A thread-local variable cannot be imported.
2249 SafeToInline = false;
2250 return SafeToInline;
2253 // A variable definition might imply a destructor call.
2254 if (VD->isThisDeclarationADefinition())
2255 SafeToInline = !HasNonDllImportDtor(VD->getType());
2257 return SafeToInline;
2260 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
2261 if (const auto *D = E->getTemporary()->getDestructor())
2262 SafeToInline = D->hasAttr<DLLImportAttr>();
2263 return SafeToInline;
2266 bool VisitDeclRefExpr(DeclRefExpr *E) {
2267 ValueDecl *VD = E->getDecl();
2268 if (isa<FunctionDecl>(VD))
2269 SafeToInline = VD->hasAttr<DLLImportAttr>();
2270 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
2271 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
2272 return SafeToInline;
2275 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2276 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
2277 return SafeToInline;
2280 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
2281 CXXMethodDecl *M = E->getMethodDecl();
2283 // Call through a pointer to member function. This is safe to inline.
2284 SafeToInline = true;
2286 SafeToInline = M->hasAttr<DLLImportAttr>();
2288 return SafeToInline;
2291 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
2292 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
2293 return SafeToInline;
2296 bool VisitCXXNewExpr(CXXNewExpr *E) {
2297 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
2298 return SafeToInline;
2303 // isTriviallyRecursive - Check if this function calls another
2304 // decl that, because of the asm attribute or the other decl being a builtin,
2305 // ends up pointing to itself.
2307 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
2309 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
2310 // asm labels are a special kind of mangling we have to support.
2311 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
2314 Name = Attr->getLabel();
2316 Name = FD->getName();
2319 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
2320 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
2321 return Walker.Result;
2324 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
2325 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
2327 const auto *F = cast<FunctionDecl>(GD.getDecl());
2328 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
2331 if (F->hasAttr<DLLImportAttr>()) {
2332 // Check whether it would be safe to inline this dllimport function.
2333 DLLImportFunctionVisitor Visitor;
2334 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
2335 if (!Visitor.SafeToInline)
2338 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
2339 // Implicit destructor invocations aren't captured in the AST, so the
2340 // check above can't see them. Check for them manually here.
2341 for (const Decl *Member : Dtor->getParent()->decls())
2342 if (isa<FieldDecl>(Member))
2343 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
2345 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
2346 if (HasNonDllImportDtor(B.getType()))
2351 // PR9614. Avoid cases where the source code is lying to us. An available
2352 // externally function should have an equivalent function somewhere else,
2353 // but a function that calls itself is clearly not equivalent to the real
2355 // This happens in glibc's btowc and in some configure checks.
2356 return !isTriviallyRecursive(F);
2359 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
2360 return CodeGenOpts.OptimizationLevel > 0;
2363 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
2364 const auto *D = cast<ValueDecl>(GD.getDecl());
2366 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
2367 Context.getSourceManager(),
2368 "Generating code for declaration");
2370 if (isa<FunctionDecl>(D)) {
2371 // At -O0, don't generate IR for functions with available_externally
2373 if (!shouldEmitFunction(GD))
2376 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2377 // Make sure to emit the definition(s) before we emit the thunks.
2378 // This is necessary for the generation of certain thunks.
2379 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
2380 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
2381 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
2382 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
2384 EmitGlobalFunctionDefinition(GD, GV);
2386 if (Method->isVirtual())
2387 getVTables().EmitThunks(GD);
2392 return EmitGlobalFunctionDefinition(GD, GV);
2395 if (const auto *VD = dyn_cast<VarDecl>(D))
2396 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2398 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2401 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2402 llvm::Function *NewFn);
2404 void CodeGenModule::emitMultiVersionFunctions() {
2405 for (GlobalDecl GD : MultiVersionFuncs) {
2406 SmallVector<CodeGenFunction::TargetMultiVersionResolverOption, 10> Options;
2407 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
2408 getContext().forEachMultiversionedFunctionVersion(
2409 FD, [this, &GD, &Options](const FunctionDecl *CurFD) {
2411 (CurFD->isDefined() ? CurFD->getDefinition() : CurFD)};
2412 StringRef MangledName = getMangledName(CurGD);
2413 llvm::Constant *Func = GetGlobalValue(MangledName);
2415 if (CurFD->isDefined()) {
2416 EmitGlobalFunctionDefinition(CurGD, nullptr);
2417 Func = GetGlobalValue(MangledName);
2419 const CGFunctionInfo &FI =
2420 getTypes().arrangeGlobalDeclaration(GD);
2421 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2422 Func = GetAddrOfFunction(CurGD, Ty, /*ForVTable=*/false,
2423 /*DontDefer=*/false, ForDefinition);
2425 assert(Func && "This should have just been created");
2427 Options.emplace_back(getTarget(), cast<llvm::Function>(Func),
2428 CurFD->getAttr<TargetAttr>()->parse());
2431 llvm::Function *ResolverFunc = cast<llvm::Function>(
2432 GetGlobalValue((getMangledName(GD) + ".resolver").str()));
2433 if (supportsCOMDAT())
2434 ResolverFunc->setComdat(
2435 getModule().getOrInsertComdat(ResolverFunc->getName()));
2437 Options.begin(), Options.end(),
2438 std::greater<CodeGenFunction::TargetMultiVersionResolverOption>());
2439 CodeGenFunction CGF(*this);
2440 CGF.EmitTargetMultiVersionResolver(ResolverFunc, Options);
2444 void CodeGenModule::emitCPUDispatchDefinition(GlobalDecl GD) {
2445 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2446 assert(FD && "Not a FunctionDecl?");
2447 const auto *DD = FD->getAttr<CPUDispatchAttr>();
2448 assert(DD && "Not a cpu_dispatch Function?");
2449 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(FD->getType());
2451 StringRef ResolverName = getMangledName(GD);
2452 llvm::Type *ResolverType = llvm::FunctionType::get(
2453 llvm::PointerType::get(DeclTy,
2454 Context.getTargetAddressSpace(FD->getType())),
2456 auto *ResolverFunc = cast<llvm::Function>(
2457 GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2458 /*ForVTable=*/false));
2460 SmallVector<CodeGenFunction::CPUDispatchMultiVersionResolverOption, 10>
2462 const TargetInfo &Target = getTarget();
2463 for (const IdentifierInfo *II : DD->cpus()) {
2464 // Get the name of the target function so we can look it up/create it.
2465 std::string MangledName = getMangledNameImpl(*this, GD, FD, true) +
2466 getCPUSpecificMangling(*this, II->getName());
2467 llvm::Constant *Func = GetOrCreateLLVMFunction(
2468 MangledName, DeclTy, GD, /*ForVTable=*/false, /*DontDefer=*/false,
2469 /*IsThunk=*/false, llvm::AttributeList(), ForDefinition);
2470 llvm::SmallVector<StringRef, 32> Features;
2471 Target.getCPUSpecificCPUDispatchFeatures(II->getName(), Features);
2472 llvm::transform(Features, Features.begin(),
2473 [](StringRef Str) { return Str.substr(1); });
2474 Features.erase(std::remove_if(
2475 Features.begin(), Features.end(), [&Target](StringRef Feat) {
2476 return !Target.validateCpuSupports(Feat);
2477 }), Features.end());
2478 Options.emplace_back(cast<llvm::Function>(Func),
2479 CodeGenFunction::GetX86CpuSupportsMask(Features));
2483 Options.begin(), Options.end(),
2484 std::greater<CodeGenFunction::CPUDispatchMultiVersionResolverOption>());
2485 CodeGenFunction CGF(*this);
2486 CGF.EmitCPUDispatchMultiVersionResolver(ResolverFunc, Options);
2489 /// If an ifunc for the specified mangled name is not in the module, create and
2490 /// return an llvm IFunc Function with the specified type.
2492 CodeGenModule::GetOrCreateMultiVersionIFunc(GlobalDecl GD, llvm::Type *DeclTy,
2493 const FunctionDecl *FD) {
2494 std::string MangledName =
2495 getMangledNameImpl(*this, GD, FD, /*OmitMultiVersionMangling=*/true);
2496 std::string IFuncName = MangledName + ".ifunc";
2497 if (llvm::GlobalValue *IFuncGV = GetGlobalValue(IFuncName))
2500 // Since this is the first time we've created this IFunc, make sure
2501 // that we put this multiversioned function into the list to be
2502 // replaced later if necessary (target multiversioning only).
2503 if (!FD->isCPUDispatchMultiVersion() && !FD->isCPUSpecificMultiVersion())
2504 MultiVersionFuncs.push_back(GD);
2506 std::string ResolverName = MangledName + ".resolver";
2507 llvm::Type *ResolverType = llvm::FunctionType::get(
2508 llvm::PointerType::get(DeclTy,
2509 Context.getTargetAddressSpace(FD->getType())),
2511 llvm::Constant *Resolver =
2512 GetOrCreateLLVMFunction(ResolverName, ResolverType, GlobalDecl{},
2513 /*ForVTable=*/false);
2514 llvm::GlobalIFunc *GIF = llvm::GlobalIFunc::create(
2515 DeclTy, 0, llvm::Function::ExternalLinkage, "", Resolver, &getModule());
2516 GIF->setName(IFuncName);
2517 SetCommonAttributes(FD, GIF);
2522 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2523 /// module, create and return an llvm Function with the specified type. If there
2524 /// is something in the module with the specified name, return it potentially
2525 /// bitcasted to the right type.
2527 /// If D is non-null, it specifies a decl that correspond to this. This is used
2528 /// to set the attributes on the function when it is first created.
2529 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2530 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2531 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2532 ForDefinition_t IsForDefinition) {
2533 const Decl *D = GD.getDecl();
2535 // Any attempts to use a MultiVersion function should result in retrieving
2536 // the iFunc instead. Name Mangling will handle the rest of the changes.
2537 if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D)) {
2538 // For the device mark the function as one that should be emitted.
2539 if (getLangOpts().OpenMPIsDevice && OpenMPRuntime &&
2540 !OpenMPRuntime->markAsGlobalTarget(GD) && FD->isDefined() &&
2541 !DontDefer && !IsForDefinition) {
2542 const FunctionDecl *FDDef = FD->getDefinition();
2544 if (const auto *CD = dyn_cast<CXXConstructorDecl>(FDDef))
2545 GDDef = GlobalDecl(CD, GD.getCtorType());
2546 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(FDDef))
2547 GDDef = GlobalDecl(DD, GD.getDtorType());
2549 GDDef = GlobalDecl(FDDef);
2550 addDeferredDeclToEmit(GDDef);
2553 if (FD->isMultiVersion()) {
2554 const auto *TA = FD->getAttr<TargetAttr>();
2555 if (TA && TA->isDefaultVersion())
2556 UpdateMultiVersionNames(GD, FD);
2557 if (!IsForDefinition)
2558 return GetOrCreateMultiVersionIFunc(GD, Ty, FD);
2562 // Lookup the entry, lazily creating it if necessary.
2563 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2565 if (WeakRefReferences.erase(Entry)) {
2566 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2567 if (FD && !FD->hasAttr<WeakAttr>())
2568 Entry->setLinkage(llvm::Function::ExternalLinkage);
2571 // Handle dropped DLL attributes.
2572 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>()) {
2573 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2577 // If there are two attempts to define the same mangled name, issue an
2579 if (IsForDefinition && !Entry->isDeclaration()) {
2581 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2582 // to make sure that we issue an error only once.
2583 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2584 (GD.getCanonicalDecl().getDecl() !=
2585 OtherGD.getCanonicalDecl().getDecl()) &&
2586 DiagnosedConflictingDefinitions.insert(GD).second) {
2587 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2589 getDiags().Report(OtherGD.getDecl()->getLocation(),
2590 diag::note_previous_definition);
2594 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2595 (Entry->getType()->getElementType() == Ty)) {
2599 // Make sure the result is of the correct type.
2600 // (If function is requested for a definition, we always need to create a new
2601 // function, not just return a bitcast.)
2602 if (!IsForDefinition)
2603 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2606 // This function doesn't have a complete type (for example, the return
2607 // type is an incomplete struct). Use a fake type instead, and make
2608 // sure not to try to set attributes.
2609 bool IsIncompleteFunction = false;
2611 llvm::FunctionType *FTy;
2612 if (isa<llvm::FunctionType>(Ty)) {
2613 FTy = cast<llvm::FunctionType>(Ty);
2615 FTy = llvm::FunctionType::get(VoidTy, false);
2616 IsIncompleteFunction = true;
2620 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2621 Entry ? StringRef() : MangledName, &getModule());
2623 // If we already created a function with the same mangled name (but different
2624 // type) before, take its name and add it to the list of functions to be
2625 // replaced with F at the end of CodeGen.
2627 // This happens if there is a prototype for a function (e.g. "int f()") and
2628 // then a definition of a different type (e.g. "int f(int x)").
2632 // This might be an implementation of a function without a prototype, in
2633 // which case, try to do special replacement of calls which match the new
2634 // prototype. The really key thing here is that we also potentially drop
2635 // arguments from the call site so as to make a direct call, which makes the
2636 // inliner happier and suppresses a number of optimizer warnings (!) about
2637 // dropping arguments.
2638 if (!Entry->use_empty()) {
2639 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2640 Entry->removeDeadConstantUsers();
2643 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2644 F, Entry->getType()->getElementType()->getPointerTo());
2645 addGlobalValReplacement(Entry, BC);
2648 assert(F->getName() == MangledName && "name was uniqued!");
2650 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2651 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2652 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2653 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2657 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2658 // each other bottoming out with the base dtor. Therefore we emit non-base
2659 // dtors on usage, even if there is no dtor definition in the TU.
2660 if (D && isa<CXXDestructorDecl>(D) &&
2661 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2663 addDeferredDeclToEmit(GD);
2665 // This is the first use or definition of a mangled name. If there is a
2666 // deferred decl with this name, remember that we need to emit it at the end
2668 auto DDI = DeferredDecls.find(MangledName);
2669 if (DDI != DeferredDecls.end()) {
2670 // Move the potentially referenced deferred decl to the
2671 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2672 // don't need it anymore).
2673 addDeferredDeclToEmit(DDI->second);
2674 DeferredDecls.erase(DDI);
2676 // Otherwise, there are cases we have to worry about where we're
2677 // using a declaration for which we must emit a definition but where
2678 // we might not find a top-level definition:
2679 // - member functions defined inline in their classes
2680 // - friend functions defined inline in some class
2681 // - special member functions with implicit definitions
2682 // If we ever change our AST traversal to walk into class methods,
2683 // this will be unnecessary.
2685 // We also don't emit a definition for a function if it's going to be an
2686 // entry in a vtable, unless it's already marked as used.
2687 } else if (getLangOpts().CPlusPlus && D) {
2688 // Look for a declaration that's lexically in a record.
2689 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2690 FD = FD->getPreviousDecl()) {
2691 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2692 if (FD->doesThisDeclarationHaveABody()) {
2693 addDeferredDeclToEmit(GD.getWithDecl(FD));
2701 // Make sure the result is of the requested type.
2702 if (!IsIncompleteFunction) {
2703 assert(F->getType()->getElementType() == Ty);
2707 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2708 return llvm::ConstantExpr::getBitCast(F, PTy);
2711 /// GetAddrOfFunction - Return the address of the given function. If Ty is
2712 /// non-null, then this function will use the specified type if it has to
2713 /// create it (this occurs when we see a definition of the function).
2714 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2718 ForDefinition_t IsForDefinition) {
2719 // If there was no specific requested type, just convert it now.
2721 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2722 auto CanonTy = Context.getCanonicalType(FD->getType());
2723 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2726 // Devirtualized destructor calls may come through here instead of via
2727 // getAddrOfCXXStructor. Make sure we use the MS ABI base destructor instead
2728 // of the complete destructor when necessary.
2729 if (const auto *DD = dyn_cast<CXXDestructorDecl>(GD.getDecl())) {
2730 if (getTarget().getCXXABI().isMicrosoft() &&
2731 GD.getDtorType() == Dtor_Complete &&
2732 DD->getParent()->getNumVBases() == 0)
2733 GD = GlobalDecl(DD, Dtor_Base);
2736 StringRef MangledName = getMangledName(GD);
2737 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2738 /*IsThunk=*/false, llvm::AttributeList(),
2742 static const FunctionDecl *
2743 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2744 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2745 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2747 IdentifierInfo &CII = C.Idents.get(Name);
2748 for (const auto &Result : DC->lookup(&CII))
2749 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2752 if (!C.getLangOpts().CPlusPlus)
2755 // Demangle the premangled name from getTerminateFn()
2756 IdentifierInfo &CXXII =
2757 (Name == "_ZSt9terminatev" || Name == "?terminate@@YAXXZ")
2758 ? C.Idents.get("terminate")
2759 : C.Idents.get(Name);
2761 for (const auto &N : {"__cxxabiv1", "std"}) {
2762 IdentifierInfo &NS = C.Idents.get(N);
2763 for (const auto &Result : DC->lookup(&NS)) {
2764 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2765 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2766 for (const auto &Result : LSD->lookup(&NS))
2767 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2771 for (const auto &Result : ND->lookup(&CXXII))
2772 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2780 /// CreateRuntimeFunction - Create a new runtime function with the specified
2783 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2784 llvm::AttributeList ExtraAttrs,
2787 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2788 /*DontDefer=*/false, /*IsThunk=*/false,
2791 if (auto *F = dyn_cast<llvm::Function>(C)) {
2793 F->setCallingConv(getRuntimeCC());
2795 if (!Local && getTriple().isOSBinFormatCOFF() &&
2796 !getCodeGenOpts().LTOVisibilityPublicStd &&
2797 !getTriple().isWindowsGNUEnvironment()) {
2798 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2799 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2800 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2801 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2811 /// CreateBuiltinFunction - Create a new builtin function with the specified
2814 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2815 llvm::AttributeList ExtraAttrs) {
2816 return CreateRuntimeFunction(FTy, Name, ExtraAttrs, true);
2819 /// isTypeConstant - Determine whether an object of this type can be emitted
2822 /// If ExcludeCtor is true, the duration when the object's constructor runs
2823 /// will not be considered. The caller will need to verify that the object is
2824 /// not written to during its construction.
2825 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2826 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2829 if (Context.getLangOpts().CPlusPlus) {
2830 if (const CXXRecordDecl *Record
2831 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2832 return ExcludeCtor && !Record->hasMutableFields() &&
2833 Record->hasTrivialDestructor();
2839 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2840 /// create and return an llvm GlobalVariable with the specified type. If there
2841 /// is something in the module with the specified name, return it potentially
2842 /// bitcasted to the right type.
2844 /// If D is non-null, it specifies a decl that correspond to this. This is used
2845 /// to set the attributes on the global when it is first created.
2847 /// If IsForDefinition is true, it is guaranteed that an actual global with
2848 /// type Ty will be returned, not conversion of a variable with the same
2849 /// mangled name but some other type.
2851 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2852 llvm::PointerType *Ty,
2854 ForDefinition_t IsForDefinition) {
2855 // Lookup the entry, lazily creating it if necessary.
2856 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2858 if (WeakRefReferences.erase(Entry)) {
2859 if (D && !D->hasAttr<WeakAttr>())
2860 Entry->setLinkage(llvm::Function::ExternalLinkage);
2863 // Handle dropped DLL attributes.
2864 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2865 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2867 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd && D)
2868 getOpenMPRuntime().registerTargetGlobalVariable(D, Entry);
2870 if (Entry->getType() == Ty)
2873 // If there are two attempts to define the same mangled name, issue an
2875 if (IsForDefinition && !Entry->isDeclaration()) {
2877 const VarDecl *OtherD;
2879 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2880 // to make sure that we issue an error only once.
2881 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2882 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2883 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2884 OtherD->hasInit() &&
2885 DiagnosedConflictingDefinitions.insert(D).second) {
2886 getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name)
2888 getDiags().Report(OtherGD.getDecl()->getLocation(),
2889 diag::note_previous_definition);
2893 // Make sure the result is of the correct type.
2894 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2895 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2897 // (If global is requested for a definition, we always need to create a new
2898 // global, not just return a bitcast.)
2899 if (!IsForDefinition)
2900 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2903 auto AddrSpace = GetGlobalVarAddressSpace(D);
2904 auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2906 auto *GV = new llvm::GlobalVariable(
2907 getModule(), Ty->getElementType(), false,
2908 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2909 llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
2911 // If we already created a global with the same mangled name (but different
2912 // type) before, take its name and remove it from its parent.
2914 GV->takeName(Entry);
2916 if (!Entry->use_empty()) {
2917 llvm::Constant *NewPtrForOldDecl =
2918 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2919 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2922 Entry->eraseFromParent();
2925 // This is the first use or definition of a mangled name. If there is a
2926 // deferred decl with this name, remember that we need to emit it at the end
2928 auto DDI = DeferredDecls.find(MangledName);
2929 if (DDI != DeferredDecls.end()) {
2930 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2931 // list, and remove it from DeferredDecls (since we don't need it anymore).
2932 addDeferredDeclToEmit(DDI->second);
2933 DeferredDecls.erase(DDI);
2936 // Handle things which are present even on external declarations.
2938 if (LangOpts.OpenMP && !LangOpts.OpenMPSimd)
2939 getOpenMPRuntime().registerTargetGlobalVariable(D, GV);
2941 // FIXME: This code is overly simple and should be merged with other global
2943 GV->setConstant(isTypeConstant(D->getType(), false));
2945 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2947 setLinkageForGV(GV, D);
2949 if (D->getTLSKind()) {
2950 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2951 CXXThreadLocals.push_back(D);
2955 setGVProperties(GV, D);
2957 // If required by the ABI, treat declarations of static data members with
2958 // inline initializers as definitions.
2959 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2960 EmitGlobalVarDefinition(D);
2963 // Emit section information for extern variables.
2964 if (D->hasExternalStorage()) {
2965 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
2966 GV->setSection(SA->getName());
2969 // Handle XCore specific ABI requirements.
2970 if (getTriple().getArch() == llvm::Triple::xcore &&
2971 D->getLanguageLinkage() == CLanguageLinkage &&
2972 D->getType().isConstant(Context) &&
2973 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2974 GV->setSection(".cp.rodata");
2976 // Check if we a have a const declaration with an initializer, we may be
2977 // able to emit it as available_externally to expose it's value to the
2979 if (Context.getLangOpts().CPlusPlus && GV->hasExternalLinkage() &&
2980 D->getType().isConstQualified() && !GV->hasInitializer() &&
2981 !D->hasDefinition() && D->hasInit() && !D->hasAttr<DLLImportAttr>()) {
2982 const auto *Record =
2983 Context.getBaseElementType(D->getType())->getAsCXXRecordDecl();
2984 bool HasMutableFields = Record && Record->hasMutableFields();
2985 if (!HasMutableFields) {
2986 const VarDecl *InitDecl;
2987 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2989 ConstantEmitter emitter(*this);
2990 llvm::Constant *Init = emitter.tryEmitForInitializer(*InitDecl);
2992 auto *InitType = Init->getType();
2993 if (GV->getType()->getElementType() != InitType) {
2994 // The type of the initializer does not match the definition.
2995 // This happens when an initializer has a different type from
2996 // the type of the global (because of padding at the end of a
2997 // structure for instance).
2998 GV->setName(StringRef());
2999 // Make a new global with the correct type, this is now guaranteed
3001 auto *NewGV = cast<llvm::GlobalVariable>(
3002 GetAddrOfGlobalVar(D, InitType, IsForDefinition));
3004 // Erase the old global, since it is no longer used.
3005 GV->eraseFromParent();
3008 GV->setInitializer(Init);
3009 GV->setConstant(true);
3010 GV->setLinkage(llvm::GlobalValue::AvailableExternallyLinkage);
3012 emitter.finalize(GV);
3020 D ? D->getType().getAddressSpace()
3021 : (LangOpts.OpenCL ? LangAS::opencl_global : LangAS::Default);
3022 assert(getContext().getTargetAddressSpace(ExpectedAS) ==
3023 Ty->getPointerAddressSpace());
3024 if (AddrSpace != ExpectedAS)
3025 return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
3032 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
3033 ForDefinition_t IsForDefinition) {
3034 const Decl *D = GD.getDecl();
3035 if (isa<CXXConstructorDecl>(D))
3036 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
3037 getFromCtorType(GD.getCtorType()),
3038 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3039 /*DontDefer=*/false, IsForDefinition);
3040 else if (isa<CXXDestructorDecl>(D))
3041 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
3042 getFromDtorType(GD.getDtorType()),
3043 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
3044 /*DontDefer=*/false, IsForDefinition);
3045 else if (isa<CXXMethodDecl>(D)) {
3046 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
3047 cast<CXXMethodDecl>(D));
3048 auto Ty = getTypes().GetFunctionType(*FInfo);
3049 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3051 } else if (isa<FunctionDecl>(D)) {
3052 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3053 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3054 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
3057 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
3061 llvm::GlobalVariable *
3062 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
3064 llvm::GlobalValue::LinkageTypes Linkage) {
3065 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
3066 llvm::GlobalVariable *OldGV = nullptr;
3069 // Check if the variable has the right type.
3070 if (GV->getType()->getElementType() == Ty)
3073 // Because C++ name mangling, the only way we can end up with an already
3074 // existing global with the same name is if it has been declared extern "C".
3075 assert(GV->isDeclaration() && "Declaration has wrong type!");
3079 // Create a new variable.
3080 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
3081 Linkage, nullptr, Name);
3084 // Replace occurrences of the old variable if needed.
3085 GV->takeName(OldGV);
3087 if (!OldGV->use_empty()) {
3088 llvm::Constant *NewPtrForOldDecl =
3089 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
3090 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
3093 OldGV->eraseFromParent();
3096 if (supportsCOMDAT() && GV->isWeakForLinker() &&
3097 !GV->hasAvailableExternallyLinkage())
3098 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3103 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
3104 /// given global variable. If Ty is non-null and if the global doesn't exist,
3105 /// then it will be created with the specified type instead of whatever the
3106 /// normal requested type would be. If IsForDefinition is true, it is guaranteed
3107 /// that an actual global with type Ty will be returned, not conversion of a
3108 /// variable with the same mangled name but some other type.
3109 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
3111 ForDefinition_t IsForDefinition) {
3112 assert(D->hasGlobalStorage() && "Not a global variable");
3113 QualType ASTTy = D->getType();
3115 Ty = getTypes().ConvertTypeForMem(ASTTy);
3117 llvm::PointerType *PTy =
3118 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
3120 StringRef MangledName = getMangledName(D);
3121 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
3124 /// CreateRuntimeVariable - Create a new runtime global variable with the
3125 /// specified type and name.
3127 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
3130 GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
3131 setDSOLocal(cast<llvm::GlobalValue>(Ret->stripPointerCasts()));
3135 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
3136 assert(!D->getInit() && "Cannot emit definite definitions here!");
3138 StringRef MangledName = getMangledName(D);
3139 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
3141 // We already have a definition, not declaration, with the same mangled name.
3142 // Emitting of declaration is not required (and actually overwrites emitted
3144 if (GV && !GV->isDeclaration())
3147 // If we have not seen a reference to this variable yet, place it into the
3148 // deferred declarations table to be emitted if needed later.
3149 if (!MustBeEmitted(D) && !GV) {
3150 DeferredDecls[MangledName] = D;
3154 // The tentative definition is the only definition.
3155 EmitGlobalVarDefinition(D);
3158 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
3159 return Context.toCharUnitsFromBits(
3160 getDataLayout().getTypeStoreSizeInBits(Ty));
3163 LangAS CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
3164 LangAS AddrSpace = LangAS::Default;
3165 if (LangOpts.OpenCL) {
3166 AddrSpace = D ? D->getType().getAddressSpace() : LangAS::opencl_global;
3167 assert(AddrSpace == LangAS::opencl_global ||
3168 AddrSpace == LangAS::opencl_constant ||
3169 AddrSpace == LangAS::opencl_local ||
3170 AddrSpace >= LangAS::FirstTargetAddressSpace);
3174 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
3175 if (D && D->hasAttr<CUDAConstantAttr>())
3176 return LangAS::cuda_constant;
3177 else if (D && D->hasAttr<CUDASharedAttr>())
3178 return LangAS::cuda_shared;
3180 return LangAS::cuda_device;
3183 return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
3186 LangAS CodeGenModule::getStringLiteralAddressSpace() const {
3187 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3188 if (LangOpts.OpenCL)
3189 return LangAS::opencl_constant;
3190 if (auto AS = getTarget().getConstantAddressSpace())
3191 return AS.getValue();
3192 return LangAS::Default;
3195 // In address space agnostic languages, string literals are in default address
3196 // space in AST. However, certain targets (e.g. amdgcn) request them to be
3197 // emitted in constant address space in LLVM IR. To be consistent with other
3198 // parts of AST, string literal global variables in constant address space
3199 // need to be casted to default address space before being put into address
3200 // map and referenced by other part of CodeGen.
3201 // In OpenCL, string literals are in constant address space in AST, therefore
3202 // they should not be casted to default address space.
3203 static llvm::Constant *
3204 castStringLiteralToDefaultAddressSpace(CodeGenModule &CGM,
3205 llvm::GlobalVariable *GV) {
3206 llvm::Constant *Cast = GV;
3207 if (!CGM.getLangOpts().OpenCL) {
3208 if (auto AS = CGM.getTarget().getConstantAddressSpace()) {
3209 if (AS != LangAS::Default)
3210 Cast = CGM.getTargetCodeGenInfo().performAddrSpaceCast(
3211 CGM, GV, AS.getValue(), LangAS::Default,
3212 GV->getValueType()->getPointerTo(
3213 CGM.getContext().getTargetAddressSpace(LangAS::Default)));
3219 template<typename SomeDecl>
3220 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
3221 llvm::GlobalValue *GV) {
3222 if (!getLangOpts().CPlusPlus)
3225 // Must have 'used' attribute, or else inline assembly can't rely on
3226 // the name existing.
3227 if (!D->template hasAttr<UsedAttr>())
3230 // Must have internal linkage and an ordinary name.
3231 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
3234 // Must be in an extern "C" context. Entities declared directly within
3235 // a record are not extern "C" even if the record is in such a context.
3236 const SomeDecl *First = D->getFirstDecl();
3237 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
3240 // OK, this is an internal linkage entity inside an extern "C" linkage
3241 // specification. Make a note of that so we can give it the "expected"
3242 // mangled name if nothing else is using that name.
3243 std::pair<StaticExternCMap::iterator, bool> R =
3244 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
3246 // If we have multiple internal linkage entities with the same name
3247 // in extern "C" regions, none of them gets that name.
3249 R.first->second = nullptr;
3252 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
3253 if (!CGM.supportsCOMDAT())
3256 if (D.hasAttr<SelectAnyAttr>())
3260 if (auto *VD = dyn_cast<VarDecl>(&D))
3261 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
3263 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
3267 case GVA_AvailableExternally:
3268 case GVA_StrongExternal:
3270 case GVA_DiscardableODR:
3274 llvm_unreachable("No such linkage");
3277 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
3278 llvm::GlobalObject &GO) {
3279 if (!shouldBeInCOMDAT(*this, D))
3281 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
3284 /// Pass IsTentative as true if you want to create a tentative definition.
3285 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
3287 // OpenCL global variables of sampler type are translated to function calls,
3288 // therefore no need to be translated.
3289 QualType ASTTy = D->getType();
3290 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
3293 // If this is OpenMP device, check if it is legal to emit this global
3295 if (LangOpts.OpenMPIsDevice && OpenMPRuntime &&
3296 OpenMPRuntime->emitTargetGlobalVariable(D))
3299 llvm::Constant *Init = nullptr;
3300 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
3301 bool NeedsGlobalCtor = false;
3302 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
3304 const VarDecl *InitDecl;
3305 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
3307 Optional<ConstantEmitter> emitter;
3309 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
3310 // as part of their declaration." Sema has already checked for
3311 // error cases, so we just need to set Init to UndefValue.
3312 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
3313 D->hasAttr<CUDASharedAttr>())
3314 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
3315 else if (!InitExpr) {
3316 // This is a tentative definition; tentative definitions are
3317 // implicitly initialized with { 0 }.
3319 // Note that tentative definitions are only emitted at the end of
3320 // a translation unit, so they should never have incomplete
3321 // type. In addition, EmitTentativeDefinition makes sure that we
3322 // never attempt to emit a tentative definition if a real one
3323 // exists. A use may still exists, however, so we still may need
3325 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
3326 Init = EmitNullConstant(D->getType());
3328 initializedGlobalDecl = GlobalDecl(D);
3329 emitter.emplace(*this);
3330 Init = emitter->tryEmitForInitializer(*InitDecl);
3333 QualType T = InitExpr->getType();
3334 if (D->getType()->isReferenceType())
3337 if (getLangOpts().CPlusPlus) {
3338 Init = EmitNullConstant(T);
3339 NeedsGlobalCtor = true;
3341 ErrorUnsupported(D, "static initializer");
3342 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
3345 // We don't need an initializer, so remove the entry for the delayed
3346 // initializer position (just in case this entry was delayed) if we
3347 // also don't need to register a destructor.
3348 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
3349 DelayedCXXInitPosition.erase(D);
3353 llvm::Type* InitType = Init->getType();
3354 llvm::Constant *Entry =
3355 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
3357 // Strip off a bitcast if we got one back.
3358 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
3359 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
3360 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
3361 // All zero index gep.
3362 CE->getOpcode() == llvm::Instruction::GetElementPtr);
3363 Entry = CE->getOperand(0);
3366 // Entry is now either a Function or GlobalVariable.
3367 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
3369 // We have a definition after a declaration with the wrong type.
3370 // We must make a new GlobalVariable* and update everything that used OldGV
3371 // (a declaration or tentative definition) with the new GlobalVariable*
3372 // (which will be a definition).
3374 // This happens if there is a prototype for a global (e.g.
3375 // "extern int x[];") and then a definition of a different type (e.g.
3376 // "int x[10];"). This also happens when an initializer has a different type
3377 // from the type of the global (this happens with unions).
3378 if (!GV || GV->getType()->getElementType() != InitType ||
3379 GV->getType()->getAddressSpace() !=
3380 getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
3382 // Move the old entry aside so that we'll create a new one.
3383 Entry->setName(StringRef());
3385 // Make a new global with the correct type, this is now guaranteed to work.
3386 GV = cast<llvm::GlobalVariable>(
3387 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
3389 // Replace all uses of the old global with the new global
3390 llvm::Constant *NewPtrForOldDecl =
3391 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
3392 Entry->replaceAllUsesWith(NewPtrForOldDecl);
3394 // Erase the old global, since it is no longer used.
3395 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
3398 MaybeHandleStaticInExternC(D, GV);
3400 if (D->hasAttr<AnnotateAttr>())
3401 AddGlobalAnnotations(D, GV);
3403 // Set the llvm linkage type as appropriate.
3404 llvm::GlobalValue::LinkageTypes Linkage =
3405 getLLVMLinkageVarDefinition(D, GV->isConstant());
3407 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
3408 // the device. [...]"
3409 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
3410 // __device__, declares a variable that: [...]
3411 // Is accessible from all the threads within the grid and from the host
3412 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
3413 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
3414 if (GV && LangOpts.CUDA) {
3415 if (LangOpts.CUDAIsDevice) {
3416 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
3417 GV->setExternallyInitialized(true);
3419 // Host-side shadows of external declarations of device-side
3420 // global variables become internal definitions. These have to
3421 // be internal in order to prevent name conflicts with global
3422 // host variables with the same name in a different TUs.
3423 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
3424 Linkage = llvm::GlobalValue::InternalLinkage;
3426 // Shadow variables and their properties must be registered
3427 // with CUDA runtime.
3429 if (!D->hasDefinition())
3430 Flags |= CGCUDARuntime::ExternDeviceVar;
3431 if (D->hasAttr<CUDAConstantAttr>())
3432 Flags |= CGCUDARuntime::ConstantDeviceVar;
3433 getCUDARuntime().registerDeviceVar(*GV, Flags);
3434 } else if (D->hasAttr<CUDASharedAttr>())
3435 // __shared__ variables are odd. Shadows do get created, but
3436 // they are not registered with the CUDA runtime, so they
3437 // can't really be used to access their device-side
3438 // counterparts. It's not clear yet whether it's nvcc's bug or
3439 // a feature, but we've got to do the same for compatibility.
3440 Linkage = llvm::GlobalValue::InternalLinkage;
3444 GV->setInitializer(Init);
3445 if (emitter) emitter->finalize(GV);
3447 // If it is safe to mark the global 'constant', do so now.
3448 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
3449 isTypeConstant(D->getType(), true));
3451 // If it is in a read-only section, mark it 'constant'.
3452 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
3453 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
3454 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
3455 GV->setConstant(true);
3458 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
3461 // On Darwin, if the normal linkage of a C++ thread_local variable is
3462 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
3463 // copies within a linkage unit; otherwise, the backing variable has
3464 // internal linkage and all accesses should just be calls to the
3465 // Itanium-specified entry point, which has the normal linkage of the
3466 // variable. This is to preserve the ability to change the implementation
3467 // behind the scenes.
3468 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
3469 Context.getTargetInfo().getTriple().isOSDarwin() &&
3470 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
3471 !llvm::GlobalVariable::isWeakLinkage(Linkage))
3472 Linkage = llvm::GlobalValue::InternalLinkage;
3474 GV->setLinkage(Linkage);
3475 if (D->hasAttr<DLLImportAttr>())
3476 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
3477 else if (D->hasAttr<DLLExportAttr>())
3478 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
3480 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
3482 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
3483 // common vars aren't constant even if declared const.
3484 GV->setConstant(false);
3485 // Tentative definition of global variables may be initialized with
3486 // non-zero null pointers. In this case they should have weak linkage
3487 // since common linkage must have zero initializer and must not have
3488 // explicit section therefore cannot have non-zero initial value.
3489 if (!GV->getInitializer()->isNullValue())
3490 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
3493 setNonAliasAttributes(D, GV);
3495 if (D->getTLSKind() && !GV->isThreadLocal()) {
3496 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
3497 CXXThreadLocals.push_back(D);
3501 maybeSetTrivialComdat(*D, *GV);
3503 // Emit the initializer function if necessary.
3504 if (NeedsGlobalCtor || NeedsGlobalDtor)
3505 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
3507 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
3509 // Emit global variable debug information.
3510 if (CGDebugInfo *DI = getModuleDebugInfo())
3511 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3512 DI->EmitGlobalVariable(GV, D);
3515 static bool isVarDeclStrongDefinition(const ASTContext &Context,
3516 CodeGenModule &CGM, const VarDecl *D,
3518 // Don't give variables common linkage if -fno-common was specified unless it
3519 // was overridden by a NoCommon attribute.
3520 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
3524 // A declaration of an identifier for an object that has file scope without
3525 // an initializer, and without a storage-class specifier or with the
3526 // storage-class specifier static, constitutes a tentative definition.
3527 if (D->getInit() || D->hasExternalStorage())
3530 // A variable cannot be both common and exist in a section.
3531 if (D->hasAttr<SectionAttr>())
3534 // A variable cannot be both common and exist in a section.
3535 // We don't try to determine which is the right section in the front-end.
3536 // If no specialized section name is applicable, it will resort to default.
3537 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
3538 D->hasAttr<PragmaClangDataSectionAttr>() ||
3539 D->hasAttr<PragmaClangRodataSectionAttr>())
3542 // Thread local vars aren't considered common linkage.
3543 if (D->getTLSKind())
3546 // Tentative definitions marked with WeakImportAttr are true definitions.
3547 if (D->hasAttr<WeakImportAttr>())
3550 // A variable cannot be both common and exist in a comdat.
3551 if (shouldBeInCOMDAT(CGM, *D))
3554 // Declarations with a required alignment do not have common linkage in MSVC
3556 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
3557 if (D->hasAttr<AlignedAttr>())
3559 QualType VarType = D->getType();
3560 if (Context.isAlignmentRequired(VarType))
3563 if (const auto *RT = VarType->getAs<RecordType>()) {
3564 const RecordDecl *RD = RT->getDecl();
3565 for (const FieldDecl *FD : RD->fields()) {
3566 if (FD->isBitField())
3568 if (FD->hasAttr<AlignedAttr>())
3570 if (Context.isAlignmentRequired(FD->getType()))
3579 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
3580 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
3581 if (Linkage == GVA_Internal)
3582 return llvm::Function::InternalLinkage;
3584 if (D->hasAttr<WeakAttr>()) {
3585 if (IsConstantVariable)
3586 return llvm::GlobalVariable::WeakODRLinkage;
3588 return llvm::GlobalVariable::WeakAnyLinkage;
3591 // We are guaranteed to have a strong definition somewhere else,
3592 // so we can use available_externally linkage.
3593 if (Linkage == GVA_AvailableExternally)
3594 return llvm::GlobalValue::AvailableExternallyLinkage;
3596 // Note that Apple's kernel linker doesn't support symbol
3597 // coalescing, so we need to avoid linkonce and weak linkages there.
3598 // Normally, this means we just map to internal, but for explicit
3599 // instantiations we'll map to external.
3601 // In C++, the compiler has to emit a definition in every translation unit
3602 // that references the function. We should use linkonce_odr because
3603 // a) if all references in this translation unit are optimized away, we
3604 // don't need to codegen it. b) if the function persists, it needs to be
3605 // merged with other definitions. c) C++ has the ODR, so we know the
3606 // definition is dependable.
3607 if (Linkage == GVA_DiscardableODR)
3608 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
3609 : llvm::Function::InternalLinkage;
3611 // An explicit instantiation of a template has weak linkage, since
3612 // explicit instantiations can occur in multiple translation units
3613 // and must all be equivalent. However, we are not allowed to
3614 // throw away these explicit instantiations.
3616 // We don't currently support CUDA device code spread out across multiple TUs,
3617 // so say that CUDA templates are either external (for kernels) or internal.
3618 // This lets llvm perform aggressive inter-procedural optimizations.
3619 if (Linkage == GVA_StrongODR) {
3620 if (Context.getLangOpts().AppleKext)
3621 return llvm::Function::ExternalLinkage;
3622 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
3623 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
3624 : llvm::Function::InternalLinkage;
3625 return llvm::Function::WeakODRLinkage;
3628 // C++ doesn't have tentative definitions and thus cannot have common
3630 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
3631 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
3632 CodeGenOpts.NoCommon))
3633 return llvm::GlobalVariable::CommonLinkage;
3635 // selectany symbols are externally visible, so use weak instead of
3636 // linkonce. MSVC optimizes away references to const selectany globals, so
3637 // all definitions should be the same and ODR linkage should be used.
3638 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
3639 if (D->hasAttr<SelectAnyAttr>())
3640 return llvm::GlobalVariable::WeakODRLinkage;
3642 // Otherwise, we have strong external linkage.
3643 assert(Linkage == GVA_StrongExternal);
3644 return llvm::GlobalVariable::ExternalLinkage;
3647 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
3648 const VarDecl *VD, bool IsConstant) {
3649 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
3650 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
3653 /// Replace the uses of a function that was declared with a non-proto type.
3654 /// We want to silently drop extra arguments from call sites
3655 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3656 llvm::Function *newFn) {
3658 if (old->use_empty()) return;
3660 llvm::Type *newRetTy = newFn->getReturnType();
3661 SmallVector<llvm::Value*, 4> newArgs;
3662 SmallVector<llvm::OperandBundleDef, 1> newBundles;
3664 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3666 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
3667 llvm::User *user = use->getUser();
3669 // Recognize and replace uses of bitcasts. Most calls to
3670 // unprototyped functions will use bitcasts.
3671 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3672 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3673 replaceUsesOfNonProtoConstant(bitcast, newFn);
3677 // Recognize calls to the function.
3678 llvm::CallSite callSite(user);
3679 if (!callSite) continue;
3680 if (!callSite.isCallee(&*use)) continue;
3682 // If the return types don't match exactly, then we can't
3683 // transform this call unless it's dead.
3684 if (callSite->getType() != newRetTy && !callSite->use_empty())
3687 // Get the call site's attribute list.
3688 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
3689 llvm::AttributeList oldAttrs = callSite.getAttributes();
3691 // If the function was passed too few arguments, don't transform.
3692 unsigned newNumArgs = newFn->arg_size();
3693 if (callSite.arg_size() < newNumArgs) continue;
3695 // If extra arguments were passed, we silently drop them.
3696 // If any of the types mismatch, we don't transform.
3698 bool dontTransform = false;
3699 for (llvm::Argument &A : newFn->args()) {
3700 if (callSite.getArgument(argNo)->getType() != A.getType()) {
3701 dontTransform = true;
3705 // Add any parameter attributes.
3706 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3712 // Okay, we can transform this. Create the new call instruction and copy
3713 // over the required information.
3714 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3716 // Copy over any operand bundles.
3717 callSite.getOperandBundlesAsDefs(newBundles);
3719 llvm::CallSite newCall;
3720 if (callSite.isCall()) {
3721 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3722 callSite.getInstruction());
3724 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3725 newCall = llvm::InvokeInst::Create(newFn,
3726 oldInvoke->getNormalDest(),
3727 oldInvoke->getUnwindDest(),
3728 newArgs, newBundles, "",
3729 callSite.getInstruction());
3731 newArgs.clear(); // for the next iteration
3733 if (!newCall->getType()->isVoidTy())
3734 newCall->takeName(callSite.getInstruction());
3735 newCall.setAttributes(llvm::AttributeList::get(
3736 newFn->getContext(), oldAttrs.getFnAttributes(),
3737 oldAttrs.getRetAttributes(), newArgAttrs));
3738 newCall.setCallingConv(callSite.getCallingConv());
3740 // Finally, remove the old call, replacing any uses with the new one.
3741 if (!callSite->use_empty())
3742 callSite->replaceAllUsesWith(newCall.getInstruction());
3744 // Copy debug location attached to CI.
3745 if (callSite->getDebugLoc())
3746 newCall->setDebugLoc(callSite->getDebugLoc());
3748 callSite->eraseFromParent();
3752 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3753 /// implement a function with no prototype, e.g. "int foo() {}". If there are
3754 /// existing call uses of the old function in the module, this adjusts them to
3755 /// call the new function directly.
3757 /// This is not just a cleanup: the always_inline pass requires direct calls to
3758 /// functions to be able to inline them. If there is a bitcast in the way, it
3759 /// won't inline them. Instcombine normally deletes these calls, but it isn't
3761 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3762 llvm::Function *NewFn) {
3763 // If we're redefining a global as a function, don't transform it.
3764 if (!isa<llvm::Function>(Old)) return;
3766 replaceUsesOfNonProtoConstant(Old, NewFn);
3769 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3770 auto DK = VD->isThisDeclarationADefinition();
3771 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3774 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3775 // If we have a definition, this might be a deferred decl. If the
3776 // instantiation is explicit, make sure we emit it at the end.
3777 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3778 GetAddrOfGlobalVar(VD);
3780 EmitTopLevelDecl(VD);
3783 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3784 llvm::GlobalValue *GV) {
3785 const auto *D = cast<FunctionDecl>(GD.getDecl());
3787 // Compute the function info and LLVM type.
3788 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3789 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3791 // Get or create the prototype for the function.
3792 if (!GV || (GV->getType()->getElementType() != Ty))
3793 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3798 if (!GV->isDeclaration())
3801 // We need to set linkage and visibility on the function before
3802 // generating code for it because various parts of IR generation
3803 // want to propagate this information down (e.g. to local static
3805 auto *Fn = cast<llvm::Function>(GV);
3806 setFunctionLinkage(GD, Fn);
3808 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3809 setGVProperties(Fn, GD);
3811 MaybeHandleStaticInExternC(D, Fn);
3814 maybeSetTrivialComdat(*D, *Fn);
3816 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3818 setNonAliasAttributes(GD, Fn);
3819 SetLLVMFunctionAttributesForDefinition(D, Fn);
3821 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3822 AddGlobalCtor(Fn, CA->getPriority());
3823 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3824 AddGlobalDtor(Fn, DA->getPriority());
3825 if (D->hasAttr<AnnotateAttr>())
3826 AddGlobalAnnotations(D, Fn);
3828 if (D->isCPUSpecificMultiVersion()) {
3829 auto *Spec = D->getAttr<CPUSpecificAttr>();
3830 // If there is another specific version we need to emit, do so here.
3831 if (Spec->ActiveArgIndex + 1 < Spec->cpus_size()) {
3832 ++Spec->ActiveArgIndex;
3833 EmitGlobalFunctionDefinition(GD, nullptr);
3838 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3839 const auto *D = cast<ValueDecl>(GD.getDecl());
3840 const AliasAttr *AA = D->getAttr<AliasAttr>();
3841 assert(AA && "Not an alias?");
3843 StringRef MangledName = getMangledName(GD);
3845 if (AA->getAliasee() == MangledName) {
3846 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3850 // If there is a definition in the module, then it wins over the alias.
3851 // This is dubious, but allow it to be safe. Just ignore the alias.
3852 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3853 if (Entry && !Entry->isDeclaration())
3856 Aliases.push_back(GD);
3858 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3860 // Create a reference to the named value. This ensures that it is emitted
3861 // if a deferred decl.
3862 llvm::Constant *Aliasee;
3863 if (isa<llvm::FunctionType>(DeclTy))
3864 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3865 /*ForVTable=*/false);
3867 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3868 llvm::PointerType::getUnqual(DeclTy),
3871 // Create the new alias itself, but don't set a name yet.
3872 auto *GA = llvm::GlobalAlias::create(
3873 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3876 if (GA->getAliasee() == Entry) {
3877 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3881 assert(Entry->isDeclaration());
3883 // If there is a declaration in the module, then we had an extern followed
3884 // by the alias, as in:
3885 // extern int test6();
3887 // int test6() __attribute__((alias("test7")));
3889 // Remove it and replace uses of it with the alias.
3890 GA->takeName(Entry);
3892 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3894 Entry->eraseFromParent();
3896 GA->setName(MangledName);
3899 // Set attributes which are particular to an alias; this is a
3900 // specialization of the attributes which may be set on a global
3901 // variable/function.
3902 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3903 D->isWeakImported()) {
3904 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3907 if (const auto *VD = dyn_cast<VarDecl>(D))
3908 if (VD->getTLSKind())
3909 setTLSMode(GA, *VD);
3911 SetCommonAttributes(GD, GA);
3914 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3915 const auto *D = cast<ValueDecl>(GD.getDecl());
3916 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3917 assert(IFA && "Not an ifunc?");
3919 StringRef MangledName = getMangledName(GD);
3921 if (IFA->getResolver() == MangledName) {
3922 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3926 // Report an error if some definition overrides ifunc.
3927 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3928 if (Entry && !Entry->isDeclaration()) {
3930 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3931 DiagnosedConflictingDefinitions.insert(GD).second) {
3932 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name)
3934 Diags.Report(OtherGD.getDecl()->getLocation(),
3935 diag::note_previous_definition);
3940 Aliases.push_back(GD);
3942 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3943 llvm::Constant *Resolver =
3944 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3945 /*ForVTable=*/false);
3946 llvm::GlobalIFunc *GIF =
3947 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3948 "", Resolver, &getModule());
3950 if (GIF->getResolver() == Entry) {
3951 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3954 assert(Entry->isDeclaration());
3956 // If there is a declaration in the module, then we had an extern followed
3957 // by the ifunc, as in:
3958 // extern int test();
3960 // int test() __attribute__((ifunc("resolver")));
3962 // Remove it and replace uses of it with the ifunc.
3963 GIF->takeName(Entry);
3965 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3967 Entry->eraseFromParent();
3969 GIF->setName(MangledName);
3971 SetCommonAttributes(GD, GIF);
3974 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3975 ArrayRef<llvm::Type*> Tys) {
3976 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3980 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3981 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3982 const StringLiteral *Literal, bool TargetIsLSB,
3983 bool &IsUTF16, unsigned &StringLength) {
3984 StringRef String = Literal->getString();
3985 unsigned NumBytes = String.size();
3987 // Check for simple case.
3988 if (!Literal->containsNonAsciiOrNull()) {
3989 StringLength = NumBytes;
3990 return *Map.insert(std::make_pair(String, nullptr)).first;
3993 // Otherwise, convert the UTF8 literals into a string of shorts.
3996 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3997 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3998 llvm::UTF16 *ToPtr = &ToBuf[0];
4000 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
4001 ToPtr + NumBytes, llvm::strictConversion);
4003 // ConvertUTF8toUTF16 returns the length in ToPtr.
4004 StringLength = ToPtr - &ToBuf[0];
4006 // Add an explicit null.
4008 return *Map.insert(std::make_pair(
4009 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
4010 (StringLength + 1) * 2),
4015 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
4016 unsigned StringLength = 0;
4017 bool isUTF16 = false;
4018 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
4019 GetConstantCFStringEntry(CFConstantStringMap, Literal,
4020 getDataLayout().isLittleEndian(), isUTF16,
4023 if (auto *C = Entry.second)
4024 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
4026 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
4027 llvm::Constant *Zeros[] = { Zero, Zero };
4029 // If we don't already have it, get __CFConstantStringClassReference.
4030 if (!CFConstantStringClassRef) {
4031 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
4032 Ty = llvm::ArrayType::get(Ty, 0);
4033 llvm::GlobalValue *GV = cast<llvm::GlobalValue>(
4034 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference"));
4036 if (getTriple().isOSBinFormatCOFF()) {
4037 IdentifierInfo &II = getContext().Idents.get(GV->getName());
4038 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
4039 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
4041 const VarDecl *VD = nullptr;
4042 for (const auto &Result : DC->lookup(&II))
4043 if ((VD = dyn_cast<VarDecl>(Result)))
4046 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
4047 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
4048 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4050 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
4051 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
4056 // Decay array -> ptr
4057 CFConstantStringClassRef =
4058 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
4061 QualType CFTy = getContext().getCFConstantStringType();
4063 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
4065 ConstantInitBuilder Builder(*this);
4066 auto Fields = Builder.beginStruct(STy);
4069 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
4072 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
4075 llvm::Constant *C = nullptr;
4077 auto Arr = llvm::makeArrayRef(
4078 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
4079 Entry.first().size() / 2);
4080 C = llvm::ConstantDataArray::get(VMContext, Arr);
4082 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
4085 // Note: -fwritable-strings doesn't make the backing store strings of
4086 // CFStrings writable. (See <rdar://problem/10657500>)
4088 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
4089 llvm::GlobalValue::PrivateLinkage, C, ".str");
4090 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4091 // Don't enforce the target's minimum global alignment, since the only use
4092 // of the string is via this class initializer.
4093 CharUnits Align = isUTF16
4094 ? getContext().getTypeAlignInChars(getContext().ShortTy)
4095 : getContext().getTypeAlignInChars(getContext().CharTy);
4096 GV->setAlignment(Align.getQuantity());
4098 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
4099 // Without it LLVM can merge the string with a non unnamed_addr one during
4100 // LTO. Doing that changes the section it ends in, which surprises ld64.
4101 if (getTriple().isOSBinFormatMachO())
4102 GV->setSection(isUTF16 ? "__TEXT,__ustring"
4103 : "__TEXT,__cstring,cstring_literals");
4106 llvm::Constant *Str =
4107 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
4110 // Cast the UTF16 string to the correct type.
4111 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
4115 auto Ty = getTypes().ConvertType(getContext().LongTy);
4116 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
4118 CharUnits Alignment = getPointerAlign();
4121 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
4122 /*isConstant=*/false,
4123 llvm::GlobalVariable::PrivateLinkage);
4124 switch (getTriple().getObjectFormat()) {
4125 case llvm::Triple::UnknownObjectFormat:
4126 llvm_unreachable("unknown file format");
4127 case llvm::Triple::COFF:
4128 case llvm::Triple::ELF:
4129 case llvm::Triple::Wasm:
4130 GV->setSection("cfstring");
4132 case llvm::Triple::MachO:
4133 GV->setSection("__DATA,__cfstring");
4138 return ConstantAddress(GV, Alignment);
4141 bool CodeGenModule::getExpressionLocationsEnabled() const {
4142 return !CodeGenOpts.EmitCodeView || CodeGenOpts.DebugColumnInfo;
4145 QualType CodeGenModule::getObjCFastEnumerationStateType() {
4146 if (ObjCFastEnumerationStateType.isNull()) {
4147 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
4148 D->startDefinition();
4150 QualType FieldTypes[] = {
4151 Context.UnsignedLongTy,
4152 Context.getPointerType(Context.getObjCIdType()),
4153 Context.getPointerType(Context.UnsignedLongTy),
4154 Context.getConstantArrayType(Context.UnsignedLongTy,
4155 llvm::APInt(32, 5), ArrayType::Normal, 0)
4158 for (size_t i = 0; i < 4; ++i) {
4159 FieldDecl *Field = FieldDecl::Create(Context,
4162 SourceLocation(), nullptr,
4163 FieldTypes[i], /*TInfo=*/nullptr,
4164 /*BitWidth=*/nullptr,
4167 Field->setAccess(AS_public);
4171 D->completeDefinition();
4172 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
4175 return ObjCFastEnumerationStateType;
4179 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
4180 assert(!E->getType()->isPointerType() && "Strings are always arrays");
4182 // Don't emit it as the address of the string, emit the string data itself
4183 // as an inline array.
4184 if (E->getCharByteWidth() == 1) {
4185 SmallString<64> Str(E->getString());
4187 // Resize the string to the right size, which is indicated by its type.
4188 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
4189 Str.resize(CAT->getSize().getZExtValue());
4190 return llvm::ConstantDataArray::getString(VMContext, Str, false);
4193 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
4194 llvm::Type *ElemTy = AType->getElementType();
4195 unsigned NumElements = AType->getNumElements();
4197 // Wide strings have either 2-byte or 4-byte elements.
4198 if (ElemTy->getPrimitiveSizeInBits() == 16) {
4199 SmallVector<uint16_t, 32> Elements;
4200 Elements.reserve(NumElements);
4202 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4203 Elements.push_back(E->getCodeUnit(i));
4204 Elements.resize(NumElements);
4205 return llvm::ConstantDataArray::get(VMContext, Elements);
4208 assert(ElemTy->getPrimitiveSizeInBits() == 32);
4209 SmallVector<uint32_t, 32> Elements;
4210 Elements.reserve(NumElements);
4212 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
4213 Elements.push_back(E->getCodeUnit(i));
4214 Elements.resize(NumElements);
4215 return llvm::ConstantDataArray::get(VMContext, Elements);
4218 static llvm::GlobalVariable *
4219 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
4220 CodeGenModule &CGM, StringRef GlobalName,
4221 CharUnits Alignment) {
4222 unsigned AddrSpace = CGM.getContext().getTargetAddressSpace(
4223 CGM.getStringLiteralAddressSpace());
4225 llvm::Module &M = CGM.getModule();
4226 // Create a global variable for this string
4227 auto *GV = new llvm::GlobalVariable(
4228 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
4229 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
4230 GV->setAlignment(Alignment.getQuantity());
4231 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
4232 if (GV->isWeakForLinker()) {
4233 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
4234 GV->setComdat(M.getOrInsertComdat(GV->getName()));
4236 CGM.setDSOLocal(GV);
4241 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
4242 /// constant array for the given string literal.
4244 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
4246 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
4248 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
4249 llvm::GlobalVariable **Entry = nullptr;
4250 if (!LangOpts.WritableStrings) {
4251 Entry = &ConstantStringMap[C];
4252 if (auto GV = *Entry) {
4253 if (Alignment.getQuantity() > GV->getAlignment())
4254 GV->setAlignment(Alignment.getQuantity());
4255 return ConstantAddress(GV, Alignment);
4259 SmallString<256> MangledNameBuffer;
4260 StringRef GlobalVariableName;
4261 llvm::GlobalValue::LinkageTypes LT;
4263 // Mangle the string literal if the ABI allows for it. However, we cannot
4264 // do this if we are compiling with ASan or -fwritable-strings because they
4265 // rely on strings having normal linkage.
4266 if (!LangOpts.WritableStrings &&
4267 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
4268 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
4269 llvm::raw_svector_ostream Out(MangledNameBuffer);
4270 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
4272 LT = llvm::GlobalValue::LinkOnceODRLinkage;
4273 GlobalVariableName = MangledNameBuffer;
4275 LT = llvm::GlobalValue::PrivateLinkage;
4276 GlobalVariableName = Name;
4279 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
4283 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
4286 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4290 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
4291 /// array for the given ObjCEncodeExpr node.
4293 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
4295 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
4297 return GetAddrOfConstantCString(Str);
4300 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
4301 /// the literal and a terminating '\0' character.
4302 /// The result has pointer to array type.
4303 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
4304 const std::string &Str, const char *GlobalName) {
4305 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
4306 CharUnits Alignment =
4307 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
4310 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
4312 // Don't share any string literals if strings aren't constant.
4313 llvm::GlobalVariable **Entry = nullptr;
4314 if (!LangOpts.WritableStrings) {
4315 Entry = &ConstantStringMap[C];
4316 if (auto GV = *Entry) {
4317 if (Alignment.getQuantity() > GV->getAlignment())
4318 GV->setAlignment(Alignment.getQuantity());
4319 return ConstantAddress(GV, Alignment);
4323 // Get the default prefix if a name wasn't specified.
4325 GlobalName = ".str";
4326 // Create a global variable for this.
4327 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
4328 GlobalName, Alignment);
4332 return ConstantAddress(castStringLiteralToDefaultAddressSpace(*this, GV),
4336 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
4337 const MaterializeTemporaryExpr *E, const Expr *Init) {
4338 assert((E->getStorageDuration() == SD_Static ||
4339 E->getStorageDuration() == SD_Thread) && "not a global temporary");
4340 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
4342 // If we're not materializing a subobject of the temporary, keep the
4343 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
4344 QualType MaterializedType = Init->getType();
4345 if (Init == E->GetTemporaryExpr())
4346 MaterializedType = E->getType();
4348 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
4350 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
4351 return ConstantAddress(Slot, Align);
4353 // FIXME: If an externally-visible declaration extends multiple temporaries,
4354 // we need to give each temporary the same name in every translation unit (and
4355 // we also need to make the temporaries externally-visible).
4356 SmallString<256> Name;
4357 llvm::raw_svector_ostream Out(Name);
4358 getCXXABI().getMangleContext().mangleReferenceTemporary(
4359 VD, E->getManglingNumber(), Out);
4361 APValue *Value = nullptr;
4362 if (E->getStorageDuration() == SD_Static) {
4363 // We might have a cached constant initializer for this temporary. Note
4364 // that this might have a different value from the value computed by
4365 // evaluating the initializer if the surrounding constant expression
4366 // modifies the temporary.
4367 Value = getContext().getMaterializedTemporaryValue(E, false);
4368 if (Value && Value->isUninit())
4372 // Try evaluating it now, it might have a constant initializer.
4373 Expr::EvalResult EvalResult;
4374 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
4375 !EvalResult.hasSideEffects())
4376 Value = &EvalResult.Val;
4379 VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
4381 Optional<ConstantEmitter> emitter;
4382 llvm::Constant *InitialValue = nullptr;
4383 bool Constant = false;
4386 // The temporary has a constant initializer, use it.
4387 emitter.emplace(*this);
4388 InitialValue = emitter->emitForInitializer(*Value, AddrSpace,
4390 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
4391 Type = InitialValue->getType();
4393 // No initializer, the initialization will be provided when we
4394 // initialize the declaration which performed lifetime extension.
4395 Type = getTypes().ConvertTypeForMem(MaterializedType);
4398 // Create a global variable for this lifetime-extended temporary.
4399 llvm::GlobalValue::LinkageTypes Linkage =
4400 getLLVMLinkageVarDefinition(VD, Constant);
4401 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
4402 const VarDecl *InitVD;
4403 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
4404 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
4405 // Temporaries defined inside a class get linkonce_odr linkage because the
4406 // class can be defined in multiple translation units.
4407 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
4409 // There is no need for this temporary to have external linkage if the
4410 // VarDecl has external linkage.
4411 Linkage = llvm::GlobalVariable::InternalLinkage;
4414 auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
4415 auto *GV = new llvm::GlobalVariable(
4416 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
4417 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
4418 if (emitter) emitter->finalize(GV);
4419 setGVProperties(GV, VD);
4420 GV->setAlignment(Align.getQuantity());
4421 if (supportsCOMDAT() && GV->isWeakForLinker())
4422 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
4423 if (VD->getTLSKind())
4424 setTLSMode(GV, *VD);
4425 llvm::Constant *CV = GV;
4426 if (AddrSpace != LangAS::Default)
4427 CV = getTargetCodeGenInfo().performAddrSpaceCast(
4428 *this, GV, AddrSpace, LangAS::Default,
4430 getContext().getTargetAddressSpace(LangAS::Default)));
4431 MaterializedGlobalTemporaryMap[E] = CV;
4432 return ConstantAddress(CV, Align);
4435 /// EmitObjCPropertyImplementations - Emit information for synthesized
4436 /// properties for an implementation.
4437 void CodeGenModule::EmitObjCPropertyImplementations(const
4438 ObjCImplementationDecl *D) {
4439 for (const auto *PID : D->property_impls()) {
4440 // Dynamic is just for type-checking.
4441 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
4442 ObjCPropertyDecl *PD = PID->getPropertyDecl();
4444 // Determine which methods need to be implemented, some may have
4445 // been overridden. Note that ::isPropertyAccessor is not the method
4446 // we want, that just indicates if the decl came from a
4447 // property. What we want to know is if the method is defined in
4448 // this implementation.
4449 if (!D->getInstanceMethod(PD->getGetterName()))
4450 CodeGenFunction(*this).GenerateObjCGetter(
4451 const_cast<ObjCImplementationDecl *>(D), PID);
4452 if (!PD->isReadOnly() &&
4453 !D->getInstanceMethod(PD->getSetterName()))
4454 CodeGenFunction(*this).GenerateObjCSetter(
4455 const_cast<ObjCImplementationDecl *>(D), PID);
4460 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
4461 const ObjCInterfaceDecl *iface = impl->getClassInterface();
4462 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
4463 ivar; ivar = ivar->getNextIvar())
4464 if (ivar->getType().isDestructedType())
4470 static bool AllTrivialInitializers(CodeGenModule &CGM,
4471 ObjCImplementationDecl *D) {
4472 CodeGenFunction CGF(CGM);
4473 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
4474 E = D->init_end(); B != E; ++B) {
4475 CXXCtorInitializer *CtorInitExp = *B;
4476 Expr *Init = CtorInitExp->getInit();
4477 if (!CGF.isTrivialInitializer(Init))
4483 /// EmitObjCIvarInitializations - Emit information for ivar initialization
4484 /// for an implementation.
4485 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
4486 // We might need a .cxx_destruct even if we don't have any ivar initializers.
4487 if (needsDestructMethod(D)) {
4488 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
4489 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4490 ObjCMethodDecl *DTORMethod =
4491 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
4492 cxxSelector, getContext().VoidTy, nullptr, D,
4493 /*isInstance=*/true, /*isVariadic=*/false,
4494 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
4495 /*isDefined=*/false, ObjCMethodDecl::Required);
4496 D->addInstanceMethod(DTORMethod);
4497 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
4498 D->setHasDestructors(true);
4501 // If the implementation doesn't have any ivar initializers, we don't need
4502 // a .cxx_construct.
4503 if (D->getNumIvarInitializers() == 0 ||
4504 AllTrivialInitializers(*this, D))
4507 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
4508 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
4509 // The constructor returns 'self'.
4510 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
4514 getContext().getObjCIdType(),
4515 nullptr, D, /*isInstance=*/true,
4516 /*isVariadic=*/false,
4517 /*isPropertyAccessor=*/true,
4518 /*isImplicitlyDeclared=*/true,
4519 /*isDefined=*/false,
4520 ObjCMethodDecl::Required);
4521 D->addInstanceMethod(CTORMethod);
4522 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
4523 D->setHasNonZeroConstructors(true);
4526 // EmitLinkageSpec - Emit all declarations in a linkage spec.
4527 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
4528 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
4529 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
4530 ErrorUnsupported(LSD, "linkage spec");
4534 EmitDeclContext(LSD);
4537 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
4538 for (auto *I : DC->decls()) {
4539 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
4540 // are themselves considered "top-level", so EmitTopLevelDecl on an
4541 // ObjCImplDecl does not recursively visit them. We need to do that in
4542 // case they're nested inside another construct (LinkageSpecDecl /
4543 // ExportDecl) that does stop them from being considered "top-level".
4544 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
4545 for (auto *M : OID->methods())
4546 EmitTopLevelDecl(M);
4549 EmitTopLevelDecl(I);
4553 /// EmitTopLevelDecl - Emit code for a single top level declaration.
4554 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
4555 // Ignore dependent declarations.
4556 if (D->isTemplated())
4559 switch (D->getKind()) {
4560 case Decl::CXXConversion:
4561 case Decl::CXXMethod:
4562 case Decl::Function:
4563 EmitGlobal(cast<FunctionDecl>(D));
4564 // Always provide some coverage mapping
4565 // even for the functions that aren't emitted.
4566 AddDeferredUnusedCoverageMapping(D);
4569 case Decl::CXXDeductionGuide:
4570 // Function-like, but does not result in code emission.
4574 case Decl::Decomposition:
4575 case Decl::VarTemplateSpecialization:
4576 EmitGlobal(cast<VarDecl>(D));
4577 if (auto *DD = dyn_cast<DecompositionDecl>(D))
4578 for (auto *B : DD->bindings())
4579 if (auto *HD = B->getHoldingVar())
4583 // Indirect fields from global anonymous structs and unions can be
4584 // ignored; only the actual variable requires IR gen support.
4585 case Decl::IndirectField:
4589 case Decl::Namespace:
4590 EmitDeclContext(cast<NamespaceDecl>(D));
4592 case Decl::ClassTemplateSpecialization: {
4593 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4595 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4596 Spec->hasDefinition())
4597 DebugInfo->completeTemplateDefinition(*Spec);
4599 case Decl::CXXRecord:
4601 if (auto *ES = D->getASTContext().getExternalSource())
4602 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
4603 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
4605 // Emit any static data members, they may be definitions.
4606 for (auto *I : cast<CXXRecordDecl>(D)->decls())
4607 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
4608 EmitTopLevelDecl(I);
4610 // No code generation needed.
4611 case Decl::UsingShadow:
4612 case Decl::ClassTemplate:
4613 case Decl::VarTemplate:
4614 case Decl::VarTemplatePartialSpecialization:
4615 case Decl::FunctionTemplate:
4616 case Decl::TypeAliasTemplate:
4620 case Decl::Using: // using X; [C++]
4621 if (CGDebugInfo *DI = getModuleDebugInfo())
4622 DI->EmitUsingDecl(cast<UsingDecl>(*D));
4624 case Decl::NamespaceAlias:
4625 if (CGDebugInfo *DI = getModuleDebugInfo())
4626 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
4628 case Decl::UsingDirective: // using namespace X; [C++]
4629 if (CGDebugInfo *DI = getModuleDebugInfo())
4630 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
4632 case Decl::CXXConstructor:
4633 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
4635 case Decl::CXXDestructor:
4636 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
4639 case Decl::StaticAssert:
4643 // Objective-C Decls
4645 // Forward declarations, no (immediate) code generation.
4646 case Decl::ObjCInterface:
4647 case Decl::ObjCCategory:
4650 case Decl::ObjCProtocol: {
4651 auto *Proto = cast<ObjCProtocolDecl>(D);
4652 if (Proto->isThisDeclarationADefinition())
4653 ObjCRuntime->GenerateProtocol(Proto);
4657 case Decl::ObjCCategoryImpl:
4658 // Categories have properties but don't support synthesize so we
4659 // can ignore them here.
4660 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4663 case Decl::ObjCImplementation: {
4664 auto *OMD = cast<ObjCImplementationDecl>(D);
4665 EmitObjCPropertyImplementations(OMD);
4666 EmitObjCIvarInitializations(OMD);
4667 ObjCRuntime->GenerateClass(OMD);
4668 // Emit global variable debug information.
4669 if (CGDebugInfo *DI = getModuleDebugInfo())
4670 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4671 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4672 OMD->getClassInterface()), OMD->getLocation());
4675 case Decl::ObjCMethod: {
4676 auto *OMD = cast<ObjCMethodDecl>(D);
4677 // If this is not a prototype, emit the body.
4679 CodeGenFunction(*this).GenerateObjCMethod(OMD);
4682 case Decl::ObjCCompatibleAlias:
4683 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4686 case Decl::PragmaComment: {
4687 const auto *PCD = cast<PragmaCommentDecl>(D);
4688 switch (PCD->getCommentKind()) {
4690 llvm_unreachable("unexpected pragma comment kind");
4692 AppendLinkerOptions(PCD->getArg());
4695 if (getTarget().getTriple().isOSBinFormatELF() &&
4696 !getTarget().getTriple().isPS4())
4697 AddELFLibDirective(PCD->getArg());
4699 AddDependentLib(PCD->getArg());
4704 break; // We ignore all of these.
4709 case Decl::PragmaDetectMismatch: {
4710 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4711 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4715 case Decl::LinkageSpec:
4716 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4719 case Decl::FileScopeAsm: {
4720 // File-scope asm is ignored during device-side CUDA compilation.
4721 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4723 // File-scope asm is ignored during device-side OpenMP compilation.
4724 if (LangOpts.OpenMPIsDevice)
4726 auto *AD = cast<FileScopeAsmDecl>(D);
4727 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4731 case Decl::Import: {
4732 auto *Import = cast<ImportDecl>(D);
4734 // If we've already imported this module, we're done.
4735 if (!ImportedModules.insert(Import->getImportedModule()))
4738 // Emit debug information for direct imports.
4739 if (!Import->getImportedOwningModule()) {
4740 if (CGDebugInfo *DI = getModuleDebugInfo())
4741 DI->EmitImportDecl(*Import);
4744 // Find all of the submodules and emit the module initializers.
4745 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4746 SmallVector<clang::Module *, 16> Stack;
4747 Visited.insert(Import->getImportedModule());
4748 Stack.push_back(Import->getImportedModule());
4750 while (!Stack.empty()) {
4751 clang::Module *Mod = Stack.pop_back_val();
4752 if (!EmittedModuleInitializers.insert(Mod).second)
4755 for (auto *D : Context.getModuleInitializers(Mod))
4756 EmitTopLevelDecl(D);
4758 // Visit the submodules of this module.
4759 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4760 SubEnd = Mod->submodule_end();
4761 Sub != SubEnd; ++Sub) {
4762 // Skip explicit children; they need to be explicitly imported to emit
4763 // the initializers.
4764 if ((*Sub)->IsExplicit)
4767 if (Visited.insert(*Sub).second)
4768 Stack.push_back(*Sub);
4775 EmitDeclContext(cast<ExportDecl>(D));
4778 case Decl::OMPThreadPrivate:
4779 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4782 case Decl::OMPDeclareReduction:
4783 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4787 // Make sure we handled everything we should, every other kind is a
4788 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4789 // function. Need to recode Decl::Kind to do that easily.
4790 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4795 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4796 // Do we need to generate coverage mapping?
4797 if (!CodeGenOpts.CoverageMapping)
4799 switch (D->getKind()) {
4800 case Decl::CXXConversion:
4801 case Decl::CXXMethod:
4802 case Decl::Function:
4803 case Decl::ObjCMethod:
4804 case Decl::CXXConstructor:
4805 case Decl::CXXDestructor: {
4806 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4808 SourceManager &SM = getContext().getSourceManager();
4809 if (LimitedCoverage && SM.getMainFileID() != SM.getFileID(D->getLocStart()))
4811 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4812 if (I == DeferredEmptyCoverageMappingDecls.end())
4813 DeferredEmptyCoverageMappingDecls[D] = true;
4821 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4822 // Do we need to generate coverage mapping?
4823 if (!CodeGenOpts.CoverageMapping)
4825 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4826 if (Fn->isTemplateInstantiation())
4827 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4829 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4830 if (I == DeferredEmptyCoverageMappingDecls.end())
4831 DeferredEmptyCoverageMappingDecls[D] = false;
4836 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4837 // We call takeVector() here to avoid use-after-free.
4838 // FIXME: DeferredEmptyCoverageMappingDecls is getting mutated because
4839 // we deserialize function bodies to emit coverage info for them, and that
4840 // deserializes more declarations. How should we handle that case?
4841 for (const auto &Entry : DeferredEmptyCoverageMappingDecls.takeVector()) {
4844 const Decl *D = Entry.first;
4845 switch (D->getKind()) {
4846 case Decl::CXXConversion:
4847 case Decl::CXXMethod:
4848 case Decl::Function:
4849 case Decl::ObjCMethod: {
4850 CodeGenPGO PGO(*this);
4851 GlobalDecl GD(cast<FunctionDecl>(D));
4852 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4853 getFunctionLinkage(GD));
4856 case Decl::CXXConstructor: {
4857 CodeGenPGO PGO(*this);
4858 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4859 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4860 getFunctionLinkage(GD));
4863 case Decl::CXXDestructor: {
4864 CodeGenPGO PGO(*this);
4865 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4866 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4867 getFunctionLinkage(GD));
4876 /// Turns the given pointer into a constant.
4877 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4879 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4880 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4881 return llvm::ConstantInt::get(i64, PtrInt);
4884 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4885 llvm::NamedMDNode *&GlobalMetadata,
4887 llvm::GlobalValue *Addr) {
4888 if (!GlobalMetadata)
4890 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4892 // TODO: should we report variant information for ctors/dtors?
4893 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4894 llvm::ConstantAsMetadata::get(GetPointerConstant(
4895 CGM.getLLVMContext(), D.getDecl()))};
4896 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4899 /// For each function which is declared within an extern "C" region and marked
4900 /// as 'used', but has internal linkage, create an alias from the unmangled
4901 /// name to the mangled name if possible. People expect to be able to refer
4902 /// to such functions with an unmangled name from inline assembly within the
4903 /// same translation unit.
4904 void CodeGenModule::EmitStaticExternCAliases() {
4905 if (!getTargetCodeGenInfo().shouldEmitStaticExternCAliases())
4907 for (auto &I : StaticExternCValues) {
4908 IdentifierInfo *Name = I.first;
4909 llvm::GlobalValue *Val = I.second;
4910 if (Val && !getModule().getNamedValue(Name->getName()))
4911 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4915 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4916 GlobalDecl &Result) const {
4917 auto Res = Manglings.find(MangledName);
4918 if (Res == Manglings.end())
4920 Result = Res->getValue();
4924 /// Emits metadata nodes associating all the global values in the
4925 /// current module with the Decls they came from. This is useful for
4926 /// projects using IR gen as a subroutine.
4928 /// Since there's currently no way to associate an MDNode directly
4929 /// with an llvm::GlobalValue, we create a global named metadata
4930 /// with the name 'clang.global.decl.ptrs'.
4931 void CodeGenModule::EmitDeclMetadata() {
4932 llvm::NamedMDNode *GlobalMetadata = nullptr;
4934 for (auto &I : MangledDeclNames) {
4935 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4936 // Some mangled names don't necessarily have an associated GlobalValue
4937 // in this module, e.g. if we mangled it for DebugInfo.
4939 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4943 /// Emits metadata nodes for all the local variables in the current
4945 void CodeGenFunction::EmitDeclMetadata() {
4946 if (LocalDeclMap.empty()) return;
4948 llvm::LLVMContext &Context = getLLVMContext();
4950 // Find the unique metadata ID for this name.
4951 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4953 llvm::NamedMDNode *GlobalMetadata = nullptr;
4955 for (auto &I : LocalDeclMap) {
4956 const Decl *D = I.first;
4957 llvm::Value *Addr = I.second.getPointer();
4958 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4959 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4960 Alloca->setMetadata(
4961 DeclPtrKind, llvm::MDNode::get(
4962 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4963 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4964 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4965 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4970 void CodeGenModule::EmitVersionIdentMetadata() {
4971 llvm::NamedMDNode *IdentMetadata =
4972 TheModule.getOrInsertNamedMetadata("llvm.ident");
4973 std::string Version = getClangFullVersion();
4974 llvm::LLVMContext &Ctx = TheModule.getContext();
4976 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4977 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4980 void CodeGenModule::EmitTargetMetadata() {
4981 // Warning, new MangledDeclNames may be appended within this loop.
4982 // We rely on MapVector insertions adding new elements to the end
4983 // of the container.
4984 // FIXME: Move this loop into the one target that needs it, and only
4985 // loop over those declarations for which we couldn't emit the target
4986 // metadata when we emitted the declaration.
4987 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4988 auto Val = *(MangledDeclNames.begin() + I);
4989 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4990 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4991 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4995 void CodeGenModule::EmitCoverageFile() {
4996 if (getCodeGenOpts().CoverageDataFile.empty() &&
4997 getCodeGenOpts().CoverageNotesFile.empty())
5000 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
5004 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
5005 llvm::LLVMContext &Ctx = TheModule.getContext();
5006 auto *CoverageDataFile =
5007 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
5008 auto *CoverageNotesFile =
5009 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
5010 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
5011 llvm::MDNode *CU = CUNode->getOperand(i);
5012 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
5013 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
5017 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
5018 // Sema has checked that all uuid strings are of the form
5019 // "12345678-1234-1234-1234-1234567890ab".
5020 assert(Uuid.size() == 36);
5021 for (unsigned i = 0; i < 36; ++i) {
5022 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
5023 else assert(isHexDigit(Uuid[i]));
5026 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
5027 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
5029 llvm::Constant *Field3[8];
5030 for (unsigned Idx = 0; Idx < 8; ++Idx)
5031 Field3[Idx] = llvm::ConstantInt::get(
5032 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
5034 llvm::Constant *Fields[4] = {
5035 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
5036 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
5037 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
5038 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
5041 return llvm::ConstantStruct::getAnon(Fields);
5044 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
5046 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
5047 // FIXME: should we even be calling this method if RTTI is disabled
5048 // and it's not for EH?
5049 if ((!ForEH && !getLangOpts().RTTI) || getLangOpts().CUDAIsDevice)
5050 return llvm::Constant::getNullValue(Int8PtrTy);
5052 if (ForEH && Ty->isObjCObjectPointerType() &&
5053 LangOpts.ObjCRuntime.isGNUFamily())
5054 return ObjCRuntime->GetEHType(Ty);
5056 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
5059 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
5060 // Do not emit threadprivates in simd-only mode.
5061 if (LangOpts.OpenMP && LangOpts.OpenMPSimd)
5063 for (auto RefExpr : D->varlists()) {
5064 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
5066 VD->getAnyInitializer() &&
5067 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
5070 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
5071 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
5072 VD, Addr, RefExpr->getLocStart(), PerformInit))
5073 CXXGlobalInits.push_back(InitFunction);
5078 CodeGenModule::CreateMetadataIdentifierImpl(QualType T, MetadataTypeMap &Map,
5080 llvm::Metadata *&InternalId = Map[T.getCanonicalType()];
5084 if (isExternallyVisible(T->getLinkage())) {
5085 std::string OutName;
5086 llvm::raw_string_ostream Out(OutName);
5087 getCXXABI().getMangleContext().mangleTypeName(T, Out);
5090 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
5092 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
5093 llvm::ArrayRef<llvm::Metadata *>());
5099 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
5100 return CreateMetadataIdentifierImpl(T, MetadataIdMap, "");
5104 CodeGenModule::CreateMetadataIdentifierForVirtualMemPtrType(QualType T) {
5105 return CreateMetadataIdentifierImpl(T, VirtualMetadataIdMap, ".virtual");
5108 // Generalize pointer types to a void pointer with the qualifiers of the
5109 // originally pointed-to type, e.g. 'const char *' and 'char * const *'
5110 // generalize to 'const void *' while 'char *' and 'const char **' generalize to
5112 static QualType GeneralizeType(ASTContext &Ctx, QualType Ty) {
5113 if (!Ty->isPointerType())
5116 return Ctx.getPointerType(
5117 QualType(Ctx.VoidTy).withCVRQualifiers(
5118 Ty->getPointeeType().getCVRQualifiers()));
5121 // Apply type generalization to a FunctionType's return and argument types
5122 static QualType GeneralizeFunctionType(ASTContext &Ctx, QualType Ty) {
5123 if (auto *FnType = Ty->getAs<FunctionProtoType>()) {
5124 SmallVector<QualType, 8> GeneralizedParams;
5125 for (auto &Param : FnType->param_types())
5126 GeneralizedParams.push_back(GeneralizeType(Ctx, Param));
5128 return Ctx.getFunctionType(
5129 GeneralizeType(Ctx, FnType->getReturnType()),
5130 GeneralizedParams, FnType->getExtProtoInfo());
5133 if (auto *FnType = Ty->getAs<FunctionNoProtoType>())
5134 return Ctx.getFunctionNoProtoType(
5135 GeneralizeType(Ctx, FnType->getReturnType()));
5137 llvm_unreachable("Encountered unknown FunctionType");
5140 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierGeneralized(QualType T) {
5141 return CreateMetadataIdentifierImpl(GeneralizeFunctionType(getContext(), T),
5142 GeneralizedMetadataIdMap, ".generalized");
5145 /// Returns whether this module needs the "all-vtables" type identifier.
5146 bool CodeGenModule::NeedAllVtablesTypeId() const {
5147 // Returns true if at least one of vtable-based CFI checkers is enabled and
5148 // is not in the trapping mode.
5149 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
5150 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
5151 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
5152 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
5153 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
5154 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
5155 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
5156 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
5159 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
5161 const CXXRecordDecl *RD) {
5162 llvm::Metadata *MD =
5163 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
5164 VTable->addTypeMetadata(Offset.getQuantity(), MD);
5166 if (CodeGenOpts.SanitizeCfiCrossDso)
5167 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
5168 VTable->addTypeMetadata(Offset.getQuantity(),
5169 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
5171 if (NeedAllVtablesTypeId()) {
5172 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
5173 VTable->addTypeMetadata(Offset.getQuantity(), MD);
5177 TargetAttr::ParsedTargetAttr CodeGenModule::filterFunctionTargetAttrs(const TargetAttr *TD) {
5178 assert(TD != nullptr);
5179 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
5181 ParsedAttr.Features.erase(
5182 llvm::remove_if(ParsedAttr.Features,
5183 [&](const std::string &Feat) {
5184 return !Target.isValidFeatureName(
5185 StringRef{Feat}.substr(1));
5187 ParsedAttr.Features.end());
5192 // Fills in the supplied string map with the set of target features for the
5193 // passed in function.
5194 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
5195 const FunctionDecl *FD) {
5196 StringRef TargetCPU = Target.getTargetOpts().CPU;
5197 if (const auto *TD = FD->getAttr<TargetAttr>()) {
5198 TargetAttr::ParsedTargetAttr ParsedAttr = filterFunctionTargetAttrs(TD);
5200 // Make a copy of the features as passed on the command line into the
5201 // beginning of the additional features from the function to override.
5202 ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
5203 Target.getTargetOpts().FeaturesAsWritten.begin(),
5204 Target.getTargetOpts().FeaturesAsWritten.end());
5206 if (ParsedAttr.Architecture != "" &&
5207 Target.isValidCPUName(ParsedAttr.Architecture))
5208 TargetCPU = ParsedAttr.Architecture;
5210 // Now populate the feature map, first with the TargetCPU which is either
5211 // the default or a new one from the target attribute string. Then we'll use
5212 // the passed in features (FeaturesAsWritten) along with the new ones from
5214 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5215 ParsedAttr.Features);
5216 } else if (const auto *SD = FD->getAttr<CPUSpecificAttr>()) {
5217 llvm::SmallVector<StringRef, 32> FeaturesTmp;
5218 Target.getCPUSpecificCPUDispatchFeatures(SD->getCurCPUName()->getName(),
5220 std::vector<std::string> Features(FeaturesTmp.begin(), FeaturesTmp.end());
5221 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, Features);
5223 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
5224 Target.getTargetOpts().Features);
5228 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
5230 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
5235 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
5236 CodeGenFunction &CGF) {
5237 llvm::Constant *C = ConstantEmitter(CGF).emitAbstract(E, E->getType());
5238 auto SamplerT = getOpenCLRuntime().getSamplerType(E->getType().getTypePtr());
5239 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
5240 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
5241 "__translate_sampler_initializer"),