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 "CodeGenTBAA.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 const char AnnotationSection[] = "llvm.metadata";
65 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
66 switch (CGM.getTarget().getCXXABI().getKind()) {
67 case TargetCXXABI::GenericAArch64:
68 case TargetCXXABI::GenericARM:
69 case TargetCXXABI::iOS:
70 case TargetCXXABI::iOS64:
71 case TargetCXXABI::WatchOS:
72 case TargetCXXABI::GenericMIPS:
73 case TargetCXXABI::GenericItanium:
74 case TargetCXXABI::WebAssembly:
75 return CreateItaniumCXXABI(CGM);
76 case TargetCXXABI::Microsoft:
77 return CreateMicrosoftCXXABI(CGM);
80 llvm_unreachable("invalid C++ ABI kind");
83 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
84 const PreprocessorOptions &PPO,
85 const CodeGenOptions &CGO, llvm::Module &M,
86 DiagnosticsEngine &diags,
87 CoverageSourceInfo *CoverageInfo)
88 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
89 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
90 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
91 VMContext(M.getContext()), Types(*this), VTables(*this),
92 SanitizerMD(new SanitizerMetadata(*this)) {
94 // Initialize the type cache.
95 llvm::LLVMContext &LLVMContext = M.getContext();
96 VoidTy = llvm::Type::getVoidTy(LLVMContext);
97 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
98 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
99 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
101 FloatTy = llvm::Type::getFloatTy(LLVMContext);
102 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
103 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
104 PointerAlignInBytes =
105 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
107 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
109 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
110 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
111 IntPtrTy = llvm::IntegerType::get(LLVMContext,
112 C.getTargetInfo().getMaxPointerWidth());
113 Int8PtrTy = Int8Ty->getPointerTo(0);
114 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
115 AllocaInt8PtrTy = Int8Ty->getPointerTo(
116 M.getDataLayout().getAllocaAddrSpace());
117 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
119 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
120 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
125 createOpenCLRuntime();
127 createOpenMPRuntime();
131 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
132 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
133 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
134 TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
135 getCXXABI().getMangleContext()));
137 // If debug info or coverage generation is enabled, create the CGDebugInfo
139 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
140 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
141 DebugInfo.reset(new CGDebugInfo(*this));
143 Block.GlobalUniqueCount = 0;
145 if (C.getLangOpts().ObjC1)
146 ObjCData.reset(new ObjCEntrypoints());
148 if (CodeGenOpts.hasProfileClangUse()) {
149 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
150 CodeGenOpts.ProfileInstrumentUsePath);
151 if (auto E = ReaderOrErr.takeError()) {
152 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
153 "Could not read profile %0: %1");
154 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
155 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
159 PGOReader = std::move(ReaderOrErr.get());
162 // If coverage mapping generation is enabled, create the
163 // CoverageMappingModuleGen object.
164 if (CodeGenOpts.CoverageMapping)
165 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
168 CodeGenModule::~CodeGenModule() {}
170 void CodeGenModule::createObjCRuntime() {
171 // This is just isGNUFamily(), but we want to force implementors of
172 // new ABIs to decide how best to do this.
173 switch (LangOpts.ObjCRuntime.getKind()) {
174 case ObjCRuntime::GNUstep:
175 case ObjCRuntime::GCC:
176 case ObjCRuntime::ObjFW:
177 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
180 case ObjCRuntime::FragileMacOSX:
181 case ObjCRuntime::MacOSX:
182 case ObjCRuntime::iOS:
183 case ObjCRuntime::WatchOS:
184 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
187 llvm_unreachable("bad runtime kind");
190 void CodeGenModule::createOpenCLRuntime() {
191 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
194 void CodeGenModule::createOpenMPRuntime() {
195 // Select a specialized code generation class based on the target, if any.
196 // If it does not exist use the default implementation.
197 switch (getTriple().getArch()) {
198 case llvm::Triple::nvptx:
199 case llvm::Triple::nvptx64:
200 assert(getLangOpts().OpenMPIsDevice &&
201 "OpenMP NVPTX is only prepared to deal with device code.");
202 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
205 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
210 void CodeGenModule::createCUDARuntime() {
211 CUDARuntime.reset(CreateNVCUDARuntime(*this));
214 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
215 Replacements[Name] = C;
218 void CodeGenModule::applyReplacements() {
219 for (auto &I : Replacements) {
220 StringRef MangledName = I.first();
221 llvm::Constant *Replacement = I.second;
222 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
225 auto *OldF = cast<llvm::Function>(Entry);
226 auto *NewF = dyn_cast<llvm::Function>(Replacement);
228 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
229 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
231 auto *CE = cast<llvm::ConstantExpr>(Replacement);
232 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
233 CE->getOpcode() == llvm::Instruction::GetElementPtr);
234 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
238 // Replace old with new, but keep the old order.
239 OldF->replaceAllUsesWith(Replacement);
241 NewF->removeFromParent();
242 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
245 OldF->eraseFromParent();
249 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
250 GlobalValReplacements.push_back(std::make_pair(GV, C));
253 void CodeGenModule::applyGlobalValReplacements() {
254 for (auto &I : GlobalValReplacements) {
255 llvm::GlobalValue *GV = I.first;
256 llvm::Constant *C = I.second;
258 GV->replaceAllUsesWith(C);
259 GV->eraseFromParent();
263 // This is only used in aliases that we created and we know they have a
265 static const llvm::GlobalObject *getAliasedGlobal(
266 const llvm::GlobalIndirectSymbol &GIS) {
267 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
268 const llvm::Constant *C = &GIS;
270 C = C->stripPointerCasts();
271 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
273 // stripPointerCasts will not walk over weak aliases.
274 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
277 if (!Visited.insert(GIS2).second)
279 C = GIS2->getIndirectSymbol();
283 void CodeGenModule::checkAliases() {
284 // Check if the constructed aliases are well formed. It is really unfortunate
285 // that we have to do this in CodeGen, but we only construct mangled names
286 // and aliases during codegen.
288 DiagnosticsEngine &Diags = getDiags();
289 for (const GlobalDecl &GD : Aliases) {
290 const auto *D = cast<ValueDecl>(GD.getDecl());
291 SourceLocation Location;
292 bool IsIFunc = D->hasAttr<IFuncAttr>();
293 if (const Attr *A = D->getDefiningAttr())
294 Location = A->getLocation();
296 llvm_unreachable("Not an alias or ifunc?");
297 StringRef MangledName = getMangledName(GD);
298 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
299 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
300 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
303 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
304 } else if (GV->isDeclaration()) {
306 Diags.Report(Location, diag::err_alias_to_undefined)
307 << IsIFunc << IsIFunc;
308 } else if (IsIFunc) {
309 // Check resolver function type.
310 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
311 GV->getType()->getPointerElementType());
313 if (!FTy->getReturnType()->isPointerTy())
314 Diags.Report(Location, diag::err_ifunc_resolver_return);
315 if (FTy->getNumParams())
316 Diags.Report(Location, diag::err_ifunc_resolver_params);
319 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
320 llvm::GlobalValue *AliaseeGV;
321 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
322 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
324 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
326 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
327 StringRef AliasSection = SA->getName();
328 if (AliasSection != AliaseeGV->getSection())
329 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
330 << AliasSection << IsIFunc << IsIFunc;
333 // We have to handle alias to weak aliases in here. LLVM itself disallows
334 // this since the object semantics would not match the IL one. For
335 // compatibility with gcc we implement it by just pointing the alias
336 // to its aliasee's aliasee. We also warn, since the user is probably
337 // expecting the link to be weak.
338 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
339 if (GA->isInterposable()) {
340 Diags.Report(Location, diag::warn_alias_to_weak_alias)
341 << GV->getName() << GA->getName() << IsIFunc;
342 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
343 GA->getIndirectSymbol(), Alias->getType());
344 Alias->setIndirectSymbol(Aliasee);
351 for (const GlobalDecl &GD : Aliases) {
352 StringRef MangledName = getMangledName(GD);
353 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
354 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
355 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
356 Alias->eraseFromParent();
360 void CodeGenModule::clear() {
361 DeferredDeclsToEmit.clear();
363 OpenMPRuntime->clear();
366 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
367 StringRef MainFile) {
368 if (!hasDiagnostics())
370 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
371 if (MainFile.empty())
372 MainFile = "<stdin>";
373 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
376 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
379 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
383 void CodeGenModule::Release() {
385 EmitVTablesOpportunistically();
386 applyGlobalValReplacements();
389 EmitCXXGlobalInitFunc();
390 EmitCXXGlobalDtorFunc();
391 EmitCXXThreadLocalInitFunc();
393 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
394 AddGlobalCtor(ObjCInitFunction);
395 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
397 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
398 AddGlobalCtor(CudaCtorFunction);
399 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
400 AddGlobalDtor(CudaDtorFunction);
403 if (llvm::Function *OpenMPRegistrationFunction =
404 OpenMPRuntime->emitRegistrationFunction()) {
405 auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
406 OpenMPRegistrationFunction : nullptr;
407 AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
410 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
411 if (PGOStats.hasDiagnostics())
412 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
414 EmitCtorList(GlobalCtors, "llvm.global_ctors");
415 EmitCtorList(GlobalDtors, "llvm.global_dtors");
416 EmitGlobalAnnotations();
417 EmitStaticExternCAliases();
418 EmitDeferredUnusedCoverageMappings();
420 CoverageMapping->emit();
421 if (CodeGenOpts.SanitizeCfiCrossDso) {
422 CodeGenFunction(*this).EmitCfiCheckFail();
423 CodeGenFunction(*this).EmitCfiCheckStub();
425 emitAtAvailableLinkGuard();
430 if (CodeGenOpts.Autolink &&
431 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
432 EmitModuleLinkOptions();
435 // Record mregparm value now so it is visible through rest of codegen.
436 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
437 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
438 CodeGenOpts.NumRegisterParameters);
440 if (CodeGenOpts.DwarfVersion) {
441 // We actually want the latest version when there are conflicts.
442 // We can change from Warning to Latest if such mode is supported.
443 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
444 CodeGenOpts.DwarfVersion);
446 if (CodeGenOpts.EmitCodeView) {
447 // Indicate that we want CodeView in the metadata.
448 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
450 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
451 // We don't support LTO with 2 with different StrictVTablePointers
452 // FIXME: we could support it by stripping all the information introduced
453 // by StrictVTablePointers.
455 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
457 llvm::Metadata *Ops[2] = {
458 llvm::MDString::get(VMContext, "StrictVTablePointers"),
459 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
460 llvm::Type::getInt32Ty(VMContext), 1))};
462 getModule().addModuleFlag(llvm::Module::Require,
463 "StrictVTablePointersRequirement",
464 llvm::MDNode::get(VMContext, Ops));
467 // We support a single version in the linked module. The LLVM
468 // parser will drop debug info with a different version number
469 // (and warn about it, too).
470 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
471 llvm::DEBUG_METADATA_VERSION);
473 // Width of wchar_t in bytes
474 uint64_t WCharWidth =
475 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
476 assert((LangOpts.ShortWChar ||
477 llvm::TargetLibraryInfoImpl::getTargetWCharSize(Target.getTriple()) ==
478 Target.getWCharWidth() / 8) &&
479 "LLVM wchar_t size out of sync");
481 // We need to record the widths of enums and wchar_t, so that we can generate
482 // the correct build attributes in the ARM backend. wchar_size is also used by
483 // TargetLibraryInfo.
484 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
486 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
487 if ( Arch == llvm::Triple::arm
488 || Arch == llvm::Triple::armeb
489 || Arch == llvm::Triple::thumb
490 || Arch == llvm::Triple::thumbeb) {
491 // The minimum width of an enum in bytes
492 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
493 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
496 if (CodeGenOpts.SanitizeCfiCrossDso) {
497 // Indicate that we want cross-DSO control flow integrity checks.
498 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
501 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
502 // Indicate whether __nvvm_reflect should be configured to flush denormal
503 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
505 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
506 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
509 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
510 assert(PLevel < 3 && "Invalid PIC Level");
511 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
512 if (Context.getLangOpts().PIE)
513 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
516 SimplifyPersonality();
518 if (getCodeGenOpts().EmitDeclMetadata)
521 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
525 DebugInfo->finalize();
527 EmitVersionIdentMetadata();
529 EmitTargetMetadata();
532 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
533 // Make sure that this type is translated.
534 Types.UpdateCompletedType(TD);
537 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
538 // Make sure that this type is translated.
539 Types.RefreshTypeCacheForClass(RD);
542 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
545 return TBAA->getTBAAInfo(QTy);
548 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
551 return TBAA->getTBAAInfoForVTablePtr();
554 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
557 return TBAA->getTBAAStructInfo(QTy);
560 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
561 llvm::MDNode *AccessN,
565 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
568 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
569 /// and struct-path aware TBAA, the tag has the same format:
570 /// base type, access type and offset.
571 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
572 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
573 llvm::MDNode *TBAAInfo,
574 bool ConvertTypeToTag) {
575 if (ConvertTypeToTag && TBAA)
576 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
577 TBAA->getTBAAScalarTagInfo(TBAAInfo));
579 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
582 void CodeGenModule::DecorateInstructionWithInvariantGroup(
583 llvm::Instruction *I, const CXXRecordDecl *RD) {
584 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
585 llvm::MDNode::get(getLLVMContext(), {}));
588 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
589 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
590 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
593 /// ErrorUnsupported - Print out an error that codegen doesn't support the
594 /// specified stmt yet.
595 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
596 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
597 "cannot compile this %0 yet");
598 std::string Msg = Type;
599 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
600 << Msg << S->getSourceRange();
603 /// ErrorUnsupported - Print out an error that codegen doesn't support the
604 /// specified decl yet.
605 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
606 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
607 "cannot compile this %0 yet");
608 std::string Msg = Type;
609 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
612 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
613 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
616 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
617 const NamedDecl *D) const {
618 // Internal definitions always have default visibility.
619 if (GV->hasLocalLinkage()) {
620 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
624 // Set visibility for definitions.
625 LinkageInfo LV = D->getLinkageAndVisibility();
626 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
627 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
630 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
631 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
632 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
633 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
634 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
635 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
638 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
639 CodeGenOptions::TLSModel M) {
641 case CodeGenOptions::GeneralDynamicTLSModel:
642 return llvm::GlobalVariable::GeneralDynamicTLSModel;
643 case CodeGenOptions::LocalDynamicTLSModel:
644 return llvm::GlobalVariable::LocalDynamicTLSModel;
645 case CodeGenOptions::InitialExecTLSModel:
646 return llvm::GlobalVariable::InitialExecTLSModel;
647 case CodeGenOptions::LocalExecTLSModel:
648 return llvm::GlobalVariable::LocalExecTLSModel;
650 llvm_unreachable("Invalid TLS model!");
653 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
654 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
656 llvm::GlobalValue::ThreadLocalMode TLM;
657 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
659 // Override the TLS model if it is explicitly specified.
660 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
661 TLM = GetLLVMTLSModel(Attr->getModel());
664 GV->setThreadLocalMode(TLM);
667 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
668 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
670 // Some ABIs don't have constructor variants. Make sure that base and
671 // complete constructors get mangled the same.
672 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
673 if (!getTarget().getCXXABI().hasConstructorVariants()) {
674 CXXCtorType OrigCtorType = GD.getCtorType();
675 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
676 if (OrigCtorType == Ctor_Base)
677 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
681 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
682 if (!FoundStr.empty())
685 const auto *ND = cast<NamedDecl>(GD.getDecl());
686 SmallString<256> Buffer;
688 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
689 llvm::raw_svector_ostream Out(Buffer);
690 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
691 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
692 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
693 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
695 getCXXABI().getMangleContext().mangleName(ND, Out);
698 IdentifierInfo *II = ND->getIdentifier();
699 assert(II && "Attempt to mangle unnamed decl.");
700 const auto *FD = dyn_cast<FunctionDecl>(ND);
703 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
704 llvm::raw_svector_ostream Out(Buffer);
705 Out << "__regcall3__" << II->getName();
712 // Keep the first result in the case of a mangling collision.
713 auto Result = Manglings.insert(std::make_pair(Str, GD));
714 return FoundStr = Result.first->first();
717 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
718 const BlockDecl *BD) {
719 MangleContext &MangleCtx = getCXXABI().getMangleContext();
720 const Decl *D = GD.getDecl();
722 SmallString<256> Buffer;
723 llvm::raw_svector_ostream Out(Buffer);
725 MangleCtx.mangleGlobalBlock(BD,
726 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
727 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
728 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
729 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
730 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
732 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
734 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
735 return Result.first->first();
738 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
739 return getModule().getNamedValue(Name);
742 /// AddGlobalCtor - Add a function to the list that will be called before
744 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
745 llvm::Constant *AssociatedData) {
746 // FIXME: Type coercion of void()* types.
747 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
750 /// AddGlobalDtor - Add a function to the list that will be called
751 /// when the module is unloaded.
752 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
753 // FIXME: Type coercion of void()* types.
754 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
757 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
758 if (Fns.empty()) return;
760 // Ctor function type is void()*.
761 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
762 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
764 // Get the type of a ctor entry, { i32, void ()*, i8* }.
765 llvm::StructType *CtorStructTy = llvm::StructType::get(
766 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
768 // Construct the constructor and destructor arrays.
769 ConstantInitBuilder builder(*this);
770 auto ctors = builder.beginArray(CtorStructTy);
771 for (const auto &I : Fns) {
772 auto ctor = ctors.beginStruct(CtorStructTy);
773 ctor.addInt(Int32Ty, I.Priority);
774 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
775 if (I.AssociatedData)
776 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
778 ctor.addNullPointer(VoidPtrTy);
779 ctor.finishAndAddTo(ctors);
783 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
785 llvm::GlobalValue::AppendingLinkage);
787 // The LTO linker doesn't seem to like it when we set an alignment
788 // on appending variables. Take it off as a workaround.
789 list->setAlignment(0);
794 llvm::GlobalValue::LinkageTypes
795 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
796 const auto *D = cast<FunctionDecl>(GD.getDecl());
798 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
800 if (isa<CXXDestructorDecl>(D) &&
801 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
803 // Destructor variants in the Microsoft C++ ABI are always internal or
804 // linkonce_odr thunks emitted on an as-needed basis.
805 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
806 : llvm::GlobalValue::LinkOnceODRLinkage;
809 if (isa<CXXConstructorDecl>(D) &&
810 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
811 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
812 // Our approach to inheriting constructors is fundamentally different from
813 // that used by the MS ABI, so keep our inheriting constructor thunks
814 // internal rather than trying to pick an unambiguous mangling for them.
815 return llvm::GlobalValue::InternalLinkage;
818 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
821 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
822 const auto *FD = cast<FunctionDecl>(GD.getDecl());
824 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
825 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
826 // Don't dllexport/import destructor thunks.
827 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
832 if (FD->hasAttr<DLLImportAttr>())
833 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
834 else if (FD->hasAttr<DLLExportAttr>())
835 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
837 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
840 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
841 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
842 if (!MDS) return nullptr;
844 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
847 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
849 setNonAliasAttributes(D, F);
852 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
853 const CGFunctionInfo &Info,
855 unsigned CallingConv;
856 llvm::AttributeList PAL;
857 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
858 F->setAttributes(PAL);
859 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
862 /// Determines whether the language options require us to model
863 /// unwind exceptions. We treat -fexceptions as mandating this
864 /// except under the fragile ObjC ABI with only ObjC exceptions
865 /// enabled. This means, for example, that C with -fexceptions
867 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
868 // If exceptions are completely disabled, obviously this is false.
869 if (!LangOpts.Exceptions) return false;
871 // If C++ exceptions are enabled, this is true.
872 if (LangOpts.CXXExceptions) return true;
874 // If ObjC exceptions are enabled, this depends on the ABI.
875 if (LangOpts.ObjCExceptions) {
876 return LangOpts.ObjCRuntime.hasUnwindExceptions();
882 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
886 if (CodeGenOpts.UnwindTables)
887 B.addAttribute(llvm::Attribute::UWTable);
889 if (!hasUnwindExceptions(LangOpts))
890 B.addAttribute(llvm::Attribute::NoUnwind);
892 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
893 B.addAttribute(llvm::Attribute::StackProtect);
894 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
895 B.addAttribute(llvm::Attribute::StackProtectStrong);
896 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
897 B.addAttribute(llvm::Attribute::StackProtectReq);
900 // If we don't have a declaration to control inlining, the function isn't
901 // explicitly marked as alwaysinline for semantic reasons, and inlining is
902 // disabled, mark the function as noinline.
903 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
904 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
905 B.addAttribute(llvm::Attribute::NoInline);
907 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
911 // Track whether we need to add the optnone LLVM attribute,
912 // starting with the default for this optimization level.
913 bool ShouldAddOptNone =
914 !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
915 // We can't add optnone in the following cases, it won't pass the verifier.
916 ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
917 ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
918 ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
920 if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
921 B.addAttribute(llvm::Attribute::OptimizeNone);
923 // OptimizeNone implies noinline; we should not be inlining such functions.
924 B.addAttribute(llvm::Attribute::NoInline);
925 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
926 "OptimizeNone and AlwaysInline on same function!");
928 // We still need to handle naked functions even though optnone subsumes
929 // much of their semantics.
930 if (D->hasAttr<NakedAttr>())
931 B.addAttribute(llvm::Attribute::Naked);
933 // OptimizeNone wins over OptimizeForSize and MinSize.
934 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
935 F->removeFnAttr(llvm::Attribute::MinSize);
936 } else if (D->hasAttr<NakedAttr>()) {
937 // Naked implies noinline: we should not be inlining such functions.
938 B.addAttribute(llvm::Attribute::Naked);
939 B.addAttribute(llvm::Attribute::NoInline);
940 } else if (D->hasAttr<NoDuplicateAttr>()) {
941 B.addAttribute(llvm::Attribute::NoDuplicate);
942 } else if (D->hasAttr<NoInlineAttr>()) {
943 B.addAttribute(llvm::Attribute::NoInline);
944 } else if (D->hasAttr<AlwaysInlineAttr>() &&
945 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
946 // (noinline wins over always_inline, and we can't specify both in IR)
947 B.addAttribute(llvm::Attribute::AlwaysInline);
948 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
949 // If we're not inlining, then force everything that isn't always_inline to
950 // carry an explicit noinline attribute.
951 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
952 B.addAttribute(llvm::Attribute::NoInline);
954 // Otherwise, propagate the inline hint attribute and potentially use its
955 // absence to mark things as noinline.
956 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
957 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
958 return Redecl->isInlineSpecified();
960 B.addAttribute(llvm::Attribute::InlineHint);
961 } else if (CodeGenOpts.getInlining() ==
962 CodeGenOptions::OnlyHintInlining &&
964 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
965 B.addAttribute(llvm::Attribute::NoInline);
970 // Add other optimization related attributes if we are optimizing this
972 if (!D->hasAttr<OptimizeNoneAttr>()) {
973 if (D->hasAttr<ColdAttr>()) {
974 if (!ShouldAddOptNone)
975 B.addAttribute(llvm::Attribute::OptimizeForSize);
976 B.addAttribute(llvm::Attribute::Cold);
979 if (D->hasAttr<MinSizeAttr>())
980 B.addAttribute(llvm::Attribute::MinSize);
983 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
985 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
987 F->setAlignment(alignment);
989 // Some C++ ABIs require 2-byte alignment for member functions, in order to
990 // reserve a bit for differentiating between virtual and non-virtual member
991 // functions. If the current target's C++ ABI requires this and this is a
992 // member function, set its alignment accordingly.
993 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
994 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
998 // In the cross-dso CFI mode, we want !type attributes on definitions only.
999 if (CodeGenOpts.SanitizeCfiCrossDso)
1000 if (auto *FD = dyn_cast<FunctionDecl>(D))
1001 CreateFunctionTypeMetadata(FD, F);
1004 void CodeGenModule::SetCommonAttributes(const Decl *D,
1005 llvm::GlobalValue *GV) {
1006 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
1007 setGlobalVisibility(GV, ND);
1009 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1011 if (D && D->hasAttr<UsedAttr>())
1015 void CodeGenModule::setAliasAttributes(const Decl *D,
1016 llvm::GlobalValue *GV) {
1017 SetCommonAttributes(D, GV);
1019 // Process the dllexport attribute based on whether the original definition
1020 // (not necessarily the aliasee) was exported.
1021 if (D->hasAttr<DLLExportAttr>())
1022 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1025 void CodeGenModule::setNonAliasAttributes(const Decl *D,
1026 llvm::GlobalObject *GO) {
1027 SetCommonAttributes(D, GO);
1030 if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1031 if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1032 GV->addAttribute("bss-section", SA->getName());
1033 if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1034 GV->addAttribute("data-section", SA->getName());
1035 if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1036 GV->addAttribute("rodata-section", SA->getName());
1039 if (auto *F = dyn_cast<llvm::Function>(GO)) {
1040 if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1041 if (!D->getAttr<SectionAttr>())
1042 F->addFnAttr("implicit-section-name", SA->getName());
1045 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1046 GO->setSection(SA->getName());
1049 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1052 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1054 const CGFunctionInfo &FI) {
1055 SetLLVMFunctionAttributes(D, FI, F);
1056 SetLLVMFunctionAttributesForDefinition(D, F);
1058 F->setLinkage(llvm::Function::InternalLinkage);
1060 setNonAliasAttributes(D, F);
1063 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
1064 const NamedDecl *ND) {
1065 // Set linkage and visibility in case we never see a definition.
1066 LinkageInfo LV = ND->getLinkageAndVisibility();
1067 if (LV.getLinkage() != ExternalLinkage) {
1068 // Don't set internal linkage on declarations.
1070 if (ND->hasAttr<DLLImportAttr>()) {
1071 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1072 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1073 } else if (ND->hasAttr<DLLExportAttr>()) {
1074 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1075 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
1076 // "extern_weak" is overloaded in LLVM; we probably should have
1077 // separate linkage types for this.
1078 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1081 // Set visibility on a declaration only if it's explicit.
1082 if (LV.isVisibilityExplicit())
1083 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
1087 void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1088 llvm::Function *F) {
1089 // Only if we are checking indirect calls.
1090 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1093 // Non-static class methods are handled via vtable pointer checks elsewhere.
1094 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1097 // Additionally, if building with cross-DSO support...
1098 if (CodeGenOpts.SanitizeCfiCrossDso) {
1099 // Skip available_externally functions. They won't be codegen'ed in the
1100 // current module anyway.
1101 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1105 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1106 F->addTypeMetadata(0, MD);
1108 // Emit a hash-based bit set entry for cross-DSO calls.
1109 if (CodeGenOpts.SanitizeCfiCrossDso)
1110 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1111 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1114 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1115 bool IsIncompleteFunction,
1117 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1118 // If this is an intrinsic function, set the function's attributes
1119 // to the intrinsic's attributes.
1120 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1124 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1126 if (!IsIncompleteFunction)
1127 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1129 // Add the Returned attribute for "this", except for iOS 5 and earlier
1130 // where substantial code, including the libstdc++ dylib, was compiled with
1131 // GCC and does not actually return "this".
1132 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1133 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1134 assert(!F->arg_empty() &&
1135 F->arg_begin()->getType()
1136 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1137 "unexpected this return");
1138 F->addAttribute(1, llvm::Attribute::Returned);
1141 // Only a few attributes are set on declarations; these may later be
1142 // overridden by a definition.
1144 setLinkageAndVisibilityForGV(F, FD);
1146 if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1147 F->addFnAttr("implicit-section-name");
1150 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1151 F->setSection(SA->getName());
1153 if (FD->isReplaceableGlobalAllocationFunction()) {
1154 // A replaceable global allocation function does not act like a builtin by
1155 // default, only if it is invoked by a new-expression or delete-expression.
1156 F->addAttribute(llvm::AttributeList::FunctionIndex,
1157 llvm::Attribute::NoBuiltin);
1159 // A sane operator new returns a non-aliasing pointer.
1160 // FIXME: Also add NonNull attribute to the return value
1161 // for the non-nothrow forms?
1162 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1163 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1164 (Kind == OO_New || Kind == OO_Array_New))
1165 F->addAttribute(llvm::AttributeList::ReturnIndex,
1166 llvm::Attribute::NoAlias);
1169 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1170 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1171 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1172 if (MD->isVirtual())
1173 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1175 // Don't emit entries for function declarations in the cross-DSO mode. This
1176 // is handled with better precision by the receiving DSO.
1177 if (!CodeGenOpts.SanitizeCfiCrossDso)
1178 CreateFunctionTypeMetadata(FD, F);
1181 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1182 assert(!GV->isDeclaration() &&
1183 "Only globals with definition can force usage.");
1184 LLVMUsed.emplace_back(GV);
1187 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1188 assert(!GV->isDeclaration() &&
1189 "Only globals with definition can force usage.");
1190 LLVMCompilerUsed.emplace_back(GV);
1193 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1194 std::vector<llvm::WeakTrackingVH> &List) {
1195 // Don't create llvm.used if there is no need.
1199 // Convert List to what ConstantArray needs.
1200 SmallVector<llvm::Constant*, 8> UsedArray;
1201 UsedArray.resize(List.size());
1202 for (unsigned i = 0, e = List.size(); i != e; ++i) {
1204 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1205 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1208 if (UsedArray.empty())
1210 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1212 auto *GV = new llvm::GlobalVariable(
1213 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1214 llvm::ConstantArray::get(ATy, UsedArray), Name);
1216 GV->setSection("llvm.metadata");
1219 void CodeGenModule::emitLLVMUsed() {
1220 emitUsed(*this, "llvm.used", LLVMUsed);
1221 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1224 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1225 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1226 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1229 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1230 llvm::SmallString<32> Opt;
1231 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1232 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1233 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1236 void CodeGenModule::AddDependentLib(StringRef Lib) {
1237 llvm::SmallString<24> Opt;
1238 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1239 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1240 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1243 /// \brief Add link options implied by the given module, including modules
1244 /// it depends on, using a postorder walk.
1245 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1246 SmallVectorImpl<llvm::MDNode *> &Metadata,
1247 llvm::SmallPtrSet<Module *, 16> &Visited) {
1248 // Import this module's parent.
1249 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1250 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1253 // Import this module's dependencies.
1254 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1255 if (Visited.insert(Mod->Imports[I - 1]).second)
1256 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1259 // Add linker options to link against the libraries/frameworks
1260 // described by this module.
1261 llvm::LLVMContext &Context = CGM.getLLVMContext();
1262 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1263 // Link against a framework. Frameworks are currently Darwin only, so we
1264 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1265 if (Mod->LinkLibraries[I-1].IsFramework) {
1266 llvm::Metadata *Args[2] = {
1267 llvm::MDString::get(Context, "-framework"),
1268 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1270 Metadata.push_back(llvm::MDNode::get(Context, Args));
1274 // Link against a library.
1275 llvm::SmallString<24> Opt;
1276 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1277 Mod->LinkLibraries[I-1].Library, Opt);
1278 auto *OptString = llvm::MDString::get(Context, Opt);
1279 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1283 void CodeGenModule::EmitModuleLinkOptions() {
1284 // Collect the set of all of the modules we want to visit to emit link
1285 // options, which is essentially the imported modules and all of their
1286 // non-explicit child modules.
1287 llvm::SetVector<clang::Module *> LinkModules;
1288 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1289 SmallVector<clang::Module *, 16> Stack;
1291 // Seed the stack with imported modules.
1292 for (Module *M : ImportedModules) {
1293 // Do not add any link flags when an implementation TU of a module imports
1294 // a header of that same module.
1295 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1296 !getLangOpts().isCompilingModule())
1298 if (Visited.insert(M).second)
1302 // Find all of the modules to import, making a little effort to prune
1303 // non-leaf modules.
1304 while (!Stack.empty()) {
1305 clang::Module *Mod = Stack.pop_back_val();
1307 bool AnyChildren = false;
1309 // Visit the submodules of this module.
1310 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1311 SubEnd = Mod->submodule_end();
1312 Sub != SubEnd; ++Sub) {
1313 // Skip explicit children; they need to be explicitly imported to be
1315 if ((*Sub)->IsExplicit)
1318 if (Visited.insert(*Sub).second) {
1319 Stack.push_back(*Sub);
1324 // We didn't find any children, so add this module to the list of
1325 // modules to link against.
1327 LinkModules.insert(Mod);
1331 // Add link options for all of the imported modules in reverse topological
1332 // order. We don't do anything to try to order import link flags with respect
1333 // to linker options inserted by things like #pragma comment().
1334 SmallVector<llvm::MDNode *, 16> MetadataArgs;
1336 for (Module *M : LinkModules)
1337 if (Visited.insert(M).second)
1338 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1339 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1340 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1342 // Add the linker options metadata flag.
1343 auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
1344 for (auto *MD : LinkerOptionsMetadata)
1345 NMD->addOperand(MD);
1348 void CodeGenModule::EmitDeferred() {
1349 // Emit code for any potentially referenced deferred decls. Since a
1350 // previously unused static decl may become used during the generation of code
1351 // for a static function, iterate until no changes are made.
1353 if (!DeferredVTables.empty()) {
1354 EmitDeferredVTables();
1356 // Emitting a vtable doesn't directly cause more vtables to
1357 // become deferred, although it can cause functions to be
1358 // emitted that then need those vtables.
1359 assert(DeferredVTables.empty());
1362 // Stop if we're out of both deferred vtables and deferred declarations.
1363 if (DeferredDeclsToEmit.empty())
1366 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1367 // work, it will not interfere with this.
1368 std::vector<GlobalDecl> CurDeclsToEmit;
1369 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1371 for (GlobalDecl &D : CurDeclsToEmit) {
1372 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1373 // to get GlobalValue with exactly the type we need, not something that
1374 // might had been created for another decl with the same mangled name but
1376 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1377 GetAddrOfGlobal(D, ForDefinition));
1379 // In case of different address spaces, we may still get a cast, even with
1380 // IsForDefinition equal to true. Query mangled names table to get
1383 GV = GetGlobalValue(getMangledName(D));
1385 // Make sure GetGlobalValue returned non-null.
1388 // Check to see if we've already emitted this. This is necessary
1389 // for a couple of reasons: first, decls can end up in the
1390 // deferred-decls queue multiple times, and second, decls can end
1391 // up with definitions in unusual ways (e.g. by an extern inline
1392 // function acquiring a strong function redefinition). Just
1393 // ignore these cases.
1394 if (!GV->isDeclaration())
1397 // Otherwise, emit the definition and move on to the next one.
1398 EmitGlobalDefinition(D, GV);
1400 // If we found out that we need to emit more decls, do that recursively.
1401 // This has the advantage that the decls are emitted in a DFS and related
1402 // ones are close together, which is convenient for testing.
1403 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1405 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1410 void CodeGenModule::EmitVTablesOpportunistically() {
1411 // Try to emit external vtables as available_externally if they have emitted
1412 // all inlined virtual functions. It runs after EmitDeferred() and therefore
1413 // is not allowed to create new references to things that need to be emitted
1414 // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1416 assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1417 && "Only emit opportunistic vtables with optimizations");
1419 for (const CXXRecordDecl *RD : OpportunisticVTables) {
1420 assert(getVTables().isVTableExternal(RD) &&
1421 "This queue should only contain external vtables");
1422 if (getCXXABI().canSpeculativelyEmitVTable(RD))
1423 VTables.GenerateClassData(RD);
1425 OpportunisticVTables.clear();
1428 void CodeGenModule::EmitGlobalAnnotations() {
1429 if (Annotations.empty())
1432 // Create a new global variable for the ConstantStruct in the Module.
1433 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1434 Annotations[0]->getType(), Annotations.size()), Annotations);
1435 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1436 llvm::GlobalValue::AppendingLinkage,
1437 Array, "llvm.global.annotations");
1438 gv->setSection(AnnotationSection);
1441 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1442 llvm::Constant *&AStr = AnnotationStrings[Str];
1446 // Not found yet, create a new global.
1447 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1449 new llvm::GlobalVariable(getModule(), s->getType(), true,
1450 llvm::GlobalValue::PrivateLinkage, s, ".str");
1451 gv->setSection(AnnotationSection);
1452 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1457 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1458 SourceManager &SM = getContext().getSourceManager();
1459 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1461 return EmitAnnotationString(PLoc.getFilename());
1462 return EmitAnnotationString(SM.getBufferName(Loc));
1465 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1466 SourceManager &SM = getContext().getSourceManager();
1467 PresumedLoc PLoc = SM.getPresumedLoc(L);
1468 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1469 SM.getExpansionLineNumber(L);
1470 return llvm::ConstantInt::get(Int32Ty, LineNo);
1473 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1474 const AnnotateAttr *AA,
1476 // Get the globals for file name, annotation, and the line number.
1477 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1478 *UnitGV = EmitAnnotationUnit(L),
1479 *LineNoCst = EmitAnnotationLineNo(L);
1481 // Create the ConstantStruct for the global annotation.
1482 llvm::Constant *Fields[4] = {
1483 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1484 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1485 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1488 return llvm::ConstantStruct::getAnon(Fields);
1491 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1492 llvm::GlobalValue *GV) {
1493 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1494 // Get the struct elements for these annotations.
1495 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1496 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1499 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1500 SourceLocation Loc) const {
1501 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1502 // Blacklist by function name.
1503 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1505 // Blacklist by location.
1507 return SanitizerBL.isBlacklistedLocation(Loc);
1508 // If location is unknown, this may be a compiler-generated function. Assume
1509 // it's located in the main file.
1510 auto &SM = Context.getSourceManager();
1511 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1512 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1517 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1518 SourceLocation Loc, QualType Ty,
1519 StringRef Category) const {
1520 // For now globals can be blacklisted only in ASan and KASan.
1521 if (!LangOpts.Sanitize.hasOneOf(
1522 SanitizerKind::Address | SanitizerKind::KernelAddress))
1524 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1525 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1527 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1529 // Check global type.
1531 // Drill down the array types: if global variable of a fixed type is
1532 // blacklisted, we also don't instrument arrays of them.
1533 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1534 Ty = AT->getElementType();
1535 Ty = Ty.getCanonicalType().getUnqualifiedType();
1536 // We allow to blacklist only record types (classes, structs etc.)
1537 if (Ty->isRecordType()) {
1538 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1539 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1546 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1547 StringRef Category) const {
1548 if (!LangOpts.XRayInstrument)
1550 const auto &XRayFilter = getContext().getXRayFilter();
1551 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1552 auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
1554 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1555 if (Attr == ImbueAttr::NONE)
1556 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1558 case ImbueAttr::NONE:
1560 case ImbueAttr::ALWAYS:
1561 Fn->addFnAttr("function-instrument", "xray-always");
1563 case ImbueAttr::ALWAYS_ARG1:
1564 Fn->addFnAttr("function-instrument", "xray-always");
1565 Fn->addFnAttr("xray-log-args", "1");
1567 case ImbueAttr::NEVER:
1568 Fn->addFnAttr("function-instrument", "xray-never");
1574 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1575 // Never defer when EmitAllDecls is specified.
1576 if (LangOpts.EmitAllDecls)
1579 return getContext().DeclMustBeEmitted(Global);
1582 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1583 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1584 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1585 // Implicit template instantiations may change linkage if they are later
1586 // explicitly instantiated, so they should not be emitted eagerly.
1588 if (const auto *VD = dyn_cast<VarDecl>(Global))
1589 if (Context.getInlineVariableDefinitionKind(VD) ==
1590 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1591 // A definition of an inline constexpr static data member may change
1592 // linkage later if it's redeclared outside the class.
1594 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1595 // codegen for global variables, because they may be marked as threadprivate.
1596 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1597 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1603 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1604 const CXXUuidofExpr* E) {
1605 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1607 StringRef Uuid = E->getUuidStr();
1608 std::string Name = "_GUID_" + Uuid.lower();
1609 std::replace(Name.begin(), Name.end(), '-', '_');
1611 // The UUID descriptor should be pointer aligned.
1612 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
1614 // Look for an existing global.
1615 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1616 return ConstantAddress(GV, Alignment);
1618 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1619 assert(Init && "failed to initialize as constant");
1621 auto *GV = new llvm::GlobalVariable(
1622 getModule(), Init->getType(),
1623 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1624 if (supportsCOMDAT())
1625 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1626 return ConstantAddress(GV, Alignment);
1629 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1630 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1631 assert(AA && "No alias?");
1633 CharUnits Alignment = getContext().getDeclAlign(VD);
1634 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1636 // See if there is already something with the target's name in the module.
1637 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1639 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1640 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1641 return ConstantAddress(Ptr, Alignment);
1644 llvm::Constant *Aliasee;
1645 if (isa<llvm::FunctionType>(DeclTy))
1646 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1647 GlobalDecl(cast<FunctionDecl>(VD)),
1648 /*ForVTable=*/false);
1650 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1651 llvm::PointerType::getUnqual(DeclTy),
1654 auto *F = cast<llvm::GlobalValue>(Aliasee);
1655 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1656 WeakRefReferences.insert(F);
1658 return ConstantAddress(Aliasee, Alignment);
1661 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1662 const auto *Global = cast<ValueDecl>(GD.getDecl());
1664 // Weak references don't produce any output by themselves.
1665 if (Global->hasAttr<WeakRefAttr>())
1668 // If this is an alias definition (which otherwise looks like a declaration)
1670 if (Global->hasAttr<AliasAttr>())
1671 return EmitAliasDefinition(GD);
1673 // IFunc like an alias whose value is resolved at runtime by calling resolver.
1674 if (Global->hasAttr<IFuncAttr>())
1675 return emitIFuncDefinition(GD);
1677 // If this is CUDA, be selective about which declarations we emit.
1678 if (LangOpts.CUDA) {
1679 if (LangOpts.CUDAIsDevice) {
1680 if (!Global->hasAttr<CUDADeviceAttr>() &&
1681 !Global->hasAttr<CUDAGlobalAttr>() &&
1682 !Global->hasAttr<CUDAConstantAttr>() &&
1683 !Global->hasAttr<CUDASharedAttr>())
1686 // We need to emit host-side 'shadows' for all global
1687 // device-side variables because the CUDA runtime needs their
1688 // size and host-side address in order to provide access to
1689 // their device-side incarnations.
1691 // So device-only functions are the only things we skip.
1692 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1693 Global->hasAttr<CUDADeviceAttr>())
1696 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1697 "Expected Variable or Function");
1701 if (LangOpts.OpenMP) {
1702 // If this is OpenMP device, check if it is legal to emit this global
1704 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1706 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1707 if (MustBeEmitted(Global))
1708 EmitOMPDeclareReduction(DRD);
1713 // Ignore declarations, they will be emitted on their first use.
1714 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1715 // Forward declarations are emitted lazily on first use.
1716 if (!FD->doesThisDeclarationHaveABody()) {
1717 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1720 StringRef MangledName = getMangledName(GD);
1722 // Compute the function info and LLVM type.
1723 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1724 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1726 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1727 /*DontDefer=*/false);
1731 const auto *VD = cast<VarDecl>(Global);
1732 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1733 // We need to emit device-side global CUDA variables even if a
1734 // variable does not have a definition -- we still need to define
1735 // host-side shadow for it.
1736 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1737 !VD->hasDefinition() &&
1738 (VD->hasAttr<CUDAConstantAttr>() ||
1739 VD->hasAttr<CUDADeviceAttr>());
1740 if (!MustEmitForCuda &&
1741 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1742 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1743 // If this declaration may have caused an inline variable definition to
1744 // change linkage, make sure that it's emitted.
1745 if (Context.getInlineVariableDefinitionKind(VD) ==
1746 ASTContext::InlineVariableDefinitionKind::Strong)
1747 GetAddrOfGlobalVar(VD);
1752 // Defer code generation to first use when possible, e.g. if this is an inline
1753 // function. If the global must always be emitted, do it eagerly if possible
1754 // to benefit from cache locality.
1755 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1756 // Emit the definition if it can't be deferred.
1757 EmitGlobalDefinition(GD);
1761 // If we're deferring emission of a C++ variable with an
1762 // initializer, remember the order in which it appeared in the file.
1763 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1764 cast<VarDecl>(Global)->hasInit()) {
1765 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1766 CXXGlobalInits.push_back(nullptr);
1769 StringRef MangledName = getMangledName(GD);
1770 if (GetGlobalValue(MangledName) != nullptr) {
1771 // The value has already been used and should therefore be emitted.
1772 addDeferredDeclToEmit(GD);
1773 } else if (MustBeEmitted(Global)) {
1774 // The value must be emitted, but cannot be emitted eagerly.
1775 assert(!MayBeEmittedEagerly(Global));
1776 addDeferredDeclToEmit(GD);
1778 // Otherwise, remember that we saw a deferred decl with this name. The
1779 // first use of the mangled name will cause it to move into
1780 // DeferredDeclsToEmit.
1781 DeferredDecls[MangledName] = GD;
1785 // Check if T is a class type with a destructor that's not dllimport.
1786 static bool HasNonDllImportDtor(QualType T) {
1787 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
1788 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1789 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1796 struct FunctionIsDirectlyRecursive :
1797 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1798 const StringRef Name;
1799 const Builtin::Context &BI;
1801 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1802 Name(N), BI(C), Result(false) {
1804 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1806 bool TraverseCallExpr(CallExpr *E) {
1807 const FunctionDecl *FD = E->getDirectCallee();
1810 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1811 if (Attr && Name == Attr->getLabel()) {
1815 unsigned BuiltinID = FD->getBuiltinID();
1816 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1818 StringRef BuiltinName = BI.getName(BuiltinID);
1819 if (BuiltinName.startswith("__builtin_") &&
1820 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1828 // Make sure we're not referencing non-imported vars or functions.
1829 struct DLLImportFunctionVisitor
1830 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1831 bool SafeToInline = true;
1833 bool shouldVisitImplicitCode() const { return true; }
1835 bool VisitVarDecl(VarDecl *VD) {
1836 if (VD->getTLSKind()) {
1837 // A thread-local variable cannot be imported.
1838 SafeToInline = false;
1839 return SafeToInline;
1842 // A variable definition might imply a destructor call.
1843 if (VD->isThisDeclarationADefinition())
1844 SafeToInline = !HasNonDllImportDtor(VD->getType());
1846 return SafeToInline;
1849 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1850 if (const auto *D = E->getTemporary()->getDestructor())
1851 SafeToInline = D->hasAttr<DLLImportAttr>();
1852 return SafeToInline;
1855 bool VisitDeclRefExpr(DeclRefExpr *E) {
1856 ValueDecl *VD = E->getDecl();
1857 if (isa<FunctionDecl>(VD))
1858 SafeToInline = VD->hasAttr<DLLImportAttr>();
1859 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1860 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1861 return SafeToInline;
1864 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
1865 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
1866 return SafeToInline;
1869 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1870 CXXMethodDecl *M = E->getMethodDecl();
1872 // Call through a pointer to member function. This is safe to inline.
1873 SafeToInline = true;
1875 SafeToInline = M->hasAttr<DLLImportAttr>();
1877 return SafeToInline;
1880 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1881 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1882 return SafeToInline;
1885 bool VisitCXXNewExpr(CXXNewExpr *E) {
1886 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1887 return SafeToInline;
1892 // isTriviallyRecursive - Check if this function calls another
1893 // decl that, because of the asm attribute or the other decl being a builtin,
1894 // ends up pointing to itself.
1896 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1898 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1899 // asm labels are a special kind of mangling we have to support.
1900 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1903 Name = Attr->getLabel();
1905 Name = FD->getName();
1908 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1909 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1910 return Walker.Result;
1913 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1914 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1916 const auto *F = cast<FunctionDecl>(GD.getDecl());
1917 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1920 if (F->hasAttr<DLLImportAttr>()) {
1921 // Check whether it would be safe to inline this dllimport function.
1922 DLLImportFunctionVisitor Visitor;
1923 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1924 if (!Visitor.SafeToInline)
1927 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
1928 // Implicit destructor invocations aren't captured in the AST, so the
1929 // check above can't see them. Check for them manually here.
1930 for (const Decl *Member : Dtor->getParent()->decls())
1931 if (isa<FieldDecl>(Member))
1932 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
1934 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
1935 if (HasNonDllImportDtor(B.getType()))
1940 // PR9614. Avoid cases where the source code is lying to us. An available
1941 // externally function should have an equivalent function somewhere else,
1942 // but a function that calls itself is clearly not equivalent to the real
1944 // This happens in glibc's btowc and in some configure checks.
1945 return !isTriviallyRecursive(F);
1948 bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
1949 return CodeGenOpts.OptimizationLevel > 0;
1952 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1953 const auto *D = cast<ValueDecl>(GD.getDecl());
1955 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1956 Context.getSourceManager(),
1957 "Generating code for declaration");
1959 if (isa<FunctionDecl>(D)) {
1960 // At -O0, don't generate IR for functions with available_externally
1962 if (!shouldEmitFunction(GD))
1965 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1966 // Make sure to emit the definition(s) before we emit the thunks.
1967 // This is necessary for the generation of certain thunks.
1968 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1969 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1970 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1971 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1973 EmitGlobalFunctionDefinition(GD, GV);
1975 if (Method->isVirtual())
1976 getVTables().EmitThunks(GD);
1981 return EmitGlobalFunctionDefinition(GD, GV);
1984 if (const auto *VD = dyn_cast<VarDecl>(D))
1985 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1987 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1990 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1991 llvm::Function *NewFn);
1993 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1994 /// module, create and return an llvm Function with the specified type. If there
1995 /// is something in the module with the specified name, return it potentially
1996 /// bitcasted to the right type.
1998 /// If D is non-null, it specifies a decl that correspond to this. This is used
1999 /// to set the attributes on the function when it is first created.
2000 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
2001 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
2002 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
2003 ForDefinition_t IsForDefinition) {
2004 const Decl *D = GD.getDecl();
2006 // Lookup the entry, lazily creating it if necessary.
2007 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2009 if (WeakRefReferences.erase(Entry)) {
2010 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2011 if (FD && !FD->hasAttr<WeakAttr>())
2012 Entry->setLinkage(llvm::Function::ExternalLinkage);
2015 // Handle dropped DLL attributes.
2016 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2017 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2019 // If there are two attempts to define the same mangled name, issue an
2021 if (IsForDefinition && !Entry->isDeclaration()) {
2023 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2024 // to make sure that we issue an error only once.
2025 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
2026 (GD.getCanonicalDecl().getDecl() !=
2027 OtherGD.getCanonicalDecl().getDecl()) &&
2028 DiagnosedConflictingDefinitions.insert(GD).second) {
2029 getDiags().Report(D->getLocation(),
2030 diag::err_duplicate_mangled_name);
2031 getDiags().Report(OtherGD.getDecl()->getLocation(),
2032 diag::note_previous_definition);
2036 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
2037 (Entry->getType()->getElementType() == Ty)) {
2041 // Make sure the result is of the correct type.
2042 // (If function is requested for a definition, we always need to create a new
2043 // function, not just return a bitcast.)
2044 if (!IsForDefinition)
2045 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2048 // This function doesn't have a complete type (for example, the return
2049 // type is an incomplete struct). Use a fake type instead, and make
2050 // sure not to try to set attributes.
2051 bool IsIncompleteFunction = false;
2053 llvm::FunctionType *FTy;
2054 if (isa<llvm::FunctionType>(Ty)) {
2055 FTy = cast<llvm::FunctionType>(Ty);
2057 FTy = llvm::FunctionType::get(VoidTy, false);
2058 IsIncompleteFunction = true;
2062 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2063 Entry ? StringRef() : MangledName, &getModule());
2065 // If we already created a function with the same mangled name (but different
2066 // type) before, take its name and add it to the list of functions to be
2067 // replaced with F at the end of CodeGen.
2069 // This happens if there is a prototype for a function (e.g. "int f()") and
2070 // then a definition of a different type (e.g. "int f(int x)").
2074 // This might be an implementation of a function without a prototype, in
2075 // which case, try to do special replacement of calls which match the new
2076 // prototype. The really key thing here is that we also potentially drop
2077 // arguments from the call site so as to make a direct call, which makes the
2078 // inliner happier and suppresses a number of optimizer warnings (!) about
2079 // dropping arguments.
2080 if (!Entry->use_empty()) {
2081 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2082 Entry->removeDeadConstantUsers();
2085 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2086 F, Entry->getType()->getElementType()->getPointerTo());
2087 addGlobalValReplacement(Entry, BC);
2090 assert(F->getName() == MangledName && "name was uniqued!");
2092 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2093 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2094 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2095 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2099 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2100 // each other bottoming out with the base dtor. Therefore we emit non-base
2101 // dtors on usage, even if there is no dtor definition in the TU.
2102 if (D && isa<CXXDestructorDecl>(D) &&
2103 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2105 addDeferredDeclToEmit(GD);
2107 // This is the first use or definition of a mangled name. If there is a
2108 // deferred decl with this name, remember that we need to emit it at the end
2110 auto DDI = DeferredDecls.find(MangledName);
2111 if (DDI != DeferredDecls.end()) {
2112 // Move the potentially referenced deferred decl to the
2113 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2114 // don't need it anymore).
2115 addDeferredDeclToEmit(DDI->second);
2116 DeferredDecls.erase(DDI);
2118 // Otherwise, there are cases we have to worry about where we're
2119 // using a declaration for which we must emit a definition but where
2120 // we might not find a top-level definition:
2121 // - member functions defined inline in their classes
2122 // - friend functions defined inline in some class
2123 // - special member functions with implicit definitions
2124 // If we ever change our AST traversal to walk into class methods,
2125 // this will be unnecessary.
2127 // We also don't emit a definition for a function if it's going to be an
2128 // entry in a vtable, unless it's already marked as used.
2129 } else if (getLangOpts().CPlusPlus && D) {
2130 // Look for a declaration that's lexically in a record.
2131 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2132 FD = FD->getPreviousDecl()) {
2133 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2134 if (FD->doesThisDeclarationHaveABody()) {
2135 addDeferredDeclToEmit(GD.getWithDecl(FD));
2143 // Make sure the result is of the requested type.
2144 if (!IsIncompleteFunction) {
2145 assert(F->getType()->getElementType() == Ty);
2149 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2150 return llvm::ConstantExpr::getBitCast(F, PTy);
2153 /// GetAddrOfFunction - Return the address of the given function. If Ty is
2154 /// non-null, then this function will use the specified type if it has to
2155 /// create it (this occurs when we see a definition of the function).
2156 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2160 ForDefinition_t IsForDefinition) {
2161 // If there was no specific requested type, just convert it now.
2163 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2164 auto CanonTy = Context.getCanonicalType(FD->getType());
2165 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2168 StringRef MangledName = getMangledName(GD);
2169 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2170 /*IsThunk=*/false, llvm::AttributeList(),
2174 static const FunctionDecl *
2175 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2176 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2177 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2179 IdentifierInfo &CII = C.Idents.get(Name);
2180 for (const auto &Result : DC->lookup(&CII))
2181 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2184 if (!C.getLangOpts().CPlusPlus)
2187 // Demangle the premangled name from getTerminateFn()
2188 IdentifierInfo &CXXII =
2189 (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2190 ? C.Idents.get("terminate")
2191 : C.Idents.get(Name);
2193 for (const auto &N : {"__cxxabiv1", "std"}) {
2194 IdentifierInfo &NS = C.Idents.get(N);
2195 for (const auto &Result : DC->lookup(&NS)) {
2196 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2197 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2198 for (const auto &Result : LSD->lookup(&NS))
2199 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2203 for (const auto &Result : ND->lookup(&CXXII))
2204 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2212 /// CreateRuntimeFunction - Create a new runtime function with the specified
2215 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2216 llvm::AttributeList ExtraAttrs,
2219 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2220 /*DontDefer=*/false, /*IsThunk=*/false,
2223 if (auto *F = dyn_cast<llvm::Function>(C)) {
2225 F->setCallingConv(getRuntimeCC());
2227 if (!Local && getTriple().isOSBinFormatCOFF() &&
2228 !getCodeGenOpts().LTOVisibilityPublicStd) {
2229 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2230 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2231 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2232 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2241 /// CreateBuiltinFunction - Create a new builtin function with the specified
2244 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2245 llvm::AttributeList ExtraAttrs) {
2247 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2248 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2249 if (auto *F = dyn_cast<llvm::Function>(C))
2251 F->setCallingConv(getBuiltinCC());
2255 /// isTypeConstant - Determine whether an object of this type can be emitted
2258 /// If ExcludeCtor is true, the duration when the object's constructor runs
2259 /// will not be considered. The caller will need to verify that the object is
2260 /// not written to during its construction.
2261 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2262 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2265 if (Context.getLangOpts().CPlusPlus) {
2266 if (const CXXRecordDecl *Record
2267 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2268 return ExcludeCtor && !Record->hasMutableFields() &&
2269 Record->hasTrivialDestructor();
2275 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2276 /// create and return an llvm GlobalVariable with the specified type. If there
2277 /// is something in the module with the specified name, return it potentially
2278 /// bitcasted to the right type.
2280 /// If D is non-null, it specifies a decl that correspond to this. This is used
2281 /// to set the attributes on the global when it is first created.
2283 /// If IsForDefinition is true, it is guranteed that an actual global with
2284 /// type Ty will be returned, not conversion of a variable with the same
2285 /// mangled name but some other type.
2287 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2288 llvm::PointerType *Ty,
2290 ForDefinition_t IsForDefinition) {
2291 // Lookup the entry, lazily creating it if necessary.
2292 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2294 if (WeakRefReferences.erase(Entry)) {
2295 if (D && !D->hasAttr<WeakAttr>())
2296 Entry->setLinkage(llvm::Function::ExternalLinkage);
2299 // Handle dropped DLL attributes.
2300 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2301 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2303 if (Entry->getType() == Ty)
2306 // If there are two attempts to define the same mangled name, issue an
2308 if (IsForDefinition && !Entry->isDeclaration()) {
2310 const VarDecl *OtherD;
2312 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2313 // to make sure that we issue an error only once.
2314 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2315 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2316 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2317 OtherD->hasInit() &&
2318 DiagnosedConflictingDefinitions.insert(D).second) {
2319 getDiags().Report(D->getLocation(),
2320 diag::err_duplicate_mangled_name);
2321 getDiags().Report(OtherGD.getDecl()->getLocation(),
2322 diag::note_previous_definition);
2326 // Make sure the result is of the correct type.
2327 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2328 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2330 // (If global is requested for a definition, we always need to create a new
2331 // global, not just return a bitcast.)
2332 if (!IsForDefinition)
2333 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2336 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2337 auto *GV = new llvm::GlobalVariable(
2338 getModule(), Ty->getElementType(), false,
2339 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2340 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2342 // If we already created a global with the same mangled name (but different
2343 // type) before, take its name and remove it from its parent.
2345 GV->takeName(Entry);
2347 if (!Entry->use_empty()) {
2348 llvm::Constant *NewPtrForOldDecl =
2349 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2350 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2353 Entry->eraseFromParent();
2356 // This is the first use or definition of a mangled name. If there is a
2357 // deferred decl with this name, remember that we need to emit it at the end
2359 auto DDI = DeferredDecls.find(MangledName);
2360 if (DDI != DeferredDecls.end()) {
2361 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2362 // list, and remove it from DeferredDecls (since we don't need it anymore).
2363 addDeferredDeclToEmit(DDI->second);
2364 DeferredDecls.erase(DDI);
2367 // Handle things which are present even on external declarations.
2369 // FIXME: This code is overly simple and should be merged with other global
2371 GV->setConstant(isTypeConstant(D->getType(), false));
2373 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2375 setLinkageAndVisibilityForGV(GV, D);
2377 if (D->getTLSKind()) {
2378 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2379 CXXThreadLocals.push_back(D);
2383 // If required by the ABI, treat declarations of static data members with
2384 // inline initializers as definitions.
2385 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2386 EmitGlobalVarDefinition(D);
2389 // Handle XCore specific ABI requirements.
2390 if (getTriple().getArch() == llvm::Triple::xcore &&
2391 D->getLanguageLinkage() == CLanguageLinkage &&
2392 D->getType().isConstant(Context) &&
2393 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2394 GV->setSection(".cp.rodata");
2397 if (AddrSpace != Ty->getAddressSpace())
2398 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2404 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2405 ForDefinition_t IsForDefinition) {
2406 const Decl *D = GD.getDecl();
2407 if (isa<CXXConstructorDecl>(D))
2408 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
2409 getFromCtorType(GD.getCtorType()),
2410 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2411 /*DontDefer=*/false, IsForDefinition);
2412 else if (isa<CXXDestructorDecl>(D))
2413 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
2414 getFromDtorType(GD.getDtorType()),
2415 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2416 /*DontDefer=*/false, IsForDefinition);
2417 else if (isa<CXXMethodDecl>(D)) {
2418 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2419 cast<CXXMethodDecl>(D));
2420 auto Ty = getTypes().GetFunctionType(*FInfo);
2421 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2423 } else if (isa<FunctionDecl>(D)) {
2424 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2425 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2426 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2429 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2433 llvm::GlobalVariable *
2434 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2436 llvm::GlobalValue::LinkageTypes Linkage) {
2437 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2438 llvm::GlobalVariable *OldGV = nullptr;
2441 // Check if the variable has the right type.
2442 if (GV->getType()->getElementType() == Ty)
2445 // Because C++ name mangling, the only way we can end up with an already
2446 // existing global with the same name is if it has been declared extern "C".
2447 assert(GV->isDeclaration() && "Declaration has wrong type!");
2451 // Create a new variable.
2452 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2453 Linkage, nullptr, Name);
2456 // Replace occurrences of the old variable if needed.
2457 GV->takeName(OldGV);
2459 if (!OldGV->use_empty()) {
2460 llvm::Constant *NewPtrForOldDecl =
2461 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2462 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2465 OldGV->eraseFromParent();
2468 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2469 !GV->hasAvailableExternallyLinkage())
2470 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2475 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2476 /// given global variable. If Ty is non-null and if the global doesn't exist,
2477 /// then it will be created with the specified type instead of whatever the
2478 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2479 /// that an actual global with type Ty will be returned, not conversion of a
2480 /// variable with the same mangled name but some other type.
2481 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2483 ForDefinition_t IsForDefinition) {
2484 assert(D->hasGlobalStorage() && "Not a global variable");
2485 QualType ASTTy = D->getType();
2487 Ty = getTypes().ConvertTypeForMem(ASTTy);
2489 llvm::PointerType *PTy =
2490 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2492 StringRef MangledName = getMangledName(D);
2493 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2496 /// CreateRuntimeVariable - Create a new runtime global variable with the
2497 /// specified type and name.
2499 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2501 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2504 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2505 assert(!D->getInit() && "Cannot emit definite definitions here!");
2507 StringRef MangledName = getMangledName(D);
2508 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2510 // We already have a definition, not declaration, with the same mangled name.
2511 // Emitting of declaration is not required (and actually overwrites emitted
2513 if (GV && !GV->isDeclaration())
2516 // If we have not seen a reference to this variable yet, place it into the
2517 // deferred declarations table to be emitted if needed later.
2518 if (!MustBeEmitted(D) && !GV) {
2519 DeferredDecls[MangledName] = D;
2523 // The tentative definition is the only definition.
2524 EmitGlobalVarDefinition(D);
2527 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2528 return Context.toCharUnitsFromBits(
2529 getDataLayout().getTypeStoreSizeInBits(Ty));
2532 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2533 unsigned AddrSpace) {
2534 if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2535 if (D->hasAttr<CUDAConstantAttr>())
2536 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2537 else if (D->hasAttr<CUDASharedAttr>())
2538 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2540 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2546 template<typename SomeDecl>
2547 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2548 llvm::GlobalValue *GV) {
2549 if (!getLangOpts().CPlusPlus)
2552 // Must have 'used' attribute, or else inline assembly can't rely on
2553 // the name existing.
2554 if (!D->template hasAttr<UsedAttr>())
2557 // Must have internal linkage and an ordinary name.
2558 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2561 // Must be in an extern "C" context. Entities declared directly within
2562 // a record are not extern "C" even if the record is in such a context.
2563 const SomeDecl *First = D->getFirstDecl();
2564 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2567 // OK, this is an internal linkage entity inside an extern "C" linkage
2568 // specification. Make a note of that so we can give it the "expected"
2569 // mangled name if nothing else is using that name.
2570 std::pair<StaticExternCMap::iterator, bool> R =
2571 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2573 // If we have multiple internal linkage entities with the same name
2574 // in extern "C" regions, none of them gets that name.
2576 R.first->second = nullptr;
2579 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2580 if (!CGM.supportsCOMDAT())
2583 if (D.hasAttr<SelectAnyAttr>())
2587 if (auto *VD = dyn_cast<VarDecl>(&D))
2588 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2590 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2594 case GVA_AvailableExternally:
2595 case GVA_StrongExternal:
2597 case GVA_DiscardableODR:
2601 llvm_unreachable("No such linkage");
2604 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2605 llvm::GlobalObject &GO) {
2606 if (!shouldBeInCOMDAT(*this, D))
2608 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2611 /// Pass IsTentative as true if you want to create a tentative definition.
2612 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2614 // OpenCL global variables of sampler type are translated to function calls,
2615 // therefore no need to be translated.
2616 QualType ASTTy = D->getType();
2617 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
2620 llvm::Constant *Init = nullptr;
2621 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2622 bool NeedsGlobalCtor = false;
2623 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2625 const VarDecl *InitDecl;
2626 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2628 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2629 // as part of their declaration." Sema has already checked for
2630 // error cases, so we just need to set Init to UndefValue.
2631 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2632 D->hasAttr<CUDASharedAttr>())
2633 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2634 else if (!InitExpr) {
2635 // This is a tentative definition; tentative definitions are
2636 // implicitly initialized with { 0 }.
2638 // Note that tentative definitions are only emitted at the end of
2639 // a translation unit, so they should never have incomplete
2640 // type. In addition, EmitTentativeDefinition makes sure that we
2641 // never attempt to emit a tentative definition if a real one
2642 // exists. A use may still exists, however, so we still may need
2644 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2645 Init = EmitNullConstant(D->getType());
2647 initializedGlobalDecl = GlobalDecl(D);
2648 Init = EmitConstantInit(*InitDecl);
2651 QualType T = InitExpr->getType();
2652 if (D->getType()->isReferenceType())
2655 if (getLangOpts().CPlusPlus) {
2656 Init = EmitNullConstant(T);
2657 NeedsGlobalCtor = true;
2659 ErrorUnsupported(D, "static initializer");
2660 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2663 // We don't need an initializer, so remove the entry for the delayed
2664 // initializer position (just in case this entry was delayed) if we
2665 // also don't need to register a destructor.
2666 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2667 DelayedCXXInitPosition.erase(D);
2671 llvm::Type* InitType = Init->getType();
2672 llvm::Constant *Entry =
2673 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2675 // Strip off a bitcast if we got one back.
2676 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2677 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2678 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2679 // All zero index gep.
2680 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2681 Entry = CE->getOperand(0);
2684 // Entry is now either a Function or GlobalVariable.
2685 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2687 // We have a definition after a declaration with the wrong type.
2688 // We must make a new GlobalVariable* and update everything that used OldGV
2689 // (a declaration or tentative definition) with the new GlobalVariable*
2690 // (which will be a definition).
2692 // This happens if there is a prototype for a global (e.g.
2693 // "extern int x[];") and then a definition of a different type (e.g.
2694 // "int x[10];"). This also happens when an initializer has a different type
2695 // from the type of the global (this happens with unions).
2697 GV->getType()->getElementType() != InitType ||
2698 GV->getType()->getAddressSpace() !=
2699 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2701 // Move the old entry aside so that we'll create a new one.
2702 Entry->setName(StringRef());
2704 // Make a new global with the correct type, this is now guaranteed to work.
2705 GV = cast<llvm::GlobalVariable>(
2706 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2708 // Replace all uses of the old global with the new global
2709 llvm::Constant *NewPtrForOldDecl =
2710 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2711 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2713 // Erase the old global, since it is no longer used.
2714 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2717 MaybeHandleStaticInExternC(D, GV);
2719 if (D->hasAttr<AnnotateAttr>())
2720 AddGlobalAnnotations(D, GV);
2722 // Set the llvm linkage type as appropriate.
2723 llvm::GlobalValue::LinkageTypes Linkage =
2724 getLLVMLinkageVarDefinition(D, GV->isConstant());
2726 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2727 // the device. [...]"
2728 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2729 // __device__, declares a variable that: [...]
2730 // Is accessible from all the threads within the grid and from the host
2731 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2732 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2733 if (GV && LangOpts.CUDA) {
2734 if (LangOpts.CUDAIsDevice) {
2735 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2736 GV->setExternallyInitialized(true);
2738 // Host-side shadows of external declarations of device-side
2739 // global variables become internal definitions. These have to
2740 // be internal in order to prevent name conflicts with global
2741 // host variables with the same name in a different TUs.
2742 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2743 Linkage = llvm::GlobalValue::InternalLinkage;
2745 // Shadow variables and their properties must be registered
2746 // with CUDA runtime.
2748 if (!D->hasDefinition())
2749 Flags |= CGCUDARuntime::ExternDeviceVar;
2750 if (D->hasAttr<CUDAConstantAttr>())
2751 Flags |= CGCUDARuntime::ConstantDeviceVar;
2752 getCUDARuntime().registerDeviceVar(*GV, Flags);
2753 } else if (D->hasAttr<CUDASharedAttr>())
2754 // __shared__ variables are odd. Shadows do get created, but
2755 // they are not registered with the CUDA runtime, so they
2756 // can't really be used to access their device-side
2757 // counterparts. It's not clear yet whether it's nvcc's bug or
2758 // a feature, but we've got to do the same for compatibility.
2759 Linkage = llvm::GlobalValue::InternalLinkage;
2762 GV->setInitializer(Init);
2764 // If it is safe to mark the global 'constant', do so now.
2765 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2766 isTypeConstant(D->getType(), true));
2768 // If it is in a read-only section, mark it 'constant'.
2769 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2770 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2771 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2772 GV->setConstant(true);
2775 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2778 // On Darwin, if the normal linkage of a C++ thread_local variable is
2779 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2780 // copies within a linkage unit; otherwise, the backing variable has
2781 // internal linkage and all accesses should just be calls to the
2782 // Itanium-specified entry point, which has the normal linkage of the
2783 // variable. This is to preserve the ability to change the implementation
2784 // behind the scenes.
2785 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2786 Context.getTargetInfo().getTriple().isOSDarwin() &&
2787 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2788 !llvm::GlobalVariable::isWeakLinkage(Linkage))
2789 Linkage = llvm::GlobalValue::InternalLinkage;
2791 GV->setLinkage(Linkage);
2792 if (D->hasAttr<DLLImportAttr>())
2793 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2794 else if (D->hasAttr<DLLExportAttr>())
2795 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2797 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2799 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2800 // common vars aren't constant even if declared const.
2801 GV->setConstant(false);
2802 // Tentative definition of global variables may be initialized with
2803 // non-zero null pointers. In this case they should have weak linkage
2804 // since common linkage must have zero initializer and must not have
2805 // explicit section therefore cannot have non-zero initial value.
2806 if (!GV->getInitializer()->isNullValue())
2807 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2810 setNonAliasAttributes(D, GV);
2812 if (D->getTLSKind() && !GV->isThreadLocal()) {
2813 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2814 CXXThreadLocals.push_back(D);
2818 maybeSetTrivialComdat(*D, *GV);
2820 // Emit the initializer function if necessary.
2821 if (NeedsGlobalCtor || NeedsGlobalDtor)
2822 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2824 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2826 // Emit global variable debug information.
2827 if (CGDebugInfo *DI = getModuleDebugInfo())
2828 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2829 DI->EmitGlobalVariable(GV, D);
2832 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2833 CodeGenModule &CGM, const VarDecl *D,
2835 // Don't give variables common linkage if -fno-common was specified unless it
2836 // was overridden by a NoCommon attribute.
2837 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2841 // A declaration of an identifier for an object that has file scope without
2842 // an initializer, and without a storage-class specifier or with the
2843 // storage-class specifier static, constitutes a tentative definition.
2844 if (D->getInit() || D->hasExternalStorage())
2847 // A variable cannot be both common and exist in a section.
2848 if (D->hasAttr<SectionAttr>())
2851 // A variable cannot be both common and exist in a section.
2852 // We dont try to determine which is the right section in the front-end.
2853 // If no specialized section name is applicable, it will resort to default.
2854 if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
2855 D->hasAttr<PragmaClangDataSectionAttr>() ||
2856 D->hasAttr<PragmaClangRodataSectionAttr>())
2859 // Thread local vars aren't considered common linkage.
2860 if (D->getTLSKind())
2863 // Tentative definitions marked with WeakImportAttr are true definitions.
2864 if (D->hasAttr<WeakImportAttr>())
2867 // A variable cannot be both common and exist in a comdat.
2868 if (shouldBeInCOMDAT(CGM, *D))
2871 // Declarations with a required alignment do not have common linkage in MSVC
2873 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2874 if (D->hasAttr<AlignedAttr>())
2876 QualType VarType = D->getType();
2877 if (Context.isAlignmentRequired(VarType))
2880 if (const auto *RT = VarType->getAs<RecordType>()) {
2881 const RecordDecl *RD = RT->getDecl();
2882 for (const FieldDecl *FD : RD->fields()) {
2883 if (FD->isBitField())
2885 if (FD->hasAttr<AlignedAttr>())
2887 if (Context.isAlignmentRequired(FD->getType()))
2896 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2897 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2898 if (Linkage == GVA_Internal)
2899 return llvm::Function::InternalLinkage;
2901 if (D->hasAttr<WeakAttr>()) {
2902 if (IsConstantVariable)
2903 return llvm::GlobalVariable::WeakODRLinkage;
2905 return llvm::GlobalVariable::WeakAnyLinkage;
2908 // We are guaranteed to have a strong definition somewhere else,
2909 // so we can use available_externally linkage.
2910 if (Linkage == GVA_AvailableExternally)
2911 return llvm::GlobalValue::AvailableExternallyLinkage;
2913 // Note that Apple's kernel linker doesn't support symbol
2914 // coalescing, so we need to avoid linkonce and weak linkages there.
2915 // Normally, this means we just map to internal, but for explicit
2916 // instantiations we'll map to external.
2918 // In C++, the compiler has to emit a definition in every translation unit
2919 // that references the function. We should use linkonce_odr because
2920 // a) if all references in this translation unit are optimized away, we
2921 // don't need to codegen it. b) if the function persists, it needs to be
2922 // merged with other definitions. c) C++ has the ODR, so we know the
2923 // definition is dependable.
2924 if (Linkage == GVA_DiscardableODR)
2925 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2926 : llvm::Function::InternalLinkage;
2928 // An explicit instantiation of a template has weak linkage, since
2929 // explicit instantiations can occur in multiple translation units
2930 // and must all be equivalent. However, we are not allowed to
2931 // throw away these explicit instantiations.
2933 // We don't currently support CUDA device code spread out across multiple TUs,
2934 // so say that CUDA templates are either external (for kernels) or internal.
2935 // This lets llvm perform aggressive inter-procedural optimizations.
2936 if (Linkage == GVA_StrongODR) {
2937 if (Context.getLangOpts().AppleKext)
2938 return llvm::Function::ExternalLinkage;
2939 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2940 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2941 : llvm::Function::InternalLinkage;
2942 return llvm::Function::WeakODRLinkage;
2945 // C++ doesn't have tentative definitions and thus cannot have common
2947 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2948 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2949 CodeGenOpts.NoCommon))
2950 return llvm::GlobalVariable::CommonLinkage;
2952 // selectany symbols are externally visible, so use weak instead of
2953 // linkonce. MSVC optimizes away references to const selectany globals, so
2954 // all definitions should be the same and ODR linkage should be used.
2955 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2956 if (D->hasAttr<SelectAnyAttr>())
2957 return llvm::GlobalVariable::WeakODRLinkage;
2959 // Otherwise, we have strong external linkage.
2960 assert(Linkage == GVA_StrongExternal);
2961 return llvm::GlobalVariable::ExternalLinkage;
2964 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2965 const VarDecl *VD, bool IsConstant) {
2966 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2967 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2970 /// Replace the uses of a function that was declared with a non-proto type.
2971 /// We want to silently drop extra arguments from call sites
2972 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2973 llvm::Function *newFn) {
2975 if (old->use_empty()) return;
2977 llvm::Type *newRetTy = newFn->getReturnType();
2978 SmallVector<llvm::Value*, 4> newArgs;
2979 SmallVector<llvm::OperandBundleDef, 1> newBundles;
2981 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2983 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2984 llvm::User *user = use->getUser();
2986 // Recognize and replace uses of bitcasts. Most calls to
2987 // unprototyped functions will use bitcasts.
2988 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2989 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2990 replaceUsesOfNonProtoConstant(bitcast, newFn);
2994 // Recognize calls to the function.
2995 llvm::CallSite callSite(user);
2996 if (!callSite) continue;
2997 if (!callSite.isCallee(&*use)) continue;
2999 // If the return types don't match exactly, then we can't
3000 // transform this call unless it's dead.
3001 if (callSite->getType() != newRetTy && !callSite->use_empty())
3004 // Get the call site's attribute list.
3005 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
3006 llvm::AttributeList oldAttrs = callSite.getAttributes();
3008 // If the function was passed too few arguments, don't transform.
3009 unsigned newNumArgs = newFn->arg_size();
3010 if (callSite.arg_size() < newNumArgs) continue;
3012 // If extra arguments were passed, we silently drop them.
3013 // If any of the types mismatch, we don't transform.
3015 bool dontTransform = false;
3016 for (llvm::Argument &A : newFn->args()) {
3017 if (callSite.getArgument(argNo)->getType() != A.getType()) {
3018 dontTransform = true;
3022 // Add any parameter attributes.
3023 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
3029 // Okay, we can transform this. Create the new call instruction and copy
3030 // over the required information.
3031 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3033 // Copy over any operand bundles.
3034 callSite.getOperandBundlesAsDefs(newBundles);
3036 llvm::CallSite newCall;
3037 if (callSite.isCall()) {
3038 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3039 callSite.getInstruction());
3041 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3042 newCall = llvm::InvokeInst::Create(newFn,
3043 oldInvoke->getNormalDest(),
3044 oldInvoke->getUnwindDest(),
3045 newArgs, newBundles, "",
3046 callSite.getInstruction());
3048 newArgs.clear(); // for the next iteration
3050 if (!newCall->getType()->isVoidTy())
3051 newCall->takeName(callSite.getInstruction());
3052 newCall.setAttributes(llvm::AttributeList::get(
3053 newFn->getContext(), oldAttrs.getFnAttributes(),
3054 oldAttrs.getRetAttributes(), newArgAttrs));
3055 newCall.setCallingConv(callSite.getCallingConv());
3057 // Finally, remove the old call, replacing any uses with the new one.
3058 if (!callSite->use_empty())
3059 callSite->replaceAllUsesWith(newCall.getInstruction());
3061 // Copy debug location attached to CI.
3062 if (callSite->getDebugLoc())
3063 newCall->setDebugLoc(callSite->getDebugLoc());
3065 callSite->eraseFromParent();
3069 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3070 /// implement a function with no prototype, e.g. "int foo() {}". If there are
3071 /// existing call uses of the old function in the module, this adjusts them to
3072 /// call the new function directly.
3074 /// This is not just a cleanup: the always_inline pass requires direct calls to
3075 /// functions to be able to inline them. If there is a bitcast in the way, it
3076 /// won't inline them. Instcombine normally deletes these calls, but it isn't
3078 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3079 llvm::Function *NewFn) {
3080 // If we're redefining a global as a function, don't transform it.
3081 if (!isa<llvm::Function>(Old)) return;
3083 replaceUsesOfNonProtoConstant(Old, NewFn);
3086 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3087 auto DK = VD->isThisDeclarationADefinition();
3088 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3091 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3092 // If we have a definition, this might be a deferred decl. If the
3093 // instantiation is explicit, make sure we emit it at the end.
3094 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3095 GetAddrOfGlobalVar(VD);
3097 EmitTopLevelDecl(VD);
3100 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3101 llvm::GlobalValue *GV) {
3102 const auto *D = cast<FunctionDecl>(GD.getDecl());
3104 // Compute the function info and LLVM type.
3105 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3106 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3108 // Get or create the prototype for the function.
3109 if (!GV || (GV->getType()->getElementType() != Ty))
3110 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3115 if (!GV->isDeclaration())
3118 // We need to set linkage and visibility on the function before
3119 // generating code for it because various parts of IR generation
3120 // want to propagate this information down (e.g. to local static
3122 auto *Fn = cast<llvm::Function>(GV);
3123 setFunctionLinkage(GD, Fn);
3124 setFunctionDLLStorageClass(GD, Fn);
3126 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3127 setGlobalVisibility(Fn, D);
3129 MaybeHandleStaticInExternC(D, Fn);
3131 maybeSetTrivialComdat(*D, *Fn);
3133 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3135 setFunctionDefinitionAttributes(D, Fn);
3136 SetLLVMFunctionAttributesForDefinition(D, Fn);
3138 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3139 AddGlobalCtor(Fn, CA->getPriority());
3140 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3141 AddGlobalDtor(Fn, DA->getPriority());
3142 if (D->hasAttr<AnnotateAttr>())
3143 AddGlobalAnnotations(D, Fn);
3146 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3147 const auto *D = cast<ValueDecl>(GD.getDecl());
3148 const AliasAttr *AA = D->getAttr<AliasAttr>();
3149 assert(AA && "Not an alias?");
3151 StringRef MangledName = getMangledName(GD);
3153 if (AA->getAliasee() == MangledName) {
3154 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3158 // If there is a definition in the module, then it wins over the alias.
3159 // This is dubious, but allow it to be safe. Just ignore the alias.
3160 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3161 if (Entry && !Entry->isDeclaration())
3164 Aliases.push_back(GD);
3166 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3168 // Create a reference to the named value. This ensures that it is emitted
3169 // if a deferred decl.
3170 llvm::Constant *Aliasee;
3171 if (isa<llvm::FunctionType>(DeclTy))
3172 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3173 /*ForVTable=*/false);
3175 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3176 llvm::PointerType::getUnqual(DeclTy),
3179 // Create the new alias itself, but don't set a name yet.
3180 auto *GA = llvm::GlobalAlias::create(
3181 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3184 if (GA->getAliasee() == Entry) {
3185 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3189 assert(Entry->isDeclaration());
3191 // If there is a declaration in the module, then we had an extern followed
3192 // by the alias, as in:
3193 // extern int test6();
3195 // int test6() __attribute__((alias("test7")));
3197 // Remove it and replace uses of it with the alias.
3198 GA->takeName(Entry);
3200 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3202 Entry->eraseFromParent();
3204 GA->setName(MangledName);
3207 // Set attributes which are particular to an alias; this is a
3208 // specialization of the attributes which may be set on a global
3209 // variable/function.
3210 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3211 D->isWeakImported()) {
3212 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3215 if (const auto *VD = dyn_cast<VarDecl>(D))
3216 if (VD->getTLSKind())
3217 setTLSMode(GA, *VD);
3219 setAliasAttributes(D, GA);
3222 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3223 const auto *D = cast<ValueDecl>(GD.getDecl());
3224 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3225 assert(IFA && "Not an ifunc?");
3227 StringRef MangledName = getMangledName(GD);
3229 if (IFA->getResolver() == MangledName) {
3230 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3234 // Report an error if some definition overrides ifunc.
3235 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3236 if (Entry && !Entry->isDeclaration()) {
3238 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3239 DiagnosedConflictingDefinitions.insert(GD).second) {
3240 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3241 Diags.Report(OtherGD.getDecl()->getLocation(),
3242 diag::note_previous_definition);
3247 Aliases.push_back(GD);
3249 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3250 llvm::Constant *Resolver =
3251 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3252 /*ForVTable=*/false);
3253 llvm::GlobalIFunc *GIF =
3254 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3255 "", Resolver, &getModule());
3257 if (GIF->getResolver() == Entry) {
3258 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3261 assert(Entry->isDeclaration());
3263 // If there is a declaration in the module, then we had an extern followed
3264 // by the ifunc, as in:
3265 // extern int test();
3267 // int test() __attribute__((ifunc("resolver")));
3269 // Remove it and replace uses of it with the ifunc.
3270 GIF->takeName(Entry);
3272 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3274 Entry->eraseFromParent();
3276 GIF->setName(MangledName);
3278 SetCommonAttributes(D, GIF);
3281 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3282 ArrayRef<llvm::Type*> Tys) {
3283 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3287 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3288 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3289 const StringLiteral *Literal, bool TargetIsLSB,
3290 bool &IsUTF16, unsigned &StringLength) {
3291 StringRef String = Literal->getString();
3292 unsigned NumBytes = String.size();
3294 // Check for simple case.
3295 if (!Literal->containsNonAsciiOrNull()) {
3296 StringLength = NumBytes;
3297 return *Map.insert(std::make_pair(String, nullptr)).first;
3300 // Otherwise, convert the UTF8 literals into a string of shorts.
3303 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3304 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3305 llvm::UTF16 *ToPtr = &ToBuf[0];
3307 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3308 ToPtr + NumBytes, llvm::strictConversion);
3310 // ConvertUTF8toUTF16 returns the length in ToPtr.
3311 StringLength = ToPtr - &ToBuf[0];
3313 // Add an explicit null.
3315 return *Map.insert(std::make_pair(
3316 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3317 (StringLength + 1) * 2),
3322 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3323 unsigned StringLength = 0;
3324 bool isUTF16 = false;
3325 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3326 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3327 getDataLayout().isLittleEndian(), isUTF16,
3330 if (auto *C = Entry.second)
3331 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3333 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3334 llvm::Constant *Zeros[] = { Zero, Zero };
3336 // If we don't already have it, get __CFConstantStringClassReference.
3337 if (!CFConstantStringClassRef) {
3338 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3339 Ty = llvm::ArrayType::get(Ty, 0);
3340 llvm::Constant *GV =
3341 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3343 if (getTriple().isOSBinFormatCOFF()) {
3344 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3345 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3346 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3347 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3349 const VarDecl *VD = nullptr;
3350 for (const auto &Result : DC->lookup(&II))
3351 if ((VD = dyn_cast<VarDecl>(Result)))
3354 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3355 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3356 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3358 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3359 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3363 // Decay array -> ptr
3364 CFConstantStringClassRef =
3365 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3368 QualType CFTy = getContext().getCFConstantStringType();
3370 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3372 ConstantInitBuilder Builder(*this);
3373 auto Fields = Builder.beginStruct(STy);
3376 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3379 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3382 llvm::Constant *C = nullptr;
3384 auto Arr = llvm::makeArrayRef(
3385 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3386 Entry.first().size() / 2);
3387 C = llvm::ConstantDataArray::get(VMContext, Arr);
3389 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3392 // Note: -fwritable-strings doesn't make the backing store strings of
3393 // CFStrings writable. (See <rdar://problem/10657500>)
3395 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3396 llvm::GlobalValue::PrivateLinkage, C, ".str");
3397 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3398 // Don't enforce the target's minimum global alignment, since the only use
3399 // of the string is via this class initializer.
3400 CharUnits Align = isUTF16
3401 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3402 : getContext().getTypeAlignInChars(getContext().CharTy);
3403 GV->setAlignment(Align.getQuantity());
3405 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3406 // Without it LLVM can merge the string with a non unnamed_addr one during
3407 // LTO. Doing that changes the section it ends in, which surprises ld64.
3408 if (getTriple().isOSBinFormatMachO())
3409 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3410 : "__TEXT,__cstring,cstring_literals");
3413 llvm::Constant *Str =
3414 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3417 // Cast the UTF16 string to the correct type.
3418 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3422 auto Ty = getTypes().ConvertType(getContext().LongTy);
3423 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3425 CharUnits Alignment = getPointerAlign();
3428 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3429 /*isConstant=*/false,
3430 llvm::GlobalVariable::PrivateLinkage);
3431 switch (getTriple().getObjectFormat()) {
3432 case llvm::Triple::UnknownObjectFormat:
3433 llvm_unreachable("unknown file format");
3434 case llvm::Triple::COFF:
3435 case llvm::Triple::ELF:
3436 case llvm::Triple::Wasm:
3437 GV->setSection("cfstring");
3439 case llvm::Triple::MachO:
3440 GV->setSection("__DATA,__cfstring");
3445 return ConstantAddress(GV, Alignment);
3448 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3449 if (ObjCFastEnumerationStateType.isNull()) {
3450 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3451 D->startDefinition();
3453 QualType FieldTypes[] = {
3454 Context.UnsignedLongTy,
3455 Context.getPointerType(Context.getObjCIdType()),
3456 Context.getPointerType(Context.UnsignedLongTy),
3457 Context.getConstantArrayType(Context.UnsignedLongTy,
3458 llvm::APInt(32, 5), ArrayType::Normal, 0)
3461 for (size_t i = 0; i < 4; ++i) {
3462 FieldDecl *Field = FieldDecl::Create(Context,
3465 SourceLocation(), nullptr,
3466 FieldTypes[i], /*TInfo=*/nullptr,
3467 /*BitWidth=*/nullptr,
3470 Field->setAccess(AS_public);
3474 D->completeDefinition();
3475 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3478 return ObjCFastEnumerationStateType;
3482 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3483 assert(!E->getType()->isPointerType() && "Strings are always arrays");
3485 // Don't emit it as the address of the string, emit the string data itself
3486 // as an inline array.
3487 if (E->getCharByteWidth() == 1) {
3488 SmallString<64> Str(E->getString());
3490 // Resize the string to the right size, which is indicated by its type.
3491 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3492 Str.resize(CAT->getSize().getZExtValue());
3493 return llvm::ConstantDataArray::getString(VMContext, Str, false);
3496 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3497 llvm::Type *ElemTy = AType->getElementType();
3498 unsigned NumElements = AType->getNumElements();
3500 // Wide strings have either 2-byte or 4-byte elements.
3501 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3502 SmallVector<uint16_t, 32> Elements;
3503 Elements.reserve(NumElements);
3505 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3506 Elements.push_back(E->getCodeUnit(i));
3507 Elements.resize(NumElements);
3508 return llvm::ConstantDataArray::get(VMContext, Elements);
3511 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3512 SmallVector<uint32_t, 32> Elements;
3513 Elements.reserve(NumElements);
3515 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3516 Elements.push_back(E->getCodeUnit(i));
3517 Elements.resize(NumElements);
3518 return llvm::ConstantDataArray::get(VMContext, Elements);
3521 static llvm::GlobalVariable *
3522 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3523 CodeGenModule &CGM, StringRef GlobalName,
3524 CharUnits Alignment) {
3525 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3526 unsigned AddrSpace = 0;
3527 if (CGM.getLangOpts().OpenCL)
3528 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3530 llvm::Module &M = CGM.getModule();
3531 // Create a global variable for this string
3532 auto *GV = new llvm::GlobalVariable(
3533 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3534 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3535 GV->setAlignment(Alignment.getQuantity());
3536 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3537 if (GV->isWeakForLinker()) {
3538 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3539 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3545 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3546 /// constant array for the given string literal.
3548 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3550 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3552 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3553 llvm::GlobalVariable **Entry = nullptr;
3554 if (!LangOpts.WritableStrings) {
3555 Entry = &ConstantStringMap[C];
3556 if (auto GV = *Entry) {
3557 if (Alignment.getQuantity() > GV->getAlignment())
3558 GV->setAlignment(Alignment.getQuantity());
3559 return ConstantAddress(GV, Alignment);
3563 SmallString<256> MangledNameBuffer;
3564 StringRef GlobalVariableName;
3565 llvm::GlobalValue::LinkageTypes LT;
3567 // Mangle the string literal if the ABI allows for it. However, we cannot
3568 // do this if we are compiling with ASan or -fwritable-strings because they
3569 // rely on strings having normal linkage.
3570 if (!LangOpts.WritableStrings &&
3571 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3572 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3573 llvm::raw_svector_ostream Out(MangledNameBuffer);
3574 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3576 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3577 GlobalVariableName = MangledNameBuffer;
3579 LT = llvm::GlobalValue::PrivateLinkage;
3580 GlobalVariableName = Name;
3583 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3587 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3589 return ConstantAddress(GV, Alignment);
3592 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3593 /// array for the given ObjCEncodeExpr node.
3595 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3597 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3599 return GetAddrOfConstantCString(Str);
3602 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3603 /// the literal and a terminating '\0' character.
3604 /// The result has pointer to array type.
3605 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3606 const std::string &Str, const char *GlobalName) {
3607 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3608 CharUnits Alignment =
3609 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3612 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3614 // Don't share any string literals if strings aren't constant.
3615 llvm::GlobalVariable **Entry = nullptr;
3616 if (!LangOpts.WritableStrings) {
3617 Entry = &ConstantStringMap[C];
3618 if (auto GV = *Entry) {
3619 if (Alignment.getQuantity() > GV->getAlignment())
3620 GV->setAlignment(Alignment.getQuantity());
3621 return ConstantAddress(GV, Alignment);
3625 // Get the default prefix if a name wasn't specified.
3627 GlobalName = ".str";
3628 // Create a global variable for this.
3629 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3630 GlobalName, Alignment);
3633 return ConstantAddress(GV, Alignment);
3636 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3637 const MaterializeTemporaryExpr *E, const Expr *Init) {
3638 assert((E->getStorageDuration() == SD_Static ||
3639 E->getStorageDuration() == SD_Thread) && "not a global temporary");
3640 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3642 // If we're not materializing a subobject of the temporary, keep the
3643 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3644 QualType MaterializedType = Init->getType();
3645 if (Init == E->GetTemporaryExpr())
3646 MaterializedType = E->getType();
3648 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3650 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3651 return ConstantAddress(Slot, Align);
3653 // FIXME: If an externally-visible declaration extends multiple temporaries,
3654 // we need to give each temporary the same name in every translation unit (and
3655 // we also need to make the temporaries externally-visible).
3656 SmallString<256> Name;
3657 llvm::raw_svector_ostream Out(Name);
3658 getCXXABI().getMangleContext().mangleReferenceTemporary(
3659 VD, E->getManglingNumber(), Out);
3661 APValue *Value = nullptr;
3662 if (E->getStorageDuration() == SD_Static) {
3663 // We might have a cached constant initializer for this temporary. Note
3664 // that this might have a different value from the value computed by
3665 // evaluating the initializer if the surrounding constant expression
3666 // modifies the temporary.
3667 Value = getContext().getMaterializedTemporaryValue(E, false);
3668 if (Value && Value->isUninit())
3672 // Try evaluating it now, it might have a constant initializer.
3673 Expr::EvalResult EvalResult;
3674 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3675 !EvalResult.hasSideEffects())
3676 Value = &EvalResult.Val;
3678 llvm::Constant *InitialValue = nullptr;
3679 bool Constant = false;
3682 // The temporary has a constant initializer, use it.
3683 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3684 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3685 Type = InitialValue->getType();
3687 // No initializer, the initialization will be provided when we
3688 // initialize the declaration which performed lifetime extension.
3689 Type = getTypes().ConvertTypeForMem(MaterializedType);
3692 // Create a global variable for this lifetime-extended temporary.
3693 llvm::GlobalValue::LinkageTypes Linkage =
3694 getLLVMLinkageVarDefinition(VD, Constant);
3695 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3696 const VarDecl *InitVD;
3697 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3698 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3699 // Temporaries defined inside a class get linkonce_odr linkage because the
3700 // class can be defined in multipe translation units.
3701 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3703 // There is no need for this temporary to have external linkage if the
3704 // VarDecl has external linkage.
3705 Linkage = llvm::GlobalVariable::InternalLinkage;
3708 unsigned AddrSpace = GetGlobalVarAddressSpace(
3709 VD, getContext().getTargetAddressSpace(MaterializedType));
3710 auto *GV = new llvm::GlobalVariable(
3711 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3712 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3714 setGlobalVisibility(GV, VD);
3715 GV->setAlignment(Align.getQuantity());
3716 if (supportsCOMDAT() && GV->isWeakForLinker())
3717 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3718 if (VD->getTLSKind())
3719 setTLSMode(GV, *VD);
3720 MaterializedGlobalTemporaryMap[E] = GV;
3721 return ConstantAddress(GV, Align);
3724 /// EmitObjCPropertyImplementations - Emit information for synthesized
3725 /// properties for an implementation.
3726 void CodeGenModule::EmitObjCPropertyImplementations(const
3727 ObjCImplementationDecl *D) {
3728 for (const auto *PID : D->property_impls()) {
3729 // Dynamic is just for type-checking.
3730 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3731 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3733 // Determine which methods need to be implemented, some may have
3734 // been overridden. Note that ::isPropertyAccessor is not the method
3735 // we want, that just indicates if the decl came from a
3736 // property. What we want to know is if the method is defined in
3737 // this implementation.
3738 if (!D->getInstanceMethod(PD->getGetterName()))
3739 CodeGenFunction(*this).GenerateObjCGetter(
3740 const_cast<ObjCImplementationDecl *>(D), PID);
3741 if (!PD->isReadOnly() &&
3742 !D->getInstanceMethod(PD->getSetterName()))
3743 CodeGenFunction(*this).GenerateObjCSetter(
3744 const_cast<ObjCImplementationDecl *>(D), PID);
3749 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3750 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3751 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3752 ivar; ivar = ivar->getNextIvar())
3753 if (ivar->getType().isDestructedType())
3759 static bool AllTrivialInitializers(CodeGenModule &CGM,
3760 ObjCImplementationDecl *D) {
3761 CodeGenFunction CGF(CGM);
3762 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3763 E = D->init_end(); B != E; ++B) {
3764 CXXCtorInitializer *CtorInitExp = *B;
3765 Expr *Init = CtorInitExp->getInit();
3766 if (!CGF.isTrivialInitializer(Init))
3772 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3773 /// for an implementation.
3774 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3775 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3776 if (needsDestructMethod(D)) {
3777 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3778 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3779 ObjCMethodDecl *DTORMethod =
3780 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3781 cxxSelector, getContext().VoidTy, nullptr, D,
3782 /*isInstance=*/true, /*isVariadic=*/false,
3783 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3784 /*isDefined=*/false, ObjCMethodDecl::Required);
3785 D->addInstanceMethod(DTORMethod);
3786 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3787 D->setHasDestructors(true);
3790 // If the implementation doesn't have any ivar initializers, we don't need
3791 // a .cxx_construct.
3792 if (D->getNumIvarInitializers() == 0 ||
3793 AllTrivialInitializers(*this, D))
3796 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3797 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3798 // The constructor returns 'self'.
3799 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3803 getContext().getObjCIdType(),
3804 nullptr, D, /*isInstance=*/true,
3805 /*isVariadic=*/false,
3806 /*isPropertyAccessor=*/true,
3807 /*isImplicitlyDeclared=*/true,
3808 /*isDefined=*/false,
3809 ObjCMethodDecl::Required);
3810 D->addInstanceMethod(CTORMethod);
3811 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3812 D->setHasNonZeroConstructors(true);
3815 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3816 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3817 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3818 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3819 ErrorUnsupported(LSD, "linkage spec");
3823 EmitDeclContext(LSD);
3826 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
3827 for (auto *I : DC->decls()) {
3828 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
3829 // are themselves considered "top-level", so EmitTopLevelDecl on an
3830 // ObjCImplDecl does not recursively visit them. We need to do that in
3831 // case they're nested inside another construct (LinkageSpecDecl /
3832 // ExportDecl) that does stop them from being considered "top-level".
3833 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3834 for (auto *M : OID->methods())
3835 EmitTopLevelDecl(M);
3838 EmitTopLevelDecl(I);
3842 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3843 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3844 // Ignore dependent declarations.
3845 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3848 switch (D->getKind()) {
3849 case Decl::CXXConversion:
3850 case Decl::CXXMethod:
3851 case Decl::Function:
3852 // Skip function templates
3853 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3854 cast<FunctionDecl>(D)->isLateTemplateParsed())
3857 EmitGlobal(cast<FunctionDecl>(D));
3858 // Always provide some coverage mapping
3859 // even for the functions that aren't emitted.
3860 AddDeferredUnusedCoverageMapping(D);
3863 case Decl::CXXDeductionGuide:
3864 // Function-like, but does not result in code emission.
3868 case Decl::Decomposition:
3869 // Skip variable templates
3870 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3873 case Decl::VarTemplateSpecialization:
3874 EmitGlobal(cast<VarDecl>(D));
3875 if (auto *DD = dyn_cast<DecompositionDecl>(D))
3876 for (auto *B : DD->bindings())
3877 if (auto *HD = B->getHoldingVar())
3881 // Indirect fields from global anonymous structs and unions can be
3882 // ignored; only the actual variable requires IR gen support.
3883 case Decl::IndirectField:
3887 case Decl::Namespace:
3888 EmitDeclContext(cast<NamespaceDecl>(D));
3890 case Decl::CXXRecord:
3892 if (auto *ES = D->getASTContext().getExternalSource())
3893 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
3894 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
3896 // Emit any static data members, they may be definitions.
3897 for (auto *I : cast<CXXRecordDecl>(D)->decls())
3898 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3899 EmitTopLevelDecl(I);
3901 // No code generation needed.
3902 case Decl::UsingShadow:
3903 case Decl::ClassTemplate:
3904 case Decl::VarTemplate:
3905 case Decl::VarTemplatePartialSpecialization:
3906 case Decl::FunctionTemplate:
3907 case Decl::TypeAliasTemplate:
3911 case Decl::Using: // using X; [C++]
3912 if (CGDebugInfo *DI = getModuleDebugInfo())
3913 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3915 case Decl::NamespaceAlias:
3916 if (CGDebugInfo *DI = getModuleDebugInfo())
3917 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3919 case Decl::UsingDirective: // using namespace X; [C++]
3920 if (CGDebugInfo *DI = getModuleDebugInfo())
3921 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3923 case Decl::CXXConstructor:
3924 // Skip function templates
3925 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3926 cast<FunctionDecl>(D)->isLateTemplateParsed())
3929 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3931 case Decl::CXXDestructor:
3932 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3934 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3937 case Decl::StaticAssert:
3941 // Objective-C Decls
3943 // Forward declarations, no (immediate) code generation.
3944 case Decl::ObjCInterface:
3945 case Decl::ObjCCategory:
3948 case Decl::ObjCProtocol: {
3949 auto *Proto = cast<ObjCProtocolDecl>(D);
3950 if (Proto->isThisDeclarationADefinition())
3951 ObjCRuntime->GenerateProtocol(Proto);
3955 case Decl::ObjCCategoryImpl:
3956 // Categories have properties but don't support synthesize so we
3957 // can ignore them here.
3958 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3961 case Decl::ObjCImplementation: {
3962 auto *OMD = cast<ObjCImplementationDecl>(D);
3963 EmitObjCPropertyImplementations(OMD);
3964 EmitObjCIvarInitializations(OMD);
3965 ObjCRuntime->GenerateClass(OMD);
3966 // Emit global variable debug information.
3967 if (CGDebugInfo *DI = getModuleDebugInfo())
3968 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3969 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3970 OMD->getClassInterface()), OMD->getLocation());
3973 case Decl::ObjCMethod: {
3974 auto *OMD = cast<ObjCMethodDecl>(D);
3975 // If this is not a prototype, emit the body.
3977 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3980 case Decl::ObjCCompatibleAlias:
3981 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3984 case Decl::PragmaComment: {
3985 const auto *PCD = cast<PragmaCommentDecl>(D);
3986 switch (PCD->getCommentKind()) {
3988 llvm_unreachable("unexpected pragma comment kind");
3990 AppendLinkerOptions(PCD->getArg());
3993 AddDependentLib(PCD->getArg());
3998 break; // We ignore all of these.
4003 case Decl::PragmaDetectMismatch: {
4004 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4005 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4009 case Decl::LinkageSpec:
4010 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4013 case Decl::FileScopeAsm: {
4014 // File-scope asm is ignored during device-side CUDA compilation.
4015 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
4017 // File-scope asm is ignored during device-side OpenMP compilation.
4018 if (LangOpts.OpenMPIsDevice)
4020 auto *AD = cast<FileScopeAsmDecl>(D);
4021 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4025 case Decl::Import: {
4026 auto *Import = cast<ImportDecl>(D);
4028 // If we've already imported this module, we're done.
4029 if (!ImportedModules.insert(Import->getImportedModule()))
4032 // Emit debug information for direct imports.
4033 if (!Import->getImportedOwningModule()) {
4034 if (CGDebugInfo *DI = getModuleDebugInfo())
4035 DI->EmitImportDecl(*Import);
4038 // Find all of the submodules and emit the module initializers.
4039 llvm::SmallPtrSet<clang::Module *, 16> Visited;
4040 SmallVector<clang::Module *, 16> Stack;
4041 Visited.insert(Import->getImportedModule());
4042 Stack.push_back(Import->getImportedModule());
4044 while (!Stack.empty()) {
4045 clang::Module *Mod = Stack.pop_back_val();
4046 if (!EmittedModuleInitializers.insert(Mod).second)
4049 for (auto *D : Context.getModuleInitializers(Mod))
4050 EmitTopLevelDecl(D);
4052 // Visit the submodules of this module.
4053 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
4054 SubEnd = Mod->submodule_end();
4055 Sub != SubEnd; ++Sub) {
4056 // Skip explicit children; they need to be explicitly imported to emit
4057 // the initializers.
4058 if ((*Sub)->IsExplicit)
4061 if (Visited.insert(*Sub).second)
4062 Stack.push_back(*Sub);
4069 EmitDeclContext(cast<ExportDecl>(D));
4072 case Decl::OMPThreadPrivate:
4073 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4076 case Decl::ClassTemplateSpecialization: {
4077 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4079 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4080 Spec->hasDefinition())
4081 DebugInfo->completeTemplateDefinition(*Spec);
4085 case Decl::OMPDeclareReduction:
4086 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4090 // Make sure we handled everything we should, every other kind is a
4091 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4092 // function. Need to recode Decl::Kind to do that easily.
4093 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4098 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4099 // Do we need to generate coverage mapping?
4100 if (!CodeGenOpts.CoverageMapping)
4102 switch (D->getKind()) {
4103 case Decl::CXXConversion:
4104 case Decl::CXXMethod:
4105 case Decl::Function:
4106 case Decl::ObjCMethod:
4107 case Decl::CXXConstructor:
4108 case Decl::CXXDestructor: {
4109 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4111 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4112 if (I == DeferredEmptyCoverageMappingDecls.end())
4113 DeferredEmptyCoverageMappingDecls[D] = true;
4121 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4122 // Do we need to generate coverage mapping?
4123 if (!CodeGenOpts.CoverageMapping)
4125 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4126 if (Fn->isTemplateInstantiation())
4127 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4129 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4130 if (I == DeferredEmptyCoverageMappingDecls.end())
4131 DeferredEmptyCoverageMappingDecls[D] = false;
4136 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4137 std::vector<const Decl *> DeferredDecls;
4138 for (const auto &I : DeferredEmptyCoverageMappingDecls) {
4141 DeferredDecls.push_back(I.first);
4143 // Sort the declarations by their location to make sure that the tests get a
4144 // predictable order for the coverage mapping for the unused declarations.
4145 if (CodeGenOpts.DumpCoverageMapping)
4146 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4147 [] (const Decl *LHS, const Decl *RHS) {
4148 return LHS->getLocStart() < RHS->getLocStart();
4150 for (const auto *D : DeferredDecls) {
4151 switch (D->getKind()) {
4152 case Decl::CXXConversion:
4153 case Decl::CXXMethod:
4154 case Decl::Function:
4155 case Decl::ObjCMethod: {
4156 CodeGenPGO PGO(*this);
4157 GlobalDecl GD(cast<FunctionDecl>(D));
4158 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4159 getFunctionLinkage(GD));
4162 case Decl::CXXConstructor: {
4163 CodeGenPGO PGO(*this);
4164 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4165 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4166 getFunctionLinkage(GD));
4169 case Decl::CXXDestructor: {
4170 CodeGenPGO PGO(*this);
4171 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4172 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4173 getFunctionLinkage(GD));
4182 /// Turns the given pointer into a constant.
4183 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4185 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4186 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4187 return llvm::ConstantInt::get(i64, PtrInt);
4190 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4191 llvm::NamedMDNode *&GlobalMetadata,
4193 llvm::GlobalValue *Addr) {
4194 if (!GlobalMetadata)
4196 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4198 // TODO: should we report variant information for ctors/dtors?
4199 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4200 llvm::ConstantAsMetadata::get(GetPointerConstant(
4201 CGM.getLLVMContext(), D.getDecl()))};
4202 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4205 /// For each function which is declared within an extern "C" region and marked
4206 /// as 'used', but has internal linkage, create an alias from the unmangled
4207 /// name to the mangled name if possible. People expect to be able to refer
4208 /// to such functions with an unmangled name from inline assembly within the
4209 /// same translation unit.
4210 void CodeGenModule::EmitStaticExternCAliases() {
4211 // Don't do anything if we're generating CUDA device code -- the NVPTX
4212 // assembly target doesn't support aliases.
4213 if (Context.getTargetInfo().getTriple().isNVPTX())
4215 for (auto &I : StaticExternCValues) {
4216 IdentifierInfo *Name = I.first;
4217 llvm::GlobalValue *Val = I.second;
4218 if (Val && !getModule().getNamedValue(Name->getName()))
4219 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4223 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4224 GlobalDecl &Result) const {
4225 auto Res = Manglings.find(MangledName);
4226 if (Res == Manglings.end())
4228 Result = Res->getValue();
4232 /// Emits metadata nodes associating all the global values in the
4233 /// current module with the Decls they came from. This is useful for
4234 /// projects using IR gen as a subroutine.
4236 /// Since there's currently no way to associate an MDNode directly
4237 /// with an llvm::GlobalValue, we create a global named metadata
4238 /// with the name 'clang.global.decl.ptrs'.
4239 void CodeGenModule::EmitDeclMetadata() {
4240 llvm::NamedMDNode *GlobalMetadata = nullptr;
4242 for (auto &I : MangledDeclNames) {
4243 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4244 // Some mangled names don't necessarily have an associated GlobalValue
4245 // in this module, e.g. if we mangled it for DebugInfo.
4247 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4251 /// Emits metadata nodes for all the local variables in the current
4253 void CodeGenFunction::EmitDeclMetadata() {
4254 if (LocalDeclMap.empty()) return;
4256 llvm::LLVMContext &Context = getLLVMContext();
4258 // Find the unique metadata ID for this name.
4259 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4261 llvm::NamedMDNode *GlobalMetadata = nullptr;
4263 for (auto &I : LocalDeclMap) {
4264 const Decl *D = I.first;
4265 llvm::Value *Addr = I.second.getPointer();
4266 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4267 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4268 Alloca->setMetadata(
4269 DeclPtrKind, llvm::MDNode::get(
4270 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4271 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4272 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4273 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4278 void CodeGenModule::EmitVersionIdentMetadata() {
4279 llvm::NamedMDNode *IdentMetadata =
4280 TheModule.getOrInsertNamedMetadata("llvm.ident");
4281 std::string Version = getClangFullVersion();
4282 llvm::LLVMContext &Ctx = TheModule.getContext();
4284 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4285 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4288 void CodeGenModule::EmitTargetMetadata() {
4289 // Warning, new MangledDeclNames may be appended within this loop.
4290 // We rely on MapVector insertions adding new elements to the end
4291 // of the container.
4292 // FIXME: Move this loop into the one target that needs it, and only
4293 // loop over those declarations for which we couldn't emit the target
4294 // metadata when we emitted the declaration.
4295 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4296 auto Val = *(MangledDeclNames.begin() + I);
4297 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4298 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4299 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4303 void CodeGenModule::EmitCoverageFile() {
4304 if (getCodeGenOpts().CoverageDataFile.empty() &&
4305 getCodeGenOpts().CoverageNotesFile.empty())
4308 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4312 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4313 llvm::LLVMContext &Ctx = TheModule.getContext();
4314 auto *CoverageDataFile =
4315 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4316 auto *CoverageNotesFile =
4317 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4318 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4319 llvm::MDNode *CU = CUNode->getOperand(i);
4320 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4321 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4325 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4326 // Sema has checked that all uuid strings are of the form
4327 // "12345678-1234-1234-1234-1234567890ab".
4328 assert(Uuid.size() == 36);
4329 for (unsigned i = 0; i < 36; ++i) {
4330 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4331 else assert(isHexDigit(Uuid[i]));
4334 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4335 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4337 llvm::Constant *Field3[8];
4338 for (unsigned Idx = 0; Idx < 8; ++Idx)
4339 Field3[Idx] = llvm::ConstantInt::get(
4340 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4342 llvm::Constant *Fields[4] = {
4343 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4344 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4345 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4346 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4349 return llvm::ConstantStruct::getAnon(Fields);
4352 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4354 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4355 // FIXME: should we even be calling this method if RTTI is disabled
4356 // and it's not for EH?
4357 if (!ForEH && !getLangOpts().RTTI)
4358 return llvm::Constant::getNullValue(Int8PtrTy);
4360 if (ForEH && Ty->isObjCObjectPointerType() &&
4361 LangOpts.ObjCRuntime.isGNUFamily())
4362 return ObjCRuntime->GetEHType(Ty);
4364 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4367 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4368 for (auto RefExpr : D->varlists()) {
4369 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4371 VD->getAnyInitializer() &&
4372 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4375 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4376 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4377 VD, Addr, RefExpr->getLocStart(), PerformInit))
4378 CXXGlobalInits.push_back(InitFunction);
4382 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4383 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4387 if (isExternallyVisible(T->getLinkage())) {
4388 std::string OutName;
4389 llvm::raw_string_ostream Out(OutName);
4390 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4392 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4394 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4395 llvm::ArrayRef<llvm::Metadata *>());
4401 /// Returns whether this module needs the "all-vtables" type identifier.
4402 bool CodeGenModule::NeedAllVtablesTypeId() const {
4403 // Returns true if at least one of vtable-based CFI checkers is enabled and
4404 // is not in the trapping mode.
4405 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4406 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4407 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4408 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4409 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4410 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4411 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4412 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4415 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4417 const CXXRecordDecl *RD) {
4418 llvm::Metadata *MD =
4419 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4420 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4422 if (CodeGenOpts.SanitizeCfiCrossDso)
4423 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4424 VTable->addTypeMetadata(Offset.getQuantity(),
4425 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4427 if (NeedAllVtablesTypeId()) {
4428 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4429 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4433 // Fills in the supplied string map with the set of target features for the
4434 // passed in function.
4435 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4436 const FunctionDecl *FD) {
4437 StringRef TargetCPU = Target.getTargetOpts().CPU;
4438 if (const auto *TD = FD->getAttr<TargetAttr>()) {
4439 // If we have a TargetAttr build up the feature map based on that.
4440 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4442 // Make a copy of the features as passed on the command line into the
4443 // beginning of the additional features from the function to override.
4444 ParsedAttr.first.insert(ParsedAttr.first.begin(),
4445 Target.getTargetOpts().FeaturesAsWritten.begin(),
4446 Target.getTargetOpts().FeaturesAsWritten.end());
4448 if (ParsedAttr.second != "")
4449 TargetCPU = ParsedAttr.second;
4451 // Now populate the feature map, first with the TargetCPU which is either
4452 // the default or a new one from the target attribute string. Then we'll use
4453 // the passed in features (FeaturesAsWritten) along with the new ones from
4455 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4457 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4458 Target.getTargetOpts().Features);
4462 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4464 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4469 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4470 CodeGenFunction &CGF) {
4471 llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
4472 auto SamplerT = getOpenCLRuntime().getSamplerType();
4473 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4474 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4475 "__translate_sampler_initializer"),