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 
509e7145dcbSDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
510e7145dcbSDimitry Andric     assert(PLevel < 3 && "Invalid PIC Level");
511e7145dcbSDimitry Andric     getModule().setPICLevel(static_cast<llvm::PICLevel::Level>(PLevel));
512e7145dcbSDimitry Andric     if (Context.getLangOpts().PIE)
513e7145dcbSDimitry Andric       getModule().setPIELevel(static_cast<llvm::PIELevel::Level>(PLevel));
51439d628a0SDimitry Andric   }
51539d628a0SDimitry Andric 
5162754fe60SDimitry Andric   SimplifyPersonality();
5172754fe60SDimitry Andric 
518ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
519ffd1746dSEd Schouten     EmitDeclMetadata();
520bd5abe19SDimitry Andric 
521bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
522bd5abe19SDimitry Andric     EmitCoverageFile();
5236122f3e6SDimitry Andric 
5246122f3e6SDimitry Andric   if (DebugInfo)
5256122f3e6SDimitry Andric     DebugInfo->finalize();
526f785676fSDimitry Andric 
527f785676fSDimitry Andric   EmitVersionIdentMetadata();
52859d1ed5bSDimitry Andric 
52959d1ed5bSDimitry Andric   EmitTargetMetadata();
530f22ef01cSRoman Divacky }
531f22ef01cSRoman Divacky 
5323b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
5333b0f4066SDimitry Andric   // Make sure that this type is translated.
5343b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
5353b0f4066SDimitry Andric }
5363b0f4066SDimitry Andric 
537e7145dcbSDimitry Andric void CodeGenModule::RefreshTypeCacheForClass(const CXXRecordDecl *RD) {
538e7145dcbSDimitry Andric   // Make sure that this type is translated.
539e7145dcbSDimitry Andric   Types.RefreshTypeCacheForClass(RD);
540e7145dcbSDimitry Andric }
541e7145dcbSDimitry Andric 
5422754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
5432754fe60SDimitry Andric   if (!TBAA)
54459d1ed5bSDimitry Andric     return nullptr;
5452754fe60SDimitry Andric   return TBAA->getTBAAInfo(QTy);
5462754fe60SDimitry Andric }
5472754fe60SDimitry Andric 
548dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
549dff0c46cSDimitry Andric   if (!TBAA)
55059d1ed5bSDimitry Andric     return nullptr;
551dff0c46cSDimitry Andric   return TBAA->getTBAAInfoForVTablePtr();
552dff0c46cSDimitry Andric }
553dff0c46cSDimitry Andric 
5543861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
5553861d79fSDimitry Andric   if (!TBAA)
55659d1ed5bSDimitry Andric     return nullptr;
5573861d79fSDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
5583861d79fSDimitry Andric }
5593861d79fSDimitry Andric 
560139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
561139f7f9bSDimitry Andric                                                   llvm::MDNode *AccessN,
562139f7f9bSDimitry Andric                                                   uint64_t O) {
563139f7f9bSDimitry Andric   if (!TBAA)
56459d1ed5bSDimitry Andric     return nullptr;
565139f7f9bSDimitry Andric   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
566139f7f9bSDimitry Andric }
567139f7f9bSDimitry Andric 
568f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA
569f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format:
570f785676fSDimitry Andric /// base type, access type and offset.
571284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
5720623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithTBAA(llvm::Instruction *Inst,
573284c1978SDimitry Andric                                                 llvm::MDNode *TBAAInfo,
574284c1978SDimitry Andric                                                 bool ConvertTypeToTag) {
575f785676fSDimitry Andric   if (ConvertTypeToTag && TBAA)
576284c1978SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
577284c1978SDimitry Andric                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
578284c1978SDimitry Andric   else
5792754fe60SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
5802754fe60SDimitry Andric }
5812754fe60SDimitry Andric 
5820623d748SDimitry Andric void CodeGenModule::DecorateInstructionWithInvariantGroup(
5830623d748SDimitry Andric     llvm::Instruction *I, const CXXRecordDecl *RD) {
58451690af2SDimitry Andric   I->setMetadata(llvm::LLVMContext::MD_invariant_group,
58551690af2SDimitry Andric                  llvm::MDNode::get(getLLVMContext(), {}));
5860623d748SDimitry Andric }
5870623d748SDimitry Andric 
58859d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
58959d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
59059d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
591f22ef01cSRoman Divacky }
592f22ef01cSRoman Divacky 
593f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
594f22ef01cSRoman Divacky /// specified stmt yet.
595f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
5966122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
597f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
598f22ef01cSRoman Divacky   std::string Msg = Type;
599f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
600f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
601f22ef01cSRoman Divacky }
602f22ef01cSRoman Divacky 
603f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
604f22ef01cSRoman Divacky /// specified decl yet.
605f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
6066122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
607f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
608f22ef01cSRoman Divacky   std::string Msg = Type;
609f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
610f22ef01cSRoman Divacky }
611f22ef01cSRoman Divacky 
61217a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
61317a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
61417a519f9SDimitry Andric }
61517a519f9SDimitry Andric 
616f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
6172754fe60SDimitry Andric                                         const NamedDecl *D) const {
618f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
619f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
620f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
621f22ef01cSRoman Divacky     return;
622f22ef01cSRoman Divacky   }
623f22ef01cSRoman Divacky 
6242754fe60SDimitry Andric   // Set visibility for definitions.
625139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
626139f7f9bSDimitry Andric   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
627139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
628f22ef01cSRoman Divacky }
629f22ef01cSRoman Divacky 
6307ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
6317ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
6327ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
6337ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
6347ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
6357ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
6367ae0e2c9SDimitry Andric }
6377ae0e2c9SDimitry Andric 
6387ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
6397ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
6407ae0e2c9SDimitry Andric   switch (M) {
6417ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
6427ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
6437ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
6447ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
6457ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
6467ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
6477ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
6487ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
6497ae0e2c9SDimitry Andric   }
6507ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
6517ae0e2c9SDimitry Andric }
6527ae0e2c9SDimitry Andric 
65339d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
654284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
6557ae0e2c9SDimitry Andric 
65639d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
6573861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
6587ae0e2c9SDimitry Andric 
6597ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
66059d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
6617ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
6627ae0e2c9SDimitry Andric   }
6637ae0e2c9SDimitry Andric 
6647ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
6657ae0e2c9SDimitry Andric }
6667ae0e2c9SDimitry Andric 
6676122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
668444ed5c5SDimitry Andric   GlobalDecl CanonicalGD = GD.getCanonicalDecl();
669444ed5c5SDimitry Andric 
670444ed5c5SDimitry Andric   // Some ABIs don't have constructor variants.  Make sure that base and
671444ed5c5SDimitry Andric   // complete constructors get mangled the same.
672444ed5c5SDimitry Andric   if (const auto *CD = dyn_cast<CXXConstructorDecl>(CanonicalGD.getDecl())) {
673444ed5c5SDimitry Andric     if (!getTarget().getCXXABI().hasConstructorVariants()) {
674444ed5c5SDimitry Andric       CXXCtorType OrigCtorType = GD.getCtorType();
675444ed5c5SDimitry Andric       assert(OrigCtorType == Ctor_Base || OrigCtorType == Ctor_Complete);
676444ed5c5SDimitry Andric       if (OrigCtorType == Ctor_Base)
677444ed5c5SDimitry Andric         CanonicalGD = GlobalDecl(CD, Ctor_Complete);
678444ed5c5SDimitry Andric     }
679444ed5c5SDimitry Andric   }
680444ed5c5SDimitry Andric 
681444ed5c5SDimitry Andric   StringRef &FoundStr = MangledDeclNames[CanonicalGD];
68259d1ed5bSDimitry Andric   if (!FoundStr.empty())
68359d1ed5bSDimitry Andric     return FoundStr;
684f22ef01cSRoman Divacky 
68559d1ed5bSDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
686dff0c46cSDimitry Andric   SmallString<256> Buffer;
68759d1ed5bSDimitry Andric   StringRef Str;
68859d1ed5bSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
6892754fe60SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
69059d1ed5bSDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
6912754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
69259d1ed5bSDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
6932754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
694ffd1746dSEd Schouten     else
6952754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleName(ND, Out);
69659d1ed5bSDimitry Andric     Str = Out.str();
69759d1ed5bSDimitry Andric   } else {
69859d1ed5bSDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
69959d1ed5bSDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
70044290647SDimitry Andric     const auto *FD = dyn_cast<FunctionDecl>(ND);
70144290647SDimitry Andric 
70244290647SDimitry Andric     if (FD &&
70344290647SDimitry Andric         FD->getType()->castAs<FunctionType>()->getCallConv() == CC_X86RegCall) {
70444290647SDimitry Andric       llvm::raw_svector_ostream Out(Buffer);
70544290647SDimitry Andric       Out << "__regcall3__" << II->getName();
70644290647SDimitry Andric       Str = Out.str();
70744290647SDimitry Andric     } else {
70859d1ed5bSDimitry Andric       Str = II->getName();
709ffd1746dSEd Schouten     }
71044290647SDimitry Andric   }
711ffd1746dSEd Schouten 
71239d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
71339d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Str, GD));
71439d628a0SDimitry Andric   return FoundStr = Result.first->first();
71559d1ed5bSDimitry Andric }
71659d1ed5bSDimitry Andric 
71759d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
718ffd1746dSEd Schouten                                              const BlockDecl *BD) {
7192754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
7202754fe60SDimitry Andric   const Decl *D = GD.getDecl();
72159d1ed5bSDimitry Andric 
72259d1ed5bSDimitry Andric   SmallString<256> Buffer;
72359d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
72459d1ed5bSDimitry Andric   if (!D)
7257ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
7267ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
72759d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
7282754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
72959d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
7302754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
7312754fe60SDimitry Andric   else
7322754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
73359d1ed5bSDimitry Andric 
73439d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
73539d628a0SDimitry Andric   return Result.first->first();
736f22ef01cSRoman Divacky }
737f22ef01cSRoman Divacky 
7386122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
739f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
740f22ef01cSRoman Divacky }
741f22ef01cSRoman Divacky 
742f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
743f22ef01cSRoman Divacky /// main() runs.
74459d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
74559d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
746f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
74759d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
748f22ef01cSRoman Divacky }
749f22ef01cSRoman Divacky 
750f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
751f22ef01cSRoman Divacky /// when the module is unloaded.
752f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
753f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
75459d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
755f22ef01cSRoman Divacky }
756f22ef01cSRoman Divacky 
75744290647SDimitry Andric void CodeGenModule::EmitCtorList(CtorList &Fns, const char *GlobalName) {
75844290647SDimitry Andric   if (Fns.empty()) return;
75944290647SDimitry Andric 
760f22ef01cSRoman Divacky   // Ctor function type is void()*.
761bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
762f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
763f22ef01cSRoman Divacky 
76459d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
76559d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
7665517e702SDimitry Andric       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy);
767f22ef01cSRoman Divacky 
768f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
76944290647SDimitry Andric   ConstantInitBuilder builder(*this);
77044290647SDimitry Andric   auto ctors = builder.beginArray(CtorStructTy);
7718f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
77244290647SDimitry Andric     auto ctor = ctors.beginStruct(CtorStructTy);
77344290647SDimitry Andric     ctor.addInt(Int32Ty, I.Priority);
77444290647SDimitry Andric     ctor.add(llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy));
77544290647SDimitry Andric     if (I.AssociatedData)
77644290647SDimitry Andric       ctor.add(llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy));
77744290647SDimitry Andric     else
77844290647SDimitry Andric       ctor.addNullPointer(VoidPtrTy);
77944290647SDimitry Andric     ctor.finishAndAddTo(ctors);
780f22ef01cSRoman Divacky   }
781f22ef01cSRoman Divacky 
78244290647SDimitry Andric   auto list =
78344290647SDimitry Andric     ctors.finishAndCreateGlobal(GlobalName, getPointerAlign(),
78444290647SDimitry Andric                                 /*constant*/ false,
78544290647SDimitry Andric                                 llvm::GlobalValue::AppendingLinkage);
78644290647SDimitry Andric 
78744290647SDimitry Andric   // The LTO linker doesn't seem to like it when we set an alignment
78844290647SDimitry Andric   // on appending variables.  Take it off as a workaround.
78944290647SDimitry Andric   list->setAlignment(0);
79044290647SDimitry Andric 
79144290647SDimitry Andric   Fns.clear();
792f22ef01cSRoman Divacky }
793f22ef01cSRoman Divacky 
794f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
795f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
79659d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
797f785676fSDimitry Andric 
798e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
799f22ef01cSRoman Divacky 
80059d1ed5bSDimitry Andric   if (isa<CXXDestructorDecl>(D) &&
80159d1ed5bSDimitry Andric       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
80259d1ed5bSDimitry Andric                                          GD.getDtorType())) {
80359d1ed5bSDimitry Andric     // Destructor variants in the Microsoft C++ ABI are always internal or
80459d1ed5bSDimitry Andric     // linkonce_odr thunks emitted on an as-needed basis.
80559d1ed5bSDimitry Andric     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
80659d1ed5bSDimitry Andric                                    : llvm::GlobalValue::LinkOnceODRLinkage;
807f22ef01cSRoman Divacky   }
808f22ef01cSRoman Divacky 
809e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(D) &&
810e7145dcbSDimitry Andric       cast<CXXConstructorDecl>(D)->isInheritingConstructor() &&
811e7145dcbSDimitry Andric       Context.getTargetInfo().getCXXABI().isMicrosoft()) {
812e7145dcbSDimitry Andric     // Our approach to inheriting constructors is fundamentally different from
813e7145dcbSDimitry Andric     // that used by the MS ABI, so keep our inheriting constructor thunks
814e7145dcbSDimitry Andric     // internal rather than trying to pick an unambiguous mangling for them.
815e7145dcbSDimitry Andric     return llvm::GlobalValue::InternalLinkage;
816e7145dcbSDimitry Andric   }
817e7145dcbSDimitry Andric 
81859d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
81959d1ed5bSDimitry Andric }
820f22ef01cSRoman Divacky 
82197bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
82297bc6c73SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
82397bc6c73SDimitry Andric 
82497bc6c73SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
82597bc6c73SDimitry Andric     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
82697bc6c73SDimitry Andric       // Don't dllexport/import destructor thunks.
82797bc6c73SDimitry Andric       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
82897bc6c73SDimitry Andric       return;
82997bc6c73SDimitry Andric     }
83097bc6c73SDimitry Andric   }
83197bc6c73SDimitry Andric 
83297bc6c73SDimitry Andric   if (FD->hasAttr<DLLImportAttr>())
83397bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
83497bc6c73SDimitry Andric   else if (FD->hasAttr<DLLExportAttr>())
83597bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
83697bc6c73SDimitry Andric   else
83797bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
83897bc6c73SDimitry Andric }
83997bc6c73SDimitry Andric 
840e7145dcbSDimitry Andric llvm::ConstantInt *CodeGenModule::CreateCrossDsoCfiTypeId(llvm::Metadata *MD) {
8410623d748SDimitry Andric   llvm::MDString *MDS = dyn_cast<llvm::MDString>(MD);
8420623d748SDimitry Andric   if (!MDS) return nullptr;
8430623d748SDimitry Andric 
84444290647SDimitry Andric   return llvm::ConstantInt::get(Int64Ty, llvm::MD5Hash(MDS->getString()));
8450623d748SDimitry Andric }
8460623d748SDimitry Andric 
84759d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
84859d1ed5bSDimitry Andric                                                     llvm::Function *F) {
84959d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
850f22ef01cSRoman Divacky }
851f22ef01cSRoman Divacky 
852f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
853f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
854f22ef01cSRoman Divacky                                               llvm::Function *F) {
855f22ef01cSRoman Divacky   unsigned CallingConv;
8566bc11b14SDimitry Andric   llvm::AttributeList PAL;
8576bc11b14SDimitry Andric   ConstructAttributeList(F->getName(), Info, D, PAL, CallingConv, false);
8586bc11b14SDimitry Andric   F->setAttributes(PAL);
859f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
860f22ef01cSRoman Divacky }
861f22ef01cSRoman Divacky 
8626122f3e6SDimitry Andric /// Determines whether the language options require us to model
8636122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
8646122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
8656122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
8666122f3e6SDimitry Andric /// enables this.
867dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
8686122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
869dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
8706122f3e6SDimitry Andric 
8716122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
872dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
8736122f3e6SDimitry Andric 
8746122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
875dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
8767ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
8776122f3e6SDimitry Andric   }
8786122f3e6SDimitry Andric 
8796122f3e6SDimitry Andric   return true;
8806122f3e6SDimitry Andric }
8816122f3e6SDimitry Andric 
882f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
883f22ef01cSRoman Divacky                                                            llvm::Function *F) {
884f785676fSDimitry Andric   llvm::AttrBuilder B;
885f785676fSDimitry Andric 
886bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
887f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
888bd5abe19SDimitry Andric 
889dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
890f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
891f22ef01cSRoman Divacky 
8920623d748SDimitry Andric   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
8930623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
8940623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
8950623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
8960623d748SDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
8970623d748SDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
8980623d748SDimitry Andric 
8990623d748SDimitry Andric   if (!D) {
90044290647SDimitry Andric     // If we don't have a declaration to control inlining, the function isn't
90144290647SDimitry Andric     // explicitly marked as alwaysinline for semantic reasons, and inlining is
90244290647SDimitry Andric     // disabled, mark the function as noinline.
90344290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
90444290647SDimitry Andric         CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining)
90544290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
90644290647SDimitry Andric 
907f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
9080623d748SDimitry Andric     return;
9090623d748SDimitry Andric   }
9100623d748SDimitry Andric 
911302affcbSDimitry Andric   // Track whether we need to add the optnone LLVM attribute,
912302affcbSDimitry Andric   // starting with the default for this optimization level.
913302affcbSDimitry Andric   bool ShouldAddOptNone =
914302affcbSDimitry Andric       !CodeGenOpts.DisableO0ImplyOptNone && CodeGenOpts.OptimizationLevel == 0;
915302affcbSDimitry Andric   // We can't add optnone in the following cases, it won't pass the verifier.
916302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<MinSizeAttr>();
917302affcbSDimitry Andric   ShouldAddOptNone &= !F->hasFnAttribute(llvm::Attribute::AlwaysInline);
918302affcbSDimitry Andric   ShouldAddOptNone &= !D->hasAttr<AlwaysInlineAttr>();
919302affcbSDimitry Andric 
920302affcbSDimitry Andric   if (ShouldAddOptNone || D->hasAttr<OptimizeNoneAttr>()) {
92144290647SDimitry Andric     B.addAttribute(llvm::Attribute::OptimizeNone);
92244290647SDimitry Andric 
92344290647SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
92444290647SDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
92544290647SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
92644290647SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
92744290647SDimitry Andric 
92844290647SDimitry Andric     // We still need to handle naked functions even though optnone subsumes
92944290647SDimitry Andric     // much of their semantics.
93044290647SDimitry Andric     if (D->hasAttr<NakedAttr>())
93144290647SDimitry Andric       B.addAttribute(llvm::Attribute::Naked);
93244290647SDimitry Andric 
93344290647SDimitry Andric     // OptimizeNone wins over OptimizeForSize and MinSize.
93444290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::OptimizeForSize);
93544290647SDimitry Andric     F->removeFnAttr(llvm::Attribute::MinSize);
93644290647SDimitry Andric   } else if (D->hasAttr<NakedAttr>()) {
9376122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
938f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
939f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
94059d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
94159d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
942f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
943f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
94459d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
94544290647SDimitry Andric              !F->hasFnAttribute(llvm::Attribute::NoInline)) {
946f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
947f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
94844290647SDimitry Andric   } else if (CodeGenOpts.getInlining() == CodeGenOptions::OnlyAlwaysInlining) {
94944290647SDimitry Andric     // If we're not inlining, then force everything that isn't always_inline to
95044290647SDimitry Andric     // carry an explicit noinline attribute.
95144290647SDimitry Andric     if (!F->hasFnAttribute(llvm::Attribute::AlwaysInline))
95244290647SDimitry Andric       B.addAttribute(llvm::Attribute::NoInline);
95344290647SDimitry Andric   } else {
95444290647SDimitry Andric     // Otherwise, propagate the inline hint attribute and potentially use its
95544290647SDimitry Andric     // absence to mark things as noinline.
95644290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D)) {
95744290647SDimitry Andric       if (any_of(FD->redecls(), [&](const FunctionDecl *Redecl) {
95844290647SDimitry Andric             return Redecl->isInlineSpecified();
95944290647SDimitry Andric           })) {
96044290647SDimitry Andric         B.addAttribute(llvm::Attribute::InlineHint);
96144290647SDimitry Andric       } else if (CodeGenOpts.getInlining() ==
96244290647SDimitry Andric                      CodeGenOptions::OnlyHintInlining &&
96344290647SDimitry Andric                  !FD->isInlined() &&
96444290647SDimitry Andric                  !F->hasFnAttribute(llvm::Attribute::AlwaysInline)) {
96544290647SDimitry Andric         B.addAttribute(llvm::Attribute::NoInline);
96644290647SDimitry Andric       }
96744290647SDimitry Andric     }
9686122f3e6SDimitry Andric   }
9692754fe60SDimitry Andric 
97044290647SDimitry Andric   // Add other optimization related attributes if we are optimizing this
97144290647SDimitry Andric   // function.
97244290647SDimitry Andric   if (!D->hasAttr<OptimizeNoneAttr>()) {
973f785676fSDimitry Andric     if (D->hasAttr<ColdAttr>()) {
974302affcbSDimitry Andric       if (!ShouldAddOptNone)
975f785676fSDimitry Andric         B.addAttribute(llvm::Attribute::OptimizeForSize);
976f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::Cold);
977f785676fSDimitry Andric     }
9783861d79fSDimitry Andric 
9793861d79fSDimitry Andric     if (D->hasAttr<MinSizeAttr>())
980f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::MinSize);
98144290647SDimitry Andric   }
982f22ef01cSRoman Divacky 
983f37b6182SDimitry Andric   F->addAttributes(llvm::AttributeList::FunctionIndex, B);
984f785676fSDimitry Andric 
985e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
986e580952dSDimitry Andric   if (alignment)
987e580952dSDimitry Andric     F->setAlignment(alignment);
988e580952dSDimitry Andric 
9890623d748SDimitry Andric   // Some C++ ABIs require 2-byte alignment for member functions, in order to
9900623d748SDimitry Andric   // reserve a bit for differentiating between virtual and non-virtual member
9910623d748SDimitry Andric   // functions. If the current target's C++ ABI requires this and this is a
9920623d748SDimitry Andric   // member function, set its alignment accordingly.
9930623d748SDimitry Andric   if (getTarget().getCXXABI().areMemberFunctionsAligned()) {
994f22ef01cSRoman Divacky     if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
995f22ef01cSRoman Divacky       F->setAlignment(2);
996f22ef01cSRoman Divacky   }
99744290647SDimitry Andric 
99844290647SDimitry Andric   // In the cross-dso CFI mode, we want !type attributes on definitions only.
99944290647SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
100044290647SDimitry Andric     if (auto *FD = dyn_cast<FunctionDecl>(D))
100144290647SDimitry Andric       CreateFunctionTypeMetadata(FD, F);
10020623d748SDimitry Andric }
1003f22ef01cSRoman Divacky 
1004f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
1005f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
10060623d748SDimitry Andric   if (const auto *ND = dyn_cast_or_null<NamedDecl>(D))
10072754fe60SDimitry Andric     setGlobalVisibility(GV, ND);
10082754fe60SDimitry Andric   else
10092754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
1010f22ef01cSRoman Divacky 
10110623d748SDimitry Andric   if (D && D->hasAttr<UsedAttr>())
101259d1ed5bSDimitry Andric     addUsedGlobal(GV);
101359d1ed5bSDimitry Andric }
101459d1ed5bSDimitry Andric 
101539d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D,
101639d628a0SDimitry Andric                                        llvm::GlobalValue *GV) {
101739d628a0SDimitry Andric   SetCommonAttributes(D, GV);
101839d628a0SDimitry Andric 
101939d628a0SDimitry Andric   // Process the dllexport attribute based on whether the original definition
102039d628a0SDimitry Andric   // (not necessarily the aliasee) was exported.
102139d628a0SDimitry Andric   if (D->hasAttr<DLLExportAttr>())
102239d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
102339d628a0SDimitry Andric }
102439d628a0SDimitry Andric 
102559d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D,
102659d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
102759d1ed5bSDimitry Andric   SetCommonAttributes(D, GO);
1028f22ef01cSRoman Divacky 
10290623d748SDimitry Andric   if (D)
1030f22ef01cSRoman Divacky     if (const SectionAttr *SA = D->getAttr<SectionAttr>())
103159d1ed5bSDimitry Andric       GO->setSection(SA->getName());
1032f22ef01cSRoman Divacky 
103397bc6c73SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
1034f22ef01cSRoman Divacky }
1035f22ef01cSRoman Divacky 
1036f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
1037f22ef01cSRoman Divacky                                                   llvm::Function *F,
1038f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
1039f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
1040f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
1041f22ef01cSRoman Divacky 
1042f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
1043f22ef01cSRoman Divacky 
104459d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
104559d1ed5bSDimitry Andric }
104659d1ed5bSDimitry Andric 
104759d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
104859d1ed5bSDimitry Andric                                          const NamedDecl *ND) {
104959d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
105059d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
105159d1ed5bSDimitry Andric   if (LV.getLinkage() != ExternalLinkage) {
105259d1ed5bSDimitry Andric     // Don't set internal linkage on declarations.
105359d1ed5bSDimitry Andric   } else {
105459d1ed5bSDimitry Andric     if (ND->hasAttr<DLLImportAttr>()) {
105559d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
105659d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
105759d1ed5bSDimitry Andric     } else if (ND->hasAttr<DLLExportAttr>()) {
105859d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
105959d1ed5bSDimitry Andric     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
106059d1ed5bSDimitry Andric       // "extern_weak" is overloaded in LLVM; we probably should have
106159d1ed5bSDimitry Andric       // separate linkage types for this.
106259d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
106359d1ed5bSDimitry Andric     }
106459d1ed5bSDimitry Andric 
106559d1ed5bSDimitry Andric     // Set visibility on a declaration only if it's explicit.
106659d1ed5bSDimitry Andric     if (LV.isVisibilityExplicit())
106759d1ed5bSDimitry Andric       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
106859d1ed5bSDimitry Andric   }
1069f22ef01cSRoman Divacky }
1070f22ef01cSRoman Divacky 
1071e7145dcbSDimitry Andric void CodeGenModule::CreateFunctionTypeMetadata(const FunctionDecl *FD,
10720623d748SDimitry Andric                                                llvm::Function *F) {
10730623d748SDimitry Andric   // Only if we are checking indirect calls.
10740623d748SDimitry Andric   if (!LangOpts.Sanitize.has(SanitizerKind::CFIICall))
10750623d748SDimitry Andric     return;
10760623d748SDimitry Andric 
10770623d748SDimitry Andric   // Non-static class methods are handled via vtable pointer checks elsewhere.
10780623d748SDimitry Andric   if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
10790623d748SDimitry Andric     return;
10800623d748SDimitry Andric 
10810623d748SDimitry Andric   // Additionally, if building with cross-DSO support...
10820623d748SDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso) {
10830623d748SDimitry Andric     // Skip available_externally functions. They won't be codegen'ed in the
10840623d748SDimitry Andric     // current module anyway.
10850623d748SDimitry Andric     if (getContext().GetGVALinkageForFunction(FD) == GVA_AvailableExternally)
10860623d748SDimitry Andric       return;
10870623d748SDimitry Andric   }
10880623d748SDimitry Andric 
10890623d748SDimitry Andric   llvm::Metadata *MD = CreateMetadataIdentifierForType(FD->getType());
1090e7145dcbSDimitry Andric   F->addTypeMetadata(0, MD);
10910623d748SDimitry Andric 
10920623d748SDimitry Andric   // Emit a hash-based bit set entry for cross-DSO calls.
1093e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
1094e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
1095e7145dcbSDimitry Andric       F->addTypeMetadata(0, llvm::ConstantAsMetadata::get(CrossDsoTypeId));
10960623d748SDimitry Andric }
10970623d748SDimitry Andric 
109839d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
109939d628a0SDimitry Andric                                           bool IsIncompleteFunction,
110039d628a0SDimitry Andric                                           bool IsThunk) {
110133956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
11023b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
11033b0f4066SDimitry Andric     // to the intrinsic's attributes.
110433956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
11053b0f4066SDimitry Andric     return;
11063b0f4066SDimitry Andric   }
11073b0f4066SDimitry Andric 
110859d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
1109f22ef01cSRoman Divacky 
1110f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
1111dff0c46cSDimitry Andric     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
1112f22ef01cSRoman Divacky 
111359d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
111459d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
111559d1ed5bSDimitry Andric   // GCC and does not actually return "this".
111639d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
111744290647SDimitry Andric       !(getTriple().isiOS() && getTriple().isOSVersionLT(6))) {
1118f785676fSDimitry Andric     assert(!F->arg_empty() &&
1119f785676fSDimitry Andric            F->arg_begin()->getType()
1120f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
1121f785676fSDimitry Andric            "unexpected this return");
1122f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
1123f785676fSDimitry Andric   }
1124f785676fSDimitry Andric 
1125f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
1126f22ef01cSRoman Divacky   // overridden by a definition.
1127f22ef01cSRoman Divacky 
112859d1ed5bSDimitry Andric   setLinkageAndVisibilityForGV(F, FD);
11292754fe60SDimitry Andric 
1130f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
1131f22ef01cSRoman Divacky     F->setSection(SA->getName());
1132f785676fSDimitry Andric 
1133e7145dcbSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction()) {
1134f785676fSDimitry Andric     // A replaceable global allocation function does not act like a builtin by
1135f785676fSDimitry Andric     // default, only if it is invoked by a new-expression or delete-expression.
113620e90f04SDimitry Andric     F->addAttribute(llvm::AttributeList::FunctionIndex,
1137f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
11380623d748SDimitry Andric 
1139e7145dcbSDimitry Andric     // A sane operator new returns a non-aliasing pointer.
1140e7145dcbSDimitry Andric     // FIXME: Also add NonNull attribute to the return value
1141e7145dcbSDimitry Andric     // for the non-nothrow forms?
1142e7145dcbSDimitry Andric     auto Kind = FD->getDeclName().getCXXOverloadedOperator();
1143e7145dcbSDimitry Andric     if (getCodeGenOpts().AssumeSaneOperatorNew &&
1144e7145dcbSDimitry Andric         (Kind == OO_New || Kind == OO_Array_New))
114520e90f04SDimitry Andric       F->addAttribute(llvm::AttributeList::ReturnIndex,
1146e7145dcbSDimitry Andric                       llvm::Attribute::NoAlias);
1147e7145dcbSDimitry Andric   }
1148e7145dcbSDimitry Andric 
1149e7145dcbSDimitry Andric   if (isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD))
1150e7145dcbSDimitry Andric     F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1151e7145dcbSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1152e7145dcbSDimitry Andric     if (MD->isVirtual())
1153e7145dcbSDimitry Andric       F->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1154e7145dcbSDimitry Andric 
115544290647SDimitry Andric   // Don't emit entries for function declarations in the cross-DSO mode. This
115644290647SDimitry Andric   // is handled with better precision by the receiving DSO.
115744290647SDimitry Andric   if (!CodeGenOpts.SanitizeCfiCrossDso)
1158e7145dcbSDimitry Andric     CreateFunctionTypeMetadata(FD, F);
1159f22ef01cSRoman Divacky }
1160f22ef01cSRoman Divacky 
116159d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
1162f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
1163f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
116497bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
1165f22ef01cSRoman Divacky }
1166f22ef01cSRoman Divacky 
116759d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
116859d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
116959d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
117097bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
117159d1ed5bSDimitry Andric }
117259d1ed5bSDimitry Andric 
117359d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
1174f37b6182SDimitry Andric                      std::vector<llvm::WeakTrackingVH> &List) {
1175f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
117659d1ed5bSDimitry Andric   if (List.empty())
1177f22ef01cSRoman Divacky     return;
1178f22ef01cSRoman Divacky 
117959d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
1180dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
118159d1ed5bSDimitry Andric   UsedArray.resize(List.size());
118259d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
1183f22ef01cSRoman Divacky     UsedArray[i] =
118444f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
118544f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
1186f22ef01cSRoman Divacky   }
1187f22ef01cSRoman Divacky 
1188f22ef01cSRoman Divacky   if (UsedArray.empty())
1189f22ef01cSRoman Divacky     return;
119059d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
1191f22ef01cSRoman Divacky 
119259d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
119359d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
119459d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
1195f22ef01cSRoman Divacky 
1196f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
1197f22ef01cSRoman Divacky }
1198f22ef01cSRoman Divacky 
119959d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
120059d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
120159d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
120259d1ed5bSDimitry Andric }
120359d1ed5bSDimitry Andric 
1204f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
120539d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
1206f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1207f785676fSDimitry Andric }
1208f785676fSDimitry Andric 
1209f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
1210f785676fSDimitry Andric   llvm::SmallString<32> Opt;
1211f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
121239d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1213f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1214f785676fSDimitry Andric }
1215f785676fSDimitry Andric 
1216f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
1217f785676fSDimitry Andric   llvm::SmallString<24> Opt;
1218f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
121939d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
1220f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
1221f785676fSDimitry Andric }
1222f785676fSDimitry Andric 
1223139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules
1224139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
122539d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
122639d628a0SDimitry Andric                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
1227139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
1228139f7f9bSDimitry Andric   // Import this module's parent.
122939d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
1230f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
1231139f7f9bSDimitry Andric   }
1232139f7f9bSDimitry Andric 
1233139f7f9bSDimitry Andric   // Import this module's dependencies.
1234139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
123539d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
1236f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
1237139f7f9bSDimitry Andric   }
1238139f7f9bSDimitry Andric 
1239139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
1240139f7f9bSDimitry Andric   // described by this module.
1241f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
1242139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1243f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1244f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1245139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
124639d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1247139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
124839d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1249139f7f9bSDimitry Andric 
1250139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1251139f7f9bSDimitry Andric       continue;
1252139f7f9bSDimitry Andric     }
1253139f7f9bSDimitry Andric 
1254139f7f9bSDimitry Andric     // Link against a library.
1255f785676fSDimitry Andric     llvm::SmallString<24> Opt;
1256f785676fSDimitry Andric     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1257f785676fSDimitry Andric       Mod->LinkLibraries[I-1].Library, Opt);
125839d628a0SDimitry Andric     auto *OptString = llvm::MDString::get(Context, Opt);
1259139f7f9bSDimitry Andric     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1260139f7f9bSDimitry Andric   }
1261139f7f9bSDimitry Andric }
1262139f7f9bSDimitry Andric 
1263139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1264139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1265139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1266139f7f9bSDimitry Andric   // non-explicit child modules.
1267139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1268139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1269139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1270139f7f9bSDimitry Andric 
1271139f7f9bSDimitry Andric   // Seed the stack with imported modules.
1272f1a29dd3SDimitry Andric   for (Module *M : ImportedModules) {
1273f1a29dd3SDimitry Andric     // Do not add any link flags when an implementation TU of a module imports
1274f1a29dd3SDimitry Andric     // a header of that same module.
1275f1a29dd3SDimitry Andric     if (M->getTopLevelModuleName() == getLangOpts().CurrentModule &&
1276f1a29dd3SDimitry Andric         !getLangOpts().isCompilingModule())
1277f1a29dd3SDimitry Andric       continue;
12788f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
12798f0fd8f6SDimitry Andric       Stack.push_back(M);
1280f1a29dd3SDimitry Andric   }
1281139f7f9bSDimitry Andric 
1282139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1283139f7f9bSDimitry Andric   // non-leaf modules.
1284139f7f9bSDimitry Andric   while (!Stack.empty()) {
1285f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1286139f7f9bSDimitry Andric 
1287139f7f9bSDimitry Andric     bool AnyChildren = false;
1288139f7f9bSDimitry Andric 
1289139f7f9bSDimitry Andric     // Visit the submodules of this module.
1290139f7f9bSDimitry Andric     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1291139f7f9bSDimitry Andric                                         SubEnd = Mod->submodule_end();
1292139f7f9bSDimitry Andric          Sub != SubEnd; ++Sub) {
1293139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1294139f7f9bSDimitry Andric       // linked against.
1295139f7f9bSDimitry Andric       if ((*Sub)->IsExplicit)
1296139f7f9bSDimitry Andric         continue;
1297139f7f9bSDimitry Andric 
129839d628a0SDimitry Andric       if (Visited.insert(*Sub).second) {
1299139f7f9bSDimitry Andric         Stack.push_back(*Sub);
1300139f7f9bSDimitry Andric         AnyChildren = true;
1301139f7f9bSDimitry Andric       }
1302139f7f9bSDimitry Andric     }
1303139f7f9bSDimitry Andric 
1304139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1305139f7f9bSDimitry Andric     // modules to link against.
1306139f7f9bSDimitry Andric     if (!AnyChildren) {
1307139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1308139f7f9bSDimitry Andric     }
1309139f7f9bSDimitry Andric   }
1310139f7f9bSDimitry Andric 
1311139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1312f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1313f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
131439d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1315139f7f9bSDimitry Andric   Visited.clear();
13168f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
13178f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
13188f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1319139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1320f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1321139f7f9bSDimitry Andric 
1322139f7f9bSDimitry Andric   // Add the linker options metadata flag.
1323139f7f9bSDimitry Andric   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1324f785676fSDimitry Andric                             llvm::MDNode::get(getLLVMContext(),
1325f785676fSDimitry Andric                                               LinkerOptionsMetadata));
1326139f7f9bSDimitry Andric }
1327139f7f9bSDimitry Andric 
1328f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1329f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1330f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1331f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1332f22ef01cSRoman Divacky 
1333f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1334139f7f9bSDimitry Andric     EmitDeferredVTables();
1335139f7f9bSDimitry Andric 
1336e7145dcbSDimitry Andric     // Emitting a vtable doesn't directly cause more vtables to
1337139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1338e7145dcbSDimitry Andric     // emitted that then need those vtables.
1339139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1340f22ef01cSRoman Divacky   }
1341f22ef01cSRoman Divacky 
1342e7145dcbSDimitry Andric   // Stop if we're out of both deferred vtables and deferred declarations.
134333956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
134433956c43SDimitry Andric     return;
1345139f7f9bSDimitry Andric 
134633956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
134733956c43SDimitry Andric   // work, it will not interfere with this.
1348f37b6182SDimitry Andric   std::vector<GlobalDecl> CurDeclsToEmit;
134933956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
135033956c43SDimitry Andric 
1351f37b6182SDimitry Andric   for (GlobalDecl &D : CurDeclsToEmit) {
13520623d748SDimitry Andric     // We should call GetAddrOfGlobal with IsForDefinition set to true in order
13530623d748SDimitry Andric     // to get GlobalValue with exactly the type we need, not something that
13540623d748SDimitry Andric     // might had been created for another decl with the same mangled name but
13550623d748SDimitry Andric     // different type.
1356e7145dcbSDimitry Andric     llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(
135744290647SDimitry Andric         GetAddrOfGlobal(D, ForDefinition));
1358e7145dcbSDimitry Andric 
1359e7145dcbSDimitry Andric     // In case of different address spaces, we may still get a cast, even with
1360e7145dcbSDimitry Andric     // IsForDefinition equal to true. Query mangled names table to get
1361e7145dcbSDimitry Andric     // GlobalValue.
136239d628a0SDimitry Andric     if (!GV)
136339d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
136439d628a0SDimitry Andric 
1365e7145dcbSDimitry Andric     // Make sure GetGlobalValue returned non-null.
1366e7145dcbSDimitry Andric     assert(GV);
1367e7145dcbSDimitry Andric 
1368f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1369f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1370f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1371f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1372f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1373f22ef01cSRoman Divacky     // ignore these cases.
1374e7145dcbSDimitry Andric     if (!GV->isDeclaration())
1375f22ef01cSRoman Divacky       continue;
1376f22ef01cSRoman Divacky 
1377f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
137859d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
137933956c43SDimitry Andric 
138033956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
138133956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
138233956c43SDimitry Andric     // ones are close together, which is convenient for testing.
138333956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
138433956c43SDimitry Andric       EmitDeferred();
138533956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
138633956c43SDimitry Andric     }
1387f22ef01cSRoman Divacky   }
1388f22ef01cSRoman Divacky }
1389f22ef01cSRoman Divacky 
1390f9448bf3SDimitry Andric void CodeGenModule::EmitVTablesOpportunistically() {
1391f9448bf3SDimitry Andric   // Try to emit external vtables as available_externally if they have emitted
1392f9448bf3SDimitry Andric   // all inlined virtual functions.  It runs after EmitDeferred() and therefore
1393f9448bf3SDimitry Andric   // is not allowed to create new references to things that need to be emitted
1394f9448bf3SDimitry Andric   // lazily. Note that it also uses fact that we eagerly emitting RTTI.
1395f9448bf3SDimitry Andric 
1396f9448bf3SDimitry Andric   assert((OpportunisticVTables.empty() || shouldOpportunisticallyEmitVTables())
1397f9448bf3SDimitry Andric          && "Only emit opportunistic vtables with optimizations");
1398f9448bf3SDimitry Andric 
1399f9448bf3SDimitry Andric   for (const CXXRecordDecl *RD : OpportunisticVTables) {
1400f9448bf3SDimitry Andric     assert(getVTables().isVTableExternal(RD) &&
1401f9448bf3SDimitry Andric            "This queue should only contain external vtables");
1402f9448bf3SDimitry Andric     if (getCXXABI().canSpeculativelyEmitVTable(RD))
1403f9448bf3SDimitry Andric       VTables.GenerateClassData(RD);
1404f9448bf3SDimitry Andric   }
1405f9448bf3SDimitry Andric   OpportunisticVTables.clear();
1406f9448bf3SDimitry Andric }
1407f9448bf3SDimitry Andric 
14086122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
14096122f3e6SDimitry Andric   if (Annotations.empty())
14106122f3e6SDimitry Andric     return;
14116122f3e6SDimitry Andric 
14126122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
14136122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
14146122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
141559d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
141659d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
141759d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
14186122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
14196122f3e6SDimitry Andric }
14206122f3e6SDimitry Andric 
1421139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1422f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1423f785676fSDimitry Andric   if (AStr)
1424f785676fSDimitry Andric     return AStr;
14256122f3e6SDimitry Andric 
14266122f3e6SDimitry Andric   // Not found yet, create a new global.
1427dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
142859d1ed5bSDimitry Andric   auto *gv =
142959d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
143059d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
14316122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
1432e7145dcbSDimitry Andric   gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1433f785676fSDimitry Andric   AStr = gv;
14346122f3e6SDimitry Andric   return gv;
14356122f3e6SDimitry Andric }
14366122f3e6SDimitry Andric 
14376122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
14386122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14396122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
14406122f3e6SDimitry Andric   if (PLoc.isValid())
14416122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
14426122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
14436122f3e6SDimitry Andric }
14446122f3e6SDimitry Andric 
14456122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
14466122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
14476122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
14486122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
14496122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
14506122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
14516122f3e6SDimitry Andric }
14526122f3e6SDimitry Andric 
1453f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1454f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
14556122f3e6SDimitry Andric                                                 SourceLocation L) {
14566122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
14576122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
14586122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
14596122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1460f22ef01cSRoman Divacky 
1461f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1462f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
14636122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
14646122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
14656122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
14666122f3e6SDimitry Andric     LineNoCst
1467f22ef01cSRoman Divacky   };
146817a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1469f22ef01cSRoman Divacky }
1470f22ef01cSRoman Divacky 
14716122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
14726122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
14736122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
14746122f3e6SDimitry Andric   // Get the struct elements for these annotations.
147559d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
147659d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
14776122f3e6SDimitry Andric }
14786122f3e6SDimitry Andric 
147939d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
148039d628a0SDimitry Andric                                            SourceLocation Loc) const {
148139d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
148239d628a0SDimitry Andric   // Blacklist by function name.
148339d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
148439d628a0SDimitry Andric     return true;
148539d628a0SDimitry Andric   // Blacklist by location.
14860623d748SDimitry Andric   if (Loc.isValid())
148739d628a0SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Loc);
148839d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
148939d628a0SDimitry Andric   // it's located in the main file.
149039d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
149139d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
149239d628a0SDimitry Andric     return SanitizerBL.isBlacklistedFile(MainFile->getName());
149339d628a0SDimitry Andric   }
149439d628a0SDimitry Andric   return false;
149539d628a0SDimitry Andric }
149639d628a0SDimitry Andric 
149739d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
149839d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
149939d628a0SDimitry Andric                                            StringRef Category) const {
15008f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
15018f0fd8f6SDimitry Andric   if (!LangOpts.Sanitize.hasOneOf(
15028f0fd8f6SDimitry Andric           SanitizerKind::Address | SanitizerKind::KernelAddress))
150339d628a0SDimitry Andric     return false;
150439d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
150539d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
150639d628a0SDimitry Andric     return true;
150739d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
150839d628a0SDimitry Andric     return true;
150939d628a0SDimitry Andric   // Check global type.
151039d628a0SDimitry Andric   if (!Ty.isNull()) {
151139d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
151239d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
151339d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
151439d628a0SDimitry Andric       Ty = AT->getElementType();
151539d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
151639d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
151739d628a0SDimitry Andric     if (Ty->isRecordType()) {
151839d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
151939d628a0SDimitry Andric       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
152039d628a0SDimitry Andric         return true;
152139d628a0SDimitry Andric     }
152239d628a0SDimitry Andric   }
152339d628a0SDimitry Andric   return false;
152439d628a0SDimitry Andric }
152539d628a0SDimitry Andric 
152620e90f04SDimitry Andric bool CodeGenModule::imbueXRayAttrs(llvm::Function *Fn, SourceLocation Loc,
152720e90f04SDimitry Andric                                    StringRef Category) const {
152820e90f04SDimitry Andric   if (!LangOpts.XRayInstrument)
152920e90f04SDimitry Andric     return false;
153020e90f04SDimitry Andric   const auto &XRayFilter = getContext().getXRayFilter();
153120e90f04SDimitry Andric   using ImbueAttr = XRayFunctionFilter::ImbueAttribute;
153220e90f04SDimitry Andric   auto Attr = XRayFunctionFilter::ImbueAttribute::NONE;
153320e90f04SDimitry Andric   if (Loc.isValid())
153420e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueLocation(Loc, Category);
153520e90f04SDimitry Andric   if (Attr == ImbueAttr::NONE)
153620e90f04SDimitry Andric     Attr = XRayFilter.shouldImbueFunction(Fn->getName());
153720e90f04SDimitry Andric   switch (Attr) {
153820e90f04SDimitry Andric   case ImbueAttr::NONE:
153920e90f04SDimitry Andric     return false;
154020e90f04SDimitry Andric   case ImbueAttr::ALWAYS:
154120e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
154220e90f04SDimitry Andric     break;
1543302affcbSDimitry Andric   case ImbueAttr::ALWAYS_ARG1:
1544302affcbSDimitry Andric     Fn->addFnAttr("function-instrument", "xray-always");
1545302affcbSDimitry Andric     Fn->addFnAttr("xray-log-args", "1");
1546302affcbSDimitry Andric     break;
154720e90f04SDimitry Andric   case ImbueAttr::NEVER:
154820e90f04SDimitry Andric     Fn->addFnAttr("function-instrument", "xray-never");
154920e90f04SDimitry Andric     break;
155020e90f04SDimitry Andric   }
155120e90f04SDimitry Andric   return true;
155220e90f04SDimitry Andric }
155320e90f04SDimitry Andric 
155439d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1555e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
1556dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
155739d628a0SDimitry Andric     return true;
155839d628a0SDimitry Andric 
155939d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
156039d628a0SDimitry Andric }
156139d628a0SDimitry Andric 
156239d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
156339d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
156439d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
156539d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
156639d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
1567f22ef01cSRoman Divacky       return false;
1568e7145dcbSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(Global))
1569e7145dcbSDimitry Andric     if (Context.getInlineVariableDefinitionKind(VD) ==
1570e7145dcbSDimitry Andric         ASTContext::InlineVariableDefinitionKind::WeakUnknown)
1571e7145dcbSDimitry Andric       // A definition of an inline constexpr static data member may change
1572e7145dcbSDimitry Andric       // linkage later if it's redeclared outside the class.
1573e7145dcbSDimitry Andric       return false;
1574875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1575875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
1576875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1577875ed548SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1578875ed548SDimitry Andric     return false;
1579f22ef01cSRoman Divacky 
158039d628a0SDimitry Andric   return true;
1581f22ef01cSRoman Divacky }
1582f22ef01cSRoman Divacky 
15830623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfUuidDescriptor(
15843861d79fSDimitry Andric     const CXXUuidofExpr* E) {
15853861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
15863861d79fSDimitry Andric   // well-formed.
1587e7145dcbSDimitry Andric   StringRef Uuid = E->getUuidStr();
1588f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
1589f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
15903861d79fSDimitry Andric 
1591e7145dcbSDimitry Andric   // The UUID descriptor should be pointer aligned.
1592e7145dcbSDimitry Andric   CharUnits Alignment = CharUnits::fromQuantity(PointerAlignInBytes);
15930623d748SDimitry Andric 
15943861d79fSDimitry Andric   // Look for an existing global.
15953861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
15960623d748SDimitry Andric     return ConstantAddress(GV, Alignment);
15973861d79fSDimitry Andric 
159839d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
15993861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
16003861d79fSDimitry Andric 
160159d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
1602f785676fSDimitry Andric       getModule(), Init->getType(),
1603f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
160433956c43SDimitry Andric   if (supportsCOMDAT())
160533956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
16060623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
16073861d79fSDimitry Andric }
16083861d79fSDimitry Andric 
16090623d748SDimitry Andric ConstantAddress CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1610f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1611f22ef01cSRoman Divacky   assert(AA && "No alias?");
1612f22ef01cSRoman Divacky 
16130623d748SDimitry Andric   CharUnits Alignment = getContext().getDeclAlign(VD);
16146122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1615f22ef01cSRoman Divacky 
1616f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
1617f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
16183861d79fSDimitry Andric   if (Entry) {
16193861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
16200623d748SDimitry Andric     auto Ptr = llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
16210623d748SDimitry Andric     return ConstantAddress(Ptr, Alignment);
16223861d79fSDimitry Andric   }
1623f22ef01cSRoman Divacky 
1624f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1625f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
16263861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
16273861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
16282754fe60SDimitry Andric                                       /*ForVTable=*/false);
1629f22ef01cSRoman Divacky   else
1630f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
163159d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
163259d1ed5bSDimitry Andric                                     nullptr);
16333861d79fSDimitry Andric 
163459d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
1635f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1636f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
1637f22ef01cSRoman Divacky 
16380623d748SDimitry Andric   return ConstantAddress(Aliasee, Alignment);
1639f22ef01cSRoman Divacky }
1640f22ef01cSRoman Divacky 
1641f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
164259d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
1643f22ef01cSRoman Divacky 
1644f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
1645f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
1646f22ef01cSRoman Divacky     return;
1647f22ef01cSRoman Divacky 
1648f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
1649f22ef01cSRoman Divacky   // emit it now.
1650f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
1651f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
1652f22ef01cSRoman Divacky 
1653e7145dcbSDimitry Andric   // IFunc like an alias whose value is resolved at runtime by calling resolver.
1654e7145dcbSDimitry Andric   if (Global->hasAttr<IFuncAttr>())
1655e7145dcbSDimitry Andric     return emitIFuncDefinition(GD);
1656e7145dcbSDimitry Andric 
16576122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
1658dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
165933956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
16606122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
16616122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
16626122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
16636122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
16646122f3e6SDimitry Andric         return;
16656122f3e6SDimitry Andric     } else {
1666e7145dcbSDimitry Andric       // We need to emit host-side 'shadows' for all global
1667e7145dcbSDimitry Andric       // device-side variables because the CUDA runtime needs their
1668e7145dcbSDimitry Andric       // size and host-side address in order to provide access to
1669e7145dcbSDimitry Andric       // their device-side incarnations.
1670e7145dcbSDimitry Andric 
1671e7145dcbSDimitry Andric       // So device-only functions are the only things we skip.
1672e7145dcbSDimitry Andric       if (isa<FunctionDecl>(Global) && !Global->hasAttr<CUDAHostAttr>() &&
1673e7145dcbSDimitry Andric           Global->hasAttr<CUDADeviceAttr>())
16746122f3e6SDimitry Andric         return;
1675e7145dcbSDimitry Andric 
1676e7145dcbSDimitry Andric       assert((isa<FunctionDecl>(Global) || isa<VarDecl>(Global)) &&
1677e7145dcbSDimitry Andric              "Expected Variable or Function");
1678e580952dSDimitry Andric     }
1679e580952dSDimitry Andric   }
1680e580952dSDimitry Andric 
1681e7145dcbSDimitry Andric   if (LangOpts.OpenMP) {
1682ea942507SDimitry Andric     // If this is OpenMP device, check if it is legal to emit this global
1683ea942507SDimitry Andric     // normally.
1684ea942507SDimitry Andric     if (OpenMPRuntime && OpenMPRuntime->emitTargetGlobal(GD))
1685ea942507SDimitry Andric       return;
1686e7145dcbSDimitry Andric     if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(Global)) {
1687e7145dcbSDimitry Andric       if (MustBeEmitted(Global))
1688e7145dcbSDimitry Andric         EmitOMPDeclareReduction(DRD);
1689e7145dcbSDimitry Andric       return;
1690e7145dcbSDimitry Andric     }
1691e7145dcbSDimitry Andric   }
1692ea942507SDimitry Andric 
16936122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
169459d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1695f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
16966122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
16976122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1698f22ef01cSRoman Divacky         return;
16996122f3e6SDimitry Andric 
17006122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
170159d1ed5bSDimitry Andric 
170259d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
170359d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
170459d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
170559d1ed5bSDimitry Andric 
170659d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
170759d1ed5bSDimitry Andric                               /*DontDefer=*/false);
17086122f3e6SDimitry Andric       return;
17096122f3e6SDimitry Andric     }
1710f22ef01cSRoman Divacky   } else {
171159d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
1712f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1713e7145dcbSDimitry Andric     // We need to emit device-side global CUDA variables even if a
1714e7145dcbSDimitry Andric     // variable does not have a definition -- we still need to define
1715e7145dcbSDimitry Andric     // host-side shadow for it.
1716e7145dcbSDimitry Andric     bool MustEmitForCuda = LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
1717e7145dcbSDimitry Andric                            !VD->hasDefinition() &&
1718e7145dcbSDimitry Andric                            (VD->hasAttr<CUDAConstantAttr>() ||
1719e7145dcbSDimitry Andric                             VD->hasAttr<CUDADeviceAttr>());
1720e7145dcbSDimitry Andric     if (!MustEmitForCuda &&
1721e7145dcbSDimitry Andric         VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1722e7145dcbSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD)) {
1723e7145dcbSDimitry Andric       // If this declaration may have caused an inline variable definition to
1724e7145dcbSDimitry Andric       // change linkage, make sure that it's emitted.
1725e7145dcbSDimitry Andric       if (Context.getInlineVariableDefinitionKind(VD) ==
1726e7145dcbSDimitry Andric           ASTContext::InlineVariableDefinitionKind::Strong)
1727e7145dcbSDimitry Andric         GetAddrOfGlobalVar(VD);
1728f22ef01cSRoman Divacky       return;
1729f22ef01cSRoman Divacky     }
1730e7145dcbSDimitry Andric   }
1731f22ef01cSRoman Divacky 
173239d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
173339d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
173439d628a0SDimitry Andric   // to benefit from cache locality.
173539d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1736f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
1737f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
1738f22ef01cSRoman Divacky     return;
1739f22ef01cSRoman Divacky   }
1740f22ef01cSRoman Divacky 
1741e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
1742e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
1743dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1744e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
1745e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
174659d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
1747e580952dSDimitry Andric   }
1748e580952dSDimitry Andric 
17496122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
1750f37b6182SDimitry Andric   if (GetGlobalValue(MangledName) != nullptr) {
175139d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
1752f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
175339d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
175439d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
175539d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
1756f37b6182SDimitry Andric     addDeferredDeclToEmit(GD);
175739d628a0SDimitry Andric   } else {
1758f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
1759f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
1760f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
1761f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
1762f22ef01cSRoman Divacky   }
1763f22ef01cSRoman Divacky }
1764f22ef01cSRoman Divacky 
176520e90f04SDimitry Andric // Check if T is a class type with a destructor that's not dllimport.
176620e90f04SDimitry Andric static bool HasNonDllImportDtor(QualType T) {
176720e90f04SDimitry Andric   if (const auto *RT = T->getBaseElementTypeUnsafe()->getAs<RecordType>())
176820e90f04SDimitry Andric     if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl()))
176920e90f04SDimitry Andric       if (RD->getDestructor() && !RD->getDestructor()->hasAttr<DLLImportAttr>())
177020e90f04SDimitry Andric         return true;
177120e90f04SDimitry Andric 
177220e90f04SDimitry Andric   return false;
177320e90f04SDimitry Andric }
177420e90f04SDimitry Andric 
1775f8254f43SDimitry Andric namespace {
1776f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
1777f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1778f8254f43SDimitry Andric     const StringRef Name;
1779dff0c46cSDimitry Andric     const Builtin::Context &BI;
1780f8254f43SDimitry Andric     bool Result;
1781dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1782dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
1783f8254f43SDimitry Andric     }
1784f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1785f8254f43SDimitry Andric 
1786f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
1787dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
1788dff0c46cSDimitry Andric       if (!FD)
1789f8254f43SDimitry Andric         return true;
1790dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1791dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
1792dff0c46cSDimitry Andric         Result = true;
1793dff0c46cSDimitry Andric         return false;
1794dff0c46cSDimitry Andric       }
1795dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
17963dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1797f8254f43SDimitry Andric         return true;
17980623d748SDimitry Andric       StringRef BuiltinName = BI.getName(BuiltinID);
1799dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
1800dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1801f8254f43SDimitry Andric         Result = true;
1802f8254f43SDimitry Andric         return false;
1803f8254f43SDimitry Andric       }
1804f8254f43SDimitry Andric       return true;
1805f8254f43SDimitry Andric     }
1806f8254f43SDimitry Andric   };
18070623d748SDimitry Andric 
180820e90f04SDimitry Andric   // Make sure we're not referencing non-imported vars or functions.
18090623d748SDimitry Andric   struct DLLImportFunctionVisitor
18100623d748SDimitry Andric       : public RecursiveASTVisitor<DLLImportFunctionVisitor> {
18110623d748SDimitry Andric     bool SafeToInline = true;
18120623d748SDimitry Andric 
181344290647SDimitry Andric     bool shouldVisitImplicitCode() const { return true; }
181444290647SDimitry Andric 
18150623d748SDimitry Andric     bool VisitVarDecl(VarDecl *VD) {
181620e90f04SDimitry Andric       if (VD->getTLSKind()) {
18170623d748SDimitry Andric         // A thread-local variable cannot be imported.
181820e90f04SDimitry Andric         SafeToInline = false;
18190623d748SDimitry Andric         return SafeToInline;
18200623d748SDimitry Andric       }
18210623d748SDimitry Andric 
182220e90f04SDimitry Andric       // A variable definition might imply a destructor call.
182320e90f04SDimitry Andric       if (VD->isThisDeclarationADefinition())
182420e90f04SDimitry Andric         SafeToInline = !HasNonDllImportDtor(VD->getType());
182520e90f04SDimitry Andric 
182620e90f04SDimitry Andric       return SafeToInline;
182720e90f04SDimitry Andric     }
182820e90f04SDimitry Andric 
182920e90f04SDimitry Andric     bool VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
183020e90f04SDimitry Andric       if (const auto *D = E->getTemporary()->getDestructor())
183120e90f04SDimitry Andric         SafeToInline = D->hasAttr<DLLImportAttr>();
183220e90f04SDimitry Andric       return SafeToInline;
183320e90f04SDimitry Andric     }
183420e90f04SDimitry Andric 
18350623d748SDimitry Andric     bool VisitDeclRefExpr(DeclRefExpr *E) {
18360623d748SDimitry Andric       ValueDecl *VD = E->getDecl();
18370623d748SDimitry Andric       if (isa<FunctionDecl>(VD))
18380623d748SDimitry Andric         SafeToInline = VD->hasAttr<DLLImportAttr>();
18390623d748SDimitry Andric       else if (VarDecl *V = dyn_cast<VarDecl>(VD))
18400623d748SDimitry Andric         SafeToInline = !V->hasGlobalStorage() || V->hasAttr<DLLImportAttr>();
18410623d748SDimitry Andric       return SafeToInline;
18420623d748SDimitry Andric     }
184320e90f04SDimitry Andric 
184444290647SDimitry Andric     bool VisitCXXConstructExpr(CXXConstructExpr *E) {
184544290647SDimitry Andric       SafeToInline = E->getConstructor()->hasAttr<DLLImportAttr>();
184644290647SDimitry Andric       return SafeToInline;
184744290647SDimitry Andric     }
184820e90f04SDimitry Andric 
184920e90f04SDimitry Andric     bool VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
185020e90f04SDimitry Andric       CXXMethodDecl *M = E->getMethodDecl();
185120e90f04SDimitry Andric       if (!M) {
185220e90f04SDimitry Andric         // Call through a pointer to member function. This is safe to inline.
185320e90f04SDimitry Andric         SafeToInline = true;
185420e90f04SDimitry Andric       } else {
185520e90f04SDimitry Andric         SafeToInline = M->hasAttr<DLLImportAttr>();
185620e90f04SDimitry Andric       }
185720e90f04SDimitry Andric       return SafeToInline;
185820e90f04SDimitry Andric     }
185920e90f04SDimitry Andric 
18600623d748SDimitry Andric     bool VisitCXXDeleteExpr(CXXDeleteExpr *E) {
18610623d748SDimitry Andric       SafeToInline = E->getOperatorDelete()->hasAttr<DLLImportAttr>();
18620623d748SDimitry Andric       return SafeToInline;
18630623d748SDimitry Andric     }
186420e90f04SDimitry Andric 
18650623d748SDimitry Andric     bool VisitCXXNewExpr(CXXNewExpr *E) {
18660623d748SDimitry Andric       SafeToInline = E->getOperatorNew()->hasAttr<DLLImportAttr>();
18670623d748SDimitry Andric       return SafeToInline;
18680623d748SDimitry Andric     }
18690623d748SDimitry Andric   };
1870f8254f43SDimitry Andric }
1871f8254f43SDimitry Andric 
1872dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
1873dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
1874dff0c46cSDimitry Andric // ends up pointing to itself.
1875f8254f43SDimitry Andric bool
1876dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1877dff0c46cSDimitry Andric   StringRef Name;
1878dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1879dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
1880dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1881dff0c46cSDimitry Andric     if (!Attr)
1882f8254f43SDimitry Andric       return false;
1883dff0c46cSDimitry Andric     Name = Attr->getLabel();
1884dff0c46cSDimitry Andric   } else {
1885dff0c46cSDimitry Andric     Name = FD->getName();
1886dff0c46cSDimitry Andric   }
1887f8254f43SDimitry Andric 
1888dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1889dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1890f8254f43SDimitry Andric   return Walker.Result;
1891f8254f43SDimitry Andric }
1892f8254f43SDimitry Andric 
189344290647SDimitry Andric bool CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1894f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1895f8254f43SDimitry Andric     return true;
189659d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
189759d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1898f8254f43SDimitry Andric     return false;
18990623d748SDimitry Andric 
19000623d748SDimitry Andric   if (F->hasAttr<DLLImportAttr>()) {
19010623d748SDimitry Andric     // Check whether it would be safe to inline this dllimport function.
19020623d748SDimitry Andric     DLLImportFunctionVisitor Visitor;
19030623d748SDimitry Andric     Visitor.TraverseFunctionDecl(const_cast<FunctionDecl*>(F));
19040623d748SDimitry Andric     if (!Visitor.SafeToInline)
19050623d748SDimitry Andric       return false;
190644290647SDimitry Andric 
190744290647SDimitry Andric     if (const CXXDestructorDecl *Dtor = dyn_cast<CXXDestructorDecl>(F)) {
190844290647SDimitry Andric       // Implicit destructor invocations aren't captured in the AST, so the
190944290647SDimitry Andric       // check above can't see them. Check for them manually here.
191044290647SDimitry Andric       for (const Decl *Member : Dtor->getParent()->decls())
191144290647SDimitry Andric         if (isa<FieldDecl>(Member))
191244290647SDimitry Andric           if (HasNonDllImportDtor(cast<FieldDecl>(Member)->getType()))
191344290647SDimitry Andric             return false;
191444290647SDimitry Andric       for (const CXXBaseSpecifier &B : Dtor->getParent()->bases())
191544290647SDimitry Andric         if (HasNonDllImportDtor(B.getType()))
191644290647SDimitry Andric           return false;
191744290647SDimitry Andric     }
19180623d748SDimitry Andric   }
19190623d748SDimitry Andric 
1920f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
1921f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
1922f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
1923f8254f43SDimitry Andric   // implementation.
1924f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
1925dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
1926f8254f43SDimitry Andric }
1927f8254f43SDimitry Andric 
1928f9448bf3SDimitry Andric bool CodeGenModule::shouldOpportunisticallyEmitVTables() {
1929f9448bf3SDimitry Andric   return CodeGenOpts.OptimizationLevel > 0;
1930f9448bf3SDimitry Andric }
1931f9448bf3SDimitry Andric 
193259d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
193359d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
1934f22ef01cSRoman Divacky 
1935f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1936f22ef01cSRoman Divacky                                  Context.getSourceManager(),
1937f22ef01cSRoman Divacky                                  "Generating code for declaration");
1938f22ef01cSRoman Divacky 
1939f785676fSDimitry Andric   if (isa<FunctionDecl>(D)) {
1940ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
1941ffd1746dSEd Schouten     // linkage.
1942f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
1943ffd1746dSEd Schouten       return;
1944ffd1746dSEd Schouten 
194559d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1946bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
1947bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
194859d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
194939d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
195059d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
195139d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1952bd5abe19SDimitry Andric       else
195359d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
1954bd5abe19SDimitry Andric 
1955f22ef01cSRoman Divacky       if (Method->isVirtual())
1956f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
1957f22ef01cSRoman Divacky 
1958bd5abe19SDimitry Andric       return;
1959ffd1746dSEd Schouten     }
1960f22ef01cSRoman Divacky 
196159d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
1962ffd1746dSEd Schouten   }
1963f22ef01cSRoman Divacky 
196459d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
1965e7145dcbSDimitry Andric     return EmitGlobalVarDefinition(VD, !VD->hasDefinition());
1966f22ef01cSRoman Divacky 
19676122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1968f22ef01cSRoman Divacky }
1969f22ef01cSRoman Divacky 
19700623d748SDimitry Andric static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
19710623d748SDimitry Andric                                                       llvm::Function *NewFn);
19720623d748SDimitry Andric 
1973f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1974f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
1975f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
1976f22ef01cSRoman Divacky /// bitcasted to the right type.
1977f22ef01cSRoman Divacky ///
1978f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
1979f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
198020e90f04SDimitry Andric llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(
198120e90f04SDimitry Andric     StringRef MangledName, llvm::Type *Ty, GlobalDecl GD, bool ForVTable,
198220e90f04SDimitry Andric     bool DontDefer, bool IsThunk, llvm::AttributeList ExtraAttrs,
198344290647SDimitry Andric     ForDefinition_t IsForDefinition) {
1984f785676fSDimitry Andric   const Decl *D = GD.getDecl();
1985f785676fSDimitry Andric 
1986f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
1987f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1988f22ef01cSRoman Divacky   if (Entry) {
19893861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
1990f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1991f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
1992f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
1993f22ef01cSRoman Divacky     }
1994f22ef01cSRoman Divacky 
199539d628a0SDimitry Andric     // Handle dropped DLL attributes.
199639d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
199739d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
199839d628a0SDimitry Andric 
19990623d748SDimitry Andric     // If there are two attempts to define the same mangled name, issue an
20000623d748SDimitry Andric     // error.
20010623d748SDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
20020623d748SDimitry Andric       GlobalDecl OtherGD;
2003e7145dcbSDimitry Andric       // Check that GD is not yet in DiagnosedConflictingDefinitions is required
2004e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
20050623d748SDimitry Andric       if (lookupRepresentativeDecl(MangledName, OtherGD) &&
20060623d748SDimitry Andric           (GD.getCanonicalDecl().getDecl() !=
20070623d748SDimitry Andric            OtherGD.getCanonicalDecl().getDecl()) &&
20080623d748SDimitry Andric           DiagnosedConflictingDefinitions.insert(GD).second) {
20090623d748SDimitry Andric         getDiags().Report(D->getLocation(),
20100623d748SDimitry Andric                           diag::err_duplicate_mangled_name);
20110623d748SDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
20120623d748SDimitry Andric                           diag::note_previous_definition);
20130623d748SDimitry Andric       }
20140623d748SDimitry Andric     }
20150623d748SDimitry Andric 
20160623d748SDimitry Andric     if ((isa<llvm::Function>(Entry) || isa<llvm::GlobalAlias>(Entry)) &&
20170623d748SDimitry Andric         (Entry->getType()->getElementType() == Ty)) {
2018f22ef01cSRoman Divacky       return Entry;
20190623d748SDimitry Andric     }
2020f22ef01cSRoman Divacky 
2021f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
20220623d748SDimitry Andric     // (If function is requested for a definition, we always need to create a new
20230623d748SDimitry Andric     // function, not just return a bitcast.)
20240623d748SDimitry Andric     if (!IsForDefinition)
202517a519f9SDimitry Andric       return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
2026f22ef01cSRoman Divacky   }
2027f22ef01cSRoman Divacky 
2028f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
2029f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
2030f22ef01cSRoman Divacky   // sure not to try to set attributes.
2031f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
2032f22ef01cSRoman Divacky 
20336122f3e6SDimitry Andric   llvm::FunctionType *FTy;
2034f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
2035f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
2036f22ef01cSRoman Divacky   } else {
2037bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
2038f22ef01cSRoman Divacky     IsIncompleteFunction = true;
2039f22ef01cSRoman Divacky   }
2040ffd1746dSEd Schouten 
20410623d748SDimitry Andric   llvm::Function *F =
20420623d748SDimitry Andric       llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
20430623d748SDimitry Andric                              Entry ? StringRef() : MangledName, &getModule());
20440623d748SDimitry Andric 
20450623d748SDimitry Andric   // If we already created a function with the same mangled name (but different
20460623d748SDimitry Andric   // type) before, take its name and add it to the list of functions to be
20470623d748SDimitry Andric   // replaced with F at the end of CodeGen.
20480623d748SDimitry Andric   //
20490623d748SDimitry Andric   // This happens if there is a prototype for a function (e.g. "int f()") and
20500623d748SDimitry Andric   // then a definition of a different type (e.g. "int f(int x)").
20510623d748SDimitry Andric   if (Entry) {
20520623d748SDimitry Andric     F->takeName(Entry);
20530623d748SDimitry Andric 
20540623d748SDimitry Andric     // This might be an implementation of a function without a prototype, in
20550623d748SDimitry Andric     // which case, try to do special replacement of calls which match the new
20560623d748SDimitry Andric     // prototype.  The really key thing here is that we also potentially drop
20570623d748SDimitry Andric     // arguments from the call site so as to make a direct call, which makes the
20580623d748SDimitry Andric     // inliner happier and suppresses a number of optimizer warnings (!) about
20590623d748SDimitry Andric     // dropping arguments.
20600623d748SDimitry Andric     if (!Entry->use_empty()) {
20610623d748SDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(Entry, F);
20620623d748SDimitry Andric       Entry->removeDeadConstantUsers();
20630623d748SDimitry Andric     }
20640623d748SDimitry Andric 
20650623d748SDimitry Andric     llvm::Constant *BC = llvm::ConstantExpr::getBitCast(
20660623d748SDimitry Andric         F, Entry->getType()->getElementType()->getPointerTo());
20670623d748SDimitry Andric     addGlobalValReplacement(Entry, BC);
20680623d748SDimitry Andric   }
20690623d748SDimitry Andric 
2070f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
2071f785676fSDimitry Andric   if (D)
207239d628a0SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
207320e90f04SDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeList::FunctionIndex)) {
207420e90f04SDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeList::FunctionIndex);
2075f37b6182SDimitry Andric     F->addAttributes(llvm::AttributeList::FunctionIndex, B);
2076139f7f9bSDimitry Andric   }
2077f22ef01cSRoman Divacky 
207859d1ed5bSDimitry Andric   if (!DontDefer) {
207959d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
208059d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
208159d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
208259d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
208359d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
208459d1ed5bSDimitry Andric                                            GD.getDtorType()))
2085f37b6182SDimitry Andric       addDeferredDeclToEmit(GD);
208659d1ed5bSDimitry Andric 
2087f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
2088f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
2089f22ef01cSRoman Divacky     // of the file.
209059d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
2091f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
209259d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
209359d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
209459d1ed5bSDimitry Andric       // don't need it anymore).
2095f37b6182SDimitry Andric       addDeferredDeclToEmit(DDI->second);
2096f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
20972754fe60SDimitry Andric 
20982754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
20992754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
21002754fe60SDimitry Andric       // we might not find a top-level definition:
21012754fe60SDimitry Andric       //   - member functions defined inline in their classes
21022754fe60SDimitry Andric       //   - friend functions defined inline in some class
21032754fe60SDimitry Andric       //   - special member functions with implicit definitions
21042754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
21052754fe60SDimitry Andric       // this will be unnecessary.
21062754fe60SDimitry Andric       //
210759d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
210839d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
2109f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
21102754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
211139d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
211239d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
21132754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
211439d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
2115f37b6182SDimitry Andric             addDeferredDeclToEmit(GD.getWithDecl(FD));
21162754fe60SDimitry Andric             break;
2117f22ef01cSRoman Divacky           }
2118f22ef01cSRoman Divacky         }
211939d628a0SDimitry Andric       }
2120f22ef01cSRoman Divacky     }
212159d1ed5bSDimitry Andric   }
2122f22ef01cSRoman Divacky 
2123f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
2124f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
2125f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
2126f22ef01cSRoman Divacky     return F;
2127f22ef01cSRoman Divacky   }
2128f22ef01cSRoman Divacky 
212917a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2130f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
2131f22ef01cSRoman Divacky }
2132f22ef01cSRoman Divacky 
2133f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
2134f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
2135f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
2136f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
21376122f3e6SDimitry Andric                                                  llvm::Type *Ty,
213859d1ed5bSDimitry Andric                                                  bool ForVTable,
21390623d748SDimitry Andric                                                  bool DontDefer,
214044290647SDimitry Andric                                               ForDefinition_t IsForDefinition) {
2141f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
21420623d748SDimitry Andric   if (!Ty) {
21430623d748SDimitry Andric     const auto *FD = cast<FunctionDecl>(GD.getDecl());
21440623d748SDimitry Andric     auto CanonTy = Context.getCanonicalType(FD->getType());
21450623d748SDimitry Andric     Ty = getTypes().ConvertFunctionType(CanonTy, FD);
21460623d748SDimitry Andric   }
2147ffd1746dSEd Schouten 
21486122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
21490623d748SDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer,
215020e90f04SDimitry Andric                                  /*IsThunk=*/false, llvm::AttributeList(),
21510623d748SDimitry Andric                                  IsForDefinition);
2152f22ef01cSRoman Divacky }
2153f22ef01cSRoman Divacky 
215444290647SDimitry Andric static const FunctionDecl *
215544290647SDimitry Andric GetRuntimeFunctionDecl(ASTContext &C, StringRef Name) {
215644290647SDimitry Andric   TranslationUnitDecl *TUDecl = C.getTranslationUnitDecl();
215744290647SDimitry Andric   DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
215844290647SDimitry Andric 
215944290647SDimitry Andric   IdentifierInfo &CII = C.Idents.get(Name);
216044290647SDimitry Andric   for (const auto &Result : DC->lookup(&CII))
216144290647SDimitry Andric     if (const auto FD = dyn_cast<FunctionDecl>(Result))
216244290647SDimitry Andric       return FD;
216344290647SDimitry Andric 
216444290647SDimitry Andric   if (!C.getLangOpts().CPlusPlus)
216544290647SDimitry Andric     return nullptr;
216644290647SDimitry Andric 
216744290647SDimitry Andric   // Demangle the premangled name from getTerminateFn()
216844290647SDimitry Andric   IdentifierInfo &CXXII =
216944290647SDimitry Andric       (Name == "_ZSt9terminatev" || Name == "\01?terminate@@YAXXZ")
217044290647SDimitry Andric           ? C.Idents.get("terminate")
217144290647SDimitry Andric           : C.Idents.get(Name);
217244290647SDimitry Andric 
217344290647SDimitry Andric   for (const auto &N : {"__cxxabiv1", "std"}) {
217444290647SDimitry Andric     IdentifierInfo &NS = C.Idents.get(N);
217544290647SDimitry Andric     for (const auto &Result : DC->lookup(&NS)) {
217644290647SDimitry Andric       NamespaceDecl *ND = dyn_cast<NamespaceDecl>(Result);
217744290647SDimitry Andric       if (auto LSD = dyn_cast<LinkageSpecDecl>(Result))
217844290647SDimitry Andric         for (const auto &Result : LSD->lookup(&NS))
217944290647SDimitry Andric           if ((ND = dyn_cast<NamespaceDecl>(Result)))
218044290647SDimitry Andric             break;
218144290647SDimitry Andric 
218244290647SDimitry Andric       if (ND)
218344290647SDimitry Andric         for (const auto &Result : ND->lookup(&CXXII))
218444290647SDimitry Andric           if (const auto *FD = dyn_cast<FunctionDecl>(Result))
218544290647SDimitry Andric             return FD;
218644290647SDimitry Andric     }
218744290647SDimitry Andric   }
218844290647SDimitry Andric 
218944290647SDimitry Andric   return nullptr;
219044290647SDimitry Andric }
219144290647SDimitry Andric 
2192f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
2193f22ef01cSRoman Divacky /// type and name.
2194f22ef01cSRoman Divacky llvm::Constant *
219544290647SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy, StringRef Name,
219620e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs,
219744290647SDimitry Andric                                      bool Local) {
219859d1ed5bSDimitry Andric   llvm::Constant *C =
219959d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
220044290647SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false,
220144290647SDimitry Andric                               ExtraAttrs);
220244290647SDimitry Andric 
220344290647SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C)) {
220444290647SDimitry Andric     if (F->empty()) {
2205139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
220644290647SDimitry Andric 
220744290647SDimitry Andric       if (!Local && getTriple().isOSBinFormatCOFF() &&
220844290647SDimitry Andric           !getCodeGenOpts().LTOVisibilityPublicStd) {
220944290647SDimitry Andric         const FunctionDecl *FD = GetRuntimeFunctionDecl(Context, Name);
221044290647SDimitry Andric         if (!FD || FD->hasAttr<DLLImportAttr>()) {
221144290647SDimitry Andric           F->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
221244290647SDimitry Andric           F->setLinkage(llvm::GlobalValue::ExternalLinkage);
221344290647SDimitry Andric         }
221444290647SDimitry Andric       }
221544290647SDimitry Andric     }
221644290647SDimitry Andric   }
221744290647SDimitry Andric 
2218139f7f9bSDimitry Andric   return C;
2219f22ef01cSRoman Divacky }
2220f22ef01cSRoman Divacky 
222139d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
222239d628a0SDimitry Andric /// type and name.
222339d628a0SDimitry Andric llvm::Constant *
222420e90f04SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy, StringRef Name,
222520e90f04SDimitry Andric                                      llvm::AttributeList ExtraAttrs) {
222639d628a0SDimitry Andric   llvm::Constant *C =
222739d628a0SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
222839d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
222939d628a0SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
223039d628a0SDimitry Andric     if (F->empty())
223139d628a0SDimitry Andric       F->setCallingConv(getBuiltinCC());
223239d628a0SDimitry Andric   return C;
223339d628a0SDimitry Andric }
223439d628a0SDimitry Andric 
2235dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
2236dff0c46cSDimitry Andric /// as a constant.
2237dff0c46cSDimitry Andric ///
2238dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
2239dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
2240dff0c46cSDimitry Andric /// not written to during its construction.
2241dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
2242dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
2243f22ef01cSRoman Divacky     return false;
2244bd5abe19SDimitry Andric 
2245dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
2246dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
2247dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
2248dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
2249dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
2250f22ef01cSRoman Divacky   }
2251bd5abe19SDimitry Andric 
2252f22ef01cSRoman Divacky   return true;
2253f22ef01cSRoman Divacky }
2254f22ef01cSRoman Divacky 
2255f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
2256f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
2257f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
2258f22ef01cSRoman Divacky /// bitcasted to the right type.
2259f22ef01cSRoman Divacky ///
2260f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
2261f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
2262e7145dcbSDimitry Andric ///
2263e7145dcbSDimitry Andric /// If IsForDefinition is true, it is guranteed that an actual global with
2264e7145dcbSDimitry Andric /// type Ty will be returned, not conversion of a variable with the same
2265e7145dcbSDimitry Andric /// mangled name but some other type.
2266f22ef01cSRoman Divacky llvm::Constant *
22676122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
22686122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
2269e7145dcbSDimitry Andric                                      const VarDecl *D,
227044290647SDimitry Andric                                      ForDefinition_t IsForDefinition) {
2271f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
2272f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2273f22ef01cSRoman Divacky   if (Entry) {
22743861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
2275f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
2276f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
2277f22ef01cSRoman Divacky     }
2278f22ef01cSRoman Divacky 
227939d628a0SDimitry Andric     // Handle dropped DLL attributes.
228039d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
228139d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
228239d628a0SDimitry Andric 
2283f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
2284f22ef01cSRoman Divacky       return Entry;
2285f22ef01cSRoman Divacky 
2286e7145dcbSDimitry Andric     // If there are two attempts to define the same mangled name, issue an
2287e7145dcbSDimitry Andric     // error.
2288e7145dcbSDimitry Andric     if (IsForDefinition && !Entry->isDeclaration()) {
2289e7145dcbSDimitry Andric       GlobalDecl OtherGD;
2290e7145dcbSDimitry Andric       const VarDecl *OtherD;
2291e7145dcbSDimitry Andric 
2292e7145dcbSDimitry Andric       // Check that D is not yet in DiagnosedConflictingDefinitions is required
2293e7145dcbSDimitry Andric       // to make sure that we issue an error only once.
2294e7145dcbSDimitry Andric       if (D && lookupRepresentativeDecl(MangledName, OtherGD) &&
2295e7145dcbSDimitry Andric           (D->getCanonicalDecl() != OtherGD.getCanonicalDecl().getDecl()) &&
2296e7145dcbSDimitry Andric           (OtherD = dyn_cast<VarDecl>(OtherGD.getDecl())) &&
2297e7145dcbSDimitry Andric           OtherD->hasInit() &&
2298e7145dcbSDimitry Andric           DiagnosedConflictingDefinitions.insert(D).second) {
2299e7145dcbSDimitry Andric         getDiags().Report(D->getLocation(),
2300e7145dcbSDimitry Andric                           diag::err_duplicate_mangled_name);
2301e7145dcbSDimitry Andric         getDiags().Report(OtherGD.getDecl()->getLocation(),
2302e7145dcbSDimitry Andric                           diag::note_previous_definition);
2303e7145dcbSDimitry Andric       }
2304e7145dcbSDimitry Andric     }
2305e7145dcbSDimitry Andric 
2306f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
2307f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
2308f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
2309f785676fSDimitry Andric 
2310e7145dcbSDimitry Andric     // (If global is requested for a definition, we always need to create a new
2311e7145dcbSDimitry Andric     // global, not just return a bitcast.)
2312e7145dcbSDimitry Andric     if (!IsForDefinition)
2313f22ef01cSRoman Divacky       return llvm::ConstantExpr::getBitCast(Entry, Ty);
2314f22ef01cSRoman Divacky   }
2315f22ef01cSRoman Divacky 
231659d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
231759d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
231859d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
231959d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
232059d1ed5bSDimitry Andric       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
232159d1ed5bSDimitry Andric 
2322e7145dcbSDimitry Andric   // If we already created a global with the same mangled name (but different
2323e7145dcbSDimitry Andric   // type) before, take its name and remove it from its parent.
2324e7145dcbSDimitry Andric   if (Entry) {
2325e7145dcbSDimitry Andric     GV->takeName(Entry);
2326e7145dcbSDimitry Andric 
2327e7145dcbSDimitry Andric     if (!Entry->use_empty()) {
2328e7145dcbSDimitry Andric       llvm::Constant *NewPtrForOldDecl =
2329e7145dcbSDimitry Andric           llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2330e7145dcbSDimitry Andric       Entry->replaceAllUsesWith(NewPtrForOldDecl);
2331e7145dcbSDimitry Andric     }
2332e7145dcbSDimitry Andric 
2333e7145dcbSDimitry Andric     Entry->eraseFromParent();
2334e7145dcbSDimitry Andric   }
2335e7145dcbSDimitry Andric 
2336f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
2337f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
2338f22ef01cSRoman Divacky   // of the file.
233959d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
2340f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
2341f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
2342f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
2343f37b6182SDimitry Andric     addDeferredDeclToEmit(DDI->second);
2344f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
2345f22ef01cSRoman Divacky   }
2346f22ef01cSRoman Divacky 
2347f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
2348f22ef01cSRoman Divacky   if (D) {
2349f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
2350f22ef01cSRoman Divacky     // handling.
2351dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
2352f22ef01cSRoman Divacky 
235333956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
235433956c43SDimitry Andric 
235559d1ed5bSDimitry Andric     setLinkageAndVisibilityForGV(GV, D);
23562754fe60SDimitry Andric 
2357284c1978SDimitry Andric     if (D->getTLSKind()) {
2358284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
23590623d748SDimitry Andric         CXXThreadLocals.push_back(D);
23607ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
2361f22ef01cSRoman Divacky     }
2362f785676fSDimitry Andric 
2363f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
2364f785676fSDimitry Andric     // inline initializers as definitions.
236559d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
2366f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
2367284c1978SDimitry Andric     }
2368f22ef01cSRoman Divacky 
236959d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
237044290647SDimitry Andric     if (getTriple().getArch() == llvm::Triple::xcore &&
237159d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
237259d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
237359d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
237459d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
237559d1ed5bSDimitry Andric   }
237659d1ed5bSDimitry Andric 
23777ae0e2c9SDimitry Andric   if (AddrSpace != Ty->getAddressSpace())
2378f785676fSDimitry Andric     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
2379f785676fSDimitry Andric 
2380f22ef01cSRoman Divacky   return GV;
2381f22ef01cSRoman Divacky }
2382f22ef01cSRoman Divacky 
23830623d748SDimitry Andric llvm::Constant *
23840623d748SDimitry Andric CodeGenModule::GetAddrOfGlobal(GlobalDecl GD,
238544290647SDimitry Andric                                ForDefinition_t IsForDefinition) {
238644290647SDimitry Andric   const Decl *D = GD.getDecl();
238744290647SDimitry Andric   if (isa<CXXConstructorDecl>(D))
238844290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXConstructorDecl>(D),
23890623d748SDimitry Andric                                 getFromCtorType(GD.getCtorType()),
23900623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23910623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
239244290647SDimitry Andric   else if (isa<CXXDestructorDecl>(D))
239344290647SDimitry Andric     return getAddrOfCXXStructor(cast<CXXDestructorDecl>(D),
23940623d748SDimitry Andric                                 getFromDtorType(GD.getDtorType()),
23950623d748SDimitry Andric                                 /*FnInfo=*/nullptr, /*FnType=*/nullptr,
23960623d748SDimitry Andric                                 /*DontDefer=*/false, IsForDefinition);
239744290647SDimitry Andric   else if (isa<CXXMethodDecl>(D)) {
23980623d748SDimitry Andric     auto FInfo = &getTypes().arrangeCXXMethodDeclaration(
239944290647SDimitry Andric         cast<CXXMethodDecl>(D));
24000623d748SDimitry Andric     auto Ty = getTypes().GetFunctionType(*FInfo);
24010623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
24020623d748SDimitry Andric                              IsForDefinition);
240344290647SDimitry Andric   } else if (isa<FunctionDecl>(D)) {
24040623d748SDimitry Andric     const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
24050623d748SDimitry Andric     llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
24060623d748SDimitry Andric     return GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer=*/false,
24070623d748SDimitry Andric                              IsForDefinition);
24080623d748SDimitry Andric   } else
240944290647SDimitry Andric     return GetAddrOfGlobalVar(cast<VarDecl>(D), /*Ty=*/nullptr,
2410e7145dcbSDimitry Andric                               IsForDefinition);
24110623d748SDimitry Andric }
2412f22ef01cSRoman Divacky 
24132754fe60SDimitry Andric llvm::GlobalVariable *
24146122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
24156122f3e6SDimitry Andric                                       llvm::Type *Ty,
24162754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
24172754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
241859d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
24192754fe60SDimitry Andric 
24202754fe60SDimitry Andric   if (GV) {
24212754fe60SDimitry Andric     // Check if the variable has the right type.
24222754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
24232754fe60SDimitry Andric       return GV;
24242754fe60SDimitry Andric 
24252754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
24262754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
24272754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
24282754fe60SDimitry Andric     OldGV = GV;
24292754fe60SDimitry Andric   }
24302754fe60SDimitry Andric 
24312754fe60SDimitry Andric   // Create a new variable.
24322754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
243359d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
24342754fe60SDimitry Andric 
24352754fe60SDimitry Andric   if (OldGV) {
24362754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
24372754fe60SDimitry Andric     GV->takeName(OldGV);
24382754fe60SDimitry Andric 
24392754fe60SDimitry Andric     if (!OldGV->use_empty()) {
24402754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
24412754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
24422754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
24432754fe60SDimitry Andric     }
24442754fe60SDimitry Andric 
24452754fe60SDimitry Andric     OldGV->eraseFromParent();
24462754fe60SDimitry Andric   }
24472754fe60SDimitry Andric 
244833956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
244933956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
245033956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
245133956c43SDimitry Andric 
24522754fe60SDimitry Andric   return GV;
24532754fe60SDimitry Andric }
24542754fe60SDimitry Andric 
2455f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
2456f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
2457cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
2458e7145dcbSDimitry Andric /// normal requested type would be. If IsForDefinition is true, it is guranteed
2459e7145dcbSDimitry Andric /// that an actual global with type Ty will be returned, not conversion of a
2460e7145dcbSDimitry Andric /// variable with the same mangled name but some other type.
2461f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
2462e7145dcbSDimitry Andric                                                   llvm::Type *Ty,
246344290647SDimitry Andric                                            ForDefinition_t IsForDefinition) {
2464f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
2465f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
246659d1ed5bSDimitry Andric   if (!Ty)
2467f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
2468f22ef01cSRoman Divacky 
24696122f3e6SDimitry Andric   llvm::PointerType *PTy =
24703b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
2471f22ef01cSRoman Divacky 
24726122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2473e7145dcbSDimitry Andric   return GetOrCreateLLVMGlobal(MangledName, PTy, D, IsForDefinition);
2474f22ef01cSRoman Divacky }
2475f22ef01cSRoman Divacky 
2476f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
2477f22ef01cSRoman Divacky /// specified type and name.
2478f22ef01cSRoman Divacky llvm::Constant *
24796122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
24806122f3e6SDimitry Andric                                      StringRef Name) {
248159d1ed5bSDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
2482f22ef01cSRoman Divacky }
2483f22ef01cSRoman Divacky 
2484f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
2485f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
2486f22ef01cSRoman Divacky 
24876122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
2488e7145dcbSDimitry Andric   llvm::GlobalValue *GV = GetGlobalValue(MangledName);
2489e7145dcbSDimitry Andric 
2490e7145dcbSDimitry Andric   // We already have a definition, not declaration, with the same mangled name.
2491e7145dcbSDimitry Andric   // Emitting of declaration is not required (and actually overwrites emitted
2492e7145dcbSDimitry Andric   // definition).
2493e7145dcbSDimitry Andric   if (GV && !GV->isDeclaration())
2494e7145dcbSDimitry Andric     return;
2495e7145dcbSDimitry Andric 
2496e7145dcbSDimitry Andric   // If we have not seen a reference to this variable yet, place it into the
2497e7145dcbSDimitry Andric   // deferred declarations table to be emitted if needed later.
2498e7145dcbSDimitry Andric   if (!MustBeEmitted(D) && !GV) {
2499f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
2500f22ef01cSRoman Divacky       return;
2501f22ef01cSRoman Divacky   }
2502f22ef01cSRoman Divacky 
2503f22ef01cSRoman Divacky   // The tentative definition is the only definition.
2504f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
2505f22ef01cSRoman Divacky }
2506f22ef01cSRoman Divacky 
25076122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
25082754fe60SDimitry Andric   return Context.toCharUnitsFromBits(
25090623d748SDimitry Andric       getDataLayout().getTypeStoreSizeInBits(Ty));
2510f22ef01cSRoman Divacky }
2511f22ef01cSRoman Divacky 
25127ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
25137ae0e2c9SDimitry Andric                                                  unsigned AddrSpace) {
2514e7145dcbSDimitry Andric   if (D && LangOpts.CUDA && LangOpts.CUDAIsDevice) {
25157ae0e2c9SDimitry Andric     if (D->hasAttr<CUDAConstantAttr>())
25167ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
25177ae0e2c9SDimitry Andric     else if (D->hasAttr<CUDASharedAttr>())
25187ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
25197ae0e2c9SDimitry Andric     else
25207ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
25217ae0e2c9SDimitry Andric   }
25227ae0e2c9SDimitry Andric 
25237ae0e2c9SDimitry Andric   return AddrSpace;
25247ae0e2c9SDimitry Andric }
25257ae0e2c9SDimitry Andric 
2526284c1978SDimitry Andric template<typename SomeDecl>
2527284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
2528284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
2529284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
2530284c1978SDimitry Andric     return;
2531284c1978SDimitry Andric 
2532284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
2533284c1978SDimitry Andric   // the name existing.
2534284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
2535284c1978SDimitry Andric     return;
2536284c1978SDimitry Andric 
2537284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
2538f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
2539284c1978SDimitry Andric     return;
2540284c1978SDimitry Andric 
2541284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
2542284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
2543f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
2544284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
2545284c1978SDimitry Andric     return;
2546284c1978SDimitry Andric 
2547284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
2548284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
2549284c1978SDimitry Andric   // mangled name if nothing else is using that name.
2550284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
2551284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
2552284c1978SDimitry Andric 
2553284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
2554284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
2555284c1978SDimitry Andric   if (!R.second)
255659d1ed5bSDimitry Andric     R.first->second = nullptr;
2557284c1978SDimitry Andric }
2558284c1978SDimitry Andric 
255933956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
256033956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
256133956c43SDimitry Andric     return false;
256233956c43SDimitry Andric 
256333956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
256433956c43SDimitry Andric     return true;
256533956c43SDimitry Andric 
256633956c43SDimitry Andric   GVALinkage Linkage;
256733956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
256833956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
256933956c43SDimitry Andric   else
257033956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
257133956c43SDimitry Andric 
257233956c43SDimitry Andric   switch (Linkage) {
257333956c43SDimitry Andric   case GVA_Internal:
257433956c43SDimitry Andric   case GVA_AvailableExternally:
257533956c43SDimitry Andric   case GVA_StrongExternal:
257633956c43SDimitry Andric     return false;
257733956c43SDimitry Andric   case GVA_DiscardableODR:
257833956c43SDimitry Andric   case GVA_StrongODR:
257933956c43SDimitry Andric     return true;
258033956c43SDimitry Andric   }
258133956c43SDimitry Andric   llvm_unreachable("No such linkage");
258233956c43SDimitry Andric }
258333956c43SDimitry Andric 
258433956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
258533956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
258633956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
258733956c43SDimitry Andric     return;
258833956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
258933956c43SDimitry Andric }
259033956c43SDimitry Andric 
2591e7145dcbSDimitry Andric /// Pass IsTentative as true if you want to create a tentative definition.
2592e7145dcbSDimitry Andric void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D,
2593e7145dcbSDimitry Andric                                             bool IsTentative) {
259444290647SDimitry Andric   // OpenCL global variables of sampler type are translated to function calls,
259544290647SDimitry Andric   // therefore no need to be translated.
2596f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
259744290647SDimitry Andric   if (getLangOpts().OpenCL && ASTTy->isSamplerT())
259844290647SDimitry Andric     return;
259944290647SDimitry Andric 
260044290647SDimitry Andric   llvm::Constant *Init = nullptr;
2601dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2602dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
2603dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
2604f22ef01cSRoman Divacky 
2605dff0c46cSDimitry Andric   const VarDecl *InitDecl;
2606dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
2607f22ef01cSRoman Divacky 
2608e7145dcbSDimitry Andric   // CUDA E.2.4.1 "__shared__ variables cannot have an initialization
2609e7145dcbSDimitry Andric   // as part of their declaration."  Sema has already checked for
2610e7145dcbSDimitry Andric   // error cases, so we just need to set Init to UndefValue.
2611e7145dcbSDimitry Andric   if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice &&
2612e7145dcbSDimitry Andric       D->hasAttr<CUDASharedAttr>())
26130623d748SDimitry Andric     Init = llvm::UndefValue::get(getTypes().ConvertType(ASTTy));
2614e7145dcbSDimitry Andric   else if (!InitExpr) {
2615f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
2616f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
2617f22ef01cSRoman Divacky     //
2618f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
2619f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
2620f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
2621f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
2622f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
2623f22ef01cSRoman Divacky     // to do a RAUW.
2624f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2625f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
2626f22ef01cSRoman Divacky   } else {
26277ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
2628dff0c46cSDimitry Andric     Init = EmitConstantInit(*InitDecl);
2629f785676fSDimitry Andric 
2630f22ef01cSRoman Divacky     if (!Init) {
2631f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
2632f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
2633f22ef01cSRoman Divacky         T = D->getType();
2634f22ef01cSRoman Divacky 
2635dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
2636f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
2637dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
2638f22ef01cSRoman Divacky       } else {
2639f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
2640f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2641f22ef01cSRoman Divacky       }
2642e580952dSDimitry Andric     } else {
2643e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
2644dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
2645dff0c46cSDimitry Andric       // also don't need to register a destructor.
2646dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2647e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
2648f22ef01cSRoman Divacky     }
2649f22ef01cSRoman Divacky   }
2650f22ef01cSRoman Divacky 
26516122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
2652e7145dcbSDimitry Andric   llvm::Constant *Entry =
265344290647SDimitry Andric       GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative));
2654f22ef01cSRoman Divacky 
2655f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
265659d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2657f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2658f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2659f785676fSDimitry Andric            // All zero index gep.
2660f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2661f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
2662f22ef01cSRoman Divacky   }
2663f22ef01cSRoman Divacky 
2664f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
266559d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2666f22ef01cSRoman Divacky 
2667f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
2668f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
2669f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
2670f22ef01cSRoman Divacky   // (which will be a definition).
2671f22ef01cSRoman Divacky   //
2672f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
2673f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
2674f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
2675f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
267659d1ed5bSDimitry Andric   if (!GV ||
2677f22ef01cSRoman Divacky       GV->getType()->getElementType() != InitType ||
26783b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
26797ae0e2c9SDimitry Andric        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2680f22ef01cSRoman Divacky 
2681f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
26826122f3e6SDimitry Andric     Entry->setName(StringRef());
2683f22ef01cSRoman Divacky 
2684f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
2685e7145dcbSDimitry Andric     GV = cast<llvm::GlobalVariable>(
268644290647SDimitry Andric         GetAddrOfGlobalVar(D, InitType, ForDefinition_t(!IsTentative)));
2687f22ef01cSRoman Divacky 
2688f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
2689f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
2690f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2691f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2692f22ef01cSRoman Divacky 
2693f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
2694f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2695f22ef01cSRoman Divacky   }
2696f22ef01cSRoman Divacky 
2697284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
2698284c1978SDimitry Andric 
26996122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
27006122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
2701f22ef01cSRoman Divacky 
2702e7145dcbSDimitry Andric   // Set the llvm linkage type as appropriate.
2703e7145dcbSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
2704e7145dcbSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
2705e7145dcbSDimitry Andric 
27060623d748SDimitry Andric   // CUDA B.2.1 "The __device__ qualifier declares a variable that resides on
27070623d748SDimitry Andric   // the device. [...]"
27080623d748SDimitry Andric   // CUDA B.2.2 "The __constant__ qualifier, optionally used together with
27090623d748SDimitry Andric   // __device__, declares a variable that: [...]
27100623d748SDimitry Andric   // Is accessible from all the threads within the grid and from the host
27110623d748SDimitry Andric   // through the runtime library (cudaGetSymbolAddress() / cudaGetSymbolSize()
27120623d748SDimitry Andric   // / cudaMemcpyToSymbol() / cudaMemcpyFromSymbol())."
2713e7145dcbSDimitry Andric   if (GV && LangOpts.CUDA) {
2714e7145dcbSDimitry Andric     if (LangOpts.CUDAIsDevice) {
2715e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>())
27160623d748SDimitry Andric         GV->setExternallyInitialized(true);
2717e7145dcbSDimitry Andric     } else {
2718e7145dcbSDimitry Andric       // Host-side shadows of external declarations of device-side
2719e7145dcbSDimitry Andric       // global variables become internal definitions. These have to
2720e7145dcbSDimitry Andric       // be internal in order to prevent name conflicts with global
2721e7145dcbSDimitry Andric       // host variables with the same name in a different TUs.
2722e7145dcbSDimitry Andric       if (D->hasAttr<CUDADeviceAttr>() || D->hasAttr<CUDAConstantAttr>()) {
2723e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2724e7145dcbSDimitry Andric 
2725e7145dcbSDimitry Andric         // Shadow variables and their properties must be registered
2726e7145dcbSDimitry Andric         // with CUDA runtime.
2727e7145dcbSDimitry Andric         unsigned Flags = 0;
2728e7145dcbSDimitry Andric         if (!D->hasDefinition())
2729e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ExternDeviceVar;
2730e7145dcbSDimitry Andric         if (D->hasAttr<CUDAConstantAttr>())
2731e7145dcbSDimitry Andric           Flags |= CGCUDARuntime::ConstantDeviceVar;
2732e7145dcbSDimitry Andric         getCUDARuntime().registerDeviceVar(*GV, Flags);
2733e7145dcbSDimitry Andric       } else if (D->hasAttr<CUDASharedAttr>())
2734e7145dcbSDimitry Andric         // __shared__ variables are odd. Shadows do get created, but
2735e7145dcbSDimitry Andric         // they are not registered with the CUDA runtime, so they
2736e7145dcbSDimitry Andric         // can't really be used to access their device-side
2737e7145dcbSDimitry Andric         // counterparts. It's not clear yet whether it's nvcc's bug or
2738e7145dcbSDimitry Andric         // a feature, but we've got to do the same for compatibility.
2739e7145dcbSDimitry Andric         Linkage = llvm::GlobalValue::InternalLinkage;
2740e7145dcbSDimitry Andric     }
27410623d748SDimitry Andric   }
2742f22ef01cSRoman Divacky   GV->setInitializer(Init);
2743f22ef01cSRoman Divacky 
2744f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
2745dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2746dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
2747f22ef01cSRoman Divacky 
274839d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
274939d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
275039d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
275139d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
275239d628a0SDimitry Andric       GV->setConstant(true);
275339d628a0SDimitry Andric   }
275439d628a0SDimitry Andric 
2755f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2756f22ef01cSRoman Divacky 
2757f785676fSDimitry Andric 
27580623d748SDimitry Andric   // On Darwin, if the normal linkage of a C++ thread_local variable is
27590623d748SDimitry Andric   // LinkOnce or Weak, we keep the normal linkage to prevent multiple
27600623d748SDimitry Andric   // copies within a linkage unit; otherwise, the backing variable has
27610623d748SDimitry Andric   // internal linkage and all accesses should just be calls to the
276259d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
27630623d748SDimitry Andric   // variable. This is to preserve the ability to change the implementation
27640623d748SDimitry Andric   // behind the scenes.
276539d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
27660623d748SDimitry Andric       Context.getTargetInfo().getTriple().isOSDarwin() &&
27670623d748SDimitry Andric       !llvm::GlobalVariable::isLinkOnceLinkage(Linkage) &&
27680623d748SDimitry Andric       !llvm::GlobalVariable::isWeakLinkage(Linkage))
276959d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
277059d1ed5bSDimitry Andric 
277159d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
277259d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
277359d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
277459d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
277559d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
277639d628a0SDimitry Andric   else
277739d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2778f785676fSDimitry Andric 
277944290647SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage) {
2780f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
2781f22ef01cSRoman Divacky     GV->setConstant(false);
278244290647SDimitry Andric     // Tentative definition of global variables may be initialized with
278344290647SDimitry Andric     // non-zero null pointers. In this case they should have weak linkage
278444290647SDimitry Andric     // since common linkage must have zero initializer and must not have
278544290647SDimitry Andric     // explicit section therefore cannot have non-zero initial value.
278644290647SDimitry Andric     if (!GV->getInitializer()->isNullValue())
278744290647SDimitry Andric       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
278844290647SDimitry Andric   }
2789f22ef01cSRoman Divacky 
279059d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
2791f22ef01cSRoman Divacky 
279239d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
279339d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
27940623d748SDimitry Andric       CXXThreadLocals.push_back(D);
279539d628a0SDimitry Andric     setTLSMode(GV, *D);
279639d628a0SDimitry Andric   }
279739d628a0SDimitry Andric 
279833956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
279933956c43SDimitry Andric 
28002754fe60SDimitry Andric   // Emit the initializer function if necessary.
2801dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
2802dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
28032754fe60SDimitry Andric 
280439d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
28053861d79fSDimitry Andric 
2806f22ef01cSRoman Divacky   // Emit global variable debug information.
28076122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
2808e7145dcbSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
2809f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
2810f22ef01cSRoman Divacky }
2811f22ef01cSRoman Divacky 
281239d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
281333956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
281433956c43SDimitry Andric                                       bool NoCommon) {
281559d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
281659d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
281759d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
281859d1ed5bSDimitry Andric     return true;
281959d1ed5bSDimitry Andric 
282059d1ed5bSDimitry Andric   // C11 6.9.2/2:
282159d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
282259d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
282359d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
282459d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
282559d1ed5bSDimitry Andric     return true;
282659d1ed5bSDimitry Andric 
282759d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
282859d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
282959d1ed5bSDimitry Andric     return true;
283059d1ed5bSDimitry Andric 
283159d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
283259d1ed5bSDimitry Andric   if (D->getTLSKind())
283359d1ed5bSDimitry Andric     return true;
283459d1ed5bSDimitry Andric 
283559d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
283659d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
283759d1ed5bSDimitry Andric     return true;
283859d1ed5bSDimitry Andric 
283933956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
284033956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
284133956c43SDimitry Andric     return true;
284233956c43SDimitry Andric 
2843e7145dcbSDimitry Andric   // Declarations with a required alignment do not have common linkage in MSVC
284439d628a0SDimitry Andric   // mode.
28450623d748SDimitry Andric   if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
284633956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
284739d628a0SDimitry Andric       return true;
284833956c43SDimitry Andric     QualType VarType = D->getType();
284933956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
285033956c43SDimitry Andric       return true;
285133956c43SDimitry Andric 
285233956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
285333956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
285433956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
285533956c43SDimitry Andric         if (FD->isBitField())
285633956c43SDimitry Andric           continue;
285733956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
285833956c43SDimitry Andric           return true;
285933956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
286033956c43SDimitry Andric           return true;
286133956c43SDimitry Andric       }
286233956c43SDimitry Andric     }
286333956c43SDimitry Andric   }
286439d628a0SDimitry Andric 
286559d1ed5bSDimitry Andric   return false;
286659d1ed5bSDimitry Andric }
286759d1ed5bSDimitry Andric 
286859d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
286959d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
28702754fe60SDimitry Andric   if (Linkage == GVA_Internal)
28712754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
287259d1ed5bSDimitry Andric 
287359d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
287459d1ed5bSDimitry Andric     if (IsConstantVariable)
287559d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
287659d1ed5bSDimitry Andric     else
287759d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
287859d1ed5bSDimitry Andric   }
287959d1ed5bSDimitry Andric 
288059d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
288159d1ed5bSDimitry Andric   // so we can use available_externally linkage.
288259d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
288320e90f04SDimitry Andric     return llvm::GlobalValue::AvailableExternallyLinkage;
288459d1ed5bSDimitry Andric 
288559d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
288659d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
288759d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
288859d1ed5bSDimitry Andric   // instantiations we'll map to external.
288959d1ed5bSDimitry Andric 
289059d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
289159d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
289259d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
289359d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
289459d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
289559d1ed5bSDimitry Andric   // definition is dependable.
289659d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
289759d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
289859d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
289959d1ed5bSDimitry Andric 
290059d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
290159d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
290259d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
290359d1ed5bSDimitry Andric   // throw away these explicit instantiations.
2904e7145dcbSDimitry Andric   //
2905e7145dcbSDimitry Andric   // We don't currently support CUDA device code spread out across multiple TUs,
2906e7145dcbSDimitry Andric   // so say that CUDA templates are either external (for kernels) or internal.
2907e7145dcbSDimitry Andric   // This lets llvm perform aggressive inter-procedural optimizations.
2908e7145dcbSDimitry Andric   if (Linkage == GVA_StrongODR) {
2909e7145dcbSDimitry Andric     if (Context.getLangOpts().AppleKext)
2910e7145dcbSDimitry Andric       return llvm::Function::ExternalLinkage;
2911e7145dcbSDimitry Andric     if (Context.getLangOpts().CUDA && Context.getLangOpts().CUDAIsDevice)
2912e7145dcbSDimitry Andric       return D->hasAttr<CUDAGlobalAttr>() ? llvm::Function::ExternalLinkage
2913e7145dcbSDimitry Andric                                           : llvm::Function::InternalLinkage;
2914e7145dcbSDimitry Andric     return llvm::Function::WeakODRLinkage;
2915e7145dcbSDimitry Andric   }
291659d1ed5bSDimitry Andric 
291759d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
291859d1ed5bSDimitry Andric   // linkage.
291959d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
292033956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
292139d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
292259d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
292359d1ed5bSDimitry Andric 
2924f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
2925f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
2926f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
2927f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
292859d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
2929f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
293059d1ed5bSDimitry Andric 
293159d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
293259d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
29332754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
29342754fe60SDimitry Andric }
29352754fe60SDimitry Andric 
293659d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
293759d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
293859d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
293959d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
294059d1ed5bSDimitry Andric }
294159d1ed5bSDimitry Andric 
2942139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
2943139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
2944139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2945139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
2946139f7f9bSDimitry Andric   // Fast path.
2947139f7f9bSDimitry Andric   if (old->use_empty()) return;
2948139f7f9bSDimitry Andric 
2949139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
2950139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
29510623d748SDimitry Andric   SmallVector<llvm::OperandBundleDef, 1> newBundles;
2952139f7f9bSDimitry Andric 
2953139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2954139f7f9bSDimitry Andric          ui != ue; ) {
2955139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
295659d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
2957139f7f9bSDimitry Andric 
2958139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
2959139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
296059d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2961139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2962139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
2963139f7f9bSDimitry Andric       continue;
2964139f7f9bSDimitry Andric     }
2965139f7f9bSDimitry Andric 
2966139f7f9bSDimitry Andric     // Recognize calls to the function.
2967139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
2968139f7f9bSDimitry Andric     if (!callSite) continue;
296959d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
2970139f7f9bSDimitry Andric 
2971139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
2972139f7f9bSDimitry Andric     // transform this call unless it's dead.
2973139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
2974139f7f9bSDimitry Andric       continue;
2975139f7f9bSDimitry Andric 
2976139f7f9bSDimitry Andric     // Get the call site's attribute list.
297720e90f04SDimitry Andric     SmallVector<llvm::AttributeSet, 8> newArgAttrs;
297820e90f04SDimitry Andric     llvm::AttributeList oldAttrs = callSite.getAttributes();
2979139f7f9bSDimitry Andric 
2980139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
2981139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
2982139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
2983139f7f9bSDimitry Andric 
2984139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
2985139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
2986139f7f9bSDimitry Andric     unsigned argNo = 0;
2987139f7f9bSDimitry Andric     bool dontTransform = false;
298820e90f04SDimitry Andric     for (llvm::Argument &A : newFn->args()) {
298920e90f04SDimitry Andric       if (callSite.getArgument(argNo)->getType() != A.getType()) {
2990139f7f9bSDimitry Andric         dontTransform = true;
2991139f7f9bSDimitry Andric         break;
2992139f7f9bSDimitry Andric       }
2993139f7f9bSDimitry Andric 
2994139f7f9bSDimitry Andric       // Add any parameter attributes.
299520e90f04SDimitry Andric       newArgAttrs.push_back(oldAttrs.getParamAttributes(argNo));
299620e90f04SDimitry Andric       argNo++;
2997139f7f9bSDimitry Andric     }
2998139f7f9bSDimitry Andric     if (dontTransform)
2999139f7f9bSDimitry Andric       continue;
3000139f7f9bSDimitry Andric 
3001139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
3002139f7f9bSDimitry Andric     // over the required information.
3003139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
3004139f7f9bSDimitry Andric 
30050623d748SDimitry Andric     // Copy over any operand bundles.
30060623d748SDimitry Andric     callSite.getOperandBundlesAsDefs(newBundles);
30070623d748SDimitry Andric 
3008139f7f9bSDimitry Andric     llvm::CallSite newCall;
3009139f7f9bSDimitry Andric     if (callSite.isCall()) {
30100623d748SDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, newBundles, "",
3011139f7f9bSDimitry Andric                                        callSite.getInstruction());
3012139f7f9bSDimitry Andric     } else {
301359d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
3014139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
3015139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
3016139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
30170623d748SDimitry Andric                                          newArgs, newBundles, "",
3018139f7f9bSDimitry Andric                                          callSite.getInstruction());
3019139f7f9bSDimitry Andric     }
3020139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
3021139f7f9bSDimitry Andric 
3022139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
3023139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
302420e90f04SDimitry Andric     newCall.setAttributes(llvm::AttributeList::get(
302520e90f04SDimitry Andric         newFn->getContext(), oldAttrs.getFnAttributes(),
302620e90f04SDimitry Andric         oldAttrs.getRetAttributes(), newArgAttrs));
3027139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
3028139f7f9bSDimitry Andric 
3029139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
3030139f7f9bSDimitry Andric     if (!callSite->use_empty())
3031139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
3032139f7f9bSDimitry Andric 
3033139f7f9bSDimitry Andric     // Copy debug location attached to CI.
303433956c43SDimitry Andric     if (callSite->getDebugLoc())
3035139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
30360623d748SDimitry Andric 
3037139f7f9bSDimitry Andric     callSite->eraseFromParent();
3038139f7f9bSDimitry Andric   }
3039139f7f9bSDimitry Andric }
3040139f7f9bSDimitry Andric 
3041f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
3042f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
3043f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
3044f22ef01cSRoman Divacky /// call the new function directly.
3045f22ef01cSRoman Divacky ///
3046f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
3047f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
3048f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
3049f22ef01cSRoman Divacky /// run at -O0.
3050f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
3051f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
3052f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
3053139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
3054f22ef01cSRoman Divacky 
3055139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
3056f22ef01cSRoman Divacky }
3057f22ef01cSRoman Divacky 
3058dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
3059e7145dcbSDimitry Andric   auto DK = VD->isThisDeclarationADefinition();
3060e7145dcbSDimitry Andric   if (DK == VarDecl::Definition && VD->hasAttr<DLLImportAttr>())
3061e7145dcbSDimitry Andric     return;
3062e7145dcbSDimitry Andric 
3063dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
3064dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
3065dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
3066dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
3067dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
3068139f7f9bSDimitry Andric 
3069139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
3070dff0c46cSDimitry Andric }
3071f22ef01cSRoman Divacky 
307259d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
307359d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
307459d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
30753b0f4066SDimitry Andric 
30763b0f4066SDimitry Andric   // Compute the function info and LLVM type.
3077dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
3078dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
30793b0f4066SDimitry Andric 
3080f22ef01cSRoman Divacky   // Get or create the prototype for the function.
30810623d748SDimitry Andric   if (!GV || (GV->getType()->getElementType() != Ty))
30820623d748SDimitry Andric     GV = cast<llvm::GlobalValue>(GetAddrOfFunction(GD, Ty, /*ForVTable=*/false,
30830623d748SDimitry Andric                                                    /*DontDefer=*/true,
308444290647SDimitry Andric                                                    ForDefinition));
3085f22ef01cSRoman Divacky 
30860623d748SDimitry Andric   // Already emitted.
30870623d748SDimitry Andric   if (!GV->isDeclaration())
3088f785676fSDimitry Andric     return;
3089f22ef01cSRoman Divacky 
30902754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
30912754fe60SDimitry Andric   // generating code for it because various parts of IR generation
30922754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
30932754fe60SDimitry Andric   // declarations).
309459d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
3095f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
309697bc6c73SDimitry Andric   setFunctionDLLStorageClass(GD, Fn);
3097f22ef01cSRoman Divacky 
309859d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
30992754fe60SDimitry Andric   setGlobalVisibility(Fn, D);
31002754fe60SDimitry Andric 
3101284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
3102284c1978SDimitry Andric 
310333956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
310433956c43SDimitry Andric 
31053b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
3106f22ef01cSRoman Divacky 
310759d1ed5bSDimitry Andric   setFunctionDefinitionAttributes(D, Fn);
3108f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
3109f22ef01cSRoman Divacky 
3110f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
3111f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
3112f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
3113f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
31146122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
31156122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
3116f22ef01cSRoman Divacky }
3117f22ef01cSRoman Divacky 
3118f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
311959d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3120f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
3121f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
3122f22ef01cSRoman Divacky 
31236122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
3124f22ef01cSRoman Divacky 
31259a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
3126e7145dcbSDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
31279a4b3118SDimitry Andric     return;
31289a4b3118SDimitry Andric   }
31299a4b3118SDimitry Andric 
3130f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
3131f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
3132f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3133f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
3134f22ef01cSRoman Divacky     return;
3135f22ef01cSRoman Divacky 
3136f785676fSDimitry Andric   Aliases.push_back(GD);
3137f785676fSDimitry Andric 
31386122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3139f22ef01cSRoman Divacky 
3140f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
3141f22ef01cSRoman Divacky   // if a deferred decl.
3142f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
3143f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
31443861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
31452754fe60SDimitry Andric                                       /*ForVTable=*/false);
3146f22ef01cSRoman Divacky   else
3147f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
314859d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
314939d628a0SDimitry Andric                                     /*D=*/nullptr);
3150f22ef01cSRoman Divacky 
3151f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
315259d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
31530623d748SDimitry Andric       DeclTy, 0, llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
3154f22ef01cSRoman Divacky 
3155f22ef01cSRoman Divacky   if (Entry) {
315659d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
3157e7145dcbSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias) << 0;
315859d1ed5bSDimitry Andric       return;
315959d1ed5bSDimitry Andric     }
316059d1ed5bSDimitry Andric 
3161f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
3162f22ef01cSRoman Divacky 
3163f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
3164f22ef01cSRoman Divacky     // by the alias, as in:
3165f22ef01cSRoman Divacky     //   extern int test6();
3166f22ef01cSRoman Divacky     //   ...
3167f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
3168f22ef01cSRoman Divacky     //
3169f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
3170f22ef01cSRoman Divacky     GA->takeName(Entry);
3171f22ef01cSRoman Divacky 
3172f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
3173f22ef01cSRoman Divacky                                                           Entry->getType()));
3174f22ef01cSRoman Divacky     Entry->eraseFromParent();
3175f22ef01cSRoman Divacky   } else {
3176ffd1746dSEd Schouten     GA->setName(MangledName);
3177f22ef01cSRoman Divacky   }
3178f22ef01cSRoman Divacky 
3179f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
3180f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
3181f22ef01cSRoman Divacky   // variable/function.
318239d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
31833b0f4066SDimitry Andric       D->isWeakImported()) {
3184f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
3185f22ef01cSRoman Divacky   }
3186f22ef01cSRoman Divacky 
318739d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
318839d628a0SDimitry Andric     if (VD->getTLSKind())
318939d628a0SDimitry Andric       setTLSMode(GA, *VD);
319039d628a0SDimitry Andric 
319139d628a0SDimitry Andric   setAliasAttributes(D, GA);
3192f22ef01cSRoman Divacky }
3193f22ef01cSRoman Divacky 
3194e7145dcbSDimitry Andric void CodeGenModule::emitIFuncDefinition(GlobalDecl GD) {
3195e7145dcbSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
3196e7145dcbSDimitry Andric   const IFuncAttr *IFA = D->getAttr<IFuncAttr>();
3197e7145dcbSDimitry Andric   assert(IFA && "Not an ifunc?");
3198e7145dcbSDimitry Andric 
3199e7145dcbSDimitry Andric   StringRef MangledName = getMangledName(GD);
3200e7145dcbSDimitry Andric 
3201e7145dcbSDimitry Andric   if (IFA->getResolver() == MangledName) {
3202e7145dcbSDimitry Andric     Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3203e7145dcbSDimitry Andric     return;
3204e7145dcbSDimitry Andric   }
3205e7145dcbSDimitry Andric 
3206e7145dcbSDimitry Andric   // Report an error if some definition overrides ifunc.
3207e7145dcbSDimitry Andric   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
3208e7145dcbSDimitry Andric   if (Entry && !Entry->isDeclaration()) {
3209e7145dcbSDimitry Andric     GlobalDecl OtherGD;
3210e7145dcbSDimitry Andric     if (lookupRepresentativeDecl(MangledName, OtherGD) &&
3211e7145dcbSDimitry Andric         DiagnosedConflictingDefinitions.insert(GD).second) {
3212e7145dcbSDimitry Andric       Diags.Report(D->getLocation(), diag::err_duplicate_mangled_name);
3213e7145dcbSDimitry Andric       Diags.Report(OtherGD.getDecl()->getLocation(),
3214e7145dcbSDimitry Andric                    diag::note_previous_definition);
3215e7145dcbSDimitry Andric     }
3216e7145dcbSDimitry Andric     return;
3217e7145dcbSDimitry Andric   }
3218e7145dcbSDimitry Andric 
3219e7145dcbSDimitry Andric   Aliases.push_back(GD);
3220e7145dcbSDimitry Andric 
3221e7145dcbSDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
3222e7145dcbSDimitry Andric   llvm::Constant *Resolver =
3223e7145dcbSDimitry Andric       GetOrCreateLLVMFunction(IFA->getResolver(), DeclTy, GD,
3224e7145dcbSDimitry Andric                               /*ForVTable=*/false);
3225e7145dcbSDimitry Andric   llvm::GlobalIFunc *GIF =
3226e7145dcbSDimitry Andric       llvm::GlobalIFunc::create(DeclTy, 0, llvm::Function::ExternalLinkage,
3227e7145dcbSDimitry Andric                                 "", Resolver, &getModule());
3228e7145dcbSDimitry Andric   if (Entry) {
3229e7145dcbSDimitry Andric     if (GIF->getResolver() == Entry) {
3230e7145dcbSDimitry Andric       Diags.Report(IFA->getLocation(), diag::err_cyclic_alias) << 1;
3231e7145dcbSDimitry Andric       return;
3232e7145dcbSDimitry Andric     }
3233e7145dcbSDimitry Andric     assert(Entry->isDeclaration());
3234e7145dcbSDimitry Andric 
3235e7145dcbSDimitry Andric     // If there is a declaration in the module, then we had an extern followed
3236e7145dcbSDimitry Andric     // by the ifunc, as in:
3237e7145dcbSDimitry Andric     //   extern int test();
3238e7145dcbSDimitry Andric     //   ...
3239e7145dcbSDimitry Andric     //   int test() __attribute__((ifunc("resolver")));
3240e7145dcbSDimitry Andric     //
3241e7145dcbSDimitry Andric     // Remove it and replace uses of it with the ifunc.
3242e7145dcbSDimitry Andric     GIF->takeName(Entry);
3243e7145dcbSDimitry Andric 
3244e7145dcbSDimitry Andric     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GIF,
3245e7145dcbSDimitry Andric                                                           Entry->getType()));
3246e7145dcbSDimitry Andric     Entry->eraseFromParent();
3247e7145dcbSDimitry Andric   } else
3248e7145dcbSDimitry Andric     GIF->setName(MangledName);
3249e7145dcbSDimitry Andric 
3250e7145dcbSDimitry Andric   SetCommonAttributes(D, GIF);
3251e7145dcbSDimitry Andric }
3252e7145dcbSDimitry Andric 
325317a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
32546122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
325517a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
325617a519f9SDimitry Andric                                          Tys);
3257f22ef01cSRoman Divacky }
3258f22ef01cSRoman Divacky 
325933956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
326033956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
326133956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
326233956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
32636122f3e6SDimitry Andric   StringRef String = Literal->getString();
3264e580952dSDimitry Andric   unsigned NumBytes = String.size();
3265f22ef01cSRoman Divacky 
3266f22ef01cSRoman Divacky   // Check for simple case.
3267f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
3268f22ef01cSRoman Divacky     StringLength = NumBytes;
326939d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
3270f22ef01cSRoman Divacky   }
3271f22ef01cSRoman Divacky 
3272dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
3273dff0c46cSDimitry Andric   IsUTF16 = true;
3274dff0c46cSDimitry Andric 
327544290647SDimitry Andric   SmallVector<llvm::UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
327644290647SDimitry Andric   const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
327744290647SDimitry Andric   llvm::UTF16 *ToPtr = &ToBuf[0];
3278f22ef01cSRoman Divacky 
327944290647SDimitry Andric   (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
328044290647SDimitry Andric                                  ToPtr + NumBytes, llvm::strictConversion);
3281f22ef01cSRoman Divacky 
3282f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
3283f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
3284f22ef01cSRoman Divacky 
3285dff0c46cSDimitry Andric   // Add an explicit null.
3286dff0c46cSDimitry Andric   *ToPtr = 0;
328739d628a0SDimitry Andric   return *Map.insert(std::make_pair(
328839d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
328939d628a0SDimitry Andric                                    (StringLength + 1) * 2),
329039d628a0SDimitry Andric                          nullptr)).first;
3291f22ef01cSRoman Divacky }
3292f22ef01cSRoman Divacky 
32930623d748SDimitry Andric ConstantAddress
3294f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
3295f22ef01cSRoman Divacky   unsigned StringLength = 0;
3296f22ef01cSRoman Divacky   bool isUTF16 = false;
329733956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
3298f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
329933956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
330033956c43SDimitry Andric                                StringLength);
3301f22ef01cSRoman Divacky 
330239d628a0SDimitry Andric   if (auto *C = Entry.second)
33030623d748SDimitry Andric     return ConstantAddress(C, CharUnits::fromQuantity(C->getAlignment()));
3304f22ef01cSRoman Divacky 
3305dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
3306f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
3307f22ef01cSRoman Divacky 
3308f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
3309f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
33106122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
3311f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
3312e7145dcbSDimitry Andric     llvm::Constant *GV =
3313e7145dcbSDimitry Andric         CreateRuntimeVariable(Ty, "__CFConstantStringClassReference");
3314e7145dcbSDimitry Andric 
331544290647SDimitry Andric     if (getTriple().isOSBinFormatCOFF()) {
3316e7145dcbSDimitry Andric       IdentifierInfo &II = getContext().Idents.get(GV->getName());
3317e7145dcbSDimitry Andric       TranslationUnitDecl *TUDecl = getContext().getTranslationUnitDecl();
3318e7145dcbSDimitry Andric       DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
3319e7145dcbSDimitry Andric       llvm::GlobalValue *CGV = cast<llvm::GlobalValue>(GV);
3320e7145dcbSDimitry Andric 
3321e7145dcbSDimitry Andric       const VarDecl *VD = nullptr;
3322e7145dcbSDimitry Andric       for (const auto &Result : DC->lookup(&II))
3323e7145dcbSDimitry Andric         if ((VD = dyn_cast<VarDecl>(Result)))
3324e7145dcbSDimitry Andric           break;
3325e7145dcbSDimitry Andric 
3326e7145dcbSDimitry Andric       if (!VD || !VD->hasAttr<DLLExportAttr>()) {
3327e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
3328e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3329e7145dcbSDimitry Andric       } else {
3330e7145dcbSDimitry Andric         CGV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
3331e7145dcbSDimitry Andric         CGV->setLinkage(llvm::GlobalValue::ExternalLinkage);
3332e7145dcbSDimitry Andric       }
3333e7145dcbSDimitry Andric     }
3334e7145dcbSDimitry Andric 
3335f22ef01cSRoman Divacky     // Decay array -> ptr
333644290647SDimitry Andric     CFConstantStringClassRef =
333744290647SDimitry Andric         llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
3338e7145dcbSDimitry Andric   }
3339f22ef01cSRoman Divacky 
3340f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
3341f22ef01cSRoman Divacky 
334259d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
3343f22ef01cSRoman Divacky 
334444290647SDimitry Andric   ConstantInitBuilder Builder(*this);
334544290647SDimitry Andric   auto Fields = Builder.beginStruct(STy);
3346f22ef01cSRoman Divacky 
3347f22ef01cSRoman Divacky   // Class pointer.
334844290647SDimitry Andric   Fields.add(cast<llvm::ConstantExpr>(CFConstantStringClassRef));
3349f22ef01cSRoman Divacky 
3350f22ef01cSRoman Divacky   // Flags.
335144290647SDimitry Andric   Fields.addInt(IntTy, isUTF16 ? 0x07d0 : 0x07C8);
3352f22ef01cSRoman Divacky 
3353f22ef01cSRoman Divacky   // String pointer.
335459d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
3355dff0c46cSDimitry Andric   if (isUTF16) {
33560623d748SDimitry Andric     auto Arr = llvm::makeArrayRef(
335739d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
335839d628a0SDimitry Andric         Entry.first().size() / 2);
3359dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
3360dff0c46cSDimitry Andric   } else {
336139d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
3362dff0c46cSDimitry Andric   }
3363f22ef01cSRoman Divacky 
3364dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
3365dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
336659d1ed5bSDimitry Andric   auto *GV =
3367dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
336859d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
3369e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
3370284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
3371284c1978SDimitry Andric   // of the string is via this class initializer.
3372e7145dcbSDimitry Andric   CharUnits Align = isUTF16
3373e7145dcbSDimitry Andric                         ? getContext().getTypeAlignInChars(getContext().ShortTy)
3374e7145dcbSDimitry Andric                         : getContext().getTypeAlignInChars(getContext().CharTy);
3375f22ef01cSRoman Divacky   GV->setAlignment(Align.getQuantity());
3376e7145dcbSDimitry Andric 
3377e7145dcbSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1.
3378e7145dcbSDimitry Andric   // Without it LLVM can merge the string with a non unnamed_addr one during
3379e7145dcbSDimitry Andric   // LTO.  Doing that changes the section it ends in, which surprises ld64.
338044290647SDimitry Andric   if (getTriple().isOSBinFormatMachO())
3381e7145dcbSDimitry Andric     GV->setSection(isUTF16 ? "__TEXT,__ustring"
3382e7145dcbSDimitry Andric                            : "__TEXT,__cstring,cstring_literals");
3383dff0c46cSDimitry Andric 
3384dff0c46cSDimitry Andric   // String.
338544290647SDimitry Andric   llvm::Constant *Str =
338633956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
3387f22ef01cSRoman Divacky 
3388dff0c46cSDimitry Andric   if (isUTF16)
3389dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
339044290647SDimitry Andric     Str = llvm::ConstantExpr::getBitCast(Str, Int8PtrTy);
339144290647SDimitry Andric   Fields.add(Str);
3392dff0c46cSDimitry Andric 
3393f22ef01cSRoman Divacky   // String length.
339444290647SDimitry Andric   auto Ty = getTypes().ConvertType(getContext().LongTy);
339544290647SDimitry Andric   Fields.addInt(cast<llvm::IntegerType>(Ty), StringLength);
3396f22ef01cSRoman Divacky 
33970623d748SDimitry Andric   CharUnits Alignment = getPointerAlign();
33980623d748SDimitry Andric 
3399f22ef01cSRoman Divacky   // The struct.
340044290647SDimitry Andric   GV = Fields.finishAndCreateGlobal("_unnamed_cfstring_", Alignment,
340144290647SDimitry Andric                                     /*isConstant=*/false,
340244290647SDimitry Andric                                     llvm::GlobalVariable::PrivateLinkage);
340344290647SDimitry Andric   switch (getTriple().getObjectFormat()) {
3404e7145dcbSDimitry Andric   case llvm::Triple::UnknownObjectFormat:
3405e7145dcbSDimitry Andric     llvm_unreachable("unknown file format");
3406e7145dcbSDimitry Andric   case llvm::Triple::COFF:
3407e7145dcbSDimitry Andric   case llvm::Triple::ELF:
340820e90f04SDimitry Andric   case llvm::Triple::Wasm:
3409e7145dcbSDimitry Andric     GV->setSection("cfstring");
3410e7145dcbSDimitry Andric     break;
3411e7145dcbSDimitry Andric   case llvm::Triple::MachO:
3412e7145dcbSDimitry Andric     GV->setSection("__DATA,__cfstring");
3413e7145dcbSDimitry Andric     break;
3414e7145dcbSDimitry Andric   }
341539d628a0SDimitry Andric   Entry.second = GV;
3416f22ef01cSRoman Divacky 
34170623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3418f22ef01cSRoman Divacky }
3419f22ef01cSRoman Divacky 
34206122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
34216122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
342259d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
34236122f3e6SDimitry Andric     D->startDefinition();
34246122f3e6SDimitry Andric 
34256122f3e6SDimitry Andric     QualType FieldTypes[] = {
34266122f3e6SDimitry Andric       Context.UnsignedLongTy,
34276122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
34286122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
34296122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
34306122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
34316122f3e6SDimitry Andric     };
34326122f3e6SDimitry Andric 
34336122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
34346122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
34356122f3e6SDimitry Andric                                            D,
34366122f3e6SDimitry Andric                                            SourceLocation(),
343759d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
343859d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
343959d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
34406122f3e6SDimitry Andric                                            /*Mutable=*/false,
34417ae0e2c9SDimitry Andric                                            ICIS_NoInit);
34426122f3e6SDimitry Andric       Field->setAccess(AS_public);
34436122f3e6SDimitry Andric       D->addDecl(Field);
34446122f3e6SDimitry Andric     }
34456122f3e6SDimitry Andric 
34466122f3e6SDimitry Andric     D->completeDefinition();
34476122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
34486122f3e6SDimitry Andric   }
34496122f3e6SDimitry Andric 
34506122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
34516122f3e6SDimitry Andric }
34526122f3e6SDimitry Andric 
3453dff0c46cSDimitry Andric llvm::Constant *
3454dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
3455dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
3456f22ef01cSRoman Divacky 
3457dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
3458dff0c46cSDimitry Andric   // as an inline array.
3459dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
3460dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
3461f22ef01cSRoman Divacky 
3462dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
3463dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
3464dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
3465dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
34666122f3e6SDimitry Andric   }
3467f22ef01cSRoman Divacky 
346859d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
3469dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
3470dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
3471f22ef01cSRoman Divacky 
3472dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
3473dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
3474dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
3475dff0c46cSDimitry Andric     Elements.reserve(NumElements);
3476dff0c46cSDimitry Andric 
3477dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3478dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
3479dff0c46cSDimitry Andric     Elements.resize(NumElements);
3480dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
3481dff0c46cSDimitry Andric   }
3482dff0c46cSDimitry Andric 
3483dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
3484dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
3485dff0c46cSDimitry Andric   Elements.reserve(NumElements);
3486dff0c46cSDimitry Andric 
3487dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
3488dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
3489dff0c46cSDimitry Andric   Elements.resize(NumElements);
3490dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
3491f22ef01cSRoman Divacky }
3492f22ef01cSRoman Divacky 
349359d1ed5bSDimitry Andric static llvm::GlobalVariable *
349459d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
349559d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
34960623d748SDimitry Andric                       CharUnits Alignment) {
349759d1ed5bSDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
349859d1ed5bSDimitry Andric   unsigned AddrSpace = 0;
349959d1ed5bSDimitry Andric   if (CGM.getLangOpts().OpenCL)
350059d1ed5bSDimitry Andric     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
3501dff0c46cSDimitry Andric 
350233956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
350359d1ed5bSDimitry Andric   // Create a global variable for this string
350459d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
350533956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
350633956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
35070623d748SDimitry Andric   GV->setAlignment(Alignment.getQuantity());
3508e7145dcbSDimitry Andric   GV->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
350933956c43SDimitry Andric   if (GV->isWeakForLinker()) {
351033956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
351133956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
351233956c43SDimitry Andric   }
351333956c43SDimitry Andric 
351459d1ed5bSDimitry Andric   return GV;
3515f22ef01cSRoman Divacky }
3516dff0c46cSDimitry Andric 
351759d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
351859d1ed5bSDimitry Andric /// constant array for the given string literal.
35190623d748SDimitry Andric ConstantAddress
352039d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
352139d628a0SDimitry Andric                                                   StringRef Name) {
35220623d748SDimitry Andric   CharUnits Alignment = getContext().getAlignOfGlobalVarInChars(S->getType());
3523dff0c46cSDimitry Andric 
352459d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
352559d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
352659d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
352759d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
352859d1ed5bSDimitry Andric     if (auto GV = *Entry) {
35290623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
35300623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
35310623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
353259d1ed5bSDimitry Andric     }
353359d1ed5bSDimitry Andric   }
353459d1ed5bSDimitry Andric 
353559d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
353659d1ed5bSDimitry Andric   StringRef GlobalVariableName;
353759d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
353859d1ed5bSDimitry Andric 
353959d1ed5bSDimitry Andric   // Mangle the string literal if the ABI allows for it.  However, we cannot
354059d1ed5bSDimitry Andric   // do this if  we are compiling with ASan or -fwritable-strings because they
354159d1ed5bSDimitry Andric   // rely on strings having normal linkage.
354239d628a0SDimitry Andric   if (!LangOpts.WritableStrings &&
354339d628a0SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
354459d1ed5bSDimitry Andric       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
354559d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
354659d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
354759d1ed5bSDimitry Andric 
354859d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
354959d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
355059d1ed5bSDimitry Andric   } else {
355159d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
355239d628a0SDimitry Andric     GlobalVariableName = Name;
355359d1ed5bSDimitry Andric   }
355459d1ed5bSDimitry Andric 
355559d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
355659d1ed5bSDimitry Andric   if (Entry)
355759d1ed5bSDimitry Andric     *Entry = GV;
355859d1ed5bSDimitry Andric 
355939d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
356039d628a0SDimitry Andric                                   QualType());
35610623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3562f22ef01cSRoman Divacky }
3563f22ef01cSRoman Divacky 
3564f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
3565f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
35660623d748SDimitry Andric ConstantAddress
3567f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
3568f22ef01cSRoman Divacky   std::string Str;
3569f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
3570f22ef01cSRoman Divacky 
3571f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
3572f22ef01cSRoman Divacky }
3573f22ef01cSRoman Divacky 
357459d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
357559d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
357659d1ed5bSDimitry Andric /// The result has pointer to array type.
35770623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfConstantCString(
35780623d748SDimitry Andric     const std::string &Str, const char *GlobalName) {
357959d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
35800623d748SDimitry Andric   CharUnits Alignment =
35810623d748SDimitry Andric     getContext().getAlignOfGlobalVarInChars(getContext().CharTy);
3582f22ef01cSRoman Divacky 
358359d1ed5bSDimitry Andric   llvm::Constant *C =
358459d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
358559d1ed5bSDimitry Andric 
358659d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
358759d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
358859d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
358959d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
359059d1ed5bSDimitry Andric     if (auto GV = *Entry) {
35910623d748SDimitry Andric       if (Alignment.getQuantity() > GV->getAlignment())
35920623d748SDimitry Andric         GV->setAlignment(Alignment.getQuantity());
35930623d748SDimitry Andric       return ConstantAddress(GV, Alignment);
359459d1ed5bSDimitry Andric     }
359559d1ed5bSDimitry Andric   }
359659d1ed5bSDimitry Andric 
3597f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
3598f22ef01cSRoman Divacky   if (!GlobalName)
3599f22ef01cSRoman Divacky     GlobalName = ".str";
3600f22ef01cSRoman Divacky   // Create a global variable for this.
360159d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
360259d1ed5bSDimitry Andric                                   GlobalName, Alignment);
360359d1ed5bSDimitry Andric   if (Entry)
360459d1ed5bSDimitry Andric     *Entry = GV;
36050623d748SDimitry Andric   return ConstantAddress(GV, Alignment);
3606f22ef01cSRoman Divacky }
3607f22ef01cSRoman Divacky 
36080623d748SDimitry Andric ConstantAddress CodeGenModule::GetAddrOfGlobalTemporary(
3609f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
3610f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
3611f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
361259d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3613f785676fSDimitry Andric 
3614f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
3615f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3616f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
3617f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
3618f785676fSDimitry Andric     MaterializedType = E->getType();
3619f785676fSDimitry Andric 
36200623d748SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(MaterializedType);
36210623d748SDimitry Andric 
36220623d748SDimitry Andric   if (llvm::Constant *Slot = MaterializedGlobalTemporaryMap[E])
36230623d748SDimitry Andric     return ConstantAddress(Slot, Align);
3624f785676fSDimitry Andric 
3625f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
3626f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
3627f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
3628f785676fSDimitry Andric   SmallString<256> Name;
3629f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
363059d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
363159d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
3632f785676fSDimitry Andric 
363359d1ed5bSDimitry Andric   APValue *Value = nullptr;
3634f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
3635f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
3636f785676fSDimitry Andric     // that this might have a different value from the value computed by
3637f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
3638f785676fSDimitry Andric     // modifies the temporary.
3639f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
3640f785676fSDimitry Andric     if (Value && Value->isUninit())
364159d1ed5bSDimitry Andric       Value = nullptr;
3642f785676fSDimitry Andric   }
3643f785676fSDimitry Andric 
3644f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
3645f785676fSDimitry Andric   Expr::EvalResult EvalResult;
3646f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3647f785676fSDimitry Andric       !EvalResult.hasSideEffects())
3648f785676fSDimitry Andric     Value = &EvalResult.Val;
3649f785676fSDimitry Andric 
365059d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
3651f785676fSDimitry Andric   bool Constant = false;
3652f785676fSDimitry Andric   llvm::Type *Type;
3653f785676fSDimitry Andric   if (Value) {
3654f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
365559d1ed5bSDimitry Andric     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3656f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3657f785676fSDimitry Andric     Type = InitialValue->getType();
3658f785676fSDimitry Andric   } else {
3659f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
3660f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
3661f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
3662f785676fSDimitry Andric   }
3663f785676fSDimitry Andric 
3664f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
366559d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
366659d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
366733956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
366833956c43SDimitry Andric     const VarDecl *InitVD;
366933956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
367033956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
367133956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
367233956c43SDimitry Andric       // class can be defined in multipe translation units.
367333956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
367433956c43SDimitry Andric     } else {
367533956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
367633956c43SDimitry Andric       // VarDecl has external linkage.
367733956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
367833956c43SDimitry Andric     }
367933956c43SDimitry Andric   }
368059d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(
368159d1ed5bSDimitry Andric       VD, getContext().getTargetAddressSpace(MaterializedType));
368259d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
368359d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
368459d1ed5bSDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
368559d1ed5bSDimitry Andric       AddrSpace);
368659d1ed5bSDimitry Andric   setGlobalVisibility(GV, VD);
36870623d748SDimitry Andric   GV->setAlignment(Align.getQuantity());
368833956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
368933956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3690f785676fSDimitry Andric   if (VD->getTLSKind())
3691f785676fSDimitry Andric     setTLSMode(GV, *VD);
36920623d748SDimitry Andric   MaterializedGlobalTemporaryMap[E] = GV;
36930623d748SDimitry Andric   return ConstantAddress(GV, Align);
3694f785676fSDimitry Andric }
3695f785676fSDimitry Andric 
3696f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
3697f22ef01cSRoman Divacky /// properties for an implementation.
3698f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
3699f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
370059d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
3701f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
3702f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3703f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3704f22ef01cSRoman Divacky 
3705f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
37063861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
3707f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
3708f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
3709f22ef01cSRoman Divacky       // this implementation.
3710f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
3711f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
3712f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3713f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
3714f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
3715f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
3716f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3717f22ef01cSRoman Divacky     }
3718f22ef01cSRoman Divacky   }
3719f22ef01cSRoman Divacky }
3720f22ef01cSRoman Divacky 
37213b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
37226122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
37236122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
37243b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
37253b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
37263b0f4066SDimitry Andric       return true;
37273b0f4066SDimitry Andric 
37283b0f4066SDimitry Andric   return false;
37293b0f4066SDimitry Andric }
37303b0f4066SDimitry Andric 
373139d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
373239d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
373339d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
373439d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
373539d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
373639d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
373739d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
373839d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
373939d628a0SDimitry Andric       return false;
374039d628a0SDimitry Andric   }
374139d628a0SDimitry Andric   return true;
374239d628a0SDimitry Andric }
374339d628a0SDimitry Andric 
3744f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
3745f22ef01cSRoman Divacky /// for an implementation.
3746f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
37473b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
37483b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
3749f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3750f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
37513b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
37523b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
375359d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
37546122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
37553861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
37566122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
3757f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
3758f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
37593861d79fSDimitry Andric     D->setHasDestructors(true);
37603b0f4066SDimitry Andric   }
3761f22ef01cSRoman Divacky 
37623b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
37633b0f4066SDimitry Andric   // a .cxx_construct.
376439d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
376539d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
37663b0f4066SDimitry Andric     return;
37673b0f4066SDimitry Andric 
37683b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
37693b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3770f22ef01cSRoman Divacky   // The constructor returns 'self'.
3771f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3772f22ef01cSRoman Divacky                                                 D->getLocation(),
37736122f3e6SDimitry Andric                                                 D->getLocation(),
37746122f3e6SDimitry Andric                                                 cxxSelector,
377559d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
377659d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
37776122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
37783861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
37796122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
37806122f3e6SDimitry Andric                                                 /*isDefined=*/false,
3781f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
3782f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
3783f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
37843861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
3785f22ef01cSRoman Divacky }
3786f22ef01cSRoman Divacky 
3787f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
3788f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3789f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3790f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3791f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
3792f22ef01cSRoman Divacky     return;
3793f22ef01cSRoman Divacky   }
3794f22ef01cSRoman Divacky 
379544290647SDimitry Andric   EmitDeclContext(LSD);
379644290647SDimitry Andric }
379744290647SDimitry Andric 
379844290647SDimitry Andric void CodeGenModule::EmitDeclContext(const DeclContext *DC) {
379944290647SDimitry Andric   for (auto *I : DC->decls()) {
380044290647SDimitry Andric     // Unlike other DeclContexts, the contents of an ObjCImplDecl at TU scope
380144290647SDimitry Andric     // are themselves considered "top-level", so EmitTopLevelDecl on an
380244290647SDimitry Andric     // ObjCImplDecl does not recursively visit them. We need to do that in
380344290647SDimitry Andric     // case they're nested inside another construct (LinkageSpecDecl /
380444290647SDimitry Andric     // ExportDecl) that does stop them from being considered "top-level".
380559d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
380659d1ed5bSDimitry Andric       for (auto *M : OID->methods())
380759d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
38083861d79fSDimitry Andric     }
380944290647SDimitry Andric 
381059d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3811f22ef01cSRoman Divacky   }
38123861d79fSDimitry Andric }
3813f22ef01cSRoman Divacky 
3814f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
3815f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3816f22ef01cSRoman Divacky   // Ignore dependent declarations.
3817f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3818f22ef01cSRoman Divacky     return;
3819f22ef01cSRoman Divacky 
3820f22ef01cSRoman Divacky   switch (D->getKind()) {
3821f22ef01cSRoman Divacky   case Decl::CXXConversion:
3822f22ef01cSRoman Divacky   case Decl::CXXMethod:
3823f22ef01cSRoman Divacky   case Decl::Function:
3824f22ef01cSRoman Divacky     // Skip function templates
38253b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
38263b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3827f22ef01cSRoman Divacky       return;
3828f22ef01cSRoman Divacky 
3829f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
383039d628a0SDimitry Andric     // Always provide some coverage mapping
383139d628a0SDimitry Andric     // even for the functions that aren't emitted.
383239d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
3833f22ef01cSRoman Divacky     break;
3834f22ef01cSRoman Divacky 
38356bc11b14SDimitry Andric   case Decl::CXXDeductionGuide:
38366bc11b14SDimitry Andric     // Function-like, but does not result in code emission.
38376bc11b14SDimitry Andric     break;
38386bc11b14SDimitry Andric 
3839f22ef01cSRoman Divacky   case Decl::Var:
384044290647SDimitry Andric   case Decl::Decomposition:
3841f785676fSDimitry Andric     // Skip variable templates
3842f785676fSDimitry Andric     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3843f785676fSDimitry Andric       return;
38446d97bb29SDimitry Andric     LLVM_FALLTHROUGH;
3845f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
3846f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
384744290647SDimitry Andric     if (auto *DD = dyn_cast<DecompositionDecl>(D))
384844290647SDimitry Andric       for (auto *B : DD->bindings())
384944290647SDimitry Andric         if (auto *HD = B->getHoldingVar())
385044290647SDimitry Andric           EmitGlobal(HD);
3851f22ef01cSRoman Divacky     break;
3852f22ef01cSRoman Divacky 
38533b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
38543b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
38553b0f4066SDimitry Andric   case Decl::IndirectField:
38563b0f4066SDimitry Andric     break;
38573b0f4066SDimitry Andric 
3858f22ef01cSRoman Divacky   // C++ Decls
3859f22ef01cSRoman Divacky   case Decl::Namespace:
386044290647SDimitry Andric     EmitDeclContext(cast<NamespaceDecl>(D));
3861f22ef01cSRoman Divacky     break;
3862e7145dcbSDimitry Andric   case Decl::CXXRecord:
386320e90f04SDimitry Andric     if (DebugInfo) {
386420e90f04SDimitry Andric       if (auto *ES = D->getASTContext().getExternalSource())
386520e90f04SDimitry Andric         if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
386620e90f04SDimitry Andric           DebugInfo->completeUnusedClass(cast<CXXRecordDecl>(*D));
386720e90f04SDimitry Andric     }
3868e7145dcbSDimitry Andric     // Emit any static data members, they may be definitions.
3869e7145dcbSDimitry Andric     for (auto *I : cast<CXXRecordDecl>(D)->decls())
3870e7145dcbSDimitry Andric       if (isa<VarDecl>(I) || isa<CXXRecordDecl>(I))
3871e7145dcbSDimitry Andric         EmitTopLevelDecl(I);
3872e7145dcbSDimitry Andric     break;
3873f22ef01cSRoman Divacky     // No code generation needed.
3874f22ef01cSRoman Divacky   case Decl::UsingShadow:
3875f22ef01cSRoman Divacky   case Decl::ClassTemplate:
3876f785676fSDimitry Andric   case Decl::VarTemplate:
3877f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
3878f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
3879bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
3880bd5abe19SDimitry Andric   case Decl::Block:
3881139f7f9bSDimitry Andric   case Decl::Empty:
3882f22ef01cSRoman Divacky     break;
388359d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
388459d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
388559d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
388659d1ed5bSDimitry Andric     return;
3887f785676fSDimitry Andric   case Decl::NamespaceAlias:
3888f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3889f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3890f785676fSDimitry Andric     return;
3891284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
3892284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3893284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3894284c1978SDimitry Andric     return;
3895f22ef01cSRoman Divacky   case Decl::CXXConstructor:
3896f22ef01cSRoman Divacky     // Skip function templates
38973b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
38983b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3899f22ef01cSRoman Divacky       return;
3900f22ef01cSRoman Divacky 
3901f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3902f22ef01cSRoman Divacky     break;
3903f22ef01cSRoman Divacky   case Decl::CXXDestructor:
39043b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
39053b0f4066SDimitry Andric       return;
3906f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3907f22ef01cSRoman Divacky     break;
3908f22ef01cSRoman Divacky 
3909f22ef01cSRoman Divacky   case Decl::StaticAssert:
3910f22ef01cSRoman Divacky     // Nothing to do.
3911f22ef01cSRoman Divacky     break;
3912f22ef01cSRoman Divacky 
3913f22ef01cSRoman Divacky   // Objective-C Decls
3914f22ef01cSRoman Divacky 
3915f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
3916f22ef01cSRoman Divacky   case Decl::ObjCInterface:
39177ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
3918f22ef01cSRoman Divacky     break;
3919f22ef01cSRoman Divacky 
3920dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
392159d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
3922dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
3923dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
3924f22ef01cSRoman Divacky     break;
3925dff0c46cSDimitry Andric   }
3926f22ef01cSRoman Divacky 
3927f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
3928f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
3929f22ef01cSRoman Divacky     // can ignore them here.
39306122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3931f22ef01cSRoman Divacky     break;
3932f22ef01cSRoman Divacky 
3933f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
393459d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
3935f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
3936f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
39376122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
3938dff0c46cSDimitry Andric     // Emit global variable debug information.
3939dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3940e7145dcbSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= codegenoptions::LimitedDebugInfo)
3941139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3942139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
3943f22ef01cSRoman Divacky     break;
3944f22ef01cSRoman Divacky   }
3945f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
394659d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
3947f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
3948f22ef01cSRoman Divacky     if (OMD->getBody())
3949f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3950f22ef01cSRoman Divacky     break;
3951f22ef01cSRoman Divacky   }
3952f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
3953dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3954f22ef01cSRoman Divacky     break;
3955f22ef01cSRoman Divacky 
3956e7145dcbSDimitry Andric   case Decl::PragmaComment: {
3957e7145dcbSDimitry Andric     const auto *PCD = cast<PragmaCommentDecl>(D);
3958e7145dcbSDimitry Andric     switch (PCD->getCommentKind()) {
3959e7145dcbSDimitry Andric     case PCK_Unknown:
3960e7145dcbSDimitry Andric       llvm_unreachable("unexpected pragma comment kind");
3961e7145dcbSDimitry Andric     case PCK_Linker:
3962e7145dcbSDimitry Andric       AppendLinkerOptions(PCD->getArg());
3963e7145dcbSDimitry Andric       break;
3964e7145dcbSDimitry Andric     case PCK_Lib:
3965e7145dcbSDimitry Andric       AddDependentLib(PCD->getArg());
3966e7145dcbSDimitry Andric       break;
3967e7145dcbSDimitry Andric     case PCK_Compiler:
3968e7145dcbSDimitry Andric     case PCK_ExeStr:
3969e7145dcbSDimitry Andric     case PCK_User:
3970e7145dcbSDimitry Andric       break; // We ignore all of these.
3971e7145dcbSDimitry Andric     }
3972e7145dcbSDimitry Andric     break;
3973e7145dcbSDimitry Andric   }
3974e7145dcbSDimitry Andric 
3975e7145dcbSDimitry Andric   case Decl::PragmaDetectMismatch: {
3976e7145dcbSDimitry Andric     const auto *PDMD = cast<PragmaDetectMismatchDecl>(D);
3977e7145dcbSDimitry Andric     AddDetectMismatch(PDMD->getName(), PDMD->getValue());
3978e7145dcbSDimitry Andric     break;
3979e7145dcbSDimitry Andric   }
3980e7145dcbSDimitry Andric 
3981f22ef01cSRoman Divacky   case Decl::LinkageSpec:
3982f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3983f22ef01cSRoman Divacky     break;
3984f22ef01cSRoman Divacky 
3985f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
398633956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
398733956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
398833956c43SDimitry Andric       break;
3989ea942507SDimitry Andric     // File-scope asm is ignored during device-side OpenMP compilation.
3990ea942507SDimitry Andric     if (LangOpts.OpenMPIsDevice)
3991ea942507SDimitry Andric       break;
399259d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
399333956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3994f22ef01cSRoman Divacky     break;
3995f22ef01cSRoman Divacky   }
3996f22ef01cSRoman Divacky 
3997139f7f9bSDimitry Andric   case Decl::Import: {
399859d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
3999139f7f9bSDimitry Andric 
400044290647SDimitry Andric     // If we've already imported this module, we're done.
400144290647SDimitry Andric     if (!ImportedModules.insert(Import->getImportedModule()))
4002139f7f9bSDimitry Andric       break;
400344290647SDimitry Andric 
400444290647SDimitry Andric     // Emit debug information for direct imports.
400544290647SDimitry Andric     if (!Import->getImportedOwningModule()) {
40063dac3a9bSDimitry Andric       if (CGDebugInfo *DI = getModuleDebugInfo())
40073dac3a9bSDimitry Andric         DI->EmitImportDecl(*Import);
400844290647SDimitry Andric     }
4009139f7f9bSDimitry Andric 
401044290647SDimitry Andric     // Find all of the submodules and emit the module initializers.
401144290647SDimitry Andric     llvm::SmallPtrSet<clang::Module *, 16> Visited;
401244290647SDimitry Andric     SmallVector<clang::Module *, 16> Stack;
401344290647SDimitry Andric     Visited.insert(Import->getImportedModule());
401444290647SDimitry Andric     Stack.push_back(Import->getImportedModule());
401544290647SDimitry Andric 
401644290647SDimitry Andric     while (!Stack.empty()) {
401744290647SDimitry Andric       clang::Module *Mod = Stack.pop_back_val();
401844290647SDimitry Andric       if (!EmittedModuleInitializers.insert(Mod).second)
401944290647SDimitry Andric         continue;
402044290647SDimitry Andric 
402144290647SDimitry Andric       for (auto *D : Context.getModuleInitializers(Mod))
402244290647SDimitry Andric         EmitTopLevelDecl(D);
402344290647SDimitry Andric 
402444290647SDimitry Andric       // Visit the submodules of this module.
402544290647SDimitry Andric       for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
402644290647SDimitry Andric                                              SubEnd = Mod->submodule_end();
402744290647SDimitry Andric            Sub != SubEnd; ++Sub) {
402844290647SDimitry Andric         // Skip explicit children; they need to be explicitly imported to emit
402944290647SDimitry Andric         // the initializers.
403044290647SDimitry Andric         if ((*Sub)->IsExplicit)
403144290647SDimitry Andric           continue;
403244290647SDimitry Andric 
403344290647SDimitry Andric         if (Visited.insert(*Sub).second)
403444290647SDimitry Andric           Stack.push_back(*Sub);
403544290647SDimitry Andric       }
403644290647SDimitry Andric     }
4037139f7f9bSDimitry Andric     break;
4038139f7f9bSDimitry Andric   }
4039139f7f9bSDimitry Andric 
404044290647SDimitry Andric   case Decl::Export:
404144290647SDimitry Andric     EmitDeclContext(cast<ExportDecl>(D));
404244290647SDimitry Andric     break;
404344290647SDimitry Andric 
404439d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
404539d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
404639d628a0SDimitry Andric     break;
404739d628a0SDimitry Andric 
404859d1ed5bSDimitry Andric   case Decl::ClassTemplateSpecialization: {
404959d1ed5bSDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
405059d1ed5bSDimitry Andric     if (DebugInfo &&
405139d628a0SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
405239d628a0SDimitry Andric         Spec->hasDefinition())
405359d1ed5bSDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
405439d628a0SDimitry Andric     break;
405559d1ed5bSDimitry Andric   }
405659d1ed5bSDimitry Andric 
4057e7145dcbSDimitry Andric   case Decl::OMPDeclareReduction:
4058e7145dcbSDimitry Andric     EmitOMPDeclareReduction(cast<OMPDeclareReductionDecl>(D));
4059e7145dcbSDimitry Andric     break;
4060e7145dcbSDimitry Andric 
4061f22ef01cSRoman Divacky   default:
4062f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
4063f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
4064f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
4065f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
406639d628a0SDimitry Andric     break;
406739d628a0SDimitry Andric   }
406839d628a0SDimitry Andric }
406939d628a0SDimitry Andric 
407039d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
407139d628a0SDimitry Andric   // Do we need to generate coverage mapping?
407239d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
407339d628a0SDimitry Andric     return;
407439d628a0SDimitry Andric   switch (D->getKind()) {
407539d628a0SDimitry Andric   case Decl::CXXConversion:
407639d628a0SDimitry Andric   case Decl::CXXMethod:
407739d628a0SDimitry Andric   case Decl::Function:
407839d628a0SDimitry Andric   case Decl::ObjCMethod:
407939d628a0SDimitry Andric   case Decl::CXXConstructor:
408039d628a0SDimitry Andric   case Decl::CXXDestructor: {
40810623d748SDimitry Andric     if (!cast<FunctionDecl>(D)->doesThisDeclarationHaveABody())
408239d628a0SDimitry Andric       return;
408339d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
408439d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
408539d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
408639d628a0SDimitry Andric     break;
408739d628a0SDimitry Andric   }
408839d628a0SDimitry Andric   default:
408939d628a0SDimitry Andric     break;
409039d628a0SDimitry Andric   };
409139d628a0SDimitry Andric }
409239d628a0SDimitry Andric 
409339d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
409439d628a0SDimitry Andric   // Do we need to generate coverage mapping?
409539d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
409639d628a0SDimitry Andric     return;
409739d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
409839d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
409939d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
410039d628a0SDimitry Andric   }
410139d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
410239d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
410339d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
410439d628a0SDimitry Andric   else
410539d628a0SDimitry Andric     I->second = false;
410639d628a0SDimitry Andric }
410739d628a0SDimitry Andric 
410839d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
410939d628a0SDimitry Andric   std::vector<const Decl *> DeferredDecls;
411033956c43SDimitry Andric   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
411139d628a0SDimitry Andric     if (!I.second)
411239d628a0SDimitry Andric       continue;
411339d628a0SDimitry Andric     DeferredDecls.push_back(I.first);
411439d628a0SDimitry Andric   }
411539d628a0SDimitry Andric   // Sort the declarations by their location to make sure that the tests get a
411639d628a0SDimitry Andric   // predictable order for the coverage mapping for the unused declarations.
411739d628a0SDimitry Andric   if (CodeGenOpts.DumpCoverageMapping)
411839d628a0SDimitry Andric     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
411939d628a0SDimitry Andric               [] (const Decl *LHS, const Decl *RHS) {
412039d628a0SDimitry Andric       return LHS->getLocStart() < RHS->getLocStart();
412139d628a0SDimitry Andric     });
412239d628a0SDimitry Andric   for (const auto *D : DeferredDecls) {
412339d628a0SDimitry Andric     switch (D->getKind()) {
412439d628a0SDimitry Andric     case Decl::CXXConversion:
412539d628a0SDimitry Andric     case Decl::CXXMethod:
412639d628a0SDimitry Andric     case Decl::Function:
412739d628a0SDimitry Andric     case Decl::ObjCMethod: {
412839d628a0SDimitry Andric       CodeGenPGO PGO(*this);
412939d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
413039d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
413139d628a0SDimitry Andric                                   getFunctionLinkage(GD));
413239d628a0SDimitry Andric       break;
413339d628a0SDimitry Andric     }
413439d628a0SDimitry Andric     case Decl::CXXConstructor: {
413539d628a0SDimitry Andric       CodeGenPGO PGO(*this);
413639d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
413739d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
413839d628a0SDimitry Andric                                   getFunctionLinkage(GD));
413939d628a0SDimitry Andric       break;
414039d628a0SDimitry Andric     }
414139d628a0SDimitry Andric     case Decl::CXXDestructor: {
414239d628a0SDimitry Andric       CodeGenPGO PGO(*this);
414339d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
414439d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
414539d628a0SDimitry Andric                                   getFunctionLinkage(GD));
414639d628a0SDimitry Andric       break;
414739d628a0SDimitry Andric     }
414839d628a0SDimitry Andric     default:
414939d628a0SDimitry Andric       break;
415039d628a0SDimitry Andric     };
4151f22ef01cSRoman Divacky   }
4152f22ef01cSRoman Divacky }
4153ffd1746dSEd Schouten 
4154ffd1746dSEd Schouten /// Turns the given pointer into a constant.
4155ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
4156ffd1746dSEd Schouten                                           const void *Ptr) {
4157ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
41586122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
4159ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
4160ffd1746dSEd Schouten }
4161ffd1746dSEd Schouten 
4162ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
4163ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
4164ffd1746dSEd Schouten                                    GlobalDecl D,
4165ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
4166ffd1746dSEd Schouten   if (!GlobalMetadata)
4167ffd1746dSEd Schouten     GlobalMetadata =
4168ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
4169ffd1746dSEd Schouten 
4170ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
417139d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
417239d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
417339d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
41743b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
4175ffd1746dSEd Schouten }
4176ffd1746dSEd Schouten 
4177284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
4178284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
4179284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
4180284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
4181284c1978SDimitry Andric /// same translation unit.
4182284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
4183e7145dcbSDimitry Andric   // Don't do anything if we're generating CUDA device code -- the NVPTX
4184e7145dcbSDimitry Andric   // assembly target doesn't support aliases.
4185e7145dcbSDimitry Andric   if (Context.getTargetInfo().getTriple().isNVPTX())
4186e7145dcbSDimitry Andric     return;
41878f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
41888f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
41898f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
4190284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
419159d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
4192284c1978SDimitry Andric   }
4193284c1978SDimitry Andric }
4194284c1978SDimitry Andric 
419559d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
419659d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
419759d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
419859d1ed5bSDimitry Andric   if (Res == Manglings.end())
419959d1ed5bSDimitry Andric     return false;
420059d1ed5bSDimitry Andric   Result = Res->getValue();
420159d1ed5bSDimitry Andric   return true;
420259d1ed5bSDimitry Andric }
420359d1ed5bSDimitry Andric 
4204ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
4205ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
4206ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
4207ffd1746dSEd Schouten ///
4208ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
4209ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
4210ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
4211ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
421259d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4213ffd1746dSEd Schouten 
421459d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
421559d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
42160623d748SDimitry Andric     // Some mangled names don't necessarily have an associated GlobalValue
42170623d748SDimitry Andric     // in this module, e.g. if we mangled it for DebugInfo.
42180623d748SDimitry Andric     if (Addr)
421959d1ed5bSDimitry Andric       EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
4220ffd1746dSEd Schouten   }
4221ffd1746dSEd Schouten }
4222ffd1746dSEd Schouten 
4223ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
4224ffd1746dSEd Schouten /// function.
4225ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
4226ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
4227ffd1746dSEd Schouten 
4228ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
4229ffd1746dSEd Schouten 
4230ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
4231ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
4232ffd1746dSEd Schouten 
423359d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
4234ffd1746dSEd Schouten 
423559d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
423659d1ed5bSDimitry Andric     const Decl *D = I.first;
42370623d748SDimitry Andric     llvm::Value *Addr = I.second.getPointer();
423859d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
4239ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
424039d628a0SDimitry Andric       Alloca->setMetadata(
424139d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
424239d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
424359d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
4244ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
4245ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
4246ffd1746dSEd Schouten     }
4247ffd1746dSEd Schouten   }
4248ffd1746dSEd Schouten }
4249e580952dSDimitry Andric 
4250f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
4251f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
4252f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
4253f785676fSDimitry Andric   std::string Version = getClangFullVersion();
4254f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
4255f785676fSDimitry Andric 
425639d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
4257f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
4258f785676fSDimitry Andric }
4259f785676fSDimitry Andric 
426059d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
426139d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
426239d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
426339d628a0SDimitry Andric   // of the container.
426439d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
426539d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
426639d628a0SDimitry Andric   // metadata when we emitted the declaration.
426739d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
426839d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
426939d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
427039d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
427159d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
427259d1ed5bSDimitry Andric   }
427359d1ed5bSDimitry Andric }
427459d1ed5bSDimitry Andric 
4275bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
427644290647SDimitry Andric   if (getCodeGenOpts().CoverageDataFile.empty() &&
427744290647SDimitry Andric       getCodeGenOpts().CoverageNotesFile.empty())
427844290647SDimitry Andric     return;
427944290647SDimitry Andric 
428044290647SDimitry Andric   llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu");
428144290647SDimitry Andric   if (!CUNode)
428244290647SDimitry Andric     return;
428344290647SDimitry Andric 
4284bd5abe19SDimitry Andric   llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
4285bd5abe19SDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
428644290647SDimitry Andric   auto *CoverageDataFile =
428744290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageDataFile);
428844290647SDimitry Andric   auto *CoverageNotesFile =
428944290647SDimitry Andric       llvm::MDString::get(Ctx, getCodeGenOpts().CoverageNotesFile);
4290bd5abe19SDimitry Andric   for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
4291bd5abe19SDimitry Andric     llvm::MDNode *CU = CUNode->getOperand(i);
429244290647SDimitry Andric     llvm::Metadata *Elts[] = {CoverageNotesFile, CoverageDataFile, CU};
429339d628a0SDimitry Andric     GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
4294bd5abe19SDimitry Andric   }
4295bd5abe19SDimitry Andric }
42963861d79fSDimitry Andric 
429739d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
42983861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
42993861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
43003861d79fSDimitry Andric   assert(Uuid.size() == 36);
4301f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
4302f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
4303f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
43043861d79fSDimitry Andric   }
43053861d79fSDimitry Andric 
430639d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
4307f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
43083861d79fSDimitry Andric 
4309f785676fSDimitry Andric   llvm::Constant *Field3[8];
4310f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
4311f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
4312f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
43133861d79fSDimitry Andric 
4314f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
4315f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
4316f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
4317f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
4318f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
4319f785676fSDimitry Andric   };
4320f785676fSDimitry Andric 
4321f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
43223861d79fSDimitry Andric }
432359d1ed5bSDimitry Andric 
432459d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
432559d1ed5bSDimitry Andric                                                        bool ForEH) {
432659d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
432759d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
432859d1ed5bSDimitry Andric   // and it's not for EH?
432959d1ed5bSDimitry Andric   if (!ForEH && !getLangOpts().RTTI)
433059d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
433159d1ed5bSDimitry Andric 
433259d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
433359d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
433459d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
433559d1ed5bSDimitry Andric 
433659d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
433759d1ed5bSDimitry Andric }
433859d1ed5bSDimitry Andric 
433939d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
434039d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
434139d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
434239d628a0SDimitry Andric     bool PerformInit =
434339d628a0SDimitry Andric         VD->getAnyInitializer() &&
434439d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
434539d628a0SDimitry Andric                                                         /*ForRef=*/false);
43460623d748SDimitry Andric 
43470623d748SDimitry Andric     Address Addr(GetAddrOfGlobalVar(VD), getContext().getDeclAlign(VD));
434833956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
43490623d748SDimitry Andric             VD, Addr, RefExpr->getLocStart(), PerformInit))
435039d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
435139d628a0SDimitry Andric   }
435239d628a0SDimitry Andric }
43538f0fd8f6SDimitry Andric 
43540623d748SDimitry Andric llvm::Metadata *CodeGenModule::CreateMetadataIdentifierForType(QualType T) {
43550623d748SDimitry Andric   llvm::Metadata *&InternalId = MetadataIdMap[T.getCanonicalType()];
43560623d748SDimitry Andric   if (InternalId)
43570623d748SDimitry Andric     return InternalId;
43580623d748SDimitry Andric 
43590623d748SDimitry Andric   if (isExternallyVisible(T->getLinkage())) {
43608f0fd8f6SDimitry Andric     std::string OutName;
43618f0fd8f6SDimitry Andric     llvm::raw_string_ostream Out(OutName);
43620623d748SDimitry Andric     getCXXABI().getMangleContext().mangleTypeName(T, Out);
43638f0fd8f6SDimitry Andric 
43640623d748SDimitry Andric     InternalId = llvm::MDString::get(getLLVMContext(), Out.str());
43650623d748SDimitry Andric   } else {
43660623d748SDimitry Andric     InternalId = llvm::MDNode::getDistinct(getLLVMContext(),
43670623d748SDimitry Andric                                            llvm::ArrayRef<llvm::Metadata *>());
43680623d748SDimitry Andric   }
43690623d748SDimitry Andric 
43700623d748SDimitry Andric   return InternalId;
43710623d748SDimitry Andric }
43720623d748SDimitry Andric 
4373e7145dcbSDimitry Andric /// Returns whether this module needs the "all-vtables" type identifier.
4374e7145dcbSDimitry Andric bool CodeGenModule::NeedAllVtablesTypeId() const {
4375e7145dcbSDimitry Andric   // Returns true if at least one of vtable-based CFI checkers is enabled and
4376e7145dcbSDimitry Andric   // is not in the trapping mode.
4377e7145dcbSDimitry Andric   return ((LangOpts.Sanitize.has(SanitizerKind::CFIVCall) &&
4378e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIVCall)) ||
4379e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFINVCall) &&
4380e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFINVCall)) ||
4381e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIDerivedCast) &&
4382e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIDerivedCast)) ||
4383e7145dcbSDimitry Andric           (LangOpts.Sanitize.has(SanitizerKind::CFIUnrelatedCast) &&
4384e7145dcbSDimitry Andric            !CodeGenOpts.SanitizeTrap.has(SanitizerKind::CFIUnrelatedCast)));
4385e7145dcbSDimitry Andric }
4386e7145dcbSDimitry Andric 
4387e7145dcbSDimitry Andric void CodeGenModule::AddVTableTypeMetadata(llvm::GlobalVariable *VTable,
43880623d748SDimitry Andric                                           CharUnits Offset,
43890623d748SDimitry Andric                                           const CXXRecordDecl *RD) {
43900623d748SDimitry Andric   llvm::Metadata *MD =
43910623d748SDimitry Andric       CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0));
4392e7145dcbSDimitry Andric   VTable->addTypeMetadata(Offset.getQuantity(), MD);
43930623d748SDimitry Andric 
4394e7145dcbSDimitry Andric   if (CodeGenOpts.SanitizeCfiCrossDso)
4395e7145dcbSDimitry Andric     if (auto CrossDsoTypeId = CreateCrossDsoCfiTypeId(MD))
4396e7145dcbSDimitry Andric       VTable->addTypeMetadata(Offset.getQuantity(),
4397e7145dcbSDimitry Andric                               llvm::ConstantAsMetadata::get(CrossDsoTypeId));
4398e7145dcbSDimitry Andric 
4399e7145dcbSDimitry Andric   if (NeedAllVtablesTypeId()) {
4400e7145dcbSDimitry Andric     llvm::Metadata *MD = llvm::MDString::get(getLLVMContext(), "all-vtables");
4401e7145dcbSDimitry Andric     VTable->addTypeMetadata(Offset.getQuantity(), MD);
44020623d748SDimitry Andric   }
44030623d748SDimitry Andric }
44040623d748SDimitry Andric 
44050623d748SDimitry Andric // Fills in the supplied string map with the set of target features for the
44060623d748SDimitry Andric // passed in function.
44070623d748SDimitry Andric void CodeGenModule::getFunctionFeatureMap(llvm::StringMap<bool> &FeatureMap,
44080623d748SDimitry Andric                                           const FunctionDecl *FD) {
44090623d748SDimitry Andric   StringRef TargetCPU = Target.getTargetOpts().CPU;
44100623d748SDimitry Andric   if (const auto *TD = FD->getAttr<TargetAttr>()) {
44110623d748SDimitry Andric     // If we have a TargetAttr build up the feature map based on that.
44120623d748SDimitry Andric     TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
44130623d748SDimitry Andric 
44140623d748SDimitry Andric     // Make a copy of the features as passed on the command line into the
44150623d748SDimitry Andric     // beginning of the additional features from the function to override.
44160623d748SDimitry Andric     ParsedAttr.first.insert(ParsedAttr.first.begin(),
44170623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.begin(),
44180623d748SDimitry Andric                             Target.getTargetOpts().FeaturesAsWritten.end());
44190623d748SDimitry Andric 
44200623d748SDimitry Andric     if (ParsedAttr.second != "")
44210623d748SDimitry Andric       TargetCPU = ParsedAttr.second;
44220623d748SDimitry Andric 
44230623d748SDimitry Andric     // Now populate the feature map, first with the TargetCPU which is either
44240623d748SDimitry Andric     // the default or a new one from the target attribute string. Then we'll use
44250623d748SDimitry Andric     // the passed in features (FeaturesAsWritten) along with the new ones from
44260623d748SDimitry Andric     // the attribute.
44270623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU, ParsedAttr.first);
44280623d748SDimitry Andric   } else {
44290623d748SDimitry Andric     Target.initFeatureMap(FeatureMap, getDiags(), TargetCPU,
44300623d748SDimitry Andric                           Target.getTargetOpts().Features);
44310623d748SDimitry Andric   }
44328f0fd8f6SDimitry Andric }
4433e7145dcbSDimitry Andric 
4434e7145dcbSDimitry Andric llvm::SanitizerStatReport &CodeGenModule::getSanStats() {
4435e7145dcbSDimitry Andric   if (!SanStats)
4436e7145dcbSDimitry Andric     SanStats = llvm::make_unique<llvm::SanitizerStatReport>(&getModule());
4437e7145dcbSDimitry Andric 
4438e7145dcbSDimitry Andric   return *SanStats;
4439e7145dcbSDimitry Andric }
444044290647SDimitry Andric llvm::Value *
444144290647SDimitry Andric CodeGenModule::createOpenCLIntToSamplerConversion(const Expr *E,
444244290647SDimitry Andric                                                   CodeGenFunction &CGF) {
444344290647SDimitry Andric   llvm::Constant *C = EmitConstantExpr(E, E->getType(), &CGF);
444444290647SDimitry Andric   auto SamplerT = getOpenCLRuntime().getSamplerType();
444544290647SDimitry Andric   auto FTy = llvm::FunctionType::get(SamplerT, {C->getType()}, false);
444644290647SDimitry Andric   return CGF.Builder.CreateCall(CreateRuntimeFunction(FTy,
444744290647SDimitry Andric                                 "__translate_sampler_initializer"),
444844290647SDimitry Andric                                 {C});
444944290647SDimitry Andric }
4450