1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the per-module state used while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenModule.h"
16 #include "CGCUDARuntime.h"
19 #include "CGDebugInfo.h"
20 #include "CGObjCRuntime.h"
21 #include "CGOpenCLRuntime.h"
22 #include "CGOpenMPRuntime.h"
23 #include "CGOpenMPRuntimeNVPTX.h"
24 #include "CodeGenFunction.h"
25 #include "CodeGenPGO.h"
26 #include "CodeGenTBAA.h"
27 #include "ConstantBuilder.h"
28 #include "CoverageMappingGen.h"
29 #include "TargetInfo.h"
30 #include "clang/AST/ASTContext.h"
31 #include "clang/AST/CharUnits.h"
32 #include "clang/AST/DeclCXX.h"
33 #include "clang/AST/DeclObjC.h"
34 #include "clang/AST/DeclTemplate.h"
35 #include "clang/AST/Mangle.h"
36 #include "clang/AST/RecordLayout.h"
37 #include "clang/AST/RecursiveASTVisitor.h"
38 #include "clang/Basic/Builtins.h"
39 #include "clang/Basic/CharInfo.h"
40 #include "clang/Basic/Diagnostic.h"
41 #include "clang/Basic/Module.h"
42 #include "clang/Basic/SourceManager.h"
43 #include "clang/Basic/TargetInfo.h"
44 #include "clang/Basic/Version.h"
45 #include "clang/Frontend/CodeGenOptions.h"
46 #include "clang/Sema/SemaDiagnostic.h"
47 #include "llvm/ADT/Triple.h"
48 #include "llvm/IR/CallSite.h"
49 #include "llvm/IR/CallingConv.h"
50 #include "llvm/IR/DataLayout.h"
51 #include "llvm/IR/Intrinsics.h"
52 #include "llvm/IR/LLVMContext.h"
53 #include "llvm/IR/Module.h"
54 #include "llvm/ProfileData/InstrProfReader.h"
55 #include "llvm/Support/ConvertUTF.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/MD5.h"
59 using namespace clang;
60 using namespace CodeGen;
62 static const char AnnotationSection[] = "llvm.metadata";
64 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
65 switch (CGM.getTarget().getCXXABI().getKind()) {
66 case TargetCXXABI::GenericAArch64:
67 case TargetCXXABI::GenericARM:
68 case TargetCXXABI::iOS:
69 case TargetCXXABI::iOS64:
70 case TargetCXXABI::WatchOS:
71 case TargetCXXABI::GenericMIPS:
72 case TargetCXXABI::GenericItanium:
73 case TargetCXXABI::WebAssembly:
74 return CreateItaniumCXXABI(CGM);
75 case TargetCXXABI::Microsoft:
76 return CreateMicrosoftCXXABI(CGM);
79 llvm_unreachable("invalid C++ ABI kind");
82 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
83 const PreprocessorOptions &PPO,
84 const CodeGenOptions &CGO, llvm::Module &M,
85 DiagnosticsEngine &diags,
86 CoverageSourceInfo *CoverageInfo)
87 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
88 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
89 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
90 VMContext(M.getContext()), Types(*this), VTables(*this),
91 SanitizerMD(new SanitizerMetadata(*this)) {
93 // Initialize the type cache.
94 llvm::LLVMContext &LLVMContext = M.getContext();
95 VoidTy = llvm::Type::getVoidTy(LLVMContext);
96 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
98 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
99 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
100 FloatTy = llvm::Type::getFloatTy(LLVMContext);
101 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
102 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
103 PointerAlignInBytes =
104 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
106 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
108 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
109 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
110 IntPtrTy = llvm::IntegerType::get(LLVMContext,
111 C.getTargetInfo().getMaxPointerWidth());
112 Int8PtrTy = Int8Ty->getPointerTo(0);
113 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
115 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
116 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
121 createOpenCLRuntime();
123 createOpenMPRuntime();
127 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
128 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
129 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
130 TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
131 getCXXABI().getMangleContext()));
133 // If debug info or coverage generation is enabled, create the CGDebugInfo
135 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
136 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
137 DebugInfo.reset(new CGDebugInfo(*this));
139 Block.GlobalUniqueCount = 0;
141 if (C.getLangOpts().ObjC1)
142 ObjCData.reset(new ObjCEntrypoints());
144 if (CodeGenOpts.hasProfileClangUse()) {
145 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
146 CodeGenOpts.ProfileInstrumentUsePath);
147 if (auto E = ReaderOrErr.takeError()) {
148 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
149 "Could not read profile %0: %1");
150 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
151 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
155 PGOReader = std::move(ReaderOrErr.get());
158 // If coverage mapping generation is enabled, create the
159 // CoverageMappingModuleGen object.
160 if (CodeGenOpts.CoverageMapping)
161 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
164 CodeGenModule::~CodeGenModule() {}
166 void CodeGenModule::createObjCRuntime() {
167 // This is just isGNUFamily(), but we want to force implementors of
168 // new ABIs to decide how best to do this.
169 switch (LangOpts.ObjCRuntime.getKind()) {
170 case ObjCRuntime::GNUstep:
171 case ObjCRuntime::GCC:
172 case ObjCRuntime::ObjFW:
173 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
176 case ObjCRuntime::FragileMacOSX:
177 case ObjCRuntime::MacOSX:
178 case ObjCRuntime::iOS:
179 case ObjCRuntime::WatchOS:
180 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
183 llvm_unreachable("bad runtime kind");
186 void CodeGenModule::createOpenCLRuntime() {
187 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
190 void CodeGenModule::createOpenMPRuntime() {
191 // Select a specialized code generation class based on the target, if any.
192 // If it does not exist use the default implementation.
193 switch (getTriple().getArch()) {
194 case llvm::Triple::nvptx:
195 case llvm::Triple::nvptx64:
196 assert(getLangOpts().OpenMPIsDevice &&
197 "OpenMP NVPTX is only prepared to deal with device code.");
198 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
201 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
206 void CodeGenModule::createCUDARuntime() {
207 CUDARuntime.reset(CreateNVCUDARuntime(*this));
210 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
211 Replacements[Name] = C;
214 void CodeGenModule::applyReplacements() {
215 for (auto &I : Replacements) {
216 StringRef MangledName = I.first();
217 llvm::Constant *Replacement = I.second;
218 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
221 auto *OldF = cast<llvm::Function>(Entry);
222 auto *NewF = dyn_cast<llvm::Function>(Replacement);
224 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
225 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
227 auto *CE = cast<llvm::ConstantExpr>(Replacement);
228 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
229 CE->getOpcode() == llvm::Instruction::GetElementPtr);
230 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
234 // Replace old with new, but keep the old order.
235 OldF->replaceAllUsesWith(Replacement);
237 NewF->removeFromParent();
238 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
241 OldF->eraseFromParent();
245 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
246 GlobalValReplacements.push_back(std::make_pair(GV, C));
249 void CodeGenModule::applyGlobalValReplacements() {
250 for (auto &I : GlobalValReplacements) {
251 llvm::GlobalValue *GV = I.first;
252 llvm::Constant *C = I.second;
254 GV->replaceAllUsesWith(C);
255 GV->eraseFromParent();
259 // This is only used in aliases that we created and we know they have a
261 static const llvm::GlobalObject *getAliasedGlobal(
262 const llvm::GlobalIndirectSymbol &GIS) {
263 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
264 const llvm::Constant *C = &GIS;
266 C = C->stripPointerCasts();
267 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
269 // stripPointerCasts will not walk over weak aliases.
270 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
273 if (!Visited.insert(GIS2).second)
275 C = GIS2->getIndirectSymbol();
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 SourceLocation Location;
288 bool IsIFunc = D->hasAttr<IFuncAttr>();
289 if (const Attr *A = D->getDefiningAttr())
290 Location = A->getLocation();
292 llvm_unreachable("Not an alias or ifunc?");
293 StringRef MangledName = getMangledName(GD);
294 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
295 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
296 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
299 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
300 } else if (GV->isDeclaration()) {
302 Diags.Report(Location, diag::err_alias_to_undefined)
303 << IsIFunc << IsIFunc;
304 } else if (IsIFunc) {
305 // Check resolver function type.
306 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
307 GV->getType()->getPointerElementType());
309 if (!FTy->getReturnType()->isPointerTy())
310 Diags.Report(Location, diag::err_ifunc_resolver_return);
311 if (FTy->getNumParams())
312 Diags.Report(Location, diag::err_ifunc_resolver_params);
315 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
316 llvm::GlobalValue *AliaseeGV;
317 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
318 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
320 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
322 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
323 StringRef AliasSection = SA->getName();
324 if (AliasSection != AliaseeGV->getSection())
325 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
326 << AliasSection << IsIFunc << IsIFunc;
329 // We have to handle alias to weak aliases in here. LLVM itself disallows
330 // this since the object semantics would not match the IL one. For
331 // compatibility with gcc we implement it by just pointing the alias
332 // to its aliasee's aliasee. We also warn, since the user is probably
333 // expecting the link to be weak.
334 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
335 if (GA->isInterposable()) {
336 Diags.Report(Location, diag::warn_alias_to_weak_alias)
337 << GV->getName() << GA->getName() << IsIFunc;
338 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
339 GA->getIndirectSymbol(), Alias->getType());
340 Alias->setIndirectSymbol(Aliasee);
347 for (const GlobalDecl &GD : Aliases) {
348 StringRef MangledName = getMangledName(GD);
349 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
350 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
351 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
352 Alias->eraseFromParent();
356 void CodeGenModule::clear() {
357 DeferredDeclsToEmit.clear();
359 OpenMPRuntime->clear();
362 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
363 StringRef MainFile) {
364 if (!hasDiagnostics())
366 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
367 if (MainFile.empty())
368 MainFile = "<stdin>";
369 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
371 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
375 void CodeGenModule::Release() {
377 applyGlobalValReplacements();
380 EmitCXXGlobalInitFunc();
381 EmitCXXGlobalDtorFunc();
382 EmitCXXThreadLocalInitFunc();
384 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
385 AddGlobalCtor(ObjCInitFunction);
386 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
388 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
389 AddGlobalCtor(CudaCtorFunction);
390 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
391 AddGlobalDtor(CudaDtorFunction);
394 if (llvm::Function *OpenMPRegistrationFunction =
395 OpenMPRuntime->emitRegistrationFunction())
396 AddGlobalCtor(OpenMPRegistrationFunction, 0);
398 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
399 if (PGOStats.hasDiagnostics())
400 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
402 EmitCtorList(GlobalCtors, "llvm.global_ctors");
403 EmitCtorList(GlobalDtors, "llvm.global_dtors");
404 EmitGlobalAnnotations();
405 EmitStaticExternCAliases();
406 EmitDeferredUnusedCoverageMappings();
408 CoverageMapping->emit();
409 if (CodeGenOpts.SanitizeCfiCrossDso)
410 CodeGenFunction(*this).EmitCfiCheckFail();
415 if (CodeGenOpts.Autolink &&
416 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
417 EmitModuleLinkOptions();
419 if (CodeGenOpts.DwarfVersion) {
420 // We actually want the latest version when there are conflicts.
421 // We can change from Warning to Latest if such mode is supported.
422 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
423 CodeGenOpts.DwarfVersion);
425 if (CodeGenOpts.EmitCodeView) {
426 // Indicate that we want CodeView in the metadata.
427 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
429 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
430 // We don't support LTO with 2 with different StrictVTablePointers
431 // FIXME: we could support it by stripping all the information introduced
432 // by StrictVTablePointers.
434 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
436 llvm::Metadata *Ops[2] = {
437 llvm::MDString::get(VMContext, "StrictVTablePointers"),
438 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
439 llvm::Type::getInt32Ty(VMContext), 1))};
441 getModule().addModuleFlag(llvm::Module::Require,
442 "StrictVTablePointersRequirement",
443 llvm::MDNode::get(VMContext, Ops));
446 // We support a single version in the linked module. The LLVM
447 // parser will drop debug info with a different version number
448 // (and warn about it, too).
449 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
450 llvm::DEBUG_METADATA_VERSION);
452 // We need to record the widths of enums and wchar_t, so that we can generate
453 // the correct build attributes in the ARM backend.
454 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
455 if ( Arch == llvm::Triple::arm
456 || Arch == llvm::Triple::armeb
457 || Arch == llvm::Triple::thumb
458 || Arch == llvm::Triple::thumbeb) {
459 // Width of wchar_t in bytes
460 uint64_t WCharWidth =
461 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
462 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
464 // The minimum width of an enum in bytes
465 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
466 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
469 if (CodeGenOpts.SanitizeCfiCrossDso) {
470 // Indicate that we want cross-DSO control flow integrity checks.
471 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
474 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
475 // Indicate whether __nvvm_reflect should be configured to flush denormal
476 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
478 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
479 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
482 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
483 assert(PLevel < 3 && "Invalid PIC Level");
484 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
485 if (Context.getLangOpts().PIE)
486 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
489 SimplifyPersonality();
491 if (getCodeGenOpts().EmitDeclMetadata)
494 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
498 DebugInfo->finalize();
500 EmitVersionIdentMetadata();
502 EmitTargetMetadata();
505 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
506 // Make sure that this type is translated.
507 Types.UpdateCompletedType(TD);
510 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
511 // Make sure that this type is translated.
512 Types.RefreshTypeCacheForClass(RD);
515 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
518 return TBAA->getTBAAInfo(QTy);
521 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
524 return TBAA->getTBAAInfoForVTablePtr();
527 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
530 return TBAA->getTBAAStructInfo(QTy);
533 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
534 llvm::MDNode *AccessN,
538 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
541 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
542 /// and struct-path aware TBAA, the tag has the same format:
543 /// base type, access type and offset.
544 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
545 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
546 llvm::MDNode *TBAAInfo,
547 bool ConvertTypeToTag) {
548 if (ConvertTypeToTag && TBAA)
549 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
550 TBAA->getTBAAScalarTagInfo(TBAAInfo));
552 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
555 void CodeGenModule::DecorateInstructionWithInvariantGroup(
556 llvm::Instruction *I, const CXXRecordDecl *RD) {
557 llvm::Metadata *MD = CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
558 auto *MetaDataNode = dyn_cast<llvm::MDNode>(MD);
559 // Check if we have to wrap MDString in MDNode.
561 MetaDataNode = llvm::MDNode::get(getLLVMContext(), MD);
562 I->setMetadata(llvm::LLVMContext::MD_invariant_group, MetaDataNode);
565 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
566 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
567 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
570 /// ErrorUnsupported - Print out an error that codegen doesn't support the
571 /// specified stmt yet.
572 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
573 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
574 "cannot compile this %0 yet");
575 std::string Msg = Type;
576 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
577 << Msg << S->getSourceRange();
580 /// ErrorUnsupported - Print out an error that codegen doesn't support the
581 /// specified decl yet.
582 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
583 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
584 "cannot compile this %0 yet");
585 std::string Msg = Type;
586 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
589 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
590 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
593 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
594 const NamedDecl *D) const {
595 // Internal definitions always have default visibility.
596 if (GV->hasLocalLinkage()) {
597 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
601 // Set visibility for definitions.
602 LinkageInfo LV = D->getLinkageAndVisibility();
603 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
604 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
607 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
608 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
609 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
610 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
611 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
612 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
615 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
616 CodeGenOptions::TLSModel M) {
618 case CodeGenOptions::GeneralDynamicTLSModel:
619 return llvm::GlobalVariable::GeneralDynamicTLSModel;
620 case CodeGenOptions::LocalDynamicTLSModel:
621 return llvm::GlobalVariable::LocalDynamicTLSModel;
622 case CodeGenOptions::InitialExecTLSModel:
623 return llvm::GlobalVariable::InitialExecTLSModel;
624 case CodeGenOptions::LocalExecTLSModel:
625 return llvm::GlobalVariable::LocalExecTLSModel;
627 llvm_unreachable("Invalid TLS model!");
630 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
631 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
633 llvm::GlobalValue::ThreadLocalMode TLM;
634 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
636 // Override the TLS model if it is explicitly specified.
637 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
638 TLM = GetLLVMTLSModel(Attr->getModel());
641 GV->setThreadLocalMode(TLM);
644 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
645 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
647 // Some ABIs don't have constructor variants. Make sure that base and
648 // complete constructors get mangled the same.
649 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
650 if (!getTarget().getCXXABI().hasConstructorVariants()) {
651 CXXCtorType OrigCtorType = GD.getCtorType();
652 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
653 if (OrigCtorType == Ctor_Base)
654 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
658 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
659 if (!FoundStr.empty())
662 const auto *ND = cast<NamedDecl>(GD.getDecl());
663 SmallString<256> Buffer;
665 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
666 llvm::raw_svector_ostream Out(Buffer);
667 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
668 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
669 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
670 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
672 getCXXABI().getMangleContext().mangleName(ND, Out);
675 IdentifierInfo *II = ND->getIdentifier();
676 assert(II && "Attempt to mangle unnamed decl.");
677 const auto *FD = dyn_cast<FunctionDecl>(ND);
680 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
681 llvm::raw_svector_ostream Out(Buffer);
682 Out << "__regcall3__" << II->getName();
689 // Keep the first result in the case of a mangling collision.
690 auto Result = Manglings.insert(std::make_pair(Str, GD));
691 return FoundStr = Result.first->first();
694 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
695 const BlockDecl *BD) {
696 MangleContext &MangleCtx = getCXXABI().getMangleContext();
697 const Decl *D = GD.getDecl();
699 SmallString<256> Buffer;
700 llvm::raw_svector_ostream Out(Buffer);
702 MangleCtx.mangleGlobalBlock(BD,
703 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
704 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
705 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
706 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
707 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
709 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
711 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
712 return Result.first->first();
715 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
716 return getModule().getNamedValue(Name);
719 /// AddGlobalCtor - Add a function to the list that will be called before
721 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
722 llvm::Constant *AssociatedData) {
723 // FIXME: Type coercion of void()* types.
724 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
727 /// AddGlobalDtor - Add a function to the list that will be called
728 /// when the module is unloaded.
729 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
730 // FIXME: Type coercion of void()* types.
731 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
734 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
735 if (Fns.empty()) return;
737 // Ctor function type is void()*.
738 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
739 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
741 // Get the type of a ctor entry, { i32, void ()*, i8* }.
742 llvm::StructType *CtorStructTy = llvm::StructType::get(
743 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
745 // Construct the constructor and destructor arrays.
746 ConstantInitBuilder builder(*this);
747 auto ctors = builder.beginArray(CtorStructTy);
748 for (const auto &I : Fns) {
749 auto ctor = ctors.beginStruct(CtorStructTy);
750 ctor.addInt(Int32Ty, I.Priority);
751 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
752 if (I.AssociatedData)
753 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
755 ctor.addNullPointer(VoidPtrTy);
756 ctor.finishAndAddTo(ctors);
760 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
762 llvm::GlobalValue::AppendingLinkage);
764 // The LTO linker doesn't seem to like it when we set an alignment
765 // on appending variables. Take it off as a workaround.
766 list->setAlignment(0);
771 llvm::GlobalValue::LinkageTypes
772 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
773 const auto *D = cast<FunctionDecl>(GD.getDecl());
775 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
777 if (isa<CXXDestructorDecl>(D) &&
778 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
780 // Destructor variants in the Microsoft C++ ABI are always internal or
781 // linkonce_odr thunks emitted on an as-needed basis.
782 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
783 : llvm::GlobalValue::LinkOnceODRLinkage;
786 if (isa<CXXConstructorDecl>(D) &&
787 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
788 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
789 // Our approach to inheriting constructors is fundamentally different from
790 // that used by the MS ABI, so keep our inheriting constructor thunks
791 // internal rather than trying to pick an unambiguous mangling for them.
792 return llvm::GlobalValue::InternalLinkage;
795 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
798 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
799 const auto *FD = cast<FunctionDecl>(GD.getDecl());
801 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
802 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
803 // Don't dllexport/import destructor thunks.
804 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
809 if (FD->hasAttr<DLLImportAttr>())
810 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
811 else if (FD->hasAttr<DLLExportAttr>())
812 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
814 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
817 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
818 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
819 if (!MDS) return nullptr;
821 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
824 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
826 setNonAliasAttributes(D, F);
829 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
830 const CGFunctionInfo &Info,
832 unsigned CallingConv;
833 AttributeListType AttributeList;
834 ConstructAttributeList(F->getName(), Info, D, AttributeList, CallingConv,
836 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
837 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
840 /// Determines whether the language options require us to model
841 /// unwind exceptions. We treat -fexceptions as mandating this
842 /// except under the fragile ObjC ABI with only ObjC exceptions
843 /// enabled. This means, for example, that C with -fexceptions
845 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
846 // If exceptions are completely disabled, obviously this is false.
847 if (!LangOpts.Exceptions) return false;
849 // If C++ exceptions are enabled, this is true.
850 if (LangOpts.CXXExceptions) return true;
852 // If ObjC exceptions are enabled, this depends on the ABI.
853 if (LangOpts.ObjCExceptions) {
854 return LangOpts.ObjCRuntime.hasUnwindExceptions();
860 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
864 if (CodeGenOpts.UnwindTables)
865 B.addAttribute(llvm::Attribute::UWTable);
867 if (!hasUnwindExceptions(LangOpts))
868 B.addAttribute(llvm::Attribute::NoUnwind);
870 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
871 B.addAttribute(llvm::Attribute::StackProtect);
872 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
873 B.addAttribute(llvm::Attribute::StackProtectStrong);
874 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
875 B.addAttribute(llvm::Attribute::StackProtectReq);
878 // If we don't have a declaration to control inlining, the function isn't
879 // explicitly marked as alwaysinline for semantic reasons, and inlining is
880 // disabled, mark the function as noinline.
881 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
882 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
883 B.addAttribute(llvm::Attribute::NoInline);
885 F->addAttributes(llvm::AttributeSet::FunctionIndex,
886 llvm::AttributeSet::get(
888 llvm::AttributeSet::FunctionIndex, B));
892 if (D->hasAttr<OptimizeNoneAttr>()) {
893 B.addAttribute(llvm::Attribute::OptimizeNone);
895 // OptimizeNone implies noinline; we should not be inlining such functions.
896 B.addAttribute(llvm::Attribute::NoInline);
897 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
898 "OptimizeNone and AlwaysInline on same function!");
900 // We still need to handle naked functions even though optnone subsumes
901 // much of their semantics.
902 if (D->hasAttr<NakedAttr>())
903 B.addAttribute(llvm::Attribute::Naked);
905 // OptimizeNone wins over OptimizeForSize and MinSize.
906 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
907 F->removeFnAttr(llvm::Attribute::MinSize);
908 } else if (D->hasAttr<NakedAttr>()) {
909 // Naked implies noinline: we should not be inlining such functions.
910 B.addAttribute(llvm::Attribute::Naked);
911 B.addAttribute(llvm::Attribute::NoInline);
912 } else if (D->hasAttr<NoDuplicateAttr>()) {
913 B.addAttribute(llvm::Attribute::NoDuplicate);
914 } else if (D->hasAttr<NoInlineAttr>()) {
915 B.addAttribute(llvm::Attribute::NoInline);
916 } else if (D->hasAttr<AlwaysInlineAttr>() &&
917 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
918 // (noinline wins over always_inline, and we can't specify both in IR)
919 B.addAttribute(llvm::Attribute::AlwaysInline);
920 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
921 // If we're not inlining, then force everything that isn't always_inline to
922 // carry an explicit noinline attribute.
923 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
924 B.addAttribute(llvm::Attribute::NoInline);
926 // Otherwise, propagate the inline hint attribute and potentially use its
927 // absence to mark things as noinline.
928 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
929 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
930 return Redecl->isInlineSpecified();
932 B.addAttribute(llvm::Attribute::InlineHint);
933 } else if (CodeGenOpts.getInlining() ==
934 CodeGenOptions::OnlyHintInlining &&
936 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
937 B.addAttribute(llvm::Attribute::NoInline);
942 // Add other optimization related attributes if we are optimizing this
944 if (!D->hasAttr<OptimizeNoneAttr>()) {
945 if (D->hasAttr<ColdAttr>()) {
946 B.addAttribute(llvm::Attribute::OptimizeForSize);
947 B.addAttribute(llvm::Attribute::Cold);
950 if (D->hasAttr<MinSizeAttr>())
951 B.addAttribute(llvm::Attribute::MinSize);
954 F->addAttributes(llvm::AttributeSet::FunctionIndex,
955 llvm::AttributeSet::get(
956 F->getContext(), llvm::AttributeSet::FunctionIndex, B));
958 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
960 F->setAlignment(alignment);
962 // Some C++ ABIs require 2-byte alignment for member functions, in order to
963 // reserve a bit for differentiating between virtual and non-virtual member
964 // functions. If the current target's C++ ABI requires this and this is a
965 // member function, set its alignment accordingly.
966 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
967 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
971 // In the cross-dso CFI mode, we want !type attributes on definitions only.
972 if (CodeGenOpts.SanitizeCfiCrossDso)
973 if (auto *FD = dyn_cast<FunctionDecl>(D))
974 CreateFunctionTypeMetadata(FD, F);
977 void CodeGenModule::SetCommonAttributes(const Decl *D,
978 llvm::GlobalValue *GV) {
979 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
980 setGlobalVisibility(GV, ND);
982 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
984 if (D && D->hasAttr<UsedAttr>())
988 void CodeGenModule::setAliasAttributes(const Decl *D,
989 llvm::GlobalValue *GV) {
990 SetCommonAttributes(D, GV);
992 // Process the dllexport attribute based on whether the original definition
993 // (not necessarily the aliasee) was exported.
994 if (D->hasAttr<DLLExportAttr>())
995 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
998 void CodeGenModule::setNonAliasAttributes(const Decl *D,
999 llvm::GlobalObject *GO) {
1000 SetCommonAttributes(D, GO);
1003 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1004 GO->setSection(SA->getName());
1006 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1009 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1011 const CGFunctionInfo &FI) {
1012 SetLLVMFunctionAttributes(D, FI, F);
1013 SetLLVMFunctionAttributesForDefinition(D, F);
1015 F->setLinkage(llvm::Function::InternalLinkage);
1017 setNonAliasAttributes(D, F);
1020 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
1021 const NamedDecl *ND) {
1022 // Set linkage and visibility in case we never see a definition.
1023 LinkageInfo LV = ND->getLinkageAndVisibility();
1024 if (LV.getLinkage() != ExternalLinkage) {
1025 // Don't set internal linkage on declarations.
1027 if (ND->hasAttr<DLLImportAttr>()) {
1028 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1029 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1030 } else if (ND->hasAttr<DLLExportAttr>()) {
1031 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1032 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1033 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
1034 // "extern_weak" is overloaded in LLVM; we probably should have
1035 // separate linkage types for this.
1036 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1039 // Set visibility on a declaration only if it's explicit.
1040 if (LV.isVisibilityExplicit())
1041 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
1045 void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1046 llvm::Function *F) {
1047 // Only if we are checking indirect calls.
1048 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1051 // Non-static class methods are handled via vtable pointer checks elsewhere.
1052 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1055 // Additionally, if building with cross-DSO support...
1056 if (CodeGenOpts.SanitizeCfiCrossDso) {
1057 // Skip available_externally functions. They won't be codegen'ed in the
1058 // current module anyway.
1059 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1063 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1064 F->addTypeMetadata(0, MD);
1066 // Emit a hash-based bit set entry for cross-DSO calls.
1067 if (CodeGenOpts.SanitizeCfiCrossDso)
1068 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1069 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1072 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1073 bool IsIncompleteFunction,
1075 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1076 // If this is an intrinsic function, set the function's attributes
1077 // to the intrinsic's attributes.
1078 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1082 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1084 if (!IsIncompleteFunction)
1085 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1087 // Add the Returned attribute for "this", except for iOS 5 and earlier
1088 // where substantial code, including the libstdc++ dylib, was compiled with
1089 // GCC and does not actually return "this".
1090 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1091 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1092 assert(!F->arg_empty() &&
1093 F->arg_begin()->getType()
1094 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1095 "unexpected this return");
1096 F->addAttribute(1, llvm::Attribute::Returned);
1099 // Only a few attributes are set on declarations; these may later be
1100 // overridden by a definition.
1102 setLinkageAndVisibilityForGV(F, FD);
1104 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1105 F->setSection(SA->getName());
1107 if (FD->isReplaceableGlobalAllocationFunction()) {
1108 // A replaceable global allocation function does not act like a builtin by
1109 // default, only if it is invoked by a new-expression or delete-expression.
1110 F->addAttribute(llvm::AttributeSet::FunctionIndex,
1111 llvm::Attribute::NoBuiltin);
1113 // A sane operator new returns a non-aliasing pointer.
1114 // FIXME: Also add NonNull attribute to the return value
1115 // for the non-nothrow forms?
1116 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1117 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1118 (Kind == OO_New || Kind == OO_Array_New))
1119 F->addAttribute(llvm::AttributeSet::ReturnIndex,
1120 llvm::Attribute::NoAlias);
1123 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1124 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1125 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1126 if (MD->isVirtual())
1127 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1129 // Don't emit entries for function declarations in the cross-DSO mode. This
1130 // is handled with better precision by the receiving DSO.
1131 if (!CodeGenOpts.SanitizeCfiCrossDso)
1132 CreateFunctionTypeMetadata(FD, F);
1135 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1136 assert(!GV->isDeclaration() &&
1137 "Only globals with definition can force usage.");
1138 LLVMUsed.emplace_back(GV);
1141 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1142 assert(!GV->isDeclaration() &&
1143 "Only globals with definition can force usage.");
1144 LLVMCompilerUsed.emplace_back(GV);
1147 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1148 std::vector<llvm::WeakVH> &List) {
1149 // Don't create llvm.used if there is no need.
1153 // Convert List to what ConstantArray needs.
1154 SmallVector<llvm::Constant*, 8> UsedArray;
1155 UsedArray.resize(List.size());
1156 for (unsigned i = 0, e = List.size(); i != e; ++i) {
1158 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1159 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1162 if (UsedArray.empty())
1164 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1166 auto *GV = new llvm::GlobalVariable(
1167 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1168 llvm::ConstantArray::get(ATy, UsedArray), Name);
1170 GV->setSection("llvm.metadata");
1173 void CodeGenModule::emitLLVMUsed() {
1174 emitUsed(*this, "llvm.used", LLVMUsed);
1175 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1178 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1179 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1180 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1183 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1184 llvm::SmallString<32> Opt;
1185 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1186 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1187 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1190 void CodeGenModule::AddDependentLib(StringRef Lib) {
1191 llvm::SmallString<24> Opt;
1192 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1193 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1194 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1197 /// \brief Add link options implied by the given module, including modules
1198 /// it depends on, using a postorder walk.
1199 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1200 SmallVectorImpl<llvm::Metadata *> &Metadata,
1201 llvm::SmallPtrSet<Module *, 16> &Visited) {
1202 // Import this module's parent.
1203 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1204 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1207 // Import this module's dependencies.
1208 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1209 if (Visited.insert(Mod->Imports[I - 1]).second)
1210 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1213 // Add linker options to link against the libraries/frameworks
1214 // described by this module.
1215 llvm::LLVMContext &Context = CGM.getLLVMContext();
1216 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1217 // Link against a framework. Frameworks are currently Darwin only, so we
1218 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1219 if (Mod->LinkLibraries[I-1].IsFramework) {
1220 llvm::Metadata *Args[2] = {
1221 llvm::MDString::get(Context, "-framework"),
1222 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1224 Metadata.push_back(llvm::MDNode::get(Context, Args));
1228 // Link against a library.
1229 llvm::SmallString<24> Opt;
1230 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1231 Mod->LinkLibraries[I-1].Library, Opt);
1232 auto *OptString = llvm::MDString::get(Context, Opt);
1233 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1237 void CodeGenModule::EmitModuleLinkOptions() {
1238 // Collect the set of all of the modules we want to visit to emit link
1239 // options, which is essentially the imported modules and all of their
1240 // non-explicit child modules.
1241 llvm::SetVector<clang::Module *> LinkModules;
1242 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1243 SmallVector<clang::Module *, 16> Stack;
1245 // Seed the stack with imported modules.
1246 for (Module *M : ImportedModules)
1247 if (Visited.insert(M).second)
1250 // Find all of the modules to import, making a little effort to prune
1251 // non-leaf modules.
1252 while (!Stack.empty()) {
1253 clang::Module *Mod = Stack.pop_back_val();
1255 bool AnyChildren = false;
1257 // Visit the submodules of this module.
1258 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1259 SubEnd = Mod->submodule_end();
1260 Sub != SubEnd; ++Sub) {
1261 // Skip explicit children; they need to be explicitly imported to be
1263 if ((*Sub)->IsExplicit)
1266 if (Visited.insert(*Sub).second) {
1267 Stack.push_back(*Sub);
1272 // We didn't find any children, so add this module to the list of
1273 // modules to link against.
1275 LinkModules.insert(Mod);
1279 // Add link options for all of the imported modules in reverse topological
1280 // order. We don't do anything to try to order import link flags with respect
1281 // to linker options inserted by things like #pragma comment().
1282 SmallVector<llvm::Metadata *, 16> MetadataArgs;
1284 for (Module *M : LinkModules)
1285 if (Visited.insert(M).second)
1286 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1287 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1288 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1290 // Add the linker options metadata flag.
1291 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1292 llvm::MDNode::get(getLLVMContext(),
1293 LinkerOptionsMetadata));
1296 void CodeGenModule::EmitDeferred() {
1297 // Emit code for any potentially referenced deferred decls. Since a
1298 // previously unused static decl may become used during the generation of code
1299 // for a static function, iterate until no changes are made.
1301 if (!DeferredVTables.empty()) {
1302 EmitDeferredVTables();
1304 // Emitting a vtable doesn't directly cause more vtables to
1305 // become deferred, although it can cause functions to be
1306 // emitted that then need those vtables.
1307 assert(DeferredVTables.empty());
1310 // Stop if we're out of both deferred vtables and deferred declarations.
1311 if (DeferredDeclsToEmit.empty())
1314 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1315 // work, it will not interfere with this.
1316 std::vector<DeferredGlobal> CurDeclsToEmit;
1317 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1319 for (DeferredGlobal &G : CurDeclsToEmit) {
1320 GlobalDecl D = G.GD;
1323 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1324 // to get GlobalValue with exactly the type we need, not something that
1325 // might had been created for another decl with the same mangled name but
1327 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1328 GetAddrOfGlobal(D, ForDefinition));
1330 // In case of different address spaces, we may still get a cast, even with
1331 // IsForDefinition equal to true. Query mangled names table to get
1334 GV = GetGlobalValue(getMangledName(D));
1336 // Make sure GetGlobalValue returned non-null.
1339 // Check to see if we've already emitted this. This is necessary
1340 // for a couple of reasons: first, decls can end up in the
1341 // deferred-decls queue multiple times, and second, decls can end
1342 // up with definitions in unusual ways (e.g. by an extern inline
1343 // function acquiring a strong function redefinition). Just
1344 // ignore these cases.
1345 if (!GV->isDeclaration())
1348 // Otherwise, emit the definition and move on to the next one.
1349 EmitGlobalDefinition(D, GV);
1351 // If we found out that we need to emit more decls, do that recursively.
1352 // This has the advantage that the decls are emitted in a DFS and related
1353 // ones are close together, which is convenient for testing.
1354 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1356 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1361 void CodeGenModule::EmitGlobalAnnotations() {
1362 if (Annotations.empty())
1365 // Create a new global variable for the ConstantStruct in the Module.
1366 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1367 Annotations[0]->getType(), Annotations.size()), Annotations);
1368 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1369 llvm::GlobalValue::AppendingLinkage,
1370 Array, "llvm.global.annotations");
1371 gv->setSection(AnnotationSection);
1374 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1375 llvm::Constant *&AStr = AnnotationStrings[Str];
1379 // Not found yet, create a new global.
1380 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1382 new llvm::GlobalVariable(getModule(), s->getType(), true,
1383 llvm::GlobalValue::PrivateLinkage, s, ".str");
1384 gv->setSection(AnnotationSection);
1385 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1390 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1391 SourceManager &SM = getContext().getSourceManager();
1392 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1394 return EmitAnnotationString(PLoc.getFilename());
1395 return EmitAnnotationString(SM.getBufferName(Loc));
1398 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1399 SourceManager &SM = getContext().getSourceManager();
1400 PresumedLoc PLoc = SM.getPresumedLoc(L);
1401 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1402 SM.getExpansionLineNumber(L);
1403 return llvm::ConstantInt::get(Int32Ty, LineNo);
1406 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1407 const AnnotateAttr *AA,
1409 // Get the globals for file name, annotation, and the line number.
1410 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1411 *UnitGV = EmitAnnotationUnit(L),
1412 *LineNoCst = EmitAnnotationLineNo(L);
1414 // Create the ConstantStruct for the global annotation.
1415 llvm::Constant *Fields[4] = {
1416 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1417 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1418 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1421 return llvm::ConstantStruct::getAnon(Fields);
1424 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1425 llvm::GlobalValue *GV) {
1426 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1427 // Get the struct elements for these annotations.
1428 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1429 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1432 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1433 SourceLocation Loc) const {
1434 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1435 // Blacklist by function name.
1436 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1438 // Blacklist by location.
1440 return SanitizerBL.isBlacklistedLocation(Loc);
1441 // If location is unknown, this may be a compiler-generated function. Assume
1442 // it's located in the main file.
1443 auto &SM = Context.getSourceManager();
1444 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1445 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1450 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1451 SourceLocation Loc, QualType Ty,
1452 StringRef Category) const {
1453 // For now globals can be blacklisted only in ASan and KASan.
1454 if (!LangOpts.Sanitize.hasOneOf(
1455 SanitizerKind::Address | SanitizerKind::KernelAddress))
1457 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1458 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1460 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1462 // Check global type.
1464 // Drill down the array types: if global variable of a fixed type is
1465 // blacklisted, we also don't instrument arrays of them.
1466 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1467 Ty = AT->getElementType();
1468 Ty = Ty.getCanonicalType().getUnqualifiedType();
1469 // We allow to blacklist only record types (classes, structs etc.)
1470 if (Ty->isRecordType()) {
1471 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1472 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1479 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1480 // Never defer when EmitAllDecls is specified.
1481 if (LangOpts.EmitAllDecls)
1484 return getContext().DeclMustBeEmitted(Global);
1487 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1488 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1489 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1490 // Implicit template instantiations may change linkage if they are later
1491 // explicitly instantiated, so they should not be emitted eagerly.
1493 if (const auto *VD = dyn_cast<VarDecl>(Global))
1494 if (Context.getInlineVariableDefinitionKind(VD) ==
1495 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1496 // A definition of an inline constexpr static data member may change
1497 // linkage later if it's redeclared outside the class.
1499 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1500 // codegen for global variables, because they may be marked as threadprivate.
1501 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1502 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1508 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1509 const CXXUuidofExpr* E) {
1510 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1512 StringRef Uuid = E->getUuidStr();
1513 std::string Name = "_GUID_" + Uuid.lower();
1514 std::replace(Name.begin(), Name.end(), '-', '_');
1516 // The UUID descriptor should be pointer aligned.
1517 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
1519 // Look for an existing global.
1520 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1521 return ConstantAddress(GV, Alignment);
1523 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1524 assert(Init && "failed to initialize as constant");
1526 auto *GV = new llvm::GlobalVariable(
1527 getModule(), Init->getType(),
1528 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1529 if (supportsCOMDAT())
1530 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1531 return ConstantAddress(GV, Alignment);
1534 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1535 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1536 assert(AA && "No alias?");
1538 CharUnits Alignment = getContext().getDeclAlign(VD);
1539 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1541 // See if there is already something with the target's name in the module.
1542 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1544 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1545 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1546 return ConstantAddress(Ptr, Alignment);
1549 llvm::Constant *Aliasee;
1550 if (isa<llvm::FunctionType>(DeclTy))
1551 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1552 GlobalDecl(cast<FunctionDecl>(VD)),
1553 /*ForVTable=*/false);
1555 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1556 llvm::PointerType::getUnqual(DeclTy),
1559 auto *F = cast<llvm::GlobalValue>(Aliasee);
1560 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1561 WeakRefReferences.insert(F);
1563 return ConstantAddress(Aliasee, Alignment);
1566 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1567 const auto *Global = cast<ValueDecl>(GD.getDecl());
1569 // Weak references don't produce any output by themselves.
1570 if (Global->hasAttr<WeakRefAttr>())
1573 // If this is an alias definition (which otherwise looks like a declaration)
1575 if (Global->hasAttr<AliasAttr>())
1576 return EmitAliasDefinition(GD);
1578 // IFunc like an alias whose value is resolved at runtime by calling resolver.
1579 if (Global->hasAttr<IFuncAttr>())
1580 return emitIFuncDefinition(GD);
1582 // If this is CUDA, be selective about which declarations we emit.
1583 if (LangOpts.CUDA) {
1584 if (LangOpts.CUDAIsDevice) {
1585 if (!Global->hasAttr<CUDADeviceAttr>() &&
1586 !Global->hasAttr<CUDAGlobalAttr>() &&
1587 !Global->hasAttr<CUDAConstantAttr>() &&
1588 !Global->hasAttr<CUDASharedAttr>())
1591 // We need to emit host-side 'shadows' for all global
1592 // device-side variables because the CUDA runtime needs their
1593 // size and host-side address in order to provide access to
1594 // their device-side incarnations.
1596 // So device-only functions are the only things we skip.
1597 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1598 Global->hasAttr<CUDADeviceAttr>())
1601 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1602 "Expected Variable or Function");
1606 if (LangOpts.OpenMP) {
1607 // If this is OpenMP device, check if it is legal to emit this global
1609 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1611 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1612 if (MustBeEmitted(Global))
1613 EmitOMPDeclareReduction(DRD);
1618 // Ignore declarations, they will be emitted on their first use.
1619 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1620 // Forward declarations are emitted lazily on first use.
1621 if (!FD->doesThisDeclarationHaveABody()) {
1622 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1625 StringRef MangledName = getMangledName(GD);
1627 // Compute the function info and LLVM type.
1628 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1629 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1631 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1632 /*DontDefer=*/false);
1636 const auto *VD = cast<VarDecl>(Global);
1637 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1638 // We need to emit device-side global CUDA variables even if a
1639 // variable does not have a definition -- we still need to define
1640 // host-side shadow for it.
1641 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1642 !VD->hasDefinition() &&
1643 (VD->hasAttr<CUDAConstantAttr>() ||
1644 VD->hasAttr<CUDADeviceAttr>());
1645 if (!MustEmitForCuda &&
1646 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1647 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1648 // If this declaration may have caused an inline variable definition to
1649 // change linkage, make sure that it's emitted.
1650 if (Context.getInlineVariableDefinitionKind(VD) ==
1651 ASTContext::InlineVariableDefinitionKind::Strong)
1652 GetAddrOfGlobalVar(VD);
1657 // Defer code generation to first use when possible, e.g. if this is an inline
1658 // function. If the global must always be emitted, do it eagerly if possible
1659 // to benefit from cache locality.
1660 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1661 // Emit the definition if it can't be deferred.
1662 EmitGlobalDefinition(GD);
1666 // If we're deferring emission of a C++ variable with an
1667 // initializer, remember the order in which it appeared in the file.
1668 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1669 cast<VarDecl>(Global)->hasInit()) {
1670 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1671 CXXGlobalInits.push_back(nullptr);
1674 StringRef MangledName = getMangledName(GD);
1675 if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1676 // The value has already been used and should therefore be emitted.
1677 addDeferredDeclToEmit(GV, GD);
1678 } else if (MustBeEmitted(Global)) {
1679 // The value must be emitted, but cannot be emitted eagerly.
1680 assert(!MayBeEmittedEagerly(Global));
1681 addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1683 // Otherwise, remember that we saw a deferred decl with this name. The
1684 // first use of the mangled name will cause it to move into
1685 // DeferredDeclsToEmit.
1686 DeferredDecls[MangledName] = GD;
1691 struct FunctionIsDirectlyRecursive :
1692 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1693 const StringRef Name;
1694 const Builtin::Context &BI;
1696 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1697 Name(N), BI(C), Result(false) {
1699 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1701 bool TraverseCallExpr(CallExpr *E) {
1702 const FunctionDecl *FD = E->getDirectCallee();
1705 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1706 if (Attr && Name == Attr->getLabel()) {
1710 unsigned BuiltinID = FD->getBuiltinID();
1711 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1713 StringRef BuiltinName = BI.getName(BuiltinID);
1714 if (BuiltinName.startswith("__builtin_") &&
1715 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1723 struct DLLImportFunctionVisitor
1724 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1725 bool SafeToInline = true;
1727 bool shouldVisitImplicitCode() const { return true; }
1729 bool VisitVarDecl(VarDecl *VD) {
1730 // A thread-local variable cannot be imported.
1731 SafeToInline = !VD->getTLSKind();
1732 return SafeToInline;
1735 // Make sure we're not referencing non-imported vars or functions.
1736 bool VisitDeclRefExpr(DeclRefExpr *E) {
1737 ValueDecl *VD = E->getDecl();
1738 if (isa<FunctionDecl>(VD))
1739 SafeToInline = VD->hasAttr<DLLImportAttr>();
1740 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1741 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1742 return SafeToInline;
1744 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
1745 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
1746 return SafeToInline;
1748 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1749 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1750 return SafeToInline;
1752 bool VisitCXXNewExpr(CXXNewExpr *E) {
1753 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1754 return SafeToInline;
1759 // isTriviallyRecursive - Check if this function calls another
1760 // decl that, because of the asm attribute or the other decl being a builtin,
1761 // ends up pointing to itself.
1763 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1765 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1766 // asm labels are a special kind of mangling we have to support.
1767 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1770 Name = Attr->getLabel();
1772 Name = FD->getName();
1775 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1776 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1777 return Walker.Result;
1780 // Check if T is a class type with a destructor that's not dllimport.
1781 static bool HasNonDllImportDtor(QualType T) {
1782 if (const RecordType *RT = dyn_cast<RecordType>(T))
1783 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1784 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1790 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1791 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1793 const auto *F = cast<FunctionDecl>(GD.getDecl());
1794 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1797 if (F->hasAttr<DLLImportAttr>()) {
1798 // Check whether it would be safe to inline this dllimport function.
1799 DLLImportFunctionVisitor Visitor;
1800 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1801 if (!Visitor.SafeToInline)
1804 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
1805 // Implicit destructor invocations aren't captured in the AST, so the
1806 // check above can't see them. Check for them manually here.
1807 for (const Decl *Member : Dtor->getParent()->decls())
1808 if (isa<FieldDecl>(Member))
1809 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
1811 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
1812 if (HasNonDllImportDtor(B.getType()))
1817 // PR9614. Avoid cases where the source code is lying to us. An available
1818 // externally function should have an equivalent function somewhere else,
1819 // but a function that calls itself is clearly not equivalent to the real
1821 // This happens in glibc's btowc and in some configure checks.
1822 return !isTriviallyRecursive(F);
1825 /// If the type for the method's class was generated by
1826 /// CGDebugInfo::createContextChain(), the cache contains only a
1827 /// limited DIType without any declarations. Since EmitFunctionStart()
1828 /// needs to find the canonical declaration for each method, we need
1829 /// to construct the complete type prior to emitting the method.
1830 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1831 if (!D->isInstance())
1834 if (CGDebugInfo *DI = getModuleDebugInfo())
1835 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo) {
1836 const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1837 DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1841 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1842 const auto *D = cast<ValueDecl>(GD.getDecl());
1844 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1845 Context.getSourceManager(),
1846 "Generating code for declaration");
1848 if (isa<FunctionDecl>(D)) {
1849 // At -O0, don't generate IR for functions with available_externally
1851 if (!shouldEmitFunction(GD))
1854 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1855 CompleteDIClassType(Method);
1856 // Make sure to emit the definition(s) before we emit the thunks.
1857 // This is necessary for the generation of certain thunks.
1858 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1859 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1860 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1861 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1863 EmitGlobalFunctionDefinition(GD, GV);
1865 if (Method->isVirtual())
1866 getVTables().EmitThunks(GD);
1871 return EmitGlobalFunctionDefinition(GD, GV);
1874 if (const auto *VD = dyn_cast<VarDecl>(D))
1875 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1877 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1880 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1881 llvm::Function *NewFn);
1883 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1884 /// module, create and return an llvm Function with the specified type. If there
1885 /// is something in the module with the specified name, return it potentially
1886 /// bitcasted to the right type.
1888 /// If D is non-null, it specifies a decl that correspond to this. This is used
1889 /// to set the attributes on the function when it is first created.
1891 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1893 GlobalDecl GD, bool ForVTable,
1894 bool DontDefer, bool IsThunk,
1895 llvm::AttributeSet ExtraAttrs,
1896 ForDefinition_t IsForDefinition) {
1897 const Decl *D = GD.getDecl();
1899 // Lookup the entry, lazily creating it if necessary.
1900 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1902 if (WeakRefReferences.erase(Entry)) {
1903 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1904 if (FD && !FD->hasAttr<WeakAttr>())
1905 Entry->setLinkage(llvm::Function::ExternalLinkage);
1908 // Handle dropped DLL attributes.
1909 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1910 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1912 // If there are two attempts to define the same mangled name, issue an
1914 if (IsForDefinition && !Entry->isDeclaration()) {
1916 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1917 // to make sure that we issue an error only once.
1918 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1919 (GD.getCanonicalDecl().getDecl() !=
1920 OtherGD.getCanonicalDecl().getDecl()) &&
1921 DiagnosedConflictingDefinitions.insert(GD).second) {
1922 getDiags().Report(D->getLocation(),
1923 diag::err_duplicate_mangled_name);
1924 getDiags().Report(OtherGD.getDecl()->getLocation(),
1925 diag::note_previous_definition);
1929 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1930 (Entry->getType()->getElementType() == Ty)) {
1934 // Make sure the result is of the correct type.
1935 // (If function is requested for a definition, we always need to create a new
1936 // function, not just return a bitcast.)
1937 if (!IsForDefinition)
1938 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1941 // This function doesn't have a complete type (for example, the return
1942 // type is an incomplete struct). Use a fake type instead, and make
1943 // sure not to try to set attributes.
1944 bool IsIncompleteFunction = false;
1946 llvm::FunctionType *FTy;
1947 if (isa<llvm::FunctionType>(Ty)) {
1948 FTy = cast<llvm::FunctionType>(Ty);
1950 FTy = llvm::FunctionType::get(VoidTy, false);
1951 IsIncompleteFunction = true;
1955 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
1956 Entry ? StringRef() : MangledName, &getModule());
1958 // If we already created a function with the same mangled name (but different
1959 // type) before, take its name and add it to the list of functions to be
1960 // replaced with F at the end of CodeGen.
1962 // This happens if there is a prototype for a function (e.g. "int f()") and
1963 // then a definition of a different type (e.g. "int f(int x)").
1967 // This might be an implementation of a function without a prototype, in
1968 // which case, try to do special replacement of calls which match the new
1969 // prototype. The really key thing here is that we also potentially drop
1970 // arguments from the call site so as to make a direct call, which makes the
1971 // inliner happier and suppresses a number of optimizer warnings (!) about
1972 // dropping arguments.
1973 if (!Entry->use_empty()) {
1974 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
1975 Entry->removeDeadConstantUsers();
1978 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
1979 F, Entry->getType()->getElementType()->getPointerTo());
1980 addGlobalValReplacement(Entry, BC);
1983 assert(F->getName() == MangledName && "name was uniqued!");
1985 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1986 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1987 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1988 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1989 llvm::AttributeSet::get(VMContext,
1990 llvm::AttributeSet::FunctionIndex,
1995 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1996 // each other bottoming out with the base dtor. Therefore we emit non-base
1997 // dtors on usage, even if there is no dtor definition in the TU.
1998 if (D && isa<CXXDestructorDecl>(D) &&
1999 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2001 addDeferredDeclToEmit(F, GD);
2003 // This is the first use or definition of a mangled name. If there is a
2004 // deferred decl with this name, remember that we need to emit it at the end
2006 auto DDI = DeferredDecls.find(MangledName);
2007 if (DDI != DeferredDecls.end()) {
2008 // Move the potentially referenced deferred decl to the
2009 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2010 // don't need it anymore).
2011 addDeferredDeclToEmit(F, DDI->second);
2012 DeferredDecls.erase(DDI);
2014 // Otherwise, there are cases we have to worry about where we're
2015 // using a declaration for which we must emit a definition but where
2016 // we might not find a top-level definition:
2017 // - member functions defined inline in their classes
2018 // - friend functions defined inline in some class
2019 // - special member functions with implicit definitions
2020 // If we ever change our AST traversal to walk into class methods,
2021 // this will be unnecessary.
2023 // We also don't emit a definition for a function if it's going to be an
2024 // entry in a vtable, unless it's already marked as used.
2025 } else if (getLangOpts().CPlusPlus && D) {
2026 // Look for a declaration that's lexically in a record.
2027 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2028 FD = FD->getPreviousDecl()) {
2029 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2030 if (FD->doesThisDeclarationHaveABody()) {
2031 addDeferredDeclToEmit(F, GD.getWithDecl(FD));
2039 // Make sure the result is of the requested type.
2040 if (!IsIncompleteFunction) {
2041 assert(F->getType()->getElementType() == Ty);
2045 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2046 return llvm::ConstantExpr::getBitCast(F, PTy);
2049 /// GetAddrOfFunction - Return the address of the given function. If Ty is
2050 /// non-null, then this function will use the specified type if it has to
2051 /// create it (this occurs when we see a definition of the function).
2052 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2056 ForDefinition_t IsForDefinition) {
2057 // If there was no specific requested type, just convert it now.
2059 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2060 auto CanonTy = Context.getCanonicalType(FD->getType());
2061 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2064 StringRef MangledName = getMangledName(GD);
2065 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2066 /*IsThunk=*/false, llvm::AttributeSet(),
2070 static const FunctionDecl *
2071 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2072 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2073 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2075 IdentifierInfo &CII = C.Idents.get(Name);
2076 for (const auto &Result : DC->lookup(&CII))
2077 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2080 if (!C.getLangOpts().CPlusPlus)
2083 // Demangle the premangled name from getTerminateFn()
2084 IdentifierInfo &CXXII =
2085 (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2086 ? C.Idents.get("terminate")
2087 : C.Idents.get(Name);
2089 for (const auto &N : {"__cxxabiv1", "std"}) {
2090 IdentifierInfo &NS = C.Idents.get(N);
2091 for (const auto &Result : DC->lookup(&NS)) {
2092 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2093 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2094 for (const auto &Result : LSD->lookup(&NS))
2095 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2099 for (const auto &Result : ND->lookup(&CXXII))
2100 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2108 /// CreateRuntimeFunction - Create a new runtime function with the specified
2111 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2112 llvm::AttributeSet ExtraAttrs,
2115 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2116 /*DontDefer=*/false, /*IsThunk=*/false,
2119 if (auto *F = dyn_cast<llvm::Function>(C)) {
2121 F->setCallingConv(getRuntimeCC());
2123 if (!Local && getTriple().isOSBinFormatCOFF() &&
2124 !getCodeGenOpts().LTOVisibilityPublicStd) {
2125 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2126 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2127 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2128 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2137 /// CreateBuiltinFunction - Create a new builtin function with the specified
2140 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
2142 llvm::AttributeSet ExtraAttrs) {
2144 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2145 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2146 if (auto *F = dyn_cast<llvm::Function>(C))
2148 F->setCallingConv(getBuiltinCC());
2152 /// isTypeConstant - Determine whether an object of this type can be emitted
2155 /// If ExcludeCtor is true, the duration when the object's constructor runs
2156 /// will not be considered. The caller will need to verify that the object is
2157 /// not written to during its construction.
2158 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2159 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2162 if (Context.getLangOpts().CPlusPlus) {
2163 if (const CXXRecordDecl *Record
2164 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2165 return ExcludeCtor && !Record->hasMutableFields() &&
2166 Record->hasTrivialDestructor();
2172 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2173 /// create and return an llvm GlobalVariable with the specified type. If there
2174 /// is something in the module with the specified name, return it potentially
2175 /// bitcasted to the right type.
2177 /// If D is non-null, it specifies a decl that correspond to this. This is used
2178 /// to set the attributes on the global when it is first created.
2180 /// If IsForDefinition is true, it is guranteed that an actual global with
2181 /// type Ty will be returned, not conversion of a variable with the same
2182 /// mangled name but some other type.
2184 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2185 llvm::PointerType *Ty,
2187 ForDefinition_t IsForDefinition) {
2188 // Lookup the entry, lazily creating it if necessary.
2189 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2191 if (WeakRefReferences.erase(Entry)) {
2192 if (D && !D->hasAttr<WeakAttr>())
2193 Entry->setLinkage(llvm::Function::ExternalLinkage);
2196 // Handle dropped DLL attributes.
2197 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2198 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2200 if (Entry->getType() == Ty)
2203 // If there are two attempts to define the same mangled name, issue an
2205 if (IsForDefinition && !Entry->isDeclaration()) {
2207 const VarDecl *OtherD;
2209 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2210 // to make sure that we issue an error only once.
2211 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2212 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2213 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2214 OtherD->hasInit() &&
2215 DiagnosedConflictingDefinitions.insert(D).second) {
2216 getDiags().Report(D->getLocation(),
2217 diag::err_duplicate_mangled_name);
2218 getDiags().Report(OtherGD.getDecl()->getLocation(),
2219 diag::note_previous_definition);
2223 // Make sure the result is of the correct type.
2224 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2225 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2227 // (If global is requested for a definition, we always need to create a new
2228 // global, not just return a bitcast.)
2229 if (!IsForDefinition)
2230 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2233 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2234 auto *GV = new llvm::GlobalVariable(
2235 getModule(), Ty->getElementType(), false,
2236 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2237 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2239 // If we already created a global with the same mangled name (but different
2240 // type) before, take its name and remove it from its parent.
2242 GV->takeName(Entry);
2244 if (!Entry->use_empty()) {
2245 llvm::Constant *NewPtrForOldDecl =
2246 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2247 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2250 Entry->eraseFromParent();
2253 // This is the first use or definition of a mangled name. If there is a
2254 // deferred decl with this name, remember that we need to emit it at the end
2256 auto DDI = DeferredDecls.find(MangledName);
2257 if (DDI != DeferredDecls.end()) {
2258 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2259 // list, and remove it from DeferredDecls (since we don't need it anymore).
2260 addDeferredDeclToEmit(GV, DDI->second);
2261 DeferredDecls.erase(DDI);
2264 // Handle things which are present even on external declarations.
2266 // FIXME: This code is overly simple and should be merged with other global
2268 GV->setConstant(isTypeConstant(D->getType(), false));
2270 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2272 setLinkageAndVisibilityForGV(GV, D);
2274 if (D->getTLSKind()) {
2275 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2276 CXXThreadLocals.push_back(D);
2280 // If required by the ABI, treat declarations of static data members with
2281 // inline initializers as definitions.
2282 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2283 EmitGlobalVarDefinition(D);
2286 // Handle XCore specific ABI requirements.
2287 if (getTriple().getArch() == llvm::Triple::xcore &&
2288 D->getLanguageLinkage() == CLanguageLinkage &&
2289 D->getType().isConstant(Context) &&
2290 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2291 GV->setSection(".cp.rodata");
2294 if (AddrSpace != Ty->getAddressSpace())
2295 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2301 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2302 ForDefinition_t IsForDefinition) {
2303 const Decl *D = GD.getDecl();
2304 if (isa<CXXConstructorDecl>(D))
2305 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
2306 getFromCtorType(GD.getCtorType()),
2307 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2308 /*DontDefer=*/false, IsForDefinition);
2309 else if (isa<CXXDestructorDecl>(D))
2310 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
2311 getFromDtorType(GD.getDtorType()),
2312 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2313 /*DontDefer=*/false, IsForDefinition);
2314 else if (isa<CXXMethodDecl>(D)) {
2315 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2316 cast<CXXMethodDecl>(D));
2317 auto Ty = getTypes().GetFunctionType(*FInfo);
2318 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2320 } else if (isa<FunctionDecl>(D)) {
2321 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2322 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2323 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2326 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2330 llvm::GlobalVariable *
2331 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2333 llvm::GlobalValue::LinkageTypes Linkage) {
2334 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2335 llvm::GlobalVariable *OldGV = nullptr;
2338 // Check if the variable has the right type.
2339 if (GV->getType()->getElementType() == Ty)
2342 // Because C++ name mangling, the only way we can end up with an already
2343 // existing global with the same name is if it has been declared extern "C".
2344 assert(GV->isDeclaration() && "Declaration has wrong type!");
2348 // Create a new variable.
2349 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2350 Linkage, nullptr, Name);
2353 // Replace occurrences of the old variable if needed.
2354 GV->takeName(OldGV);
2356 if (!OldGV->use_empty()) {
2357 llvm::Constant *NewPtrForOldDecl =
2358 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2359 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2362 OldGV->eraseFromParent();
2365 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2366 !GV->hasAvailableExternallyLinkage())
2367 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2372 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2373 /// given global variable. If Ty is non-null and if the global doesn't exist,
2374 /// then it will be created with the specified type instead of whatever the
2375 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2376 /// that an actual global with type Ty will be returned, not conversion of a
2377 /// variable with the same mangled name but some other type.
2378 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2380 ForDefinition_t IsForDefinition) {
2381 assert(D->hasGlobalStorage() && "Not a global variable");
2382 QualType ASTTy = D->getType();
2384 Ty = getTypes().ConvertTypeForMem(ASTTy);
2386 llvm::PointerType *PTy =
2387 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2389 StringRef MangledName = getMangledName(D);
2390 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2393 /// CreateRuntimeVariable - Create a new runtime global variable with the
2394 /// specified type and name.
2396 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2398 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2401 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2402 assert(!D->getInit() && "Cannot emit definite definitions here!");
2404 StringRef MangledName = getMangledName(D);
2405 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2407 // We already have a definition, not declaration, with the same mangled name.
2408 // Emitting of declaration is not required (and actually overwrites emitted
2410 if (GV && !GV->isDeclaration())
2413 // If we have not seen a reference to this variable yet, place it into the
2414 // deferred declarations table to be emitted if needed later.
2415 if (!MustBeEmitted(D) && !GV) {
2416 DeferredDecls[MangledName] = D;
2420 // The tentative definition is the only definition.
2421 EmitGlobalVarDefinition(D);
2424 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2425 return Context.toCharUnitsFromBits(
2426 getDataLayout().getTypeStoreSizeInBits(Ty));
2429 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2430 unsigned AddrSpace) {
2431 if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2432 if (D->hasAttr<CUDAConstantAttr>())
2433 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2434 else if (D->hasAttr<CUDASharedAttr>())
2435 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2437 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2443 template<typename SomeDecl>
2444 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2445 llvm::GlobalValue *GV) {
2446 if (!getLangOpts().CPlusPlus)
2449 // Must have 'used' attribute, or else inline assembly can't rely on
2450 // the name existing.
2451 if (!D->template hasAttr<UsedAttr>())
2454 // Must have internal linkage and an ordinary name.
2455 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2458 // Must be in an extern "C" context. Entities declared directly within
2459 // a record are not extern "C" even if the record is in such a context.
2460 const SomeDecl *First = D->getFirstDecl();
2461 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2464 // OK, this is an internal linkage entity inside an extern "C" linkage
2465 // specification. Make a note of that so we can give it the "expected"
2466 // mangled name if nothing else is using that name.
2467 std::pair<StaticExternCMap::iterator, bool> R =
2468 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2470 // If we have multiple internal linkage entities with the same name
2471 // in extern "C" regions, none of them gets that name.
2473 R.first->second = nullptr;
2476 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2477 if (!CGM.supportsCOMDAT())
2480 if (D.hasAttr<SelectAnyAttr>())
2484 if (auto *VD = dyn_cast<VarDecl>(&D))
2485 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2487 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2491 case GVA_AvailableExternally:
2492 case GVA_StrongExternal:
2494 case GVA_DiscardableODR:
2498 llvm_unreachable("No such linkage");
2501 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2502 llvm::GlobalObject &GO) {
2503 if (!shouldBeInCOMDAT(*this, D))
2505 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2508 /// Pass IsTentative as true if you want to create a tentative definition.
2509 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2511 // OpenCL global variables of sampler type are translated to function calls,
2512 // therefore no need to be translated.
2513 QualType ASTTy = D->getType();
2514 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
2517 llvm::Constant *Init = nullptr;
2518 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2519 bool NeedsGlobalCtor = false;
2520 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2522 const VarDecl *InitDecl;
2523 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2525 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2526 // as part of their declaration." Sema has already checked for
2527 // error cases, so we just need to set Init to UndefValue.
2528 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2529 D->hasAttr<CUDASharedAttr>())
2530 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2531 else if (!InitExpr) {
2532 // This is a tentative definition; tentative definitions are
2533 // implicitly initialized with { 0 }.
2535 // Note that tentative definitions are only emitted at the end of
2536 // a translation unit, so they should never have incomplete
2537 // type. In addition, EmitTentativeDefinition makes sure that we
2538 // never attempt to emit a tentative definition if a real one
2539 // exists. A use may still exists, however, so we still may need
2541 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2542 Init = EmitNullConstant(D->getType());
2544 initializedGlobalDecl = GlobalDecl(D);
2545 Init = EmitConstantInit(*InitDecl);
2548 QualType T = InitExpr->getType();
2549 if (D->getType()->isReferenceType())
2552 if (getLangOpts().CPlusPlus) {
2553 Init = EmitNullConstant(T);
2554 NeedsGlobalCtor = true;
2556 ErrorUnsupported(D, "static initializer");
2557 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2560 // We don't need an initializer, so remove the entry for the delayed
2561 // initializer position (just in case this entry was delayed) if we
2562 // also don't need to register a destructor.
2563 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2564 DelayedCXXInitPosition.erase(D);
2568 llvm::Type* InitType = Init->getType();
2569 llvm::Constant *Entry =
2570 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2572 // Strip off a bitcast if we got one back.
2573 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2574 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2575 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2576 // All zero index gep.
2577 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2578 Entry = CE->getOperand(0);
2581 // Entry is now either a Function or GlobalVariable.
2582 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2584 // We have a definition after a declaration with the wrong type.
2585 // We must make a new GlobalVariable* and update everything that used OldGV
2586 // (a declaration or tentative definition) with the new GlobalVariable*
2587 // (which will be a definition).
2589 // This happens if there is a prototype for a global (e.g.
2590 // "extern int x[];") and then a definition of a different type (e.g.
2591 // "int x[10];"). This also happens when an initializer has a different type
2592 // from the type of the global (this happens with unions).
2594 GV->getType()->getElementType() != InitType ||
2595 GV->getType()->getAddressSpace() !=
2596 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2598 // Move the old entry aside so that we'll create a new one.
2599 Entry->setName(StringRef());
2601 // Make a new global with the correct type, this is now guaranteed to work.
2602 GV = cast<llvm::GlobalVariable>(
2603 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2605 // Replace all uses of the old global with the new global
2606 llvm::Constant *NewPtrForOldDecl =
2607 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2608 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2610 // Erase the old global, since it is no longer used.
2611 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2614 MaybeHandleStaticInExternC(D, GV);
2616 if (D->hasAttr<AnnotateAttr>())
2617 AddGlobalAnnotations(D, GV);
2619 // Set the llvm linkage type as appropriate.
2620 llvm::GlobalValue::LinkageTypes Linkage =
2621 getLLVMLinkageVarDefinition(D, GV->isConstant());
2623 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2624 // the device. [...]"
2625 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2626 // __device__, declares a variable that: [...]
2627 // Is accessible from all the threads within the grid and from the host
2628 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2629 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2630 if (GV && LangOpts.CUDA) {
2631 if (LangOpts.CUDAIsDevice) {
2632 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2633 GV->setExternallyInitialized(true);
2635 // Host-side shadows of external declarations of device-side
2636 // global variables become internal definitions. These have to
2637 // be internal in order to prevent name conflicts with global
2638 // host variables with the same name in a different TUs.
2639 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2640 Linkage = llvm::GlobalValue::InternalLinkage;
2642 // Shadow variables and their properties must be registered
2643 // with CUDA runtime.
2645 if (!D->hasDefinition())
2646 Flags |= CGCUDARuntime::ExternDeviceVar;
2647 if (D->hasAttr<CUDAConstantAttr>())
2648 Flags |= CGCUDARuntime::ConstantDeviceVar;
2649 getCUDARuntime().registerDeviceVar(*GV, Flags);
2650 } else if (D->hasAttr<CUDASharedAttr>())
2651 // __shared__ variables are odd. Shadows do get created, but
2652 // they are not registered with the CUDA runtime, so they
2653 // can't really be used to access their device-side
2654 // counterparts. It's not clear yet whether it's nvcc's bug or
2655 // a feature, but we've got to do the same for compatibility.
2656 Linkage = llvm::GlobalValue::InternalLinkage;
2659 GV->setInitializer(Init);
2661 // If it is safe to mark the global 'constant', do so now.
2662 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2663 isTypeConstant(D->getType(), true));
2665 // If it is in a read-only section, mark it 'constant'.
2666 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2667 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2668 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2669 GV->setConstant(true);
2672 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2675 // On Darwin, if the normal linkage of a C++ thread_local variable is
2676 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2677 // copies within a linkage unit; otherwise, the backing variable has
2678 // internal linkage and all accesses should just be calls to the
2679 // Itanium-specified entry point, which has the normal linkage of the
2680 // variable. This is to preserve the ability to change the implementation
2681 // behind the scenes.
2682 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2683 Context.getTargetInfo().getTriple().isOSDarwin() &&
2684 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2685 !llvm::GlobalVariable::isWeakLinkage(Linkage))
2686 Linkage = llvm::GlobalValue::InternalLinkage;
2688 GV->setLinkage(Linkage);
2689 if (D->hasAttr<DLLImportAttr>())
2690 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2691 else if (D->hasAttr<DLLExportAttr>())
2692 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2694 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2696 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2697 // common vars aren't constant even if declared const.
2698 GV->setConstant(false);
2699 // Tentative definition of global variables may be initialized with
2700 // non-zero null pointers. In this case they should have weak linkage
2701 // since common linkage must have zero initializer and must not have
2702 // explicit section therefore cannot have non-zero initial value.
2703 if (!GV->getInitializer()->isNullValue())
2704 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2707 setNonAliasAttributes(D, GV);
2709 if (D->getTLSKind() && !GV->isThreadLocal()) {
2710 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2711 CXXThreadLocals.push_back(D);
2715 maybeSetTrivialComdat(*D, *GV);
2717 // Emit the initializer function if necessary.
2718 if (NeedsGlobalCtor || NeedsGlobalDtor)
2719 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2721 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2723 // Emit global variable debug information.
2724 if (CGDebugInfo *DI = getModuleDebugInfo())
2725 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2726 DI->EmitGlobalVariable(GV, D);
2729 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2730 CodeGenModule &CGM, const VarDecl *D,
2732 // Don't give variables common linkage if -fno-common was specified unless it
2733 // was overridden by a NoCommon attribute.
2734 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2738 // A declaration of an identifier for an object that has file scope without
2739 // an initializer, and without a storage-class specifier or with the
2740 // storage-class specifier static, constitutes a tentative definition.
2741 if (D->getInit() || D->hasExternalStorage())
2744 // A variable cannot be both common and exist in a section.
2745 if (D->hasAttr<SectionAttr>())
2748 // Thread local vars aren't considered common linkage.
2749 if (D->getTLSKind())
2752 // Tentative definitions marked with WeakImportAttr are true definitions.
2753 if (D->hasAttr<WeakImportAttr>())
2756 // A variable cannot be both common and exist in a comdat.
2757 if (shouldBeInCOMDAT(CGM, *D))
2760 // Declarations with a required alignment do not have common linkage in MSVC
2762 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2763 if (D->hasAttr<AlignedAttr>())
2765 QualType VarType = D->getType();
2766 if (Context.isAlignmentRequired(VarType))
2769 if (const auto *RT = VarType->getAs<RecordType>()) {
2770 const RecordDecl *RD = RT->getDecl();
2771 for (const FieldDecl *FD : RD->fields()) {
2772 if (FD->isBitField())
2774 if (FD->hasAttr<AlignedAttr>())
2776 if (Context.isAlignmentRequired(FD->getType()))
2785 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2786 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2787 if (Linkage == GVA_Internal)
2788 return llvm::Function::InternalLinkage;
2790 if (D->hasAttr<WeakAttr>()) {
2791 if (IsConstantVariable)
2792 return llvm::GlobalVariable::WeakODRLinkage;
2794 return llvm::GlobalVariable::WeakAnyLinkage;
2797 // We are guaranteed to have a strong definition somewhere else,
2798 // so we can use available_externally linkage.
2799 if (Linkage == GVA_AvailableExternally)
2800 return llvm::Function::AvailableExternallyLinkage;
2802 // Note that Apple's kernel linker doesn't support symbol
2803 // coalescing, so we need to avoid linkonce and weak linkages there.
2804 // Normally, this means we just map to internal, but for explicit
2805 // instantiations we'll map to external.
2807 // In C++, the compiler has to emit a definition in every translation unit
2808 // that references the function. We should use linkonce_odr because
2809 // a) if all references in this translation unit are optimized away, we
2810 // don't need to codegen it. b) if the function persists, it needs to be
2811 // merged with other definitions. c) C++ has the ODR, so we know the
2812 // definition is dependable.
2813 if (Linkage == GVA_DiscardableODR)
2814 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2815 : llvm::Function::InternalLinkage;
2817 // An explicit instantiation of a template has weak linkage, since
2818 // explicit instantiations can occur in multiple translation units
2819 // and must all be equivalent. However, we are not allowed to
2820 // throw away these explicit instantiations.
2822 // We don't currently support CUDA device code spread out across multiple TUs,
2823 // so say that CUDA templates are either external (for kernels) or internal.
2824 // This lets llvm perform aggressive inter-procedural optimizations.
2825 if (Linkage == GVA_StrongODR) {
2826 if (Context.getLangOpts().AppleKext)
2827 return llvm::Function::ExternalLinkage;
2828 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2829 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2830 : llvm::Function::InternalLinkage;
2831 return llvm::Function::WeakODRLinkage;
2834 // C++ doesn't have tentative definitions and thus cannot have common
2836 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2837 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2838 CodeGenOpts.NoCommon))
2839 return llvm::GlobalVariable::CommonLinkage;
2841 // selectany symbols are externally visible, so use weak instead of
2842 // linkonce. MSVC optimizes away references to const selectany globals, so
2843 // all definitions should be the same and ODR linkage should be used.
2844 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2845 if (D->hasAttr<SelectAnyAttr>())
2846 return llvm::GlobalVariable::WeakODRLinkage;
2848 // Otherwise, we have strong external linkage.
2849 assert(Linkage == GVA_StrongExternal);
2850 return llvm::GlobalVariable::ExternalLinkage;
2853 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2854 const VarDecl *VD, bool IsConstant) {
2855 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2856 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2859 /// Replace the uses of a function that was declared with a non-proto type.
2860 /// We want to silently drop extra arguments from call sites
2861 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2862 llvm::Function *newFn) {
2864 if (old->use_empty()) return;
2866 llvm::Type *newRetTy = newFn->getReturnType();
2867 SmallVector<llvm::Value*, 4> newArgs;
2868 SmallVector<llvm::OperandBundleDef, 1> newBundles;
2870 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2872 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2873 llvm::User *user = use->getUser();
2875 // Recognize and replace uses of bitcasts. Most calls to
2876 // unprototyped functions will use bitcasts.
2877 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2878 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2879 replaceUsesOfNonProtoConstant(bitcast, newFn);
2883 // Recognize calls to the function.
2884 llvm::CallSite callSite(user);
2885 if (!callSite) continue;
2886 if (!callSite.isCallee(&*use)) continue;
2888 // If the return types don't match exactly, then we can't
2889 // transform this call unless it's dead.
2890 if (callSite->getType() != newRetTy && !callSite->use_empty())
2893 // Get the call site's attribute list.
2894 SmallVector<llvm::AttributeSet, 8> newAttrs;
2895 llvm::AttributeSet oldAttrs = callSite.getAttributes();
2897 // Collect any return attributes from the call.
2898 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2900 llvm::AttributeSet::get(newFn->getContext(),
2901 oldAttrs.getRetAttributes()));
2903 // If the function was passed too few arguments, don't transform.
2904 unsigned newNumArgs = newFn->arg_size();
2905 if (callSite.arg_size() < newNumArgs) continue;
2907 // If extra arguments were passed, we silently drop them.
2908 // If any of the types mismatch, we don't transform.
2910 bool dontTransform = false;
2911 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2912 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2913 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2914 dontTransform = true;
2918 // Add any parameter attributes.
2919 if (oldAttrs.hasAttributes(argNo + 1))
2922 AttributeSet::get(newFn->getContext(),
2923 oldAttrs.getParamAttributes(argNo + 1)));
2928 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2929 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2930 oldAttrs.getFnAttributes()));
2932 // Okay, we can transform this. Create the new call instruction and copy
2933 // over the required information.
2934 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2936 // Copy over any operand bundles.
2937 callSite.getOperandBundlesAsDefs(newBundles);
2939 llvm::CallSite newCall;
2940 if (callSite.isCall()) {
2941 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2942 callSite.getInstruction());
2944 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2945 newCall = llvm::InvokeInst::Create(newFn,
2946 oldInvoke->getNormalDest(),
2947 oldInvoke->getUnwindDest(),
2948 newArgs, newBundles, "",
2949 callSite.getInstruction());
2951 newArgs.clear(); // for the next iteration
2953 if (!newCall->getType()->isVoidTy())
2954 newCall->takeName(callSite.getInstruction());
2955 newCall.setAttributes(
2956 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2957 newCall.setCallingConv(callSite.getCallingConv());
2959 // Finally, remove the old call, replacing any uses with the new one.
2960 if (!callSite->use_empty())
2961 callSite->replaceAllUsesWith(newCall.getInstruction());
2963 // Copy debug location attached to CI.
2964 if (callSite->getDebugLoc())
2965 newCall->setDebugLoc(callSite->getDebugLoc());
2967 callSite->eraseFromParent();
2971 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2972 /// implement a function with no prototype, e.g. "int foo() {}". If there are
2973 /// existing call uses of the old function in the module, this adjusts them to
2974 /// call the new function directly.
2976 /// This is not just a cleanup: the always_inline pass requires direct calls to
2977 /// functions to be able to inline them. If there is a bitcast in the way, it
2978 /// won't inline them. Instcombine normally deletes these calls, but it isn't
2980 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2981 llvm::Function *NewFn) {
2982 // If we're redefining a global as a function, don't transform it.
2983 if (!isa<llvm::Function>(Old)) return;
2985 replaceUsesOfNonProtoConstant(Old, NewFn);
2988 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2989 auto DK = VD->isThisDeclarationADefinition();
2990 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
2993 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2994 // If we have a definition, this might be a deferred decl. If the
2995 // instantiation is explicit, make sure we emit it at the end.
2996 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2997 GetAddrOfGlobalVar(VD);
2999 EmitTopLevelDecl(VD);
3002 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3003 llvm::GlobalValue *GV) {
3004 const auto *D = cast<FunctionDecl>(GD.getDecl());
3006 // Compute the function info and LLVM type.
3007 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3008 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3010 // Get or create the prototype for the function.
3011 if (!GV || (GV->getType()->getElementType() != Ty))
3012 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3017 if (!GV->isDeclaration())
3020 // We need to set linkage and visibility on the function before
3021 // generating code for it because various parts of IR generation
3022 // want to propagate this information down (e.g. to local static
3024 auto *Fn = cast<llvm::Function>(GV);
3025 setFunctionLinkage(GD, Fn);
3026 setFunctionDLLStorageClass(GD, Fn);
3028 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3029 setGlobalVisibility(Fn, D);
3031 MaybeHandleStaticInExternC(D, Fn);
3033 maybeSetTrivialComdat(*D, *Fn);
3035 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3037 setFunctionDefinitionAttributes(D, Fn);
3038 SetLLVMFunctionAttributesForDefinition(D, Fn);
3040 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3041 AddGlobalCtor(Fn, CA->getPriority());
3042 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3043 AddGlobalDtor(Fn, DA->getPriority());
3044 if (D->hasAttr<AnnotateAttr>())
3045 AddGlobalAnnotations(D, Fn);
3048 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3049 const auto *D = cast<ValueDecl>(GD.getDecl());
3050 const AliasAttr *AA = D->getAttr<AliasAttr>();
3051 assert(AA && "Not an alias?");
3053 StringRef MangledName = getMangledName(GD);
3055 if (AA->getAliasee() == MangledName) {
3056 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3060 // If there is a definition in the module, then it wins over the alias.
3061 // This is dubious, but allow it to be safe. Just ignore the alias.
3062 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3063 if (Entry && !Entry->isDeclaration())
3066 Aliases.push_back(GD);
3068 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3070 // Create a reference to the named value. This ensures that it is emitted
3071 // if a deferred decl.
3072 llvm::Constant *Aliasee;
3073 if (isa<llvm::FunctionType>(DeclTy))
3074 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3075 /*ForVTable=*/false);
3077 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3078 llvm::PointerType::getUnqual(DeclTy),
3081 // Create the new alias itself, but don't set a name yet.
3082 auto *GA = llvm::GlobalAlias::create(
3083 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3086 if (GA->getAliasee() == Entry) {
3087 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3091 assert(Entry->isDeclaration());
3093 // If there is a declaration in the module, then we had an extern followed
3094 // by the alias, as in:
3095 // extern int test6();
3097 // int test6() __attribute__((alias("test7")));
3099 // Remove it and replace uses of it with the alias.
3100 GA->takeName(Entry);
3102 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3104 Entry->eraseFromParent();
3106 GA->setName(MangledName);
3109 // Set attributes which are particular to an alias; this is a
3110 // specialization of the attributes which may be set on a global
3111 // variable/function.
3112 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3113 D->isWeakImported()) {
3114 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3117 if (const auto *VD = dyn_cast<VarDecl>(D))
3118 if (VD->getTLSKind())
3119 setTLSMode(GA, *VD);
3121 setAliasAttributes(D, GA);
3124 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3125 const auto *D = cast<ValueDecl>(GD.getDecl());
3126 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3127 assert(IFA && "Not an ifunc?");
3129 StringRef MangledName = getMangledName(GD);
3131 if (IFA->getResolver() == MangledName) {
3132 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3136 // Report an error if some definition overrides ifunc.
3137 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3138 if (Entry && !Entry->isDeclaration()) {
3140 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3141 DiagnosedConflictingDefinitions.insert(GD).second) {
3142 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3143 Diags.Report(OtherGD.getDecl()->getLocation(),
3144 diag::note_previous_definition);
3149 Aliases.push_back(GD);
3151 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3152 llvm::Constant *Resolver =
3153 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3154 /*ForVTable=*/false);
3155 llvm::GlobalIFunc *GIF =
3156 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3157 "", Resolver, &getModule());
3159 if (GIF->getResolver() == Entry) {
3160 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3163 assert(Entry->isDeclaration());
3165 // If there is a declaration in the module, then we had an extern followed
3166 // by the ifunc, as in:
3167 // extern int test();
3169 // int test() __attribute__((ifunc("resolver")));
3171 // Remove it and replace uses of it with the ifunc.
3172 GIF->takeName(Entry);
3174 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3176 Entry->eraseFromParent();
3178 GIF->setName(MangledName);
3180 SetCommonAttributes(D, GIF);
3183 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3184 ArrayRef<llvm::Type*> Tys) {
3185 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3189 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3190 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3191 const StringLiteral *Literal, bool TargetIsLSB,
3192 bool &IsUTF16, unsigned &StringLength) {
3193 StringRef String = Literal->getString();
3194 unsigned NumBytes = String.size();
3196 // Check for simple case.
3197 if (!Literal->containsNonAsciiOrNull()) {
3198 StringLength = NumBytes;
3199 return *Map.insert(std::make_pair(String, nullptr)).first;
3202 // Otherwise, convert the UTF8 literals into a string of shorts.
3205 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3206 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3207 llvm::UTF16 *ToPtr = &ToBuf[0];
3209 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3210 ToPtr + NumBytes, llvm::strictConversion);
3212 // ConvertUTF8toUTF16 returns the length in ToPtr.
3213 StringLength = ToPtr - &ToBuf[0];
3215 // Add an explicit null.
3217 return *Map.insert(std::make_pair(
3218 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3219 (StringLength + 1) * 2),
3224 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3225 unsigned StringLength = 0;
3226 bool isUTF16 = false;
3227 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3228 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3229 getDataLayout().isLittleEndian(), isUTF16,
3232 if (auto *C = Entry.second)
3233 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3235 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3236 llvm::Constant *Zeros[] = { Zero, Zero };
3238 // If we don't already have it, get __CFConstantStringClassReference.
3239 if (!CFConstantStringClassRef) {
3240 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3241 Ty = llvm::ArrayType::get(Ty, 0);
3242 llvm::Constant *GV =
3243 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3245 if (getTriple().isOSBinFormatCOFF()) {
3246 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3247 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3248 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3249 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3251 const VarDecl *VD = nullptr;
3252 for (const auto &Result : DC->lookup(&II))
3253 if ((VD = dyn_cast<VarDecl>(Result)))
3256 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3257 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3258 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3260 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3261 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3265 // Decay array -> ptr
3266 CFConstantStringClassRef =
3267 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3270 QualType CFTy = getContext().getCFConstantStringType();
3272 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3274 ConstantInitBuilder Builder(*this);
3275 auto Fields = Builder.beginStruct(STy);
3278 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3281 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3284 llvm::Constant *C = nullptr;
3286 auto Arr = llvm::makeArrayRef(
3287 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3288 Entry.first().size() / 2);
3289 C = llvm::ConstantDataArray::get(VMContext, Arr);
3291 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3294 // Note: -fwritable-strings doesn't make the backing store strings of
3295 // CFStrings writable. (See <rdar://problem/10657500>)
3297 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3298 llvm::GlobalValue::PrivateLinkage, C, ".str");
3299 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3300 // Don't enforce the target's minimum global alignment, since the only use
3301 // of the string is via this class initializer.
3302 CharUnits Align = isUTF16
3303 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3304 : getContext().getTypeAlignInChars(getContext().CharTy);
3305 GV->setAlignment(Align.getQuantity());
3307 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3308 // Without it LLVM can merge the string with a non unnamed_addr one during
3309 // LTO. Doing that changes the section it ends in, which surprises ld64.
3310 if (getTriple().isOSBinFormatMachO())
3311 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3312 : "__TEXT,__cstring,cstring_literals");
3315 llvm::Constant *Str =
3316 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3319 // Cast the UTF16 string to the correct type.
3320 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3324 auto Ty = getTypes().ConvertType(getContext().LongTy);
3325 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3327 CharUnits Alignment = getPointerAlign();
3330 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3331 /*isConstant=*/false,
3332 llvm::GlobalVariable::PrivateLinkage);
3333 switch (getTriple().getObjectFormat()) {
3334 case llvm::Triple::UnknownObjectFormat:
3335 llvm_unreachable("unknown file format");
3336 case llvm::Triple::COFF:
3337 case llvm::Triple::ELF:
3338 GV->setSection("cfstring");
3340 case llvm::Triple::MachO:
3341 GV->setSection("__DATA,__cfstring");
3346 return ConstantAddress(GV, Alignment);
3349 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3350 if (ObjCFastEnumerationStateType.isNull()) {
3351 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3352 D->startDefinition();
3354 QualType FieldTypes[] = {
3355 Context.UnsignedLongTy,
3356 Context.getPointerType(Context.getObjCIdType()),
3357 Context.getPointerType(Context.UnsignedLongTy),
3358 Context.getConstantArrayType(Context.UnsignedLongTy,
3359 llvm::APInt(32, 5), ArrayType::Normal, 0)
3362 for (size_t i = 0; i < 4; ++i) {
3363 FieldDecl *Field = FieldDecl::Create(Context,
3366 SourceLocation(), nullptr,
3367 FieldTypes[i], /*TInfo=*/nullptr,
3368 /*BitWidth=*/nullptr,
3371 Field->setAccess(AS_public);
3375 D->completeDefinition();
3376 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3379 return ObjCFastEnumerationStateType;
3383 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3384 assert(!E->getType()->isPointerType() && "Strings are always arrays");
3386 // Don't emit it as the address of the string, emit the string data itself
3387 // as an inline array.
3388 if (E->getCharByteWidth() == 1) {
3389 SmallString<64> Str(E->getString());
3391 // Resize the string to the right size, which is indicated by its type.
3392 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3393 Str.resize(CAT->getSize().getZExtValue());
3394 return llvm::ConstantDataArray::getString(VMContext, Str, false);
3397 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3398 llvm::Type *ElemTy = AType->getElementType();
3399 unsigned NumElements = AType->getNumElements();
3401 // Wide strings have either 2-byte or 4-byte elements.
3402 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3403 SmallVector<uint16_t, 32> Elements;
3404 Elements.reserve(NumElements);
3406 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3407 Elements.push_back(E->getCodeUnit(i));
3408 Elements.resize(NumElements);
3409 return llvm::ConstantDataArray::get(VMContext, Elements);
3412 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3413 SmallVector<uint32_t, 32> Elements;
3414 Elements.reserve(NumElements);
3416 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3417 Elements.push_back(E->getCodeUnit(i));
3418 Elements.resize(NumElements);
3419 return llvm::ConstantDataArray::get(VMContext, Elements);
3422 static llvm::GlobalVariable *
3423 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3424 CodeGenModule &CGM, StringRef GlobalName,
3425 CharUnits Alignment) {
3426 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3427 unsigned AddrSpace = 0;
3428 if (CGM.getLangOpts().OpenCL)
3429 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3431 llvm::Module &M = CGM.getModule();
3432 // Create a global variable for this string
3433 auto *GV = new llvm::GlobalVariable(
3434 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3435 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3436 GV->setAlignment(Alignment.getQuantity());
3437 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3438 if (GV->isWeakForLinker()) {
3439 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3440 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3446 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3447 /// constant array for the given string literal.
3449 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3451 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3453 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3454 llvm::GlobalVariable **Entry = nullptr;
3455 if (!LangOpts.WritableStrings) {
3456 Entry = &ConstantStringMap[C];
3457 if (auto GV = *Entry) {
3458 if (Alignment.getQuantity() > GV->getAlignment())
3459 GV->setAlignment(Alignment.getQuantity());
3460 return ConstantAddress(GV, Alignment);
3464 SmallString<256> MangledNameBuffer;
3465 StringRef GlobalVariableName;
3466 llvm::GlobalValue::LinkageTypes LT;
3468 // Mangle the string literal if the ABI allows for it. However, we cannot
3469 // do this if we are compiling with ASan or -fwritable-strings because they
3470 // rely on strings having normal linkage.
3471 if (!LangOpts.WritableStrings &&
3472 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3473 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3474 llvm::raw_svector_ostream Out(MangledNameBuffer);
3475 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3477 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3478 GlobalVariableName = MangledNameBuffer;
3480 LT = llvm::GlobalValue::PrivateLinkage;
3481 GlobalVariableName = Name;
3484 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3488 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3490 return ConstantAddress(GV, Alignment);
3493 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3494 /// array for the given ObjCEncodeExpr node.
3496 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3498 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3500 return GetAddrOfConstantCString(Str);
3503 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3504 /// the literal and a terminating '\0' character.
3505 /// The result has pointer to array type.
3506 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3507 const std::string &Str, const char *GlobalName) {
3508 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3509 CharUnits Alignment =
3510 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3513 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3515 // Don't share any string literals if strings aren't constant.
3516 llvm::GlobalVariable **Entry = nullptr;
3517 if (!LangOpts.WritableStrings) {
3518 Entry = &ConstantStringMap[C];
3519 if (auto GV = *Entry) {
3520 if (Alignment.getQuantity() > GV->getAlignment())
3521 GV->setAlignment(Alignment.getQuantity());
3522 return ConstantAddress(GV, Alignment);
3526 // Get the default prefix if a name wasn't specified.
3528 GlobalName = ".str";
3529 // Create a global variable for this.
3530 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3531 GlobalName, Alignment);
3534 return ConstantAddress(GV, Alignment);
3537 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3538 const MaterializeTemporaryExpr *E, const Expr *Init) {
3539 assert((E->getStorageDuration() == SD_Static ||
3540 E->getStorageDuration() == SD_Thread) && "not a global temporary");
3541 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3543 // If we're not materializing a subobject of the temporary, keep the
3544 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3545 QualType MaterializedType = Init->getType();
3546 if (Init == E->GetTemporaryExpr())
3547 MaterializedType = E->getType();
3549 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3551 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3552 return ConstantAddress(Slot, Align);
3554 // FIXME: If an externally-visible declaration extends multiple temporaries,
3555 // we need to give each temporary the same name in every translation unit (and
3556 // we also need to make the temporaries externally-visible).
3557 SmallString<256> Name;
3558 llvm::raw_svector_ostream Out(Name);
3559 getCXXABI().getMangleContext().mangleReferenceTemporary(
3560 VD, E->getManglingNumber(), Out);
3562 APValue *Value = nullptr;
3563 if (E->getStorageDuration() == SD_Static) {
3564 // We might have a cached constant initializer for this temporary. Note
3565 // that this might have a different value from the value computed by
3566 // evaluating the initializer if the surrounding constant expression
3567 // modifies the temporary.
3568 Value = getContext().getMaterializedTemporaryValue(E, false);
3569 if (Value && Value->isUninit())
3573 // Try evaluating it now, it might have a constant initializer.
3574 Expr::EvalResult EvalResult;
3575 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3576 !EvalResult.hasSideEffects())
3577 Value = &EvalResult.Val;
3579 llvm::Constant *InitialValue = nullptr;
3580 bool Constant = false;
3583 // The temporary has a constant initializer, use it.
3584 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3585 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3586 Type = InitialValue->getType();
3588 // No initializer, the initialization will be provided when we
3589 // initialize the declaration which performed lifetime extension.
3590 Type = getTypes().ConvertTypeForMem(MaterializedType);
3593 // Create a global variable for this lifetime-extended temporary.
3594 llvm::GlobalValue::LinkageTypes Linkage =
3595 getLLVMLinkageVarDefinition(VD, Constant);
3596 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3597 const VarDecl *InitVD;
3598 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3599 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3600 // Temporaries defined inside a class get linkonce_odr linkage because the
3601 // class can be defined in multipe translation units.
3602 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3604 // There is no need for this temporary to have external linkage if the
3605 // VarDecl has external linkage.
3606 Linkage = llvm::GlobalVariable::InternalLinkage;
3609 unsigned AddrSpace = GetGlobalVarAddressSpace(
3610 VD, getContext().getTargetAddressSpace(MaterializedType));
3611 auto *GV = new llvm::GlobalVariable(
3612 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3613 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3615 setGlobalVisibility(GV, VD);
3616 GV->setAlignment(Align.getQuantity());
3617 if (supportsCOMDAT() && GV->isWeakForLinker())
3618 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3619 if (VD->getTLSKind())
3620 setTLSMode(GV, *VD);
3621 MaterializedGlobalTemporaryMap[E] = GV;
3622 return ConstantAddress(GV, Align);
3625 /// EmitObjCPropertyImplementations - Emit information for synthesized
3626 /// properties for an implementation.
3627 void CodeGenModule::EmitObjCPropertyImplementations(const
3628 ObjCImplementationDecl *D) {
3629 for (const auto *PID : D->property_impls()) {
3630 // Dynamic is just for type-checking.
3631 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3632 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3634 // Determine which methods need to be implemented, some may have
3635 // been overridden. Note that ::isPropertyAccessor is not the method
3636 // we want, that just indicates if the decl came from a
3637 // property. What we want to know is if the method is defined in
3638 // this implementation.
3639 if (!D->getInstanceMethod(PD->getGetterName()))
3640 CodeGenFunction(*this).GenerateObjCGetter(
3641 const_cast<ObjCImplementationDecl *>(D), PID);
3642 if (!PD->isReadOnly() &&
3643 !D->getInstanceMethod(PD->getSetterName()))
3644 CodeGenFunction(*this).GenerateObjCSetter(
3645 const_cast<ObjCImplementationDecl *>(D), PID);
3650 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3651 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3652 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3653 ivar; ivar = ivar->getNextIvar())
3654 if (ivar->getType().isDestructedType())
3660 static bool AllTrivialInitializers(CodeGenModule &CGM,
3661 ObjCImplementationDecl *D) {
3662 CodeGenFunction CGF(CGM);
3663 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3664 E = D->init_end(); B != E; ++B) {
3665 CXXCtorInitializer *CtorInitExp = *B;
3666 Expr *Init = CtorInitExp->getInit();
3667 if (!CGF.isTrivialInitializer(Init))
3673 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3674 /// for an implementation.
3675 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3676 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3677 if (needsDestructMethod(D)) {
3678 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3679 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3680 ObjCMethodDecl *DTORMethod =
3681 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3682 cxxSelector, getContext().VoidTy, nullptr, D,
3683 /*isInstance=*/true, /*isVariadic=*/false,
3684 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3685 /*isDefined=*/false, ObjCMethodDecl::Required);
3686 D->addInstanceMethod(DTORMethod);
3687 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3688 D->setHasDestructors(true);
3691 // If the implementation doesn't have any ivar initializers, we don't need
3692 // a .cxx_construct.
3693 if (D->getNumIvarInitializers() == 0 ||
3694 AllTrivialInitializers(*this, D))
3697 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3698 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3699 // The constructor returns 'self'.
3700 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3704 getContext().getObjCIdType(),
3705 nullptr, D, /*isInstance=*/true,
3706 /*isVariadic=*/false,
3707 /*isPropertyAccessor=*/true,
3708 /*isImplicitlyDeclared=*/true,
3709 /*isDefined=*/false,
3710 ObjCMethodDecl::Required);
3711 D->addInstanceMethod(CTORMethod);
3712 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3713 D->setHasNonZeroConstructors(true);
3716 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3717 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3718 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3719 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3720 ErrorUnsupported(LSD, "linkage spec");
3724 EmitDeclContext(LSD);
3727 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
3728 for (auto *I : DC->decls()) {
3729 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
3730 // are themselves considered "top-level", so EmitTopLevelDecl on an
3731 // ObjCImplDecl does not recursively visit them. We need to do that in
3732 // case they're nested inside another construct (LinkageSpecDecl /
3733 // ExportDecl) that does stop them from being considered "top-level".
3734 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3735 for (auto *M : OID->methods())
3736 EmitTopLevelDecl(M);
3739 EmitTopLevelDecl(I);
3743 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3744 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3745 // Ignore dependent declarations.
3746 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3749 switch (D->getKind()) {
3750 case Decl::CXXConversion:
3751 case Decl::CXXMethod:
3752 case Decl::Function:
3753 // Skip function templates
3754 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3755 cast<FunctionDecl>(D)->isLateTemplateParsed())
3758 EmitGlobal(cast<FunctionDecl>(D));
3759 // Always provide some coverage mapping
3760 // even for the functions that aren't emitted.
3761 AddDeferredUnusedCoverageMapping(D);
3765 case Decl::Decomposition:
3766 // Skip variable templates
3767 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3769 case Decl::VarTemplateSpecialization:
3770 EmitGlobal(cast<VarDecl>(D));
3771 if (auto *DD = dyn_cast<DecompositionDecl>(D))
3772 for (auto *B : DD->bindings())
3773 if (auto *HD = B->getHoldingVar())
3777 // Indirect fields from global anonymous structs and unions can be
3778 // ignored; only the actual variable requires IR gen support.
3779 case Decl::IndirectField:
3783 case Decl::Namespace:
3784 EmitDeclContext(cast<NamespaceDecl>(D));
3786 case Decl::CXXRecord:
3787 // Emit any static data members, they may be definitions.
3788 for (auto *I : cast<CXXRecordDecl>(D)->decls())
3789 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3790 EmitTopLevelDecl(I);
3792 // No code generation needed.
3793 case Decl::UsingShadow:
3794 case Decl::ClassTemplate:
3795 case Decl::VarTemplate:
3796 case Decl::VarTemplatePartialSpecialization:
3797 case Decl::FunctionTemplate:
3798 case Decl::TypeAliasTemplate:
3802 case Decl::Using: // using X; [C++]
3803 if (CGDebugInfo *DI = getModuleDebugInfo())
3804 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3806 case Decl::NamespaceAlias:
3807 if (CGDebugInfo *DI = getModuleDebugInfo())
3808 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3810 case Decl::UsingDirective: // using namespace X; [C++]
3811 if (CGDebugInfo *DI = getModuleDebugInfo())
3812 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3814 case Decl::CXXConstructor:
3815 // Skip function templates
3816 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3817 cast<FunctionDecl>(D)->isLateTemplateParsed())
3820 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3822 case Decl::CXXDestructor:
3823 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3825 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3828 case Decl::StaticAssert:
3832 // Objective-C Decls
3834 // Forward declarations, no (immediate) code generation.
3835 case Decl::ObjCInterface:
3836 case Decl::ObjCCategory:
3839 case Decl::ObjCProtocol: {
3840 auto *Proto = cast<ObjCProtocolDecl>(D);
3841 if (Proto->isThisDeclarationADefinition())
3842 ObjCRuntime->GenerateProtocol(Proto);
3846 case Decl::ObjCCategoryImpl:
3847 // Categories have properties but don't support synthesize so we
3848 // can ignore them here.
3849 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3852 case Decl::ObjCImplementation: {
3853 auto *OMD = cast<ObjCImplementationDecl>(D);
3854 EmitObjCPropertyImplementations(OMD);
3855 EmitObjCIvarInitializations(OMD);
3856 ObjCRuntime->GenerateClass(OMD);
3857 // Emit global variable debug information.
3858 if (CGDebugInfo *DI = getModuleDebugInfo())
3859 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3860 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3861 OMD->getClassInterface()), OMD->getLocation());
3864 case Decl::ObjCMethod: {
3865 auto *OMD = cast<ObjCMethodDecl>(D);
3866 // If this is not a prototype, emit the body.
3868 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3871 case Decl::ObjCCompatibleAlias:
3872 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3875 case Decl::PragmaComment: {
3876 const auto *PCD = cast<PragmaCommentDecl>(D);
3877 switch (PCD->getCommentKind()) {
3879 llvm_unreachable("unexpected pragma comment kind");
3881 AppendLinkerOptions(PCD->getArg());
3884 AddDependentLib(PCD->getArg());
3889 break; // We ignore all of these.
3894 case Decl::PragmaDetectMismatch: {
3895 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3896 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3900 case Decl::LinkageSpec:
3901 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3904 case Decl::FileScopeAsm: {
3905 // File-scope asm is ignored during device-side CUDA compilation.
3906 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3908 // File-scope asm is ignored during device-side OpenMP compilation.
3909 if (LangOpts.OpenMPIsDevice)
3911 auto *AD = cast<FileScopeAsmDecl>(D);
3912 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3916 case Decl::Import: {
3917 auto *Import = cast<ImportDecl>(D);
3919 // If we've already imported this module, we're done.
3920 if (!ImportedModules.insert(Import->getImportedModule()))
3923 // Emit debug information for direct imports.
3924 if (!Import->getImportedOwningModule()) {
3925 if (CGDebugInfo *DI = getModuleDebugInfo())
3926 DI->EmitImportDecl(*Import);
3929 // Find all of the submodules and emit the module initializers.
3930 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3931 SmallVector<clang::Module *, 16> Stack;
3932 Visited.insert(Import->getImportedModule());
3933 Stack.push_back(Import->getImportedModule());
3935 while (!Stack.empty()) {
3936 clang::Module *Mod = Stack.pop_back_val();
3937 if (!EmittedModuleInitializers.insert(Mod).second)
3940 for (auto *D : Context.getModuleInitializers(Mod))
3941 EmitTopLevelDecl(D);
3943 // Visit the submodules of this module.
3944 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
3945 SubEnd = Mod->submodule_end();
3946 Sub != SubEnd; ++Sub) {
3947 // Skip explicit children; they need to be explicitly imported to emit
3948 // the initializers.
3949 if ((*Sub)->IsExplicit)
3952 if (Visited.insert(*Sub).second)
3953 Stack.push_back(*Sub);
3960 EmitDeclContext(cast<ExportDecl>(D));
3963 case Decl::OMPThreadPrivate:
3964 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3967 case Decl::ClassTemplateSpecialization: {
3968 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3970 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3971 Spec->hasDefinition())
3972 DebugInfo->completeTemplateDefinition(*Spec);
3976 case Decl::OMPDeclareReduction:
3977 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
3981 // Make sure we handled everything we should, every other kind is a
3982 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
3983 // function. Need to recode Decl::Kind to do that easily.
3984 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3989 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3990 // Do we need to generate coverage mapping?
3991 if (!CodeGenOpts.CoverageMapping)
3993 switch (D->getKind()) {
3994 case Decl::CXXConversion:
3995 case Decl::CXXMethod:
3996 case Decl::Function:
3997 case Decl::ObjCMethod:
3998 case Decl::CXXConstructor:
3999 case Decl::CXXDestructor: {
4000 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4002 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4003 if (I == DeferredEmptyCoverageMappingDecls.end())
4004 DeferredEmptyCoverageMappingDecls[D] = true;
4012 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4013 // Do we need to generate coverage mapping?
4014 if (!CodeGenOpts.CoverageMapping)
4016 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4017 if (Fn->isTemplateInstantiation())
4018 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4020 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4021 if (I == DeferredEmptyCoverageMappingDecls.end())
4022 DeferredEmptyCoverageMappingDecls[D] = false;
4027 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4028 std::vector<const Decl *> DeferredDecls;
4029 for (const auto &I : DeferredEmptyCoverageMappingDecls) {
4032 DeferredDecls.push_back(I.first);
4034 // Sort the declarations by their location to make sure that the tests get a
4035 // predictable order for the coverage mapping for the unused declarations.
4036 if (CodeGenOpts.DumpCoverageMapping)
4037 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4038 [] (const Decl *LHS, const Decl *RHS) {
4039 return LHS->getLocStart() < RHS->getLocStart();
4041 for (const auto *D : DeferredDecls) {
4042 switch (D->getKind()) {
4043 case Decl::CXXConversion:
4044 case Decl::CXXMethod:
4045 case Decl::Function:
4046 case Decl::ObjCMethod: {
4047 CodeGenPGO PGO(*this);
4048 GlobalDecl GD(cast<FunctionDecl>(D));
4049 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4050 getFunctionLinkage(GD));
4053 case Decl::CXXConstructor: {
4054 CodeGenPGO PGO(*this);
4055 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4056 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4057 getFunctionLinkage(GD));
4060 case Decl::CXXDestructor: {
4061 CodeGenPGO PGO(*this);
4062 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4063 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4064 getFunctionLinkage(GD));
4073 /// Turns the given pointer into a constant.
4074 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4076 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4077 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4078 return llvm::ConstantInt::get(i64, PtrInt);
4081 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4082 llvm::NamedMDNode *&GlobalMetadata,
4084 llvm::GlobalValue *Addr) {
4085 if (!GlobalMetadata)
4087 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4089 // TODO: should we report variant information for ctors/dtors?
4090 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4091 llvm::ConstantAsMetadata::get(GetPointerConstant(
4092 CGM.getLLVMContext(), D.getDecl()))};
4093 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4096 /// For each function which is declared within an extern "C" region and marked
4097 /// as 'used', but has internal linkage, create an alias from the unmangled
4098 /// name to the mangled name if possible. People expect to be able to refer
4099 /// to such functions with an unmangled name from inline assembly within the
4100 /// same translation unit.
4101 void CodeGenModule::EmitStaticExternCAliases() {
4102 // Don't do anything if we're generating CUDA device code -- the NVPTX
4103 // assembly target doesn't support aliases.
4104 if (Context.getTargetInfo().getTriple().isNVPTX())
4106 for (auto &I : StaticExternCValues) {
4107 IdentifierInfo *Name = I.first;
4108 llvm::GlobalValue *Val = I.second;
4109 if (Val && !getModule().getNamedValue(Name->getName()))
4110 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4114 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4115 GlobalDecl &Result) const {
4116 auto Res = Manglings.find(MangledName);
4117 if (Res == Manglings.end())
4119 Result = Res->getValue();
4123 /// Emits metadata nodes associating all the global values in the
4124 /// current module with the Decls they came from. This is useful for
4125 /// projects using IR gen as a subroutine.
4127 /// Since there's currently no way to associate an MDNode directly
4128 /// with an llvm::GlobalValue, we create a global named metadata
4129 /// with the name 'clang.global.decl.ptrs'.
4130 void CodeGenModule::EmitDeclMetadata() {
4131 llvm::NamedMDNode *GlobalMetadata = nullptr;
4133 for (auto &I : MangledDeclNames) {
4134 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4135 // Some mangled names don't necessarily have an associated GlobalValue
4136 // in this module, e.g. if we mangled it for DebugInfo.
4138 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4142 /// Emits metadata nodes for all the local variables in the current
4144 void CodeGenFunction::EmitDeclMetadata() {
4145 if (LocalDeclMap.empty()) return;
4147 llvm::LLVMContext &Context = getLLVMContext();
4149 // Find the unique metadata ID for this name.
4150 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4152 llvm::NamedMDNode *GlobalMetadata = nullptr;
4154 for (auto &I : LocalDeclMap) {
4155 const Decl *D = I.first;
4156 llvm::Value *Addr = I.second.getPointer();
4157 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4158 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4159 Alloca->setMetadata(
4160 DeclPtrKind, llvm::MDNode::get(
4161 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4162 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4163 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4164 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4169 void CodeGenModule::EmitVersionIdentMetadata() {
4170 llvm::NamedMDNode *IdentMetadata =
4171 TheModule.getOrInsertNamedMetadata("llvm.ident");
4172 std::string Version = getClangFullVersion();
4173 llvm::LLVMContext &Ctx = TheModule.getContext();
4175 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4176 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4179 void CodeGenModule::EmitTargetMetadata() {
4180 // Warning, new MangledDeclNames may be appended within this loop.
4181 // We rely on MapVector insertions adding new elements to the end
4182 // of the container.
4183 // FIXME: Move this loop into the one target that needs it, and only
4184 // loop over those declarations for which we couldn't emit the target
4185 // metadata when we emitted the declaration.
4186 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4187 auto Val = *(MangledDeclNames.begin() + I);
4188 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4189 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4190 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4194 void CodeGenModule::EmitCoverageFile() {
4195 if (getCodeGenOpts().CoverageDataFile.empty() &&
4196 getCodeGenOpts().CoverageNotesFile.empty())
4199 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4203 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4204 llvm::LLVMContext &Ctx = TheModule.getContext();
4205 auto *CoverageDataFile =
4206 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4207 auto *CoverageNotesFile =
4208 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4209 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4210 llvm::MDNode *CU = CUNode->getOperand(i);
4211 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4212 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4216 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4217 // Sema has checked that all uuid strings are of the form
4218 // "12345678-1234-1234-1234-1234567890ab".
4219 assert(Uuid.size() == 36);
4220 for (unsigned i = 0; i < 36; ++i) {
4221 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4222 else assert(isHexDigit(Uuid[i]));
4225 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4226 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4228 llvm::Constant *Field3[8];
4229 for (unsigned Idx = 0; Idx < 8; ++Idx)
4230 Field3[Idx] = llvm::ConstantInt::get(
4231 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4233 llvm::Constant *Fields[4] = {
4234 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4235 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4236 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4237 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4240 return llvm::ConstantStruct::getAnon(Fields);
4243 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4245 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4246 // FIXME: should we even be calling this method if RTTI is disabled
4247 // and it's not for EH?
4248 if (!ForEH && !getLangOpts().RTTI)
4249 return llvm::Constant::getNullValue(Int8PtrTy);
4251 if (ForEH && Ty->isObjCObjectPointerType() &&
4252 LangOpts.ObjCRuntime.isGNUFamily())
4253 return ObjCRuntime->GetEHType(Ty);
4255 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4258 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4259 for (auto RefExpr : D->varlists()) {
4260 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4262 VD->getAnyInitializer() &&
4263 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4266 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4267 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4268 VD, Addr, RefExpr->getLocStart(), PerformInit))
4269 CXXGlobalInits.push_back(InitFunction);
4273 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4274 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4278 if (isExternallyVisible(T->getLinkage())) {
4279 std::string OutName;
4280 llvm::raw_string_ostream Out(OutName);
4281 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4283 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4285 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4286 llvm::ArrayRef<llvm::Metadata *>());
4292 /// Returns whether this module needs the "all-vtables" type identifier.
4293 bool CodeGenModule::NeedAllVtablesTypeId() const {
4294 // Returns true if at least one of vtable-based CFI checkers is enabled and
4295 // is not in the trapping mode.
4296 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4297 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4298 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4299 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4300 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4301 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4302 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4303 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4306 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4308 const CXXRecordDecl *RD) {
4309 llvm::Metadata *MD =
4310 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4311 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4313 if (CodeGenOpts.SanitizeCfiCrossDso)
4314 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4315 VTable->addTypeMetadata(Offset.getQuantity(),
4316 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4318 if (NeedAllVtablesTypeId()) {
4319 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4320 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4324 // Fills in the supplied string map with the set of target features for the
4325 // passed in function.
4326 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4327 const FunctionDecl *FD) {
4328 StringRef TargetCPU = Target.getTargetOpts().CPU;
4329 if (const auto *TD = FD->getAttr<TargetAttr>()) {
4330 // If we have a TargetAttr build up the feature map based on that.
4331 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4333 // Make a copy of the features as passed on the command line into the
4334 // beginning of the additional features from the function to override.
4335 ParsedAttr.first.insert(ParsedAttr.first.begin(),
4336 Target.getTargetOpts().FeaturesAsWritten.begin(),
4337 Target.getTargetOpts().FeaturesAsWritten.end());
4339 if (ParsedAttr.second != "")
4340 TargetCPU = ParsedAttr.second;
4342 // Now populate the feature map, first with the TargetCPU which is either
4343 // the default or a new one from the target attribute string. Then we'll use
4344 // the passed in features (FeaturesAsWritten) along with the new ones from
4346 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4348 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4349 Target.getTargetOpts().Features);
4353 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4355 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4360 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4361 CodeGenFunction &CGF) {
4362 llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
4363 auto SamplerT = getOpenCLRuntime().getSamplerType();
4364 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4365 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4366 "__translate_sampler_initializer"),