1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This coordinates the per-module state used while generating code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenModule.h"
16 #include "CGCUDARuntime.h"
19 #include "CGDebugInfo.h"
20 #include "CGObjCRuntime.h"
21 #include "CGOpenCLRuntime.h"
22 #include "CGOpenMPRuntime.h"
23 #include "CGOpenMPRuntimeNVPTX.h"
24 #include "CodeGenFunction.h"
25 #include "CodeGenPGO.h"
26 #include "CodeGenTBAA.h"
27 #include "CoverageMappingGen.h"
28 #include "TargetInfo.h"
29 #include "clang/AST/ASTContext.h"
30 #include "clang/AST/CharUnits.h"
31 #include "clang/AST/DeclCXX.h"
32 #include "clang/AST/DeclObjC.h"
33 #include "clang/AST/DeclTemplate.h"
34 #include "clang/AST/Mangle.h"
35 #include "clang/AST/RecordLayout.h"
36 #include "clang/AST/RecursiveASTVisitor.h"
37 #include "clang/Basic/Builtins.h"
38 #include "clang/Basic/CharInfo.h"
39 #include "clang/Basic/Diagnostic.h"
40 #include "clang/Basic/Module.h"
41 #include "clang/Basic/SourceManager.h"
42 #include "clang/Basic/TargetInfo.h"
43 #include "clang/Basic/Version.h"
44 #include "clang/CodeGen/ConstantInitBuilder.h"
45 #include "clang/Frontend/CodeGenOptions.h"
46 #include "clang/Sema/SemaDiagnostic.h"
47 #include "llvm/ADT/Triple.h"
48 #include "llvm/Analysis/TargetLibraryInfo.h"
49 #include "llvm/IR/CallSite.h"
50 #include "llvm/IR/CallingConv.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/Intrinsics.h"
53 #include "llvm/IR/LLVMContext.h"
54 #include "llvm/IR/Module.h"
55 #include "llvm/ProfileData/InstrProfReader.h"
56 #include "llvm/Support/ConvertUTF.h"
57 #include "llvm/Support/ErrorHandling.h"
58 #include "llvm/Support/MD5.h"
60 using namespace clang;
61 using namespace CodeGen;
63 static const char AnnotationSection[] = "llvm.metadata";
65 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
66 switch (CGM.getTarget().getCXXABI().getKind()) {
67 case TargetCXXABI::GenericAArch64:
68 case TargetCXXABI::GenericARM:
69 case TargetCXXABI::iOS:
70 case TargetCXXABI::iOS64:
71 case TargetCXXABI::WatchOS:
72 case TargetCXXABI::GenericMIPS:
73 case TargetCXXABI::GenericItanium:
74 case TargetCXXABI::WebAssembly:
75 return CreateItaniumCXXABI(CGM);
76 case TargetCXXABI::Microsoft:
77 return CreateMicrosoftCXXABI(CGM);
80 llvm_unreachable("invalid C++ ABI kind");
83 CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
84 const PreprocessorOptions &PPO,
85 const CodeGenOptions &CGO, llvm::Module &M,
86 DiagnosticsEngine &diags,
87 CoverageSourceInfo *CoverageInfo)
88 : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
89 PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
90 Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
91 VMContext(M.getContext()), Types(*this), VTables(*this),
92 SanitizerMD(new SanitizerMetadata(*this)) {
94 // Initialize the type cache.
95 llvm::LLVMContext &LLVMContext = M.getContext();
96 VoidTy = llvm::Type::getVoidTy(LLVMContext);
97 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
98 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
99 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
101 FloatTy = llvm::Type::getFloatTy(LLVMContext);
102 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
103 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
104 PointerAlignInBytes =
105 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
107 C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
109 C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
110 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
111 IntPtrTy = llvm::IntegerType::get(LLVMContext,
112 C.getTargetInfo().getMaxPointerWidth());
113 Int8PtrTy = Int8Ty->getPointerTo(0);
114 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
115 AllocaInt8PtrTy = Int8Ty->getPointerTo(
116 M.getDataLayout().getAllocaAddrSpace());
117 ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
119 RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
120 BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
125 createOpenCLRuntime();
127 createOpenMPRuntime();
131 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
132 if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
133 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
134 TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
135 getCXXABI().getMangleContext()));
137 // If debug info or coverage generation is enabled, create the CGDebugInfo
139 if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
140 CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
141 DebugInfo.reset(new CGDebugInfo(*this));
143 Block.GlobalUniqueCount = 0;
145 if (C.getLangOpts().ObjC1)
146 ObjCData.reset(new ObjCEntrypoints());
148 if (CodeGenOpts.hasProfileClangUse()) {
149 auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
150 CodeGenOpts.ProfileInstrumentUsePath);
151 if (auto E = ReaderOrErr.takeError()) {
152 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
153 "Could not read profile %0: %1");
154 llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
155 getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
159 PGOReader = std::move(ReaderOrErr.get());
162 // If coverage mapping generation is enabled, create the
163 // CoverageMappingModuleGen object.
164 if (CodeGenOpts.CoverageMapping)
165 CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
168 CodeGenModule::~CodeGenModule() {}
170 void CodeGenModule::createObjCRuntime() {
171 // This is just isGNUFamily(), but we want to force implementors of
172 // new ABIs to decide how best to do this.
173 switch (LangOpts.ObjCRuntime.getKind()) {
174 case ObjCRuntime::GNUstep:
175 case ObjCRuntime::GCC:
176 case ObjCRuntime::ObjFW:
177 ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
180 case ObjCRuntime::FragileMacOSX:
181 case ObjCRuntime::MacOSX:
182 case ObjCRuntime::iOS:
183 case ObjCRuntime::WatchOS:
184 ObjCRuntime.reset(CreateMacObjCRuntime(*this));
187 llvm_unreachable("bad runtime kind");
190 void CodeGenModule::createOpenCLRuntime() {
191 OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
194 void CodeGenModule::createOpenMPRuntime() {
195 // Select a specialized code generation class based on the target, if any.
196 // If it does not exist use the default implementation.
197 switch (getTriple().getArch()) {
198 case llvm::Triple::nvptx:
199 case llvm::Triple::nvptx64:
200 assert(getLangOpts().OpenMPIsDevice &&
201 "OpenMP NVPTX is only prepared to deal with device code.");
202 OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
205 OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
210 void CodeGenModule::createCUDARuntime() {
211 CUDARuntime.reset(CreateNVCUDARuntime(*this));
214 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
215 Replacements[Name] = C;
218 void CodeGenModule::applyReplacements() {
219 for (auto &I : Replacements) {
220 StringRef MangledName = I.first();
221 llvm::Constant *Replacement = I.second;
222 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
225 auto *OldF = cast<llvm::Function>(Entry);
226 auto *NewF = dyn_cast<llvm::Function>(Replacement);
228 if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
229 NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
231 auto *CE = cast<llvm::ConstantExpr>(Replacement);
232 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
233 CE->getOpcode() == llvm::Instruction::GetElementPtr);
234 NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
238 // Replace old with new, but keep the old order.
239 OldF->replaceAllUsesWith(Replacement);
241 NewF->removeFromParent();
242 OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
245 OldF->eraseFromParent();
249 void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
250 GlobalValReplacements.push_back(std::make_pair(GV, C));
253 void CodeGenModule::applyGlobalValReplacements() {
254 for (auto &I : GlobalValReplacements) {
255 llvm::GlobalValue *GV = I.first;
256 llvm::Constant *C = I.second;
258 GV->replaceAllUsesWith(C);
259 GV->eraseFromParent();
263 // This is only used in aliases that we created and we know they have a
265 static const llvm::GlobalObject *getAliasedGlobal(
266 const llvm::GlobalIndirectSymbol &GIS) {
267 llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
268 const llvm::Constant *C = &GIS;
270 C = C->stripPointerCasts();
271 if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
273 // stripPointerCasts will not walk over weak aliases.
274 auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
277 if (!Visited.insert(GIS2).second)
279 C = GIS2->getIndirectSymbol();
283 void CodeGenModule::checkAliases() {
284 // Check if the constructed aliases are well formed. It is really unfortunate
285 // that we have to do this in CodeGen, but we only construct mangled names
286 // and aliases during codegen.
288 DiagnosticsEngine &Diags = getDiags();
289 for (const GlobalDecl &GD : Aliases) {
290 const auto *D = cast<ValueDecl>(GD.getDecl());
291 SourceLocation Location;
292 bool IsIFunc = D->hasAttr<IFuncAttr>();
293 if (const Attr *A = D->getDefiningAttr())
294 Location = A->getLocation();
296 llvm_unreachable("Not an alias or ifunc?");
297 StringRef MangledName = getMangledName(GD);
298 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
299 auto *Alias = cast<llvm::GlobalIndirectSymbol>(Entry);
300 const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
303 Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
304 } else if (GV->isDeclaration()) {
306 Diags.Report(Location, diag::err_alias_to_undefined)
307 << IsIFunc << IsIFunc;
308 } else if (IsIFunc) {
309 // Check resolver function type.
310 llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
311 GV->getType()->getPointerElementType());
313 if (!FTy->getReturnType()->isPointerTy())
314 Diags.Report(Location, diag::err_ifunc_resolver_return);
315 if (FTy->getNumParams())
316 Diags.Report(Location, diag::err_ifunc_resolver_params);
319 llvm::Constant *Aliasee = Alias->getIndirectSymbol();
320 llvm::GlobalValue *AliaseeGV;
321 if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
322 AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
324 AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
326 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
327 StringRef AliasSection = SA->getName();
328 if (AliasSection != AliaseeGV->getSection())
329 Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
330 << AliasSection << IsIFunc << IsIFunc;
333 // We have to handle alias to weak aliases in here. LLVM itself disallows
334 // this since the object semantics would not match the IL one. For
335 // compatibility with gcc we implement it by just pointing the alias
336 // to its aliasee's aliasee. We also warn, since the user is probably
337 // expecting the link to be weak.
338 if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
339 if (GA->isInterposable()) {
340 Diags.Report(Location, diag::warn_alias_to_weak_alias)
341 << GV->getName() << GA->getName() << IsIFunc;
342 Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
343 GA->getIndirectSymbol(), Alias->getType());
344 Alias->setIndirectSymbol(Aliasee);
351 for (const GlobalDecl &GD : Aliases) {
352 StringRef MangledName = getMangledName(GD);
353 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
354 auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
355 Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
356 Alias->eraseFromParent();
360 void CodeGenModule::clear() {
361 DeferredDeclsToEmit.clear();
363 OpenMPRuntime->clear();
366 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
367 StringRef MainFile) {
368 if (!hasDiagnostics())
370 if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
371 if (MainFile.empty())
372 MainFile = "<stdin>";
373 Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
376 Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
379 Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
383 void CodeGenModule::Release() {
385 applyGlobalValReplacements();
388 EmitCXXGlobalInitFunc();
389 EmitCXXGlobalDtorFunc();
390 EmitCXXThreadLocalInitFunc();
392 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
393 AddGlobalCtor(ObjCInitFunction);
394 if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
396 if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
397 AddGlobalCtor(CudaCtorFunction);
398 if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
399 AddGlobalDtor(CudaDtorFunction);
402 if (llvm::Function *OpenMPRegistrationFunction =
403 OpenMPRuntime->emitRegistrationFunction())
404 AddGlobalCtor(OpenMPRegistrationFunction, 0);
406 getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
407 if (PGOStats.hasDiagnostics())
408 PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
410 EmitCtorList(GlobalCtors, "llvm.global_ctors");
411 EmitCtorList(GlobalDtors, "llvm.global_dtors");
412 EmitGlobalAnnotations();
413 EmitStaticExternCAliases();
414 EmitDeferredUnusedCoverageMappings();
416 CoverageMapping->emit();
417 if (CodeGenOpts.SanitizeCfiCrossDso) {
418 CodeGenFunction(*this).EmitCfiCheckFail();
419 CodeGenFunction(*this).EmitCfiCheckStub();
421 emitAtAvailableLinkGuard();
426 if (CodeGenOpts.Autolink &&
427 (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
428 EmitModuleLinkOptions();
431 // Record mregparm value now so it is visible through rest of codegen.
432 if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
433 getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
434 CodeGenOpts.NumRegisterParameters);
436 if (CodeGenOpts.DwarfVersion) {
437 // We actually want the latest version when there are conflicts.
438 // We can change from Warning to Latest if such mode is supported.
439 getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
440 CodeGenOpts.DwarfVersion);
442 if (CodeGenOpts.EmitCodeView) {
443 // Indicate that we want CodeView in the metadata.
444 getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
446 if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
447 // We don't support LTO with 2 with different StrictVTablePointers
448 // FIXME: we could support it by stripping all the information introduced
449 // by StrictVTablePointers.
451 getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
453 llvm::Metadata *Ops[2] = {
454 llvm::MDString::get(VMContext, "StrictVTablePointers"),
455 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
456 llvm::Type::getInt32Ty(VMContext), 1))};
458 getModule().addModuleFlag(llvm::Module::Require,
459 "StrictVTablePointersRequirement",
460 llvm::MDNode::get(VMContext, Ops));
463 // We support a single version in the linked module. The LLVM
464 // parser will drop debug info with a different version number
465 // (and warn about it, too).
466 getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
467 llvm::DEBUG_METADATA_VERSION);
469 // Width of wchar_t in bytes
470 uint64_t WCharWidth =
471 Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
472 assert(LangOpts.ShortWChar ||
473 llvm::TargetLibraryInfoImpl::getTargetWCharSize(Target.getTriple()) ==
474 Target.getWCharWidth() / 8 &&
475 "LLVM wchar_t size out of sync");
477 // We need to record the widths of enums and wchar_t, so that we can generate
478 // the correct build attributes in the ARM backend. wchar_size is also used by
479 // TargetLibraryInfo.
480 getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
482 llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
483 if ( Arch == llvm::Triple::arm
484 || Arch == llvm::Triple::armeb
485 || Arch == llvm::Triple::thumb
486 || Arch == llvm::Triple::thumbeb) {
487 // The minimum width of an enum in bytes
488 uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
489 getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
492 if (CodeGenOpts.SanitizeCfiCrossDso) {
493 // Indicate that we want cross-DSO control flow integrity checks.
494 getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
497 if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
498 // Indicate whether __nvvm_reflect should be configured to flush denormal
499 // floating point values to 0. (This corresponds to its "__CUDA_FTZ"
501 getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
502 LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
505 if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
506 assert(PLevel < 3 && "Invalid PIC Level");
507 getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
508 if (Context.getLangOpts().PIE)
509 getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
512 SimplifyPersonality();
514 if (getCodeGenOpts().EmitDeclMetadata)
517 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
521 DebugInfo->finalize();
523 EmitVersionIdentMetadata();
525 EmitTargetMetadata();
528 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
529 // Make sure that this type is translated.
530 Types.UpdateCompletedType(TD);
533 void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
534 // Make sure that this type is translated.
535 Types.RefreshTypeCacheForClass(RD);
538 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
541 return TBAA->getTBAAInfo(QTy);
544 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
547 return TBAA->getTBAAInfoForVTablePtr();
550 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
553 return TBAA->getTBAAStructInfo(QTy);
556 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
557 llvm::MDNode *AccessN,
561 return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
564 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
565 /// and struct-path aware TBAA, the tag has the same format:
566 /// base type, access type and offset.
567 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
568 void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
569 llvm::MDNode *TBAAInfo,
570 bool ConvertTypeToTag) {
571 if (ConvertTypeToTag && TBAA)
572 Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
573 TBAA->getTBAAScalarTagInfo(TBAAInfo));
575 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
578 void CodeGenModule::DecorateInstructionWithInvariantGroup(
579 llvm::Instruction *I, const CXXRecordDecl *RD) {
580 I->setMetadata(llvm::LLVMContext::MD_invariant_group,
581 llvm::MDNode::get(getLLVMContext(), {}));
584 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
585 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
586 getDiags().Report(Context.getFullLoc(loc), diagID) << message;
589 /// ErrorUnsupported - Print out an error that codegen doesn't support the
590 /// specified stmt yet.
591 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
592 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
593 "cannot compile this %0 yet");
594 std::string Msg = Type;
595 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
596 << Msg << S->getSourceRange();
599 /// ErrorUnsupported - Print out an error that codegen doesn't support the
600 /// specified decl yet.
601 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
602 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
603 "cannot compile this %0 yet");
604 std::string Msg = Type;
605 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
608 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
609 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
612 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
613 const NamedDecl *D) const {
614 // Internal definitions always have default visibility.
615 if (GV->hasLocalLinkage()) {
616 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
620 // Set visibility for definitions.
621 LinkageInfo LV = D->getLinkageAndVisibility();
622 if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
623 GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
626 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
627 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
628 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
629 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
630 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
631 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
634 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
635 CodeGenOptions::TLSModel M) {
637 case CodeGenOptions::GeneralDynamicTLSModel:
638 return llvm::GlobalVariable::GeneralDynamicTLSModel;
639 case CodeGenOptions::LocalDynamicTLSModel:
640 return llvm::GlobalVariable::LocalDynamicTLSModel;
641 case CodeGenOptions::InitialExecTLSModel:
642 return llvm::GlobalVariable::InitialExecTLSModel;
643 case CodeGenOptions::LocalExecTLSModel:
644 return llvm::GlobalVariable::LocalExecTLSModel;
646 llvm_unreachable("Invalid TLS model!");
649 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
650 assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
652 llvm::GlobalValue::ThreadLocalMode TLM;
653 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
655 // Override the TLS model if it is explicitly specified.
656 if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
657 TLM = GetLLVMTLSModel(Attr->getModel());
660 GV->setThreadLocalMode(TLM);
663 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
664 GlobalDecl CanonicalGD = GD.getCanonicalDecl();
666 // Some ABIs don't have constructor variants. Make sure that base and
667 // complete constructors get mangled the same.
668 if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
669 if (!getTarget().getCXXABI().hasConstructorVariants()) {
670 CXXCtorType OrigCtorType = GD.getCtorType();
671 assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
672 if (OrigCtorType == Ctor_Base)
673 CanonicalGD = GlobalDecl(CD, Ctor_Complete);
677 StringRef &FoundStr = MangledDeclNames[CanonicalGD];
678 if (!FoundStr.empty())
681 const auto *ND = cast<NamedDecl>(GD.getDecl());
682 SmallString<256> Buffer;
684 if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
685 llvm::raw_svector_ostream Out(Buffer);
686 if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
687 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
688 else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
689 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
691 getCXXABI().getMangleContext().mangleName(ND, Out);
694 IdentifierInfo *II = ND->getIdentifier();
695 assert(II && "Attempt to mangle unnamed decl.");
696 const auto *FD = dyn_cast<FunctionDecl>(ND);
699 FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
700 llvm::raw_svector_ostream Out(Buffer);
701 Out << "__regcall3__" << II->getName();
708 // Keep the first result in the case of a mangling collision.
709 auto Result = Manglings.insert(std::make_pair(Str, GD));
710 return FoundStr = Result.first->first();
713 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
714 const BlockDecl *BD) {
715 MangleContext &MangleCtx = getCXXABI().getMangleContext();
716 const Decl *D = GD.getDecl();
718 SmallString<256> Buffer;
719 llvm::raw_svector_ostream Out(Buffer);
721 MangleCtx.mangleGlobalBlock(BD,
722 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
723 else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
724 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
725 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
726 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
728 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
730 auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
731 return Result.first->first();
734 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
735 return getModule().getNamedValue(Name);
738 /// AddGlobalCtor - Add a function to the list that will be called before
740 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
741 llvm::Constant *AssociatedData) {
742 // FIXME: Type coercion of void()* types.
743 GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
746 /// AddGlobalDtor - Add a function to the list that will be called
747 /// when the module is unloaded.
748 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
749 // FIXME: Type coercion of void()* types.
750 GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
753 void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
754 if (Fns.empty()) return;
756 // Ctor function type is void()*.
757 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
758 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
760 // Get the type of a ctor entry, { i32, void ()*, i8* }.
761 llvm::StructType *CtorStructTy = llvm::StructType::get(
762 Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
764 // Construct the constructor and destructor arrays.
765 ConstantInitBuilder builder(*this);
766 auto ctors = builder.beginArray(CtorStructTy);
767 for (const auto &I : Fns) {
768 auto ctor = ctors.beginStruct(CtorStructTy);
769 ctor.addInt(Int32Ty, I.Priority);
770 ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
771 if (I.AssociatedData)
772 ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
774 ctor.addNullPointer(VoidPtrTy);
775 ctor.finishAndAddTo(ctors);
779 ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
781 llvm::GlobalValue::AppendingLinkage);
783 // The LTO linker doesn't seem to like it when we set an alignment
784 // on appending variables. Take it off as a workaround.
785 list->setAlignment(0);
790 llvm::GlobalValue::LinkageTypes
791 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
792 const auto *D = cast<FunctionDecl>(GD.getDecl());
794 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
796 if (isa<CXXDestructorDecl>(D) &&
797 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
799 // Destructor variants in the Microsoft C++ ABI are always internal or
800 // linkonce_odr thunks emitted on an as-needed basis.
801 return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
802 : llvm::GlobalValue::LinkOnceODRLinkage;
805 if (isa<CXXConstructorDecl>(D) &&
806 cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
807 Context.getTargetInfo().getCXXABI().isMicrosoft()) {
808 // Our approach to inheriting constructors is fundamentally different from
809 // that used by the MS ABI, so keep our inheriting constructor thunks
810 // internal rather than trying to pick an unambiguous mangling for them.
811 return llvm::GlobalValue::InternalLinkage;
814 return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
817 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
818 const auto *FD = cast<FunctionDecl>(GD.getDecl());
820 if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
821 if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
822 // Don't dllexport/import destructor thunks.
823 F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
828 if (FD->hasAttr<DLLImportAttr>())
829 F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
830 else if (FD->hasAttr<DLLExportAttr>())
831 F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
833 F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
836 llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
837 llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
838 if (!MDS) return nullptr;
840 return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
843 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
845 setNonAliasAttributes(D, F);
848 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
849 const CGFunctionInfo &Info,
851 unsigned CallingConv;
852 llvm::AttributeList PAL;
853 ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
854 F->setAttributes(PAL);
855 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
858 /// Determines whether the language options require us to model
859 /// unwind exceptions. We treat -fexceptions as mandating this
860 /// except under the fragile ObjC ABI with only ObjC exceptions
861 /// enabled. This means, for example, that C with -fexceptions
863 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
864 // If exceptions are completely disabled, obviously this is false.
865 if (!LangOpts.Exceptions) return false;
867 // If C++ exceptions are enabled, this is true.
868 if (LangOpts.CXXExceptions) return true;
870 // If ObjC exceptions are enabled, this depends on the ABI.
871 if (LangOpts.ObjCExceptions) {
872 return LangOpts.ObjCRuntime.hasUnwindExceptions();
878 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
882 if (CodeGenOpts.UnwindTables)
883 B.addAttribute(llvm::Attribute::UWTable);
885 if (!hasUnwindExceptions(LangOpts))
886 B.addAttribute(llvm::Attribute::NoUnwind);
888 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
889 B.addAttribute(llvm::Attribute::StackProtect);
890 else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
891 B.addAttribute(llvm::Attribute::StackProtectStrong);
892 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
893 B.addAttribute(llvm::Attribute::StackProtectReq);
896 // If we don't have a declaration to control inlining, the function isn't
897 // explicitly marked as alwaysinline for semantic reasons, and inlining is
898 // disabled, mark the function as noinline.
899 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
900 CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
901 B.addAttribute(llvm::Attribute::NoInline);
903 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
907 if (D->hasAttr<OptimizeNoneAttr>()) {
908 B.addAttribute(llvm::Attribute::OptimizeNone);
910 // OptimizeNone implies noinline; we should not be inlining such functions.
911 B.addAttribute(llvm::Attribute::NoInline);
912 assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
913 "OptimizeNone and AlwaysInline on same function!");
915 // We still need to handle naked functions even though optnone subsumes
916 // much of their semantics.
917 if (D->hasAttr<NakedAttr>())
918 B.addAttribute(llvm::Attribute::Naked);
920 // OptimizeNone wins over OptimizeForSize and MinSize.
921 F->removeFnAttr(llvm::Attribute::OptimizeForSize);
922 F->removeFnAttr(llvm::Attribute::MinSize);
923 } else if (D->hasAttr<NakedAttr>()) {
924 // Naked implies noinline: we should not be inlining such functions.
925 B.addAttribute(llvm::Attribute::Naked);
926 B.addAttribute(llvm::Attribute::NoInline);
927 } else if (D->hasAttr<NoDuplicateAttr>()) {
928 B.addAttribute(llvm::Attribute::NoDuplicate);
929 } else if (D->hasAttr<NoInlineAttr>()) {
930 B.addAttribute(llvm::Attribute::NoInline);
931 } else if (D->hasAttr<AlwaysInlineAttr>() &&
932 !F->hasFnAttribute(llvm::Attribute::NoInline)) {
933 // (noinline wins over always_inline, and we can't specify both in IR)
934 B.addAttribute(llvm::Attribute::AlwaysInline);
935 } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
936 // If we're not inlining, then force everything that isn't always_inline to
937 // carry an explicit noinline attribute.
938 if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
939 B.addAttribute(llvm::Attribute::NoInline);
941 // Otherwise, propagate the inline hint attribute and potentially use its
942 // absence to mark things as noinline.
943 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
944 if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
945 return Redecl->isInlineSpecified();
947 B.addAttribute(llvm::Attribute::InlineHint);
948 } else if (CodeGenOpts.getInlining() ==
949 CodeGenOptions::OnlyHintInlining &&
951 !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
952 B.addAttribute(llvm::Attribute::NoInline);
957 // Add other optimization related attributes if we are optimizing this
959 if (!D->hasAttr<OptimizeNoneAttr>()) {
960 if (D->hasAttr<ColdAttr>()) {
961 B.addAttribute(llvm::Attribute::OptimizeForSize);
962 B.addAttribute(llvm::Attribute::Cold);
965 if (D->hasAttr<MinSizeAttr>())
966 B.addAttribute(llvm::Attribute::MinSize);
969 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
971 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
973 F->setAlignment(alignment);
975 // Some C++ ABIs require 2-byte alignment for member functions, in order to
976 // reserve a bit for differentiating between virtual and non-virtual member
977 // functions. If the current target's C++ ABI requires this and this is a
978 // member function, set its alignment accordingly.
979 if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
980 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
984 // In the cross-dso CFI mode, we want !type attributes on definitions only.
985 if (CodeGenOpts.SanitizeCfiCrossDso)
986 if (auto *FD = dyn_cast<FunctionDecl>(D))
987 CreateFunctionTypeMetadata(FD, F);
990 void CodeGenModule::SetCommonAttributes(const Decl *D,
991 llvm::GlobalValue *GV) {
992 if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
993 setGlobalVisibility(GV, ND);
995 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
997 if (D && D->hasAttr<UsedAttr>())
1001 void CodeGenModule::setAliasAttributes(const Decl *D,
1002 llvm::GlobalValue *GV) {
1003 SetCommonAttributes(D, GV);
1005 // Process the dllexport attribute based on whether the original definition
1006 // (not necessarily the aliasee) was exported.
1007 if (D->hasAttr<DLLExportAttr>())
1008 GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1011 void CodeGenModule::setNonAliasAttributes(const Decl *D,
1012 llvm::GlobalObject *GO) {
1013 SetCommonAttributes(D, GO);
1016 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
1017 GO->setSection(SA->getName());
1019 getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1022 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1024 const CGFunctionInfo &FI) {
1025 SetLLVMFunctionAttributes(D, FI, F);
1026 SetLLVMFunctionAttributesForDefinition(D, F);
1028 F->setLinkage(llvm::Function::InternalLinkage);
1030 setNonAliasAttributes(D, F);
1033 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
1034 const NamedDecl *ND) {
1035 // Set linkage and visibility in case we never see a definition.
1036 LinkageInfo LV = ND->getLinkageAndVisibility();
1037 if (LV.getLinkage() != ExternalLinkage) {
1038 // Don't set internal linkage on declarations.
1040 if (ND->hasAttr<DLLImportAttr>()) {
1041 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1042 GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1043 } else if (ND->hasAttr<DLLExportAttr>()) {
1044 GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
1045 } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
1046 // "extern_weak" is overloaded in LLVM; we probably should have
1047 // separate linkage types for this.
1048 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
1051 // Set visibility on a declaration only if it's explicit.
1052 if (LV.isVisibilityExplicit())
1053 GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
1057 void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
1058 llvm::Function *F) {
1059 // Only if we are checking indirect calls.
1060 if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
1063 // Non-static class methods are handled via vtable pointer checks elsewhere.
1064 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
1067 // Additionally, if building with cross-DSO support...
1068 if (CodeGenOpts.SanitizeCfiCrossDso) {
1069 // Skip available_externally functions. They won't be codegen'ed in the
1070 // current module anyway.
1071 if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
1075 llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1076 F->addTypeMetadata(0, MD);
1078 // Emit a hash-based bit set entry for cross-DSO calls.
1079 if (CodeGenOpts.SanitizeCfiCrossDso)
1080 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1081 F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
1084 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
1085 bool IsIncompleteFunction,
1087 if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
1088 // If this is an intrinsic function, set the function's attributes
1089 // to the intrinsic's attributes.
1090 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
1094 const auto *FD = cast<FunctionDecl>(GD.getDecl());
1096 if (!IsIncompleteFunction)
1097 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1099 // Add the Returned attribute for "this", except for iOS 5 and earlier
1100 // where substantial code, including the libstdc++ dylib, was compiled with
1101 // GCC and does not actually return "this".
1102 if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
1103 !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1104 assert(!F->arg_empty() &&
1105 F->arg_begin()->getType()
1106 ->canLosslesslyBitCastTo(F->getReturnType()) &&
1107 "unexpected this return");
1108 F->addAttribute(1, llvm::Attribute::Returned);
1111 // Only a few attributes are set on declarations; these may later be
1112 // overridden by a definition.
1114 setLinkageAndVisibilityForGV(F, FD);
1116 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1117 F->setSection(SA->getName());
1119 if (FD->isReplaceableGlobalAllocationFunction()) {
1120 // A replaceable global allocation function does not act like a builtin by
1121 // default, only if it is invoked by a new-expression or delete-expression.
1122 F->addAttribute(llvm::AttributeList::FunctionIndex,
1123 llvm::Attribute::NoBuiltin);
1125 // A sane operator new returns a non-aliasing pointer.
1126 // FIXME: Also add NonNull attribute to the return value
1127 // for the non-nothrow forms?
1128 auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1129 if (getCodeGenOpts().AssumeSaneOperatorNew &&
1130 (Kind == OO_New || Kind == OO_Array_New))
1131 F->addAttribute(llvm::AttributeList::ReturnIndex,
1132 llvm::Attribute::NoAlias);
1135 if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1136 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1137 else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1138 if (MD->isVirtual())
1139 F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1141 // Don't emit entries for function declarations in the cross-DSO mode. This
1142 // is handled with better precision by the receiving DSO.
1143 if (!CodeGenOpts.SanitizeCfiCrossDso)
1144 CreateFunctionTypeMetadata(FD, F);
1147 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1148 assert(!GV->isDeclaration() &&
1149 "Only globals with definition can force usage.");
1150 LLVMUsed.emplace_back(GV);
1153 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
1154 assert(!GV->isDeclaration() &&
1155 "Only globals with definition can force usage.");
1156 LLVMCompilerUsed.emplace_back(GV);
1159 static void emitUsed(CodeGenModule &CGM, StringRef Name,
1160 std::vector<llvm::WeakTrackingVH> &List) {
1161 // Don't create llvm.used if there is no need.
1165 // Convert List to what ConstantArray needs.
1166 SmallVector<llvm::Constant*, 8> UsedArray;
1167 UsedArray.resize(List.size());
1168 for (unsigned i = 0, e = List.size(); i != e; ++i) {
1170 llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
1171 cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1174 if (UsedArray.empty())
1176 llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1178 auto *GV = new llvm::GlobalVariable(
1179 CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
1180 llvm::ConstantArray::get(ATy, UsedArray), Name);
1182 GV->setSection("llvm.metadata");
1185 void CodeGenModule::emitLLVMUsed() {
1186 emitUsed(*this, "llvm.used", LLVMUsed);
1187 emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
1190 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
1191 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1192 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1195 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1196 llvm::SmallString<32> Opt;
1197 getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
1198 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1199 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1202 void CodeGenModule::AddDependentLib(StringRef Lib) {
1203 llvm::SmallString<24> Opt;
1204 getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
1205 auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1206 LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1209 /// \brief Add link options implied by the given module, including modules
1210 /// it depends on, using a postorder walk.
1211 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
1212 SmallVectorImpl<llvm::Metadata *> &Metadata,
1213 llvm::SmallPtrSet<Module *, 16> &Visited) {
1214 // Import this module's parent.
1215 if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1216 addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1219 // Import this module's dependencies.
1220 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
1221 if (Visited.insert(Mod->Imports[I - 1]).second)
1222 addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1225 // Add linker options to link against the libraries/frameworks
1226 // described by this module.
1227 llvm::LLVMContext &Context = CGM.getLLVMContext();
1228 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1229 // Link against a framework. Frameworks are currently Darwin only, so we
1230 // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1231 if (Mod->LinkLibraries[I-1].IsFramework) {
1232 llvm::Metadata *Args[2] = {
1233 llvm::MDString::get(Context, "-framework"),
1234 llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1236 Metadata.push_back(llvm::MDNode::get(Context, Args));
1240 // Link against a library.
1241 llvm::SmallString<24> Opt;
1242 CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1243 Mod->LinkLibraries[I-1].Library, Opt);
1244 auto *OptString = llvm::MDString::get(Context, Opt);
1245 Metadata.push_back(llvm::MDNode::get(Context, OptString));
1249 void CodeGenModule::EmitModuleLinkOptions() {
1250 // Collect the set of all of the modules we want to visit to emit link
1251 // options, which is essentially the imported modules and all of their
1252 // non-explicit child modules.
1253 llvm::SetVector<clang::Module *> LinkModules;
1254 llvm::SmallPtrSet<clang::Module *, 16> Visited;
1255 SmallVector<clang::Module *, 16> Stack;
1257 // Seed the stack with imported modules.
1258 for (Module *M : ImportedModules) {
1259 // Do not add any link flags when an implementation TU of a module imports
1260 // a header of that same module.
1261 if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1262 !getLangOpts().isCompilingModule())
1264 if (Visited.insert(M).second)
1268 // Find all of the modules to import, making a little effort to prune
1269 // non-leaf modules.
1270 while (!Stack.empty()) {
1271 clang::Module *Mod = Stack.pop_back_val();
1273 bool AnyChildren = false;
1275 // Visit the submodules of this module.
1276 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1277 SubEnd = Mod->submodule_end();
1278 Sub != SubEnd; ++Sub) {
1279 // Skip explicit children; they need to be explicitly imported to be
1281 if ((*Sub)->IsExplicit)
1284 if (Visited.insert(*Sub).second) {
1285 Stack.push_back(*Sub);
1290 // We didn't find any children, so add this module to the list of
1291 // modules to link against.
1293 LinkModules.insert(Mod);
1297 // Add link options for all of the imported modules in reverse topological
1298 // order. We don't do anything to try to order import link flags with respect
1299 // to linker options inserted by things like #pragma comment().
1300 SmallVector<llvm::Metadata *, 16> MetadataArgs;
1302 for (Module *M : LinkModules)
1303 if (Visited.insert(M).second)
1304 addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1305 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1306 LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1308 // Add the linker options metadata flag.
1309 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1310 llvm::MDNode::get(getLLVMContext(),
1311 LinkerOptionsMetadata));
1314 void CodeGenModule::EmitDeferred() {
1315 // Emit code for any potentially referenced deferred decls. Since a
1316 // previously unused static decl may become used during the generation of code
1317 // for a static function, iterate until no changes are made.
1319 if (!DeferredVTables.empty()) {
1320 EmitDeferredVTables();
1322 // Emitting a vtable doesn't directly cause more vtables to
1323 // become deferred, although it can cause functions to be
1324 // emitted that then need those vtables.
1325 assert(DeferredVTables.empty());
1328 // Stop if we're out of both deferred vtables and deferred declarations.
1329 if (DeferredDeclsToEmit.empty())
1332 // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1333 // work, it will not interfere with this.
1334 std::vector<GlobalDecl> CurDeclsToEmit;
1335 CurDeclsToEmit.swap(DeferredDeclsToEmit);
1337 for (GlobalDecl &D : CurDeclsToEmit) {
1338 // We should call GetAddrOfGlobal with IsForDefinition set to true in order
1339 // to get GlobalValue with exactly the type we need, not something that
1340 // might had been created for another decl with the same mangled name but
1342 llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
1343 GetAddrOfGlobal(D, ForDefinition));
1345 // In case of different address spaces, we may still get a cast, even with
1346 // IsForDefinition equal to true. Query mangled names table to get
1349 GV = GetGlobalValue(getMangledName(D));
1351 // Make sure GetGlobalValue returned non-null.
1354 // Check to see if we've already emitted this. This is necessary
1355 // for a couple of reasons: first, decls can end up in the
1356 // deferred-decls queue multiple times, and second, decls can end
1357 // up with definitions in unusual ways (e.g. by an extern inline
1358 // function acquiring a strong function redefinition). Just
1359 // ignore these cases.
1360 if (!GV->isDeclaration())
1363 // Otherwise, emit the definition and move on to the next one.
1364 EmitGlobalDefinition(D, GV);
1366 // If we found out that we need to emit more decls, do that recursively.
1367 // This has the advantage that the decls are emitted in a DFS and related
1368 // ones are close together, which is convenient for testing.
1369 if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1371 assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1376 void CodeGenModule::EmitGlobalAnnotations() {
1377 if (Annotations.empty())
1380 // Create a new global variable for the ConstantStruct in the Module.
1381 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1382 Annotations[0]->getType(), Annotations.size()), Annotations);
1383 auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1384 llvm::GlobalValue::AppendingLinkage,
1385 Array, "llvm.global.annotations");
1386 gv->setSection(AnnotationSection);
1389 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1390 llvm::Constant *&AStr = AnnotationStrings[Str];
1394 // Not found yet, create a new global.
1395 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1397 new llvm::GlobalVariable(getModule(), s->getType(), true,
1398 llvm::GlobalValue::PrivateLinkage, s, ".str");
1399 gv->setSection(AnnotationSection);
1400 gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1405 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1406 SourceManager &SM = getContext().getSourceManager();
1407 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1409 return EmitAnnotationString(PLoc.getFilename());
1410 return EmitAnnotationString(SM.getBufferName(Loc));
1413 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1414 SourceManager &SM = getContext().getSourceManager();
1415 PresumedLoc PLoc = SM.getPresumedLoc(L);
1416 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1417 SM.getExpansionLineNumber(L);
1418 return llvm::ConstantInt::get(Int32Ty, LineNo);
1421 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1422 const AnnotateAttr *AA,
1424 // Get the globals for file name, annotation, and the line number.
1425 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1426 *UnitGV = EmitAnnotationUnit(L),
1427 *LineNoCst = EmitAnnotationLineNo(L);
1429 // Create the ConstantStruct for the global annotation.
1430 llvm::Constant *Fields[4] = {
1431 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1432 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1433 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1436 return llvm::ConstantStruct::getAnon(Fields);
1439 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1440 llvm::GlobalValue *GV) {
1441 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1442 // Get the struct elements for these annotations.
1443 for (const auto *I : D->specific_attrs<AnnotateAttr>())
1444 Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1447 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1448 SourceLocation Loc) const {
1449 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1450 // Blacklist by function name.
1451 if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1453 // Blacklist by location.
1455 return SanitizerBL.isBlacklistedLocation(Loc);
1456 // If location is unknown, this may be a compiler-generated function. Assume
1457 // it's located in the main file.
1458 auto &SM = Context.getSourceManager();
1459 if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1460 return SanitizerBL.isBlacklistedFile(MainFile->getName());
1465 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1466 SourceLocation Loc, QualType Ty,
1467 StringRef Category) const {
1468 // For now globals can be blacklisted only in ASan and KASan.
1469 if (!LangOpts.Sanitize.hasOneOf(
1470 SanitizerKind::Address | SanitizerKind::KernelAddress))
1472 const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1473 if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1475 if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1477 // Check global type.
1479 // Drill down the array types: if global variable of a fixed type is
1480 // blacklisted, we also don't instrument arrays of them.
1481 while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1482 Ty = AT->getElementType();
1483 Ty = Ty.getCanonicalType().getUnqualifiedType();
1484 // We allow to blacklist only record types (classes, structs etc.)
1485 if (Ty->isRecordType()) {
1486 std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1487 if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1494 bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
1495 StringRef Category) const {
1496 if (!LangOpts.XRayInstrument)
1498 const auto &XRayFilter = getContext().getXRayFilter();
1499 using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
1500 auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
1502 Attr = XRayFilter.shouldImbueLocation(Loc, Category);
1503 if (Attr == ImbueAttr::NONE)
1504 Attr = XRayFilter.shouldImbueFunction(Fn->getName());
1506 case ImbueAttr::NONE:
1508 case ImbueAttr::ALWAYS:
1509 Fn->addFnAttr("function-instrument", "xray-always");
1511 case ImbueAttr::NEVER:
1512 Fn->addFnAttr("function-instrument", "xray-never");
1518 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1519 // Never defer when EmitAllDecls is specified.
1520 if (LangOpts.EmitAllDecls)
1523 return getContext().DeclMustBeEmitted(Global);
1526 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1527 if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1528 if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1529 // Implicit template instantiations may change linkage if they are later
1530 // explicitly instantiated, so they should not be emitted eagerly.
1532 if (const auto *VD = dyn_cast<VarDecl>(Global))
1533 if (Context.getInlineVariableDefinitionKind(VD) ==
1534 ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1535 // A definition of an inline constexpr static data member may change
1536 // linkage later if it's redeclared outside the class.
1538 // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1539 // codegen for global variables, because they may be marked as threadprivate.
1540 if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1541 getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1547 ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
1548 const CXXUuidofExpr* E) {
1549 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1551 StringRef Uuid = E->getUuidStr();
1552 std::string Name = "_GUID_" + Uuid.lower();
1553 std::replace(Name.begin(), Name.end(), '-', '_');
1555 // The UUID descriptor should be pointer aligned.
1556 CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
1558 // Look for an existing global.
1559 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1560 return ConstantAddress(GV, Alignment);
1562 llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1563 assert(Init && "failed to initialize as constant");
1565 auto *GV = new llvm::GlobalVariable(
1566 getModule(), Init->getType(),
1567 /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1568 if (supportsCOMDAT())
1569 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1570 return ConstantAddress(GV, Alignment);
1573 ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1574 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1575 assert(AA && "No alias?");
1577 CharUnits Alignment = getContext().getDeclAlign(VD);
1578 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1580 // See if there is already something with the target's name in the module.
1581 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1583 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1584 auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1585 return ConstantAddress(Ptr, Alignment);
1588 llvm::Constant *Aliasee;
1589 if (isa<llvm::FunctionType>(DeclTy))
1590 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1591 GlobalDecl(cast<FunctionDecl>(VD)),
1592 /*ForVTable=*/false);
1594 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1595 llvm::PointerType::getUnqual(DeclTy),
1598 auto *F = cast<llvm::GlobalValue>(Aliasee);
1599 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1600 WeakRefReferences.insert(F);
1602 return ConstantAddress(Aliasee, Alignment);
1605 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1606 const auto *Global = cast<ValueDecl>(GD.getDecl());
1608 // Weak references don't produce any output by themselves.
1609 if (Global->hasAttr<WeakRefAttr>())
1612 // If this is an alias definition (which otherwise looks like a declaration)
1614 if (Global->hasAttr<AliasAttr>())
1615 return EmitAliasDefinition(GD);
1617 // IFunc like an alias whose value is resolved at runtime by calling resolver.
1618 if (Global->hasAttr<IFuncAttr>())
1619 return emitIFuncDefinition(GD);
1621 // If this is CUDA, be selective about which declarations we emit.
1622 if (LangOpts.CUDA) {
1623 if (LangOpts.CUDAIsDevice) {
1624 if (!Global->hasAttr<CUDADeviceAttr>() &&
1625 !Global->hasAttr<CUDAGlobalAttr>() &&
1626 !Global->hasAttr<CUDAConstantAttr>() &&
1627 !Global->hasAttr<CUDASharedAttr>())
1630 // We need to emit host-side 'shadows' for all global
1631 // device-side variables because the CUDA runtime needs their
1632 // size and host-side address in order to provide access to
1633 // their device-side incarnations.
1635 // So device-only functions are the only things we skip.
1636 if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1637 Global->hasAttr<CUDADeviceAttr>())
1640 assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1641 "Expected Variable or Function");
1645 if (LangOpts.OpenMP) {
1646 // If this is OpenMP device, check if it is legal to emit this global
1648 if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1650 if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1651 if (MustBeEmitted(Global))
1652 EmitOMPDeclareReduction(DRD);
1657 // Ignore declarations, they will be emitted on their first use.
1658 if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1659 // Forward declarations are emitted lazily on first use.
1660 if (!FD->doesThisDeclarationHaveABody()) {
1661 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1664 StringRef MangledName = getMangledName(GD);
1666 // Compute the function info and LLVM type.
1667 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1668 llvm::Type *Ty = getTypes().GetFunctionType(FI);
1670 GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1671 /*DontDefer=*/false);
1675 const auto *VD = cast<VarDecl>(Global);
1676 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1677 // We need to emit device-side global CUDA variables even if a
1678 // variable does not have a definition -- we still need to define
1679 // host-side shadow for it.
1680 bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1681 !VD->hasDefinition() &&
1682 (VD->hasAttr<CUDAConstantAttr>() ||
1683 VD->hasAttr<CUDADeviceAttr>());
1684 if (!MustEmitForCuda &&
1685 VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1686 !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1687 // If this declaration may have caused an inline variable definition to
1688 // change linkage, make sure that it's emitted.
1689 if (Context.getInlineVariableDefinitionKind(VD) ==
1690 ASTContext::InlineVariableDefinitionKind::Strong)
1691 GetAddrOfGlobalVar(VD);
1696 // Defer code generation to first use when possible, e.g. if this is an inline
1697 // function. If the global must always be emitted, do it eagerly if possible
1698 // to benefit from cache locality.
1699 if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1700 // Emit the definition if it can't be deferred.
1701 EmitGlobalDefinition(GD);
1705 // If we're deferring emission of a C++ variable with an
1706 // initializer, remember the order in which it appeared in the file.
1707 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1708 cast<VarDecl>(Global)->hasInit()) {
1709 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1710 CXXGlobalInits.push_back(nullptr);
1713 StringRef MangledName = getMangledName(GD);
1714 if (GetGlobalValue(MangledName) != nullptr) {
1715 // The value has already been used and should therefore be emitted.
1716 addDeferredDeclToEmit(GD);
1717 } else if (MustBeEmitted(Global)) {
1718 // The value must be emitted, but cannot be emitted eagerly.
1719 assert(!MayBeEmittedEagerly(Global));
1720 addDeferredDeclToEmit(GD);
1722 // Otherwise, remember that we saw a deferred decl with this name. The
1723 // first use of the mangled name will cause it to move into
1724 // DeferredDeclsToEmit.
1725 DeferredDecls[MangledName] = GD;
1729 // Check if T is a class type with a destructor that's not dllimport.
1730 static bool HasNonDllImportDtor(QualType T) {
1731 if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
1732 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
1733 if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
1740 struct FunctionIsDirectlyRecursive :
1741 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1742 const StringRef Name;
1743 const Builtin::Context &BI;
1745 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1746 Name(N), BI(C), Result(false) {
1748 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1750 bool TraverseCallExpr(CallExpr *E) {
1751 const FunctionDecl *FD = E->getDirectCallee();
1754 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1755 if (Attr && Name == Attr->getLabel()) {
1759 unsigned BuiltinID = FD->getBuiltinID();
1760 if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1762 StringRef BuiltinName = BI.getName(BuiltinID);
1763 if (BuiltinName.startswith("__builtin_") &&
1764 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1772 // Make sure we're not referencing non-imported vars or functions.
1773 struct DLLImportFunctionVisitor
1774 : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
1775 bool SafeToInline = true;
1777 bool shouldVisitImplicitCode() const { return true; }
1779 bool VisitVarDecl(VarDecl *VD) {
1780 if (VD->getTLSKind()) {
1781 // A thread-local variable cannot be imported.
1782 SafeToInline = false;
1783 return SafeToInline;
1786 // A variable definition might imply a destructor call.
1787 if (VD->isThisDeclarationADefinition())
1788 SafeToInline = !HasNonDllImportDtor(VD->getType());
1790 return SafeToInline;
1793 bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
1794 if (const auto *D = E->getTemporary()->getDestructor())
1795 SafeToInline = D->hasAttr<DLLImportAttr>();
1796 return SafeToInline;
1799 bool VisitDeclRefExpr(DeclRefExpr *E) {
1800 ValueDecl *VD = E->getDecl();
1801 if (isa<FunctionDecl>(VD))
1802 SafeToInline = VD->hasAttr<DLLImportAttr>();
1803 else if (VarDecl *V = dyn_cast<VarDecl>(VD))
1804 SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
1805 return SafeToInline;
1808 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
1809 SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
1810 return SafeToInline;
1813 bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
1814 CXXMethodDecl *M = E->getMethodDecl();
1816 // Call through a pointer to member function. This is safe to inline.
1817 SafeToInline = true;
1819 SafeToInline = M->hasAttr<DLLImportAttr>();
1821 return SafeToInline;
1824 bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
1825 SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
1826 return SafeToInline;
1829 bool VisitCXXNewExpr(CXXNewExpr *E) {
1830 SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
1831 return SafeToInline;
1836 // isTriviallyRecursive - Check if this function calls another
1837 // decl that, because of the asm attribute or the other decl being a builtin,
1838 // ends up pointing to itself.
1840 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1842 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1843 // asm labels are a special kind of mangling we have to support.
1844 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1847 Name = Attr->getLabel();
1849 Name = FD->getName();
1852 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1853 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1854 return Walker.Result;
1857 bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1858 if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1860 const auto *F = cast<FunctionDecl>(GD.getDecl());
1861 if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1864 if (F->hasAttr<DLLImportAttr>()) {
1865 // Check whether it would be safe to inline this dllimport function.
1866 DLLImportFunctionVisitor Visitor;
1867 Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
1868 if (!Visitor.SafeToInline)
1871 if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
1872 // Implicit destructor invocations aren't captured in the AST, so the
1873 // check above can't see them. Check for them manually here.
1874 for (const Decl *Member : Dtor->getParent()->decls())
1875 if (isa<FieldDecl>(Member))
1876 if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
1878 for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
1879 if (HasNonDllImportDtor(B.getType()))
1884 // PR9614. Avoid cases where the source code is lying to us. An available
1885 // externally function should have an equivalent function somewhere else,
1886 // but a function that calls itself is clearly not equivalent to the real
1888 // This happens in glibc's btowc and in some configure checks.
1889 return !isTriviallyRecursive(F);
1892 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1893 const auto *D = cast<ValueDecl>(GD.getDecl());
1895 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1896 Context.getSourceManager(),
1897 "Generating code for declaration");
1899 if (isa<FunctionDecl>(D)) {
1900 // At -O0, don't generate IR for functions with available_externally
1902 if (!shouldEmitFunction(GD))
1905 if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1906 // Make sure to emit the definition(s) before we emit the thunks.
1907 // This is necessary for the generation of certain thunks.
1908 if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1909 ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1910 else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1911 ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1913 EmitGlobalFunctionDefinition(GD, GV);
1915 if (Method->isVirtual())
1916 getVTables().EmitThunks(GD);
1921 return EmitGlobalFunctionDefinition(GD, GV);
1924 if (const auto *VD = dyn_cast<VarDecl>(D))
1925 return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1927 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1930 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1931 llvm::Function *NewFn);
1933 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1934 /// module, create and return an llvm Function with the specified type. If there
1935 /// is something in the module with the specified name, return it potentially
1936 /// bitcasted to the right type.
1938 /// If D is non-null, it specifies a decl that correspond to this. This is used
1939 /// to set the attributes on the function when it is first created.
1940 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
1941 StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
1942 bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
1943 ForDefinition_t IsForDefinition) {
1944 const Decl *D = GD.getDecl();
1946 // Lookup the entry, lazily creating it if necessary.
1947 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1949 if (WeakRefReferences.erase(Entry)) {
1950 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1951 if (FD && !FD->hasAttr<WeakAttr>())
1952 Entry->setLinkage(llvm::Function::ExternalLinkage);
1955 // Handle dropped DLL attributes.
1956 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1957 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1959 // If there are two attempts to define the same mangled name, issue an
1961 if (IsForDefinition && !Entry->isDeclaration()) {
1963 // Check that GD is not yet in DiagnosedConflictingDefinitions is required
1964 // to make sure that we issue an error only once.
1965 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
1966 (GD.getCanonicalDecl().getDecl() !=
1967 OtherGD.getCanonicalDecl().getDecl()) &&
1968 DiagnosedConflictingDefinitions.insert(GD).second) {
1969 getDiags().Report(D->getLocation(),
1970 diag::err_duplicate_mangled_name);
1971 getDiags().Report(OtherGD.getDecl()->getLocation(),
1972 diag::note_previous_definition);
1976 if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
1977 (Entry->getType()->getElementType() == Ty)) {
1981 // Make sure the result is of the correct type.
1982 // (If function is requested for a definition, we always need to create a new
1983 // function, not just return a bitcast.)
1984 if (!IsForDefinition)
1985 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1988 // This function doesn't have a complete type (for example, the return
1989 // type is an incomplete struct). Use a fake type instead, and make
1990 // sure not to try to set attributes.
1991 bool IsIncompleteFunction = false;
1993 llvm::FunctionType *FTy;
1994 if (isa<llvm::FunctionType>(Ty)) {
1995 FTy = cast<llvm::FunctionType>(Ty);
1997 FTy = llvm::FunctionType::get(VoidTy, false);
1998 IsIncompleteFunction = true;
2002 llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
2003 Entry ? StringRef() : MangledName, &getModule());
2005 // If we already created a function with the same mangled name (but different
2006 // type) before, take its name and add it to the list of functions to be
2007 // replaced with F at the end of CodeGen.
2009 // This happens if there is a prototype for a function (e.g. "int f()") and
2010 // then a definition of a different type (e.g. "int f(int x)").
2014 // This might be an implementation of a function without a prototype, in
2015 // which case, try to do special replacement of calls which match the new
2016 // prototype. The really key thing here is that we also potentially drop
2017 // arguments from the call site so as to make a direct call, which makes the
2018 // inliner happier and suppresses a number of optimizer warnings (!) about
2019 // dropping arguments.
2020 if (!Entry->use_empty()) {
2021 ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
2022 Entry->removeDeadConstantUsers();
2025 llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
2026 F, Entry->getType()->getElementType()->getPointerTo());
2027 addGlobalValReplacement(Entry, BC);
2030 assert(F->getName() == MangledName && "name was uniqued!");
2032 SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
2033 if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
2034 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2035 F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2039 // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
2040 // each other bottoming out with the base dtor. Therefore we emit non-base
2041 // dtors on usage, even if there is no dtor definition in the TU.
2042 if (D && isa<CXXDestructorDecl>(D) &&
2043 getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
2045 addDeferredDeclToEmit(GD);
2047 // This is the first use or definition of a mangled name. If there is a
2048 // deferred decl with this name, remember that we need to emit it at the end
2050 auto DDI = DeferredDecls.find(MangledName);
2051 if (DDI != DeferredDecls.end()) {
2052 // Move the potentially referenced deferred decl to the
2053 // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
2054 // don't need it anymore).
2055 addDeferredDeclToEmit(DDI->second);
2056 DeferredDecls.erase(DDI);
2058 // Otherwise, there are cases we have to worry about where we're
2059 // using a declaration for which we must emit a definition but where
2060 // we might not find a top-level definition:
2061 // - member functions defined inline in their classes
2062 // - friend functions defined inline in some class
2063 // - special member functions with implicit definitions
2064 // If we ever change our AST traversal to walk into class methods,
2065 // this will be unnecessary.
2067 // We also don't emit a definition for a function if it's going to be an
2068 // entry in a vtable, unless it's already marked as used.
2069 } else if (getLangOpts().CPlusPlus && D) {
2070 // Look for a declaration that's lexically in a record.
2071 for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
2072 FD = FD->getPreviousDecl()) {
2073 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
2074 if (FD->doesThisDeclarationHaveABody()) {
2075 addDeferredDeclToEmit(GD.getWithDecl(FD));
2083 // Make sure the result is of the requested type.
2084 if (!IsIncompleteFunction) {
2085 assert(F->getType()->getElementType() == Ty);
2089 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2090 return llvm::ConstantExpr::getBitCast(F, PTy);
2093 /// GetAddrOfFunction - Return the address of the given function. If Ty is
2094 /// non-null, then this function will use the specified type if it has to
2095 /// create it (this occurs when we see a definition of the function).
2096 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
2100 ForDefinition_t IsForDefinition) {
2101 // If there was no specific requested type, just convert it now.
2103 const auto *FD = cast<FunctionDecl>(GD.getDecl());
2104 auto CanonTy = Context.getCanonicalType(FD->getType());
2105 Ty = getTypes().ConvertFunctionType(CanonTy, FD);
2108 StringRef MangledName = getMangledName(GD);
2109 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
2110 /*IsThunk=*/false, llvm::AttributeList(),
2114 static const FunctionDecl *
2115 GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
2116 TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
2117 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2119 IdentifierInfo &CII = C.Idents.get(Name);
2120 for (const auto &Result : DC->lookup(&CII))
2121 if (const auto FD = dyn_cast<FunctionDecl>(Result))
2124 if (!C.getLangOpts().CPlusPlus)
2127 // Demangle the premangled name from getTerminateFn()
2128 IdentifierInfo &CXXII =
2129 (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
2130 ? C.Idents.get("terminate")
2131 : C.Idents.get(Name);
2133 for (const auto &N : {"__cxxabiv1", "std"}) {
2134 IdentifierInfo &NS = C.Idents.get(N);
2135 for (const auto &Result : DC->lookup(&NS)) {
2136 NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
2137 if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
2138 for (const auto &Result : LSD->lookup(&NS))
2139 if ((ND = dyn_cast<NamespaceDecl>(Result)))
2143 for (const auto &Result : ND->lookup(&CXXII))
2144 if (const auto *FD = dyn_cast<FunctionDecl>(Result))
2152 /// CreateRuntimeFunction - Create a new runtime function with the specified
2155 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
2156 llvm::AttributeList ExtraAttrs,
2159 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2160 /*DontDefer=*/false, /*IsThunk=*/false,
2163 if (auto *F = dyn_cast<llvm::Function>(C)) {
2165 F->setCallingConv(getRuntimeCC());
2167 if (!Local && getTriple().isOSBinFormatCOFF() &&
2168 !getCodeGenOpts().LTOVisibilityPublicStd) {
2169 const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
2170 if (!FD || FD->hasAttr<DLLImportAttr>()) {
2171 F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
2172 F->setLinkage(llvm::GlobalValue::ExternalLinkage);
2181 /// CreateBuiltinFunction - Create a new builtin function with the specified
2184 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
2185 llvm::AttributeList ExtraAttrs) {
2187 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
2188 /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
2189 if (auto *F = dyn_cast<llvm::Function>(C))
2191 F->setCallingConv(getBuiltinCC());
2195 /// isTypeConstant - Determine whether an object of this type can be emitted
2198 /// If ExcludeCtor is true, the duration when the object's constructor runs
2199 /// will not be considered. The caller will need to verify that the object is
2200 /// not written to during its construction.
2201 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2202 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2205 if (Context.getLangOpts().CPlusPlus) {
2206 if (const CXXRecordDecl *Record
2207 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2208 return ExcludeCtor && !Record->hasMutableFields() &&
2209 Record->hasTrivialDestructor();
2215 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2216 /// create and return an llvm GlobalVariable with the specified type. If there
2217 /// is something in the module with the specified name, return it potentially
2218 /// bitcasted to the right type.
2220 /// If D is non-null, it specifies a decl that correspond to this. This is used
2221 /// to set the attributes on the global when it is first created.
2223 /// If IsForDefinition is true, it is guranteed that an actual global with
2224 /// type Ty will be returned, not conversion of a variable with the same
2225 /// mangled name but some other type.
2227 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
2228 llvm::PointerType *Ty,
2230 ForDefinition_t IsForDefinition) {
2231 // Lookup the entry, lazily creating it if necessary.
2232 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2234 if (WeakRefReferences.erase(Entry)) {
2235 if (D && !D->hasAttr<WeakAttr>())
2236 Entry->setLinkage(llvm::Function::ExternalLinkage);
2239 // Handle dropped DLL attributes.
2240 if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
2241 Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
2243 if (Entry->getType() == Ty)
2246 // If there are two attempts to define the same mangled name, issue an
2248 if (IsForDefinition && !Entry->isDeclaration()) {
2250 const VarDecl *OtherD;
2252 // Check that D is not yet in DiagnosedConflictingDefinitions is required
2253 // to make sure that we issue an error only once.
2254 if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2255 (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2256 (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2257 OtherD->hasInit() &&
2258 DiagnosedConflictingDefinitions.insert(D).second) {
2259 getDiags().Report(D->getLocation(),
2260 diag::err_duplicate_mangled_name);
2261 getDiags().Report(OtherGD.getDecl()->getLocation(),
2262 diag::note_previous_definition);
2266 // Make sure the result is of the correct type.
2267 if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2268 return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2270 // (If global is requested for a definition, we always need to create a new
2271 // global, not just return a bitcast.)
2272 if (!IsForDefinition)
2273 return llvm::ConstantExpr::getBitCast(Entry, Ty);
2276 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
2277 auto *GV = new llvm::GlobalVariable(
2278 getModule(), Ty->getElementType(), false,
2279 llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2280 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2282 // If we already created a global with the same mangled name (but different
2283 // type) before, take its name and remove it from its parent.
2285 GV->takeName(Entry);
2287 if (!Entry->use_empty()) {
2288 llvm::Constant *NewPtrForOldDecl =
2289 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2290 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2293 Entry->eraseFromParent();
2296 // This is the first use or definition of a mangled name. If there is a
2297 // deferred decl with this name, remember that we need to emit it at the end
2299 auto DDI = DeferredDecls.find(MangledName);
2300 if (DDI != DeferredDecls.end()) {
2301 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2302 // list, and remove it from DeferredDecls (since we don't need it anymore).
2303 addDeferredDeclToEmit(DDI->second);
2304 DeferredDecls.erase(DDI);
2307 // Handle things which are present even on external declarations.
2309 // FIXME: This code is overly simple and should be merged with other global
2311 GV->setConstant(isTypeConstant(D->getType(), false));
2313 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2315 setLinkageAndVisibilityForGV(GV, D);
2317 if (D->getTLSKind()) {
2318 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2319 CXXThreadLocals.push_back(D);
2323 // If required by the ABI, treat declarations of static data members with
2324 // inline initializers as definitions.
2325 if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2326 EmitGlobalVarDefinition(D);
2329 // Handle XCore specific ABI requirements.
2330 if (getTriple().getArch() == llvm::Triple::xcore &&
2331 D->getLanguageLinkage() == CLanguageLinkage &&
2332 D->getType().isConstant(Context) &&
2333 isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
2334 GV->setSection(".cp.rodata");
2337 if (AddrSpace != Ty->getAddressSpace())
2338 return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2344 CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
2345 ForDefinition_t IsForDefinition) {
2346 const Decl *D = GD.getDecl();
2347 if (isa<CXXConstructorDecl>(D))
2348 return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
2349 getFromCtorType(GD.getCtorType()),
2350 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2351 /*DontDefer=*/false, IsForDefinition);
2352 else if (isa<CXXDestructorDecl>(D))
2353 return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
2354 getFromDtorType(GD.getDtorType()),
2355 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
2356 /*DontDefer=*/false, IsForDefinition);
2357 else if (isa<CXXMethodDecl>(D)) {
2358 auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
2359 cast<CXXMethodDecl>(D));
2360 auto Ty = getTypes().GetFunctionType(*FInfo);
2361 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2363 } else if (isa<FunctionDecl>(D)) {
2364 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2365 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2366 return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
2369 return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2373 llvm::GlobalVariable *
2374 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
2376 llvm::GlobalValue::LinkageTypes Linkage) {
2377 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
2378 llvm::GlobalVariable *OldGV = nullptr;
2381 // Check if the variable has the right type.
2382 if (GV->getType()->getElementType() == Ty)
2385 // Because C++ name mangling, the only way we can end up with an already
2386 // existing global with the same name is if it has been declared extern "C".
2387 assert(GV->isDeclaration() && "Declaration has wrong type!");
2391 // Create a new variable.
2392 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
2393 Linkage, nullptr, Name);
2396 // Replace occurrences of the old variable if needed.
2397 GV->takeName(OldGV);
2399 if (!OldGV->use_empty()) {
2400 llvm::Constant *NewPtrForOldDecl =
2401 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
2402 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
2405 OldGV->eraseFromParent();
2408 if (supportsCOMDAT() && GV->isWeakForLinker() &&
2409 !GV->hasAvailableExternallyLinkage())
2410 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
2415 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2416 /// given global variable. If Ty is non-null and if the global doesn't exist,
2417 /// then it will be created with the specified type instead of whatever the
2418 /// normal requested type would be. If IsForDefinition is true, it is guranteed
2419 /// that an actual global with type Ty will be returned, not conversion of a
2420 /// variable with the same mangled name but some other type.
2421 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2423 ForDefinition_t IsForDefinition) {
2424 assert(D->hasGlobalStorage() && "Not a global variable");
2425 QualType ASTTy = D->getType();
2427 Ty = getTypes().ConvertTypeForMem(ASTTy);
2429 llvm::PointerType *PTy =
2430 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2432 StringRef MangledName = getMangledName(D);
2433 return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2436 /// CreateRuntimeVariable - Create a new runtime global variable with the
2437 /// specified type and name.
2439 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
2441 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2444 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2445 assert(!D->getInit() && "Cannot emit definite definitions here!");
2447 StringRef MangledName = getMangledName(D);
2448 llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2450 // We already have a definition, not declaration, with the same mangled name.
2451 // Emitting of declaration is not required (and actually overwrites emitted
2453 if (GV && !GV->isDeclaration())
2456 // If we have not seen a reference to this variable yet, place it into the
2457 // deferred declarations table to be emitted if needed later.
2458 if (!MustBeEmitted(D) && !GV) {
2459 DeferredDecls[MangledName] = D;
2463 // The tentative definition is the only definition.
2464 EmitGlobalVarDefinition(D);
2467 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
2468 return Context.toCharUnitsFromBits(
2469 getDataLayout().getTypeStoreSizeInBits(Ty));
2472 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
2473 unsigned AddrSpace) {
2474 if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2475 if (D->hasAttr<CUDAConstantAttr>())
2476 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
2477 else if (D->hasAttr<CUDASharedAttr>())
2478 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
2480 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
2486 template<typename SomeDecl>
2487 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2488 llvm::GlobalValue *GV) {
2489 if (!getLangOpts().CPlusPlus)
2492 // Must have 'used' attribute, or else inline assembly can't rely on
2493 // the name existing.
2494 if (!D->template hasAttr<UsedAttr>())
2497 // Must have internal linkage and an ordinary name.
2498 if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2501 // Must be in an extern "C" context. Entities declared directly within
2502 // a record are not extern "C" even if the record is in such a context.
2503 const SomeDecl *First = D->getFirstDecl();
2504 if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2507 // OK, this is an internal linkage entity inside an extern "C" linkage
2508 // specification. Make a note of that so we can give it the "expected"
2509 // mangled name if nothing else is using that name.
2510 std::pair<StaticExternCMap::iterator, bool> R =
2511 StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2513 // If we have multiple internal linkage entities with the same name
2514 // in extern "C" regions, none of them gets that name.
2516 R.first->second = nullptr;
2519 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
2520 if (!CGM.supportsCOMDAT())
2523 if (D.hasAttr<SelectAnyAttr>())
2527 if (auto *VD = dyn_cast<VarDecl>(&D))
2528 Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
2530 Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
2534 case GVA_AvailableExternally:
2535 case GVA_StrongExternal:
2537 case GVA_DiscardableODR:
2541 llvm_unreachable("No such linkage");
2544 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
2545 llvm::GlobalObject &GO) {
2546 if (!shouldBeInCOMDAT(*this, D))
2548 GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
2551 /// Pass IsTentative as true if you want to create a tentative definition.
2552 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2554 // OpenCL global variables of sampler type are translated to function calls,
2555 // therefore no need to be translated.
2556 QualType ASTTy = D->getType();
2557 if (getLangOpts().OpenCL && ASTTy->isSamplerT())
2560 llvm::Constant *Init = nullptr;
2561 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2562 bool NeedsGlobalCtor = false;
2563 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2565 const VarDecl *InitDecl;
2566 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2568 // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2569 // as part of their declaration." Sema has already checked for
2570 // error cases, so we just need to set Init to UndefValue.
2571 if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2572 D->hasAttr<CUDASharedAttr>())
2573 Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2574 else if (!InitExpr) {
2575 // This is a tentative definition; tentative definitions are
2576 // implicitly initialized with { 0 }.
2578 // Note that tentative definitions are only emitted at the end of
2579 // a translation unit, so they should never have incomplete
2580 // type. In addition, EmitTentativeDefinition makes sure that we
2581 // never attempt to emit a tentative definition if a real one
2582 // exists. A use may still exists, however, so we still may need
2584 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2585 Init = EmitNullConstant(D->getType());
2587 initializedGlobalDecl = GlobalDecl(D);
2588 Init = EmitConstantInit(*InitDecl);
2591 QualType T = InitExpr->getType();
2592 if (D->getType()->isReferenceType())
2595 if (getLangOpts().CPlusPlus) {
2596 Init = EmitNullConstant(T);
2597 NeedsGlobalCtor = true;
2599 ErrorUnsupported(D, "static initializer");
2600 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2603 // We don't need an initializer, so remove the entry for the delayed
2604 // initializer position (just in case this entry was delayed) if we
2605 // also don't need to register a destructor.
2606 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2607 DelayedCXXInitPosition.erase(D);
2611 llvm::Type* InitType = Init->getType();
2612 llvm::Constant *Entry =
2613 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2615 // Strip off a bitcast if we got one back.
2616 if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2617 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2618 CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2619 // All zero index gep.
2620 CE->getOpcode() == llvm::Instruction::GetElementPtr);
2621 Entry = CE->getOperand(0);
2624 // Entry is now either a Function or GlobalVariable.
2625 auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2627 // We have a definition after a declaration with the wrong type.
2628 // We must make a new GlobalVariable* and update everything that used OldGV
2629 // (a declaration or tentative definition) with the new GlobalVariable*
2630 // (which will be a definition).
2632 // This happens if there is a prototype for a global (e.g.
2633 // "extern int x[];") and then a definition of a different type (e.g.
2634 // "int x[10];"). This also happens when an initializer has a different type
2635 // from the type of the global (this happens with unions).
2637 GV->getType()->getElementType() != InitType ||
2638 GV->getType()->getAddressSpace() !=
2639 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2641 // Move the old entry aside so that we'll create a new one.
2642 Entry->setName(StringRef());
2644 // Make a new global with the correct type, this is now guaranteed to work.
2645 GV = cast<llvm::GlobalVariable>(
2646 GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2648 // Replace all uses of the old global with the new global
2649 llvm::Constant *NewPtrForOldDecl =
2650 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2651 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2653 // Erase the old global, since it is no longer used.
2654 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2657 MaybeHandleStaticInExternC(D, GV);
2659 if (D->hasAttr<AnnotateAttr>())
2660 AddGlobalAnnotations(D, GV);
2662 // Set the llvm linkage type as appropriate.
2663 llvm::GlobalValue::LinkageTypes Linkage =
2664 getLLVMLinkageVarDefinition(D, GV->isConstant());
2666 // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
2667 // the device. [...]"
2668 // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
2669 // __device__, declares a variable that: [...]
2670 // Is accessible from all the threads within the grid and from the host
2671 // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
2672 // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2673 if (GV && LangOpts.CUDA) {
2674 if (LangOpts.CUDAIsDevice) {
2675 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
2676 GV->setExternallyInitialized(true);
2678 // Host-side shadows of external declarations of device-side
2679 // global variables become internal definitions. These have to
2680 // be internal in order to prevent name conflicts with global
2681 // host variables with the same name in a different TUs.
2682 if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2683 Linkage = llvm::GlobalValue::InternalLinkage;
2685 // Shadow variables and their properties must be registered
2686 // with CUDA runtime.
2688 if (!D->hasDefinition())
2689 Flags |= CGCUDARuntime::ExternDeviceVar;
2690 if (D->hasAttr<CUDAConstantAttr>())
2691 Flags |= CGCUDARuntime::ConstantDeviceVar;
2692 getCUDARuntime().registerDeviceVar(*GV, Flags);
2693 } else if (D->hasAttr<CUDASharedAttr>())
2694 // __shared__ variables are odd. Shadows do get created, but
2695 // they are not registered with the CUDA runtime, so they
2696 // can't really be used to access their device-side
2697 // counterparts. It's not clear yet whether it's nvcc's bug or
2698 // a feature, but we've got to do the same for compatibility.
2699 Linkage = llvm::GlobalValue::InternalLinkage;
2702 GV->setInitializer(Init);
2704 // If it is safe to mark the global 'constant', do so now.
2705 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2706 isTypeConstant(D->getType(), true));
2708 // If it is in a read-only section, mark it 'constant'.
2709 if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2710 const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2711 if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2712 GV->setConstant(true);
2715 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2718 // On Darwin, if the normal linkage of a C++ thread_local variable is
2719 // LinkOnce or Weak, we keep the normal linkage to prevent multiple
2720 // copies within a linkage unit; otherwise, the backing variable has
2721 // internal linkage and all accesses should just be calls to the
2722 // Itanium-specified entry point, which has the normal linkage of the
2723 // variable. This is to preserve the ability to change the implementation
2724 // behind the scenes.
2725 if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2726 Context.getTargetInfo().getTriple().isOSDarwin() &&
2727 !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
2728 !llvm::GlobalVariable::isWeakLinkage(Linkage))
2729 Linkage = llvm::GlobalValue::InternalLinkage;
2731 GV->setLinkage(Linkage);
2732 if (D->hasAttr<DLLImportAttr>())
2733 GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2734 else if (D->hasAttr<DLLExportAttr>())
2735 GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2737 GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2739 if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2740 // common vars aren't constant even if declared const.
2741 GV->setConstant(false);
2742 // Tentative definition of global variables may be initialized with
2743 // non-zero null pointers. In this case they should have weak linkage
2744 // since common linkage must have zero initializer and must not have
2745 // explicit section therefore cannot have non-zero initial value.
2746 if (!GV->getInitializer()->isNullValue())
2747 GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
2750 setNonAliasAttributes(D, GV);
2752 if (D->getTLSKind() && !GV->isThreadLocal()) {
2753 if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2754 CXXThreadLocals.push_back(D);
2758 maybeSetTrivialComdat(*D, *GV);
2760 // Emit the initializer function if necessary.
2761 if (NeedsGlobalCtor || NeedsGlobalDtor)
2762 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2764 SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2766 // Emit global variable debug information.
2767 if (CGDebugInfo *DI = getModuleDebugInfo())
2768 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2769 DI->EmitGlobalVariable(GV, D);
2772 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2773 CodeGenModule &CGM, const VarDecl *D,
2775 // Don't give variables common linkage if -fno-common was specified unless it
2776 // was overridden by a NoCommon attribute.
2777 if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2781 // A declaration of an identifier for an object that has file scope without
2782 // an initializer, and without a storage-class specifier or with the
2783 // storage-class specifier static, constitutes a tentative definition.
2784 if (D->getInit() || D->hasExternalStorage())
2787 // A variable cannot be both common and exist in a section.
2788 if (D->hasAttr<SectionAttr>())
2791 // Thread local vars aren't considered common linkage.
2792 if (D->getTLSKind())
2795 // Tentative definitions marked with WeakImportAttr are true definitions.
2796 if (D->hasAttr<WeakImportAttr>())
2799 // A variable cannot be both common and exist in a comdat.
2800 if (shouldBeInCOMDAT(CGM, *D))
2803 // Declarations with a required alignment do not have common linkage in MSVC
2805 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2806 if (D->hasAttr<AlignedAttr>())
2808 QualType VarType = D->getType();
2809 if (Context.isAlignmentRequired(VarType))
2812 if (const auto *RT = VarType->getAs<RecordType>()) {
2813 const RecordDecl *RD = RT->getDecl();
2814 for (const FieldDecl *FD : RD->fields()) {
2815 if (FD->isBitField())
2817 if (FD->hasAttr<AlignedAttr>())
2819 if (Context.isAlignmentRequired(FD->getType()))
2828 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2829 const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2830 if (Linkage == GVA_Internal)
2831 return llvm::Function::InternalLinkage;
2833 if (D->hasAttr<WeakAttr>()) {
2834 if (IsConstantVariable)
2835 return llvm::GlobalVariable::WeakODRLinkage;
2837 return llvm::GlobalVariable::WeakAnyLinkage;
2840 // We are guaranteed to have a strong definition somewhere else,
2841 // so we can use available_externally linkage.
2842 if (Linkage == GVA_AvailableExternally)
2843 return llvm::GlobalValue::AvailableExternallyLinkage;
2845 // Note that Apple's kernel linker doesn't support symbol
2846 // coalescing, so we need to avoid linkonce and weak linkages there.
2847 // Normally, this means we just map to internal, but for explicit
2848 // instantiations we'll map to external.
2850 // In C++, the compiler has to emit a definition in every translation unit
2851 // that references the function. We should use linkonce_odr because
2852 // a) if all references in this translation unit are optimized away, we
2853 // don't need to codegen it. b) if the function persists, it needs to be
2854 // merged with other definitions. c) C++ has the ODR, so we know the
2855 // definition is dependable.
2856 if (Linkage == GVA_DiscardableODR)
2857 return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2858 : llvm::Function::InternalLinkage;
2860 // An explicit instantiation of a template has weak linkage, since
2861 // explicit instantiations can occur in multiple translation units
2862 // and must all be equivalent. However, we are not allowed to
2863 // throw away these explicit instantiations.
2865 // We don't currently support CUDA device code spread out across multiple TUs,
2866 // so say that CUDA templates are either external (for kernels) or internal.
2867 // This lets llvm perform aggressive inter-procedural optimizations.
2868 if (Linkage == GVA_StrongODR) {
2869 if (Context.getLangOpts().AppleKext)
2870 return llvm::Function::ExternalLinkage;
2871 if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2872 return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2873 : llvm::Function::InternalLinkage;
2874 return llvm::Function::WeakODRLinkage;
2877 // C++ doesn't have tentative definitions and thus cannot have common
2879 if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2880 !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2881 CodeGenOpts.NoCommon))
2882 return llvm::GlobalVariable::CommonLinkage;
2884 // selectany symbols are externally visible, so use weak instead of
2885 // linkonce. MSVC optimizes away references to const selectany globals, so
2886 // all definitions should be the same and ODR linkage should be used.
2887 // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2888 if (D->hasAttr<SelectAnyAttr>())
2889 return llvm::GlobalVariable::WeakODRLinkage;
2891 // Otherwise, we have strong external linkage.
2892 assert(Linkage == GVA_StrongExternal);
2893 return llvm::GlobalVariable::ExternalLinkage;
2896 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2897 const VarDecl *VD, bool IsConstant) {
2898 GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2899 return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2902 /// Replace the uses of a function that was declared with a non-proto type.
2903 /// We want to silently drop extra arguments from call sites
2904 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2905 llvm::Function *newFn) {
2907 if (old->use_empty()) return;
2909 llvm::Type *newRetTy = newFn->getReturnType();
2910 SmallVector<llvm::Value*, 4> newArgs;
2911 SmallVector<llvm::OperandBundleDef, 1> newBundles;
2913 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2915 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2916 llvm::User *user = use->getUser();
2918 // Recognize and replace uses of bitcasts. Most calls to
2919 // unprototyped functions will use bitcasts.
2920 if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2921 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2922 replaceUsesOfNonProtoConstant(bitcast, newFn);
2926 // Recognize calls to the function.
2927 llvm::CallSite callSite(user);
2928 if (!callSite) continue;
2929 if (!callSite.isCallee(&*use)) continue;
2931 // If the return types don't match exactly, then we can't
2932 // transform this call unless it's dead.
2933 if (callSite->getType() != newRetTy && !callSite->use_empty())
2936 // Get the call site's attribute list.
2937 SmallVector<llvm::AttributeSet, 8> newArgAttrs;
2938 llvm::AttributeList oldAttrs = callSite.getAttributes();
2940 // If the function was passed too few arguments, don't transform.
2941 unsigned newNumArgs = newFn->arg_size();
2942 if (callSite.arg_size() < newNumArgs) continue;
2944 // If extra arguments were passed, we silently drop them.
2945 // If any of the types mismatch, we don't transform.
2947 bool dontTransform = false;
2948 for (llvm::Argument &A : newFn->args()) {
2949 if (callSite.getArgument(argNo)->getType() != A.getType()) {
2950 dontTransform = true;
2954 // Add any parameter attributes.
2955 newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
2961 // Okay, we can transform this. Create the new call instruction and copy
2962 // over the required information.
2963 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2965 // Copy over any operand bundles.
2966 callSite.getOperandBundlesAsDefs(newBundles);
2968 llvm::CallSite newCall;
2969 if (callSite.isCall()) {
2970 newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
2971 callSite.getInstruction());
2973 auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2974 newCall = llvm::InvokeInst::Create(newFn,
2975 oldInvoke->getNormalDest(),
2976 oldInvoke->getUnwindDest(),
2977 newArgs, newBundles, "",
2978 callSite.getInstruction());
2980 newArgs.clear(); // for the next iteration
2982 if (!newCall->getType()->isVoidTy())
2983 newCall->takeName(callSite.getInstruction());
2984 newCall.setAttributes(llvm::AttributeList::get(
2985 newFn->getContext(), oldAttrs.getFnAttributes(),
2986 oldAttrs.getRetAttributes(), newArgAttrs));
2987 newCall.setCallingConv(callSite.getCallingConv());
2989 // Finally, remove the old call, replacing any uses with the new one.
2990 if (!callSite->use_empty())
2991 callSite->replaceAllUsesWith(newCall.getInstruction());
2993 // Copy debug location attached to CI.
2994 if (callSite->getDebugLoc())
2995 newCall->setDebugLoc(callSite->getDebugLoc());
2997 callSite->eraseFromParent();
3001 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3002 /// implement a function with no prototype, e.g. "int foo() {}". If there are
3003 /// existing call uses of the old function in the module, this adjusts them to
3004 /// call the new function directly.
3006 /// This is not just a cleanup: the always_inline pass requires direct calls to
3007 /// functions to be able to inline them. If there is a bitcast in the way, it
3008 /// won't inline them. Instcombine normally deletes these calls, but it isn't
3010 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3011 llvm::Function *NewFn) {
3012 // If we're redefining a global as a function, don't transform it.
3013 if (!isa<llvm::Function>(Old)) return;
3015 replaceUsesOfNonProtoConstant(Old, NewFn);
3018 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3019 auto DK = VD->isThisDeclarationADefinition();
3020 if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3023 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3024 // If we have a definition, this might be a deferred decl. If the
3025 // instantiation is explicit, make sure we emit it at the end.
3026 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3027 GetAddrOfGlobalVar(VD);
3029 EmitTopLevelDecl(VD);
3032 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
3033 llvm::GlobalValue *GV) {
3034 const auto *D = cast<FunctionDecl>(GD.getDecl());
3036 // Compute the function info and LLVM type.
3037 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3038 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
3040 // Get or create the prototype for the function.
3041 if (!GV || (GV->getType()->getElementType() != Ty))
3042 GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
3047 if (!GV->isDeclaration())
3050 // We need to set linkage and visibility on the function before
3051 // generating code for it because various parts of IR generation
3052 // want to propagate this information down (e.g. to local static
3054 auto *Fn = cast<llvm::Function>(GV);
3055 setFunctionLinkage(GD, Fn);
3056 setFunctionDLLStorageClass(GD, Fn);
3058 // FIXME: this is redundant with part of setFunctionDefinitionAttributes
3059 setGlobalVisibility(Fn, D);
3061 MaybeHandleStaticInExternC(D, Fn);
3063 maybeSetTrivialComdat(*D, *Fn);
3065 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3067 setFunctionDefinitionAttributes(D, Fn);
3068 SetLLVMFunctionAttributesForDefinition(D, Fn);
3070 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3071 AddGlobalCtor(Fn, CA->getPriority());
3072 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3073 AddGlobalDtor(Fn, DA->getPriority());
3074 if (D->hasAttr<AnnotateAttr>())
3075 AddGlobalAnnotations(D, Fn);
3078 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
3079 const auto *D = cast<ValueDecl>(GD.getDecl());
3080 const AliasAttr *AA = D->getAttr<AliasAttr>();
3081 assert(AA && "Not an alias?");
3083 StringRef MangledName = getMangledName(GD);
3085 if (AA->getAliasee() == MangledName) {
3086 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3090 // If there is a definition in the module, then it wins over the alias.
3091 // This is dubious, but allow it to be safe. Just ignore the alias.
3092 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3093 if (Entry && !Entry->isDeclaration())
3096 Aliases.push_back(GD);
3098 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3100 // Create a reference to the named value. This ensures that it is emitted
3101 // if a deferred decl.
3102 llvm::Constant *Aliasee;
3103 if (isa<llvm::FunctionType>(DeclTy))
3104 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
3105 /*ForVTable=*/false);
3107 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
3108 llvm::PointerType::getUnqual(DeclTy),
3111 // Create the new alias itself, but don't set a name yet.
3112 auto *GA = llvm::GlobalAlias::create(
3113 DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3116 if (GA->getAliasee() == Entry) {
3117 Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
3121 assert(Entry->isDeclaration());
3123 // If there is a declaration in the module, then we had an extern followed
3124 // by the alias, as in:
3125 // extern int test6();
3127 // int test6() __attribute__((alias("test7")));
3129 // Remove it and replace uses of it with the alias.
3130 GA->takeName(Entry);
3132 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3134 Entry->eraseFromParent();
3136 GA->setName(MangledName);
3139 // Set attributes which are particular to an alias; this is a
3140 // specialization of the attributes which may be set on a global
3141 // variable/function.
3142 if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
3143 D->isWeakImported()) {
3144 GA->setLinkage(llvm::Function::WeakAnyLinkage);
3147 if (const auto *VD = dyn_cast<VarDecl>(D))
3148 if (VD->getTLSKind())
3149 setTLSMode(GA, *VD);
3151 setAliasAttributes(D, GA);
3154 void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3155 const auto *D = cast<ValueDecl>(GD.getDecl());
3156 const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3157 assert(IFA && "Not an ifunc?");
3159 StringRef MangledName = getMangledName(GD);
3161 if (IFA->getResolver() == MangledName) {
3162 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3166 // Report an error if some definition overrides ifunc.
3167 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3168 if (Entry && !Entry->isDeclaration()) {
3170 if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3171 DiagnosedConflictingDefinitions.insert(GD).second) {
3172 Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3173 Diags.Report(OtherGD.getDecl()->getLocation(),
3174 diag::note_previous_definition);
3179 Aliases.push_back(GD);
3181 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3182 llvm::Constant *Resolver =
3183 GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3184 /*ForVTable=*/false);
3185 llvm::GlobalIFunc *GIF =
3186 llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3187 "", Resolver, &getModule());
3189 if (GIF->getResolver() == Entry) {
3190 Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3193 assert(Entry->isDeclaration());
3195 // If there is a declaration in the module, then we had an extern followed
3196 // by the ifunc, as in:
3197 // extern int test();
3199 // int test() __attribute__((ifunc("resolver")));
3201 // Remove it and replace uses of it with the ifunc.
3202 GIF->takeName(Entry);
3204 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3206 Entry->eraseFromParent();
3208 GIF->setName(MangledName);
3210 SetCommonAttributes(D, GIF);
3213 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
3214 ArrayRef<llvm::Type*> Tys) {
3215 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
3219 static llvm::StringMapEntry<llvm::GlobalVariable *> &
3220 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
3221 const StringLiteral *Literal, bool TargetIsLSB,
3222 bool &IsUTF16, unsigned &StringLength) {
3223 StringRef String = Literal->getString();
3224 unsigned NumBytes = String.size();
3226 // Check for simple case.
3227 if (!Literal->containsNonAsciiOrNull()) {
3228 StringLength = NumBytes;
3229 return *Map.insert(std::make_pair(String, nullptr)).first;
3232 // Otherwise, convert the UTF8 literals into a string of shorts.
3235 SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
3236 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
3237 llvm::UTF16 *ToPtr = &ToBuf[0];
3239 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
3240 ToPtr + NumBytes, llvm::strictConversion);
3242 // ConvertUTF8toUTF16 returns the length in ToPtr.
3243 StringLength = ToPtr - &ToBuf[0];
3245 // Add an explicit null.
3247 return *Map.insert(std::make_pair(
3248 StringRef(reinterpret_cast<const char *>(ToBuf.data()),
3249 (StringLength + 1) * 2),
3254 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3255 unsigned StringLength = 0;
3256 bool isUTF16 = false;
3257 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3258 GetConstantCFStringEntry(CFConstantStringMap, Literal,
3259 getDataLayout().isLittleEndian(), isUTF16,
3262 if (auto *C = Entry.second)
3263 return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3265 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3266 llvm::Constant *Zeros[] = { Zero, Zero };
3268 // If we don't already have it, get __CFConstantStringClassReference.
3269 if (!CFConstantStringClassRef) {
3270 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3271 Ty = llvm::ArrayType::get(Ty, 0);
3272 llvm::Constant *GV =
3273 CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3275 if (getTriple().isOSBinFormatCOFF()) {
3276 IdentifierInfo &II = getContext().Idents.get(GV->getName());
3277 TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3278 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3279 llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3281 const VarDecl *VD = nullptr;
3282 for (const auto &Result : DC->lookup(&II))
3283 if ((VD = dyn_cast<VarDecl>(Result)))
3286 if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3287 CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3288 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3290 CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3291 CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3295 // Decay array -> ptr
3296 CFConstantStringClassRef =
3297 llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3300 QualType CFTy = getContext().getCFConstantStringType();
3302 auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3304 ConstantInitBuilder Builder(*this);
3305 auto Fields = Builder.beginStruct(STy);
3308 Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3311 Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3314 llvm::Constant *C = nullptr;
3316 auto Arr = llvm::makeArrayRef(
3317 reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
3318 Entry.first().size() / 2);
3319 C = llvm::ConstantDataArray::get(VMContext, Arr);
3321 C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3324 // Note: -fwritable-strings doesn't make the backing store strings of
3325 // CFStrings writable. (See <rdar://problem/10657500>)
3327 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
3328 llvm::GlobalValue::PrivateLinkage, C, ".str");
3329 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3330 // Don't enforce the target's minimum global alignment, since the only use
3331 // of the string is via this class initializer.
3332 CharUnits Align = isUTF16
3333 ? getContext().getTypeAlignInChars(getContext().ShortTy)
3334 : getContext().getTypeAlignInChars(getContext().CharTy);
3335 GV->setAlignment(Align.getQuantity());
3337 // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3338 // Without it LLVM can merge the string with a non unnamed_addr one during
3339 // LTO. Doing that changes the section it ends in, which surprises ld64.
3340 if (getTriple().isOSBinFormatMachO())
3341 GV->setSection(isUTF16 ? "__TEXT,__ustring"
3342 : "__TEXT,__cstring,cstring_literals");
3345 llvm::Constant *Str =
3346 llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3349 // Cast the UTF16 string to the correct type.
3350 Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
3354 auto Ty = getTypes().ConvertType(getContext().LongTy);
3355 Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3357 CharUnits Alignment = getPointerAlign();
3360 GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
3361 /*isConstant=*/false,
3362 llvm::GlobalVariable::PrivateLinkage);
3363 switch (getTriple().getObjectFormat()) {
3364 case llvm::Triple::UnknownObjectFormat:
3365 llvm_unreachable("unknown file format");
3366 case llvm::Triple::COFF:
3367 case llvm::Triple::ELF:
3368 case llvm::Triple::Wasm:
3369 GV->setSection("cfstring");
3371 case llvm::Triple::MachO:
3372 GV->setSection("__DATA,__cfstring");
3377 return ConstantAddress(GV, Alignment);
3380 QualType CodeGenModule::getObjCFastEnumerationStateType() {
3381 if (ObjCFastEnumerationStateType.isNull()) {
3382 RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
3383 D->startDefinition();
3385 QualType FieldTypes[] = {
3386 Context.UnsignedLongTy,
3387 Context.getPointerType(Context.getObjCIdType()),
3388 Context.getPointerType(Context.UnsignedLongTy),
3389 Context.getConstantArrayType(Context.UnsignedLongTy,
3390 llvm::APInt(32, 5), ArrayType::Normal, 0)
3393 for (size_t i = 0; i < 4; ++i) {
3394 FieldDecl *Field = FieldDecl::Create(Context,
3397 SourceLocation(), nullptr,
3398 FieldTypes[i], /*TInfo=*/nullptr,
3399 /*BitWidth=*/nullptr,
3402 Field->setAccess(AS_public);
3406 D->completeDefinition();
3407 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
3410 return ObjCFastEnumerationStateType;
3414 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3415 assert(!E->getType()->isPointerType() && "Strings are always arrays");
3417 // Don't emit it as the address of the string, emit the string data itself
3418 // as an inline array.
3419 if (E->getCharByteWidth() == 1) {
3420 SmallString<64> Str(E->getString());
3422 // Resize the string to the right size, which is indicated by its type.
3423 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3424 Str.resize(CAT->getSize().getZExtValue());
3425 return llvm::ConstantDataArray::getString(VMContext, Str, false);
3428 auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3429 llvm::Type *ElemTy = AType->getElementType();
3430 unsigned NumElements = AType->getNumElements();
3432 // Wide strings have either 2-byte or 4-byte elements.
3433 if (ElemTy->getPrimitiveSizeInBits() == 16) {
3434 SmallVector<uint16_t, 32> Elements;
3435 Elements.reserve(NumElements);
3437 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3438 Elements.push_back(E->getCodeUnit(i));
3439 Elements.resize(NumElements);
3440 return llvm::ConstantDataArray::get(VMContext, Elements);
3443 assert(ElemTy->getPrimitiveSizeInBits() == 32);
3444 SmallVector<uint32_t, 32> Elements;
3445 Elements.reserve(NumElements);
3447 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3448 Elements.push_back(E->getCodeUnit(i));
3449 Elements.resize(NumElements);
3450 return llvm::ConstantDataArray::get(VMContext, Elements);
3453 static llvm::GlobalVariable *
3454 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
3455 CodeGenModule &CGM, StringRef GlobalName,
3456 CharUnits Alignment) {
3457 // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
3458 unsigned AddrSpace = 0;
3459 if (CGM.getLangOpts().OpenCL)
3460 AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3462 llvm::Module &M = CGM.getModule();
3463 // Create a global variable for this string
3464 auto *GV = new llvm::GlobalVariable(
3465 M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
3466 nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
3467 GV->setAlignment(Alignment.getQuantity());
3468 GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3469 if (GV->isWeakForLinker()) {
3470 assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
3471 GV->setComdat(M.getOrInsertComdat(GV->getName()));
3477 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
3478 /// constant array for the given string literal.
3480 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
3482 CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3484 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
3485 llvm::GlobalVariable **Entry = nullptr;
3486 if (!LangOpts.WritableStrings) {
3487 Entry = &ConstantStringMap[C];
3488 if (auto GV = *Entry) {
3489 if (Alignment.getQuantity() > GV->getAlignment())
3490 GV->setAlignment(Alignment.getQuantity());
3491 return ConstantAddress(GV, Alignment);
3495 SmallString<256> MangledNameBuffer;
3496 StringRef GlobalVariableName;
3497 llvm::GlobalValue::LinkageTypes LT;
3499 // Mangle the string literal if the ABI allows for it. However, we cannot
3500 // do this if we are compiling with ASan or -fwritable-strings because they
3501 // rely on strings having normal linkage.
3502 if (!LangOpts.WritableStrings &&
3503 !LangOpts.Sanitize.has(SanitizerKind::Address) &&
3504 getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
3505 llvm::raw_svector_ostream Out(MangledNameBuffer);
3506 getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
3508 LT = llvm::GlobalValue::LinkOnceODRLinkage;
3509 GlobalVariableName = MangledNameBuffer;
3511 LT = llvm::GlobalValue::PrivateLinkage;
3512 GlobalVariableName = Name;
3515 auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
3519 SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
3521 return ConstantAddress(GV, Alignment);
3524 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3525 /// array for the given ObjCEncodeExpr node.
3527 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3529 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3531 return GetAddrOfConstantCString(Str);
3534 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
3535 /// the literal and a terminating '\0' character.
3536 /// The result has pointer to array type.
3537 ConstantAddress CodeGenModule::GetAddrOfConstantCString(
3538 const std::string &Str, const char *GlobalName) {
3539 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
3540 CharUnits Alignment =
3541 getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3544 llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
3546 // Don't share any string literals if strings aren't constant.
3547 llvm::GlobalVariable **Entry = nullptr;
3548 if (!LangOpts.WritableStrings) {
3549 Entry = &ConstantStringMap[C];
3550 if (auto GV = *Entry) {
3551 if (Alignment.getQuantity() > GV->getAlignment())
3552 GV->setAlignment(Alignment.getQuantity());
3553 return ConstantAddress(GV, Alignment);
3557 // Get the default prefix if a name wasn't specified.
3559 GlobalName = ".str";
3560 // Create a global variable for this.
3561 auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3562 GlobalName, Alignment);
3565 return ConstantAddress(GV, Alignment);
3568 ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3569 const MaterializeTemporaryExpr *E, const Expr *Init) {
3570 assert((E->getStorageDuration() == SD_Static ||
3571 E->getStorageDuration() == SD_Thread) && "not a global temporary");
3572 const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3574 // If we're not materializing a subobject of the temporary, keep the
3575 // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3576 QualType MaterializedType = Init->getType();
3577 if (Init == E->GetTemporaryExpr())
3578 MaterializedType = E->getType();
3580 CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
3582 if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
3583 return ConstantAddress(Slot, Align);
3585 // FIXME: If an externally-visible declaration extends multiple temporaries,
3586 // we need to give each temporary the same name in every translation unit (and
3587 // we also need to make the temporaries externally-visible).
3588 SmallString<256> Name;
3589 llvm::raw_svector_ostream Out(Name);
3590 getCXXABI().getMangleContext().mangleReferenceTemporary(
3591 VD, E->getManglingNumber(), Out);
3593 APValue *Value = nullptr;
3594 if (E->getStorageDuration() == SD_Static) {
3595 // We might have a cached constant initializer for this temporary. Note
3596 // that this might have a different value from the value computed by
3597 // evaluating the initializer if the surrounding constant expression
3598 // modifies the temporary.
3599 Value = getContext().getMaterializedTemporaryValue(E, false);
3600 if (Value && Value->isUninit())
3604 // Try evaluating it now, it might have a constant initializer.
3605 Expr::EvalResult EvalResult;
3606 if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3607 !EvalResult.hasSideEffects())
3608 Value = &EvalResult.Val;
3610 llvm::Constant *InitialValue = nullptr;
3611 bool Constant = false;
3614 // The temporary has a constant initializer, use it.
3615 InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3616 Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3617 Type = InitialValue->getType();
3619 // No initializer, the initialization will be provided when we
3620 // initialize the declaration which performed lifetime extension.
3621 Type = getTypes().ConvertTypeForMem(MaterializedType);
3624 // Create a global variable for this lifetime-extended temporary.
3625 llvm::GlobalValue::LinkageTypes Linkage =
3626 getLLVMLinkageVarDefinition(VD, Constant);
3627 if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3628 const VarDecl *InitVD;
3629 if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3630 isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3631 // Temporaries defined inside a class get linkonce_odr linkage because the
3632 // class can be defined in multipe translation units.
3633 Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3635 // There is no need for this temporary to have external linkage if the
3636 // VarDecl has external linkage.
3637 Linkage = llvm::GlobalVariable::InternalLinkage;
3640 unsigned AddrSpace = GetGlobalVarAddressSpace(
3641 VD, getContext().getTargetAddressSpace(MaterializedType));
3642 auto *GV = new llvm::GlobalVariable(
3643 getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3644 /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3646 setGlobalVisibility(GV, VD);
3647 GV->setAlignment(Align.getQuantity());
3648 if (supportsCOMDAT() && GV->isWeakForLinker())
3649 GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3650 if (VD->getTLSKind())
3651 setTLSMode(GV, *VD);
3652 MaterializedGlobalTemporaryMap[E] = GV;
3653 return ConstantAddress(GV, Align);
3656 /// EmitObjCPropertyImplementations - Emit information for synthesized
3657 /// properties for an implementation.
3658 void CodeGenModule::EmitObjCPropertyImplementations(const
3659 ObjCImplementationDecl *D) {
3660 for (const auto *PID : D->property_impls()) {
3661 // Dynamic is just for type-checking.
3662 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3663 ObjCPropertyDecl *PD = PID->getPropertyDecl();
3665 // Determine which methods need to be implemented, some may have
3666 // been overridden. Note that ::isPropertyAccessor is not the method
3667 // we want, that just indicates if the decl came from a
3668 // property. What we want to know is if the method is defined in
3669 // this implementation.
3670 if (!D->getInstanceMethod(PD->getGetterName()))
3671 CodeGenFunction(*this).GenerateObjCGetter(
3672 const_cast<ObjCImplementationDecl *>(D), PID);
3673 if (!PD->isReadOnly() &&
3674 !D->getInstanceMethod(PD->getSetterName()))
3675 CodeGenFunction(*this).GenerateObjCSetter(
3676 const_cast<ObjCImplementationDecl *>(D), PID);
3681 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3682 const ObjCInterfaceDecl *iface = impl->getClassInterface();
3683 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3684 ivar; ivar = ivar->getNextIvar())
3685 if (ivar->getType().isDestructedType())
3691 static bool AllTrivialInitializers(CodeGenModule &CGM,
3692 ObjCImplementationDecl *D) {
3693 CodeGenFunction CGF(CGM);
3694 for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3695 E = D->init_end(); B != E; ++B) {
3696 CXXCtorInitializer *CtorInitExp = *B;
3697 Expr *Init = CtorInitExp->getInit();
3698 if (!CGF.isTrivialInitializer(Init))
3704 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3705 /// for an implementation.
3706 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3707 // We might need a .cxx_destruct even if we don't have any ivar initializers.
3708 if (needsDestructMethod(D)) {
3709 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3710 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3711 ObjCMethodDecl *DTORMethod =
3712 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3713 cxxSelector, getContext().VoidTy, nullptr, D,
3714 /*isInstance=*/true, /*isVariadic=*/false,
3715 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3716 /*isDefined=*/false, ObjCMethodDecl::Required);
3717 D->addInstanceMethod(DTORMethod);
3718 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3719 D->setHasDestructors(true);
3722 // If the implementation doesn't have any ivar initializers, we don't need
3723 // a .cxx_construct.
3724 if (D->getNumIvarInitializers() == 0 ||
3725 AllTrivialInitializers(*this, D))
3728 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3729 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3730 // The constructor returns 'self'.
3731 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3735 getContext().getObjCIdType(),
3736 nullptr, D, /*isInstance=*/true,
3737 /*isVariadic=*/false,
3738 /*isPropertyAccessor=*/true,
3739 /*isImplicitlyDeclared=*/true,
3740 /*isDefined=*/false,
3741 ObjCMethodDecl::Required);
3742 D->addInstanceMethod(CTORMethod);
3743 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3744 D->setHasNonZeroConstructors(true);
3747 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3748 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3749 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3750 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3751 ErrorUnsupported(LSD, "linkage spec");
3755 EmitDeclContext(LSD);
3758 void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
3759 for (auto *I : DC->decls()) {
3760 // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
3761 // are themselves considered "top-level", so EmitTopLevelDecl on an
3762 // ObjCImplDecl does not recursively visit them. We need to do that in
3763 // case they're nested inside another construct (LinkageSpecDecl /
3764 // ExportDecl) that does stop them from being considered "top-level".
3765 if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3766 for (auto *M : OID->methods())
3767 EmitTopLevelDecl(M);
3770 EmitTopLevelDecl(I);
3774 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3775 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3776 // Ignore dependent declarations.
3777 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3780 switch (D->getKind()) {
3781 case Decl::CXXConversion:
3782 case Decl::CXXMethod:
3783 case Decl::Function:
3784 // Skip function templates
3785 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3786 cast<FunctionDecl>(D)->isLateTemplateParsed())
3789 EmitGlobal(cast<FunctionDecl>(D));
3790 // Always provide some coverage mapping
3791 // even for the functions that aren't emitted.
3792 AddDeferredUnusedCoverageMapping(D);
3795 case Decl::CXXDeductionGuide:
3796 // Function-like, but does not result in code emission.
3800 case Decl::Decomposition:
3801 // Skip variable templates
3802 if (cast<VarDecl>(D)->getDescribedVarTemplate())
3804 case Decl::VarTemplateSpecialization:
3805 EmitGlobal(cast<VarDecl>(D));
3806 if (auto *DD = dyn_cast<DecompositionDecl>(D))
3807 for (auto *B : DD->bindings())
3808 if (auto *HD = B->getHoldingVar())
3812 // Indirect fields from global anonymous structs and unions can be
3813 // ignored; only the actual variable requires IR gen support.
3814 case Decl::IndirectField:
3818 case Decl::Namespace:
3819 EmitDeclContext(cast<NamespaceDecl>(D));
3821 case Decl::CXXRecord:
3823 if (auto *ES = D->getASTContext().getExternalSource())
3824 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
3825 DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
3827 // Emit any static data members, they may be definitions.
3828 for (auto *I : cast<CXXRecordDecl>(D)->decls())
3829 if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3830 EmitTopLevelDecl(I);
3832 // No code generation needed.
3833 case Decl::UsingShadow:
3834 case Decl::ClassTemplate:
3835 case Decl::VarTemplate:
3836 case Decl::VarTemplatePartialSpecialization:
3837 case Decl::FunctionTemplate:
3838 case Decl::TypeAliasTemplate:
3842 case Decl::Using: // using X; [C++]
3843 if (CGDebugInfo *DI = getModuleDebugInfo())
3844 DI->EmitUsingDecl(cast<UsingDecl>(*D));
3846 case Decl::NamespaceAlias:
3847 if (CGDebugInfo *DI = getModuleDebugInfo())
3848 DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3850 case Decl::UsingDirective: // using namespace X; [C++]
3851 if (CGDebugInfo *DI = getModuleDebugInfo())
3852 DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3854 case Decl::CXXConstructor:
3855 // Skip function templates
3856 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3857 cast<FunctionDecl>(D)->isLateTemplateParsed())
3860 getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3862 case Decl::CXXDestructor:
3863 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3865 getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3868 case Decl::StaticAssert:
3872 // Objective-C Decls
3874 // Forward declarations, no (immediate) code generation.
3875 case Decl::ObjCInterface:
3876 case Decl::ObjCCategory:
3879 case Decl::ObjCProtocol: {
3880 auto *Proto = cast<ObjCProtocolDecl>(D);
3881 if (Proto->isThisDeclarationADefinition())
3882 ObjCRuntime->GenerateProtocol(Proto);
3886 case Decl::ObjCCategoryImpl:
3887 // Categories have properties but don't support synthesize so we
3888 // can ignore them here.
3889 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3892 case Decl::ObjCImplementation: {
3893 auto *OMD = cast<ObjCImplementationDecl>(D);
3894 EmitObjCPropertyImplementations(OMD);
3895 EmitObjCIvarInitializations(OMD);
3896 ObjCRuntime->GenerateClass(OMD);
3897 // Emit global variable debug information.
3898 if (CGDebugInfo *DI = getModuleDebugInfo())
3899 if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3900 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3901 OMD->getClassInterface()), OMD->getLocation());
3904 case Decl::ObjCMethod: {
3905 auto *OMD = cast<ObjCMethodDecl>(D);
3906 // If this is not a prototype, emit the body.
3908 CodeGenFunction(*this).GenerateObjCMethod(OMD);
3911 case Decl::ObjCCompatibleAlias:
3912 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3915 case Decl::PragmaComment: {
3916 const auto *PCD = cast<PragmaCommentDecl>(D);
3917 switch (PCD->getCommentKind()) {
3919 llvm_unreachable("unexpected pragma comment kind");
3921 AppendLinkerOptions(PCD->getArg());
3924 AddDependentLib(PCD->getArg());
3929 break; // We ignore all of these.
3934 case Decl::PragmaDetectMismatch: {
3935 const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3936 AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3940 case Decl::LinkageSpec:
3941 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3944 case Decl::FileScopeAsm: {
3945 // File-scope asm is ignored during device-side CUDA compilation.
3946 if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3948 // File-scope asm is ignored during device-side OpenMP compilation.
3949 if (LangOpts.OpenMPIsDevice)
3951 auto *AD = cast<FileScopeAsmDecl>(D);
3952 getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3956 case Decl::Import: {
3957 auto *Import = cast<ImportDecl>(D);
3959 // If we've already imported this module, we're done.
3960 if (!ImportedModules.insert(Import->getImportedModule()))
3963 // Emit debug information for direct imports.
3964 if (!Import->getImportedOwningModule()) {
3965 if (CGDebugInfo *DI = getModuleDebugInfo())
3966 DI->EmitImportDecl(*Import);
3969 // Find all of the submodules and emit the module initializers.
3970 llvm::SmallPtrSet<clang::Module *, 16> Visited;
3971 SmallVector<clang::Module *, 16> Stack;
3972 Visited.insert(Import->getImportedModule());
3973 Stack.push_back(Import->getImportedModule());
3975 while (!Stack.empty()) {
3976 clang::Module *Mod = Stack.pop_back_val();
3977 if (!EmittedModuleInitializers.insert(Mod).second)
3980 for (auto *D : Context.getModuleInitializers(Mod))
3981 EmitTopLevelDecl(D);
3983 // Visit the submodules of this module.
3984 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
3985 SubEnd = Mod->submodule_end();
3986 Sub != SubEnd; ++Sub) {
3987 // Skip explicit children; they need to be explicitly imported to emit
3988 // the initializers.
3989 if ((*Sub)->IsExplicit)
3992 if (Visited.insert(*Sub).second)
3993 Stack.push_back(*Sub);
4000 EmitDeclContext(cast<ExportDecl>(D));
4003 case Decl::OMPThreadPrivate:
4004 EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
4007 case Decl::ClassTemplateSpecialization: {
4008 const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
4010 Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
4011 Spec->hasDefinition())
4012 DebugInfo->completeTemplateDefinition(*Spec);
4016 case Decl::OMPDeclareReduction:
4017 EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4021 // Make sure we handled everything we should, every other kind is a
4022 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
4023 // function. Need to recode Decl::Kind to do that easily.
4024 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
4029 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
4030 // Do we need to generate coverage mapping?
4031 if (!CodeGenOpts.CoverageMapping)
4033 switch (D->getKind()) {
4034 case Decl::CXXConversion:
4035 case Decl::CXXMethod:
4036 case Decl::Function:
4037 case Decl::ObjCMethod:
4038 case Decl::CXXConstructor:
4039 case Decl::CXXDestructor: {
4040 if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
4042 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4043 if (I == DeferredEmptyCoverageMappingDecls.end())
4044 DeferredEmptyCoverageMappingDecls[D] = true;
4052 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
4053 // Do we need to generate coverage mapping?
4054 if (!CodeGenOpts.CoverageMapping)
4056 if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
4057 if (Fn->isTemplateInstantiation())
4058 ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
4060 auto I = DeferredEmptyCoverageMappingDecls.find(D);
4061 if (I == DeferredEmptyCoverageMappingDecls.end())
4062 DeferredEmptyCoverageMappingDecls[D] = false;
4067 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
4068 std::vector<const Decl *> DeferredDecls;
4069 for (const auto &I : DeferredEmptyCoverageMappingDecls) {
4072 DeferredDecls.push_back(I.first);
4074 // Sort the declarations by their location to make sure that the tests get a
4075 // predictable order for the coverage mapping for the unused declarations.
4076 if (CodeGenOpts.DumpCoverageMapping)
4077 std::sort(DeferredDecls.begin(), DeferredDecls.end(),
4078 [] (const Decl *LHS, const Decl *RHS) {
4079 return LHS->getLocStart() < RHS->getLocStart();
4081 for (const auto *D : DeferredDecls) {
4082 switch (D->getKind()) {
4083 case Decl::CXXConversion:
4084 case Decl::CXXMethod:
4085 case Decl::Function:
4086 case Decl::ObjCMethod: {
4087 CodeGenPGO PGO(*this);
4088 GlobalDecl GD(cast<FunctionDecl>(D));
4089 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4090 getFunctionLinkage(GD));
4093 case Decl::CXXConstructor: {
4094 CodeGenPGO PGO(*this);
4095 GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
4096 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4097 getFunctionLinkage(GD));
4100 case Decl::CXXDestructor: {
4101 CodeGenPGO PGO(*this);
4102 GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
4103 PGO.emitEmptyCounterMapping(D, getMangledName(GD),
4104 getFunctionLinkage(GD));
4113 /// Turns the given pointer into a constant.
4114 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4116 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
4117 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4118 return llvm::ConstantInt::get(i64, PtrInt);
4121 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4122 llvm::NamedMDNode *&GlobalMetadata,
4124 llvm::GlobalValue *Addr) {
4125 if (!GlobalMetadata)
4127 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4129 // TODO: should we report variant information for ctors/dtors?
4130 llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
4131 llvm::ConstantAsMetadata::get(GetPointerConstant(
4132 CGM.getLLVMContext(), D.getDecl()))};
4133 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4136 /// For each function which is declared within an extern "C" region and marked
4137 /// as 'used', but has internal linkage, create an alias from the unmangled
4138 /// name to the mangled name if possible. People expect to be able to refer
4139 /// to such functions with an unmangled name from inline assembly within the
4140 /// same translation unit.
4141 void CodeGenModule::EmitStaticExternCAliases() {
4142 // Don't do anything if we're generating CUDA device code -- the NVPTX
4143 // assembly target doesn't support aliases.
4144 if (Context.getTargetInfo().getTriple().isNVPTX())
4146 for (auto &I : StaticExternCValues) {
4147 IdentifierInfo *Name = I.first;
4148 llvm::GlobalValue *Val = I.second;
4149 if (Val && !getModule().getNamedValue(Name->getName()))
4150 addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4154 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
4155 GlobalDecl &Result) const {
4156 auto Res = Manglings.find(MangledName);
4157 if (Res == Manglings.end())
4159 Result = Res->getValue();
4163 /// Emits metadata nodes associating all the global values in the
4164 /// current module with the Decls they came from. This is useful for
4165 /// projects using IR gen as a subroutine.
4167 /// Since there's currently no way to associate an MDNode directly
4168 /// with an llvm::GlobalValue, we create a global named metadata
4169 /// with the name 'clang.global.decl.ptrs'.
4170 void CodeGenModule::EmitDeclMetadata() {
4171 llvm::NamedMDNode *GlobalMetadata = nullptr;
4173 for (auto &I : MangledDeclNames) {
4174 llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
4175 // Some mangled names don't necessarily have an associated GlobalValue
4176 // in this module, e.g. if we mangled it for DebugInfo.
4178 EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4182 /// Emits metadata nodes for all the local variables in the current
4184 void CodeGenFunction::EmitDeclMetadata() {
4185 if (LocalDeclMap.empty()) return;
4187 llvm::LLVMContext &Context = getLLVMContext();
4189 // Find the unique metadata ID for this name.
4190 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4192 llvm::NamedMDNode *GlobalMetadata = nullptr;
4194 for (auto &I : LocalDeclMap) {
4195 const Decl *D = I.first;
4196 llvm::Value *Addr = I.second.getPointer();
4197 if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4198 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
4199 Alloca->setMetadata(
4200 DeclPtrKind, llvm::MDNode::get(
4201 Context, llvm::ValueAsMetadata::getConstant(DAddr)));
4202 } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4203 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4204 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4209 void CodeGenModule::EmitVersionIdentMetadata() {
4210 llvm::NamedMDNode *IdentMetadata =
4211 TheModule.getOrInsertNamedMetadata("llvm.ident");
4212 std::string Version = getClangFullVersion();
4213 llvm::LLVMContext &Ctx = TheModule.getContext();
4215 llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4216 IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4219 void CodeGenModule::EmitTargetMetadata() {
4220 // Warning, new MangledDeclNames may be appended within this loop.
4221 // We rely on MapVector insertions adding new elements to the end
4222 // of the container.
4223 // FIXME: Move this loop into the one target that needs it, and only
4224 // loop over those declarations for which we couldn't emit the target
4225 // metadata when we emitted the declaration.
4226 for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
4227 auto Val = *(MangledDeclNames.begin() + I);
4228 const Decl *D = Val.first.getDecl()->getMostRecentDecl();
4229 llvm::GlobalValue *GV = GetGlobalValue(Val.second);
4230 getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
4234 void CodeGenModule::EmitCoverageFile() {
4235 if (getCodeGenOpts().CoverageDataFile.empty() &&
4236 getCodeGenOpts().CoverageNotesFile.empty())
4239 llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
4243 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4244 llvm::LLVMContext &Ctx = TheModule.getContext();
4245 auto *CoverageDataFile =
4246 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
4247 auto *CoverageNotesFile =
4248 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4249 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4250 llvm::MDNode *CU = CUNode->getOperand(i);
4251 llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
4252 GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4256 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
4257 // Sema has checked that all uuid strings are of the form
4258 // "12345678-1234-1234-1234-1234567890ab".
4259 assert(Uuid.size() == 36);
4260 for (unsigned i = 0; i < 36; ++i) {
4261 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4262 else assert(isHexDigit(Uuid[i]));
4265 // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4266 const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
4268 llvm::Constant *Field3[8];
4269 for (unsigned Idx = 0; Idx < 8; ++Idx)
4270 Field3[Idx] = llvm::ConstantInt::get(
4271 Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
4273 llvm::Constant *Fields[4] = {
4274 llvm::ConstantInt::get(Int32Ty, Uuid.substr(0, 8), 16),
4275 llvm::ConstantInt::get(Int16Ty, Uuid.substr(9, 4), 16),
4276 llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4277 llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4280 return llvm::ConstantStruct::getAnon(Fields);
4283 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
4285 // Return a bogus pointer if RTTI is disabled, unless it's for EH.
4286 // FIXME: should we even be calling this method if RTTI is disabled
4287 // and it's not for EH?
4288 if (!ForEH && !getLangOpts().RTTI)
4289 return llvm::Constant::getNullValue(Int8PtrTy);
4291 if (ForEH && Ty->isObjCObjectPointerType() &&
4292 LangOpts.ObjCRuntime.isGNUFamily())
4293 return ObjCRuntime->GetEHType(Ty);
4295 return getCXXABI().getAddrOfRTTIDescriptor(Ty);
4298 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
4299 for (auto RefExpr : D->varlists()) {
4300 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
4302 VD->getAnyInitializer() &&
4303 !VD->getAnyInitializer()->isConstantInitializer(getContext(),
4306 Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
4307 if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
4308 VD, Addr, RefExpr->getLocStart(), PerformInit))
4309 CXXGlobalInits.push_back(InitFunction);
4313 llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
4314 llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
4318 if (isExternallyVisible(T->getLinkage())) {
4319 std::string OutName;
4320 llvm::raw_string_ostream Out(OutName);
4321 getCXXABI().getMangleContext().mangleTypeName(T, Out);
4323 InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
4325 InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
4326 llvm::ArrayRef<llvm::Metadata *>());
4332 /// Returns whether this module needs the "all-vtables" type identifier.
4333 bool CodeGenModule::NeedAllVtablesTypeId() const {
4334 // Returns true if at least one of vtable-based CFI checkers is enabled and
4335 // is not in the trapping mode.
4336 return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4337 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4338 (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4339 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4340 (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4341 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4342 (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4343 !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4346 void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
4348 const CXXRecordDecl *RD) {
4349 llvm::Metadata *MD =
4350 CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4351 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4353 if (CodeGenOpts.SanitizeCfiCrossDso)
4354 if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4355 VTable->addTypeMetadata(Offset.getQuantity(),
4356 llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4358 if (NeedAllVtablesTypeId()) {
4359 llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4360 VTable->addTypeMetadata(Offset.getQuantity(), MD);
4364 // Fills in the supplied string map with the set of target features for the
4365 // passed in function.
4366 void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
4367 const FunctionDecl *FD) {
4368 StringRef TargetCPU = Target.getTargetOpts().CPU;
4369 if (const auto *TD = FD->getAttr<TargetAttr>()) {
4370 // If we have a TargetAttr build up the feature map based on that.
4371 TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
4373 // Make a copy of the features as passed on the command line into the
4374 // beginning of the additional features from the function to override.
4375 ParsedAttr.first.insert(ParsedAttr.first.begin(),
4376 Target.getTargetOpts().FeaturesAsWritten.begin(),
4377 Target.getTargetOpts().FeaturesAsWritten.end());
4379 if (ParsedAttr.second != "")
4380 TargetCPU = ParsedAttr.second;
4382 // Now populate the feature map, first with the TargetCPU which is either
4383 // the default or a new one from the target attribute string. Then we'll use
4384 // the passed in features (FeaturesAsWritten) along with the new ones from
4386 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
4388 Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4389 Target.getTargetOpts().Features);
4393 llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4395 SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4400 CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
4401 CodeGenFunction &CGF) {
4402 llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
4403 auto SamplerT = getOpenCLRuntime().getSamplerType();
4404 auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
4405 return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
4406 "__translate_sampler_initializer"),