1f22ef01cSRoman Divacky //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This coordinates the per-module state used while generating code.
11f22ef01cSRoman Divacky //
12f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
13f22ef01cSRoman Divacky 
14f22ef01cSRoman Divacky #include "CodeGenModule.h"
150623d748SDimitry Andric #include "CGBlocks.h"
166122f3e6SDimitry Andric #include "CGCUDARuntime.h"
17e580952dSDimitry Andric #include "CGCXXABI.h"
18139f7f9bSDimitry Andric #include "CGCall.h"
19139f7f9bSDimitry Andric #include "CGDebugInfo.h"
20f22ef01cSRoman Divacky #include "CGObjCRuntime.h"
216122f3e6SDimitry Andric #include "CGOpenCLRuntime.h"
2259d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h"
23e7145dcbSDimitry Andric #include "CGOpenMPRuntimeNVPTX.h"
24139f7f9bSDimitry Andric #include "CodeGenFunction.h"
2559d1ed5bSDimitry Andric #include "CodeGenPGO.h"
26139f7f9bSDimitry Andric #include "CodeGenTBAA.h"
2739d628a0SDimitry Andric #include "CoverageMappingGen.h"
28f22ef01cSRoman Divacky #include "TargetInfo.h"
29f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
30f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h"
31f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
32139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h"
33ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h"
342754fe60SDimitry Andric #include "clang/AST/Mangle.h"
35f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h"
36f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
37dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h"
38139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h"
39f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h"
40139f7f9bSDimitry Andric #include "clang/Basic/Module.h"
41f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h"
42f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h"
43f785676fSDimitry Andric #include "clang/Basic/Version.h"
4420e90f04SDimitry Andric #include "clang/CodeGen/ConstantInitBuilder.h"
45139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h"
46f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h"
47f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h"
48d8866befSDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
4959d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h"
50139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h"
51139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
52139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
53139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
54139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
5559d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
56139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h"
57f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
580623d748SDimitry Andric #include "llvm/Support/MD5.h"
59139f7f9bSDimitry Andric 
60f22ef01cSRoman Divacky using namespace clang;
61f22ef01cSRoman Divacky using namespace CodeGen;
62f22ef01cSRoman Divacky 
636122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
646122f3e6SDimitry Andric 
6559d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
66284c1978SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
67139f7f9bSDimitry Andric   case TargetCXXABI::GenericAArch64:
68139f7f9bSDimitry Andric   case TargetCXXABI::GenericARM:
69139f7f9bSDimitry Andric   case TargetCXXABI::iOS:
7059d1ed5bSDimitry Andric   case TargetCXXABI::iOS64:
710623d748SDimitry Andric   case TargetCXXABI::WatchOS:
72ef6fa9e2SDimitry Andric   case TargetCXXABI::GenericMIPS:
73139f7f9bSDimitry Andric   case TargetCXXABI::GenericItanium:
740623d748SDimitry Andric   case TargetCXXABI::WebAssembly:
7559d1ed5bSDimitry Andric     return CreateItaniumCXXABI(CGM);
76139f7f9bSDimitry Andric   case TargetCXXABI::Microsoft:
7759d1ed5bSDimitry Andric     return CreateMicrosoftCXXABI(CGM);
78e580952dSDimitry Andric   }
79e580952dSDimitry Andric 
80e580952dSDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
81e580952dSDimitry Andric }
82e580952dSDimitry Andric 
833dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
843dac3a9bSDimitry Andric                              const PreprocessorOptions &PPO,
853dac3a9bSDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
8639d628a0SDimitry Andric                              DiagnosticsEngine &diags,
8739d628a0SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
883dac3a9bSDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
893dac3a9bSDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
900623d748SDimitry Andric       Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
91e7145dcbSDimitry Andric       VMContext(M.getContext()), Types(*this), VTables(*this),
92e7145dcbSDimitry Andric       SanitizerMD(new SanitizerMetadata(*this)) {
93dff0c46cSDimitry Andric 
94dff0c46cSDimitry Andric   // Initialize the type cache.
95dff0c46cSDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
96dff0c46cSDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
97dff0c46cSDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
98dff0c46cSDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
99dff0c46cSDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
100dff0c46cSDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
101dff0c46cSDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
102dff0c46cSDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
103dff0c46cSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
104dff0c46cSDimitry Andric   PointerAlignInBytes =
105dff0c46cSDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
10644290647SDimitry Andric   SizeSizeInBytes =
10744290647SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getMaxPointerWidth()).getQuantity();
1080623d748SDimitry Andric   IntAlignInBytes =
1090623d748SDimitry Andric     C.toCharUnitsFromBits(C.getTargetInfo().getIntAlign()).getQuantity();
110dff0c46cSDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
11144290647SDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext,
11244290647SDimitry Andric     C.getTargetInfo().getMaxPointerWidth());
113dff0c46cSDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
114dff0c46cSDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
1156bc11b14SDimitry Andric   AllocaInt8PtrTy = Int8Ty->getPointerTo(
1166bc11b14SDimitry Andric       M.getDataLayout().getAllocaAddrSpace());
117d8866befSDimitry Andric   ASTAllocaAddressSpace = getTargetCodeGenInfo().getASTAllocaAddressSpace();
118dff0c46cSDimitry Andric 
119139f7f9bSDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
12039d628a0SDimitry Andric   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
121139f7f9bSDimitry Andric 
122dff0c46cSDimitry Andric   if (LangOpts.ObjC1)
1233b0f4066SDimitry Andric     createObjCRuntime();
124dff0c46cSDimitry Andric   if (LangOpts.OpenCL)
1256122f3e6SDimitry Andric     createOpenCLRuntime();
12659d1ed5bSDimitry Andric   if (LangOpts.OpenMP)
12759d1ed5bSDimitry Andric     createOpenMPRuntime();
128dff0c46cSDimitry Andric   if (LangOpts.CUDA)
1296122f3e6SDimitry Andric     createCUDARuntime();
130f22ef01cSRoman Divacky 
1317ae0e2c9SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
13239d628a0SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1337ae0e2c9SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
134e7145dcbSDimitry Andric     TBAA.reset(new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
135e7145dcbSDimitry Andric                                getCXXABI().getMangleContext()));
1362754fe60SDimitry Andric 
1373b0f4066SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1383b0f4066SDimitry Andric   // object.
139e7145dcbSDimitry Andric   if (CodeGenOpts.getDebugInfo() != codegenoptions::NoDebugInfo ||
140e7145dcbSDimitry Andric       CodeGenOpts.EmitGcovArcs || CodeGenOpts.EmitGcovNotes)
141e7145dcbSDimitry Andric     DebugInfo.reset(new CGDebugInfo(*this));
1422754fe60SDimitry Andric 
1432754fe60SDimitry Andric   Block.GlobalUniqueCount = 0;
1442754fe60SDimitry Andric 
1450623d748SDimitry Andric   if (C.getLangOpts().ObjC1)
146e7145dcbSDimitry Andric     ObjCData.reset(new ObjCEntrypoints());
14759d1ed5bSDimitry Andric 
148e7145dcbSDimitry Andric   if (CodeGenOpts.hasProfileClangUse()) {
149e7145dcbSDimitry Andric     auto ReaderOrErr = llvm::IndexedInstrProfReader::create(
150e7145dcbSDimitry Andric         CodeGenOpts.ProfileInstrumentUsePath);
151e7145dcbSDimitry Andric     if (auto E = ReaderOrErr.takeError()) {
15259d1ed5bSDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1533dac3a9bSDimitry Andric                                               "Could not read profile %0: %1");
154e7145dcbSDimitry Andric       llvm::handleAllErrors(std::move(E), [&](const llvm::ErrorInfoBase &EI) {
155e7145dcbSDimitry Andric         getDiags().Report(DiagID) << CodeGenOpts.ProfileInstrumentUsePath
156e7145dcbSDimitry Andric                                   << EI.message();
157e7145dcbSDimitry Andric       });
15833956c43SDimitry Andric     } else
15933956c43SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
16059d1ed5bSDimitry Andric   }
16139d628a0SDimitry Andric 
16239d628a0SDimitry Andric   // If coverage mapping generation is enabled, create the
16339d628a0SDimitry Andric   // CoverageMappingModuleGen object.
16439d628a0SDimitry Andric   if (CodeGenOpts.CoverageMapping)
16539d628a0SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
166f22ef01cSRoman Divacky }
167f22ef01cSRoman Divacky 
168e7145dcbSDimitry Andric CodeGenModule::~CodeGenModule() {}
169f22ef01cSRoman Divacky 
170f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
1717ae0e2c9SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1727ae0e2c9SDimitry Andric   // new ABIs to decide how best to do this.
1737ae0e2c9SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1747ae0e2c9SDimitry Andric   case ObjCRuntime::GNUstep:
1757ae0e2c9SDimitry Andric   case ObjCRuntime::GCC:
1767ae0e2c9SDimitry Andric   case ObjCRuntime::ObjFW:
177e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateGNUObjCRuntime(*this));
1787ae0e2c9SDimitry Andric     return;
1797ae0e2c9SDimitry Andric 
1807ae0e2c9SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1817ae0e2c9SDimitry Andric   case ObjCRuntime::MacOSX:
1827ae0e2c9SDimitry Andric   case ObjCRuntime::iOS:
1830623d748SDimitry Andric   case ObjCRuntime::WatchOS:
184e7145dcbSDimitry Andric     ObjCRuntime.reset(CreateMacObjCRuntime(*this));
1857ae0e2c9SDimitry Andric     return;
1867ae0e2c9SDimitry Andric   }
1877ae0e2c9SDimitry Andric   llvm_unreachable("bad runtime kind");
1886122f3e6SDimitry Andric }
1896122f3e6SDimitry Andric 
1906122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
191e7145dcbSDimitry Andric   OpenCLRuntime.reset(new CGOpenCLRuntime(*this));
1926122f3e6SDimitry Andric }
1936122f3e6SDimitry Andric 
19459d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() {
195e7145dcbSDimitry Andric   // Select a specialized code generation class based on the target, if any.
196e7145dcbSDimitry Andric   // If it does not exist use the default implementation.
19744290647SDimitry Andric   switch (getTriple().getArch()) {
198e7145dcbSDimitry Andric   case llvm::Triple::nvptx:
199e7145dcbSDimitry Andric   case llvm::Triple::nvptx64:
200e7145dcbSDimitry Andric     assert(getLangOpts().OpenMPIsDevice &&
201e7145dcbSDimitry Andric            "OpenMP NVPTX is only prepared to deal with device code.");
202e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntimeNVPTX(*this));
203e7145dcbSDimitry Andric     break;
204e7145dcbSDimitry Andric   default:
205e7145dcbSDimitry Andric     OpenMPRuntime.reset(new CGOpenMPRuntime(*this));
206e7145dcbSDimitry Andric     break;
207e7145dcbSDimitry Andric   }
20859d1ed5bSDimitry Andric }
20959d1ed5bSDimitry Andric 
2106122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() {
211e7145dcbSDimitry Andric   CUDARuntime.reset(CreateNVCUDARuntime(*this));
212f22ef01cSRoman Divacky }
213f22ef01cSRoman Divacky 
21439d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
21539d628a0SDimitry Andric   Replacements[Name] = C;
21639d628a0SDimitry Andric }
21739d628a0SDimitry Andric 
218f785676fSDimitry Andric void CodeGenModule::applyReplacements() {
2198f0fd8f6SDimitry Andric   for (auto &I : Replacements) {
2208f0fd8f6SDimitry Andric     StringRef MangledName = I.first();
2218f0fd8f6SDimitry Andric     llvm::Constant *Replacement = I.second;
222f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
223f785676fSDimitry Andric     if (!Entry)
224f785676fSDimitry Andric       continue;
22559d1ed5bSDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
22659d1ed5bSDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
227f785676fSDimitry Andric     if (!NewF) {
22859d1ed5bSDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
22959d1ed5bSDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
23059d1ed5bSDimitry Andric       } else {
23159d1ed5bSDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
232f785676fSDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
233f785676fSDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
234f785676fSDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
235f785676fSDimitry Andric       }
23659d1ed5bSDimitry Andric     }
237f785676fSDimitry Andric 
238f785676fSDimitry Andric     // Replace old with new, but keep the old order.
239f785676fSDimitry Andric     OldF->replaceAllUsesWith(Replacement);
240f785676fSDimitry Andric     if (NewF) {
241f785676fSDimitry Andric       NewF->removeFromParent();
2420623d748SDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF->getIterator(),
2430623d748SDimitry Andric                                                        NewF);
244f785676fSDimitry Andric     }
245f785676fSDimitry Andric     OldF->eraseFromParent();
246f785676fSDimitry Andric   }
247f785676fSDimitry Andric }
248f785676fSDimitry Andric 
2490623d748SDimitry Andric void CodeGenModule::addGlobalValReplacement(llvm::GlobalValue *GV, llvm::Constant *C) {
2500623d748SDimitry Andric   GlobalValReplacements.push_back(std::make_pair(GV, C));
2510623d748SDimitry Andric }
2520623d748SDimitry Andric 
2530623d748SDimitry Andric void CodeGenModule::applyGlobalValReplacements() {
2540623d748SDimitry Andric   for (auto &I : GlobalValReplacements) {
2550623d748SDimitry Andric     llvm::GlobalValue *GV = I.first;
2560623d748SDimitry Andric     llvm::Constant *C = I.second;
2570623d748SDimitry Andric 
2580623d748SDimitry Andric     GV->replaceAllUsesWith(C);
2590623d748SDimitry Andric     GV->eraseFromParent();
2600623d748SDimitry Andric   }
2610623d748SDimitry Andric }
2620623d748SDimitry Andric 
26359d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a
26459d1ed5bSDimitry Andric // linear structure.
265e7145dcbSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(
266e7145dcbSDimitry Andric     const llvm::GlobalIndirectSymbol &GIS) {
267e7145dcbSDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalIndirectSymbol*, 4> Visited;
268e7145dcbSDimitry Andric   const llvm::Constant *C = &GIS;
26959d1ed5bSDimitry Andric   for (;;) {
27059d1ed5bSDimitry Andric     C = C->stripPointerCasts();
27159d1ed5bSDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
27259d1ed5bSDimitry Andric       return GO;
27359d1ed5bSDimitry Andric     // stripPointerCasts will not walk over weak aliases.
274e7145dcbSDimitry Andric     auto *GIS2 = dyn_cast<llvm::GlobalIndirectSymbol>(C);
275e7145dcbSDimitry Andric     if (!GIS2)
27659d1ed5bSDimitry Andric       return nullptr;
277e7145dcbSDimitry Andric     if (!Visited.insert(GIS2).second)
27859d1ed5bSDimitry Andric       return nullptr;
279e7145dcbSDimitry Andric     C = GIS2->getIndirectSymbol();
28059d1ed5bSDimitry Andric   }
28159d1ed5bSDimitry Andric }
28259d1ed5bSDimitry Andric 
283f785676fSDimitry Andric void CodeGenModule::checkAliases() {
28459d1ed5bSDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
28559d1ed5bSDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
28659d1ed5bSDimitry Andric   // and aliases during codegen.
287f785676fSDimitry Andric   bool Error = false;
28859d1ed5bSDimitry Andric   DiagnosticsEngine &Diags = getDiags();
2898f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
29059d1ed5bSDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
291e7145dcbSDimitry Andric     SourceLocation Location;
292e7145dcbSDimitry Andric     bool IsIFunc = D->hasAttr<IFuncAttr>();
293e7145dcbSDimitry Andric     if (const Attr *A = D->getDefiningAttr())
294e7145dcbSDimitry Andric       Location = A->getLocation();
295e7145dcbSDimitry Andric     else
296e7145dcbSDimitry Andric       llvm_unreachable("Not an alias or ifunc?");
297f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
298f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
299e7145dcbSDimitry Andric     auto *Alias  = cast<llvm::GlobalIndirectSymbol>(Entry);
30059d1ed5bSDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
30159d1ed5bSDimitry Andric     if (!GV) {
302f785676fSDimitry Andric       Error = true;
303e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_cyclic_alias) << IsIFunc;
30459d1ed5bSDimitry Andric     } else if (GV->isDeclaration()) {
305f785676fSDimitry Andric       Error = true;
306e7145dcbSDimitry Andric       Diags.Report(Location, diag::err_alias_to_undefined)
307e7145dcbSDimitry Andric           << IsIFunc << IsIFunc;
308e7145dcbSDimitry Andric     } else if (IsIFunc) {
309e7145dcbSDimitry Andric       // Check resolver function type.
310e7145dcbSDimitry Andric       llvm::FunctionType *FTy = dyn_cast<llvm::FunctionType>(
311e7145dcbSDimitry Andric           GV->getType()->getPointerElementType());
312e7145dcbSDimitry Andric       assert(FTy);
313e7145dcbSDimitry Andric       if (!FTy->getReturnType()->isPointerTy())
314e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_return);
315e7145dcbSDimitry Andric       if (FTy->getNumParams())
316e7145dcbSDimitry Andric         Diags.Report(Location, diag::err_ifunc_resolver_params);
31759d1ed5bSDimitry Andric     }
31859d1ed5bSDimitry Andric 
319e7145dcbSDimitry Andric     llvm::Constant *Aliasee = Alias->getIndirectSymbol();
32059d1ed5bSDimitry Andric     llvm::GlobalValue *AliaseeGV;
32159d1ed5bSDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
32259d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
32359d1ed5bSDimitry Andric     else
32459d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
32559d1ed5bSDimitry Andric 
32659d1ed5bSDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
32759d1ed5bSDimitry Andric       StringRef AliasSection = SA->getName();
32859d1ed5bSDimitry Andric       if (AliasSection != AliaseeGV->getSection())
32959d1ed5bSDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
330e7145dcbSDimitry Andric             << AliasSection << IsIFunc << IsIFunc;
33159d1ed5bSDimitry Andric     }
33259d1ed5bSDimitry Andric 
33359d1ed5bSDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
33459d1ed5bSDimitry Andric     // this since the object semantics would not match the IL one. For
33559d1ed5bSDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
33659d1ed5bSDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
33759d1ed5bSDimitry Andric     // expecting the link to be weak.
338e7145dcbSDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalIndirectSymbol>(AliaseeGV)) {
339e7145dcbSDimitry Andric       if (GA->isInterposable()) {
340e7145dcbSDimitry Andric         Diags.Report(Location, diag::warn_alias_to_weak_alias)
341e7145dcbSDimitry Andric             << GV->getName() << GA->getName() << IsIFunc;
34259d1ed5bSDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
343e7145dcbSDimitry Andric             GA->getIndirectSymbol(), Alias->getType());
344e7145dcbSDimitry Andric         Alias->setIndirectSymbol(Aliasee);
34559d1ed5bSDimitry Andric       }
346f785676fSDimitry Andric     }
347f785676fSDimitry Andric   }
348f785676fSDimitry Andric   if (!Error)
349f785676fSDimitry Andric     return;
350f785676fSDimitry Andric 
3518f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
352f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
353f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
354e7145dcbSDimitry Andric     auto *Alias = dyn_cast<llvm::GlobalIndirectSymbol>(Entry);
355f785676fSDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
356f785676fSDimitry Andric     Alias->eraseFromParent();
357f785676fSDimitry Andric   }
358f785676fSDimitry Andric }
359f785676fSDimitry Andric 
36059d1ed5bSDimitry Andric void CodeGenModule::clear() {
36159d1ed5bSDimitry Andric   DeferredDeclsToEmit.clear();
36233956c43SDimitry Andric   if (OpenMPRuntime)
36333956c43SDimitry Andric     OpenMPRuntime->clear();
36459d1ed5bSDimitry Andric }
36559d1ed5bSDimitry Andric 
36659d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
36759d1ed5bSDimitry Andric                                        StringRef MainFile) {
36859d1ed5bSDimitry Andric   if (!hasDiagnostics())
36959d1ed5bSDimitry Andric     return;
37059d1ed5bSDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
37159d1ed5bSDimitry Andric     if (MainFile.empty())
37259d1ed5bSDimitry Andric       MainFile = "<stdin>";
37359d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
374f37b6182SDimitry Andric   } else {
375f37b6182SDimitry Andric     if (Mismatched > 0)
376f37b6182SDimitry Andric       Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Mismatched;
377f37b6182SDimitry Andric 
378f37b6182SDimitry Andric     if (Missing > 0)
379f37b6182SDimitry Andric       Diags.Report(diag::warn_profile_data_missing) << Visited << Missing;
380f37b6182SDimitry Andric   }
38159d1ed5bSDimitry Andric }
38259d1ed5bSDimitry Andric 
383f22ef01cSRoman Divacky void CodeGenModule::Release() {
384f22ef01cSRoman Divacky   EmitDeferred();
385f9448bf3SDimitry Andric   EmitVTablesOpportunistically();
3860623d748SDimitry Andric   applyGlobalValReplacements();
387f785676fSDimitry Andric   applyReplacements();
388f785676fSDimitry Andric   checkAliases();
389f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
390f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
391284c1978SDimitry Andric   EmitCXXThreadLocalInitFunc();
3926122f3e6SDimitry Andric   if (ObjCRuntime)
3936122f3e6SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
394f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
39533956c43SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
39633956c43SDimitry Andric       CUDARuntime) {
39733956c43SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
39833956c43SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
39933956c43SDimitry Andric     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
40033956c43SDimitry Andric       AddGlobalDtor(CudaDtorFunction);
40133956c43SDimitry Andric   }
402ea942507SDimitry Andric   if (OpenMPRuntime)
403ea942507SDimitry Andric     if (llvm::Function *OpenMPRegistrationFunction =
404302affcbSDimitry Andric             OpenMPRuntime->emitRegistrationFunction()) {
405302affcbSDimitry Andric       auto ComdatKey = OpenMPRegistrationFunction->hasComdat() ?
406302affcbSDimitry Andric         OpenMPRegistrationFunction : nullptr;
407302affcbSDimitry Andric       AddGlobalCtor(OpenMPRegistrationFunction, 0, ComdatKey);
408302affcbSDimitry Andric     }
4090623d748SDimitry Andric   if (PGOReader) {
410e7145dcbSDimitry Andric     getModule().setProfileSummary(PGOReader->getSummary().getMD(VMContext));
4110623d748SDimitry Andric     if (PGOStats.hasDiagnostics())
41259d1ed5bSDimitry Andric       PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
4130623d748SDimitry Andric   }
414f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
415f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
4166122f3e6SDimitry Andric   EmitGlobalAnnotations();
417284c1978SDimitry Andric   EmitStaticExternCAliases();
41839d628a0SDimitry Andric   EmitDeferredUnusedCoverageMappings();
41939d628a0SDimitry Andric   if (CoverageMapping)
42039d628a0SDimitry Andric     CoverageMapping->emit();
42120e90f04SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
422e7145dcbSDimitry Andric     CodeGenFunction(*this).EmitCfiCheckFail();
42320e90f04SDimitry Andric     CodeGenFunction(*this).EmitCfiCheckStub();
42420e90f04SDimitry Andric   }
42520e90f04SDimitry Andric   emitAtAvailableLinkGuard();
42659d1ed5bSDimitry Andric   emitLLVMUsed();
427e7145dcbSDimitry Andric   if (SanStats)
428e7145dcbSDimitry Andric     SanStats->finish();
429ffd1746dSEd Schouten 
430f785676fSDimitry Andric   if (CodeGenOpts.Autolink &&
431f785676fSDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
432139f7f9bSDimitry Andric     EmitModuleLinkOptions();
433139f7f9bSDimitry Andric   }
43420e90f04SDimitry Andric 
43520e90f04SDimitry Andric   // Record mregparm value now so it is visible through rest of codegen.
43620e90f04SDimitry Andric   if (Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
43720e90f04SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "NumRegisterParameters",
43820e90f04SDimitry Andric                               CodeGenOpts.NumRegisterParameters);
43920e90f04SDimitry Andric 
4400623d748SDimitry Andric   if (CodeGenOpts.DwarfVersion) {
441f785676fSDimitry Andric     // We actually want the latest version when there are conflicts.
442f785676fSDimitry Andric     // We can change from Warning to Latest if such mode is supported.
443f785676fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
444f785676fSDimitry Andric                               CodeGenOpts.DwarfVersion);
4450623d748SDimitry Andric   }
4460623d748SDimitry Andric   if (CodeGenOpts.EmitCodeView) {
4470623d748SDimitry Andric     // Indicate that we want CodeView in the metadata.
4480623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "CodeView", 1);
4490623d748SDimitry Andric   }
4500623d748SDimitry Andric   if (CodeGenOpts.OptimizationLevel > 0 && CodeGenOpts.StrictVTablePointers) {
4510623d748SDimitry Andric     // We don't support LTO with 2 with different StrictVTablePointers
4520623d748SDimitry Andric     // FIXME: we could support it by stripping all the information introduced
4530623d748SDimitry Andric     // by StrictVTablePointers.
4540623d748SDimitry Andric 
4550623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "StrictVTablePointers",1);
4560623d748SDimitry Andric 
4570623d748SDimitry Andric     llvm::Metadata *Ops[2] = {
4580623d748SDimitry Andric               llvm::MDString::get(VMContext, "StrictVTablePointers"),
4590623d748SDimitry Andric               llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
4600623d748SDimitry Andric                   llvm::Type::getInt32Ty(VMContext), 1))};
4610623d748SDimitry Andric 
4620623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Require,
4630623d748SDimitry Andric                               "StrictVTablePointersRequirement",
4640623d748SDimitry Andric                               llvm::MDNode::get(VMContext, Ops));
4650623d748SDimitry Andric   }
466f785676fSDimitry Andric   if (DebugInfo)
46759d1ed5bSDimitry Andric     // We support a single version in the linked module. The LLVM
46859d1ed5bSDimitry Andric     // parser will drop debug info with a different version number
46959d1ed5bSDimitry Andric     // (and warn about it, too).
47059d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
471f785676fSDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
472139f7f9bSDimitry Andric 
473d8866befSDimitry Andric   // Width of wchar_t in bytes
474d8866befSDimitry Andric   uint64_t WCharWidth =
475d8866befSDimitry Andric       Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
476f9448bf3SDimitry Andric   assert((LangOpts.ShortWChar ||
477d8866befSDimitry Andric           llvm::TargetLibraryInfoImpl::getTargetWCharSize(Target.getTriple()) ==
478f9448bf3SDimitry Andric               Target.getWCharWidth() / 8) &&
479d8866befSDimitry Andric          "LLVM wchar_t size out of sync");
480d8866befSDimitry Andric 
48159d1ed5bSDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
482d8866befSDimitry Andric   // the correct build attributes in the ARM backend. wchar_size is also used by
483d8866befSDimitry Andric   // TargetLibraryInfo.
484d8866befSDimitry Andric   getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
485d8866befSDimitry Andric 
48659d1ed5bSDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
48759d1ed5bSDimitry Andric   if (   Arch == llvm::Triple::arm
48859d1ed5bSDimitry Andric       || Arch == llvm::Triple::armeb
48959d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumb
49059d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumbeb) {
49159d1ed5bSDimitry Andric     // The minimum width of an enum in bytes
49259d1ed5bSDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
49359d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
49459d1ed5bSDimitry Andric   }
49559d1ed5bSDimitry Andric 
4960623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
4970623d748SDimitry Andric     // Indicate that we want cross-DSO control flow integrity checks.
4980623d748SDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "Cross-DSO CFI", 1);
4990623d748SDimitry Andric   }
5000623d748SDimitry Andric 
50144290647SDimitry Andric   if (LangOpts.CUDAIsDevice && getTriple().isNVPTX()) {
502e7145dcbSDimitry Andric     // Indicate whether __nvvm_reflect should be configured to flush denormal
503e7145dcbSDimitry Andric     // floating point values to 0.  (This corresponds to its "__CUDA_FTZ"
504e7145dcbSDimitry Andric     // property.)
505e7145dcbSDimitry Andric     getModule().addModuleFlag(llvm::Module::Override, "nvvm-reflect-ftz",
506e7145dcbSDimitry Andric                               LangOpts.CUDADeviceFlushDenormalsToZero ? 1 : 0);
50739d628a0SDimitry Andric   }
50839d628a0SDimitry Andric 
509edd7eaddSDimitry Andric   // Emit OpenCL specific module metadata: OpenCL/SPIR version.
510edd7eaddSDimitry Andric   if (LangOpts.OpenCL) {
511edd7eaddSDimitry Andric     EmitOpenCLMetadata();
512edd7eaddSDimitry Andric     // Emit SPIR version.
513edd7eaddSDimitry Andric     if (getTriple().getArch() == llvm::Triple::spir ||
514edd7eaddSDimitry Andric         getTriple().getArch() == llvm::Triple::spir64) {
515edd7eaddSDimitry Andric       // SPIR v2.0 s2.12 - The SPIR version used by the module is stored in the
516edd7eaddSDimitry Andric       // opencl.spir.version named metadata.
517edd7eaddSDimitry Andric       llvm::Metadata *SPIRVerElts[] = {
518edd7eaddSDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
519edd7eaddSDimitry Andric               Int32Ty, LangOpts.OpenCLVersion / 100)),
520edd7eaddSDimitry Andric           llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
521edd7eaddSDimitry Andric               Int32Ty, (LangOpts.OpenCLVersion / 100 > 1) ? 0 : 2))};
522edd7eaddSDimitry Andric       llvm::NamedMDNode *SPIRVerMD =
523edd7eaddSDimitry Andric           TheModule.getOrInsertNamedMetadata("opencl.spir.version");
524edd7eaddSDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
525edd7eaddSDimitry Andric       SPIRVerMD->addOperand(llvm::MDNode::get(Ctx, SPIRVerElts));
526edd7eaddSDimitry Andric     }
527edd7eaddSDimitry Andric   }
528edd7eaddSDimitry Andric 
529e7145dcbSDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
530e7145dcbSDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
531e7145dcbSDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
532e7145dcbSDimitry Andric     if (Context.getLangOpts().PIE)
533e7145dcbSDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
53439d628a0SDimitry Andric   }
53539d628a0SDimitry Andric 
5362754fe60SDimitry Andric   SimplifyPersonality();
5372754fe60SDimitry Andric 
538ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
539ffd1746dSEd Schouten     EmitDeclMetadata();
540bd5abe19SDimitry Andric 
541bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
542bd5abe19SDimitry Andric     EmitCoverageFile();
5436122f3e6SDimitry Andric 
5446122f3e6SDimitry Andric   if (DebugInfo)
5456122f3e6SDimitry Andric     DebugInfo->finalize();
546f785676fSDimitry Andric 
547f785676fSDimitry Andric   EmitVersionIdentMetadata();
54859d1ed5bSDimitry Andric 
54959d1ed5bSDimitry Andric   EmitTargetMetadata();
550f22ef01cSRoman Divacky }
551f22ef01cSRoman Divacky 
552edd7eaddSDimitry Andric void CodeGenModule::EmitOpenCLMetadata() {
553edd7eaddSDimitry Andric   // SPIR v2.0 s2.13 - The OpenCL version used by the module is stored in the
554edd7eaddSDimitry Andric   // opencl.ocl.version named metadata node.
555edd7eaddSDimitry Andric   llvm::Metadata *OCLVerElts[] = {
556edd7eaddSDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
557edd7eaddSDimitry Andric           Int32Ty, LangOpts.OpenCLVersion / 100)),
558edd7eaddSDimitry Andric       llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
559edd7eaddSDimitry Andric           Int32Ty, (LangOpts.OpenCLVersion % 100) / 10))};
560edd7eaddSDimitry Andric   llvm::NamedMDNode *OCLVerMD =
561edd7eaddSDimitry Andric       TheModule.getOrInsertNamedMetadata("opencl.ocl.version");
562edd7eaddSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
563edd7eaddSDimitry Andric   OCLVerMD->addOperand(llvm::MDNode::get(Ctx, OCLVerElts));
564edd7eaddSDimitry Andric }
565edd7eaddSDimitry Andric 
5663b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
5673b0f4066SDimitry Andric   // Make sure that this type is translated.
5683b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
5693b0f4066SDimitry Andric }
5703b0f4066SDimitry Andric 
571e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
572e7145dcbSDimitry Andric   // Make sure that this type is translated.
573e7145dcbSDimitry Andric   Types.RefreshTypeCacheForClass(RD);
574e7145dcbSDimitry Andric }
575e7145dcbSDimitry Andric 
5762754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
5772754fe60SDimitry Andric   if (!TBAA)
57859d1ed5bSDimitry Andric     return nullptr;
5792754fe60SDimitry Andric   return TBAA->getTBAAInfo(QTy);
5802754fe60SDimitry Andric }
5812754fe60SDimitry Andric 
582dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
583dff0c46cSDimitry Andric   if (!TBAA)
58459d1ed5bSDimitry Andric     return nullptr;
585dff0c46cSDimitry Andric   return TBAA->getTBAAInfoForVTablePtr();
586dff0c46cSDimitry Andric }
587dff0c46cSDimitry Andric 
5883861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
5893861d79fSDimitry Andric   if (!TBAA)
59059d1ed5bSDimitry Andric     return nullptr;
5913861d79fSDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
5923861d79fSDimitry Andric }
5933861d79fSDimitry Andric 
594139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
595139f7f9bSDimitry Andric                                                   llvm::MDNode *AccessN,
596139f7f9bSDimitry Andric                                                   uint64_t O) {
597139f7f9bSDimitry Andric   if (!TBAA)
59859d1ed5bSDimitry Andric     return nullptr;
599139f7f9bSDimitry Andric   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
600139f7f9bSDimitry Andric }
601139f7f9bSDimitry Andric 
602f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA
603f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format:
604f785676fSDimitry Andric /// base type, access type and offset.
605284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
6060623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
607284c1978SDimitry Andric                                                 llvm::MDNode *TBAAInfo,
608284c1978SDimitry Andric                                                 bool ConvertTypeToTag) {
609f785676fSDimitry Andric   if (ConvertTypeToTag && TBAA)
610284c1978SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
611284c1978SDimitry Andric                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
612284c1978SDimitry Andric   else
6132754fe60SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
6142754fe60SDimitry Andric }
6152754fe60SDimitry Andric 
6160623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
6170623d748SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
61851690af2SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
61951690af2SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
6200623d748SDimitry Andric }
6210623d748SDimitry Andric 
62259d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
62359d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
62459d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
625f22ef01cSRoman Divacky }
626f22ef01cSRoman Divacky 
627f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
628f22ef01cSRoman Divacky /// specified stmt yet.
629f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
6306122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
631f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
632f22ef01cSRoman Divacky   std::string Msg = Type;
633f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
634f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
635f22ef01cSRoman Divacky }
636f22ef01cSRoman Divacky 
637f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
638f22ef01cSRoman Divacky /// specified decl yet.
639f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
6406122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
641f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
642f22ef01cSRoman Divacky   std::string Msg = Type;
643f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
644f22ef01cSRoman Divacky }
645f22ef01cSRoman Divacky 
64617a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
64717a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
64817a519f9SDimitry Andric }
64917a519f9SDimitry Andric 
650f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
6512754fe60SDimitry Andric                                         const NamedDecl *D) const {
652f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
653f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
654f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
655f22ef01cSRoman Divacky     return;
656f22ef01cSRoman Divacky   }
657f22ef01cSRoman Divacky 
6582754fe60SDimitry Andric   // Set visibility for definitions.
659139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
660139f7f9bSDimitry Andric   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
661139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
662f22ef01cSRoman Divacky }
663f22ef01cSRoman Divacky 
6647ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
6657ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
6667ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
6677ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
6687ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
6697ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
6707ae0e2c9SDimitry Andric }
6717ae0e2c9SDimitry Andric 
6727ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
6737ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
6747ae0e2c9SDimitry Andric   switch (M) {
6757ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
6767ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
6777ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
6787ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
6797ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
6807ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
6817ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
6827ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
6837ae0e2c9SDimitry Andric   }
6847ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
6857ae0e2c9SDimitry Andric }
6867ae0e2c9SDimitry Andric 
68739d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
688284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
6897ae0e2c9SDimitry Andric 
69039d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
6913861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
6927ae0e2c9SDimitry Andric 
6937ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
69459d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
6957ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
6967ae0e2c9SDimitry Andric   }
6977ae0e2c9SDimitry Andric 
6987ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
6997ae0e2c9SDimitry Andric }
7007ae0e2c9SDimitry Andric 
7016122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
702444ed5c5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
703444ed5c5SDimitry Andric 
704444ed5c5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
705444ed5c5SDimitry Andric   // complete constructors get mangled the same.
706444ed5c5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
707444ed5c5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
708444ed5c5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
709444ed5c5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
710444ed5c5SDimitry Andric       if (OrigCtorType == Ctor_Base)
711444ed5c5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
712444ed5c5SDimitry Andric     }
713444ed5c5SDimitry Andric   }
714444ed5c5SDimitry Andric 
715444ed5c5SDimitry Andric   StringRef &FoundStr = MangledDeclNames[CanonicalGD];
71659d1ed5bSDimitry Andric   if (!FoundStr.empty())
71759d1ed5bSDimitry Andric     return FoundStr;
718f22ef01cSRoman Divacky 
71959d1ed5bSDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
720dff0c46cSDimitry Andric   SmallString<256> Buffer;
72159d1ed5bSDimitry Andric   StringRef Str;
72259d1ed5bSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
7232754fe60SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
72459d1ed5bSDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
7252754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
72659d1ed5bSDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
7272754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
728ffd1746dSEd Schouten     else
7292754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleName(ND, Out);
73059d1ed5bSDimitry Andric     Str = Out.str();
73159d1ed5bSDimitry Andric   } else {
73259d1ed5bSDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
73359d1ed5bSDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
73444290647SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
73544290647SDimitry Andric 
73644290647SDimitry Andric     if (FD &&
73744290647SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
73844290647SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
73944290647SDimitry Andric       Out << "__regcall3__" << II->getName();
74044290647SDimitry Andric       Str = Out.str();
74144290647SDimitry Andric     } else {
74259d1ed5bSDimitry Andric       Str = II->getName();
743ffd1746dSEd Schouten     }
74444290647SDimitry Andric   }
745ffd1746dSEd Schouten 
74639d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
74739d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Str, GD));
74839d628a0SDimitry Andric   return FoundStr = Result.first->first();
74959d1ed5bSDimitry Andric }
75059d1ed5bSDimitry Andric 
75159d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
752ffd1746dSEd Schouten                                              const BlockDecl *BD) {
7532754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
7542754fe60SDimitry Andric   const Decl *D = GD.getDecl();
75559d1ed5bSDimitry Andric 
75659d1ed5bSDimitry Andric   SmallString<256> Buffer;
75759d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
75859d1ed5bSDimitry Andric   if (!D)
7597ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
7607ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
76159d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
7622754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
76359d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
7642754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
7652754fe60SDimitry Andric   else
7662754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
76759d1ed5bSDimitry Andric 
76839d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
76939d628a0SDimitry Andric   return Result.first->first();
770f22ef01cSRoman Divacky }
771f22ef01cSRoman Divacky 
7726122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
773f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
774f22ef01cSRoman Divacky }
775f22ef01cSRoman Divacky 
776f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
777f22ef01cSRoman Divacky /// main() runs.
77859d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
77959d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
780f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
78159d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
782f22ef01cSRoman Divacky }
783f22ef01cSRoman Divacky 
784f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
785f22ef01cSRoman Divacky /// when the module is unloaded.
786f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
787f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
78859d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
789f22ef01cSRoman Divacky }
790f22ef01cSRoman Divacky 
79144290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
79244290647SDimitry Andric   if (Fns.empty()) return;
79344290647SDimitry Andric 
794f22ef01cSRoman Divacky   // Ctor function type is void()*.
795bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
796f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
797f22ef01cSRoman Divacky 
79859d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
79959d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
8005517e702SDimitry Andric       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
801f22ef01cSRoman Divacky 
802f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
80344290647SDimitry Andric   ConstantInitBuilder builder(*this);
80444290647SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
8058f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
80644290647SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
80744290647SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
80844290647SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
80944290647SDimitry Andric     if (I.AssociatedData)
81044290647SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
81144290647SDimitry Andric     else
81244290647SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
81344290647SDimitry Andric     ctor.finishAndAddTo(ctors);
814f22ef01cSRoman Divacky   }
815f22ef01cSRoman Divacky 
81644290647SDimitry Andric   auto list =
81744290647SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
81844290647SDimitry Andric                                 /*constant*/ false,
81944290647SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
82044290647SDimitry Andric 
82144290647SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
82244290647SDimitry Andric   // on appending variables.  Take it off as a workaround.
82344290647SDimitry Andric   list->setAlignment(0);
82444290647SDimitry Andric 
82544290647SDimitry Andric   Fns.clear();
826f22ef01cSRoman Divacky }
827f22ef01cSRoman Divacky 
828f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
829f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
83059d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
831f785676fSDimitry Andric 
832e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
833f22ef01cSRoman Divacky 
83459d1ed5bSDimitry Andric   if (isa<CXXDestructorDecl>(D) &&
83559d1ed5bSDimitry Andric       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
83659d1ed5bSDimitry Andric                                          GD.getDtorType())) {
83759d1ed5bSDimitry Andric     // Destructor variants in the Microsoft C++ ABI are always internal or
83859d1ed5bSDimitry Andric     // linkonce_odr thunks emitted on an as-needed basis.
83959d1ed5bSDimitry Andric     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
84059d1ed5bSDimitry Andric                                    : llvm::GlobalValue::LinkOnceODRLinkage;
841f22ef01cSRoman Divacky   }
842f22ef01cSRoman Divacky 
843e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
844e7145dcbSDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
845e7145dcbSDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
846e7145dcbSDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
847e7145dcbSDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
848e7145dcbSDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
849e7145dcbSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
850e7145dcbSDimitry Andric   }
851e7145dcbSDimitry Andric 
85259d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
85359d1ed5bSDimitry Andric }
854f22ef01cSRoman Divacky 
85597bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
85697bc6c73SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
85797bc6c73SDimitry Andric 
85897bc6c73SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
85997bc6c73SDimitry Andric     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
86097bc6c73SDimitry Andric       // Don't dllexport/import destructor thunks.
86197bc6c73SDimitry Andric       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
86297bc6c73SDimitry Andric       return;
86397bc6c73SDimitry Andric     }
86497bc6c73SDimitry Andric   }
86597bc6c73SDimitry Andric 
86697bc6c73SDimitry Andric   if (FD->hasAttr<DLLImportAttr>())
86797bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
86897bc6c73SDimitry Andric   else if (FD->hasAttr<DLLExportAttr>())
86997bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
87097bc6c73SDimitry Andric   else
87197bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
87297bc6c73SDimitry Andric }
87397bc6c73SDimitry Andric 
874e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
8750623d748SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
8760623d748SDimitry Andric   if (!MDS) return nullptr;
8770623d748SDimitry Andric 
87844290647SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
8790623d748SDimitry Andric }
8800623d748SDimitry Andric 
88159d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
88259d1ed5bSDimitry Andric                                                     llvm::Function *F) {
88359d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
884f22ef01cSRoman Divacky }
885f22ef01cSRoman Divacky 
886f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
887f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
888f22ef01cSRoman Divacky                                               llvm::Function *F) {
889f22ef01cSRoman Divacky   unsigned CallingConv;
8906bc11b14SDimitry Andric   llvm::AttributeList PAL;
8916bc11b14SDimitry Andric   ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
8926bc11b14SDimitry Andric   F->setAttributes(PAL);
893f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
894f22ef01cSRoman Divacky }
895f22ef01cSRoman Divacky 
8966122f3e6SDimitry Andric /// Determines whether the language options require us to model
8976122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
8986122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
8996122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
9006122f3e6SDimitry Andric /// enables this.
901dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
9026122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
903dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
9046122f3e6SDimitry Andric 
9056122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
906dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
9076122f3e6SDimitry Andric 
9086122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
909dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
9107ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
9116122f3e6SDimitry Andric   }
9126122f3e6SDimitry Andric 
9136122f3e6SDimitry Andric   return true;
9146122f3e6SDimitry Andric }
9156122f3e6SDimitry Andric 
916f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
917f22ef01cSRoman Divacky                                                            llvm::Function *F) {
918f785676fSDimitry Andric   llvm::AttrBuilder B;
919f785676fSDimitry Andric 
920bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
921f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
922bd5abe19SDimitry Andric 
923dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
924f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
925f22ef01cSRoman Divacky 
9260623d748SDimitry Andric   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
9270623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
9280623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
9290623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
9300623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
9310623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
9320623d748SDimitry Andric 
9330623d748SDimitry Andric   if (!D) {
93444290647SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
93544290647SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
93644290647SDimitry Andric     // disabled, mark the function as noinline.
93744290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
93844290647SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
93944290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
94044290647SDimitry Andric 
941f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
9420623d748SDimitry Andric     return;
9430623d748SDimitry Andric   }
9440623d748SDimitry Andric 
945302affcbSDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
946302affcbSDimitry Andric   // starting with the default for this optimization level.
947302affcbSDimitry Andric   bool ShouldAddOptNone =
948302affcbSDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
949302affcbSDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
950302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
951302affcbSDimitry Andric   ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
952302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
953302affcbSDimitry Andric 
954302affcbSDimitry Andric   if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
95544290647SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
95644290647SDimitry Andric 
95744290647SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
95844290647SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
95944290647SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
96044290647SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
96144290647SDimitry Andric 
96244290647SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
96344290647SDimitry Andric     // much of their semantics.
96444290647SDimitry Andric     if (D->hasAttr<NakedAttr>())
96544290647SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
96644290647SDimitry Andric 
96744290647SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
96844290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
96944290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
97044290647SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
9716122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
972f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
973f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
97459d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
97559d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
976f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
977f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
97859d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
97944290647SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
980f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
981f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
98244290647SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
98344290647SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
98444290647SDimitry Andric     // carry an explicit noinline attribute.
98544290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
98644290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
98744290647SDimitry Andric   } else {
98844290647SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
98944290647SDimitry Andric     // absence to mark things as noinline.
99044290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
99144290647SDimitry Andric       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
99244290647SDimitry Andric             return Redecl->isInlineSpecified();
99344290647SDimitry Andric           })) {
99444290647SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
99544290647SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
99644290647SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
99744290647SDimitry Andric                  !FD->isInlined() &&
99844290647SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
99944290647SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
100044290647SDimitry Andric       }
100144290647SDimitry Andric     }
10026122f3e6SDimitry Andric   }
10032754fe60SDimitry Andric 
100444290647SDimitry Andric   // Add other optimization related attributes if we are optimizing this
100544290647SDimitry Andric   // function.
100644290647SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
1007f785676fSDimitry Andric     if (D->hasAttr<ColdAttr>()) {
1008302affcbSDimitry Andric       if (!ShouldAddOptNone)
1009f785676fSDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
1010f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
1011f785676fSDimitry Andric     }
10123861d79fSDimitry Andric 
10133861d79fSDimitry Andric     if (D->hasAttr<MinSizeAttr>())
1014f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
101544290647SDimitry Andric   }
1016f22ef01cSRoman Divacky 
1017f37b6182SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
1018f785676fSDimitry Andric 
1019e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
1020e580952dSDimitry Andric   if (alignment)
1021e580952dSDimitry Andric     F->setAlignment(alignment);
1022e580952dSDimitry Andric 
10230623d748SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
10240623d748SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
10250623d748SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
10260623d748SDimitry Andric   // member function, set its alignment accordingly.
10270623d748SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
1028f22ef01cSRoman Divacky     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
1029f22ef01cSRoman Divacky       F->setAlignment(2);
1030f22ef01cSRoman Divacky   }
103144290647SDimitry Andric 
103244290647SDimitry Andric   // In the cross-dso CFI mode, we want !type attributes on definitions only.
103344290647SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
103444290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
103544290647SDimitry Andric       CreateFunctionTypeMetadata(FD, F);
10360623d748SDimitry Andric }
1037f22ef01cSRoman Divacky 
1038f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
1039f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
10400623d748SDimitry Andric   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
10412754fe60SDimitry Andric     setGlobalVisibility(GV, ND);
10422754fe60SDimitry Andric   else
10432754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1044f22ef01cSRoman Divacky 
10450623d748SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
104659d1ed5bSDimitry Andric     addUsedGlobal(GV);
104759d1ed5bSDimitry Andric }
104859d1ed5bSDimitry Andric 
104939d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D,
105039d628a0SDimitry Andric                                        llvm::GlobalValue *GV) {
105139d628a0SDimitry Andric   SetCommonAttributes(D, GV);
105239d628a0SDimitry Andric 
105339d628a0SDimitry Andric   // Process the dllexport attribute based on whether the original definition
105439d628a0SDimitry Andric   // (not necessarily the aliasee) was exported.
105539d628a0SDimitry Andric   if (D->hasAttr<DLLExportAttr>())
105639d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
105739d628a0SDimitry Andric }
105839d628a0SDimitry Andric 
105959d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D,
106059d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
106159d1ed5bSDimitry Andric   SetCommonAttributes(D, GO);
1062f22ef01cSRoman Divacky 
1063db17bf38SDimitry Andric   if (D) {
1064db17bf38SDimitry Andric     if (auto *GV = dyn_cast<llvm::GlobalVariable>(GO)) {
1065db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangBSSSectionAttr>())
1066db17bf38SDimitry Andric         GV->addAttribute("bss-section", SA->getName());
1067db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangDataSectionAttr>())
1068db17bf38SDimitry Andric         GV->addAttribute("data-section", SA->getName());
1069db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangRodataSectionAttr>())
1070db17bf38SDimitry Andric         GV->addAttribute("rodata-section", SA->getName());
1071db17bf38SDimitry Andric     }
1072db17bf38SDimitry Andric 
1073db17bf38SDimitry Andric     if (auto *F = dyn_cast<llvm::Function>(GO)) {
1074db17bf38SDimitry Andric       if (auto *SA = D->getAttr<PragmaClangTextSectionAttr>())
1075db17bf38SDimitry Andric        if (!D->getAttr<SectionAttr>())
1076db17bf38SDimitry Andric          F->addFnAttr("implicit-section-name", SA->getName());
1077db17bf38SDimitry Andric     }
1078db17bf38SDimitry Andric 
1079f22ef01cSRoman Divacky     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
108059d1ed5bSDimitry Andric       GO->setSection(SA->getName());
1081db17bf38SDimitry Andric   }
1082f22ef01cSRoman Divacky 
108397bc6c73SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1084f22ef01cSRoman Divacky }
1085f22ef01cSRoman Divacky 
1086f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1087f22ef01cSRoman Divacky                                                   llvm::Function *F,
1088f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
1089f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
1090f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
1091f22ef01cSRoman Divacky 
1092f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
1093f22ef01cSRoman Divacky 
109459d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
109559d1ed5bSDimitry Andric }
109659d1ed5bSDimitry Andric 
109759d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
109859d1ed5bSDimitry Andric                                          const NamedDecl *ND) {
109959d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
110059d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
1101c4394386SDimitry Andric   if (!isExternallyVisible(LV.getLinkage())) {
110259d1ed5bSDimitry Andric     // Don't set internal linkage on declarations.
110359d1ed5bSDimitry Andric   } else {
110459d1ed5bSDimitry Andric     if (ND->hasAttr<DLLImportAttr>()) {
110559d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
110659d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
110759d1ed5bSDimitry Andric     } else if (ND->hasAttr<DLLExportAttr>()) {
110859d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
110959d1ed5bSDimitry Andric     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
111059d1ed5bSDimitry Andric       // "extern_weak" is overloaded in LLVM; we probably should have
111159d1ed5bSDimitry Andric       // separate linkage types for this.
111259d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
111359d1ed5bSDimitry Andric     }
111459d1ed5bSDimitry Andric 
111559d1ed5bSDimitry Andric     // Set visibility on a declaration only if it's explicit.
111659d1ed5bSDimitry Andric     if (LV.isVisibilityExplicit())
111759d1ed5bSDimitry Andric       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
111859d1ed5bSDimitry Andric   }
1119f22ef01cSRoman Divacky }
1120f22ef01cSRoman Divacky 
1121e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
11220623d748SDimitry Andric                                                llvm::Function *F) {
11230623d748SDimitry Andric   // Only if we are checking indirect calls.
11240623d748SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
11250623d748SDimitry Andric     return;
11260623d748SDimitry Andric 
11270623d748SDimitry Andric   // Non-static class methods are handled via vtable pointer checks elsewhere.
11280623d748SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
11290623d748SDimitry Andric     return;
11300623d748SDimitry Andric 
11310623d748SDimitry Andric   // Additionally, if building with cross-DSO support...
11320623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
11330623d748SDimitry Andric     // Skip available_externally functions. They won't be codegen'ed in the
11340623d748SDimitry Andric     // current module anyway.
11350623d748SDimitry Andric     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
11360623d748SDimitry Andric       return;
11370623d748SDimitry Andric   }
11380623d748SDimitry Andric 
11390623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1140e7145dcbSDimitry Andric   F->addTypeMetadata(0, MD);
11410623d748SDimitry Andric 
11420623d748SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1143e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1144e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1145e7145dcbSDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
11460623d748SDimitry Andric }
11470623d748SDimitry Andric 
114839d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
114939d628a0SDimitry Andric                                           bool IsIncompleteFunction,
115039d628a0SDimitry Andric                                           bool IsThunk) {
115133956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
11523b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
11533b0f4066SDimitry Andric     // to the intrinsic's attributes.
115433956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
11553b0f4066SDimitry Andric     return;
11563b0f4066SDimitry Andric   }
11573b0f4066SDimitry Andric 
115859d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1159f22ef01cSRoman Divacky 
1160f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
1161dff0c46cSDimitry Andric     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1162f22ef01cSRoman Divacky 
116359d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
116459d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
116559d1ed5bSDimitry Andric   // GCC and does not actually return "this".
116639d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
116744290647SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1168f785676fSDimitry Andric     assert(!F->arg_empty() &&
1169f785676fSDimitry Andric            F->arg_begin()->getType()
1170f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1171f785676fSDimitry Andric            "unexpected this return");
1172f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1173f785676fSDimitry Andric   }
1174f785676fSDimitry Andric 
1175f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
1176f22ef01cSRoman Divacky   // overridden by a definition.
1177f22ef01cSRoman Divacky 
117859d1ed5bSDimitry Andric   setLinkageAndVisibilityForGV(F, FD);
11792754fe60SDimitry Andric 
1180db17bf38SDimitry Andric   if (FD->getAttr<PragmaClangTextSectionAttr>()) {
1181db17bf38SDimitry Andric     F->addFnAttr("implicit-section-name");
1182db17bf38SDimitry Andric   }
1183db17bf38SDimitry Andric 
1184f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1185f22ef01cSRoman Divacky     F->setSection(SA->getName());
1186f785676fSDimitry Andric 
1187e7145dcbSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1188f785676fSDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1189f785676fSDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
119020e90f04SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
1191f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
11920623d748SDimitry Andric 
1193e7145dcbSDimitry Andric     // A sane operator new returns a non-aliasing pointer.
1194e7145dcbSDimitry Andric     // FIXME: Also add NonNull attribute to the return value
1195e7145dcbSDimitry Andric     // for the non-nothrow forms?
1196e7145dcbSDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1197e7145dcbSDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1198e7145dcbSDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
119920e90f04SDimitry Andric       F->addAttribute(llvm::AttributeList::ReturnIndex,
1200e7145dcbSDimitry Andric                       llvm::Attribute::NoAlias);
1201e7145dcbSDimitry Andric   }
1202e7145dcbSDimitry Andric 
1203e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1204e7145dcbSDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1205e7145dcbSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1206e7145dcbSDimitry Andric     if (MD->isVirtual())
1207e7145dcbSDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1208e7145dcbSDimitry Andric 
120944290647SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
121044290647SDimitry Andric   // is handled with better precision by the receiving DSO.
121144290647SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso)
1212e7145dcbSDimitry Andric     CreateFunctionTypeMetadata(FD, F);
1213f22ef01cSRoman Divacky }
1214f22ef01cSRoman Divacky 
121559d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1216f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
1217f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
121897bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
1219f22ef01cSRoman Divacky }
1220f22ef01cSRoman Divacky 
122159d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
122259d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
122359d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
122497bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
122559d1ed5bSDimitry Andric }
122659d1ed5bSDimitry Andric 
122759d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
1228f37b6182SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
1229f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
123059d1ed5bSDimitry Andric   if (List.empty())
1231f22ef01cSRoman Divacky     return;
1232f22ef01cSRoman Divacky 
123359d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
1234dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
123559d1ed5bSDimitry Andric   UsedArray.resize(List.size());
123659d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1237f22ef01cSRoman Divacky     UsedArray[i] =
123844f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
123944f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1240f22ef01cSRoman Divacky   }
1241f22ef01cSRoman Divacky 
1242f22ef01cSRoman Divacky   if (UsedArray.empty())
1243f22ef01cSRoman Divacky     return;
124459d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1245f22ef01cSRoman Divacky 
124659d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
124759d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
124859d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1249f22ef01cSRoman Divacky 
1250f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
1251f22ef01cSRoman Divacky }
1252f22ef01cSRoman Divacky 
125359d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
125459d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
125559d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
125659d1ed5bSDimitry Andric }
125759d1ed5bSDimitry Andric 
1258f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
125939d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1260f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1261f785676fSDimitry Andric }
1262f785676fSDimitry Andric 
1263f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1264f785676fSDimitry Andric   llvm::SmallString<32> Opt;
1265f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
126639d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1267f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1268f785676fSDimitry Andric }
1269f785676fSDimitry Andric 
1270f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
1271f785676fSDimitry Andric   llvm::SmallString<24> Opt;
1272f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
127339d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1274f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1275f785676fSDimitry Andric }
1276f785676fSDimitry Andric 
1277139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules
1278139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
127939d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
128024d58133SDimitry Andric                                     SmallVectorImpl<llvm::MDNode *> &Metadata,
1281139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1282139f7f9bSDimitry Andric   // Import this module's parent.
128339d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1284f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1285139f7f9bSDimitry Andric   }
1286139f7f9bSDimitry Andric 
1287139f7f9bSDimitry Andric   // Import this module's dependencies.
1288139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
128939d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
1290f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1291139f7f9bSDimitry Andric   }
1292139f7f9bSDimitry Andric 
1293139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
1294139f7f9bSDimitry Andric   // described by this module.
1295f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
1296139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1297f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1298f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1299139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
130039d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1301139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
130239d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1303139f7f9bSDimitry Andric 
1304139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1305139f7f9bSDimitry Andric       continue;
1306139f7f9bSDimitry Andric     }
1307139f7f9bSDimitry Andric 
1308139f7f9bSDimitry Andric     // Link against a library.
1309f785676fSDimitry Andric     llvm::SmallString<24> Opt;
1310f785676fSDimitry Andric     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1311f785676fSDimitry Andric       Mod->LinkLibraries[I-1].Library, Opt);
131239d628a0SDimitry Andric     auto *OptString = llvm::MDString::get(Context, Opt);
1313139f7f9bSDimitry Andric     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1314139f7f9bSDimitry Andric   }
1315139f7f9bSDimitry Andric }
1316139f7f9bSDimitry Andric 
1317139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1318139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1319139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1320139f7f9bSDimitry Andric   // non-explicit child modules.
1321139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1322139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1323139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1324139f7f9bSDimitry Andric 
1325139f7f9bSDimitry Andric   // Seed the stack with imported modules.
1326f1a29dd3SDimitry Andric   for (Module *M : ImportedModules) {
1327f1a29dd3SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
1328f1a29dd3SDimitry Andric     // a header of that same module.
1329f1a29dd3SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1330f1a29dd3SDimitry Andric         !getLangOpts().isCompilingModule())
1331f1a29dd3SDimitry Andric       continue;
13328f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
13338f0fd8f6SDimitry Andric       Stack.push_back(M);
1334f1a29dd3SDimitry Andric   }
1335139f7f9bSDimitry Andric 
1336139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1337139f7f9bSDimitry Andric   // non-leaf modules.
1338139f7f9bSDimitry Andric   while (!Stack.empty()) {
1339f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1340139f7f9bSDimitry Andric 
1341139f7f9bSDimitry Andric     bool AnyChildren = false;
1342139f7f9bSDimitry Andric 
1343139f7f9bSDimitry Andric     // Visit the submodules of this module.
1344139f7f9bSDimitry Andric     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1345139f7f9bSDimitry Andric                                         SubEnd = Mod->submodule_end();
1346139f7f9bSDimitry Andric          Sub != SubEnd; ++Sub) {
1347139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1348139f7f9bSDimitry Andric       // linked against.
1349139f7f9bSDimitry Andric       if ((*Sub)->IsExplicit)
1350139f7f9bSDimitry Andric         continue;
1351139f7f9bSDimitry Andric 
135239d628a0SDimitry Andric       if (Visited.insert(*Sub).second) {
1353139f7f9bSDimitry Andric         Stack.push_back(*Sub);
1354139f7f9bSDimitry Andric         AnyChildren = true;
1355139f7f9bSDimitry Andric       }
1356139f7f9bSDimitry Andric     }
1357139f7f9bSDimitry Andric 
1358139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1359139f7f9bSDimitry Andric     // modules to link against.
1360139f7f9bSDimitry Andric     if (!AnyChildren) {
1361139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1362139f7f9bSDimitry Andric     }
1363139f7f9bSDimitry Andric   }
1364139f7f9bSDimitry Andric 
1365139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1366f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1367f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
136824d58133SDimitry Andric   SmallVector<llvm::MDNode *, 16> MetadataArgs;
1369139f7f9bSDimitry Andric   Visited.clear();
13708f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
13718f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
13728f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1373139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1374f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1375139f7f9bSDimitry Andric 
1376139f7f9bSDimitry Andric   // Add the linker options metadata flag.
137724d58133SDimitry Andric   auto *NMD = getModule().getOrInsertNamedMetadata("llvm.linker.options");
137824d58133SDimitry Andric   for (auto *MD : LinkerOptionsMetadata)
137924d58133SDimitry Andric     NMD->addOperand(MD);
1380139f7f9bSDimitry Andric }
1381139f7f9bSDimitry Andric 
1382f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1383f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1384f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1385f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1386f22ef01cSRoman Divacky 
1387f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1388139f7f9bSDimitry Andric     EmitDeferredVTables();
1389139f7f9bSDimitry Andric 
1390e7145dcbSDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
1391139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1392e7145dcbSDimitry Andric     // emitted that then need those vtables.
1393139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1394f22ef01cSRoman Divacky   }
1395f22ef01cSRoman Divacky 
1396e7145dcbSDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
139733956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
139833956c43SDimitry Andric     return;
1399139f7f9bSDimitry Andric 
140033956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
140133956c43SDimitry Andric   // work, it will not interfere with this.
1402f37b6182SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
140333956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
140433956c43SDimitry Andric 
1405f37b6182SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
14060623d748SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
14070623d748SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
14080623d748SDimitry Andric     // might had been created for another decl with the same mangled name but
14090623d748SDimitry Andric     // different type.
1410e7145dcbSDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
141144290647SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
1412e7145dcbSDimitry Andric 
1413e7145dcbSDimitry Andric     // In case of different address spaces, we may still get a cast, even with
1414e7145dcbSDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
1415e7145dcbSDimitry Andric     // GlobalValue.
141639d628a0SDimitry Andric     if (!GV)
141739d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
141839d628a0SDimitry Andric 
1419e7145dcbSDimitry Andric     // Make sure GetGlobalValue returned non-null.
1420e7145dcbSDimitry Andric     assert(GV);
1421e7145dcbSDimitry Andric 
1422f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1423f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1424f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1425f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1426f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1427f22ef01cSRoman Divacky     // ignore these cases.
1428e7145dcbSDimitry Andric     if (!GV->isDeclaration())
1429f22ef01cSRoman Divacky       continue;
1430f22ef01cSRoman Divacky 
1431f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
143259d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
143333956c43SDimitry Andric 
143433956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
143533956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
143633956c43SDimitry Andric     // ones are close together, which is convenient for testing.
143733956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
143833956c43SDimitry Andric       EmitDeferred();
143933956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
144033956c43SDimitry Andric     }
1441f22ef01cSRoman Divacky   }
1442f22ef01cSRoman Divacky }
1443f22ef01cSRoman Divacky 
1444f9448bf3SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
1445f9448bf3SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
1446f9448bf3SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
1447f9448bf3SDimitry Andric   // is not allowed to create new references to things that need to be emitted
1448f9448bf3SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1449f9448bf3SDimitry Andric 
1450f9448bf3SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1451f9448bf3SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
1452f9448bf3SDimitry Andric 
1453f9448bf3SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
1454f9448bf3SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
1455f9448bf3SDimitry Andric            "This queue should only contain external vtables");
1456f9448bf3SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
1457f9448bf3SDimitry Andric       VTables.GenerateClassData(RD);
1458f9448bf3SDimitry Andric   }
1459f9448bf3SDimitry Andric   OpportunisticVTables.clear();
1460f9448bf3SDimitry Andric }
1461f9448bf3SDimitry Andric 
14626122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
14636122f3e6SDimitry Andric   if (Annotations.empty())
14646122f3e6SDimitry Andric     return;
14656122f3e6SDimitry Andric 
14666122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
14676122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
14686122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
146959d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
147059d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
147159d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
14726122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
14736122f3e6SDimitry Andric }
14746122f3e6SDimitry Andric 
1475139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1476f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1477f785676fSDimitry Andric   if (AStr)
1478f785676fSDimitry Andric     return AStr;
14796122f3e6SDimitry Andric 
14806122f3e6SDimitry Andric   // Not found yet, create a new global.
1481dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
148259d1ed5bSDimitry Andric   auto *gv =
148359d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
148459d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
14856122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
1486e7145dcbSDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1487f785676fSDimitry Andric   AStr = gv;
14886122f3e6SDimitry Andric   return gv;
14896122f3e6SDimitry Andric }
14906122f3e6SDimitry Andric 
14916122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
14926122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14936122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
14946122f3e6SDimitry Andric   if (PLoc.isValid())
14956122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
14966122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
14976122f3e6SDimitry Andric }
14986122f3e6SDimitry Andric 
14996122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
15006122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
15016122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
15026122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
15036122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
15046122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
15056122f3e6SDimitry Andric }
15066122f3e6SDimitry Andric 
1507f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1508f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
15096122f3e6SDimitry Andric                                                 SourceLocation L) {
15106122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
15116122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
15126122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
15136122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1514f22ef01cSRoman Divacky 
1515f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1516f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
15176122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
15186122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
15196122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
15206122f3e6SDimitry Andric     LineNoCst
1521f22ef01cSRoman Divacky   };
152217a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1523f22ef01cSRoman Divacky }
1524f22ef01cSRoman Divacky 
15256122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
15266122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
15276122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
15286122f3e6SDimitry Andric   // Get the struct elements for these annotations.
152959d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
153059d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
15316122f3e6SDimitry Andric }
15326122f3e6SDimitry Andric 
153339d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
153439d628a0SDimitry Andric                                            SourceLocation Loc) const {
153539d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
153639d628a0SDimitry Andric   // Blacklist by function name.
153739d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
153839d628a0SDimitry Andric     return true;
153939d628a0SDimitry Andric   // Blacklist by location.
15400623d748SDimitry Andric   if (Loc.isValid())
154139d628a0SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Loc);
154239d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
154339d628a0SDimitry Andric   // it's located in the main file.
154439d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
154539d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
154639d628a0SDimitry Andric     return SanitizerBL.isBlacklistedFile(MainFile->getName());
154739d628a0SDimitry Andric   }
154839d628a0SDimitry Andric   return false;
154939d628a0SDimitry Andric }
155039d628a0SDimitry Andric 
155139d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
155239d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
155339d628a0SDimitry Andric                                            StringRef Category) const {
15548f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
15558f0fd8f6SDimitry Andric   if (!LangOpts.Sanitize.hasOneOf(
15568f0fd8f6SDimitry Andric           SanitizerKind::Address | SanitizerKind::KernelAddress))
155739d628a0SDimitry Andric     return false;
155839d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
155939d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
156039d628a0SDimitry Andric     return true;
156139d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
156239d628a0SDimitry Andric     return true;
156339d628a0SDimitry Andric   // Check global type.
156439d628a0SDimitry Andric   if (!Ty.isNull()) {
156539d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
156639d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
156739d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
156839d628a0SDimitry Andric       Ty = AT->getElementType();
156939d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
157039d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
157139d628a0SDimitry Andric     if (Ty->isRecordType()) {
157239d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
157339d628a0SDimitry Andric       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
157439d628a0SDimitry Andric         return true;
157539d628a0SDimitry Andric     }
157639d628a0SDimitry Andric   }
157739d628a0SDimitry Andric   return false;
157839d628a0SDimitry Andric }
157939d628a0SDimitry Andric 
158020e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
158120e90f04SDimitry Andric                                    StringRef Category) const {
158220e90f04SDimitry Andric   if (!LangOpts.XRayInstrument)
158320e90f04SDimitry Andric     return false;
158420e90f04SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
158520e90f04SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
158620e90f04SDimitry Andric   auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
158720e90f04SDimitry Andric   if (Loc.isValid())
158820e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
158920e90f04SDimitry Andric   if (Attr == ImbueAttr::NONE)
159020e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
159120e90f04SDimitry Andric   switch (Attr) {
159220e90f04SDimitry Andric   case ImbueAttr::NONE:
159320e90f04SDimitry Andric     return false;
159420e90f04SDimitry Andric   case ImbueAttr::ALWAYS:
159520e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
159620e90f04SDimitry Andric     break;
1597302affcbSDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
1598302affcbSDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
1599302affcbSDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
1600302affcbSDimitry Andric     break;
160120e90f04SDimitry Andric   case ImbueAttr::NEVER:
160220e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
160320e90f04SDimitry Andric     break;
160420e90f04SDimitry Andric   }
160520e90f04SDimitry Andric   return true;
160620e90f04SDimitry Andric }
160720e90f04SDimitry Andric 
160839d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1609e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
1610dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
161139d628a0SDimitry Andric     return true;
161239d628a0SDimitry Andric 
161339d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
161439d628a0SDimitry Andric }
161539d628a0SDimitry Andric 
161639d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
161739d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
161839d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
161939d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
162039d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
1621f22ef01cSRoman Divacky       return false;
1622e7145dcbSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
1623e7145dcbSDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
1624e7145dcbSDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1625e7145dcbSDimitry Andric       // A definition of an inline constexpr static data member may change
1626e7145dcbSDimitry Andric       // linkage later if it's redeclared outside the class.
1627e7145dcbSDimitry Andric       return false;
1628875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1629875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
1630875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1631875ed548SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1632875ed548SDimitry Andric     return false;
1633f22ef01cSRoman Divacky 
163439d628a0SDimitry Andric   return true;
1635f22ef01cSRoman Divacky }
1636f22ef01cSRoman Divacky 
16370623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
16383861d79fSDimitry Andric     const CXXUuidofExpr* E) {
16393861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
16403861d79fSDimitry Andric   // well-formed.
1641e7145dcbSDimitry Andric   StringRef Uuid = E->getUuidStr();
1642f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
1643f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
16443861d79fSDimitry Andric 
1645e7145dcbSDimitry Andric   // The UUID descriptor should be pointer aligned.
1646e7145dcbSDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
16470623d748SDimitry Andric 
16483861d79fSDimitry Andric   // Look for an existing global.
16493861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
16500623d748SDimitry Andric     return ConstantAddress(GV, Alignment);
16513861d79fSDimitry Andric 
165239d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
16533861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
16543861d79fSDimitry Andric 
165559d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
1656f785676fSDimitry Andric       getModule(), Init->getType(),
1657f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
165833956c43SDimitry Andric   if (supportsCOMDAT())
165933956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
16600623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
16613861d79fSDimitry Andric }
16623861d79fSDimitry Andric 
16630623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1664f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1665f22ef01cSRoman Divacky   assert(AA && "No alias?");
1666f22ef01cSRoman Divacky 
16670623d748SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
16686122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1669f22ef01cSRoman Divacky 
1670f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
1671f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
16723861d79fSDimitry Andric   if (Entry) {
16733861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
16740623d748SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
16750623d748SDimitry Andric     return ConstantAddress(Ptr, Alignment);
16763861d79fSDimitry Andric   }
1677f22ef01cSRoman Divacky 
1678f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1679f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
16803861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
16813861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
16822754fe60SDimitry Andric                                       /*ForVTable=*/false);
1683f22ef01cSRoman Divacky   else
1684f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
168559d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
168659d1ed5bSDimitry Andric                                     nullptr);
16873861d79fSDimitry Andric 
168859d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
1689f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1690f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
1691f22ef01cSRoman Divacky 
16920623d748SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
1693f22ef01cSRoman Divacky }
1694f22ef01cSRoman Divacky 
1695f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
169659d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
1697f22ef01cSRoman Divacky 
1698f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
1699f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
1700f22ef01cSRoman Divacky     return;
1701f22ef01cSRoman Divacky 
1702f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
1703f22ef01cSRoman Divacky   // emit it now.
1704f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
1705f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
1706f22ef01cSRoman Divacky 
1707e7145dcbSDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1708e7145dcbSDimitry Andric   if (Global->hasAttr<IFuncAttr>())
1709e7145dcbSDimitry Andric     return emitIFuncDefinition(GD);
1710e7145dcbSDimitry Andric 
17116122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
1712dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
171333956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
17146122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
17156122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
17166122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
17176122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
17186122f3e6SDimitry Andric         return;
17196122f3e6SDimitry Andric     } else {
1720e7145dcbSDimitry Andric       // We need to emit host-side 'shadows' for all global
1721e7145dcbSDimitry Andric       // device-side variables because the CUDA runtime needs their
1722e7145dcbSDimitry Andric       // size and host-side address in order to provide access to
1723e7145dcbSDimitry Andric       // their device-side incarnations.
1724e7145dcbSDimitry Andric 
1725e7145dcbSDimitry Andric       // So device-only functions are the only things we skip.
1726e7145dcbSDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1727e7145dcbSDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
17286122f3e6SDimitry Andric         return;
1729e7145dcbSDimitry Andric 
1730e7145dcbSDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1731e7145dcbSDimitry Andric              "Expected Variable or Function");
1732e580952dSDimitry Andric     }
1733e580952dSDimitry Andric   }
1734e580952dSDimitry Andric 
1735e7145dcbSDimitry Andric   if (LangOpts.OpenMP) {
1736ea942507SDimitry Andric     // If this is OpenMP device, check if it is legal to emit this global
1737ea942507SDimitry Andric     // normally.
1738ea942507SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1739ea942507SDimitry Andric       return;
1740e7145dcbSDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1741e7145dcbSDimitry Andric       if (MustBeEmitted(Global))
1742e7145dcbSDimitry Andric         EmitOMPDeclareReduction(DRD);
1743e7145dcbSDimitry Andric       return;
1744e7145dcbSDimitry Andric     }
1745e7145dcbSDimitry Andric   }
1746ea942507SDimitry Andric 
17476122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
174859d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1749f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
17506122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
17516122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1752f22ef01cSRoman Divacky         return;
17536122f3e6SDimitry Andric 
17546122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
175559d1ed5bSDimitry Andric 
175659d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
175759d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
175859d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
175959d1ed5bSDimitry Andric 
176059d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
176159d1ed5bSDimitry Andric                               /*DontDefer=*/false);
17626122f3e6SDimitry Andric       return;
17636122f3e6SDimitry Andric     }
1764f22ef01cSRoman Divacky   } else {
176559d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
1766f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1767e7145dcbSDimitry Andric     // We need to emit device-side global CUDA variables even if a
1768e7145dcbSDimitry Andric     // variable does not have a definition -- we still need to define
1769e7145dcbSDimitry Andric     // host-side shadow for it.
1770e7145dcbSDimitry Andric     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1771e7145dcbSDimitry Andric                            !VD->hasDefinition() &&
1772e7145dcbSDimitry Andric                            (VD->hasAttr<CUDAConstantAttr>() ||
1773e7145dcbSDimitry Andric                             VD->hasAttr<CUDADeviceAttr>());
1774e7145dcbSDimitry Andric     if (!MustEmitForCuda &&
1775e7145dcbSDimitry Andric         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1776e7145dcbSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1777e7145dcbSDimitry Andric       // If this declaration may have caused an inline variable definition to
1778e7145dcbSDimitry Andric       // change linkage, make sure that it's emitted.
1779e7145dcbSDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
1780e7145dcbSDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
1781e7145dcbSDimitry Andric         GetAddrOfGlobalVar(VD);
1782f22ef01cSRoman Divacky       return;
1783f22ef01cSRoman Divacky     }
1784e7145dcbSDimitry Andric   }
1785f22ef01cSRoman Divacky 
178639d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
178739d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
178839d628a0SDimitry Andric   // to benefit from cache locality.
178939d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1790f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
1791f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
1792f22ef01cSRoman Divacky     return;
1793f22ef01cSRoman Divacky   }
1794f22ef01cSRoman Divacky 
1795e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
1796e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
1797dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1798e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
1799e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
180059d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
1801e580952dSDimitry Andric   }
1802e580952dSDimitry Andric 
18036122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
1804f37b6182SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
180539d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
1806f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
180739d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
180839d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
180939d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
1810f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
181139d628a0SDimitry Andric   } else {
1812f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
1813f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
1814f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
1815f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
1816f22ef01cSRoman Divacky   }
1817f22ef01cSRoman Divacky }
1818f22ef01cSRoman Divacky 
181920e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
182020e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
182120e90f04SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
182220e90f04SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
182320e90f04SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
182420e90f04SDimitry Andric         return true;
182520e90f04SDimitry Andric 
182620e90f04SDimitry Andric   return false;
182720e90f04SDimitry Andric }
182820e90f04SDimitry Andric 
1829f8254f43SDimitry Andric namespace {
1830f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
1831f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1832f8254f43SDimitry Andric     const StringRef Name;
1833dff0c46cSDimitry Andric     const Builtin::Context &BI;
1834f8254f43SDimitry Andric     bool Result;
1835dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1836dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
1837f8254f43SDimitry Andric     }
1838f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1839f8254f43SDimitry Andric 
1840f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
1841dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
1842dff0c46cSDimitry Andric       if (!FD)
1843f8254f43SDimitry Andric         return true;
1844dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1845dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
1846dff0c46cSDimitry Andric         Result = true;
1847dff0c46cSDimitry Andric         return false;
1848dff0c46cSDimitry Andric       }
1849dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
18503dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1851f8254f43SDimitry Andric         return true;
18520623d748SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
1853dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
1854dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1855f8254f43SDimitry Andric         Result = true;
1856f8254f43SDimitry Andric         return false;
1857f8254f43SDimitry Andric       }
1858f8254f43SDimitry Andric       return true;
1859f8254f43SDimitry Andric     }
1860f8254f43SDimitry Andric   };
18610623d748SDimitry Andric 
186220e90f04SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
18630623d748SDimitry Andric   struct DLLImportFunctionVisitor
18640623d748SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
18650623d748SDimitry Andric     bool SafeToInline = true;
18660623d748SDimitry Andric 
186744290647SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
186844290647SDimitry Andric 
18690623d748SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
187020e90f04SDimitry Andric       if (VD->getTLSKind()) {
18710623d748SDimitry Andric         // A thread-local variable cannot be imported.
187220e90f04SDimitry Andric         SafeToInline = false;
18730623d748SDimitry Andric         return SafeToInline;
18740623d748SDimitry Andric       }
18750623d748SDimitry Andric 
187620e90f04SDimitry Andric       // A variable definition might imply a destructor call.
187720e90f04SDimitry Andric       if (VD->isThisDeclarationADefinition())
187820e90f04SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
187920e90f04SDimitry Andric 
188020e90f04SDimitry Andric       return SafeToInline;
188120e90f04SDimitry Andric     }
188220e90f04SDimitry Andric 
188320e90f04SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
188420e90f04SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
188520e90f04SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
188620e90f04SDimitry Andric       return SafeToInline;
188720e90f04SDimitry Andric     }
188820e90f04SDimitry Andric 
18890623d748SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
18900623d748SDimitry Andric       ValueDecl *VD = E->getDecl();
18910623d748SDimitry Andric       if (isa<FunctionDecl>(VD))
18920623d748SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
18930623d748SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
18940623d748SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
18950623d748SDimitry Andric       return SafeToInline;
18960623d748SDimitry Andric     }
189720e90f04SDimitry Andric 
189844290647SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
189944290647SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
190044290647SDimitry Andric       return SafeToInline;
190144290647SDimitry Andric     }
190220e90f04SDimitry Andric 
190320e90f04SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
190420e90f04SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
190520e90f04SDimitry Andric       if (!M) {
190620e90f04SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
190720e90f04SDimitry Andric         SafeToInline = true;
190820e90f04SDimitry Andric       } else {
190920e90f04SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
191020e90f04SDimitry Andric       }
191120e90f04SDimitry Andric       return SafeToInline;
191220e90f04SDimitry Andric     }
191320e90f04SDimitry Andric 
19140623d748SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
19150623d748SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
19160623d748SDimitry Andric       return SafeToInline;
19170623d748SDimitry Andric     }
191820e90f04SDimitry Andric 
19190623d748SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
19200623d748SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
19210623d748SDimitry Andric       return SafeToInline;
19220623d748SDimitry Andric     }
19230623d748SDimitry Andric   };
1924f8254f43SDimitry Andric }
1925f8254f43SDimitry Andric 
1926dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
1927dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
1928dff0c46cSDimitry Andric // ends up pointing to itself.
1929f8254f43SDimitry Andric bool
1930dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1931dff0c46cSDimitry Andric   StringRef Name;
1932dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1933dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
1934dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1935dff0c46cSDimitry Andric     if (!Attr)
1936f8254f43SDimitry Andric       return false;
1937dff0c46cSDimitry Andric     Name = Attr->getLabel();
1938dff0c46cSDimitry Andric   } else {
1939dff0c46cSDimitry Andric     Name = FD->getName();
1940dff0c46cSDimitry Andric   }
1941f8254f43SDimitry Andric 
1942dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1943dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1944f8254f43SDimitry Andric   return Walker.Result;
1945f8254f43SDimitry Andric }
1946f8254f43SDimitry Andric 
194744290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1948f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1949f8254f43SDimitry Andric     return true;
195059d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
195159d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1952f8254f43SDimitry Andric     return false;
19530623d748SDimitry Andric 
19540623d748SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
19550623d748SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
19560623d748SDimitry Andric     DLLImportFunctionVisitor Visitor;
19570623d748SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
19580623d748SDimitry Andric     if (!Visitor.SafeToInline)
19590623d748SDimitry Andric       return false;
196044290647SDimitry Andric 
196144290647SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
196244290647SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
196344290647SDimitry Andric       // check above can't see them. Check for them manually here.
196444290647SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
196544290647SDimitry Andric         if (isa<FieldDecl>(Member))
196644290647SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
196744290647SDimitry Andric             return false;
196844290647SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
196944290647SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
197044290647SDimitry Andric           return false;
197144290647SDimitry Andric     }
19720623d748SDimitry Andric   }
19730623d748SDimitry Andric 
1974f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
1975f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
1976f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
1977f8254f43SDimitry Andric   // implementation.
1978f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
1979dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
1980f8254f43SDimitry Andric }
1981f8254f43SDimitry Andric 
1982f9448bf3SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
1983f9448bf3SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
1984f9448bf3SDimitry Andric }
1985f9448bf3SDimitry Andric 
198659d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
198759d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
1988f22ef01cSRoman Divacky 
1989f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1990f22ef01cSRoman Divacky                                  Context.getSourceManager(),
1991f22ef01cSRoman Divacky                                  "Generating code for declaration");
1992f22ef01cSRoman Divacky 
1993f785676fSDimitry Andric   if (isa<FunctionDecl>(D)) {
1994ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
1995ffd1746dSEd Schouten     // linkage.
1996f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
1997ffd1746dSEd Schouten       return;
1998ffd1746dSEd Schouten 
199959d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
2000bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
2001bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
200259d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
200339d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
200459d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
200539d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
2006bd5abe19SDimitry Andric       else
200759d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
2008bd5abe19SDimitry Andric 
2009f22ef01cSRoman Divacky       if (Method->isVirtual())
2010f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
2011f22ef01cSRoman Divacky 
2012bd5abe19SDimitry Andric       return;
2013ffd1746dSEd Schouten     }
2014f22ef01cSRoman Divacky 
201559d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
2016ffd1746dSEd Schouten   }
2017f22ef01cSRoman Divacky 
201859d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
2019e7145dcbSDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
2020f22ef01cSRoman Divacky 
20216122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
2022f22ef01cSRoman Divacky }
2023f22ef01cSRoman Divacky 
20240623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
20250623d748SDimitry Andric                                                       llvm::Function *NewFn);
20260623d748SDimitry Andric 
2027f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
2028f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
2029f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2030f22ef01cSRoman Divacky /// bitcasted to the right type.
2031f22ef01cSRoman Divacky ///
2032f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2033f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
203420e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
203520e90f04SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
203620e90f04SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
203744290647SDimitry Andric     ForDefinition_t IsForDefinition) {
2038f785676fSDimitry Andric   const Decl *D = GD.getDecl();
2039f785676fSDimitry Andric 
2040f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2041f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2042f22ef01cSRoman Divacky   if (Entry) {
20433861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2044f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
2045f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
2046f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2047f22ef01cSRoman Divacky     }
2048f22ef01cSRoman Divacky 
204939d628a0SDimitry Andric     // Handle dropped DLL attributes.
205039d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
205139d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
205239d628a0SDimitry Andric 
20530623d748SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
20540623d748SDimitry Andric     // error.
20550623d748SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
20560623d748SDimitry Andric       GlobalDecl OtherGD;
2057e7145dcbSDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2058e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
20590623d748SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
20600623d748SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
20610623d748SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
20620623d748SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
20630623d748SDimitry Andric         getDiags().Report(D->getLocation(),
20640623d748SDimitry Andric                           diag::err_duplicate_mangled_name);
20650623d748SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
20660623d748SDimitry Andric                           diag::note_previous_definition);
20670623d748SDimitry Andric       }
20680623d748SDimitry Andric     }
20690623d748SDimitry Andric 
20700623d748SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
20710623d748SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
2072f22ef01cSRoman Divacky       return Entry;
20730623d748SDimitry Andric     }
2074f22ef01cSRoman Divacky 
2075f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
20760623d748SDimitry Andric     // (If function is requested for a definition, we always need to create a new
20770623d748SDimitry Andric     // function, not just return a bitcast.)
20780623d748SDimitry Andric     if (!IsForDefinition)
207917a519f9SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2080f22ef01cSRoman Divacky   }
2081f22ef01cSRoman Divacky 
2082f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
2083f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
2084f22ef01cSRoman Divacky   // sure not to try to set attributes.
2085f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
2086f22ef01cSRoman Divacky 
20876122f3e6SDimitry Andric   llvm::FunctionType *FTy;
2088f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
2089f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
2090f22ef01cSRoman Divacky   } else {
2091bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
2092f22ef01cSRoman Divacky     IsIncompleteFunction = true;
2093f22ef01cSRoman Divacky   }
2094ffd1746dSEd Schouten 
20950623d748SDimitry Andric   llvm::Function *F =
20960623d748SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
20970623d748SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
20980623d748SDimitry Andric 
20990623d748SDimitry Andric   // If we already created a function with the same mangled name (but different
21000623d748SDimitry Andric   // type) before, take its name and add it to the list of functions to be
21010623d748SDimitry Andric   // replaced with F at the end of CodeGen.
21020623d748SDimitry Andric   //
21030623d748SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
21040623d748SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
21050623d748SDimitry Andric   if (Entry) {
21060623d748SDimitry Andric     F->takeName(Entry);
21070623d748SDimitry Andric 
21080623d748SDimitry Andric     // This might be an implementation of a function without a prototype, in
21090623d748SDimitry Andric     // which case, try to do special replacement of calls which match the new
21100623d748SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
21110623d748SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
21120623d748SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
21130623d748SDimitry Andric     // dropping arguments.
21140623d748SDimitry Andric     if (!Entry->use_empty()) {
21150623d748SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
21160623d748SDimitry Andric       Entry->removeDeadConstantUsers();
21170623d748SDimitry Andric     }
21180623d748SDimitry Andric 
21190623d748SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
21200623d748SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
21210623d748SDimitry Andric     addGlobalValReplacement(Entry, BC);
21220623d748SDimitry Andric   }
21230623d748SDimitry Andric 
2124f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
2125f785676fSDimitry Andric   if (D)
212639d628a0SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
212720e90f04SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
212820e90f04SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2129f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2130139f7f9bSDimitry Andric   }
2131f22ef01cSRoman Divacky 
213259d1ed5bSDimitry Andric   if (!DontDefer) {
213359d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
213459d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
213559d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
213659d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
213759d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
213859d1ed5bSDimitry Andric                                            GD.getDtorType()))
2139f37b6182SDimitry Andric       addDeferredDeclToEmit(GD);
214059d1ed5bSDimitry Andric 
2141f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
2142f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
2143f22ef01cSRoman Divacky     // of the file.
214459d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
2145f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
214659d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
214759d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
214859d1ed5bSDimitry Andric       // don't need it anymore).
2149f37b6182SDimitry Andric       addDeferredDeclToEmit(DDI->second);
2150f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
21512754fe60SDimitry Andric 
21522754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
21532754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
21542754fe60SDimitry Andric       // we might not find a top-level definition:
21552754fe60SDimitry Andric       //   - member functions defined inline in their classes
21562754fe60SDimitry Andric       //   - friend functions defined inline in some class
21572754fe60SDimitry Andric       //   - special member functions with implicit definitions
21582754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
21592754fe60SDimitry Andric       // this will be unnecessary.
21602754fe60SDimitry Andric       //
216159d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
216239d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
2163f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
21642754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
216539d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
216639d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
21672754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
216839d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
2169f37b6182SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
21702754fe60SDimitry Andric             break;
2171f22ef01cSRoman Divacky           }
2172f22ef01cSRoman Divacky         }
217339d628a0SDimitry Andric       }
2174f22ef01cSRoman Divacky     }
217559d1ed5bSDimitry Andric   }
2176f22ef01cSRoman Divacky 
2177f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
2178f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
2179f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
2180f22ef01cSRoman Divacky     return F;
2181f22ef01cSRoman Divacky   }
2182f22ef01cSRoman Divacky 
218317a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2184f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
2185f22ef01cSRoman Divacky }
2186f22ef01cSRoman Divacky 
2187f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2188f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
2189f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
2190f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
21916122f3e6SDimitry Andric                                                  llvm::Type *Ty,
219259d1ed5bSDimitry Andric                                                  bool ForVTable,
21930623d748SDimitry Andric                                                  bool DontDefer,
219444290647SDimitry Andric                                               ForDefinition_t IsForDefinition) {
2195f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
21960623d748SDimitry Andric   if (!Ty) {
21970623d748SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
21980623d748SDimitry Andric     auto CanonTy = Context.getCanonicalType(FD->getType());
21990623d748SDimitry Andric     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
22000623d748SDimitry Andric   }
2201ffd1746dSEd Schouten 
22026122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
22030623d748SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
220420e90f04SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
22050623d748SDimitry Andric                                  IsForDefinition);
2206f22ef01cSRoman Divacky }
2207f22ef01cSRoman Divacky 
220844290647SDimitry Andric static const FunctionDecl *
220944290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
221044290647SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
221144290647SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
221244290647SDimitry Andric 
221344290647SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
221444290647SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
221544290647SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
221644290647SDimitry Andric       return FD;
221744290647SDimitry Andric 
221844290647SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
221944290647SDimitry Andric     return nullptr;
222044290647SDimitry Andric 
222144290647SDimitry Andric   // Demangle the premangled name from getTerminateFn()
222244290647SDimitry Andric   IdentifierInfo &CXXII =
222344290647SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
222444290647SDimitry Andric           ? C.Idents.get("terminate")
222544290647SDimitry Andric           : C.Idents.get(Name);
222644290647SDimitry Andric 
222744290647SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
222844290647SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
222944290647SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
223044290647SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
223144290647SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
223244290647SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
223344290647SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
223444290647SDimitry Andric             break;
223544290647SDimitry Andric 
223644290647SDimitry Andric       if (ND)
223744290647SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
223844290647SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
223944290647SDimitry Andric             return FD;
224044290647SDimitry Andric     }
224144290647SDimitry Andric   }
224244290647SDimitry Andric 
224344290647SDimitry Andric   return nullptr;
224444290647SDimitry Andric }
224544290647SDimitry Andric 
2246f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
2247f22ef01cSRoman Divacky /// type and name.
2248f22ef01cSRoman Divacky llvm::Constant *
224944290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
225020e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs,
225144290647SDimitry Andric                                      bool Local) {
225259d1ed5bSDimitry Andric   llvm::Constant *C =
225359d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
225444290647SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
225544290647SDimitry Andric                               ExtraAttrs);
225644290647SDimitry Andric 
225744290647SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
225844290647SDimitry Andric     if (F->empty()) {
2259139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
226044290647SDimitry Andric 
226144290647SDimitry Andric       if (!Local && getTriple().isOSBinFormatCOFF() &&
226244290647SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
226344290647SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
226444290647SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
226544290647SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
226644290647SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
226744290647SDimitry Andric         }
226844290647SDimitry Andric       }
226944290647SDimitry Andric     }
227044290647SDimitry Andric   }
227144290647SDimitry Andric 
2272139f7f9bSDimitry Andric   return C;
2273f22ef01cSRoman Divacky }
2274f22ef01cSRoman Divacky 
227539d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
227639d628a0SDimitry Andric /// type and name.
227739d628a0SDimitry Andric llvm::Constant *
227820e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
227920e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs) {
228039d628a0SDimitry Andric   llvm::Constant *C =
228139d628a0SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
228239d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
228339d628a0SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
228439d628a0SDimitry Andric     if (F->empty())
228539d628a0SDimitry Andric       F->setCallingConv(getBuiltinCC());
228639d628a0SDimitry Andric   return C;
228739d628a0SDimitry Andric }
228839d628a0SDimitry Andric 
2289dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
2290dff0c46cSDimitry Andric /// as a constant.
2291dff0c46cSDimitry Andric ///
2292dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
2293dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
2294dff0c46cSDimitry Andric /// not written to during its construction.
2295dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2296dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2297f22ef01cSRoman Divacky     return false;
2298bd5abe19SDimitry Andric 
2299dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
2300dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
2301dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2302dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
2303dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
2304f22ef01cSRoman Divacky   }
2305bd5abe19SDimitry Andric 
2306f22ef01cSRoman Divacky   return true;
2307f22ef01cSRoman Divacky }
2308f22ef01cSRoman Divacky 
2309f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2310f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
2311f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2312f22ef01cSRoman Divacky /// bitcasted to the right type.
2313f22ef01cSRoman Divacky ///
2314f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2315f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
2316e7145dcbSDimitry Andric ///
2317e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with
2318e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
2319e7145dcbSDimitry Andric /// mangled name but some other type.
2320f22ef01cSRoman Divacky llvm::Constant *
23216122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
23226122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
2323e7145dcbSDimitry Andric                                      const VarDecl *D,
232444290647SDimitry Andric                                      ForDefinition_t IsForDefinition) {
2325f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2326f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2327f22ef01cSRoman Divacky   if (Entry) {
23283861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2329f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
2330f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2331f22ef01cSRoman Divacky     }
2332f22ef01cSRoman Divacky 
233339d628a0SDimitry Andric     // Handle dropped DLL attributes.
233439d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
233539d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
233639d628a0SDimitry Andric 
2337f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
2338f22ef01cSRoman Divacky       return Entry;
2339f22ef01cSRoman Divacky 
2340e7145dcbSDimitry Andric     // If there are two attempts to define the same mangled name, issue an
2341e7145dcbSDimitry Andric     // error.
2342e7145dcbSDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
2343e7145dcbSDimitry Andric       GlobalDecl OtherGD;
2344e7145dcbSDimitry Andric       const VarDecl *OtherD;
2345e7145dcbSDimitry Andric 
2346e7145dcbSDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2347e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
2348e7145dcbSDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2349e7145dcbSDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2350e7145dcbSDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2351e7145dcbSDimitry Andric           OtherD->hasInit() &&
2352e7145dcbSDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
2353e7145dcbSDimitry Andric         getDiags().Report(D->getLocation(),
2354e7145dcbSDimitry Andric                           diag::err_duplicate_mangled_name);
2355e7145dcbSDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
2356e7145dcbSDimitry Andric                           diag::note_previous_definition);
2357e7145dcbSDimitry Andric       }
2358e7145dcbSDimitry Andric     }
2359e7145dcbSDimitry Andric 
2360f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
2361f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2362f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2363f785676fSDimitry Andric 
2364e7145dcbSDimitry Andric     // (If global is requested for a definition, we always need to create a new
2365e7145dcbSDimitry Andric     // global, not just return a bitcast.)
2366e7145dcbSDimitry Andric     if (!IsForDefinition)
2367f22ef01cSRoman Divacky       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2368f22ef01cSRoman Divacky   }
2369f22ef01cSRoman Divacky 
2370c4394386SDimitry Andric   auto AddrSpace = GetGlobalVarAddressSpace(D);
2371c4394386SDimitry Andric   auto TargetAddrSpace = getContext().getTargetAddressSpace(AddrSpace);
2372c4394386SDimitry Andric 
237359d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
237459d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
237559d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
2376c4394386SDimitry Andric       llvm::GlobalVariable::NotThreadLocal, TargetAddrSpace);
237759d1ed5bSDimitry Andric 
2378e7145dcbSDimitry Andric   // If we already created a global with the same mangled name (but different
2379e7145dcbSDimitry Andric   // type) before, take its name and remove it from its parent.
2380e7145dcbSDimitry Andric   if (Entry) {
2381e7145dcbSDimitry Andric     GV->takeName(Entry);
2382e7145dcbSDimitry Andric 
2383e7145dcbSDimitry Andric     if (!Entry->use_empty()) {
2384e7145dcbSDimitry Andric       llvm::Constant *NewPtrForOldDecl =
2385e7145dcbSDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2386e7145dcbSDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2387e7145dcbSDimitry Andric     }
2388e7145dcbSDimitry Andric 
2389e7145dcbSDimitry Andric     Entry->eraseFromParent();
2390e7145dcbSDimitry Andric   }
2391e7145dcbSDimitry Andric 
2392f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
2393f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
2394f22ef01cSRoman Divacky   // of the file.
239559d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
2396f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
2397f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2398f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
2399f37b6182SDimitry Andric     addDeferredDeclToEmit(DDI->second);
2400f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
2401f22ef01cSRoman Divacky   }
2402f22ef01cSRoman Divacky 
2403f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
2404f22ef01cSRoman Divacky   if (D) {
2405f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
2406f22ef01cSRoman Divacky     // handling.
2407dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
2408f22ef01cSRoman Divacky 
240933956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
241033956c43SDimitry Andric 
241159d1ed5bSDimitry Andric     setLinkageAndVisibilityForGV(GV, D);
24122754fe60SDimitry Andric 
2413284c1978SDimitry Andric     if (D->getTLSKind()) {
2414284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
24150623d748SDimitry Andric         CXXThreadLocals.push_back(D);
24167ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
2417f22ef01cSRoman Divacky     }
2418f785676fSDimitry Andric 
2419f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
2420f785676fSDimitry Andric     // inline initializers as definitions.
242159d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2422f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
2423284c1978SDimitry Andric     }
2424f22ef01cSRoman Divacky 
242559d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
242644290647SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
242759d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
242859d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
242959d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
243059d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
243159d1ed5bSDimitry Andric   }
243259d1ed5bSDimitry Andric 
2433c4394386SDimitry Andric   auto ExpectedAS =
2434c4394386SDimitry Andric       D ? D->getType().getAddressSpace()
2435c4394386SDimitry Andric         : static_cast<unsigned>(LangOpts.OpenCL ? LangAS::opencl_global
2436c4394386SDimitry Andric                                                 : LangAS::Default);
2437c4394386SDimitry Andric   assert(getContext().getTargetAddressSpace(ExpectedAS) ==
2438c4394386SDimitry Andric          Ty->getPointerAddressSpace());
2439c4394386SDimitry Andric   if (AddrSpace != ExpectedAS)
2440c4394386SDimitry Andric     return getTargetCodeGenInfo().performAddrSpaceCast(*this, GV, AddrSpace,
2441c4394386SDimitry Andric                                                        ExpectedAS, Ty);
2442f785676fSDimitry Andric 
2443f22ef01cSRoman Divacky   return GV;
2444f22ef01cSRoman Divacky }
2445f22ef01cSRoman Divacky 
24460623d748SDimitry Andric llvm::Constant *
24470623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
244844290647SDimitry Andric                                ForDefinition_t IsForDefinition) {
244944290647SDimitry Andric   const Decl *D = GD.getDecl();
245044290647SDimitry Andric   if (isa<CXXConstructorDecl>(D))
245144290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
24520623d748SDimitry Andric                                 getFromCtorType(GD.getCtorType()),
24530623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
24540623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
245544290647SDimitry Andric   else if (isa<CXXDestructorDecl>(D))
245644290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
24570623d748SDimitry Andric                                 getFromDtorType(GD.getDtorType()),
24580623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
24590623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
246044290647SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
24610623d748SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
246244290647SDimitry Andric         cast<CXXMethodDecl>(D));
24630623d748SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
24640623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
24650623d748SDimitry Andric                              IsForDefinition);
246644290647SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
24670623d748SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
24680623d748SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
24690623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
24700623d748SDimitry Andric                              IsForDefinition);
24710623d748SDimitry Andric   } else
247244290647SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2473e7145dcbSDimitry Andric                               IsForDefinition);
24740623d748SDimitry Andric }
2475f22ef01cSRoman Divacky 
24762754fe60SDimitry Andric llvm::GlobalVariable *
24776122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
24786122f3e6SDimitry Andric                                       llvm::Type *Ty,
24792754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
24802754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
248159d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
24822754fe60SDimitry Andric 
24832754fe60SDimitry Andric   if (GV) {
24842754fe60SDimitry Andric     // Check if the variable has the right type.
24852754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
24862754fe60SDimitry Andric       return GV;
24872754fe60SDimitry Andric 
24882754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
24892754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
24902754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
24912754fe60SDimitry Andric     OldGV = GV;
24922754fe60SDimitry Andric   }
24932754fe60SDimitry Andric 
24942754fe60SDimitry Andric   // Create a new variable.
24952754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
249659d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
24972754fe60SDimitry Andric 
24982754fe60SDimitry Andric   if (OldGV) {
24992754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
25002754fe60SDimitry Andric     GV->takeName(OldGV);
25012754fe60SDimitry Andric 
25022754fe60SDimitry Andric     if (!OldGV->use_empty()) {
25032754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
25042754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
25052754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
25062754fe60SDimitry Andric     }
25072754fe60SDimitry Andric 
25082754fe60SDimitry Andric     OldGV->eraseFromParent();
25092754fe60SDimitry Andric   }
25102754fe60SDimitry Andric 
251133956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
251233956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
251333956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
251433956c43SDimitry Andric 
25152754fe60SDimitry Andric   return GV;
25162754fe60SDimitry Andric }
25172754fe60SDimitry Andric 
2518f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2519f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
2520cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
2521e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed
2522e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
2523e7145dcbSDimitry Andric /// variable with the same mangled name but some other type.
2524f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2525e7145dcbSDimitry Andric                                                   llvm::Type *Ty,
252644290647SDimitry Andric                                            ForDefinition_t IsForDefinition) {
2527f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
2528f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
252959d1ed5bSDimitry Andric   if (!Ty)
2530f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
2531f22ef01cSRoman Divacky 
25326122f3e6SDimitry Andric   llvm::PointerType *PTy =
25333b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2534f22ef01cSRoman Divacky 
25356122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2536e7145dcbSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2537f22ef01cSRoman Divacky }
2538f22ef01cSRoman Divacky 
2539f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
2540f22ef01cSRoman Divacky /// specified type and name.
2541f22ef01cSRoman Divacky llvm::Constant *
25426122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
25436122f3e6SDimitry Andric                                      StringRef Name) {
254459d1ed5bSDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2545f22ef01cSRoman Divacky }
2546f22ef01cSRoman Divacky 
2547f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2548f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
2549f22ef01cSRoman Divacky 
25506122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2551e7145dcbSDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2552e7145dcbSDimitry Andric 
2553e7145dcbSDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
2554e7145dcbSDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
2555e7145dcbSDimitry Andric   // definition).
2556e7145dcbSDimitry Andric   if (GV && !GV->isDeclaration())
2557e7145dcbSDimitry Andric     return;
2558e7145dcbSDimitry Andric 
2559e7145dcbSDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
2560e7145dcbSDimitry Andric   // deferred declarations table to be emitted if needed later.
2561e7145dcbSDimitry Andric   if (!MustBeEmitted(D) && !GV) {
2562f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
2563f22ef01cSRoman Divacky       return;
2564f22ef01cSRoman Divacky   }
2565f22ef01cSRoman Divacky 
2566f22ef01cSRoman Divacky   // The tentative definition is the only definition.
2567f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
2568f22ef01cSRoman Divacky }
2569f22ef01cSRoman Divacky 
25706122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
25712754fe60SDimitry Andric   return Context.toCharUnitsFromBits(
25720623d748SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
2573f22ef01cSRoman Divacky }
2574f22ef01cSRoman Divacky 
2575c4394386SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D) {
2576c4394386SDimitry Andric   unsigned AddrSpace;
2577c4394386SDimitry Andric   if (LangOpts.OpenCL) {
2578c4394386SDimitry Andric     AddrSpace = D ? D->getType().getAddressSpace()
2579c4394386SDimitry Andric                   : static_cast<unsigned>(LangAS::opencl_global);
2580c4394386SDimitry Andric     assert(AddrSpace == LangAS::opencl_global ||
2581c4394386SDimitry Andric            AddrSpace == LangAS::opencl_constant ||
2582c4394386SDimitry Andric            AddrSpace == LangAS::opencl_local ||
2583c4394386SDimitry Andric            AddrSpace >= LangAS::FirstTargetAddressSpace);
2584c4394386SDimitry Andric     return AddrSpace;
25857ae0e2c9SDimitry Andric   }
25867ae0e2c9SDimitry Andric 
2587c4394386SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
2588c4394386SDimitry Andric     if (D && D->hasAttr<CUDAConstantAttr>())
2589c4394386SDimitry Andric       return LangAS::cuda_constant;
2590c4394386SDimitry Andric     else if (D && D->hasAttr<CUDASharedAttr>())
2591c4394386SDimitry Andric       return LangAS::cuda_shared;
2592c4394386SDimitry Andric     else
2593c4394386SDimitry Andric       return LangAS::cuda_device;
2594c4394386SDimitry Andric   }
2595c4394386SDimitry Andric 
2596c4394386SDimitry Andric   return getTargetCodeGenInfo().getGlobalVarAddressSpace(*this, D);
25977ae0e2c9SDimitry Andric }
25987ae0e2c9SDimitry Andric 
2599284c1978SDimitry Andric template<typename SomeDecl>
2600284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2601284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
2602284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
2603284c1978SDimitry Andric     return;
2604284c1978SDimitry Andric 
2605284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
2606284c1978SDimitry Andric   // the name existing.
2607284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
2608284c1978SDimitry Andric     return;
2609284c1978SDimitry Andric 
2610284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
2611f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2612284c1978SDimitry Andric     return;
2613284c1978SDimitry Andric 
2614284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
2615284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
2616f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
2617284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2618284c1978SDimitry Andric     return;
2619284c1978SDimitry Andric 
2620284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
2621284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
2622284c1978SDimitry Andric   // mangled name if nothing else is using that name.
2623284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
2624284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2625284c1978SDimitry Andric 
2626284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
2627284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
2628284c1978SDimitry Andric   if (!R.second)
262959d1ed5bSDimitry Andric     R.first->second = nullptr;
2630284c1978SDimitry Andric }
2631284c1978SDimitry Andric 
263233956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
263333956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
263433956c43SDimitry Andric     return false;
263533956c43SDimitry Andric 
263633956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
263733956c43SDimitry Andric     return true;
263833956c43SDimitry Andric 
263933956c43SDimitry Andric   GVALinkage Linkage;
264033956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
264133956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
264233956c43SDimitry Andric   else
264333956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
264433956c43SDimitry Andric 
264533956c43SDimitry Andric   switch (Linkage) {
264633956c43SDimitry Andric   case GVA_Internal:
264733956c43SDimitry Andric   case GVA_AvailableExternally:
264833956c43SDimitry Andric   case GVA_StrongExternal:
264933956c43SDimitry Andric     return false;
265033956c43SDimitry Andric   case GVA_DiscardableODR:
265133956c43SDimitry Andric   case GVA_StrongODR:
265233956c43SDimitry Andric     return true;
265333956c43SDimitry Andric   }
265433956c43SDimitry Andric   llvm_unreachable("No such linkage");
265533956c43SDimitry Andric }
265633956c43SDimitry Andric 
265733956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
265833956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
265933956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
266033956c43SDimitry Andric     return;
266133956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
266233956c43SDimitry Andric }
266333956c43SDimitry Andric 
2664e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
2665e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2666e7145dcbSDimitry Andric                                             bool IsTentative) {
266744290647SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
266844290647SDimitry Andric   // therefore no need to be translated.
2669f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
267044290647SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
267144290647SDimitry Andric     return;
267244290647SDimitry Andric 
267344290647SDimitry Andric   llvm::Constant *Init = nullptr;
2674dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2675dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
2676dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2677f22ef01cSRoman Divacky 
2678dff0c46cSDimitry Andric   const VarDecl *InitDecl;
2679dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2680f22ef01cSRoman Divacky 
2681e7145dcbSDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2682e7145dcbSDimitry Andric   // as part of their declaration."  Sema has already checked for
2683e7145dcbSDimitry Andric   // error cases, so we just need to set Init to UndefValue.
2684e7145dcbSDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2685e7145dcbSDimitry Andric       D->hasAttr<CUDASharedAttr>())
26860623d748SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2687e7145dcbSDimitry Andric   else if (!InitExpr) {
2688f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
2689f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
2690f22ef01cSRoman Divacky     //
2691f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
2692f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
2693f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
2694f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
2695f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
2696f22ef01cSRoman Divacky     // to do a RAUW.
2697f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2698f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
2699f22ef01cSRoman Divacky   } else {
27007ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
2701dff0c46cSDimitry Andric     Init = EmitConstantInit(*InitDecl);
2702f785676fSDimitry Andric 
2703f22ef01cSRoman Divacky     if (!Init) {
2704f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
2705f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
2706f22ef01cSRoman Divacky         T = D->getType();
2707f22ef01cSRoman Divacky 
2708dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
2709f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
2710dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
2711f22ef01cSRoman Divacky       } else {
2712f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
2713f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2714f22ef01cSRoman Divacky       }
2715e580952dSDimitry Andric     } else {
2716e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
2717dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
2718dff0c46cSDimitry Andric       // also don't need to register a destructor.
2719dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2720e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
2721f22ef01cSRoman Divacky     }
2722f22ef01cSRoman Divacky   }
2723f22ef01cSRoman Divacky 
27246122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
2725e7145dcbSDimitry Andric   llvm::Constant *Entry =
272644290647SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2727f22ef01cSRoman Divacky 
2728f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
272959d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2730f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2731f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2732f785676fSDimitry Andric            // All zero index gep.
2733f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2734f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
2735f22ef01cSRoman Divacky   }
2736f22ef01cSRoman Divacky 
2737f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
273859d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2739f22ef01cSRoman Divacky 
2740f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
2741f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
2742f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
2743f22ef01cSRoman Divacky   // (which will be a definition).
2744f22ef01cSRoman Divacky   //
2745f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
2746f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
2747f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
2748f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
2749c4394386SDimitry Andric   if (!GV || GV->getType()->getElementType() != InitType ||
27503b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
2751c4394386SDimitry Andric           getContext().getTargetAddressSpace(GetGlobalVarAddressSpace(D))) {
2752f22ef01cSRoman Divacky 
2753f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
27546122f3e6SDimitry Andric     Entry->setName(StringRef());
2755f22ef01cSRoman Divacky 
2756f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
2757e7145dcbSDimitry Andric     GV = cast<llvm::GlobalVariable>(
275844290647SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2759f22ef01cSRoman Divacky 
2760f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
2761f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
2762f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2763f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2764f22ef01cSRoman Divacky 
2765f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
2766f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2767f22ef01cSRoman Divacky   }
2768f22ef01cSRoman Divacky 
2769284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
2770284c1978SDimitry Andric 
27716122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
27726122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
2773f22ef01cSRoman Divacky 
2774e7145dcbSDimitry Andric   // Set the llvm linkage type as appropriate.
2775e7145dcbSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
2776e7145dcbSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
2777e7145dcbSDimitry Andric 
27780623d748SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
27790623d748SDimitry Andric   // the device. [...]"
27800623d748SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
27810623d748SDimitry Andric   // __device__, declares a variable that: [...]
27820623d748SDimitry Andric   // Is accessible from all the threads within the grid and from the host
27830623d748SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
27840623d748SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2785e7145dcbSDimitry Andric   if (GV && LangOpts.CUDA) {
2786e7145dcbSDimitry Andric     if (LangOpts.CUDAIsDevice) {
2787e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
27880623d748SDimitry Andric         GV->setExternallyInitialized(true);
2789e7145dcbSDimitry Andric     } else {
2790e7145dcbSDimitry Andric       // Host-side shadows of external declarations of device-side
2791e7145dcbSDimitry Andric       // global variables become internal definitions. These have to
2792e7145dcbSDimitry Andric       // be internal in order to prevent name conflicts with global
2793e7145dcbSDimitry Andric       // host variables with the same name in a different TUs.
2794e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2795e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2796e7145dcbSDimitry Andric 
2797e7145dcbSDimitry Andric         // Shadow variables and their properties must be registered
2798e7145dcbSDimitry Andric         // with CUDA runtime.
2799e7145dcbSDimitry Andric         unsigned Flags = 0;
2800e7145dcbSDimitry Andric         if (!D->hasDefinition())
2801e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
2802e7145dcbSDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
2803e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
2804e7145dcbSDimitry Andric         getCUDARuntime().registerDeviceVar(*GV, Flags);
2805e7145dcbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
2806e7145dcbSDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
2807e7145dcbSDimitry Andric         // they are not registered with the CUDA runtime, so they
2808e7145dcbSDimitry Andric         // can't really be used to access their device-side
2809e7145dcbSDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
2810e7145dcbSDimitry Andric         // a feature, but we've got to do the same for compatibility.
2811e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2812e7145dcbSDimitry Andric     }
28130623d748SDimitry Andric   }
2814f22ef01cSRoman Divacky   GV->setInitializer(Init);
2815f22ef01cSRoman Divacky 
2816f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
2817dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2818dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
2819f22ef01cSRoman Divacky 
282039d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
282139d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
282239d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
282339d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
282439d628a0SDimitry Andric       GV->setConstant(true);
282539d628a0SDimitry Andric   }
282639d628a0SDimitry Andric 
2827f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2828f22ef01cSRoman Divacky 
2829f785676fSDimitry Andric 
28300623d748SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
28310623d748SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
28320623d748SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
28330623d748SDimitry Andric   // internal linkage and all accesses should just be calls to the
283459d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
28350623d748SDimitry Andric   // variable. This is to preserve the ability to change the implementation
28360623d748SDimitry Andric   // behind the scenes.
283739d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
28380623d748SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
28390623d748SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
28400623d748SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
284159d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
284259d1ed5bSDimitry Andric 
284359d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
284459d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
284559d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
284659d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
284759d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
284839d628a0SDimitry Andric   else
284939d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2850f785676fSDimitry Andric 
285144290647SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2852f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
2853f22ef01cSRoman Divacky     GV->setConstant(false);
285444290647SDimitry Andric     // Tentative definition of global variables may be initialized with
285544290647SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
285644290647SDimitry Andric     // since common linkage must have zero initializer and must not have
285744290647SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
285844290647SDimitry Andric     if (!GV->getInitializer()->isNullValue())
285944290647SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
286044290647SDimitry Andric   }
2861f22ef01cSRoman Divacky 
286259d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
2863f22ef01cSRoman Divacky 
286439d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
286539d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
28660623d748SDimitry Andric       CXXThreadLocals.push_back(D);
286739d628a0SDimitry Andric     setTLSMode(GV, *D);
286839d628a0SDimitry Andric   }
286939d628a0SDimitry Andric 
287033956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
287133956c43SDimitry Andric 
28722754fe60SDimitry Andric   // Emit the initializer function if necessary.
2873dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
2874dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
28752754fe60SDimitry Andric 
287639d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
28773861d79fSDimitry Andric 
2878f22ef01cSRoman Divacky   // Emit global variable debug information.
28796122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
2880e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2881f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
2882f22ef01cSRoman Divacky }
2883f22ef01cSRoman Divacky 
288439d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
288533956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
288633956c43SDimitry Andric                                       bool NoCommon) {
288759d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
288859d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
288959d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
289059d1ed5bSDimitry Andric     return true;
289159d1ed5bSDimitry Andric 
289259d1ed5bSDimitry Andric   // C11 6.9.2/2:
289359d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
289459d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
289559d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
289659d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
289759d1ed5bSDimitry Andric     return true;
289859d1ed5bSDimitry Andric 
289959d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
290059d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
290159d1ed5bSDimitry Andric     return true;
290259d1ed5bSDimitry Andric 
2903db17bf38SDimitry Andric   // A variable cannot be both common and exist in a section.
2904db17bf38SDimitry Andric   // We dont try to determine which is the right section in the front-end.
2905db17bf38SDimitry Andric   // If no specialized section name is applicable, it will resort to default.
2906db17bf38SDimitry Andric   if (D->hasAttr<PragmaClangBSSSectionAttr>() ||
2907db17bf38SDimitry Andric       D->hasAttr<PragmaClangDataSectionAttr>() ||
2908db17bf38SDimitry Andric       D->hasAttr<PragmaClangRodataSectionAttr>())
2909db17bf38SDimitry Andric     return true;
2910db17bf38SDimitry Andric 
291159d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
291259d1ed5bSDimitry Andric   if (D->getTLSKind())
291359d1ed5bSDimitry Andric     return true;
291459d1ed5bSDimitry Andric 
291559d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
291659d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
291759d1ed5bSDimitry Andric     return true;
291859d1ed5bSDimitry Andric 
291933956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
292033956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
292133956c43SDimitry Andric     return true;
292233956c43SDimitry Andric 
2923e7145dcbSDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
292439d628a0SDimitry Andric   // mode.
29250623d748SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
292633956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
292739d628a0SDimitry Andric       return true;
292833956c43SDimitry Andric     QualType VarType = D->getType();
292933956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
293033956c43SDimitry Andric       return true;
293133956c43SDimitry Andric 
293233956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
293333956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
293433956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
293533956c43SDimitry Andric         if (FD->isBitField())
293633956c43SDimitry Andric           continue;
293733956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
293833956c43SDimitry Andric           return true;
293933956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
294033956c43SDimitry Andric           return true;
294133956c43SDimitry Andric       }
294233956c43SDimitry Andric     }
294333956c43SDimitry Andric   }
294439d628a0SDimitry Andric 
294559d1ed5bSDimitry Andric   return false;
294659d1ed5bSDimitry Andric }
294759d1ed5bSDimitry Andric 
294859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
294959d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
29502754fe60SDimitry Andric   if (Linkage == GVA_Internal)
29512754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
295259d1ed5bSDimitry Andric 
295359d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
295459d1ed5bSDimitry Andric     if (IsConstantVariable)
295559d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
295659d1ed5bSDimitry Andric     else
295759d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
295859d1ed5bSDimitry Andric   }
295959d1ed5bSDimitry Andric 
296059d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
296159d1ed5bSDimitry Andric   // so we can use available_externally linkage.
296259d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
296320e90f04SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
296459d1ed5bSDimitry Andric 
296559d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
296659d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
296759d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
296859d1ed5bSDimitry Andric   // instantiations we'll map to external.
296959d1ed5bSDimitry Andric 
297059d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
297159d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
297259d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
297359d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
297459d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
297559d1ed5bSDimitry Andric   // definition is dependable.
297659d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
297759d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
297859d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
297959d1ed5bSDimitry Andric 
298059d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
298159d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
298259d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
298359d1ed5bSDimitry Andric   // throw away these explicit instantiations.
2984e7145dcbSDimitry Andric   //
2985e7145dcbSDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
2986e7145dcbSDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
2987e7145dcbSDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
2988e7145dcbSDimitry Andric   if (Linkage == GVA_StrongODR) {
2989e7145dcbSDimitry Andric     if (Context.getLangOpts().AppleKext)
2990e7145dcbSDimitry Andric       return llvm::Function::ExternalLinkage;
2991e7145dcbSDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2992e7145dcbSDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2993e7145dcbSDimitry Andric                                           : llvm::Function::InternalLinkage;
2994e7145dcbSDimitry Andric     return llvm::Function::WeakODRLinkage;
2995e7145dcbSDimitry Andric   }
299659d1ed5bSDimitry Andric 
299759d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
299859d1ed5bSDimitry Andric   // linkage.
299959d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
300033956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
300139d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
300259d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
300359d1ed5bSDimitry Andric 
3004f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
3005f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
3006f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
3007f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
300859d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
3009f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
301059d1ed5bSDimitry Andric 
301159d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
301259d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
30132754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
30142754fe60SDimitry Andric }
30152754fe60SDimitry Andric 
301659d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
301759d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
301859d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
301959d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
302059d1ed5bSDimitry Andric }
302159d1ed5bSDimitry Andric 
3022139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
3023139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
3024139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
3025139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
3026139f7f9bSDimitry Andric   // Fast path.
3027139f7f9bSDimitry Andric   if (old->use_empty()) return;
3028139f7f9bSDimitry Andric 
3029139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
3030139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
30310623d748SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
3032139f7f9bSDimitry Andric 
3033139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
3034139f7f9bSDimitry Andric          ui != ue; ) {
3035139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
303659d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
3037139f7f9bSDimitry Andric 
3038139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
3039139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
304059d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
3041139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
3042139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
3043139f7f9bSDimitry Andric       continue;
3044139f7f9bSDimitry Andric     }
3045139f7f9bSDimitry Andric 
3046139f7f9bSDimitry Andric     // Recognize calls to the function.
3047139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
3048139f7f9bSDimitry Andric     if (!callSite) continue;
304959d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
3050139f7f9bSDimitry Andric 
3051139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
3052139f7f9bSDimitry Andric     // transform this call unless it's dead.
3053139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
3054139f7f9bSDimitry Andric       continue;
3055139f7f9bSDimitry Andric 
3056139f7f9bSDimitry Andric     // Get the call site's attribute list.
305720e90f04SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
305820e90f04SDimitry Andric     llvm::AttributeList oldAttrs = callSite.getAttributes();
3059139f7f9bSDimitry Andric 
3060139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
3061139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
3062139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
3063139f7f9bSDimitry Andric 
3064139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
3065139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
3066139f7f9bSDimitry Andric     unsigned argNo = 0;
3067139f7f9bSDimitry Andric     bool dontTransform = false;
306820e90f04SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
306920e90f04SDimitry Andric       if (callSite.getArgument(argNo)->getType() != A.getType()) {
3070139f7f9bSDimitry Andric         dontTransform = true;
3071139f7f9bSDimitry Andric         break;
3072139f7f9bSDimitry Andric       }
3073139f7f9bSDimitry Andric 
3074139f7f9bSDimitry Andric       // Add any parameter attributes.
307520e90f04SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
307620e90f04SDimitry Andric       argNo++;
3077139f7f9bSDimitry Andric     }
3078139f7f9bSDimitry Andric     if (dontTransform)
3079139f7f9bSDimitry Andric       continue;
3080139f7f9bSDimitry Andric 
3081139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
3082139f7f9bSDimitry Andric     // over the required information.
3083139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3084139f7f9bSDimitry Andric 
30850623d748SDimitry Andric     // Copy over any operand bundles.
30860623d748SDimitry Andric     callSite.getOperandBundlesAsDefs(newBundles);
30870623d748SDimitry Andric 
3088139f7f9bSDimitry Andric     llvm::CallSite newCall;
3089139f7f9bSDimitry Andric     if (callSite.isCall()) {
30900623d748SDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3091139f7f9bSDimitry Andric                                        callSite.getInstruction());
3092139f7f9bSDimitry Andric     } else {
309359d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3094139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
3095139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
3096139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
30970623d748SDimitry Andric                                          newArgs, newBundles, "",
3098139f7f9bSDimitry Andric                                          callSite.getInstruction());
3099139f7f9bSDimitry Andric     }
3100139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
3101139f7f9bSDimitry Andric 
3102139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
3103139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
310420e90f04SDimitry Andric     newCall.setAttributes(llvm::AttributeList::get(
310520e90f04SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
310620e90f04SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
3107139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
3108139f7f9bSDimitry Andric 
3109139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
3110139f7f9bSDimitry Andric     if (!callSite->use_empty())
3111139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
3112139f7f9bSDimitry Andric 
3113139f7f9bSDimitry Andric     // Copy debug location attached to CI.
311433956c43SDimitry Andric     if (callSite->getDebugLoc())
3115139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
31160623d748SDimitry Andric 
3117139f7f9bSDimitry Andric     callSite->eraseFromParent();
3118139f7f9bSDimitry Andric   }
3119139f7f9bSDimitry Andric }
3120139f7f9bSDimitry Andric 
3121f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3122f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3123f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
3124f22ef01cSRoman Divacky /// call the new function directly.
3125f22ef01cSRoman Divacky ///
3126f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
3127f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
3128f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3129f22ef01cSRoman Divacky /// run at -O0.
3130f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3131f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
3132f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
3133139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
3134f22ef01cSRoman Divacky 
3135139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
3136f22ef01cSRoman Divacky }
3137f22ef01cSRoman Divacky 
3138dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3139e7145dcbSDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
3140e7145dcbSDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3141e7145dcbSDimitry Andric     return;
3142e7145dcbSDimitry Andric 
3143dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3144dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
3145dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
3146dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3147dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
3148139f7f9bSDimitry Andric 
3149139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
3150dff0c46cSDimitry Andric }
3151f22ef01cSRoman Divacky 
315259d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
315359d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
315459d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
31553b0f4066SDimitry Andric 
31563b0f4066SDimitry Andric   // Compute the function info and LLVM type.
3157dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3158dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
31593b0f4066SDimitry Andric 
3160f22ef01cSRoman Divacky   // Get or create the prototype for the function.
31610623d748SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
31620623d748SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
31630623d748SDimitry Andric                                                    /*DontDefer=*/true,
316444290647SDimitry Andric                                                    ForDefinition));
3165f22ef01cSRoman Divacky 
31660623d748SDimitry Andric   // Already emitted.
31670623d748SDimitry Andric   if (!GV->isDeclaration())
3168f785676fSDimitry Andric     return;
3169f22ef01cSRoman Divacky 
31702754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
31712754fe60SDimitry Andric   // generating code for it because various parts of IR generation
31722754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
31732754fe60SDimitry Andric   // declarations).
317459d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
3175f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
317697bc6c73SDimitry Andric   setFunctionDLLStorageClass(GD, Fn);
3177f22ef01cSRoman Divacky 
317859d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
31792754fe60SDimitry Andric   setGlobalVisibility(Fn, D);
31802754fe60SDimitry Andric 
3181284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
3182284c1978SDimitry Andric 
318333956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
318433956c43SDimitry Andric 
31853b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3186f22ef01cSRoman Divacky 
318759d1ed5bSDimitry Andric   setFunctionDefinitionAttributes(D, Fn);
3188f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
3189f22ef01cSRoman Divacky 
3190f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3191f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
3192f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3193f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
31946122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
31956122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
3196f22ef01cSRoman Divacky }
3197f22ef01cSRoman Divacky 
3198f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
319959d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3200f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
3201f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
3202f22ef01cSRoman Divacky 
32036122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
3204f22ef01cSRoman Divacky 
32059a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
3206e7145dcbSDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
32079a4b3118SDimitry Andric     return;
32089a4b3118SDimitry Andric   }
32099a4b3118SDimitry Andric 
3210f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
3211f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
3212f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3213f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
3214f22ef01cSRoman Divacky     return;
3215f22ef01cSRoman Divacky 
3216f785676fSDimitry Andric   Aliases.push_back(GD);
3217f785676fSDimitry Andric 
32186122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3219f22ef01cSRoman Divacky 
3220f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
3221f22ef01cSRoman Divacky   // if a deferred decl.
3222f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
3223f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
32243861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
32252754fe60SDimitry Andric                                       /*ForVTable=*/false);
3226f22ef01cSRoman Divacky   else
3227f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
322859d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
322939d628a0SDimitry Andric                                     /*D=*/nullptr);
3230f22ef01cSRoman Divacky 
3231f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
323259d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
32330623d748SDimitry Andric       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3234f22ef01cSRoman Divacky 
3235f22ef01cSRoman Divacky   if (Entry) {
323659d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
3237e7145dcbSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
323859d1ed5bSDimitry Andric       return;
323959d1ed5bSDimitry Andric     }
324059d1ed5bSDimitry Andric 
3241f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
3242f22ef01cSRoman Divacky 
3243f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
3244f22ef01cSRoman Divacky     // by the alias, as in:
3245f22ef01cSRoman Divacky     //   extern int test6();
3246f22ef01cSRoman Divacky     //   ...
3247f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
3248f22ef01cSRoman Divacky     //
3249f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
3250f22ef01cSRoman Divacky     GA->takeName(Entry);
3251f22ef01cSRoman Divacky 
3252f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3253f22ef01cSRoman Divacky                                                           Entry->getType()));
3254f22ef01cSRoman Divacky     Entry->eraseFromParent();
3255f22ef01cSRoman Divacky   } else {
3256ffd1746dSEd Schouten     GA->setName(MangledName);
3257f22ef01cSRoman Divacky   }
3258f22ef01cSRoman Divacky 
3259f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
3260f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
3261f22ef01cSRoman Divacky   // variable/function.
326239d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
32633b0f4066SDimitry Andric       D->isWeakImported()) {
3264f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3265f22ef01cSRoman Divacky   }
3266f22ef01cSRoman Divacky 
326739d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
326839d628a0SDimitry Andric     if (VD->getTLSKind())
326939d628a0SDimitry Andric       setTLSMode(GA, *VD);
327039d628a0SDimitry Andric 
327139d628a0SDimitry Andric   setAliasAttributes(D, GA);
3272f22ef01cSRoman Divacky }
3273f22ef01cSRoman Divacky 
3274e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3275e7145dcbSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3276e7145dcbSDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3277e7145dcbSDimitry Andric   assert(IFA && "Not an ifunc?");
3278e7145dcbSDimitry Andric 
3279e7145dcbSDimitry Andric   StringRef MangledName = getMangledName(GD);
3280e7145dcbSDimitry Andric 
3281e7145dcbSDimitry Andric   if (IFA->getResolver() == MangledName) {
3282e7145dcbSDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3283e7145dcbSDimitry Andric     return;
3284e7145dcbSDimitry Andric   }
3285e7145dcbSDimitry Andric 
3286e7145dcbSDimitry Andric   // Report an error if some definition overrides ifunc.
3287e7145dcbSDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3288e7145dcbSDimitry Andric   if (Entry && !Entry->isDeclaration()) {
3289e7145dcbSDimitry Andric     GlobalDecl OtherGD;
3290e7145dcbSDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3291e7145dcbSDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
3292e7145dcbSDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3293e7145dcbSDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
3294e7145dcbSDimitry Andric                    diag::note_previous_definition);
3295e7145dcbSDimitry Andric     }
3296e7145dcbSDimitry Andric     return;
3297e7145dcbSDimitry Andric   }
3298e7145dcbSDimitry Andric 
3299e7145dcbSDimitry Andric   Aliases.push_back(GD);
3300e7145dcbSDimitry Andric 
3301e7145dcbSDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3302e7145dcbSDimitry Andric   llvm::Constant *Resolver =
3303e7145dcbSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3304e7145dcbSDimitry Andric                               /*ForVTable=*/false);
3305e7145dcbSDimitry Andric   llvm::GlobalIFunc *GIF =
3306e7145dcbSDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3307e7145dcbSDimitry Andric                                 "", Resolver, &getModule());
3308e7145dcbSDimitry Andric   if (Entry) {
3309e7145dcbSDimitry Andric     if (GIF->getResolver() == Entry) {
3310e7145dcbSDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3311e7145dcbSDimitry Andric       return;
3312e7145dcbSDimitry Andric     }
3313e7145dcbSDimitry Andric     assert(Entry->isDeclaration());
3314e7145dcbSDimitry Andric 
3315e7145dcbSDimitry Andric     // If there is a declaration in the module, then we had an extern followed
3316e7145dcbSDimitry Andric     // by the ifunc, as in:
3317e7145dcbSDimitry Andric     //   extern int test();
3318e7145dcbSDimitry Andric     //   ...
3319e7145dcbSDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
3320e7145dcbSDimitry Andric     //
3321e7145dcbSDimitry Andric     // Remove it and replace uses of it with the ifunc.
3322e7145dcbSDimitry Andric     GIF->takeName(Entry);
3323e7145dcbSDimitry Andric 
3324e7145dcbSDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3325e7145dcbSDimitry Andric                                                           Entry->getType()));
3326e7145dcbSDimitry Andric     Entry->eraseFromParent();
3327e7145dcbSDimitry Andric   } else
3328e7145dcbSDimitry Andric     GIF->setName(MangledName);
3329e7145dcbSDimitry Andric 
3330e7145dcbSDimitry Andric   SetCommonAttributes(D, GIF);
3331e7145dcbSDimitry Andric }
3332e7145dcbSDimitry Andric 
333317a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
33346122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
333517a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
333617a519f9SDimitry Andric                                          Tys);
3337f22ef01cSRoman Divacky }
3338f22ef01cSRoman Divacky 
333933956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
334033956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
334133956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
334233956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
33436122f3e6SDimitry Andric   StringRef String = Literal->getString();
3344e580952dSDimitry Andric   unsigned NumBytes = String.size();
3345f22ef01cSRoman Divacky 
3346f22ef01cSRoman Divacky   // Check for simple case.
3347f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
3348f22ef01cSRoman Divacky     StringLength = NumBytes;
334939d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
3350f22ef01cSRoman Divacky   }
3351f22ef01cSRoman Divacky 
3352dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
3353dff0c46cSDimitry Andric   IsUTF16 = true;
3354dff0c46cSDimitry Andric 
335544290647SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
335644290647SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
335744290647SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
3358f22ef01cSRoman Divacky 
335944290647SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
336044290647SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
3361f22ef01cSRoman Divacky 
3362f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
3363f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
3364f22ef01cSRoman Divacky 
3365dff0c46cSDimitry Andric   // Add an explicit null.
3366dff0c46cSDimitry Andric   *ToPtr = 0;
336739d628a0SDimitry Andric   return *Map.insert(std::make_pair(
336839d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
336939d628a0SDimitry Andric                                    (StringLength + 1) * 2),
337039d628a0SDimitry Andric                          nullptr)).first;
3371f22ef01cSRoman Divacky }
3372f22ef01cSRoman Divacky 
33730623d748SDimitry Andric ConstantAddress
3374f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3375f22ef01cSRoman Divacky   unsigned StringLength = 0;
3376f22ef01cSRoman Divacky   bool isUTF16 = false;
337733956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3378f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
337933956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
338033956c43SDimitry Andric                                StringLength);
3381f22ef01cSRoman Divacky 
338239d628a0SDimitry Andric   if (auto *C = Entry.second)
33830623d748SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3384f22ef01cSRoman Divacky 
3385dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3386f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
3387f22ef01cSRoman Divacky 
3388f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
3389f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
33906122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3391f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
3392e7145dcbSDimitry Andric     llvm::Constant *GV =
3393e7145dcbSDimitry Andric         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3394e7145dcbSDimitry Andric 
339544290647SDimitry Andric     if (getTriple().isOSBinFormatCOFF()) {
3396e7145dcbSDimitry Andric       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3397e7145dcbSDimitry Andric       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3398e7145dcbSDimitry Andric       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3399e7145dcbSDimitry Andric       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3400e7145dcbSDimitry Andric 
3401e7145dcbSDimitry Andric       const VarDecl *VD = nullptr;
3402e7145dcbSDimitry Andric       for (const auto &Result : DC->lookup(&II))
3403e7145dcbSDimitry Andric         if ((VD = dyn_cast<VarDecl>(Result)))
3404e7145dcbSDimitry Andric           break;
3405e7145dcbSDimitry Andric 
3406e7145dcbSDimitry Andric       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3407e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3408e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3409e7145dcbSDimitry Andric       } else {
3410e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3411e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3412e7145dcbSDimitry Andric       }
3413e7145dcbSDimitry Andric     }
3414e7145dcbSDimitry Andric 
3415f22ef01cSRoman Divacky     // Decay array -> ptr
341644290647SDimitry Andric     CFConstantStringClassRef =
341744290647SDimitry Andric         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3418e7145dcbSDimitry Andric   }
3419f22ef01cSRoman Divacky 
3420f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
3421f22ef01cSRoman Divacky 
342259d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3423f22ef01cSRoman Divacky 
342444290647SDimitry Andric   ConstantInitBuilder Builder(*this);
342544290647SDimitry Andric   auto Fields = Builder.beginStruct(STy);
3426f22ef01cSRoman Divacky 
3427f22ef01cSRoman Divacky   // Class pointer.
342844290647SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3429f22ef01cSRoman Divacky 
3430f22ef01cSRoman Divacky   // Flags.
343144290647SDimitry Andric   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3432f22ef01cSRoman Divacky 
3433f22ef01cSRoman Divacky   // String pointer.
343459d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
3435dff0c46cSDimitry Andric   if (isUTF16) {
34360623d748SDimitry Andric     auto Arr = llvm::makeArrayRef(
343739d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
343839d628a0SDimitry Andric         Entry.first().size() / 2);
3439dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
3440dff0c46cSDimitry Andric   } else {
344139d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3442dff0c46cSDimitry Andric   }
3443f22ef01cSRoman Divacky 
3444dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
3445dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
344659d1ed5bSDimitry Andric   auto *GV =
3447dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
344859d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3449e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3450284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
3451284c1978SDimitry Andric   // of the string is via this class initializer.
3452e7145dcbSDimitry Andric   CharUnits Align = isUTF16
3453e7145dcbSDimitry Andric                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3454e7145dcbSDimitry Andric                         : getContext().getTypeAlignInChars(getContext().CharTy);
3455f22ef01cSRoman Divacky   GV->setAlignment(Align.getQuantity());
3456e7145dcbSDimitry Andric 
3457e7145dcbSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3458e7145dcbSDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
3459e7145dcbSDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
346044290647SDimitry Andric   if (getTriple().isOSBinFormatMachO())
3461e7145dcbSDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3462e7145dcbSDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
3463dff0c46cSDimitry Andric 
3464dff0c46cSDimitry Andric   // String.
346544290647SDimitry Andric   llvm::Constant *Str =
346633956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3467f22ef01cSRoman Divacky 
3468dff0c46cSDimitry Andric   if (isUTF16)
3469dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
347044290647SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
347144290647SDimitry Andric   Fields.add(Str);
3472dff0c46cSDimitry Andric 
3473f22ef01cSRoman Divacky   // String length.
347444290647SDimitry Andric   auto Ty = getTypes().ConvertType(getContext().LongTy);
347544290647SDimitry Andric   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3476f22ef01cSRoman Divacky 
34770623d748SDimitry Andric   CharUnits Alignment = getPointerAlign();
34780623d748SDimitry Andric 
3479f22ef01cSRoman Divacky   // The struct.
348044290647SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
348144290647SDimitry Andric                                     /*isConstant=*/false,
348244290647SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
348344290647SDimitry Andric   switch (getTriple().getObjectFormat()) {
3484e7145dcbSDimitry Andric   case llvm::Triple::UnknownObjectFormat:
3485e7145dcbSDimitry Andric     llvm_unreachable("unknown file format");
3486e7145dcbSDimitry Andric   case llvm::Triple::COFF:
3487e7145dcbSDimitry Andric   case llvm::Triple::ELF:
348820e90f04SDimitry Andric   case llvm::Triple::Wasm:
3489e7145dcbSDimitry Andric     GV->setSection("cfstring");
3490e7145dcbSDimitry Andric     break;
3491e7145dcbSDimitry Andric   case llvm::Triple::MachO:
3492e7145dcbSDimitry Andric     GV->setSection("__DATA,__cfstring");
3493e7145dcbSDimitry Andric     break;
3494e7145dcbSDimitry Andric   }
349539d628a0SDimitry Andric   Entry.second = GV;
3496f22ef01cSRoman Divacky 
34970623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3498f22ef01cSRoman Divacky }
3499f22ef01cSRoman Divacky 
35006122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
35016122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
350259d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
35036122f3e6SDimitry Andric     D->startDefinition();
35046122f3e6SDimitry Andric 
35056122f3e6SDimitry Andric     QualType FieldTypes[] = {
35066122f3e6SDimitry Andric       Context.UnsignedLongTy,
35076122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
35086122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
35096122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
35106122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
35116122f3e6SDimitry Andric     };
35126122f3e6SDimitry Andric 
35136122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
35146122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
35156122f3e6SDimitry Andric                                            D,
35166122f3e6SDimitry Andric                                            SourceLocation(),
351759d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
351859d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
351959d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
35206122f3e6SDimitry Andric                                            /*Mutable=*/false,
35217ae0e2c9SDimitry Andric                                            ICIS_NoInit);
35226122f3e6SDimitry Andric       Field->setAccess(AS_public);
35236122f3e6SDimitry Andric       D->addDecl(Field);
35246122f3e6SDimitry Andric     }
35256122f3e6SDimitry Andric 
35266122f3e6SDimitry Andric     D->completeDefinition();
35276122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
35286122f3e6SDimitry Andric   }
35296122f3e6SDimitry Andric 
35306122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
35316122f3e6SDimitry Andric }
35326122f3e6SDimitry Andric 
3533dff0c46cSDimitry Andric llvm::Constant *
3534dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3535dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3536f22ef01cSRoman Divacky 
3537dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
3538dff0c46cSDimitry Andric   // as an inline array.
3539dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
3540dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
3541f22ef01cSRoman Divacky 
3542dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
3543dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3544dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
3545dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
35466122f3e6SDimitry Andric   }
3547f22ef01cSRoman Divacky 
354859d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3549dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
3550dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
3551f22ef01cSRoman Divacky 
3552dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
3553dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3554dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
3555dff0c46cSDimitry Andric     Elements.reserve(NumElements);
3556dff0c46cSDimitry Andric 
3557dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3558dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
3559dff0c46cSDimitry Andric     Elements.resize(NumElements);
3560dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
3561dff0c46cSDimitry Andric   }
3562dff0c46cSDimitry Andric 
3563dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3564dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
3565dff0c46cSDimitry Andric   Elements.reserve(NumElements);
3566dff0c46cSDimitry Andric 
3567dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3568dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
3569dff0c46cSDimitry Andric   Elements.resize(NumElements);
3570dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
3571f22ef01cSRoman Divacky }
3572f22ef01cSRoman Divacky 
357359d1ed5bSDimitry Andric static llvm::GlobalVariable *
357459d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
357559d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
35760623d748SDimitry Andric                       CharUnits Alignment) {
357759d1ed5bSDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
357859d1ed5bSDimitry Andric   unsigned AddrSpace = 0;
357959d1ed5bSDimitry Andric   if (CGM.getLangOpts().OpenCL)
358059d1ed5bSDimitry Andric     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3581dff0c46cSDimitry Andric 
358233956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
358359d1ed5bSDimitry Andric   // Create a global variable for this string
358459d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
358533956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
358633956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
35870623d748SDimitry Andric   GV->setAlignment(Alignment.getQuantity());
3588e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
358933956c43SDimitry Andric   if (GV->isWeakForLinker()) {
359033956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
359133956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
359233956c43SDimitry Andric   }
359333956c43SDimitry Andric 
359459d1ed5bSDimitry Andric   return GV;
3595f22ef01cSRoman Divacky }
3596dff0c46cSDimitry Andric 
359759d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
359859d1ed5bSDimitry Andric /// constant array for the given string literal.
35990623d748SDimitry Andric ConstantAddress
360039d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
360139d628a0SDimitry Andric                                                   StringRef Name) {
36020623d748SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3603dff0c46cSDimitry Andric 
360459d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
360559d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
360659d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
360759d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
360859d1ed5bSDimitry Andric     if (auto GV = *Entry) {
36090623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
36100623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
36110623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
361259d1ed5bSDimitry Andric     }
361359d1ed5bSDimitry Andric   }
361459d1ed5bSDimitry Andric 
361559d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
361659d1ed5bSDimitry Andric   StringRef GlobalVariableName;
361759d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
361859d1ed5bSDimitry Andric 
361959d1ed5bSDimitry Andric   // Mangle the string literal if the ABI allows for it.  However, we cannot
362059d1ed5bSDimitry Andric   // do this if  we are compiling with ASan or -fwritable-strings because they
362159d1ed5bSDimitry Andric   // rely on strings having normal linkage.
362239d628a0SDimitry Andric   if (!LangOpts.WritableStrings &&
362339d628a0SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
362459d1ed5bSDimitry Andric       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
362559d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
362659d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
362759d1ed5bSDimitry Andric 
362859d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
362959d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
363059d1ed5bSDimitry Andric   } else {
363159d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
363239d628a0SDimitry Andric     GlobalVariableName = Name;
363359d1ed5bSDimitry Andric   }
363459d1ed5bSDimitry Andric 
363559d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
363659d1ed5bSDimitry Andric   if (Entry)
363759d1ed5bSDimitry Andric     *Entry = GV;
363859d1ed5bSDimitry Andric 
363939d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
364039d628a0SDimitry Andric                                   QualType());
36410623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3642f22ef01cSRoman Divacky }
3643f22ef01cSRoman Divacky 
3644f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3645f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
36460623d748SDimitry Andric ConstantAddress
3647f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3648f22ef01cSRoman Divacky   std::string Str;
3649f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3650f22ef01cSRoman Divacky 
3651f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
3652f22ef01cSRoman Divacky }
3653f22ef01cSRoman Divacky 
365459d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
365559d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
365659d1ed5bSDimitry Andric /// The result has pointer to array type.
36570623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
36580623d748SDimitry Andric     const std::string &Str, const char *GlobalName) {
365959d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
36600623d748SDimitry Andric   CharUnits Alignment =
36610623d748SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3662f22ef01cSRoman Divacky 
366359d1ed5bSDimitry Andric   llvm::Constant *C =
366459d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
366559d1ed5bSDimitry Andric 
366659d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
366759d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
366859d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
366959d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
367059d1ed5bSDimitry Andric     if (auto GV = *Entry) {
36710623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
36720623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
36730623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
367459d1ed5bSDimitry Andric     }
367559d1ed5bSDimitry Andric   }
367659d1ed5bSDimitry Andric 
3677f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
3678f22ef01cSRoman Divacky   if (!GlobalName)
3679f22ef01cSRoman Divacky     GlobalName = ".str";
3680f22ef01cSRoman Divacky   // Create a global variable for this.
368159d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
368259d1ed5bSDimitry Andric                                   GlobalName, Alignment);
368359d1ed5bSDimitry Andric   if (Entry)
368459d1ed5bSDimitry Andric     *Entry = GV;
36850623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3686f22ef01cSRoman Divacky }
3687f22ef01cSRoman Divacky 
36880623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3689f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
3690f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
3691f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
369259d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3693f785676fSDimitry Andric 
3694f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
3695f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3696f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
3697f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
3698f785676fSDimitry Andric     MaterializedType = E->getType();
3699f785676fSDimitry Andric 
37000623d748SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
37010623d748SDimitry Andric 
37020623d748SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
37030623d748SDimitry Andric     return ConstantAddress(Slot, Align);
3704f785676fSDimitry Andric 
3705f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
3706f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
3707f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
3708f785676fSDimitry Andric   SmallString<256> Name;
3709f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
371059d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
371159d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
3712f785676fSDimitry Andric 
371359d1ed5bSDimitry Andric   APValue *Value = nullptr;
3714f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
3715f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
3716f785676fSDimitry Andric     // that this might have a different value from the value computed by
3717f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
3718f785676fSDimitry Andric     // modifies the temporary.
3719f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
3720f785676fSDimitry Andric     if (Value && Value->isUninit())
372159d1ed5bSDimitry Andric       Value = nullptr;
3722f785676fSDimitry Andric   }
3723f785676fSDimitry Andric 
3724f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
3725f785676fSDimitry Andric   Expr::EvalResult EvalResult;
3726f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3727f785676fSDimitry Andric       !EvalResult.hasSideEffects())
3728f785676fSDimitry Andric     Value = &EvalResult.Val;
3729f785676fSDimitry Andric 
373059d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
3731f785676fSDimitry Andric   bool Constant = false;
3732f785676fSDimitry Andric   llvm::Type *Type;
3733f785676fSDimitry Andric   if (Value) {
3734f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
373559d1ed5bSDimitry Andric     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3736f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3737f785676fSDimitry Andric     Type = InitialValue->getType();
3738f785676fSDimitry Andric   } else {
3739f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
3740f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
3741f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
3742f785676fSDimitry Andric   }
3743f785676fSDimitry Andric 
3744f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
374559d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
374659d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
374733956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
374833956c43SDimitry Andric     const VarDecl *InitVD;
374933956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
375033956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
375133956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
375233956c43SDimitry Andric       // class can be defined in multipe translation units.
375333956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
375433956c43SDimitry Andric     } else {
375533956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
375633956c43SDimitry Andric       // VarDecl has external linkage.
375733956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
375833956c43SDimitry Andric     }
375933956c43SDimitry Andric   }
3760c4394386SDimitry Andric   unsigned AddrSpace =
3761c4394386SDimitry Andric       VD ? GetGlobalVarAddressSpace(VD) : MaterializedType.getAddressSpace();
3762c4394386SDimitry Andric   auto TargetAS = getContext().getTargetAddressSpace(AddrSpace);
376359d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
376459d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3765c4394386SDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal, TargetAS);
376659d1ed5bSDimitry Andric   setGlobalVisibility(GV, VD);
37670623d748SDimitry Andric   GV->setAlignment(Align.getQuantity());
376833956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
376933956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3770f785676fSDimitry Andric   if (VD->getTLSKind())
3771f785676fSDimitry Andric     setTLSMode(GV, *VD);
3772c4394386SDimitry Andric   llvm::Constant *CV = GV;
3773c4394386SDimitry Andric   if (AddrSpace != LangAS::Default)
3774c4394386SDimitry Andric     CV = getTargetCodeGenInfo().performAddrSpaceCast(
3775c4394386SDimitry Andric         *this, GV, AddrSpace, LangAS::Default,
3776c4394386SDimitry Andric         Type->getPointerTo(
3777c4394386SDimitry Andric             getContext().getTargetAddressSpace(LangAS::Default)));
3778c4394386SDimitry Andric   MaterializedGlobalTemporaryMap[E] = CV;
3779c4394386SDimitry Andric   return ConstantAddress(CV, Align);
3780f785676fSDimitry Andric }
3781f785676fSDimitry Andric 
3782f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
3783f22ef01cSRoman Divacky /// properties for an implementation.
3784f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
3785f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
378659d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
3787f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
3788f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3789f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3790f22ef01cSRoman Divacky 
3791f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
37923861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
3793f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
3794f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
3795f22ef01cSRoman Divacky       // this implementation.
3796f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
3797f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
3798f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3799f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
3800f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
3801f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
3802f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3803f22ef01cSRoman Divacky     }
3804f22ef01cSRoman Divacky   }
3805f22ef01cSRoman Divacky }
3806f22ef01cSRoman Divacky 
38073b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
38086122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
38096122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
38103b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
38113b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
38123b0f4066SDimitry Andric       return true;
38133b0f4066SDimitry Andric 
38143b0f4066SDimitry Andric   return false;
38153b0f4066SDimitry Andric }
38163b0f4066SDimitry Andric 
381739d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
381839d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
381939d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
382039d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
382139d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
382239d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
382339d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
382439d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
382539d628a0SDimitry Andric       return false;
382639d628a0SDimitry Andric   }
382739d628a0SDimitry Andric   return true;
382839d628a0SDimitry Andric }
382939d628a0SDimitry Andric 
3830f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
3831f22ef01cSRoman Divacky /// for an implementation.
3832f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
38333b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
38343b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
3835f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3836f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
38373b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
38383b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
383959d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
38406122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
38413861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
38426122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
3843f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
3844f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
38453861d79fSDimitry Andric     D->setHasDestructors(true);
38463b0f4066SDimitry Andric   }
3847f22ef01cSRoman Divacky 
38483b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
38493b0f4066SDimitry Andric   // a .cxx_construct.
385039d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
385139d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
38523b0f4066SDimitry Andric     return;
38533b0f4066SDimitry Andric 
38543b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
38553b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3856f22ef01cSRoman Divacky   // The constructor returns 'self'.
3857f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3858f22ef01cSRoman Divacky                                                 D->getLocation(),
38596122f3e6SDimitry Andric                                                 D->getLocation(),
38606122f3e6SDimitry Andric                                                 cxxSelector,
386159d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
386259d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
38636122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
38643861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
38656122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
38666122f3e6SDimitry Andric                                                 /*isDefined=*/false,
3867f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
3868f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
3869f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
38703861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
3871f22ef01cSRoman Divacky }
3872f22ef01cSRoman Divacky 
3873f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
3874f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3875f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3876f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3877f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
3878f22ef01cSRoman Divacky     return;
3879f22ef01cSRoman Divacky   }
3880f22ef01cSRoman Divacky 
388144290647SDimitry Andric   EmitDeclContext(LSD);
388244290647SDimitry Andric }
388344290647SDimitry Andric 
388444290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
388544290647SDimitry Andric   for (auto *I : DC->decls()) {
388644290647SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
388744290647SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
388844290647SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
388944290647SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
389044290647SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
389159d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
389259d1ed5bSDimitry Andric       for (auto *M : OID->methods())
389359d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
38943861d79fSDimitry Andric     }
389544290647SDimitry Andric 
389659d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3897f22ef01cSRoman Divacky   }
38983861d79fSDimitry Andric }
3899f22ef01cSRoman Divacky 
3900f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
3901f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3902f22ef01cSRoman Divacky   // Ignore dependent declarations.
3903f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3904f22ef01cSRoman Divacky     return;
3905f22ef01cSRoman Divacky 
3906f22ef01cSRoman Divacky   switch (D->getKind()) {
3907f22ef01cSRoman Divacky   case Decl::CXXConversion:
3908f22ef01cSRoman Divacky   case Decl::CXXMethod:
3909f22ef01cSRoman Divacky   case Decl::Function:
3910f22ef01cSRoman Divacky     // Skip function templates
39113b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
39123b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3913f22ef01cSRoman Divacky       return;
3914f22ef01cSRoman Divacky 
3915f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
391639d628a0SDimitry Andric     // Always provide some coverage mapping
391739d628a0SDimitry Andric     // even for the functions that aren't emitted.
391839d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
3919f22ef01cSRoman Divacky     break;
3920f22ef01cSRoman Divacky 
39216bc11b14SDimitry Andric   case Decl::CXXDeductionGuide:
39226bc11b14SDimitry Andric     // Function-like, but does not result in code emission.
39236bc11b14SDimitry Andric     break;
39246bc11b14SDimitry Andric 
3925f22ef01cSRoman Divacky   case Decl::Var:
392644290647SDimitry Andric   case Decl::Decomposition:
3927f785676fSDimitry Andric     // Skip variable templates
3928f785676fSDimitry Andric     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3929f785676fSDimitry Andric       return;
39306d97bb29SDimitry Andric     LLVM_FALLTHROUGH;
3931f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
3932f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
393344290647SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
393444290647SDimitry Andric       for (auto *B : DD->bindings())
393544290647SDimitry Andric         if (auto *HD = B->getHoldingVar())
393644290647SDimitry Andric           EmitGlobal(HD);
3937f22ef01cSRoman Divacky     break;
3938f22ef01cSRoman Divacky 
39393b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
39403b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
39413b0f4066SDimitry Andric   case Decl::IndirectField:
39423b0f4066SDimitry Andric     break;
39433b0f4066SDimitry Andric 
3944f22ef01cSRoman Divacky   // C++ Decls
3945f22ef01cSRoman Divacky   case Decl::Namespace:
394644290647SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
3947f22ef01cSRoman Divacky     break;
3948e7145dcbSDimitry Andric   case Decl::CXXRecord:
394920e90f04SDimitry Andric     if (DebugInfo) {
395020e90f04SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
395120e90f04SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
395220e90f04SDimitry Andric           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
395320e90f04SDimitry Andric     }
3954e7145dcbSDimitry Andric     // Emit any static data members, they may be definitions.
3955e7145dcbSDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
3956e7145dcbSDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3957e7145dcbSDimitry Andric         EmitTopLevelDecl(I);
3958e7145dcbSDimitry Andric     break;
3959f22ef01cSRoman Divacky     // No code generation needed.
3960f22ef01cSRoman Divacky   case Decl::UsingShadow:
3961f22ef01cSRoman Divacky   case Decl::ClassTemplate:
3962f785676fSDimitry Andric   case Decl::VarTemplate:
3963f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
3964f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
3965bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
3966bd5abe19SDimitry Andric   case Decl::Block:
3967139f7f9bSDimitry Andric   case Decl::Empty:
3968f22ef01cSRoman Divacky     break;
396959d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
397059d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
397159d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
397259d1ed5bSDimitry Andric     return;
3973f785676fSDimitry Andric   case Decl::NamespaceAlias:
3974f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3975f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3976f785676fSDimitry Andric     return;
3977284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
3978284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3979284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3980284c1978SDimitry Andric     return;
3981f22ef01cSRoman Divacky   case Decl::CXXConstructor:
3982f22ef01cSRoman Divacky     // Skip function templates
39833b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
39843b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3985f22ef01cSRoman Divacky       return;
3986f22ef01cSRoman Divacky 
3987f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3988f22ef01cSRoman Divacky     break;
3989f22ef01cSRoman Divacky   case Decl::CXXDestructor:
39903b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
39913b0f4066SDimitry Andric       return;
3992f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3993f22ef01cSRoman Divacky     break;
3994f22ef01cSRoman Divacky 
3995f22ef01cSRoman Divacky   case Decl::StaticAssert:
3996f22ef01cSRoman Divacky     // Nothing to do.
3997f22ef01cSRoman Divacky     break;
3998f22ef01cSRoman Divacky 
3999f22ef01cSRoman Divacky   // Objective-C Decls
4000f22ef01cSRoman Divacky 
4001f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
4002f22ef01cSRoman Divacky   case Decl::ObjCInterface:
40037ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
4004f22ef01cSRoman Divacky     break;
4005f22ef01cSRoman Divacky 
4006dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
400759d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
4008dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
4009dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
4010f22ef01cSRoman Divacky     break;
4011dff0c46cSDimitry Andric   }
4012f22ef01cSRoman Divacky 
4013f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
4014f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
4015f22ef01cSRoman Divacky     // can ignore them here.
40166122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
4017f22ef01cSRoman Divacky     break;
4018f22ef01cSRoman Divacky 
4019f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
402059d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
4021f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
4022f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
40236122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
4024dff0c46cSDimitry Andric     // Emit global variable debug information.
4025dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
4026e7145dcbSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
4027139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
4028139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
4029f22ef01cSRoman Divacky     break;
4030f22ef01cSRoman Divacky   }
4031f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
403259d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
4033f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
4034f22ef01cSRoman Divacky     if (OMD->getBody())
4035f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
4036f22ef01cSRoman Divacky     break;
4037f22ef01cSRoman Divacky   }
4038f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
4039dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
4040f22ef01cSRoman Divacky     break;
4041f22ef01cSRoman Divacky 
4042e7145dcbSDimitry Andric   case Decl::PragmaComment: {
4043e7145dcbSDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
4044e7145dcbSDimitry Andric     switch (PCD->getCommentKind()) {
4045e7145dcbSDimitry Andric     case PCK_Unknown:
4046e7145dcbSDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
4047e7145dcbSDimitry Andric     case PCK_Linker:
4048e7145dcbSDimitry Andric       AppendLinkerOptions(PCD->getArg());
4049e7145dcbSDimitry Andric       break;
4050e7145dcbSDimitry Andric     case PCK_Lib:
4051e7145dcbSDimitry Andric       AddDependentLib(PCD->getArg());
4052e7145dcbSDimitry Andric       break;
4053e7145dcbSDimitry Andric     case PCK_Compiler:
4054e7145dcbSDimitry Andric     case PCK_ExeStr:
4055e7145dcbSDimitry Andric     case PCK_User:
4056e7145dcbSDimitry Andric       break; // We ignore all of these.
4057e7145dcbSDimitry Andric     }
4058e7145dcbSDimitry Andric     break;
4059e7145dcbSDimitry Andric   }
4060e7145dcbSDimitry Andric 
4061e7145dcbSDimitry Andric   case Decl::PragmaDetectMismatch: {
4062e7145dcbSDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
4063e7145dcbSDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
4064e7145dcbSDimitry Andric     break;
4065e7145dcbSDimitry Andric   }
4066e7145dcbSDimitry Andric 
4067f22ef01cSRoman Divacky   case Decl::LinkageSpec:
4068f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
4069f22ef01cSRoman Divacky     break;
4070f22ef01cSRoman Divacky 
4071f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
407233956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
407333956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
407433956c43SDimitry Andric       break;
4075ea942507SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
4076ea942507SDimitry Andric     if (LangOpts.OpenMPIsDevice)
4077ea942507SDimitry Andric       break;
407859d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
407933956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
4080f22ef01cSRoman Divacky     break;
4081f22ef01cSRoman Divacky   }
4082f22ef01cSRoman Divacky 
4083139f7f9bSDimitry Andric   case Decl::Import: {
408459d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
4085139f7f9bSDimitry Andric 
408644290647SDimitry Andric     // If we've already imported this module, we're done.
408744290647SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
4088139f7f9bSDimitry Andric       break;
408944290647SDimitry Andric 
409044290647SDimitry Andric     // Emit debug information for direct imports.
409144290647SDimitry Andric     if (!Import->getImportedOwningModule()) {
40923dac3a9bSDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
40933dac3a9bSDimitry Andric         DI->EmitImportDecl(*Import);
409444290647SDimitry Andric     }
4095139f7f9bSDimitry Andric 
409644290647SDimitry Andric     // Find all of the submodules and emit the module initializers.
409744290647SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
409844290647SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
409944290647SDimitry Andric     Visited.insert(Import->getImportedModule());
410044290647SDimitry Andric     Stack.push_back(Import->getImportedModule());
410144290647SDimitry Andric 
410244290647SDimitry Andric     while (!Stack.empty()) {
410344290647SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
410444290647SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
410544290647SDimitry Andric         continue;
410644290647SDimitry Andric 
410744290647SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
410844290647SDimitry Andric         EmitTopLevelDecl(D);
410944290647SDimitry Andric 
411044290647SDimitry Andric       // Visit the submodules of this module.
411144290647SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
411244290647SDimitry Andric                                              SubEnd = Mod->submodule_end();
411344290647SDimitry Andric            Sub != SubEnd; ++Sub) {
411444290647SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
411544290647SDimitry Andric         // the initializers.
411644290647SDimitry Andric         if ((*Sub)->IsExplicit)
411744290647SDimitry Andric           continue;
411844290647SDimitry Andric 
411944290647SDimitry Andric         if (Visited.insert(*Sub).second)
412044290647SDimitry Andric           Stack.push_back(*Sub);
412144290647SDimitry Andric       }
412244290647SDimitry Andric     }
4123139f7f9bSDimitry Andric     break;
4124139f7f9bSDimitry Andric   }
4125139f7f9bSDimitry Andric 
412644290647SDimitry Andric   case Decl::Export:
412744290647SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
412844290647SDimitry Andric     break;
412944290647SDimitry Andric 
413039d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
413139d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
413239d628a0SDimitry Andric     break;
413339d628a0SDimitry Andric 
413459d1ed5bSDimitry Andric   case Decl::ClassTemplateSpecialization: {
413559d1ed5bSDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
413659d1ed5bSDimitry Andric     if (DebugInfo &&
413739d628a0SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
413839d628a0SDimitry Andric         Spec->hasDefinition())
413959d1ed5bSDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
414039d628a0SDimitry Andric     break;
414159d1ed5bSDimitry Andric   }
414259d1ed5bSDimitry Andric 
4143e7145dcbSDimitry Andric   case Decl::OMPDeclareReduction:
4144e7145dcbSDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4145e7145dcbSDimitry Andric     break;
4146e7145dcbSDimitry Andric 
4147f22ef01cSRoman Divacky   default:
4148f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
4149f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4150f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
4151f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
415239d628a0SDimitry Andric     break;
415339d628a0SDimitry Andric   }
415439d628a0SDimitry Andric }
415539d628a0SDimitry Andric 
415639d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
415739d628a0SDimitry Andric   // Do we need to generate coverage mapping?
415839d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
415939d628a0SDimitry Andric     return;
416039d628a0SDimitry Andric   switch (D->getKind()) {
416139d628a0SDimitry Andric   case Decl::CXXConversion:
416239d628a0SDimitry Andric   case Decl::CXXMethod:
416339d628a0SDimitry Andric   case Decl::Function:
416439d628a0SDimitry Andric   case Decl::ObjCMethod:
416539d628a0SDimitry Andric   case Decl::CXXConstructor:
416639d628a0SDimitry Andric   case Decl::CXXDestructor: {
41670623d748SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
416839d628a0SDimitry Andric       return;
416939d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
417039d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
417139d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
417239d628a0SDimitry Andric     break;
417339d628a0SDimitry Andric   }
417439d628a0SDimitry Andric   default:
417539d628a0SDimitry Andric     break;
417639d628a0SDimitry Andric   };
417739d628a0SDimitry Andric }
417839d628a0SDimitry Andric 
417939d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
418039d628a0SDimitry Andric   // Do we need to generate coverage mapping?
418139d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
418239d628a0SDimitry Andric     return;
418339d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
418439d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
418539d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
418639d628a0SDimitry Andric   }
418739d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
418839d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
418939d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
419039d628a0SDimitry Andric   else
419139d628a0SDimitry Andric     I->second = false;
419239d628a0SDimitry Andric }
419339d628a0SDimitry Andric 
419439d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
419539d628a0SDimitry Andric   std::vector<const Decl *> DeferredDecls;
419633956c43SDimitry Andric   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
419739d628a0SDimitry Andric     if (!I.second)
419839d628a0SDimitry Andric       continue;
419939d628a0SDimitry Andric     DeferredDecls.push_back(I.first);
420039d628a0SDimitry Andric   }
420139d628a0SDimitry Andric   // Sort the declarations by their location to make sure that the tests get a
420239d628a0SDimitry Andric   // predictable order for the coverage mapping for the unused declarations.
420339d628a0SDimitry Andric   if (CodeGenOpts.DumpCoverageMapping)
420439d628a0SDimitry Andric     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
420539d628a0SDimitry Andric               [] (const Decl *LHS, const Decl *RHS) {
420639d628a0SDimitry Andric       return LHS->getLocStart() < RHS->getLocStart();
420739d628a0SDimitry Andric     });
420839d628a0SDimitry Andric   for (const auto *D : DeferredDecls) {
420939d628a0SDimitry Andric     switch (D->getKind()) {
421039d628a0SDimitry Andric     case Decl::CXXConversion:
421139d628a0SDimitry Andric     case Decl::CXXMethod:
421239d628a0SDimitry Andric     case Decl::Function:
421339d628a0SDimitry Andric     case Decl::ObjCMethod: {
421439d628a0SDimitry Andric       CodeGenPGO PGO(*this);
421539d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
421639d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
421739d628a0SDimitry Andric                                   getFunctionLinkage(GD));
421839d628a0SDimitry Andric       break;
421939d628a0SDimitry Andric     }
422039d628a0SDimitry Andric     case Decl::CXXConstructor: {
422139d628a0SDimitry Andric       CodeGenPGO PGO(*this);
422239d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
422339d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
422439d628a0SDimitry Andric                                   getFunctionLinkage(GD));
422539d628a0SDimitry Andric       break;
422639d628a0SDimitry Andric     }
422739d628a0SDimitry Andric     case Decl::CXXDestructor: {
422839d628a0SDimitry Andric       CodeGenPGO PGO(*this);
422939d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
423039d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
423139d628a0SDimitry Andric                                   getFunctionLinkage(GD));
423239d628a0SDimitry Andric       break;
423339d628a0SDimitry Andric     }
423439d628a0SDimitry Andric     default:
423539d628a0SDimitry Andric       break;
423639d628a0SDimitry Andric     };
4237f22ef01cSRoman Divacky   }
4238f22ef01cSRoman Divacky }
4239ffd1746dSEd Schouten 
4240ffd1746dSEd Schouten /// Turns the given pointer into a constant.
4241ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4242ffd1746dSEd Schouten                                           const void *Ptr) {
4243ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
42446122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4245ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
4246ffd1746dSEd Schouten }
4247ffd1746dSEd Schouten 
4248ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4249ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
4250ffd1746dSEd Schouten                                    GlobalDecl D,
4251ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
4252ffd1746dSEd Schouten   if (!GlobalMetadata)
4253ffd1746dSEd Schouten     GlobalMetadata =
4254ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4255ffd1746dSEd Schouten 
4256ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
425739d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
425839d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
425939d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
42603b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4261ffd1746dSEd Schouten }
4262ffd1746dSEd Schouten 
4263284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
4264284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
4265284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
4266284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
4267284c1978SDimitry Andric /// same translation unit.
4268284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
4269e7145dcbSDimitry Andric   // Don't do anything if we're generating CUDA device code -- the NVPTX
4270e7145dcbSDimitry Andric   // assembly target doesn't support aliases.
4271e7145dcbSDimitry Andric   if (Context.getTargetInfo().getTriple().isNVPTX())
4272e7145dcbSDimitry Andric     return;
42738f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
42748f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
42758f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
4276284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
427759d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4278284c1978SDimitry Andric   }
4279284c1978SDimitry Andric }
4280284c1978SDimitry Andric 
428159d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
428259d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
428359d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
428459d1ed5bSDimitry Andric   if (Res == Manglings.end())
428559d1ed5bSDimitry Andric     return false;
428659d1ed5bSDimitry Andric   Result = Res->getValue();
428759d1ed5bSDimitry Andric   return true;
428859d1ed5bSDimitry Andric }
428959d1ed5bSDimitry Andric 
4290ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
4291ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
4292ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
4293ffd1746dSEd Schouten ///
4294ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
4295ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
4296ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
4297ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
429859d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4299ffd1746dSEd Schouten 
430059d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
430159d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
43020623d748SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
43030623d748SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
43040623d748SDimitry Andric     if (Addr)
430559d1ed5bSDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4306ffd1746dSEd Schouten   }
4307ffd1746dSEd Schouten }
4308ffd1746dSEd Schouten 
4309ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
4310ffd1746dSEd Schouten /// function.
4311ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
4312ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
4313ffd1746dSEd Schouten 
4314ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
4315ffd1746dSEd Schouten 
4316ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
4317ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4318ffd1746dSEd Schouten 
431959d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4320ffd1746dSEd Schouten 
432159d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
432259d1ed5bSDimitry Andric     const Decl *D = I.first;
43230623d748SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
432459d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4325ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
432639d628a0SDimitry Andric       Alloca->setMetadata(
432739d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
432839d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
432959d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4330ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4331ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4332ffd1746dSEd Schouten     }
4333ffd1746dSEd Schouten   }
4334ffd1746dSEd Schouten }
4335e580952dSDimitry Andric 
4336f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
4337f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
4338f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
4339f785676fSDimitry Andric   std::string Version = getClangFullVersion();
4340f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
4341f785676fSDimitry Andric 
434239d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4343f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4344f785676fSDimitry Andric }
4345f785676fSDimitry Andric 
434659d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
434739d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
434839d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
434939d628a0SDimitry Andric   // of the container.
435039d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
435139d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
435239d628a0SDimitry Andric   // metadata when we emitted the declaration.
435339d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
435439d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
435539d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
435639d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
435759d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
435859d1ed5bSDimitry Andric   }
435959d1ed5bSDimitry Andric }
436059d1ed5bSDimitry Andric 
4361bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
436244290647SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
436344290647SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
436444290647SDimitry Andric     return;
436544290647SDimitry Andric 
436644290647SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
436744290647SDimitry Andric   if (!CUNode)
436844290647SDimitry Andric     return;
436944290647SDimitry Andric 
4370bd5abe19SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4371bd5abe19SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
437244290647SDimitry Andric   auto *CoverageDataFile =
437344290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
437444290647SDimitry Andric   auto *CoverageNotesFile =
437544290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4376bd5abe19SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4377bd5abe19SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
437844290647SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
437939d628a0SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4380bd5abe19SDimitry Andric   }
4381bd5abe19SDimitry Andric }
43823861d79fSDimitry Andric 
438339d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
43843861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
43853861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
43863861d79fSDimitry Andric   assert(Uuid.size() == 36);
4387f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
4388f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4389f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
43903861d79fSDimitry Andric   }
43913861d79fSDimitry Andric 
439239d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4393f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
43943861d79fSDimitry Andric 
4395f785676fSDimitry Andric   llvm::Constant *Field3[8];
4396f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
4397f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
4398f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
43993861d79fSDimitry Andric 
4400f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
4401f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4402f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4403f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4404f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4405f785676fSDimitry Andric   };
4406f785676fSDimitry Andric 
4407f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
44083861d79fSDimitry Andric }
440959d1ed5bSDimitry Andric 
441059d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
441159d1ed5bSDimitry Andric                                                        bool ForEH) {
441259d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
441359d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
441459d1ed5bSDimitry Andric   // and it's not for EH?
441559d1ed5bSDimitry Andric   if (!ForEH && !getLangOpts().RTTI)
441659d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
441759d1ed5bSDimitry Andric 
441859d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
441959d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
442059d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
442159d1ed5bSDimitry Andric 
442259d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
442359d1ed5bSDimitry Andric }
442459d1ed5bSDimitry Andric 
442539d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
442639d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
442739d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
442839d628a0SDimitry Andric     bool PerformInit =
442939d628a0SDimitry Andric         VD->getAnyInitializer() &&
443039d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
443139d628a0SDimitry Andric                                                         /*ForRef=*/false);
44320623d748SDimitry Andric 
44330623d748SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
443433956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
44350623d748SDimitry Andric             VD, Addr, RefExpr->getLocStart(), PerformInit))
443639d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
443739d628a0SDimitry Andric   }
443839d628a0SDimitry Andric }
44398f0fd8f6SDimitry Andric 
44400623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
44410623d748SDimitry Andric   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
44420623d748SDimitry Andric   if (InternalId)
44430623d748SDimitry Andric     return InternalId;
44440623d748SDimitry Andric 
44450623d748SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
44468f0fd8f6SDimitry Andric     std::string OutName;
44478f0fd8f6SDimitry Andric     llvm::raw_string_ostream Out(OutName);
44480623d748SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
44498f0fd8f6SDimitry Andric 
44500623d748SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
44510623d748SDimitry Andric   } else {
44520623d748SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
44530623d748SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
44540623d748SDimitry Andric   }
44550623d748SDimitry Andric 
44560623d748SDimitry Andric   return InternalId;
44570623d748SDimitry Andric }
44580623d748SDimitry Andric 
4459e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
4460e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
4461e7145dcbSDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
4462e7145dcbSDimitry Andric   // is not in the trapping mode.
4463e7145dcbSDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4464e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4465e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4466e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4467e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4468e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4469e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4470e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4471e7145dcbSDimitry Andric }
4472e7145dcbSDimitry Andric 
4473e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
44740623d748SDimitry Andric                                           CharUnits Offset,
44750623d748SDimitry Andric                                           const CXXRecordDecl *RD) {
44760623d748SDimitry Andric   llvm::Metadata *MD =
44770623d748SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4478e7145dcbSDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
44790623d748SDimitry Andric 
4480e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
4481e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4482e7145dcbSDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
4483e7145dcbSDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4484e7145dcbSDimitry Andric 
4485e7145dcbSDimitry Andric   if (NeedAllVtablesTypeId()) {
4486e7145dcbSDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4487e7145dcbSDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
44880623d748SDimitry Andric   }
44890623d748SDimitry Andric }
44900623d748SDimitry Andric 
44910623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the
44920623d748SDimitry Andric // passed in function.
44930623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
44940623d748SDimitry Andric                                           const FunctionDecl *FD) {
44950623d748SDimitry Andric   StringRef TargetCPU = Target.getTargetOpts().CPU;
44960623d748SDimitry Andric   if (const auto *TD = FD->getAttr<TargetAttr>()) {
44970623d748SDimitry Andric     // If we have a TargetAttr build up the feature map based on that.
44980623d748SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
44990623d748SDimitry Andric 
45000623d748SDimitry Andric     // Make a copy of the features as passed on the command line into the
45010623d748SDimitry Andric     // beginning of the additional features from the function to override.
4502b40b48b8SDimitry Andric     ParsedAttr.Features.insert(ParsedAttr.Features.begin(),
45030623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.begin(),
45040623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.end());
45050623d748SDimitry Andric 
4506b40b48b8SDimitry Andric     if (ParsedAttr.Architecture != "")
4507b40b48b8SDimitry Andric       TargetCPU = ParsedAttr.Architecture ;
45080623d748SDimitry Andric 
45090623d748SDimitry Andric     // Now populate the feature map, first with the TargetCPU which is either
45100623d748SDimitry Andric     // the default or a new one from the target attribute string. Then we'll use
45110623d748SDimitry Andric     // the passed in features (FeaturesAsWritten) along with the new ones from
45120623d748SDimitry Andric     // the attribute.
4513b40b48b8SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
4514b40b48b8SDimitry Andric                           ParsedAttr.Features);
45150623d748SDimitry Andric   } else {
45160623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
45170623d748SDimitry Andric                           Target.getTargetOpts().Features);
45180623d748SDimitry Andric   }
45198f0fd8f6SDimitry Andric }
4520e7145dcbSDimitry Andric 
4521e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4522e7145dcbSDimitry Andric   if (!SanStats)
4523e7145dcbSDimitry Andric     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4524e7145dcbSDimitry Andric 
4525e7145dcbSDimitry Andric   return *SanStats;
4526e7145dcbSDimitry Andric }
452744290647SDimitry Andric llvm::Value *
452844290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
452944290647SDimitry Andric                                                   CodeGenFunction &CGF) {
453044290647SDimitry Andric   llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
453144290647SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType();
453244290647SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
453344290647SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
453444290647SDimitry Andric                                 "__translate_sampler_initializer"),
453544290647SDimitry Andric                                 {C});
453644290647SDimitry Andric }
4537