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 "CodeGenFunction.h"
24 #include "CodeGenPGO.h"
25 #include "CodeGenTBAA.h"
26 #include "CoverageMappingGen.h"
27 #include "TargetInfo.h"
28 #include "clang/AST/ASTContext.h"
29 #include "clang/AST/CharUnits.h"
30 #include "clang/AST/DeclCXX.h"
31 #include "clang/AST/DeclObjC.h"
32 #include "clang/AST/DeclTemplate.h"
33 #include "clang/AST/Mangle.h"
34 #include "clang/AST/RecordLayout.h"
35 #include "clang/AST/RecursiveASTVisitor.h"
36 #include "clang/Basic/Builtins.h"
37 #include "clang/Basic/CharInfo.h"
38 #include "clang/Basic/Diagnostic.h"
39 #include "clang/Basic/Module.h"
40 #include "clang/Basic/SourceManager.h"
41 #include "clang/Basic/TargetInfo.h"
42 #include "clang/Basic/Version.h"
43 #include "clang/Frontend/CodeGenOptions.h"
44 #include "clang/Sema/SemaDiagnostic.h"
45 #include "llvm/ADT/APSInt.h"
46 #include "llvm/ADT/Triple.h"
47 #include "llvm/IR/CallSite.h"
48 #include "llvm/IR/CallingConv.h"
49 #include "llvm/IR/DataLayout.h"
50 #include "llvm/IR/Intrinsics.h"
51 #include "llvm/IR/LLVMContext.h"
52 #include "llvm/IR/Module.h"
53 #include "llvm/ProfileData/InstrProfReader.h"
54 #include "llvm/Support/ConvertUTF.h"
55 #include "llvm/Support/ErrorHandling.h"
56 #include "llvm/Support/MD5.h"
58 using namespace clang;
59 using namespace CodeGen;
61 static const char AnnotationSection[] = "llvm.metadata";
63 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
64 switch (CGM.getTarget().getCXXABI().getKind()) {
65 case TargetCXXABI::GenericAArch64:
66 case TargetCXXABI::GenericARM:
67 case TargetCXXABI::iOS:
68 case TargetCXXABI::iOS64:
69 case TargetCXXABI::WatchOS:
70 case TargetCXXABI::GenericMIPS:
71 case TargetCXXABI::GenericItanium:
72 case TargetCXXABI::WebAssembly:
73 return CreateItaniumCXXABI(CGM);
74 case TargetCXXABI::Microsoft:
75 return CreateMicrosoftCXXABI(CGM);
78 llvm_unreachable("invalid C++ ABI kind");
81 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
82 const PreprocessorOptions &PPO,
83 const CodeGenOptions &CGO, llvm::Module &M,
84 DiagnosticsEngine &diags,
85 CoverageSourceInfo *CoverageInfo)
86 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
87 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
88 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
89 VMContext(M.getContext()), TBAA(nullptr), TheTargetCodeGenInfo(nullptr),
90 Types(*this), VTables(*this), ObjCRuntime(nullptr),
91 OpenCLRuntime(nullptr), OpenMPRuntime(nullptr), CUDARuntime(nullptr),
92 DebugInfo(nullptr), ObjCData(nullptr),
93 NoObjCARCExceptionsMetadata(nullptr), PGOReader(nullptr),
94 CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
95 NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
96 NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
97 BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
98 GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
99 LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
101 // Initialize the type cache.
102 llvm::LLVMContext &LLVMContext = M.getContext();
103 VoidTy = llvm::Type::getVoidTy(LLVMContext);
104 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
105 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
106 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
107 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
108 FloatTy = llvm::Type::getFloatTy(LLVMContext);
109 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
110 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
111 PointerAlignInBytes =
112 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
114 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
115 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
116 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
117 Int8PtrTy = Int8Ty->getPointerTo(0);
118 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
120 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
121 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
126 createOpenCLRuntime();
128 createOpenMPRuntime();
132 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
133 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
134 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
135 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
136 getCXXABI().getMangleContext());
138 // If debug info or coverage generation is enabled, create the CGDebugInfo
140 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
141 CodeGenOpts.EmitGcovArcs ||
142 CodeGenOpts.EmitGcovNotes)
143 DebugInfo = new CGDebugInfo(*this);
145 Block.GlobalUniqueCount = 0;
147 if (C.getLangOpts().ObjC1)
148 ObjCData = new ObjCEntrypoints();
150 if (!CodeGenOpts.InstrProfileInput.empty()) {
152 llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput);
153 if (std::error_code EC = ReaderOrErr.getError()) {
154 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
155 "Could not read profile %0: %1");
156 getDiags().Report(DiagID) << CodeGenOpts.InstrProfileInput
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 delete OpenCLRuntime;
171 delete OpenMPRuntime;
173 delete TheTargetCodeGenInfo;
179 void CodeGenModule::createObjCRuntime() {
180 // This is just isGNUFamily(), but we want to force implementors of
181 // new ABIs to decide how best to do this.
182 switch (LangOpts.ObjCRuntime.getKind()) {
183 case ObjCRuntime::GNUstep:
184 case ObjCRuntime::GCC:
185 case ObjCRuntime::ObjFW:
186 ObjCRuntime = CreateGNUObjCRuntime(*this);
189 case ObjCRuntime::FragileMacOSX:
190 case ObjCRuntime::MacOSX:
191 case ObjCRuntime::iOS:
192 case ObjCRuntime::WatchOS:
193 ObjCRuntime = CreateMacObjCRuntime(*this);
196 llvm_unreachable("bad runtime kind");
199 void CodeGenModule::createOpenCLRuntime() {
200 OpenCLRuntime = new CGOpenCLRuntime(*this);
203 void CodeGenModule::createOpenMPRuntime() {
204 OpenMPRuntime = new CGOpenMPRuntime(*this);
207 void CodeGenModule::createCUDARuntime() {
208 CUDARuntime = CreateNVCUDARuntime(*this);
211 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
212 Replacements[Name] = C;
215 void CodeGenModule::applyReplacements() {
216 for (auto &I : Replacements) {
217 StringRef MangledName = I.first();
218 llvm::Constant *Replacement = I.second;
219 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
222 auto *OldF = cast<llvm::Function>(Entry);
223 auto *NewF = dyn_cast<llvm::Function>(Replacement);
225 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
226 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
228 auto *CE = cast<llvm::ConstantExpr>(Replacement);
229 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
230 CE->getOpcode() == llvm::Instruction::GetElementPtr);
231 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
235 // Replace old with new, but keep the old order.
236 OldF->replaceAllUsesWith(Replacement);
238 NewF->removeFromParent();
239 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
242 OldF->eraseFromParent();
246 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
247 GlobalValReplacements.push_back(std::make_pair(GV, C));
250 void CodeGenModule::applyGlobalValReplacements() {
251 for (auto &I : GlobalValReplacements) {
252 llvm::GlobalValue *GV = I.first;
253 llvm::Constant *C = I.second;
255 GV->replaceAllUsesWith(C);
256 GV->eraseFromParent();
260 // This is only used in aliases that we created and we know they have a
262 static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
263 llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
264 const llvm::Constant *C = &GA;
266 C = C->stripPointerCasts();
267 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
269 // stripPointerCasts will not walk over weak aliases.
270 auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
273 if (!Visited.insert(GA2).second)
275 C = GA2->getAliasee();
279 void CodeGenModule::checkAliases() {
280 // Check if the constructed aliases are well formed. It is really unfortunate
281 // that we have to do this in CodeGen, but we only construct mangled names
282 // and aliases during codegen.
284 DiagnosticsEngine &Diags = getDiags();
285 for (const GlobalDecl &GD : Aliases) {
286 const auto *D = cast<ValueDecl>(GD.getDecl());
287 const AliasAttr *AA = D->getAttr<AliasAttr>();
288 StringRef MangledName = getMangledName(GD);
289 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
290 auto *Alias = cast<llvm::GlobalAlias>(Entry);
291 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
294 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
295 } else if (GV->isDeclaration()) {
297 Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
300 llvm::Constant *Aliasee = Alias->getAliasee();
301 llvm::GlobalValue *AliaseeGV;
302 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
303 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
305 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
307 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
308 StringRef AliasSection = SA->getName();
309 if (AliasSection != AliaseeGV->getSection())
310 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
314 // We have to handle alias to weak aliases in here. LLVM itself disallows
315 // this since the object semantics would not match the IL one. For
316 // compatibility with gcc we implement it by just pointing the alias
317 // to its aliasee's aliasee. We also warn, since the user is probably
318 // expecting the link to be weak.
319 if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
320 if (GA->mayBeOverridden()) {
321 Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
322 << GV->getName() << GA->getName();
323 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
324 GA->getAliasee(), Alias->getType());
325 Alias->setAliasee(Aliasee);
332 for (const GlobalDecl &GD : Aliases) {
333 StringRef MangledName = getMangledName(GD);
334 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
335 auto *Alias = cast<llvm::GlobalAlias>(Entry);
336 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
337 Alias->eraseFromParent();
341 void CodeGenModule::clear() {
342 DeferredDeclsToEmit.clear();
344 OpenMPRuntime->clear();
347 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
348 StringRef MainFile) {
349 if (!hasDiagnostics())
351 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
352 if (MainFile.empty())
353 MainFile = "<stdin>";
354 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
356 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
360 void CodeGenModule::Release() {
362 applyGlobalValReplacements();
365 EmitCXXGlobalInitFunc();
366 EmitCXXGlobalDtorFunc();
367 EmitCXXThreadLocalInitFunc();
369 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
370 AddGlobalCtor(ObjCInitFunction);
371 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
373 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
374 AddGlobalCtor(CudaCtorFunction);
375 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
376 AddGlobalDtor(CudaDtorFunction);
379 if (llvm::Function *OpenMPRegistrationFunction =
380 OpenMPRuntime->emitRegistrationFunction())
381 AddGlobalCtor(OpenMPRegistrationFunction, 0);
383 getModule().setMaximumFunctionCount(PGOReader->getMaximumFunctionCount());
384 if (PGOStats.hasDiagnostics())
385 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
387 EmitCtorList(GlobalCtors, "llvm.global_ctors");
388 EmitCtorList(GlobalDtors, "llvm.global_dtors");
389 EmitGlobalAnnotations();
390 EmitStaticExternCAliases();
391 EmitDeferredUnusedCoverageMappings();
393 CoverageMapping->emit();
396 if (CodeGenOpts.Autolink &&
397 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
398 EmitModuleLinkOptions();
400 if (CodeGenOpts.DwarfVersion) {
401 // We actually want the latest version when there are conflicts.
402 // We can change from Warning to Latest if such mode is supported.
403 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
404 CodeGenOpts.DwarfVersion);
406 if (CodeGenOpts.EmitCodeView) {
407 // Indicate that we want CodeView in the metadata.
408 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
410 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
411 // We don't support LTO with 2 with different StrictVTablePointers
412 // FIXME: we could support it by stripping all the information introduced
413 // by StrictVTablePointers.
415 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
417 llvm::Metadata *Ops[2] = {
418 llvm::MDString::get(VMContext, "StrictVTablePointers"),
419 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
420 llvm::Type::getInt32Ty(VMContext), 1))};
422 getModule().addModuleFlag(llvm::Module::Require,
423 "StrictVTablePointersRequirement",
424 llvm::MDNode::get(VMContext, Ops));
427 // We support a single version in the linked module. The LLVM
428 // parser will drop debug info with a different version number
429 // (and warn about it, too).
430 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
431 llvm::DEBUG_METADATA_VERSION);
433 // We need to record the widths of enums and wchar_t, so that we can generate
434 // the correct build attributes in the ARM backend.
435 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
436 if ( Arch == llvm::Triple::arm
437 || Arch == llvm::Triple::armeb
438 || Arch == llvm::Triple::thumb
439 || Arch == llvm::Triple::thumbeb) {
440 // Width of wchar_t in bytes
441 uint64_t WCharWidth =
442 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
443 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
445 // The minimum width of an enum in bytes
446 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
447 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
450 if (CodeGenOpts.SanitizeCfiCrossDso) {
451 // Indicate that we want cross-DSO control flow integrity checks.
452 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
455 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
456 llvm::PICLevel::Level PL = llvm::PICLevel::Default;
459 case 1: PL = llvm::PICLevel::Small; break;
460 case 2: PL = llvm::PICLevel::Large; break;
461 default: llvm_unreachable("Invalid PIC Level");
464 getModule().setPICLevel(PL);
467 SimplifyPersonality();
469 if (getCodeGenOpts().EmitDeclMetadata)
472 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
476 DebugInfo->finalize();
478 EmitVersionIdentMetadata();
480 EmitTargetMetadata();
483 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
484 // Make sure that this type is translated.
485 Types.UpdateCompletedType(TD);
488 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
491 return TBAA->getTBAAInfo(QTy);
494 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
497 return TBAA->getTBAAInfoForVTablePtr();
500 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
503 return TBAA->getTBAAStructInfo(QTy);
506 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
507 llvm::MDNode *AccessN,
511 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
514 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
515 /// and struct-path aware TBAA, the tag has the same format:
516 /// base type, access type and offset.
517 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
518 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
519 llvm::MDNode *TBAAInfo,
520 bool ConvertTypeToTag) {
521 if (ConvertTypeToTag && TBAA)
522 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
523 TBAA->getTBAAScalarTagInfo(TBAAInfo));
525 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
528 void CodeGenModule::DecorateInstructionWithInvariantGroup(
529 llvm::Instruction *I, const CXXRecordDecl *RD) {
530 llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
531 auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
532 // Check if we have to wrap MDString in MDNode.
534 MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
535 I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
538 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
539 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
540 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
543 /// ErrorUnsupported - Print out an error that codegen doesn't support the
544 /// specified stmt yet.
545 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
546 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
547 "cannot compile this %0 yet");
548 std::string Msg = Type;
549 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
550 << Msg << S->getSourceRange();
553 /// ErrorUnsupported - Print out an error that codegen doesn't support the
554 /// specified decl yet.
555 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
556 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
557 "cannot compile this %0 yet");
558 std::string Msg = Type;
559 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
562 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
563 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
566 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
567 const NamedDecl *D) const {
568 // Internal definitions always have default visibility.
569 if (GV->hasLocalLinkage()) {
570 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
574 // Set visibility for definitions.
575 LinkageInfo LV = D->getLinkageAndVisibility();
576 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
577 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
580 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
581 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
582 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
583 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
584 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
585 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
588 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
589 CodeGenOptions::TLSModel M) {
591 case CodeGenOptions::GeneralDynamicTLSModel:
592 return llvm::GlobalVariable::GeneralDynamicTLSModel;
593 case CodeGenOptions::LocalDynamicTLSModel:
594 return llvm::GlobalVariable::LocalDynamicTLSModel;
595 case CodeGenOptions::InitialExecTLSModel:
596 return llvm::GlobalVariable::InitialExecTLSModel;
597 case CodeGenOptions::LocalExecTLSModel:
598 return llvm::GlobalVariable::LocalExecTLSModel;
600 llvm_unreachable("Invalid TLS model!");
603 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
604 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
606 llvm::GlobalValue::ThreadLocalMode TLM;
607 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
609 // Override the TLS model if it is explicitly specified.
610 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
611 TLM = GetLLVMTLSModel(Attr->getModel());
614 GV->setThreadLocalMode(TLM);
617 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
618 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
620 // Some ABIs don't have constructor variants. Make sure that base and
621 // complete constructors get mangled the same.
622 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
623 if (!getTarget().getCXXABI().hasConstructorVariants()) {
624 CXXCtorType OrigCtorType = GD.getCtorType();
625 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
626 if (OrigCtorType == Ctor_Base)
627 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
631 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
632 if (!FoundStr.empty())
635 const auto *ND = cast<NamedDecl>(GD.getDecl());
636 SmallString<256> Buffer;
638 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
639 llvm::raw_svector_ostream Out(Buffer);
640 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
641 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
642 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
643 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
645 getCXXABI().getMangleContext().mangleName(ND, Out);
648 IdentifierInfo *II = ND->getIdentifier();
649 assert(II && "Attempt to mangle unnamed decl.");
653 // Keep the first result in the case of a mangling collision.
654 auto Result = Manglings.insert(std::make_pair(Str, GD));
655 return FoundStr = Result.first->first();
658 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
659 const BlockDecl *BD) {
660 MangleContext &MangleCtx = getCXXABI().getMangleContext();
661 const Decl *D = GD.getDecl();
663 SmallString<256> Buffer;
664 llvm::raw_svector_ostream Out(Buffer);
666 MangleCtx.mangleGlobalBlock(BD,
667 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
668 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
669 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
670 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
671 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
673 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
675 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
676 return Result.first->first();
679 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
680 return getModule().getNamedValue(Name);
683 /// AddGlobalCtor - Add a function to the list that will be called before
685 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
686 llvm::Constant *AssociatedData) {
687 // FIXME: Type coercion of void()* types.
688 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
691 /// AddGlobalDtor - Add a function to the list that will be called
692 /// when the module is unloaded.
693 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
694 // FIXME: Type coercion of void()* types.
695 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
698 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
699 // Ctor function type is void()*.
700 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
701 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
703 // Get the type of a ctor entry, { i32, void ()*, i8* }.
704 llvm::StructType *CtorStructTy = llvm::StructType::get(
705 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
707 // Construct the constructor and destructor arrays.
708 SmallVector<llvm::Constant *, 8> Ctors;
709 for (const auto &I : Fns) {
710 llvm::Constant *S[] = {
711 llvm::ConstantInt::get(Int32Ty, I.Priority, false),
712 llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy),
714 ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)
715 : llvm::Constant::getNullValue(VoidPtrTy))};
716 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
719 if (!Ctors.empty()) {
720 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
721 new llvm::GlobalVariable(TheModule, AT, false,
722 llvm::GlobalValue::AppendingLinkage,
723 llvm::ConstantArray::get(AT, Ctors),
728 llvm::GlobalValue::LinkageTypes
729 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
730 const auto *D = cast<FunctionDecl>(GD.getDecl());
732 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
734 if (isa<CXXDestructorDecl>(D) &&
735 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
737 // Destructor variants in the Microsoft C++ ABI are always internal or
738 // linkonce_odr thunks emitted on an as-needed basis.
739 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
740 : llvm::GlobalValue::LinkOnceODRLinkage;
743 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
746 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
747 const auto *FD = cast<FunctionDecl>(GD.getDecl());
749 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
750 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
751 // Don't dllexport/import destructor thunks.
752 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
757 if (FD->hasAttr<DLLImportAttr>())
758 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
759 else if (FD->hasAttr<DLLExportAttr>())
760 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
762 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
766 CodeGenModule::CreateCfiIdForTypeMetadata(llvm::Metadata *MD) {
767 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
768 if (!MDS) return nullptr;
771 llvm::MD5::MD5Result result;
772 md5.update(MDS->getString());
775 for (int i = 0; i < 8; ++i)
776 id |= static_cast<uint64_t>(result[i]) << (i * 8);
777 return llvm::ConstantInt::get(Int64Ty, id);
780 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
782 setNonAliasAttributes(D, F);
785 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
786 const CGFunctionInfo &Info,
788 unsigned CallingConv;
789 AttributeListType AttributeList;
790 ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
792 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
793 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
796 /// Determines whether the language options require us to model
797 /// unwind exceptions. We treat -fexceptions as mandating this
798 /// except under the fragile ObjC ABI with only ObjC exceptions
799 /// enabled. This means, for example, that C with -fexceptions
801 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
802 // If exceptions are completely disabled, obviously this is false.
803 if (!LangOpts.Exceptions) return false;
805 // If C++ exceptions are enabled, this is true.
806 if (LangOpts.CXXExceptions) return true;
808 // If ObjC exceptions are enabled, this depends on the ABI.
809 if (LangOpts.ObjCExceptions) {
810 return LangOpts.ObjCRuntime.hasUnwindExceptions();
816 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
820 if (CodeGenOpts.UnwindTables)
821 B.addAttribute(llvm::Attribute::UWTable);
823 if (!hasUnwindExceptions(LangOpts))
824 B.addAttribute(llvm::Attribute::NoUnwind);
826 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
827 B.addAttribute(llvm::Attribute::StackProtect);
828 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
829 B.addAttribute(llvm::Attribute::StackProtectStrong);
830 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
831 B.addAttribute(llvm::Attribute::StackProtectReq);
834 F->addAttributes(llvm::AttributeSet::FunctionIndex,
835 llvm::AttributeSet::get(
837 llvm::AttributeSet::FunctionIndex, B));
841 if (D->hasAttr<NakedAttr>()) {
842 // Naked implies noinline: we should not be inlining such functions.
843 B.addAttribute(llvm::Attribute::Naked);
844 B.addAttribute(llvm::Attribute::NoInline);
845 } else if (D->hasAttr<NoDuplicateAttr>()) {
846 B.addAttribute(llvm::Attribute::NoDuplicate);
847 } else if (D->hasAttr<NoInlineAttr>()) {
848 B.addAttribute(llvm::Attribute::NoInline);
849 } else if (D->hasAttr<AlwaysInlineAttr>() &&
850 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
851 llvm::Attribute::NoInline)) {
852 // (noinline wins over always_inline, and we can't specify both in IR)
853 B.addAttribute(llvm::Attribute::AlwaysInline);
856 if (D->hasAttr<ColdAttr>()) {
857 if (!D->hasAttr<OptimizeNoneAttr>())
858 B.addAttribute(llvm::Attribute::OptimizeForSize);
859 B.addAttribute(llvm::Attribute::Cold);
862 if (D->hasAttr<MinSizeAttr>())
863 B.addAttribute(llvm::Attribute::MinSize);
865 F->addAttributes(llvm::AttributeSet::FunctionIndex,
866 llvm::AttributeSet::get(
867 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
869 if (D->hasAttr<OptimizeNoneAttr>()) {
870 // OptimizeNone implies noinline; we should not be inlining such functions.
871 F->addFnAttr(llvm::Attribute::OptimizeNone);
872 F->addFnAttr(llvm::Attribute::NoInline);
874 // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
875 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
876 F->removeFnAttr(llvm::Attribute::MinSize);
877 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
878 "OptimizeNone and AlwaysInline on same function!");
880 // Attribute 'inlinehint' has no effect on 'optnone' functions.
881 // Explicitly remove it from the set of function attributes.
882 F->removeFnAttr(llvm::Attribute::InlineHint);
885 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
886 F->setUnnamedAddr(true);
887 else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
889 F->setUnnamedAddr(true);
891 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
893 F->setAlignment(alignment);
895 // Some C++ ABIs require 2-byte alignment for member functions, in order to
896 // reserve a bit for differentiating between virtual and non-virtual member
897 // functions. If the current target's C++ ABI requires this and this is a
898 // member function, set its alignment accordingly.
899 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
900 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
905 void CodeGenModule::SetCommonAttributes(const Decl *D,
906 llvm::GlobalValue *GV) {
907 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
908 setGlobalVisibility(GV, ND);
910 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
912 if (D && D->hasAttr<UsedAttr>())
916 void CodeGenModule::setAliasAttributes(const Decl *D,
917 llvm::GlobalValue *GV) {
918 SetCommonAttributes(D, GV);
920 // Process the dllexport attribute based on whether the original definition
921 // (not necessarily the aliasee) was exported.
922 if (D->hasAttr<DLLExportAttr>())
923 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
926 void CodeGenModule::setNonAliasAttributes(const Decl *D,
927 llvm::GlobalObject *GO) {
928 SetCommonAttributes(D, GO);
931 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
932 GO->setSection(SA->getName());
934 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
937 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
939 const CGFunctionInfo &FI) {
940 SetLLVMFunctionAttributes(D, FI, F);
941 SetLLVMFunctionAttributesForDefinition(D, F);
943 F->setLinkage(llvm::Function::InternalLinkage);
945 setNonAliasAttributes(D, F);
948 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
949 const NamedDecl *ND) {
950 // Set linkage and visibility in case we never see a definition.
951 LinkageInfo LV = ND->getLinkageAndVisibility();
952 if (LV.getLinkage() != ExternalLinkage) {
953 // Don't set internal linkage on declarations.
955 if (ND->hasAttr<DLLImportAttr>()) {
956 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
957 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
958 } else if (ND->hasAttr<DLLExportAttr>()) {
959 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
960 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
961 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
962 // "extern_weak" is overloaded in LLVM; we probably should have
963 // separate linkage types for this.
964 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
967 // Set visibility on a declaration only if it's explicit.
968 if (LV.isVisibilityExplicit())
969 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
973 void CodeGenModule::CreateFunctionBitSetEntry(const FunctionDecl *FD,
975 // Only if we are checking indirect calls.
976 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
979 // Non-static class methods are handled via vtable pointer checks elsewhere.
980 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
983 // Additionally, if building with cross-DSO support...
984 if (CodeGenOpts.SanitizeCfiCrossDso) {
985 // Don't emit entries for function declarations. In cross-DSO mode these are
986 // handled with better precision at run time.
989 // Skip available_externally functions. They won't be codegen'ed in the
990 // current module anyway.
991 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
995 llvm::NamedMDNode *BitsetsMD =
996 getModule().getOrInsertNamedMetadata("llvm.bitsets");
998 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
999 llvm::Metadata *BitsetOps[] = {
1000 MD, llvm::ConstantAsMetadata::get(F),
1001 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))};
1002 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps));
1004 // Emit a hash-based bit set entry for cross-DSO calls.
1005 if (CodeGenOpts.SanitizeCfiCrossDso) {
1006 if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) {
1007 llvm::Metadata *BitsetOps2[] = {
1008 llvm::ConstantAsMetadata::get(TypeId),
1009 llvm::ConstantAsMetadata::get(F),
1010 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(Int64Ty, 0))};
1011 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2));
1016 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1017 bool IsIncompleteFunction,
1019 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1020 // If this is an intrinsic function, set the function's attributes
1021 // to the intrinsic's attributes.
1022 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1026 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1028 if (!IsIncompleteFunction)
1029 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1031 // Add the Returned attribute for "this", except for iOS 5 and earlier
1032 // where substantial code, including the libstdc++ dylib, was compiled with
1033 // GCC and does not actually return "this".
1034 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1035 !(getTarget().getTriple().isiOS() &&
1036 getTarget().getTriple().isOSVersionLT(6))) {
1037 assert(!F->arg_empty() &&
1038 F->arg_begin()->getType()
1039 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1040 "unexpected this return");
1041 F->addAttribute(1, llvm::Attribute::Returned);
1044 // Only a few attributes are set on declarations; these may later be
1045 // overridden by a definition.
1047 setLinkageAndVisibilityForGV(F, FD);
1049 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1050 F->setSection(SA->getName());
1052 // A replaceable global allocation function does not act like a builtin by
1053 // default, only if it is invoked by a new-expression or delete-expression.
1054 if (FD->isReplaceableGlobalAllocationFunction())
1055 F->addAttribute(llvm::AttributeSet::FunctionIndex,
1056 llvm::Attribute::NoBuiltin);
1058 CreateFunctionBitSetEntry(FD, F);
1061 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1062 assert(!GV->isDeclaration() &&
1063 "Only globals with definition can force usage.");
1064 LLVMUsed.emplace_back(GV);
1067 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1068 assert(!GV->isDeclaration() &&
1069 "Only globals with definition can force usage.");
1070 LLVMCompilerUsed.emplace_back(GV);
1073 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1074 std::vector<llvm::WeakVH> &List) {
1075 // Don't create llvm.used if there is no need.
1079 // Convert List to what ConstantArray needs.
1080 SmallVector<llvm::Constant*, 8> UsedArray;
1081 UsedArray.resize(List.size());
1082 for (unsigned i = 0, e = List.size(); i != e; ++i) {
1084 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1085 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1088 if (UsedArray.empty())
1090 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1092 auto *GV = new llvm::GlobalVariable(
1093 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1094 llvm::ConstantArray::get(ATy, UsedArray), Name);
1096 GV->setSection("llvm.metadata");
1099 void CodeGenModule::emitLLVMUsed() {
1100 emitUsed(*this, "llvm.used", LLVMUsed);
1101 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1104 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1105 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1106 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1109 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1110 llvm::SmallString<32> Opt;
1111 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1112 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1113 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1116 void CodeGenModule::AddDependentLib(StringRef Lib) {
1117 llvm::SmallString<24> Opt;
1118 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1119 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1120 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1123 /// \brief Add link options implied by the given module, including modules
1124 /// it depends on, using a postorder walk.
1125 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1126 SmallVectorImpl<llvm::Metadata *> &Metadata,
1127 llvm::SmallPtrSet<Module *, 16> &Visited) {
1128 // Import this module's parent.
1129 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1130 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1133 // Import this module's dependencies.
1134 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1135 if (Visited.insert(Mod->Imports[I - 1]).second)
1136 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1139 // Add linker options to link against the libraries/frameworks
1140 // described by this module.
1141 llvm::LLVMContext &Context = CGM.getLLVMContext();
1142 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1143 // Link against a framework. Frameworks are currently Darwin only, so we
1144 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1145 if (Mod->LinkLibraries[I-1].IsFramework) {
1146 llvm::Metadata *Args[2] = {
1147 llvm::MDString::get(Context, "-framework"),
1148 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1150 Metadata.push_back(llvm::MDNode::get(Context, Args));
1154 // Link against a library.
1155 llvm::SmallString<24> Opt;
1156 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1157 Mod->LinkLibraries[I-1].Library, Opt);
1158 auto *OptString = llvm::MDString::get(Context, Opt);
1159 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1163 void CodeGenModule::EmitModuleLinkOptions() {
1164 // Collect the set of all of the modules we want to visit to emit link
1165 // options, which is essentially the imported modules and all of their
1166 // non-explicit child modules.
1167 llvm::SetVector<clang::Module *> LinkModules;
1168 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1169 SmallVector<clang::Module *, 16> Stack;
1171 // Seed the stack with imported modules.
1172 for (Module *M : ImportedModules)
1173 if (Visited.insert(M).second)
1176 // Find all of the modules to import, making a little effort to prune
1177 // non-leaf modules.
1178 while (!Stack.empty()) {
1179 clang::Module *Mod = Stack.pop_back_val();
1181 bool AnyChildren = false;
1183 // Visit the submodules of this module.
1184 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1185 SubEnd = Mod->submodule_end();
1186 Sub != SubEnd; ++Sub) {
1187 // Skip explicit children; they need to be explicitly imported to be
1189 if ((*Sub)->IsExplicit)
1192 if (Visited.insert(*Sub).second) {
1193 Stack.push_back(*Sub);
1198 // We didn't find any children, so add this module to the list of
1199 // modules to link against.
1201 LinkModules.insert(Mod);
1205 // Add link options for all of the imported modules in reverse topological
1206 // order. We don't do anything to try to order import link flags with respect
1207 // to linker options inserted by things like #pragma comment().
1208 SmallVector<llvm::Metadata *, 16> MetadataArgs;
1210 for (Module *M : LinkModules)
1211 if (Visited.insert(M).second)
1212 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1213 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1214 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1216 // Add the linker options metadata flag.
1217 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1218 llvm::MDNode::get(getLLVMContext(),
1219 LinkerOptionsMetadata));
1222 void CodeGenModule::EmitDeferred() {
1223 // Emit code for any potentially referenced deferred decls. Since a
1224 // previously unused static decl may become used during the generation of code
1225 // for a static function, iterate until no changes are made.
1227 if (!DeferredVTables.empty()) {
1228 EmitDeferredVTables();
1230 // Emitting a v-table doesn't directly cause more v-tables to
1231 // become deferred, although it can cause functions to be
1232 // emitted that then need those v-tables.
1233 assert(DeferredVTables.empty());
1236 // Stop if we're out of both deferred v-tables and deferred declarations.
1237 if (DeferredDeclsToEmit.empty())
1240 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1241 // work, it will not interfere with this.
1242 std::vector<DeferredGlobal> CurDeclsToEmit;
1243 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1245 for (DeferredGlobal &G : CurDeclsToEmit) {
1246 GlobalDecl D = G.GD;
1247 llvm::GlobalValue *GV = G.GV;
1250 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1251 // to get GlobalValue with exactly the type we need, not something that
1252 // might had been created for another decl with the same mangled name but
1254 // FIXME: Support for variables is not implemented yet.
1255 if (isa<FunctionDecl>(D.getDecl()))
1256 GV = cast<llvm::GlobalValue>(GetAddrOfGlobal(D, /*IsForDefinition=*/true));
1259 GV = GetGlobalValue(getMangledName(D));
1261 // Check to see if we've already emitted this. This is necessary
1262 // for a couple of reasons: first, decls can end up in the
1263 // deferred-decls queue multiple times, and second, decls can end
1264 // up with definitions in unusual ways (e.g. by an extern inline
1265 // function acquiring a strong function redefinition). Just
1266 // ignore these cases.
1267 if (GV && !GV->isDeclaration())
1270 // Otherwise, emit the definition and move on to the next one.
1271 EmitGlobalDefinition(D, GV);
1273 // If we found out that we need to emit more decls, do that recursively.
1274 // This has the advantage that the decls are emitted in a DFS and related
1275 // ones are close together, which is convenient for testing.
1276 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1278 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1283 void CodeGenModule::EmitGlobalAnnotations() {
1284 if (Annotations.empty())
1287 // Create a new global variable for the ConstantStruct in the Module.
1288 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1289 Annotations[0]->getType(), Annotations.size()), Annotations);
1290 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1291 llvm::GlobalValue::AppendingLinkage,
1292 Array, "llvm.global.annotations");
1293 gv->setSection(AnnotationSection);
1296 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1297 llvm::Constant *&AStr = AnnotationStrings[Str];
1301 // Not found yet, create a new global.
1302 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1304 new llvm::GlobalVariable(getModule(), s->getType(), true,
1305 llvm::GlobalValue::PrivateLinkage, s, ".str");
1306 gv->setSection(AnnotationSection);
1307 gv->setUnnamedAddr(true);
1312 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1313 SourceManager &SM = getContext().getSourceManager();
1314 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1316 return EmitAnnotationString(PLoc.getFilename());
1317 return EmitAnnotationString(SM.getBufferName(Loc));
1320 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1321 SourceManager &SM = getContext().getSourceManager();
1322 PresumedLoc PLoc = SM.getPresumedLoc(L);
1323 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1324 SM.getExpansionLineNumber(L);
1325 return llvm::ConstantInt::get(Int32Ty, LineNo);
1328 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1329 const AnnotateAttr *AA,
1331 // Get the globals for file name, annotation, and the line number.
1332 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1333 *UnitGV = EmitAnnotationUnit(L),
1334 *LineNoCst = EmitAnnotationLineNo(L);
1336 // Create the ConstantStruct for the global annotation.
1337 llvm::Constant *Fields[4] = {
1338 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1339 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1340 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1343 return llvm::ConstantStruct::getAnon(Fields);
1346 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1347 llvm::GlobalValue *GV) {
1348 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1349 // Get the struct elements for these annotations.
1350 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1351 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1354 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1355 SourceLocation Loc) const {
1356 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1357 // Blacklist by function name.
1358 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1360 // Blacklist by location.
1362 return SanitizerBL.isBlacklistedLocation(Loc);
1363 // If location is unknown, this may be a compiler-generated function. Assume
1364 // it's located in the main file.
1365 auto &SM = Context.getSourceManager();
1366 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1367 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1372 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1373 SourceLocation Loc, QualType Ty,
1374 StringRef Category) const {
1375 // For now globals can be blacklisted only in ASan and KASan.
1376 if (!LangOpts.Sanitize.hasOneOf(
1377 SanitizerKind::Address | SanitizerKind::KernelAddress))
1379 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1380 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1382 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1384 // Check global type.
1386 // Drill down the array types: if global variable of a fixed type is
1387 // blacklisted, we also don't instrument arrays of them.
1388 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1389 Ty = AT->getElementType();
1390 Ty = Ty.getCanonicalType().getUnqualifiedType();
1391 // We allow to blacklist only record types (classes, structs etc.)
1392 if (Ty->isRecordType()) {
1393 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1394 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1401 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1402 // Never defer when EmitAllDecls is specified.
1403 if (LangOpts.EmitAllDecls)
1406 return getContext().DeclMustBeEmitted(Global);
1409 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1410 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1411 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1412 // Implicit template instantiations may change linkage if they are later
1413 // explicitly instantiated, so they should not be emitted eagerly.
1415 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1416 // codegen for global variables, because they may be marked as threadprivate.
1417 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1418 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1424 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1425 const CXXUuidofExpr* E) {
1426 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1428 StringRef Uuid = E->getUuidAsStringRef(Context);
1429 std::string Name = "_GUID_" + Uuid.lower();
1430 std::replace(Name.begin(), Name.end(), '-', '_');
1432 // Contains a 32-bit field.
1433 CharUnits Alignment = CharUnits::fromQuantity(4);
1435 // Look for an existing global.
1436 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1437 return ConstantAddress(GV, Alignment);
1439 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1440 assert(Init && "failed to initialize as constant");
1442 auto *GV = new llvm::GlobalVariable(
1443 getModule(), Init->getType(),
1444 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1445 if (supportsCOMDAT())
1446 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1447 return ConstantAddress(GV, Alignment);
1450 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1451 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1452 assert(AA && "No alias?");
1454 CharUnits Alignment = getContext().getDeclAlign(VD);
1455 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1457 // See if there is already something with the target's name in the module.
1458 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1460 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1461 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1462 return ConstantAddress(Ptr, Alignment);
1465 llvm::Constant *Aliasee;
1466 if (isa<llvm::FunctionType>(DeclTy))
1467 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1468 GlobalDecl(cast<FunctionDecl>(VD)),
1469 /*ForVTable=*/false);
1471 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1472 llvm::PointerType::getUnqual(DeclTy),
1475 auto *F = cast<llvm::GlobalValue>(Aliasee);
1476 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1477 WeakRefReferences.insert(F);
1479 return ConstantAddress(Aliasee, Alignment);
1482 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1483 const auto *Global = cast<ValueDecl>(GD.getDecl());
1485 // Weak references don't produce any output by themselves.
1486 if (Global->hasAttr<WeakRefAttr>())
1489 // If this is an alias definition (which otherwise looks like a declaration)
1491 if (Global->hasAttr<AliasAttr>())
1492 return EmitAliasDefinition(GD);
1494 // If this is CUDA, be selective about which declarations we emit.
1495 if (LangOpts.CUDA) {
1496 if (LangOpts.CUDAIsDevice) {
1497 if (!Global->hasAttr<CUDADeviceAttr>() &&
1498 !Global->hasAttr<CUDAGlobalAttr>() &&
1499 !Global->hasAttr<CUDAConstantAttr>() &&
1500 !Global->hasAttr<CUDASharedAttr>())
1503 if (!Global->hasAttr<CUDAHostAttr>() && (
1504 Global->hasAttr<CUDADeviceAttr>() ||
1505 Global->hasAttr<CUDAConstantAttr>() ||
1506 Global->hasAttr<CUDASharedAttr>()))
1511 // If this is OpenMP device, check if it is legal to emit this global
1513 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1516 // Ignore declarations, they will be emitted on their first use.
1517 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1518 // Forward declarations are emitted lazily on first use.
1519 if (!FD->doesThisDeclarationHaveABody()) {
1520 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1523 StringRef MangledName = getMangledName(GD);
1525 // Compute the function info and LLVM type.
1526 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1527 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1529 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1530 /*DontDefer=*/false);
1534 const auto *VD = cast<VarDecl>(Global);
1535 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1537 if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1538 !Context.isMSStaticDataMemberInlineDefinition(VD))
1542 // Defer code generation to first use when possible, e.g. if this is an inline
1543 // function. If the global must always be emitted, do it eagerly if possible
1544 // to benefit from cache locality.
1545 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1546 // Emit the definition if it can't be deferred.
1547 EmitGlobalDefinition(GD);
1551 // If we're deferring emission of a C++ variable with an
1552 // initializer, remember the order in which it appeared in the file.
1553 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1554 cast<VarDecl>(Global)->hasInit()) {
1555 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1556 CXXGlobalInits.push_back(nullptr);
1559 StringRef MangledName = getMangledName(GD);
1560 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1561 // The value has already been used and should therefore be emitted.
1562 addDeferredDeclToEmit(GV, GD);
1563 } else if (MustBeEmitted(Global)) {
1564 // The value must be emitted, but cannot be emitted eagerly.
1565 assert(!MayBeEmittedEagerly(Global));
1566 addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1568 // Otherwise, remember that we saw a deferred decl with this name. The
1569 // first use of the mangled name will cause it to move into
1570 // DeferredDeclsToEmit.
1571 DeferredDecls[MangledName] = GD;
1576 struct FunctionIsDirectlyRecursive :
1577 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1578 const StringRef Name;
1579 const Builtin::Context &BI;
1581 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1582 Name(N), BI(C), Result(false) {
1584 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1586 bool TraverseCallExpr(CallExpr *E) {
1587 const FunctionDecl *FD = E->getDirectCallee();
1590 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1591 if (Attr && Name == Attr->getLabel()) {
1595 unsigned BuiltinID = FD->getBuiltinID();
1596 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1598 StringRef BuiltinName = BI.getName(BuiltinID);
1599 if (BuiltinName.startswith("__builtin_") &&
1600 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1608 struct DLLImportFunctionVisitor
1609 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1610 bool SafeToInline = true;
1612 bool VisitVarDecl(VarDecl *VD) {
1613 // A thread-local variable cannot be imported.
1614 SafeToInline = !VD->getTLSKind();
1615 return SafeToInline;
1618 // Make sure we're not referencing non-imported vars or functions.
1619 bool VisitDeclRefExpr(DeclRefExpr *E) {
1620 ValueDecl *VD = E->getDecl();
1621 if (isa<FunctionDecl>(VD))
1622 SafeToInline = VD->hasAttr<DLLImportAttr>();
1623 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1624 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1625 return SafeToInline;
1627 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1628 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1629 return SafeToInline;
1631 bool VisitCXXNewExpr(CXXNewExpr *E) {
1632 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1633 return SafeToInline;
1638 // isTriviallyRecursive - Check if this function calls another
1639 // decl that, because of the asm attribute or the other decl being a builtin,
1640 // ends up pointing to itself.
1642 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1644 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1645 // asm labels are a special kind of mangling we have to support.
1646 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1649 Name = Attr->getLabel();
1651 Name = FD->getName();
1654 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1655 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1656 return Walker.Result;
1660 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1661 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1663 const auto *F = cast<FunctionDecl>(GD.getDecl());
1664 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1667 if (F->hasAttr<DLLImportAttr>()) {
1668 // Check whether it would be safe to inline this dllimport function.
1669 DLLImportFunctionVisitor Visitor;
1670 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1671 if (!Visitor.SafeToInline)
1675 // PR9614. Avoid cases where the source code is lying to us. An available
1676 // externally function should have an equivalent function somewhere else,
1677 // but a function that calls itself is clearly not equivalent to the real
1679 // This happens in glibc's btowc and in some configure checks.
1680 return !isTriviallyRecursive(F);
1683 /// If the type for the method's class was generated by
1684 /// CGDebugInfo::createContextChain(), the cache contains only a
1685 /// limited DIType without any declarations. Since EmitFunctionStart()
1686 /// needs to find the canonical declaration for each method, we need
1687 /// to construct the complete type prior to emitting the method.
1688 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1689 if (!D->isInstance())
1692 if (CGDebugInfo *DI = getModuleDebugInfo())
1693 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1694 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1695 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1699 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1700 const auto *D = cast<ValueDecl>(GD.getDecl());
1702 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1703 Context.getSourceManager(),
1704 "Generating code for declaration");
1706 if (isa<FunctionDecl>(D)) {
1707 // At -O0, don't generate IR for functions with available_externally
1709 if (!shouldEmitFunction(GD))
1712 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1713 CompleteDIClassType(Method);
1714 // Make sure to emit the definition(s) before we emit the thunks.
1715 // This is necessary for the generation of certain thunks.
1716 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1717 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1718 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1719 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1721 EmitGlobalFunctionDefinition(GD, GV);
1723 if (Method->isVirtual())
1724 getVTables().EmitThunks(GD);
1729 return EmitGlobalFunctionDefinition(GD, GV);
1732 if (const auto *VD = dyn_cast<VarDecl>(D))
1733 return EmitGlobalVarDefinition(VD);
1735 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1738 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1739 llvm::Function *NewFn);
1741 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1742 /// module, create and return an llvm Function with the specified type. If there
1743 /// is something in the module with the specified name, return it potentially
1744 /// bitcasted to the right type.
1746 /// If D is non-null, it specifies a decl that correspond to this. This is used
1747 /// to set the attributes on the function when it is first created.
1749 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1751 GlobalDecl GD, bool ForVTable,
1752 bool DontDefer, bool IsThunk,
1753 llvm::AttributeSet ExtraAttrs,
1754 bool IsForDefinition) {
1755 const Decl *D = GD.getDecl();
1757 // Lookup the entry, lazily creating it if necessary.
1758 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1760 if (WeakRefReferences.erase(Entry)) {
1761 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1762 if (FD && !FD->hasAttr<WeakAttr>())
1763 Entry->setLinkage(llvm::Function::ExternalLinkage);
1766 // Handle dropped DLL attributes.
1767 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1768 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1770 // If there are two attempts to define the same mangled name, issue an
1772 if (IsForDefinition && !Entry->isDeclaration()) {
1774 // Check that GD is not yet in ExplicitDefinitions is required to make
1775 // sure that we issue an error only once.
1776 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1777 (GD.getCanonicalDecl().getDecl() !=
1778 OtherGD.getCanonicalDecl().getDecl()) &&
1779 DiagnosedConflictingDefinitions.insert(GD).second) {
1780 getDiags().Report(D->getLocation(),
1781 diag::err_duplicate_mangled_name);
1782 getDiags().Report(OtherGD.getDecl()->getLocation(),
1783 diag::note_previous_definition);
1787 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1788 (Entry->getType()->getElementType() == Ty)) {
1792 // Make sure the result is of the correct type.
1793 // (If function is requested for a definition, we always need to create a new
1794 // function, not just return a bitcast.)
1795 if (!IsForDefinition)
1796 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1799 // This function doesn't have a complete type (for example, the return
1800 // type is an incomplete struct). Use a fake type instead, and make
1801 // sure not to try to set attributes.
1802 bool IsIncompleteFunction = false;
1804 llvm::FunctionType *FTy;
1805 if (isa<llvm::FunctionType>(Ty)) {
1806 FTy = cast<llvm::FunctionType>(Ty);
1808 FTy = llvm::FunctionType::get(VoidTy, false);
1809 IsIncompleteFunction = true;
1813 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
1814 Entry ? StringRef() : MangledName, &getModule());
1816 // If we already created a function with the same mangled name (but different
1817 // type) before, take its name and add it to the list of functions to be
1818 // replaced with F at the end of CodeGen.
1820 // This happens if there is a prototype for a function (e.g. "int f()") and
1821 // then a definition of a different type (e.g. "int f(int x)").
1825 // This might be an implementation of a function without a prototype, in
1826 // which case, try to do special replacement of calls which match the new
1827 // prototype. The really key thing here is that we also potentially drop
1828 // arguments from the call site so as to make a direct call, which makes the
1829 // inliner happier and suppresses a number of optimizer warnings (!) about
1830 // dropping arguments.
1831 if (!Entry->use_empty()) {
1832 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
1833 Entry->removeDeadConstantUsers();
1836 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
1837 F, Entry->getType()->getElementType()->getPointerTo());
1838 addGlobalValReplacement(Entry, BC);
1841 assert(F->getName() == MangledName && "name was uniqued!");
1843 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1844 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1845 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1846 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1847 llvm::AttributeSet::get(VMContext,
1848 llvm::AttributeSet::FunctionIndex,
1853 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1854 // each other bottoming out with the base dtor. Therefore we emit non-base
1855 // dtors on usage, even if there is no dtor definition in the TU.
1856 if (D && isa<CXXDestructorDecl>(D) &&
1857 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1859 addDeferredDeclToEmit(F, GD);
1861 // This is the first use or definition of a mangled name. If there is a
1862 // deferred decl with this name, remember that we need to emit it at the end
1864 auto DDI = DeferredDecls.find(MangledName);
1865 if (DDI != DeferredDecls.end()) {
1866 // Move the potentially referenced deferred decl to the
1867 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1868 // don't need it anymore).
1869 addDeferredDeclToEmit(F, DDI->second);
1870 DeferredDecls.erase(DDI);
1872 // Otherwise, there are cases we have to worry about where we're
1873 // using a declaration for which we must emit a definition but where
1874 // we might not find a top-level definition:
1875 // - member functions defined inline in their classes
1876 // - friend functions defined inline in some class
1877 // - special member functions with implicit definitions
1878 // If we ever change our AST traversal to walk into class methods,
1879 // this will be unnecessary.
1881 // We also don't emit a definition for a function if it's going to be an
1882 // entry in a vtable, unless it's already marked as used.
1883 } else if (getLangOpts().CPlusPlus && D) {
1884 // Look for a declaration that's lexically in a record.
1885 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1886 FD = FD->getPreviousDecl()) {
1887 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1888 if (FD->doesThisDeclarationHaveABody()) {
1889 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1897 // Make sure the result is of the requested type.
1898 if (!IsIncompleteFunction) {
1899 assert(F->getType()->getElementType() == Ty);
1903 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1904 return llvm::ConstantExpr::getBitCast(F, PTy);
1907 /// GetAddrOfFunction - Return the address of the given function. If Ty is
1908 /// non-null, then this function will use the specified type if it has to
1909 /// create it (this occurs when we see a definition of the function).
1910 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1914 bool IsForDefinition) {
1915 // If there was no specific requested type, just convert it now.
1917 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1918 auto CanonTy = Context.getCanonicalType(FD->getType());
1919 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
1922 StringRef MangledName = getMangledName(GD);
1923 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
1924 /*IsThunk=*/false, llvm::AttributeSet(),
1928 /// CreateRuntimeFunction - Create a new runtime function with the specified
1931 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1933 llvm::AttributeSet ExtraAttrs) {
1935 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1936 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1937 if (auto *F = dyn_cast<llvm::Function>(C))
1939 F->setCallingConv(getRuntimeCC());
1943 /// CreateBuiltinFunction - Create a new builtin function with the specified
1946 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
1948 llvm::AttributeSet ExtraAttrs) {
1950 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1951 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1952 if (auto *F = dyn_cast<llvm::Function>(C))
1954 F->setCallingConv(getBuiltinCC());
1958 /// isTypeConstant - Determine whether an object of this type can be emitted
1961 /// If ExcludeCtor is true, the duration when the object's constructor runs
1962 /// will not be considered. The caller will need to verify that the object is
1963 /// not written to during its construction.
1964 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1965 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1968 if (Context.getLangOpts().CPlusPlus) {
1969 if (const CXXRecordDecl *Record
1970 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1971 return ExcludeCtor && !Record->hasMutableFields() &&
1972 Record->hasTrivialDestructor();
1978 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1979 /// create and return an llvm GlobalVariable with the specified type. If there
1980 /// is something in the module with the specified name, return it potentially
1981 /// bitcasted to the right type.
1983 /// If D is non-null, it specifies a decl that correspond to this. This is used
1984 /// to set the attributes on the global when it is first created.
1986 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1987 llvm::PointerType *Ty,
1989 // Lookup the entry, lazily creating it if necessary.
1990 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1992 if (WeakRefReferences.erase(Entry)) {
1993 if (D && !D->hasAttr<WeakAttr>())
1994 Entry->setLinkage(llvm::Function::ExternalLinkage);
1997 // Handle dropped DLL attributes.
1998 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1999 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2001 if (Entry->getType() == Ty)
2004 // Make sure the result is of the correct type.
2005 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2006 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2008 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2011 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2012 auto *GV = new llvm::GlobalVariable(
2013 getModule(), Ty->getElementType(), false,
2014 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2015 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2017 // This is the first use or definition of a mangled name. If there is a
2018 // deferred decl with this name, remember that we need to emit it at the end
2020 auto DDI = DeferredDecls.find(MangledName);
2021 if (DDI != DeferredDecls.end()) {
2022 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2023 // list, and remove it from DeferredDecls (since we don't need it anymore).
2024 addDeferredDeclToEmit(GV, DDI->second);
2025 DeferredDecls.erase(DDI);
2028 // Handle things which are present even on external declarations.
2030 // FIXME: This code is overly simple and should be merged with other global
2032 GV->setConstant(isTypeConstant(D->getType(), false));
2034 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2036 setLinkageAndVisibilityForGV(GV, D);
2038 if (D->getTLSKind()) {
2039 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2040 CXXThreadLocals.push_back(D);
2044 // If required by the ABI, treat declarations of static data members with
2045 // inline initializers as definitions.
2046 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2047 EmitGlobalVarDefinition(D);
2050 // Handle XCore specific ABI requirements.
2051 if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
2052 D->getLanguageLinkage() == CLanguageLinkage &&
2053 D->getType().isConstant(Context) &&
2054 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2055 GV->setSection(".cp.rodata");
2058 if (AddrSpace != Ty->getAddressSpace())
2059 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2065 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2066 bool IsForDefinition) {
2067 if (isa<CXXConstructorDecl>(GD.getDecl()))
2068 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(GD.getDecl()),
2069 getFromCtorType(GD.getCtorType()),
2070 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2071 /*DontDefer=*/false, IsForDefinition);
2072 else if (isa<CXXDestructorDecl>(GD.getDecl()))
2073 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(GD.getDecl()),
2074 getFromDtorType(GD.getDtorType()),
2075 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2076 /*DontDefer=*/false, IsForDefinition);
2077 else if (isa<CXXMethodDecl>(GD.getDecl())) {
2078 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2079 cast<CXXMethodDecl>(GD.getDecl()));
2080 auto Ty = getTypes().GetFunctionType(*FInfo);
2081 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2083 } else if (isa<FunctionDecl>(GD.getDecl())) {
2084 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2085 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2086 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2089 return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
2092 llvm::GlobalVariable *
2093 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2095 llvm::GlobalValue::LinkageTypes Linkage) {
2096 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2097 llvm::GlobalVariable *OldGV = nullptr;
2100 // Check if the variable has the right type.
2101 if (GV->getType()->getElementType() == Ty)
2104 // Because C++ name mangling, the only way we can end up with an already
2105 // existing global with the same name is if it has been declared extern "C".
2106 assert(GV->isDeclaration() && "Declaration has wrong type!");
2110 // Create a new variable.
2111 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2112 Linkage, nullptr, Name);
2115 // Replace occurrences of the old variable if needed.
2116 GV->takeName(OldGV);
2118 if (!OldGV->use_empty()) {
2119 llvm::Constant *NewPtrForOldDecl =
2120 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2121 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2124 OldGV->eraseFromParent();
2127 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2128 !GV->hasAvailableExternallyLinkage())
2129 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2134 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2135 /// given global variable. If Ty is non-null and if the global doesn't exist,
2136 /// then it will be created with the specified type instead of whatever the
2137 /// normal requested type would be.
2138 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2140 assert(D->hasGlobalStorage() && "Not a global variable");
2141 QualType ASTTy = D->getType();
2143 Ty = getTypes().ConvertTypeForMem(ASTTy);
2145 llvm::PointerType *PTy =
2146 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2148 StringRef MangledName = getMangledName(D);
2149 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
2152 /// CreateRuntimeVariable - Create a new runtime global variable with the
2153 /// specified type and name.
2155 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2157 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2160 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2161 assert(!D->getInit() && "Cannot emit definite definitions here!");
2163 if (!MustBeEmitted(D)) {
2164 // If we have not seen a reference to this variable yet, place it
2165 // into the deferred declarations table to be emitted if needed
2167 StringRef MangledName = getMangledName(D);
2168 if (!GetGlobalValue(MangledName)) {
2169 DeferredDecls[MangledName] = D;
2174 // The tentative definition is the only definition.
2175 EmitGlobalVarDefinition(D);
2178 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2179 return Context.toCharUnitsFromBits(
2180 getDataLayout().getTypeStoreSizeInBits(Ty));
2183 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2184 unsigned AddrSpace) {
2185 if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2186 if (D->hasAttr<CUDAConstantAttr>())
2187 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2188 else if (D->hasAttr<CUDASharedAttr>())
2189 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2191 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2197 template<typename SomeDecl>
2198 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2199 llvm::GlobalValue *GV) {
2200 if (!getLangOpts().CPlusPlus)
2203 // Must have 'used' attribute, or else inline assembly can't rely on
2204 // the name existing.
2205 if (!D->template hasAttr<UsedAttr>())
2208 // Must have internal linkage and an ordinary name.
2209 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2212 // Must be in an extern "C" context. Entities declared directly within
2213 // a record are not extern "C" even if the record is in such a context.
2214 const SomeDecl *First = D->getFirstDecl();
2215 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2218 // OK, this is an internal linkage entity inside an extern "C" linkage
2219 // specification. Make a note of that so we can give it the "expected"
2220 // mangled name if nothing else is using that name.
2221 std::pair<StaticExternCMap::iterator, bool> R =
2222 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2224 // If we have multiple internal linkage entities with the same name
2225 // in extern "C" regions, none of them gets that name.
2227 R.first->second = nullptr;
2230 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2231 if (!CGM.supportsCOMDAT())
2234 if (D.hasAttr<SelectAnyAttr>())
2238 if (auto *VD = dyn_cast<VarDecl>(&D))
2239 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2241 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2245 case GVA_AvailableExternally:
2246 case GVA_StrongExternal:
2248 case GVA_DiscardableODR:
2252 llvm_unreachable("No such linkage");
2255 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2256 llvm::GlobalObject &GO) {
2257 if (!shouldBeInCOMDAT(*this, D))
2259 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2262 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
2263 llvm::Constant *Init = nullptr;
2264 QualType ASTTy = D->getType();
2265 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2266 bool NeedsGlobalCtor = false;
2267 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2269 const VarDecl *InitDecl;
2270 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2272 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization as part
2273 // of their declaration."
2274 if (getLangOpts().CPlusPlus && getLangOpts().CUDAIsDevice
2275 && D->hasAttr<CUDASharedAttr>()) {
2277 const auto *C = dyn_cast<CXXConstructExpr>(InitExpr);
2278 if (C == nullptr || !C->getConstructor()->hasTrivialBody())
2279 Error(D->getLocation(),
2280 "__shared__ variable cannot have an initialization.");
2282 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2283 } else if (!InitExpr) {
2284 // This is a tentative definition; tentative definitions are
2285 // implicitly initialized with { 0 }.
2287 // Note that tentative definitions are only emitted at the end of
2288 // a translation unit, so they should never have incomplete
2289 // type. In addition, EmitTentativeDefinition makes sure that we
2290 // never attempt to emit a tentative definition if a real one
2291 // exists. A use may still exists, however, so we still may need
2293 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2294 Init = EmitNullConstant(D->getType());
2296 initializedGlobalDecl = GlobalDecl(D);
2297 Init = EmitConstantInit(*InitDecl);
2300 QualType T = InitExpr->getType();
2301 if (D->getType()->isReferenceType())
2304 if (getLangOpts().CPlusPlus) {
2305 Init = EmitNullConstant(T);
2306 NeedsGlobalCtor = true;
2308 ErrorUnsupported(D, "static initializer");
2309 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2312 // We don't need an initializer, so remove the entry for the delayed
2313 // initializer position (just in case this entry was delayed) if we
2314 // also don't need to register a destructor.
2315 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2316 DelayedCXXInitPosition.erase(D);
2320 llvm::Type* InitType = Init->getType();
2321 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
2323 // Strip off a bitcast if we got one back.
2324 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2325 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2326 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2327 // All zero index gep.
2328 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2329 Entry = CE->getOperand(0);
2332 // Entry is now either a Function or GlobalVariable.
2333 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2335 // We have a definition after a declaration with the wrong type.
2336 // We must make a new GlobalVariable* and update everything that used OldGV
2337 // (a declaration or tentative definition) with the new GlobalVariable*
2338 // (which will be a definition).
2340 // This happens if there is a prototype for a global (e.g.
2341 // "extern int x[];") and then a definition of a different type (e.g.
2342 // "int x[10];"). This also happens when an initializer has a different type
2343 // from the type of the global (this happens with unions).
2345 GV->getType()->getElementType() != InitType ||
2346 GV->getType()->getAddressSpace() !=
2347 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2349 // Move the old entry aside so that we'll create a new one.
2350 Entry->setName(StringRef());
2352 // Make a new global with the correct type, this is now guaranteed to work.
2353 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
2355 // Replace all uses of the old global with the new global
2356 llvm::Constant *NewPtrForOldDecl =
2357 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2358 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2360 // Erase the old global, since it is no longer used.
2361 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2364 MaybeHandleStaticInExternC(D, GV);
2366 if (D->hasAttr<AnnotateAttr>())
2367 AddGlobalAnnotations(D, GV);
2369 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2370 // the device. [...]"
2371 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2372 // __device__, declares a variable that: [...]
2373 // Is accessible from all the threads within the grid and from the host
2374 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2375 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2376 if (GV && LangOpts.CUDA && LangOpts.CUDAIsDevice &&
2377 (D->hasAttr<CUDAConstantAttr>() || D->hasAttr<CUDADeviceAttr>())) {
2378 GV->setExternallyInitialized(true);
2380 GV->setInitializer(Init);
2382 // If it is safe to mark the global 'constant', do so now.
2383 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2384 isTypeConstant(D->getType(), true));
2386 // If it is in a read-only section, mark it 'constant'.
2387 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2388 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2389 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2390 GV->setConstant(true);
2393 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2395 // Set the llvm linkage type as appropriate.
2396 llvm::GlobalValue::LinkageTypes Linkage =
2397 getLLVMLinkageVarDefinition(D, GV->isConstant());
2399 // On Darwin, if the normal linkage of a C++ thread_local variable is
2400 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2401 // copies within a linkage unit; otherwise, the backing variable has
2402 // internal linkage and all accesses should just be calls to the
2403 // Itanium-specified entry point, which has the normal linkage of the
2404 // variable. This is to preserve the ability to change the implementation
2405 // behind the scenes.
2406 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2407 Context.getTargetInfo().getTriple().isOSDarwin() &&
2408 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2409 !llvm::GlobalVariable::isWeakLinkage(Linkage))
2410 Linkage = llvm::GlobalValue::InternalLinkage;
2412 GV->setLinkage(Linkage);
2413 if (D->hasAttr<DLLImportAttr>())
2414 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2415 else if (D->hasAttr<DLLExportAttr>())
2416 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2418 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2420 if (Linkage == llvm::GlobalVariable::CommonLinkage)
2421 // common vars aren't constant even if declared const.
2422 GV->setConstant(false);
2424 setNonAliasAttributes(D, GV);
2426 if (D->getTLSKind() && !GV->isThreadLocal()) {
2427 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2428 CXXThreadLocals.push_back(D);
2432 maybeSetTrivialComdat(*D, *GV);
2434 // Emit the initializer function if necessary.
2435 if (NeedsGlobalCtor || NeedsGlobalDtor)
2436 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2438 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2440 // Emit global variable debug information.
2441 if (CGDebugInfo *DI = getModuleDebugInfo())
2442 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2443 DI->EmitGlobalVariable(GV, D);
2446 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2447 CodeGenModule &CGM, const VarDecl *D,
2449 // Don't give variables common linkage if -fno-common was specified unless it
2450 // was overridden by a NoCommon attribute.
2451 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2455 // A declaration of an identifier for an object that has file scope without
2456 // an initializer, and without a storage-class specifier or with the
2457 // storage-class specifier static, constitutes a tentative definition.
2458 if (D->getInit() || D->hasExternalStorage())
2461 // A variable cannot be both common and exist in a section.
2462 if (D->hasAttr<SectionAttr>())
2465 // Thread local vars aren't considered common linkage.
2466 if (D->getTLSKind())
2469 // Tentative definitions marked with WeakImportAttr are true definitions.
2470 if (D->hasAttr<WeakImportAttr>())
2473 // A variable cannot be both common and exist in a comdat.
2474 if (shouldBeInCOMDAT(CGM, *D))
2477 // Declarations with a required alignment do not have common linakge in MSVC
2479 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2480 if (D->hasAttr<AlignedAttr>())
2482 QualType VarType = D->getType();
2483 if (Context.isAlignmentRequired(VarType))
2486 if (const auto *RT = VarType->getAs<RecordType>()) {
2487 const RecordDecl *RD = RT->getDecl();
2488 for (const FieldDecl *FD : RD->fields()) {
2489 if (FD->isBitField())
2491 if (FD->hasAttr<AlignedAttr>())
2493 if (Context.isAlignmentRequired(FD->getType()))
2502 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2503 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2504 if (Linkage == GVA_Internal)
2505 return llvm::Function::InternalLinkage;
2507 if (D->hasAttr<WeakAttr>()) {
2508 if (IsConstantVariable)
2509 return llvm::GlobalVariable::WeakODRLinkage;
2511 return llvm::GlobalVariable::WeakAnyLinkage;
2514 // We are guaranteed to have a strong definition somewhere else,
2515 // so we can use available_externally linkage.
2516 if (Linkage == GVA_AvailableExternally)
2517 return llvm::Function::AvailableExternallyLinkage;
2519 // Note that Apple's kernel linker doesn't support symbol
2520 // coalescing, so we need to avoid linkonce and weak linkages there.
2521 // Normally, this means we just map to internal, but for explicit
2522 // instantiations we'll map to external.
2524 // In C++, the compiler has to emit a definition in every translation unit
2525 // that references the function. We should use linkonce_odr because
2526 // a) if all references in this translation unit are optimized away, we
2527 // don't need to codegen it. b) if the function persists, it needs to be
2528 // merged with other definitions. c) C++ has the ODR, so we know the
2529 // definition is dependable.
2530 if (Linkage == GVA_DiscardableODR)
2531 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2532 : llvm::Function::InternalLinkage;
2534 // An explicit instantiation of a template has weak linkage, since
2535 // explicit instantiations can occur in multiple translation units
2536 // and must all be equivalent. However, we are not allowed to
2537 // throw away these explicit instantiations.
2538 if (Linkage == GVA_StrongODR)
2539 return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2540 : llvm::Function::ExternalLinkage;
2542 // C++ doesn't have tentative definitions and thus cannot have common
2544 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2545 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2546 CodeGenOpts.NoCommon))
2547 return llvm::GlobalVariable::CommonLinkage;
2549 // selectany symbols are externally visible, so use weak instead of
2550 // linkonce. MSVC optimizes away references to const selectany globals, so
2551 // all definitions should be the same and ODR linkage should be used.
2552 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2553 if (D->hasAttr<SelectAnyAttr>())
2554 return llvm::GlobalVariable::WeakODRLinkage;
2556 // Otherwise, we have strong external linkage.
2557 assert(Linkage == GVA_StrongExternal);
2558 return llvm::GlobalVariable::ExternalLinkage;
2561 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2562 const VarDecl *VD, bool IsConstant) {
2563 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2564 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2567 /// Replace the uses of a function that was declared with a non-proto type.
2568 /// We want to silently drop extra arguments from call sites
2569 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2570 llvm::Function *newFn) {
2572 if (old->use_empty()) return;
2574 llvm::Type *newRetTy = newFn->getReturnType();
2575 SmallVector<llvm::Value*, 4> newArgs;
2576 SmallVector<llvm::OperandBundleDef, 1> newBundles;
2578 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2580 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2581 llvm::User *user = use->getUser();
2583 // Recognize and replace uses of bitcasts. Most calls to
2584 // unprototyped functions will use bitcasts.
2585 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2586 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2587 replaceUsesOfNonProtoConstant(bitcast, newFn);
2591 // Recognize calls to the function.
2592 llvm::CallSite callSite(user);
2593 if (!callSite) continue;
2594 if (!callSite.isCallee(&*use)) continue;
2596 // If the return types don't match exactly, then we can't
2597 // transform this call unless it's dead.
2598 if (callSite->getType() != newRetTy && !callSite->use_empty())
2601 // Get the call site's attribute list.
2602 SmallVector<llvm::AttributeSet, 8> newAttrs;
2603 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2605 // Collect any return attributes from the call.
2606 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2608 llvm::AttributeSet::get(newFn->getContext(),
2609 oldAttrs.getRetAttributes()));
2611 // If the function was passed too few arguments, don't transform.
2612 unsigned newNumArgs = newFn->arg_size();
2613 if (callSite.arg_size() < newNumArgs) continue;
2615 // If extra arguments were passed, we silently drop them.
2616 // If any of the types mismatch, we don't transform.
2618 bool dontTransform = false;
2619 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2620 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2621 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2622 dontTransform = true;
2626 // Add any parameter attributes.
2627 if (oldAttrs.hasAttributes(argNo + 1))
2630 AttributeSet::get(newFn->getContext(),
2631 oldAttrs.getParamAttributes(argNo + 1)));
2636 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2637 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2638 oldAttrs.getFnAttributes()));
2640 // Okay, we can transform this. Create the new call instruction and copy
2641 // over the required information.
2642 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2644 // Copy over any operand bundles.
2645 callSite.getOperandBundlesAsDefs(newBundles);
2647 llvm::CallSite newCall;
2648 if (callSite.isCall()) {
2649 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2650 callSite.getInstruction());
2652 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2653 newCall = llvm::InvokeInst::Create(newFn,
2654 oldInvoke->getNormalDest(),
2655 oldInvoke->getUnwindDest(),
2656 newArgs, newBundles, "",
2657 callSite.getInstruction());
2659 newArgs.clear(); // for the next iteration
2661 if (!newCall->getType()->isVoidTy())
2662 newCall->takeName(callSite.getInstruction());
2663 newCall.setAttributes(
2664 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2665 newCall.setCallingConv(callSite.getCallingConv());
2667 // Finally, remove the old call, replacing any uses with the new one.
2668 if (!callSite->use_empty())
2669 callSite->replaceAllUsesWith(newCall.getInstruction());
2671 // Copy debug location attached to CI.
2672 if (callSite->getDebugLoc())
2673 newCall->setDebugLoc(callSite->getDebugLoc());
2675 callSite->eraseFromParent();
2679 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2680 /// implement a function with no prototype, e.g. "int foo() {}". If there are
2681 /// existing call uses of the old function in the module, this adjusts them to
2682 /// call the new function directly.
2684 /// This is not just a cleanup: the always_inline pass requires direct calls to
2685 /// functions to be able to inline them. If there is a bitcast in the way, it
2686 /// won't inline them. Instcombine normally deletes these calls, but it isn't
2688 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2689 llvm::Function *NewFn) {
2690 // If we're redefining a global as a function, don't transform it.
2691 if (!isa<llvm::Function>(Old)) return;
2693 replaceUsesOfNonProtoConstant(Old, NewFn);
2696 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2697 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2698 // If we have a definition, this might be a deferred decl. If the
2699 // instantiation is explicit, make sure we emit it at the end.
2700 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2701 GetAddrOfGlobalVar(VD);
2703 EmitTopLevelDecl(VD);
2706 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2707 llvm::GlobalValue *GV) {
2708 const auto *D = cast<FunctionDecl>(GD.getDecl());
2710 // Compute the function info and LLVM type.
2711 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2712 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2714 // Get or create the prototype for the function.
2715 if (!GV || (GV->getType()->getElementType() != Ty))
2716 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
2718 /*IsForDefinition=*/true));
2721 if (!GV->isDeclaration())
2724 // We need to set linkage and visibility on the function before
2725 // generating code for it because various parts of IR generation
2726 // want to propagate this information down (e.g. to local static
2728 auto *Fn = cast<llvm::Function>(GV);
2729 setFunctionLinkage(GD, Fn);
2730 setFunctionDLLStorageClass(GD, Fn);
2732 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
2733 setGlobalVisibility(Fn, D);
2735 MaybeHandleStaticInExternC(D, Fn);
2737 maybeSetTrivialComdat(*D, *Fn);
2739 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2741 setFunctionDefinitionAttributes(D, Fn);
2742 SetLLVMFunctionAttributesForDefinition(D, Fn);
2744 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2745 AddGlobalCtor(Fn, CA->getPriority());
2746 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2747 AddGlobalDtor(Fn, DA->getPriority());
2748 if (D->hasAttr<AnnotateAttr>())
2749 AddGlobalAnnotations(D, Fn);
2752 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2753 const auto *D = cast<ValueDecl>(GD.getDecl());
2754 const AliasAttr *AA = D->getAttr<AliasAttr>();
2755 assert(AA && "Not an alias?");
2757 StringRef MangledName = getMangledName(GD);
2759 if (AA->getAliasee() == MangledName) {
2760 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2764 // If there is a definition in the module, then it wins over the alias.
2765 // This is dubious, but allow it to be safe. Just ignore the alias.
2766 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2767 if (Entry && !Entry->isDeclaration())
2770 Aliases.push_back(GD);
2772 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2774 // Create a reference to the named value. This ensures that it is emitted
2775 // if a deferred decl.
2776 llvm::Constant *Aliasee;
2777 if (isa<llvm::FunctionType>(DeclTy))
2778 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2779 /*ForVTable=*/false);
2781 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2782 llvm::PointerType::getUnqual(DeclTy),
2785 // Create the new alias itself, but don't set a name yet.
2786 auto *GA = llvm::GlobalAlias::create(
2787 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
2790 if (GA->getAliasee() == Entry) {
2791 Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2795 assert(Entry->isDeclaration());
2797 // If there is a declaration in the module, then we had an extern followed
2798 // by the alias, as in:
2799 // extern int test6();
2801 // int test6() __attribute__((alias("test7")));
2803 // Remove it and replace uses of it with the alias.
2804 GA->takeName(Entry);
2806 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2808 Entry->eraseFromParent();
2810 GA->setName(MangledName);
2813 // Set attributes which are particular to an alias; this is a
2814 // specialization of the attributes which may be set on a global
2815 // variable/function.
2816 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2817 D->isWeakImported()) {
2818 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2821 if (const auto *VD = dyn_cast<VarDecl>(D))
2822 if (VD->getTLSKind())
2823 setTLSMode(GA, *VD);
2825 setAliasAttributes(D, GA);
2828 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2829 ArrayRef<llvm::Type*> Tys) {
2830 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2834 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2835 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2836 const StringLiteral *Literal, bool TargetIsLSB,
2837 bool &IsUTF16, unsigned &StringLength) {
2838 StringRef String = Literal->getString();
2839 unsigned NumBytes = String.size();
2841 // Check for simple case.
2842 if (!Literal->containsNonAsciiOrNull()) {
2843 StringLength = NumBytes;
2844 return *Map.insert(std::make_pair(String, nullptr)).first;
2847 // Otherwise, convert the UTF8 literals into a string of shorts.
2850 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2851 const UTF8 *FromPtr = (const UTF8 *)String.data();
2852 UTF16 *ToPtr = &ToBuf[0];
2854 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2855 &ToPtr, ToPtr + NumBytes,
2858 // ConvertUTF8toUTF16 returns the length in ToPtr.
2859 StringLength = ToPtr - &ToBuf[0];
2861 // Add an explicit null.
2863 return *Map.insert(std::make_pair(
2864 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2865 (StringLength + 1) * 2),
2869 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2870 GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2871 const StringLiteral *Literal, unsigned &StringLength) {
2872 StringRef String = Literal->getString();
2873 StringLength = String.size();
2874 return *Map.insert(std::make_pair(String, nullptr)).first;
2878 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2879 unsigned StringLength = 0;
2880 bool isUTF16 = false;
2881 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2882 GetConstantCFStringEntry(CFConstantStringMap, Literal,
2883 getDataLayout().isLittleEndian(), isUTF16,
2886 if (auto *C = Entry.second)
2887 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
2889 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2890 llvm::Constant *Zeros[] = { Zero, Zero };
2893 // If we don't already have it, get __CFConstantStringClassReference.
2894 if (!CFConstantStringClassRef) {
2895 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2896 Ty = llvm::ArrayType::get(Ty, 0);
2897 llvm::Constant *GV = CreateRuntimeVariable(Ty,
2898 "__CFConstantStringClassReference");
2899 // Decay array -> ptr
2900 V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
2901 CFConstantStringClassRef = V;
2904 V = CFConstantStringClassRef;
2906 QualType CFTy = getContext().getCFConstantStringType();
2908 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2910 llvm::Constant *Fields[4];
2913 Fields[0] = cast<llvm::ConstantExpr>(V);
2916 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2917 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2918 llvm::ConstantInt::get(Ty, 0x07C8);
2921 llvm::Constant *C = nullptr;
2923 auto Arr = llvm::makeArrayRef(
2924 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
2925 Entry.first().size() / 2);
2926 C = llvm::ConstantDataArray::get(VMContext, Arr);
2928 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
2931 // Note: -fwritable-strings doesn't make the backing store strings of
2932 // CFStrings writable. (See <rdar://problem/10657500>)
2934 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2935 llvm::GlobalValue::PrivateLinkage, C, ".str");
2936 GV->setUnnamedAddr(true);
2937 // Don't enforce the target's minimum global alignment, since the only use
2938 // of the string is via this class initializer.
2939 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2940 // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2941 // that changes the section it ends in, which surprises ld64.
2943 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2944 GV->setAlignment(Align.getQuantity());
2945 GV->setSection("__TEXT,__ustring");
2947 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2948 GV->setAlignment(Align.getQuantity());
2949 GV->setSection("__TEXT,__cstring,cstring_literals");
2954 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2957 // Cast the UTF16 string to the correct type.
2958 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2961 Ty = getTypes().ConvertType(getContext().LongTy);
2962 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2964 CharUnits Alignment = getPointerAlign();
2967 C = llvm::ConstantStruct::get(STy, Fields);
2968 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2969 llvm::GlobalVariable::PrivateLinkage, C,
2970 "_unnamed_cfstring_");
2971 GV->setSection("__DATA,__cfstring");
2972 GV->setAlignment(Alignment.getQuantity());
2975 return ConstantAddress(GV, Alignment);
2979 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2980 unsigned StringLength = 0;
2981 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2982 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2984 if (auto *C = Entry.second)
2985 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
2987 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2988 llvm::Constant *Zeros[] = { Zero, Zero };
2990 // If we don't already have it, get _NSConstantStringClassReference.
2991 if (!ConstantStringClassRef) {
2992 std::string StringClass(getLangOpts().ObjCConstantStringClass);
2993 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2995 if (LangOpts.ObjCRuntime.isNonFragile()) {
2997 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2998 : "OBJC_CLASS_$_" + StringClass;
2999 GV = getObjCRuntime().GetClassGlobal(str);
3000 // Make sure the result is of the correct type.
3001 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
3002 V = llvm::ConstantExpr::getBitCast(GV, PTy);
3003 ConstantStringClassRef = V;
3006 StringClass.empty() ? "_NSConstantStringClassReference"
3007 : "_" + StringClass + "ClassReference";
3008 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
3009 GV = CreateRuntimeVariable(PTy, str);
3010 // Decay array -> ptr
3011 V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
3012 ConstantStringClassRef = V;
3015 V = ConstantStringClassRef;
3017 if (!NSConstantStringType) {
3018 // Construct the type for a constant NSString.
3019 RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
3020 D->startDefinition();
3022 QualType FieldTypes[3];
3025 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
3027 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
3028 // unsigned int length;
3029 FieldTypes[2] = Context.UnsignedIntTy;
3032 for (unsigned i = 0; i < 3; ++i) {
3033 FieldDecl *Field = FieldDecl::Create(Context, D,
3035 SourceLocation(), nullptr,
3036 FieldTypes[i], /*TInfo=*/nullptr,
3037 /*BitWidth=*/nullptr,
3040 Field->setAccess(AS_public);
3044 D->completeDefinition();
3045 QualType NSTy = Context.getTagDeclType(D);
3046 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
3049 llvm::Constant *Fields[3];
3052 Fields[0] = cast<llvm::ConstantExpr>(V);
3056 llvm::ConstantDataArray::getString(VMContext, Entry.first());
3058 llvm::GlobalValue::LinkageTypes Linkage;
3060 Linkage = llvm::GlobalValue::PrivateLinkage;
3061 isConstant = !LangOpts.WritableStrings;
3063 auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
3064 Linkage, C, ".str");
3065 GV->setUnnamedAddr(true);
3066 // Don't enforce the target's minimum global alignment, since the only use
3067 // of the string is via this class initializer.
3068 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
3069 GV->setAlignment(Align.getQuantity());
3071 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3074 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
3075 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
3078 CharUnits Alignment = getPointerAlign();
3079 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
3080 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
3081 llvm::GlobalVariable::PrivateLinkage, C,
3082 "_unnamed_nsstring_");
3083 GV->setAlignment(Alignment.getQuantity());
3084 const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
3085 const char *NSStringNonFragileABISection =
3086 "__DATA,__objc_stringobj,regular,no_dead_strip";
3087 // FIXME. Fix section.
3088 GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
3089 ? NSStringNonFragileABISection
3093 return ConstantAddress(GV, Alignment);
3096 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3097 if (ObjCFastEnumerationStateType.isNull()) {
3098 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3099 D->startDefinition();
3101 QualType FieldTypes[] = {
3102 Context.UnsignedLongTy,
3103 Context.getPointerType(Context.getObjCIdType()),
3104 Context.getPointerType(Context.UnsignedLongTy),
3105 Context.getConstantArrayType(Context.UnsignedLongTy,
3106 llvm::APInt(32, 5), ArrayType::Normal, 0)
3109 for (size_t i = 0; i < 4; ++i) {
3110 FieldDecl *Field = FieldDecl::Create(Context,
3113 SourceLocation(), nullptr,
3114 FieldTypes[i], /*TInfo=*/nullptr,
3115 /*BitWidth=*/nullptr,
3118 Field->setAccess(AS_public);
3122 D->completeDefinition();
3123 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3126 return ObjCFastEnumerationStateType;
3130 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3131 assert(!E->getType()->isPointerType() && "Strings are always arrays");
3133 // Don't emit it as the address of the string, emit the string data itself
3134 // as an inline array.
3135 if (E->getCharByteWidth() == 1) {
3136 SmallString<64> Str(E->getString());
3138 // Resize the string to the right size, which is indicated by its type.
3139 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3140 Str.resize(CAT->getSize().getZExtValue());
3141 return llvm::ConstantDataArray::getString(VMContext, Str, false);
3144 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3145 llvm::Type *ElemTy = AType->getElementType();
3146 unsigned NumElements = AType->getNumElements();
3148 // Wide strings have either 2-byte or 4-byte elements.
3149 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3150 SmallVector<uint16_t, 32> Elements;
3151 Elements.reserve(NumElements);
3153 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3154 Elements.push_back(E->getCodeUnit(i));
3155 Elements.resize(NumElements);
3156 return llvm::ConstantDataArray::get(VMContext, Elements);
3159 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3160 SmallVector<uint32_t, 32> Elements;
3161 Elements.reserve(NumElements);
3163 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3164 Elements.push_back(E->getCodeUnit(i));
3165 Elements.resize(NumElements);
3166 return llvm::ConstantDataArray::get(VMContext, Elements);
3169 static llvm::GlobalVariable *
3170 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3171 CodeGenModule &CGM, StringRef GlobalName,
3172 CharUnits Alignment) {
3173 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3174 unsigned AddrSpace = 0;
3175 if (CGM.getLangOpts().OpenCL)
3176 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3178 llvm::Module &M = CGM.getModule();
3179 // Create a global variable for this string
3180 auto *GV = new llvm::GlobalVariable(
3181 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3182 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3183 GV->setAlignment(Alignment.getQuantity());
3184 GV->setUnnamedAddr(true);
3185 if (GV->isWeakForLinker()) {
3186 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3187 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3193 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3194 /// constant array for the given string literal.
3196 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3198 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3200 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3201 llvm::GlobalVariable **Entry = nullptr;
3202 if (!LangOpts.WritableStrings) {
3203 Entry = &ConstantStringMap[C];
3204 if (auto GV = *Entry) {
3205 if (Alignment.getQuantity() > GV->getAlignment())
3206 GV->setAlignment(Alignment.getQuantity());
3207 return ConstantAddress(GV, Alignment);
3211 SmallString<256> MangledNameBuffer;
3212 StringRef GlobalVariableName;
3213 llvm::GlobalValue::LinkageTypes LT;
3215 // Mangle the string literal if the ABI allows for it. However, we cannot
3216 // do this if we are compiling with ASan or -fwritable-strings because they
3217 // rely on strings having normal linkage.
3218 if (!LangOpts.WritableStrings &&
3219 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3220 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3221 llvm::raw_svector_ostream Out(MangledNameBuffer);
3222 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3224 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3225 GlobalVariableName = MangledNameBuffer;
3227 LT = llvm::GlobalValue::PrivateLinkage;
3228 GlobalVariableName = Name;
3231 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3235 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3237 return ConstantAddress(GV, Alignment);
3240 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3241 /// array for the given ObjCEncodeExpr node.
3243 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3245 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3247 return GetAddrOfConstantCString(Str);
3250 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3251 /// the literal and a terminating '\0' character.
3252 /// The result has pointer to array type.
3253 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3254 const std::string &Str, const char *GlobalName) {
3255 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3256 CharUnits Alignment =
3257 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3260 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3262 // Don't share any string literals if strings aren't constant.
3263 llvm::GlobalVariable **Entry = nullptr;
3264 if (!LangOpts.WritableStrings) {
3265 Entry = &ConstantStringMap[C];
3266 if (auto GV = *Entry) {
3267 if (Alignment.getQuantity() > GV->getAlignment())
3268 GV->setAlignment(Alignment.getQuantity());
3269 return ConstantAddress(GV, Alignment);
3273 // Get the default prefix if a name wasn't specified.
3275 GlobalName = ".str";
3276 // Create a global variable for this.
3277 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3278 GlobalName, Alignment);
3281 return ConstantAddress(GV, Alignment);
3284 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3285 const MaterializeTemporaryExpr *E, const Expr *Init) {
3286 assert((E->getStorageDuration() == SD_Static ||
3287 E->getStorageDuration() == SD_Thread) && "not a global temporary");
3288 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3290 // If we're not materializing a subobject of the temporary, keep the
3291 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3292 QualType MaterializedType = Init->getType();
3293 if (Init == E->GetTemporaryExpr())
3294 MaterializedType = E->getType();
3296 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3298 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3299 return ConstantAddress(Slot, Align);
3301 // FIXME: If an externally-visible declaration extends multiple temporaries,
3302 // we need to give each temporary the same name in every translation unit (and
3303 // we also need to make the temporaries externally-visible).
3304 SmallString<256> Name;
3305 llvm::raw_svector_ostream Out(Name);
3306 getCXXABI().getMangleContext().mangleReferenceTemporary(
3307 VD, E->getManglingNumber(), Out);
3309 APValue *Value = nullptr;
3310 if (E->getStorageDuration() == SD_Static) {
3311 // We might have a cached constant initializer for this temporary. Note
3312 // that this might have a different value from the value computed by
3313 // evaluating the initializer if the surrounding constant expression
3314 // modifies the temporary.
3315 Value = getContext().getMaterializedTemporaryValue(E, false);
3316 if (Value && Value->isUninit())
3320 // Try evaluating it now, it might have a constant initializer.
3321 Expr::EvalResult EvalResult;
3322 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3323 !EvalResult.hasSideEffects())
3324 Value = &EvalResult.Val;
3326 llvm::Constant *InitialValue = nullptr;
3327 bool Constant = false;
3330 // The temporary has a constant initializer, use it.
3331 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3332 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3333 Type = InitialValue->getType();
3335 // No initializer, the initialization will be provided when we
3336 // initialize the declaration which performed lifetime extension.
3337 Type = getTypes().ConvertTypeForMem(MaterializedType);
3340 // Create a global variable for this lifetime-extended temporary.
3341 llvm::GlobalValue::LinkageTypes Linkage =
3342 getLLVMLinkageVarDefinition(VD, Constant);
3343 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3344 const VarDecl *InitVD;
3345 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3346 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3347 // Temporaries defined inside a class get linkonce_odr linkage because the
3348 // class can be defined in multipe translation units.
3349 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3351 // There is no need for this temporary to have external linkage if the
3352 // VarDecl has external linkage.
3353 Linkage = llvm::GlobalVariable::InternalLinkage;
3356 unsigned AddrSpace = GetGlobalVarAddressSpace(
3357 VD, getContext().getTargetAddressSpace(MaterializedType));
3358 auto *GV = new llvm::GlobalVariable(
3359 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3360 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3362 setGlobalVisibility(GV, VD);
3363 GV->setAlignment(Align.getQuantity());
3364 if (supportsCOMDAT() && GV->isWeakForLinker())
3365 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3366 if (VD->getTLSKind())
3367 setTLSMode(GV, *VD);
3368 MaterializedGlobalTemporaryMap[E] = GV;
3369 return ConstantAddress(GV, Align);
3372 /// EmitObjCPropertyImplementations - Emit information for synthesized
3373 /// properties for an implementation.
3374 void CodeGenModule::EmitObjCPropertyImplementations(const
3375 ObjCImplementationDecl *D) {
3376 for (const auto *PID : D->property_impls()) {
3377 // Dynamic is just for type-checking.
3378 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3379 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3381 // Determine which methods need to be implemented, some may have
3382 // been overridden. Note that ::isPropertyAccessor is not the method
3383 // we want, that just indicates if the decl came from a
3384 // property. What we want to know is if the method is defined in
3385 // this implementation.
3386 if (!D->getInstanceMethod(PD->getGetterName()))
3387 CodeGenFunction(*this).GenerateObjCGetter(
3388 const_cast<ObjCImplementationDecl *>(D), PID);
3389 if (!PD->isReadOnly() &&
3390 !D->getInstanceMethod(PD->getSetterName()))
3391 CodeGenFunction(*this).GenerateObjCSetter(
3392 const_cast<ObjCImplementationDecl *>(D), PID);
3397 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3398 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3399 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3400 ivar; ivar = ivar->getNextIvar())
3401 if (ivar->getType().isDestructedType())
3407 static bool AllTrivialInitializers(CodeGenModule &CGM,
3408 ObjCImplementationDecl *D) {
3409 CodeGenFunction CGF(CGM);
3410 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3411 E = D->init_end(); B != E; ++B) {
3412 CXXCtorInitializer *CtorInitExp = *B;
3413 Expr *Init = CtorInitExp->getInit();
3414 if (!CGF.isTrivialInitializer(Init))
3420 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3421 /// for an implementation.
3422 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3423 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3424 if (needsDestructMethod(D)) {
3425 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3426 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3427 ObjCMethodDecl *DTORMethod =
3428 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3429 cxxSelector, getContext().VoidTy, nullptr, D,
3430 /*isInstance=*/true, /*isVariadic=*/false,
3431 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3432 /*isDefined=*/false, ObjCMethodDecl::Required);
3433 D->addInstanceMethod(DTORMethod);
3434 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3435 D->setHasDestructors(true);
3438 // If the implementation doesn't have any ivar initializers, we don't need
3439 // a .cxx_construct.
3440 if (D->getNumIvarInitializers() == 0 ||
3441 AllTrivialInitializers(*this, D))
3444 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3445 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3446 // The constructor returns 'self'.
3447 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3451 getContext().getObjCIdType(),
3452 nullptr, D, /*isInstance=*/true,
3453 /*isVariadic=*/false,
3454 /*isPropertyAccessor=*/true,
3455 /*isImplicitlyDeclared=*/true,
3456 /*isDefined=*/false,
3457 ObjCMethodDecl::Required);
3458 D->addInstanceMethod(CTORMethod);
3459 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3460 D->setHasNonZeroConstructors(true);
3463 /// EmitNamespace - Emit all declarations in a namespace.
3464 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
3465 for (auto *I : ND->decls()) {
3466 if (const auto *VD = dyn_cast<VarDecl>(I))
3467 if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3468 VD->getTemplateSpecializationKind() != TSK_Undeclared)
3470 EmitTopLevelDecl(I);
3474 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3475 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3476 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3477 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3478 ErrorUnsupported(LSD, "linkage spec");
3482 for (auto *I : LSD->decls()) {
3483 // Meta-data for ObjC class includes references to implemented methods.
3484 // Generate class's method definitions first.
3485 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3486 for (auto *M : OID->methods())
3487 EmitTopLevelDecl(M);
3489 EmitTopLevelDecl(I);
3493 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3494 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3495 // Ignore dependent declarations.
3496 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3499 switch (D->getKind()) {
3500 case Decl::CXXConversion:
3501 case Decl::CXXMethod:
3502 case Decl::Function:
3503 // Skip function templates
3504 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3505 cast<FunctionDecl>(D)->isLateTemplateParsed())
3508 EmitGlobal(cast<FunctionDecl>(D));
3509 // Always provide some coverage mapping
3510 // even for the functions that aren't emitted.
3511 AddDeferredUnusedCoverageMapping(D);
3515 // Skip variable templates
3516 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3518 case Decl::VarTemplateSpecialization:
3519 EmitGlobal(cast<VarDecl>(D));
3522 // Indirect fields from global anonymous structs and unions can be
3523 // ignored; only the actual variable requires IR gen support.
3524 case Decl::IndirectField:
3528 case Decl::Namespace:
3529 EmitNamespace(cast<NamespaceDecl>(D));
3531 // No code generation needed.
3532 case Decl::UsingShadow:
3533 case Decl::ClassTemplate:
3534 case Decl::VarTemplate:
3535 case Decl::VarTemplatePartialSpecialization:
3536 case Decl::FunctionTemplate:
3537 case Decl::TypeAliasTemplate:
3541 case Decl::Using: // using X; [C++]
3542 if (CGDebugInfo *DI = getModuleDebugInfo())
3543 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3545 case Decl::NamespaceAlias:
3546 if (CGDebugInfo *DI = getModuleDebugInfo())
3547 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3549 case Decl::UsingDirective: // using namespace X; [C++]
3550 if (CGDebugInfo *DI = getModuleDebugInfo())
3551 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3553 case Decl::CXXConstructor:
3554 // Skip function templates
3555 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3556 cast<FunctionDecl>(D)->isLateTemplateParsed())
3559 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3561 case Decl::CXXDestructor:
3562 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3564 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3567 case Decl::StaticAssert:
3571 // Objective-C Decls
3573 // Forward declarations, no (immediate) code generation.
3574 case Decl::ObjCInterface:
3575 case Decl::ObjCCategory:
3578 case Decl::ObjCProtocol: {
3579 auto *Proto = cast<ObjCProtocolDecl>(D);
3580 if (Proto->isThisDeclarationADefinition())
3581 ObjCRuntime->GenerateProtocol(Proto);
3585 case Decl::ObjCCategoryImpl:
3586 // Categories have properties but don't support synthesize so we
3587 // can ignore them here.
3588 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3591 case Decl::ObjCImplementation: {
3592 auto *OMD = cast<ObjCImplementationDecl>(D);
3593 EmitObjCPropertyImplementations(OMD);
3594 EmitObjCIvarInitializations(OMD);
3595 ObjCRuntime->GenerateClass(OMD);
3596 // Emit global variable debug information.
3597 if (CGDebugInfo *DI = getModuleDebugInfo())
3598 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3599 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3600 OMD->getClassInterface()), OMD->getLocation());
3603 case Decl::ObjCMethod: {
3604 auto *OMD = cast<ObjCMethodDecl>(D);
3605 // If this is not a prototype, emit the body.
3607 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3610 case Decl::ObjCCompatibleAlias:
3611 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3614 case Decl::LinkageSpec:
3615 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3618 case Decl::FileScopeAsm: {
3619 // File-scope asm is ignored during device-side CUDA compilation.
3620 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3622 // File-scope asm is ignored during device-side OpenMP compilation.
3623 if (LangOpts.OpenMPIsDevice)
3625 auto *AD = cast<FileScopeAsmDecl>(D);
3626 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3630 case Decl::Import: {
3631 auto *Import = cast<ImportDecl>(D);
3633 // Ignore import declarations that come from imported modules.
3634 if (Import->getImportedOwningModule())
3636 if (CGDebugInfo *DI = getModuleDebugInfo())
3637 DI->EmitImportDecl(*Import);
3639 ImportedModules.insert(Import->getImportedModule());
3643 case Decl::OMPThreadPrivate:
3644 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3647 case Decl::ClassTemplateSpecialization: {
3648 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3650 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3651 Spec->hasDefinition())
3652 DebugInfo->completeTemplateDefinition(*Spec);
3657 // Make sure we handled everything we should, every other kind is a
3658 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3659 // function. Need to recode Decl::Kind to do that easily.
3660 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3665 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3666 // Do we need to generate coverage mapping?
3667 if (!CodeGenOpts.CoverageMapping)
3669 switch (D->getKind()) {
3670 case Decl::CXXConversion:
3671 case Decl::CXXMethod:
3672 case Decl::Function:
3673 case Decl::ObjCMethod:
3674 case Decl::CXXConstructor:
3675 case Decl::CXXDestructor: {
3676 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
3678 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3679 if (I == DeferredEmptyCoverageMappingDecls.end())
3680 DeferredEmptyCoverageMappingDecls[D] = true;
3688 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3689 // Do we need to generate coverage mapping?
3690 if (!CodeGenOpts.CoverageMapping)
3692 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3693 if (Fn->isTemplateInstantiation())
3694 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3696 auto I = DeferredEmptyCoverageMappingDecls.find(D);
3697 if (I == DeferredEmptyCoverageMappingDecls.end())
3698 DeferredEmptyCoverageMappingDecls[D] = false;
3703 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3704 std::vector<const Decl *> DeferredDecls;
3705 for (const auto &I : DeferredEmptyCoverageMappingDecls) {
3708 DeferredDecls.push_back(I.first);
3710 // Sort the declarations by their location to make sure that the tests get a
3711 // predictable order for the coverage mapping for the unused declarations.
3712 if (CodeGenOpts.DumpCoverageMapping)
3713 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3714 [] (const Decl *LHS, const Decl *RHS) {
3715 return LHS->getLocStart() < RHS->getLocStart();
3717 for (const auto *D : DeferredDecls) {
3718 switch (D->getKind()) {
3719 case Decl::CXXConversion:
3720 case Decl::CXXMethod:
3721 case Decl::Function:
3722 case Decl::ObjCMethod: {
3723 CodeGenPGO PGO(*this);
3724 GlobalDecl GD(cast<FunctionDecl>(D));
3725 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3726 getFunctionLinkage(GD));
3729 case Decl::CXXConstructor: {
3730 CodeGenPGO PGO(*this);
3731 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3732 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3733 getFunctionLinkage(GD));
3736 case Decl::CXXDestructor: {
3737 CodeGenPGO PGO(*this);
3738 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3739 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3740 getFunctionLinkage(GD));
3749 /// Turns the given pointer into a constant.
3750 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3752 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3753 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3754 return llvm::ConstantInt::get(i64, PtrInt);
3757 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3758 llvm::NamedMDNode *&GlobalMetadata,
3760 llvm::GlobalValue *Addr) {
3761 if (!GlobalMetadata)
3763 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3765 // TODO: should we report variant information for ctors/dtors?
3766 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3767 llvm::ConstantAsMetadata::get(GetPointerConstant(
3768 CGM.getLLVMContext(), D.getDecl()))};
3769 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3772 /// For each function which is declared within an extern "C" region and marked
3773 /// as 'used', but has internal linkage, create an alias from the unmangled
3774 /// name to the mangled name if possible. People expect to be able to refer
3775 /// to such functions with an unmangled name from inline assembly within the
3776 /// same translation unit.
3777 void CodeGenModule::EmitStaticExternCAliases() {
3778 for (auto &I : StaticExternCValues) {
3779 IdentifierInfo *Name = I.first;
3780 llvm::GlobalValue *Val = I.second;
3781 if (Val && !getModule().getNamedValue(Name->getName()))
3782 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
3786 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3787 GlobalDecl &Result) const {
3788 auto Res = Manglings.find(MangledName);
3789 if (Res == Manglings.end())
3791 Result = Res->getValue();
3795 /// Emits metadata nodes associating all the global values in the
3796 /// current module with the Decls they came from. This is useful for
3797 /// projects using IR gen as a subroutine.
3799 /// Since there's currently no way to associate an MDNode directly
3800 /// with an llvm::GlobalValue, we create a global named metadata
3801 /// with the name 'clang.global.decl.ptrs'.
3802 void CodeGenModule::EmitDeclMetadata() {
3803 llvm::NamedMDNode *GlobalMetadata = nullptr;
3805 for (auto &I : MangledDeclNames) {
3806 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3807 // Some mangled names don't necessarily have an associated GlobalValue
3808 // in this module, e.g. if we mangled it for DebugInfo.
3810 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
3814 /// Emits metadata nodes for all the local variables in the current
3816 void CodeGenFunction::EmitDeclMetadata() {
3817 if (LocalDeclMap.empty()) return;
3819 llvm::LLVMContext &Context = getLLVMContext();
3821 // Find the unique metadata ID for this name.
3822 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3824 llvm::NamedMDNode *GlobalMetadata = nullptr;
3826 for (auto &I : LocalDeclMap) {
3827 const Decl *D = I.first;
3828 llvm::Value *Addr = I.second.getPointer();
3829 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3830 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3831 Alloca->setMetadata(
3832 DeclPtrKind, llvm::MDNode::get(
3833 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
3834 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3835 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3836 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3841 void CodeGenModule::EmitVersionIdentMetadata() {
3842 llvm::NamedMDNode *IdentMetadata =
3843 TheModule.getOrInsertNamedMetadata("llvm.ident");
3844 std::string Version = getClangFullVersion();
3845 llvm::LLVMContext &Ctx = TheModule.getContext();
3847 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
3848 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3851 void CodeGenModule::EmitTargetMetadata() {
3852 // Warning, new MangledDeclNames may be appended within this loop.
3853 // We rely on MapVector insertions adding new elements to the end
3854 // of the container.
3855 // FIXME: Move this loop into the one target that needs it, and only
3856 // loop over those declarations for which we couldn't emit the target
3857 // metadata when we emitted the declaration.
3858 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
3859 auto Val = *(MangledDeclNames.begin() + I);
3860 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3861 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
3862 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3866 void CodeGenModule::EmitCoverageFile() {
3867 if (!getCodeGenOpts().CoverageFile.empty()) {
3868 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3869 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3870 llvm::LLVMContext &Ctx = TheModule.getContext();
3871 llvm::MDString *CoverageFile =
3872 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3873 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3874 llvm::MDNode *CU = CUNode->getOperand(i);
3875 llvm::Metadata *Elts[] = {CoverageFile, CU};
3876 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
3882 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
3883 // Sema has checked that all uuid strings are of the form
3884 // "12345678-1234-1234-1234-1234567890ab".
3885 assert(Uuid.size() == 36);
3886 for (unsigned i = 0; i < 36; ++i) {
3887 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3888 else assert(isHexDigit(Uuid[i]));
3891 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
3892 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3894 llvm::Constant *Field3[8];
3895 for (unsigned Idx = 0; Idx < 8; ++Idx)
3896 Field3[Idx] = llvm::ConstantInt::get(
3897 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3899 llvm::Constant *Fields[4] = {
3900 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
3901 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
3902 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3903 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3906 return llvm::ConstantStruct::getAnon(Fields);
3909 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
3911 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
3912 // FIXME: should we even be calling this method if RTTI is disabled
3913 // and it's not for EH?
3914 if (!ForEH && !getLangOpts().RTTI)
3915 return llvm::Constant::getNullValue(Int8PtrTy);
3917 if (ForEH && Ty->isObjCObjectPointerType() &&
3918 LangOpts.ObjCRuntime.isGNUFamily())
3919 return ObjCRuntime->GetEHType(Ty);
3921 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
3924 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
3925 for (auto RefExpr : D->varlists()) {
3926 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
3928 VD->getAnyInitializer() &&
3929 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
3932 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
3933 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
3934 VD, Addr, RefExpr->getLocStart(), PerformInit))
3935 CXXGlobalInits.push_back(InitFunction);
3939 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
3940 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
3944 if (isExternallyVisible(T->getLinkage())) {
3945 std::string OutName;
3946 llvm::raw_string_ostream Out(OutName);
3947 getCXXABI().getMangleContext().mangleTypeName(T, Out);
3949 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
3951 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
3952 llvm::ArrayRef<llvm::Metadata *>());
3958 void CodeGenModule::CreateVTableBitSetEntry(llvm::NamedMDNode *BitsetsMD,
3959 llvm::GlobalVariable *VTable,
3961 const CXXRecordDecl *RD) {
3962 llvm::Metadata *MD =
3963 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
3964 llvm::Metadata *BitsetOps[] = {
3965 MD, llvm::ConstantAsMetadata::get(VTable),
3966 llvm::ConstantAsMetadata::get(
3967 llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
3968 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps));
3970 if (CodeGenOpts.SanitizeCfiCrossDso) {
3971 if (auto TypeId = CreateCfiIdForTypeMetadata(MD)) {
3972 llvm::Metadata *BitsetOps2[] = {
3973 llvm::ConstantAsMetadata::get(TypeId),
3974 llvm::ConstantAsMetadata::get(VTable),
3975 llvm::ConstantAsMetadata::get(
3976 llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
3977 BitsetsMD->addOperand(llvm::MDTuple::get(getLLVMContext(), BitsetOps2));
3982 // Fills in the supplied string map with the set of target features for the
3983 // passed in function.
3984 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
3985 const FunctionDecl *FD) {
3986 StringRef TargetCPU = Target.getTargetOpts().CPU;
3987 if (const auto *TD = FD->getAttr<TargetAttr>()) {
3988 // If we have a TargetAttr build up the feature map based on that.
3989 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
3991 // Make a copy of the features as passed on the command line into the
3992 // beginning of the additional features from the function to override.
3993 ParsedAttr.first.insert(ParsedAttr.first.begin(),
3994 Target.getTargetOpts().FeaturesAsWritten.begin(),
3995 Target.getTargetOpts().FeaturesAsWritten.end());
3997 if (ParsedAttr.second != "")
3998 TargetCPU = ParsedAttr.second;
4000 // Now populate the feature map, first with the TargetCPU which is either
4001 // the default or a new one from the target attribute string. Then we'll use
4002 // the passed in features (FeaturesAsWritten) along with the new ones from
4004 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4006 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4007 Target.getTargetOpts().Features);