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"
156122f3e6SDimitry Andric #include "CGCUDARuntime.h"
16e580952dSDimitry Andric #include "CGCXXABI.h"
17139f7f9bSDimitry Andric #include "CGCall.h"
18139f7f9bSDimitry Andric #include "CGDebugInfo.h"
19f22ef01cSRoman Divacky #include "CGObjCRuntime.h"
206122f3e6SDimitry Andric #include "CGOpenCLRuntime.h"
2159d1ed5bSDimitry Andric #include "CGOpenMPRuntime.h"
22139f7f9bSDimitry Andric #include "CodeGenFunction.h"
2359d1ed5bSDimitry Andric #include "CodeGenPGO.h"
24139f7f9bSDimitry Andric #include "CodeGenTBAA.h"
2539d628a0SDimitry Andric #include "CoverageMappingGen.h"
26f22ef01cSRoman Divacky #include "TargetInfo.h"
27f22ef01cSRoman Divacky #include "clang/AST/ASTContext.h"
28f22ef01cSRoman Divacky #include "clang/AST/CharUnits.h"
29f22ef01cSRoman Divacky #include "clang/AST/DeclCXX.h"
30139f7f9bSDimitry Andric #include "clang/AST/DeclObjC.h"
31ffd1746dSEd Schouten #include "clang/AST/DeclTemplate.h"
322754fe60SDimitry Andric #include "clang/AST/Mangle.h"
33f22ef01cSRoman Divacky #include "clang/AST/RecordLayout.h"
34f8254f43SDimitry Andric #include "clang/AST/RecursiveASTVisitor.h"
35dff0c46cSDimitry Andric #include "clang/Basic/Builtins.h"
36139f7f9bSDimitry Andric #include "clang/Basic/CharInfo.h"
37f22ef01cSRoman Divacky #include "clang/Basic/Diagnostic.h"
38139f7f9bSDimitry Andric #include "clang/Basic/Module.h"
39f22ef01cSRoman Divacky #include "clang/Basic/SourceManager.h"
40f22ef01cSRoman Divacky #include "clang/Basic/TargetInfo.h"
41f785676fSDimitry Andric #include "clang/Basic/Version.h"
42139f7f9bSDimitry Andric #include "clang/Frontend/CodeGenOptions.h"
43f785676fSDimitry Andric #include "clang/Sema/SemaDiagnostic.h"
44dff0c46cSDimitry Andric #include "llvm/ADT/APSInt.h"
45f22ef01cSRoman Divacky #include "llvm/ADT/Triple.h"
4659d1ed5bSDimitry Andric #include "llvm/IR/CallSite.h"
47139f7f9bSDimitry Andric #include "llvm/IR/CallingConv.h"
48139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
49139f7f9bSDimitry Andric #include "llvm/IR/Intrinsics.h"
50139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
51139f7f9bSDimitry Andric #include "llvm/IR/Module.h"
5259d1ed5bSDimitry Andric #include "llvm/ProfileData/InstrProfReader.h"
53139f7f9bSDimitry Andric #include "llvm/Support/ConvertUTF.h"
54f22ef01cSRoman Divacky #include "llvm/Support/ErrorHandling.h"
55139f7f9bSDimitry Andric 
56f22ef01cSRoman Divacky using namespace clang;
57f22ef01cSRoman Divacky using namespace CodeGen;
58f22ef01cSRoman Divacky 
596122f3e6SDimitry Andric static const char AnnotationSection[] = "llvm.metadata";
606122f3e6SDimitry Andric 
6159d1ed5bSDimitry Andric static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
62284c1978SDimitry Andric   switch (CGM.getTarget().getCXXABI().getKind()) {
63139f7f9bSDimitry Andric   case TargetCXXABI::GenericAArch64:
64139f7f9bSDimitry Andric   case TargetCXXABI::GenericARM:
65139f7f9bSDimitry Andric   case TargetCXXABI::iOS:
6659d1ed5bSDimitry Andric   case TargetCXXABI::iOS64:
67ef6fa9e2SDimitry Andric   case TargetCXXABI::GenericMIPS:
68139f7f9bSDimitry Andric   case TargetCXXABI::GenericItanium:
6959d1ed5bSDimitry Andric     return CreateItaniumCXXABI(CGM);
70139f7f9bSDimitry Andric   case TargetCXXABI::Microsoft:
7159d1ed5bSDimitry Andric     return CreateMicrosoftCXXABI(CGM);
72e580952dSDimitry Andric   }
73e580952dSDimitry Andric 
74e580952dSDimitry Andric   llvm_unreachable("invalid C++ ABI kind");
75e580952dSDimitry Andric }
76e580952dSDimitry Andric 
773dac3a9bSDimitry Andric CodeGenModule::CodeGenModule(ASTContext &C, const HeaderSearchOptions &HSO,
783dac3a9bSDimitry Andric                              const PreprocessorOptions &PPO,
793dac3a9bSDimitry Andric                              const CodeGenOptions &CGO, llvm::Module &M,
803dac3a9bSDimitry Andric                              const llvm::DataLayout &TD,
8139d628a0SDimitry Andric                              DiagnosticsEngine &diags,
8239d628a0SDimitry Andric                              CoverageSourceInfo *CoverageInfo)
833dac3a9bSDimitry Andric     : Context(C), LangOpts(C.getLangOpts()), HeaderSearchOpts(HSO),
843dac3a9bSDimitry Andric       PreprocessorOpts(PPO), CodeGenOpts(CGO), TheModule(M), Diags(diags),
853dac3a9bSDimitry Andric       TheDataLayout(TD), Target(C.getTargetInfo()), ABI(createCXXABI(*this)),
863dac3a9bSDimitry Andric       VMContext(M.getContext()), TBAA(nullptr), TheTargetCodeGenInfo(nullptr),
873dac3a9bSDimitry Andric       Types(*this), VTables(*this), ObjCRuntime(nullptr),
883dac3a9bSDimitry Andric       OpenCLRuntime(nullptr), OpenMPRuntime(nullptr), CUDARuntime(nullptr),
893dac3a9bSDimitry Andric       DebugInfo(nullptr), ARCData(nullptr),
9059d1ed5bSDimitry Andric       NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
9159d1ed5bSDimitry Andric       CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
9259d1ed5bSDimitry Andric       NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
9359d1ed5bSDimitry Andric       NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
9459d1ed5bSDimitry Andric       BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
9559d1ed5bSDimitry Andric       GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
9639d628a0SDimitry Andric       LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
97dff0c46cSDimitry Andric 
98dff0c46cSDimitry Andric   // Initialize the type cache.
99dff0c46cSDimitry Andric   llvm::LLVMContext &LLVMContext = M.getContext();
100dff0c46cSDimitry Andric   VoidTy = llvm::Type::getVoidTy(LLVMContext);
101dff0c46cSDimitry Andric   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
102dff0c46cSDimitry Andric   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
103dff0c46cSDimitry Andric   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
104dff0c46cSDimitry Andric   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
105dff0c46cSDimitry Andric   FloatTy = llvm::Type::getFloatTy(LLVMContext);
106dff0c46cSDimitry Andric   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
107dff0c46cSDimitry Andric   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
108dff0c46cSDimitry Andric   PointerAlignInBytes =
109dff0c46cSDimitry Andric   C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
110dff0c46cSDimitry Andric   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
111dff0c46cSDimitry Andric   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
112dff0c46cSDimitry Andric   Int8PtrTy = Int8Ty->getPointerTo(0);
113dff0c46cSDimitry Andric   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
114dff0c46cSDimitry Andric 
115139f7f9bSDimitry Andric   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
11639d628a0SDimitry Andric   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
117139f7f9bSDimitry Andric 
118dff0c46cSDimitry Andric   if (LangOpts.ObjC1)
1193b0f4066SDimitry Andric     createObjCRuntime();
120dff0c46cSDimitry Andric   if (LangOpts.OpenCL)
1216122f3e6SDimitry Andric     createOpenCLRuntime();
12259d1ed5bSDimitry Andric   if (LangOpts.OpenMP)
12359d1ed5bSDimitry Andric     createOpenMPRuntime();
124dff0c46cSDimitry Andric   if (LangOpts.CUDA)
1256122f3e6SDimitry Andric     createCUDARuntime();
126f22ef01cSRoman Divacky 
1277ae0e2c9SDimitry Andric   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
12839d628a0SDimitry Andric   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
1297ae0e2c9SDimitry Andric       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
1307ae0e2c9SDimitry Andric     TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
13159d1ed5bSDimitry Andric                            getCXXABI().getMangleContext());
1322754fe60SDimitry Andric 
1333b0f4066SDimitry Andric   // If debug info or coverage generation is enabled, create the CGDebugInfo
1343b0f4066SDimitry Andric   // object.
1353861d79fSDimitry Andric   if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
1367ae0e2c9SDimitry Andric       CodeGenOpts.EmitGcovArcs ||
1373b0f4066SDimitry Andric       CodeGenOpts.EmitGcovNotes)
1383b0f4066SDimitry Andric     DebugInfo = new CGDebugInfo(*this);
1392754fe60SDimitry Andric 
1402754fe60SDimitry Andric   Block.GlobalUniqueCount = 0;
1412754fe60SDimitry Andric 
142dff0c46cSDimitry Andric   if (C.getLangOpts().ObjCAutoRefCount)
14317a519f9SDimitry Andric     ARCData = new ARCEntrypoints();
14417a519f9SDimitry Andric   RRData = new RREntrypoints();
14559d1ed5bSDimitry Andric 
14659d1ed5bSDimitry Andric   if (!CodeGenOpts.InstrProfileInput.empty()) {
14733956c43SDimitry Andric     auto ReaderOrErr =
14833956c43SDimitry Andric         llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput);
14933956c43SDimitry Andric     if (std::error_code EC = ReaderOrErr.getError()) {
15059d1ed5bSDimitry Andric       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1513dac3a9bSDimitry Andric                                               "Could not read profile %0: %1");
1523dac3a9bSDimitry Andric       getDiags().Report(DiagID) << CodeGenOpts.InstrProfileInput
1533dac3a9bSDimitry Andric                                 << EC.message();
15433956c43SDimitry Andric     } else
15533956c43SDimitry Andric       PGOReader = std::move(ReaderOrErr.get());
15659d1ed5bSDimitry Andric   }
15739d628a0SDimitry Andric 
15839d628a0SDimitry Andric   // If coverage mapping generation is enabled, create the
15939d628a0SDimitry Andric   // CoverageMappingModuleGen object.
16039d628a0SDimitry Andric   if (CodeGenOpts.CoverageMapping)
16139d628a0SDimitry Andric     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
162f22ef01cSRoman Divacky }
163f22ef01cSRoman Divacky 
164f22ef01cSRoman Divacky CodeGenModule::~CodeGenModule() {
1656122f3e6SDimitry Andric   delete ObjCRuntime;
1666122f3e6SDimitry Andric   delete OpenCLRuntime;
16759d1ed5bSDimitry Andric   delete OpenMPRuntime;
1686122f3e6SDimitry Andric   delete CUDARuntime;
1696122f3e6SDimitry Andric   delete TheTargetCodeGenInfo;
1702754fe60SDimitry Andric   delete TBAA;
171f22ef01cSRoman Divacky   delete DebugInfo;
17217a519f9SDimitry Andric   delete ARCData;
17317a519f9SDimitry Andric   delete RRData;
174f22ef01cSRoman Divacky }
175f22ef01cSRoman Divacky 
176f22ef01cSRoman Divacky void CodeGenModule::createObjCRuntime() {
1777ae0e2c9SDimitry Andric   // This is just isGNUFamily(), but we want to force implementors of
1787ae0e2c9SDimitry Andric   // new ABIs to decide how best to do this.
1797ae0e2c9SDimitry Andric   switch (LangOpts.ObjCRuntime.getKind()) {
1807ae0e2c9SDimitry Andric   case ObjCRuntime::GNUstep:
1817ae0e2c9SDimitry Andric   case ObjCRuntime::GCC:
1827ae0e2c9SDimitry Andric   case ObjCRuntime::ObjFW:
1836122f3e6SDimitry Andric     ObjCRuntime = CreateGNUObjCRuntime(*this);
1847ae0e2c9SDimitry Andric     return;
1857ae0e2c9SDimitry Andric 
1867ae0e2c9SDimitry Andric   case ObjCRuntime::FragileMacOSX:
1877ae0e2c9SDimitry Andric   case ObjCRuntime::MacOSX:
1887ae0e2c9SDimitry Andric   case ObjCRuntime::iOS:
1896122f3e6SDimitry Andric     ObjCRuntime = CreateMacObjCRuntime(*this);
1907ae0e2c9SDimitry Andric     return;
1917ae0e2c9SDimitry Andric   }
1927ae0e2c9SDimitry Andric   llvm_unreachable("bad runtime kind");
1936122f3e6SDimitry Andric }
1946122f3e6SDimitry Andric 
1956122f3e6SDimitry Andric void CodeGenModule::createOpenCLRuntime() {
1966122f3e6SDimitry Andric   OpenCLRuntime = new CGOpenCLRuntime(*this);
1976122f3e6SDimitry Andric }
1986122f3e6SDimitry Andric 
19959d1ed5bSDimitry Andric void CodeGenModule::createOpenMPRuntime() {
20059d1ed5bSDimitry Andric   OpenMPRuntime = new CGOpenMPRuntime(*this);
20159d1ed5bSDimitry Andric }
20259d1ed5bSDimitry Andric 
2036122f3e6SDimitry Andric void CodeGenModule::createCUDARuntime() {
2046122f3e6SDimitry Andric   CUDARuntime = CreateNVCUDARuntime(*this);
205f22ef01cSRoman Divacky }
206f22ef01cSRoman Divacky 
20739d628a0SDimitry Andric void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
20839d628a0SDimitry Andric   Replacements[Name] = C;
20939d628a0SDimitry Andric }
21039d628a0SDimitry Andric 
211f785676fSDimitry Andric void CodeGenModule::applyReplacements() {
2128f0fd8f6SDimitry Andric   for (auto &I : Replacements) {
2138f0fd8f6SDimitry Andric     StringRef MangledName = I.first();
2148f0fd8f6SDimitry Andric     llvm::Constant *Replacement = I.second;
215f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
216f785676fSDimitry Andric     if (!Entry)
217f785676fSDimitry Andric       continue;
21859d1ed5bSDimitry Andric     auto *OldF = cast<llvm::Function>(Entry);
21959d1ed5bSDimitry Andric     auto *NewF = dyn_cast<llvm::Function>(Replacement);
220f785676fSDimitry Andric     if (!NewF) {
22159d1ed5bSDimitry Andric       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
22259d1ed5bSDimitry Andric         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
22359d1ed5bSDimitry Andric       } else {
22459d1ed5bSDimitry Andric         auto *CE = cast<llvm::ConstantExpr>(Replacement);
225f785676fSDimitry Andric         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
226f785676fSDimitry Andric                CE->getOpcode() == llvm::Instruction::GetElementPtr);
227f785676fSDimitry Andric         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
228f785676fSDimitry Andric       }
22959d1ed5bSDimitry Andric     }
230f785676fSDimitry Andric 
231f785676fSDimitry Andric     // Replace old with new, but keep the old order.
232f785676fSDimitry Andric     OldF->replaceAllUsesWith(Replacement);
233f785676fSDimitry Andric     if (NewF) {
234f785676fSDimitry Andric       NewF->removeFromParent();
235f785676fSDimitry Andric       OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
236f785676fSDimitry Andric     }
237f785676fSDimitry Andric     OldF->eraseFromParent();
238f785676fSDimitry Andric   }
239f785676fSDimitry Andric }
240f785676fSDimitry Andric 
24159d1ed5bSDimitry Andric // This is only used in aliases that we created and we know they have a
24259d1ed5bSDimitry Andric // linear structure.
24359d1ed5bSDimitry Andric static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
24459d1ed5bSDimitry Andric   llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
24559d1ed5bSDimitry Andric   const llvm::Constant *C = &GA;
24659d1ed5bSDimitry Andric   for (;;) {
24759d1ed5bSDimitry Andric     C = C->stripPointerCasts();
24859d1ed5bSDimitry Andric     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
24959d1ed5bSDimitry Andric       return GO;
25059d1ed5bSDimitry Andric     // stripPointerCasts will not walk over weak aliases.
25159d1ed5bSDimitry Andric     auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
25259d1ed5bSDimitry Andric     if (!GA2)
25359d1ed5bSDimitry Andric       return nullptr;
25439d628a0SDimitry Andric     if (!Visited.insert(GA2).second)
25559d1ed5bSDimitry Andric       return nullptr;
25659d1ed5bSDimitry Andric     C = GA2->getAliasee();
25759d1ed5bSDimitry Andric   }
25859d1ed5bSDimitry Andric }
25959d1ed5bSDimitry Andric 
260f785676fSDimitry Andric void CodeGenModule::checkAliases() {
26159d1ed5bSDimitry Andric   // Check if the constructed aliases are well formed. It is really unfortunate
26259d1ed5bSDimitry Andric   // that we have to do this in CodeGen, but we only construct mangled names
26359d1ed5bSDimitry Andric   // and aliases during codegen.
264f785676fSDimitry Andric   bool Error = false;
26559d1ed5bSDimitry Andric   DiagnosticsEngine &Diags = getDiags();
2668f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
26759d1ed5bSDimitry Andric     const auto *D = cast<ValueDecl>(GD.getDecl());
268f785676fSDimitry Andric     const AliasAttr *AA = D->getAttr<AliasAttr>();
269f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
270f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
27159d1ed5bSDimitry Andric     auto *Alias = cast<llvm::GlobalAlias>(Entry);
27259d1ed5bSDimitry Andric     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
27359d1ed5bSDimitry Andric     if (!GV) {
274f785676fSDimitry Andric       Error = true;
27559d1ed5bSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
27659d1ed5bSDimitry Andric     } else if (GV->isDeclaration()) {
277f785676fSDimitry Andric       Error = true;
27859d1ed5bSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
27959d1ed5bSDimitry Andric     }
28059d1ed5bSDimitry Andric 
28159d1ed5bSDimitry Andric     llvm::Constant *Aliasee = Alias->getAliasee();
28259d1ed5bSDimitry Andric     llvm::GlobalValue *AliaseeGV;
28359d1ed5bSDimitry Andric     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
28459d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
28559d1ed5bSDimitry Andric     else
28659d1ed5bSDimitry Andric       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
28759d1ed5bSDimitry Andric 
28859d1ed5bSDimitry Andric     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
28959d1ed5bSDimitry Andric       StringRef AliasSection = SA->getName();
29059d1ed5bSDimitry Andric       if (AliasSection != AliaseeGV->getSection())
29159d1ed5bSDimitry Andric         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
29259d1ed5bSDimitry Andric             << AliasSection;
29359d1ed5bSDimitry Andric     }
29459d1ed5bSDimitry Andric 
29559d1ed5bSDimitry Andric     // We have to handle alias to weak aliases in here. LLVM itself disallows
29659d1ed5bSDimitry Andric     // this since the object semantics would not match the IL one. For
29759d1ed5bSDimitry Andric     // compatibility with gcc we implement it by just pointing the alias
29859d1ed5bSDimitry Andric     // to its aliasee's aliasee. We also warn, since the user is probably
29959d1ed5bSDimitry Andric     // expecting the link to be weak.
30059d1ed5bSDimitry Andric     if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
30159d1ed5bSDimitry Andric       if (GA->mayBeOverridden()) {
30259d1ed5bSDimitry Andric         Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
30359d1ed5bSDimitry Andric             << GV->getName() << GA->getName();
30459d1ed5bSDimitry Andric         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
30559d1ed5bSDimitry Andric             GA->getAliasee(), Alias->getType());
30659d1ed5bSDimitry Andric         Alias->setAliasee(Aliasee);
30759d1ed5bSDimitry Andric       }
308f785676fSDimitry Andric     }
309f785676fSDimitry Andric   }
310f785676fSDimitry Andric   if (!Error)
311f785676fSDimitry Andric     return;
312f785676fSDimitry Andric 
3138f0fd8f6SDimitry Andric   for (const GlobalDecl &GD : Aliases) {
314f785676fSDimitry Andric     StringRef MangledName = getMangledName(GD);
315f785676fSDimitry Andric     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
31659d1ed5bSDimitry Andric     auto *Alias = cast<llvm::GlobalAlias>(Entry);
317f785676fSDimitry Andric     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
318f785676fSDimitry Andric     Alias->eraseFromParent();
319f785676fSDimitry Andric   }
320f785676fSDimitry Andric }
321f785676fSDimitry Andric 
32259d1ed5bSDimitry Andric void CodeGenModule::clear() {
32359d1ed5bSDimitry Andric   DeferredDeclsToEmit.clear();
32433956c43SDimitry Andric   if (OpenMPRuntime)
32533956c43SDimitry Andric     OpenMPRuntime->clear();
32659d1ed5bSDimitry Andric }
32759d1ed5bSDimitry Andric 
32859d1ed5bSDimitry Andric void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
32959d1ed5bSDimitry Andric                                        StringRef MainFile) {
33059d1ed5bSDimitry Andric   if (!hasDiagnostics())
33159d1ed5bSDimitry Andric     return;
33259d1ed5bSDimitry Andric   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
33359d1ed5bSDimitry Andric     if (MainFile.empty())
33459d1ed5bSDimitry Andric       MainFile = "<stdin>";
33559d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
33659d1ed5bSDimitry Andric   } else
33759d1ed5bSDimitry Andric     Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
33859d1ed5bSDimitry Andric                                                       << Mismatched;
33959d1ed5bSDimitry Andric }
34059d1ed5bSDimitry Andric 
341f22ef01cSRoman Divacky void CodeGenModule::Release() {
342f22ef01cSRoman Divacky   EmitDeferred();
343f785676fSDimitry Andric   applyReplacements();
344f785676fSDimitry Andric   checkAliases();
345f22ef01cSRoman Divacky   EmitCXXGlobalInitFunc();
346f22ef01cSRoman Divacky   EmitCXXGlobalDtorFunc();
347284c1978SDimitry Andric   EmitCXXThreadLocalInitFunc();
3486122f3e6SDimitry Andric   if (ObjCRuntime)
3496122f3e6SDimitry Andric     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
350f22ef01cSRoman Divacky       AddGlobalCtor(ObjCInitFunction);
35133956c43SDimitry Andric   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
35233956c43SDimitry Andric       CUDARuntime) {
35333956c43SDimitry Andric     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
35433956c43SDimitry Andric       AddGlobalCtor(CudaCtorFunction);
35533956c43SDimitry Andric     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
35633956c43SDimitry Andric       AddGlobalDtor(CudaDtorFunction);
35733956c43SDimitry Andric   }
35859d1ed5bSDimitry Andric   if (PGOReader && PGOStats.hasDiagnostics())
35959d1ed5bSDimitry Andric     PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
360f22ef01cSRoman Divacky   EmitCtorList(GlobalCtors, "llvm.global_ctors");
361f22ef01cSRoman Divacky   EmitCtorList(GlobalDtors, "llvm.global_dtors");
3626122f3e6SDimitry Andric   EmitGlobalAnnotations();
363284c1978SDimitry Andric   EmitStaticExternCAliases();
36439d628a0SDimitry Andric   EmitDeferredUnusedCoverageMappings();
36539d628a0SDimitry Andric   if (CoverageMapping)
36639d628a0SDimitry Andric     CoverageMapping->emit();
36759d1ed5bSDimitry Andric   emitLLVMUsed();
368ffd1746dSEd Schouten 
369f785676fSDimitry Andric   if (CodeGenOpts.Autolink &&
370f785676fSDimitry Andric       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
371139f7f9bSDimitry Andric     EmitModuleLinkOptions();
372139f7f9bSDimitry Andric   }
373f785676fSDimitry Andric   if (CodeGenOpts.DwarfVersion)
374f785676fSDimitry Andric     // We actually want the latest version when there are conflicts.
375f785676fSDimitry Andric     // We can change from Warning to Latest if such mode is supported.
376f785676fSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
377f785676fSDimitry Andric                               CodeGenOpts.DwarfVersion);
378f785676fSDimitry Andric   if (DebugInfo)
37959d1ed5bSDimitry Andric     // We support a single version in the linked module. The LLVM
38059d1ed5bSDimitry Andric     // parser will drop debug info with a different version number
38159d1ed5bSDimitry Andric     // (and warn about it, too).
38259d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
383f785676fSDimitry Andric                               llvm::DEBUG_METADATA_VERSION);
384139f7f9bSDimitry Andric 
38559d1ed5bSDimitry Andric   // We need to record the widths of enums and wchar_t, so that we can generate
38659d1ed5bSDimitry Andric   // the correct build attributes in the ARM backend.
38759d1ed5bSDimitry Andric   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
38859d1ed5bSDimitry Andric   if (   Arch == llvm::Triple::arm
38959d1ed5bSDimitry Andric       || Arch == llvm::Triple::armeb
39059d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumb
39159d1ed5bSDimitry Andric       || Arch == llvm::Triple::thumbeb) {
39259d1ed5bSDimitry Andric     // Width of wchar_t in bytes
39359d1ed5bSDimitry Andric     uint64_t WCharWidth =
39459d1ed5bSDimitry Andric         Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
39559d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
39659d1ed5bSDimitry Andric 
39759d1ed5bSDimitry Andric     // The minimum width of an enum in bytes
39859d1ed5bSDimitry Andric     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
39959d1ed5bSDimitry Andric     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
40059d1ed5bSDimitry Andric   }
40159d1ed5bSDimitry Andric 
40239d628a0SDimitry Andric   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
40339d628a0SDimitry Andric     llvm::PICLevel::Level PL = llvm::PICLevel::Default;
40439d628a0SDimitry Andric     switch (PLevel) {
40539d628a0SDimitry Andric     case 0: break;
40639d628a0SDimitry Andric     case 1: PL = llvm::PICLevel::Small; break;
40739d628a0SDimitry Andric     case 2: PL = llvm::PICLevel::Large; break;
40839d628a0SDimitry Andric     default: llvm_unreachable("Invalid PIC Level");
40939d628a0SDimitry Andric     }
41039d628a0SDimitry Andric 
41139d628a0SDimitry Andric     getModule().setPICLevel(PL);
41239d628a0SDimitry Andric   }
41339d628a0SDimitry Andric 
4142754fe60SDimitry Andric   SimplifyPersonality();
4152754fe60SDimitry Andric 
416ffd1746dSEd Schouten   if (getCodeGenOpts().EmitDeclMetadata)
417ffd1746dSEd Schouten     EmitDeclMetadata();
418bd5abe19SDimitry Andric 
419bd5abe19SDimitry Andric   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
420bd5abe19SDimitry Andric     EmitCoverageFile();
4216122f3e6SDimitry Andric 
4226122f3e6SDimitry Andric   if (DebugInfo)
4236122f3e6SDimitry Andric     DebugInfo->finalize();
424f785676fSDimitry Andric 
425f785676fSDimitry Andric   EmitVersionIdentMetadata();
42659d1ed5bSDimitry Andric 
42759d1ed5bSDimitry Andric   EmitTargetMetadata();
428f22ef01cSRoman Divacky }
429f22ef01cSRoman Divacky 
4303b0f4066SDimitry Andric void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
4313b0f4066SDimitry Andric   // Make sure that this type is translated.
4323b0f4066SDimitry Andric   Types.UpdateCompletedType(TD);
4333b0f4066SDimitry Andric }
4343b0f4066SDimitry Andric 
4352754fe60SDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
4362754fe60SDimitry Andric   if (!TBAA)
43759d1ed5bSDimitry Andric     return nullptr;
4382754fe60SDimitry Andric   return TBAA->getTBAAInfo(QTy);
4392754fe60SDimitry Andric }
4402754fe60SDimitry Andric 
441dff0c46cSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
442dff0c46cSDimitry Andric   if (!TBAA)
44359d1ed5bSDimitry Andric     return nullptr;
444dff0c46cSDimitry Andric   return TBAA->getTBAAInfoForVTablePtr();
445dff0c46cSDimitry Andric }
446dff0c46cSDimitry Andric 
4473861d79fSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
4483861d79fSDimitry Andric   if (!TBAA)
44959d1ed5bSDimitry Andric     return nullptr;
4503861d79fSDimitry Andric   return TBAA->getTBAAStructInfo(QTy);
4513861d79fSDimitry Andric }
4523861d79fSDimitry Andric 
453139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
454139f7f9bSDimitry Andric   if (!TBAA)
45559d1ed5bSDimitry Andric     return nullptr;
456139f7f9bSDimitry Andric   return TBAA->getTBAAStructTypeInfo(QTy);
457139f7f9bSDimitry Andric }
458139f7f9bSDimitry Andric 
459139f7f9bSDimitry Andric llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
460139f7f9bSDimitry Andric                                                   llvm::MDNode *AccessN,
461139f7f9bSDimitry Andric                                                   uint64_t O) {
462139f7f9bSDimitry Andric   if (!TBAA)
46359d1ed5bSDimitry Andric     return nullptr;
464139f7f9bSDimitry Andric   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
465139f7f9bSDimitry Andric }
466139f7f9bSDimitry Andric 
467f785676fSDimitry Andric /// Decorate the instruction with a TBAA tag. For both scalar TBAA
468f785676fSDimitry Andric /// and struct-path aware TBAA, the tag has the same format:
469f785676fSDimitry Andric /// base type, access type and offset.
470284c1978SDimitry Andric /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
4712754fe60SDimitry Andric void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
472284c1978SDimitry Andric                                         llvm::MDNode *TBAAInfo,
473284c1978SDimitry Andric                                         bool ConvertTypeToTag) {
474f785676fSDimitry Andric   if (ConvertTypeToTag && TBAA)
475284c1978SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
476284c1978SDimitry Andric                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
477284c1978SDimitry Andric   else
4782754fe60SDimitry Andric     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
4792754fe60SDimitry Andric }
4802754fe60SDimitry Andric 
48159d1ed5bSDimitry Andric void CodeGenModule::Error(SourceLocation loc, StringRef message) {
48259d1ed5bSDimitry Andric   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
48359d1ed5bSDimitry Andric   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
484f22ef01cSRoman Divacky }
485f22ef01cSRoman Divacky 
486f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
487f22ef01cSRoman Divacky /// specified stmt yet.
488f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
4896122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
490f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
491f22ef01cSRoman Divacky   std::string Msg = Type;
492f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
493f22ef01cSRoman Divacky     << Msg << S->getSourceRange();
494f22ef01cSRoman Divacky }
495f22ef01cSRoman Divacky 
496f22ef01cSRoman Divacky /// ErrorUnsupported - Print out an error that codegen doesn't support the
497f22ef01cSRoman Divacky /// specified decl yet.
498f785676fSDimitry Andric void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
4996122f3e6SDimitry Andric   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
500f22ef01cSRoman Divacky                                                "cannot compile this %0 yet");
501f22ef01cSRoman Divacky   std::string Msg = Type;
502f22ef01cSRoman Divacky   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
503f22ef01cSRoman Divacky }
504f22ef01cSRoman Divacky 
50517a519f9SDimitry Andric llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
50617a519f9SDimitry Andric   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
50717a519f9SDimitry Andric }
50817a519f9SDimitry Andric 
509f22ef01cSRoman Divacky void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
5102754fe60SDimitry Andric                                         const NamedDecl *D) const {
511f22ef01cSRoman Divacky   // Internal definitions always have default visibility.
512f22ef01cSRoman Divacky   if (GV->hasLocalLinkage()) {
513f22ef01cSRoman Divacky     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
514f22ef01cSRoman Divacky     return;
515f22ef01cSRoman Divacky   }
516f22ef01cSRoman Divacky 
5172754fe60SDimitry Andric   // Set visibility for definitions.
518139f7f9bSDimitry Andric   LinkageInfo LV = D->getLinkageAndVisibility();
519139f7f9bSDimitry Andric   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
520139f7f9bSDimitry Andric     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
521f22ef01cSRoman Divacky }
522f22ef01cSRoman Divacky 
5237ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
5247ae0e2c9SDimitry Andric   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
5257ae0e2c9SDimitry Andric       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
5267ae0e2c9SDimitry Andric       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
5277ae0e2c9SDimitry Andric       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
5287ae0e2c9SDimitry Andric       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
5297ae0e2c9SDimitry Andric }
5307ae0e2c9SDimitry Andric 
5317ae0e2c9SDimitry Andric static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
5327ae0e2c9SDimitry Andric     CodeGenOptions::TLSModel M) {
5337ae0e2c9SDimitry Andric   switch (M) {
5347ae0e2c9SDimitry Andric   case CodeGenOptions::GeneralDynamicTLSModel:
5357ae0e2c9SDimitry Andric     return llvm::GlobalVariable::GeneralDynamicTLSModel;
5367ae0e2c9SDimitry Andric   case CodeGenOptions::LocalDynamicTLSModel:
5377ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalDynamicTLSModel;
5387ae0e2c9SDimitry Andric   case CodeGenOptions::InitialExecTLSModel:
5397ae0e2c9SDimitry Andric     return llvm::GlobalVariable::InitialExecTLSModel;
5407ae0e2c9SDimitry Andric   case CodeGenOptions::LocalExecTLSModel:
5417ae0e2c9SDimitry Andric     return llvm::GlobalVariable::LocalExecTLSModel;
5427ae0e2c9SDimitry Andric   }
5437ae0e2c9SDimitry Andric   llvm_unreachable("Invalid TLS model!");
5447ae0e2c9SDimitry Andric }
5457ae0e2c9SDimitry Andric 
54639d628a0SDimitry Andric void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
547284c1978SDimitry Andric   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
5487ae0e2c9SDimitry Andric 
54939d628a0SDimitry Andric   llvm::GlobalValue::ThreadLocalMode TLM;
5503861d79fSDimitry Andric   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
5517ae0e2c9SDimitry Andric 
5527ae0e2c9SDimitry Andric   // Override the TLS model if it is explicitly specified.
55359d1ed5bSDimitry Andric   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
5547ae0e2c9SDimitry Andric     TLM = GetLLVMTLSModel(Attr->getModel());
5557ae0e2c9SDimitry Andric   }
5567ae0e2c9SDimitry Andric 
5577ae0e2c9SDimitry Andric   GV->setThreadLocalMode(TLM);
5587ae0e2c9SDimitry Andric }
5597ae0e2c9SDimitry Andric 
5606122f3e6SDimitry Andric StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
56159d1ed5bSDimitry Andric   StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
56259d1ed5bSDimitry Andric   if (!FoundStr.empty())
56359d1ed5bSDimitry Andric     return FoundStr;
564f22ef01cSRoman Divacky 
56559d1ed5bSDimitry Andric   const auto *ND = cast<NamedDecl>(GD.getDecl());
566dff0c46cSDimitry Andric   SmallString<256> Buffer;
56759d1ed5bSDimitry Andric   StringRef Str;
56859d1ed5bSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
5692754fe60SDimitry Andric     llvm::raw_svector_ostream Out(Buffer);
57059d1ed5bSDimitry Andric     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
5712754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
57259d1ed5bSDimitry Andric     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
5732754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
574ffd1746dSEd Schouten     else
5752754fe60SDimitry Andric       getCXXABI().getMangleContext().mangleName(ND, Out);
57659d1ed5bSDimitry Andric     Str = Out.str();
57759d1ed5bSDimitry Andric   } else {
57859d1ed5bSDimitry Andric     IdentifierInfo *II = ND->getIdentifier();
57959d1ed5bSDimitry Andric     assert(II && "Attempt to mangle unnamed decl.");
58059d1ed5bSDimitry Andric     Str = II->getName();
581ffd1746dSEd Schouten   }
582ffd1746dSEd Schouten 
58339d628a0SDimitry Andric   // Keep the first result in the case of a mangling collision.
58439d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Str, GD));
58539d628a0SDimitry Andric   return FoundStr = Result.first->first();
58659d1ed5bSDimitry Andric }
58759d1ed5bSDimitry Andric 
58859d1ed5bSDimitry Andric StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
589ffd1746dSEd Schouten                                              const BlockDecl *BD) {
5902754fe60SDimitry Andric   MangleContext &MangleCtx = getCXXABI().getMangleContext();
5912754fe60SDimitry Andric   const Decl *D = GD.getDecl();
59259d1ed5bSDimitry Andric 
59359d1ed5bSDimitry Andric   SmallString<256> Buffer;
59459d1ed5bSDimitry Andric   llvm::raw_svector_ostream Out(Buffer);
59559d1ed5bSDimitry Andric   if (!D)
5967ae0e2c9SDimitry Andric     MangleCtx.mangleGlobalBlock(BD,
5977ae0e2c9SDimitry Andric       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
59859d1ed5bSDimitry Andric   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
5992754fe60SDimitry Andric     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
60059d1ed5bSDimitry Andric   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
6012754fe60SDimitry Andric     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
6022754fe60SDimitry Andric   else
6032754fe60SDimitry Andric     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
60459d1ed5bSDimitry Andric 
60539d628a0SDimitry Andric   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
60639d628a0SDimitry Andric   return Result.first->first();
607f22ef01cSRoman Divacky }
608f22ef01cSRoman Divacky 
6096122f3e6SDimitry Andric llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
610f22ef01cSRoman Divacky   return getModule().getNamedValue(Name);
611f22ef01cSRoman Divacky }
612f22ef01cSRoman Divacky 
613f22ef01cSRoman Divacky /// AddGlobalCtor - Add a function to the list that will be called before
614f22ef01cSRoman Divacky /// main() runs.
61559d1ed5bSDimitry Andric void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
61659d1ed5bSDimitry Andric                                   llvm::Constant *AssociatedData) {
617f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
61859d1ed5bSDimitry Andric   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
619f22ef01cSRoman Divacky }
620f22ef01cSRoman Divacky 
621f22ef01cSRoman Divacky /// AddGlobalDtor - Add a function to the list that will be called
622f22ef01cSRoman Divacky /// when the module is unloaded.
623f22ef01cSRoman Divacky void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
624f22ef01cSRoman Divacky   // FIXME: Type coercion of void()* types.
62559d1ed5bSDimitry Andric   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
626f22ef01cSRoman Divacky }
627f22ef01cSRoman Divacky 
628f22ef01cSRoman Divacky void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
629f22ef01cSRoman Divacky   // Ctor function type is void()*.
630bd5abe19SDimitry Andric   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
631f22ef01cSRoman Divacky   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
632f22ef01cSRoman Divacky 
63359d1ed5bSDimitry Andric   // Get the type of a ctor entry, { i32, void ()*, i8* }.
63459d1ed5bSDimitry Andric   llvm::StructType *CtorStructTy = llvm::StructType::get(
63539d628a0SDimitry Andric       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
636f22ef01cSRoman Divacky 
637f22ef01cSRoman Divacky   // Construct the constructor and destructor arrays.
638dff0c46cSDimitry Andric   SmallVector<llvm::Constant *, 8> Ctors;
6398f0fd8f6SDimitry Andric   for (const auto &I : Fns) {
640dff0c46cSDimitry Andric     llvm::Constant *S[] = {
6418f0fd8f6SDimitry Andric         llvm::ConstantInt::get(Int32Ty, I.Priority, false),
6428f0fd8f6SDimitry Andric         llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy),
6438f0fd8f6SDimitry Andric         (I.AssociatedData
6448f0fd8f6SDimitry Andric              ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)
6458f0fd8f6SDimitry Andric              : llvm::Constant::getNullValue(VoidPtrTy))};
646f22ef01cSRoman Divacky     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
647f22ef01cSRoman Divacky   }
648f22ef01cSRoman Divacky 
649f22ef01cSRoman Divacky   if (!Ctors.empty()) {
650f22ef01cSRoman Divacky     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
651f22ef01cSRoman Divacky     new llvm::GlobalVariable(TheModule, AT, false,
652f22ef01cSRoman Divacky                              llvm::GlobalValue::AppendingLinkage,
653f22ef01cSRoman Divacky                              llvm::ConstantArray::get(AT, Ctors),
654f22ef01cSRoman Divacky                              GlobalName);
655f22ef01cSRoman Divacky   }
656f22ef01cSRoman Divacky }
657f22ef01cSRoman Divacky 
658f22ef01cSRoman Divacky llvm::GlobalValue::LinkageTypes
659f785676fSDimitry Andric CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
66059d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
661f785676fSDimitry Andric 
662e580952dSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
663f22ef01cSRoman Divacky 
66459d1ed5bSDimitry Andric   if (isa<CXXDestructorDecl>(D) &&
66559d1ed5bSDimitry Andric       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
66659d1ed5bSDimitry Andric                                          GD.getDtorType())) {
66759d1ed5bSDimitry Andric     // Destructor variants in the Microsoft C++ ABI are always internal or
66859d1ed5bSDimitry Andric     // linkonce_odr thunks emitted on an as-needed basis.
66959d1ed5bSDimitry Andric     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
67059d1ed5bSDimitry Andric                                    : llvm::GlobalValue::LinkOnceODRLinkage;
671f22ef01cSRoman Divacky   }
672f22ef01cSRoman Divacky 
67359d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
67459d1ed5bSDimitry Andric }
675f22ef01cSRoman Divacky 
67697bc6c73SDimitry Andric void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
67797bc6c73SDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
67897bc6c73SDimitry Andric 
67997bc6c73SDimitry Andric   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
68097bc6c73SDimitry Andric     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
68197bc6c73SDimitry Andric       // Don't dllexport/import destructor thunks.
68297bc6c73SDimitry Andric       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
68397bc6c73SDimitry Andric       return;
68497bc6c73SDimitry Andric     }
68597bc6c73SDimitry Andric   }
68697bc6c73SDimitry Andric 
68797bc6c73SDimitry Andric   if (FD->hasAttr<DLLImportAttr>())
68897bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
68997bc6c73SDimitry Andric   else if (FD->hasAttr<DLLExportAttr>())
69097bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
69197bc6c73SDimitry Andric   else
69297bc6c73SDimitry Andric     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
69397bc6c73SDimitry Andric }
69497bc6c73SDimitry Andric 
69559d1ed5bSDimitry Andric void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
69659d1ed5bSDimitry Andric                                                     llvm::Function *F) {
69759d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
698f22ef01cSRoman Divacky }
699f22ef01cSRoman Divacky 
700f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
701f22ef01cSRoman Divacky                                               const CGFunctionInfo &Info,
702f22ef01cSRoman Divacky                                               llvm::Function *F) {
703f22ef01cSRoman Divacky   unsigned CallingConv;
704f22ef01cSRoman Divacky   AttributeListType AttributeList;
705139f7f9bSDimitry Andric   ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
706139f7f9bSDimitry Andric   F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
707f22ef01cSRoman Divacky   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
708f22ef01cSRoman Divacky }
709f22ef01cSRoman Divacky 
7106122f3e6SDimitry Andric /// Determines whether the language options require us to model
7116122f3e6SDimitry Andric /// unwind exceptions.  We treat -fexceptions as mandating this
7126122f3e6SDimitry Andric /// except under the fragile ObjC ABI with only ObjC exceptions
7136122f3e6SDimitry Andric /// enabled.  This means, for example, that C with -fexceptions
7146122f3e6SDimitry Andric /// enables this.
715dff0c46cSDimitry Andric static bool hasUnwindExceptions(const LangOptions &LangOpts) {
7166122f3e6SDimitry Andric   // If exceptions are completely disabled, obviously this is false.
717dff0c46cSDimitry Andric   if (!LangOpts.Exceptions) return false;
7186122f3e6SDimitry Andric 
7196122f3e6SDimitry Andric   // If C++ exceptions are enabled, this is true.
720dff0c46cSDimitry Andric   if (LangOpts.CXXExceptions) return true;
7216122f3e6SDimitry Andric 
7226122f3e6SDimitry Andric   // If ObjC exceptions are enabled, this depends on the ABI.
723dff0c46cSDimitry Andric   if (LangOpts.ObjCExceptions) {
7247ae0e2c9SDimitry Andric     return LangOpts.ObjCRuntime.hasUnwindExceptions();
7256122f3e6SDimitry Andric   }
7266122f3e6SDimitry Andric 
7276122f3e6SDimitry Andric   return true;
7286122f3e6SDimitry Andric }
7296122f3e6SDimitry Andric 
730f22ef01cSRoman Divacky void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
731f22ef01cSRoman Divacky                                                            llvm::Function *F) {
732f785676fSDimitry Andric   llvm::AttrBuilder B;
733f785676fSDimitry Andric 
734bd5abe19SDimitry Andric   if (CodeGenOpts.UnwindTables)
735f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::UWTable);
736bd5abe19SDimitry Andric 
737dff0c46cSDimitry Andric   if (!hasUnwindExceptions(LangOpts))
738f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoUnwind);
739f22ef01cSRoman Divacky 
7406122f3e6SDimitry Andric   if (D->hasAttr<NakedAttr>()) {
7416122f3e6SDimitry Andric     // Naked implies noinline: we should not be inlining such functions.
742f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Naked);
743f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
74459d1ed5bSDimitry Andric   } else if (D->hasAttr<NoDuplicateAttr>()) {
74559d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::NoDuplicate);
746f785676fSDimitry Andric   } else if (D->hasAttr<NoInlineAttr>()) {
747f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::NoInline);
74859d1ed5bSDimitry Andric   } else if (D->hasAttr<AlwaysInlineAttr>() &&
749f785676fSDimitry Andric              !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
750f785676fSDimitry Andric                                               llvm::Attribute::NoInline)) {
751f785676fSDimitry Andric     // (noinline wins over always_inline, and we can't specify both in IR)
752f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::AlwaysInline);
7536122f3e6SDimitry Andric   }
7542754fe60SDimitry Andric 
755f785676fSDimitry Andric   if (D->hasAttr<ColdAttr>()) {
75639d628a0SDimitry Andric     if (!D->hasAttr<OptimizeNoneAttr>())
757f785676fSDimitry Andric       B.addAttribute(llvm::Attribute::OptimizeForSize);
758f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::Cold);
759f785676fSDimitry Andric   }
7603861d79fSDimitry Andric 
7613861d79fSDimitry Andric   if (D->hasAttr<MinSizeAttr>())
762f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::MinSize);
763f22ef01cSRoman Divacky 
7643861d79fSDimitry Andric   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
765f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::StackProtect);
76659d1ed5bSDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
76759d1ed5bSDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectStrong);
7683861d79fSDimitry Andric   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
769f785676fSDimitry Andric     B.addAttribute(llvm::Attribute::StackProtectReq);
7703861d79fSDimitry Andric 
771f785676fSDimitry Andric   F->addAttributes(llvm::AttributeSet::FunctionIndex,
772f785676fSDimitry Andric                    llvm::AttributeSet::get(
773f785676fSDimitry Andric                        F->getContext(), llvm::AttributeSet::FunctionIndex, B));
774f785676fSDimitry Andric 
77539d628a0SDimitry Andric   if (D->hasAttr<OptimizeNoneAttr>()) {
77639d628a0SDimitry Andric     // OptimizeNone implies noinline; we should not be inlining such functions.
77739d628a0SDimitry Andric     F->addFnAttr(llvm::Attribute::OptimizeNone);
77839d628a0SDimitry Andric     F->addFnAttr(llvm::Attribute::NoInline);
77939d628a0SDimitry Andric 
78039d628a0SDimitry Andric     // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
78139d628a0SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) &&
78239d628a0SDimitry Andric            "OptimizeNone and OptimizeForSize on same function!");
78339d628a0SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::MinSize) &&
78439d628a0SDimitry Andric            "OptimizeNone and MinSize on same function!");
78539d628a0SDimitry Andric     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
78639d628a0SDimitry Andric            "OptimizeNone and AlwaysInline on same function!");
78739d628a0SDimitry Andric 
78839d628a0SDimitry Andric     // Attribute 'inlinehint' has no effect on 'optnone' functions.
78939d628a0SDimitry Andric     // Explicitly remove it from the set of function attributes.
79039d628a0SDimitry Andric     F->removeFnAttr(llvm::Attribute::InlineHint);
79139d628a0SDimitry Andric   }
79239d628a0SDimitry Andric 
793f785676fSDimitry Andric   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
794f785676fSDimitry Andric     F->setUnnamedAddr(true);
79559d1ed5bSDimitry Andric   else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
796f785676fSDimitry Andric     if (MD->isVirtual())
797f785676fSDimitry Andric       F->setUnnamedAddr(true);
798f785676fSDimitry Andric 
799e580952dSDimitry Andric   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
800e580952dSDimitry Andric   if (alignment)
801e580952dSDimitry Andric     F->setAlignment(alignment);
802e580952dSDimitry Andric 
803f22ef01cSRoman Divacky   // C++ ABI requires 2-byte alignment for member functions.
804f22ef01cSRoman Divacky   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
805f22ef01cSRoman Divacky     F->setAlignment(2);
806f22ef01cSRoman Divacky }
807f22ef01cSRoman Divacky 
808f22ef01cSRoman Divacky void CodeGenModule::SetCommonAttributes(const Decl *D,
809f22ef01cSRoman Divacky                                         llvm::GlobalValue *GV) {
81059d1ed5bSDimitry Andric   if (const auto *ND = dyn_cast<NamedDecl>(D))
8112754fe60SDimitry Andric     setGlobalVisibility(GV, ND);
8122754fe60SDimitry Andric   else
8132754fe60SDimitry Andric     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
814f22ef01cSRoman Divacky 
815f22ef01cSRoman Divacky   if (D->hasAttr<UsedAttr>())
81659d1ed5bSDimitry Andric     addUsedGlobal(GV);
81759d1ed5bSDimitry Andric }
81859d1ed5bSDimitry Andric 
81939d628a0SDimitry Andric void CodeGenModule::setAliasAttributes(const Decl *D,
82039d628a0SDimitry Andric                                        llvm::GlobalValue *GV) {
82139d628a0SDimitry Andric   SetCommonAttributes(D, GV);
82239d628a0SDimitry Andric 
82339d628a0SDimitry Andric   // Process the dllexport attribute based on whether the original definition
82439d628a0SDimitry Andric   // (not necessarily the aliasee) was exported.
82539d628a0SDimitry Andric   if (D->hasAttr<DLLExportAttr>())
82639d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
82739d628a0SDimitry Andric }
82839d628a0SDimitry Andric 
82959d1ed5bSDimitry Andric void CodeGenModule::setNonAliasAttributes(const Decl *D,
83059d1ed5bSDimitry Andric                                           llvm::GlobalObject *GO) {
83159d1ed5bSDimitry Andric   SetCommonAttributes(D, GO);
832f22ef01cSRoman Divacky 
833f22ef01cSRoman Divacky   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
83459d1ed5bSDimitry Andric     GO->setSection(SA->getName());
835f22ef01cSRoman Divacky 
83697bc6c73SDimitry Andric   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
837f22ef01cSRoman Divacky }
838f22ef01cSRoman Divacky 
839f22ef01cSRoman Divacky void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
840f22ef01cSRoman Divacky                                                   llvm::Function *F,
841f22ef01cSRoman Divacky                                                   const CGFunctionInfo &FI) {
842f22ef01cSRoman Divacky   SetLLVMFunctionAttributes(D, FI, F);
843f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, F);
844f22ef01cSRoman Divacky 
845f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::InternalLinkage);
846f22ef01cSRoman Divacky 
84759d1ed5bSDimitry Andric   setNonAliasAttributes(D, F);
84859d1ed5bSDimitry Andric }
84959d1ed5bSDimitry Andric 
85059d1ed5bSDimitry Andric static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
85159d1ed5bSDimitry Andric                                          const NamedDecl *ND) {
85259d1ed5bSDimitry Andric   // Set linkage and visibility in case we never see a definition.
85359d1ed5bSDimitry Andric   LinkageInfo LV = ND->getLinkageAndVisibility();
85459d1ed5bSDimitry Andric   if (LV.getLinkage() != ExternalLinkage) {
85559d1ed5bSDimitry Andric     // Don't set internal linkage on declarations.
85659d1ed5bSDimitry Andric   } else {
85759d1ed5bSDimitry Andric     if (ND->hasAttr<DLLImportAttr>()) {
85859d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
85959d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
86059d1ed5bSDimitry Andric     } else if (ND->hasAttr<DLLExportAttr>()) {
86159d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
86259d1ed5bSDimitry Andric       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
86359d1ed5bSDimitry Andric     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
86459d1ed5bSDimitry Andric       // "extern_weak" is overloaded in LLVM; we probably should have
86559d1ed5bSDimitry Andric       // separate linkage types for this.
86659d1ed5bSDimitry Andric       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
86759d1ed5bSDimitry Andric     }
86859d1ed5bSDimitry Andric 
86959d1ed5bSDimitry Andric     // Set visibility on a declaration only if it's explicit.
87059d1ed5bSDimitry Andric     if (LV.isVisibilityExplicit())
87159d1ed5bSDimitry Andric       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
87259d1ed5bSDimitry Andric   }
873f22ef01cSRoman Divacky }
874f22ef01cSRoman Divacky 
87539d628a0SDimitry Andric void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
87639d628a0SDimitry Andric                                           bool IsIncompleteFunction,
87739d628a0SDimitry Andric                                           bool IsThunk) {
87833956c43SDimitry Andric   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
8793b0f4066SDimitry Andric     // If this is an intrinsic function, set the function's attributes
8803b0f4066SDimitry Andric     // to the intrinsic's attributes.
88133956c43SDimitry Andric     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
8823b0f4066SDimitry Andric     return;
8833b0f4066SDimitry Andric   }
8843b0f4066SDimitry Andric 
88559d1ed5bSDimitry Andric   const auto *FD = cast<FunctionDecl>(GD.getDecl());
886f22ef01cSRoman Divacky 
887f22ef01cSRoman Divacky   if (!IsIncompleteFunction)
888dff0c46cSDimitry Andric     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
889f22ef01cSRoman Divacky 
89059d1ed5bSDimitry Andric   // Add the Returned attribute for "this", except for iOS 5 and earlier
89159d1ed5bSDimitry Andric   // where substantial code, including the libstdc++ dylib, was compiled with
89259d1ed5bSDimitry Andric   // GCC and does not actually return "this".
89339d628a0SDimitry Andric   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
89459d1ed5bSDimitry Andric       !(getTarget().getTriple().isiOS() &&
89559d1ed5bSDimitry Andric         getTarget().getTriple().isOSVersionLT(6))) {
896f785676fSDimitry Andric     assert(!F->arg_empty() &&
897f785676fSDimitry Andric            F->arg_begin()->getType()
898f785676fSDimitry Andric              ->canLosslesslyBitCastTo(F->getReturnType()) &&
899f785676fSDimitry Andric            "unexpected this return");
900f785676fSDimitry Andric     F->addAttribute(1, llvm::Attribute::Returned);
901f785676fSDimitry Andric   }
902f785676fSDimitry Andric 
903f22ef01cSRoman Divacky   // Only a few attributes are set on declarations; these may later be
904f22ef01cSRoman Divacky   // overridden by a definition.
905f22ef01cSRoman Divacky 
90659d1ed5bSDimitry Andric   setLinkageAndVisibilityForGV(F, FD);
9072754fe60SDimitry Andric 
908f22ef01cSRoman Divacky   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
909f22ef01cSRoman Divacky     F->setSection(SA->getName());
910f785676fSDimitry Andric 
911f785676fSDimitry Andric   // A replaceable global allocation function does not act like a builtin by
912f785676fSDimitry Andric   // default, only if it is invoked by a new-expression or delete-expression.
913f785676fSDimitry Andric   if (FD->isReplaceableGlobalAllocationFunction())
914f785676fSDimitry Andric     F->addAttribute(llvm::AttributeSet::FunctionIndex,
915f785676fSDimitry Andric                     llvm::Attribute::NoBuiltin);
916f22ef01cSRoman Divacky }
917f22ef01cSRoman Divacky 
91859d1ed5bSDimitry Andric void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
919f22ef01cSRoman Divacky   assert(!GV->isDeclaration() &&
920f22ef01cSRoman Divacky          "Only globals with definition can force usage.");
92197bc6c73SDimitry Andric   LLVMUsed.emplace_back(GV);
922f22ef01cSRoman Divacky }
923f22ef01cSRoman Divacky 
92459d1ed5bSDimitry Andric void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
92559d1ed5bSDimitry Andric   assert(!GV->isDeclaration() &&
92659d1ed5bSDimitry Andric          "Only globals with definition can force usage.");
92797bc6c73SDimitry Andric   LLVMCompilerUsed.emplace_back(GV);
92859d1ed5bSDimitry Andric }
92959d1ed5bSDimitry Andric 
93059d1ed5bSDimitry Andric static void emitUsed(CodeGenModule &CGM, StringRef Name,
93159d1ed5bSDimitry Andric                      std::vector<llvm::WeakVH> &List) {
932f22ef01cSRoman Divacky   // Don't create llvm.used if there is no need.
93359d1ed5bSDimitry Andric   if (List.empty())
934f22ef01cSRoman Divacky     return;
935f22ef01cSRoman Divacky 
93659d1ed5bSDimitry Andric   // Convert List to what ConstantArray needs.
937dff0c46cSDimitry Andric   SmallVector<llvm::Constant*, 8> UsedArray;
93859d1ed5bSDimitry Andric   UsedArray.resize(List.size());
93959d1ed5bSDimitry Andric   for (unsigned i = 0, e = List.size(); i != e; ++i) {
940f22ef01cSRoman Divacky     UsedArray[i] =
94144f7b0dcSDimitry Andric         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
94244f7b0dcSDimitry Andric             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
943f22ef01cSRoman Divacky   }
944f22ef01cSRoman Divacky 
945f22ef01cSRoman Divacky   if (UsedArray.empty())
946f22ef01cSRoman Divacky     return;
94759d1ed5bSDimitry Andric   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
948f22ef01cSRoman Divacky 
94959d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
95059d1ed5bSDimitry Andric       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
95159d1ed5bSDimitry Andric       llvm::ConstantArray::get(ATy, UsedArray), Name);
952f22ef01cSRoman Divacky 
953f22ef01cSRoman Divacky   GV->setSection("llvm.metadata");
954f22ef01cSRoman Divacky }
955f22ef01cSRoman Divacky 
95659d1ed5bSDimitry Andric void CodeGenModule::emitLLVMUsed() {
95759d1ed5bSDimitry Andric   emitUsed(*this, "llvm.used", LLVMUsed);
95859d1ed5bSDimitry Andric   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
95959d1ed5bSDimitry Andric }
96059d1ed5bSDimitry Andric 
961f785676fSDimitry Andric void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
96239d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
963f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
964f785676fSDimitry Andric }
965f785676fSDimitry Andric 
966f785676fSDimitry Andric void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
967f785676fSDimitry Andric   llvm::SmallString<32> Opt;
968f785676fSDimitry Andric   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
96939d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
970f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
971f785676fSDimitry Andric }
972f785676fSDimitry Andric 
973f785676fSDimitry Andric void CodeGenModule::AddDependentLib(StringRef Lib) {
974f785676fSDimitry Andric   llvm::SmallString<24> Opt;
975f785676fSDimitry Andric   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
97639d628a0SDimitry Andric   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
977f785676fSDimitry Andric   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
978f785676fSDimitry Andric }
979f785676fSDimitry Andric 
980139f7f9bSDimitry Andric /// \brief Add link options implied by the given module, including modules
981139f7f9bSDimitry Andric /// it depends on, using a postorder walk.
98239d628a0SDimitry Andric static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
98339d628a0SDimitry Andric                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
984139f7f9bSDimitry Andric                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
985139f7f9bSDimitry Andric   // Import this module's parent.
98639d628a0SDimitry Andric   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
987f785676fSDimitry Andric     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
988139f7f9bSDimitry Andric   }
989139f7f9bSDimitry Andric 
990139f7f9bSDimitry Andric   // Import this module's dependencies.
991139f7f9bSDimitry Andric   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
99239d628a0SDimitry Andric     if (Visited.insert(Mod->Imports[I - 1]).second)
993f785676fSDimitry Andric       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
994139f7f9bSDimitry Andric   }
995139f7f9bSDimitry Andric 
996139f7f9bSDimitry Andric   // Add linker options to link against the libraries/frameworks
997139f7f9bSDimitry Andric   // described by this module.
998f785676fSDimitry Andric   llvm::LLVMContext &Context = CGM.getLLVMContext();
999139f7f9bSDimitry Andric   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
1000f785676fSDimitry Andric     // Link against a framework.  Frameworks are currently Darwin only, so we
1001f785676fSDimitry Andric     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
1002139f7f9bSDimitry Andric     if (Mod->LinkLibraries[I-1].IsFramework) {
100339d628a0SDimitry Andric       llvm::Metadata *Args[2] = {
1004139f7f9bSDimitry Andric           llvm::MDString::get(Context, "-framework"),
100539d628a0SDimitry Andric           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1006139f7f9bSDimitry Andric 
1007139f7f9bSDimitry Andric       Metadata.push_back(llvm::MDNode::get(Context, Args));
1008139f7f9bSDimitry Andric       continue;
1009139f7f9bSDimitry Andric     }
1010139f7f9bSDimitry Andric 
1011139f7f9bSDimitry Andric     // Link against a library.
1012f785676fSDimitry Andric     llvm::SmallString<24> Opt;
1013f785676fSDimitry Andric     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1014f785676fSDimitry Andric       Mod->LinkLibraries[I-1].Library, Opt);
101539d628a0SDimitry Andric     auto *OptString = llvm::MDString::get(Context, Opt);
1016139f7f9bSDimitry Andric     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1017139f7f9bSDimitry Andric   }
1018139f7f9bSDimitry Andric }
1019139f7f9bSDimitry Andric 
1020139f7f9bSDimitry Andric void CodeGenModule::EmitModuleLinkOptions() {
1021139f7f9bSDimitry Andric   // Collect the set of all of the modules we want to visit to emit link
1022139f7f9bSDimitry Andric   // options, which is essentially the imported modules and all of their
1023139f7f9bSDimitry Andric   // non-explicit child modules.
1024139f7f9bSDimitry Andric   llvm::SetVector<clang::Module *> LinkModules;
1025139f7f9bSDimitry Andric   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1026139f7f9bSDimitry Andric   SmallVector<clang::Module *, 16> Stack;
1027139f7f9bSDimitry Andric 
1028139f7f9bSDimitry Andric   // Seed the stack with imported modules.
10298f0fd8f6SDimitry Andric   for (Module *M : ImportedModules)
10308f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
10318f0fd8f6SDimitry Andric       Stack.push_back(M);
1032139f7f9bSDimitry Andric 
1033139f7f9bSDimitry Andric   // Find all of the modules to import, making a little effort to prune
1034139f7f9bSDimitry Andric   // non-leaf modules.
1035139f7f9bSDimitry Andric   while (!Stack.empty()) {
1036f785676fSDimitry Andric     clang::Module *Mod = Stack.pop_back_val();
1037139f7f9bSDimitry Andric 
1038139f7f9bSDimitry Andric     bool AnyChildren = false;
1039139f7f9bSDimitry Andric 
1040139f7f9bSDimitry Andric     // Visit the submodules of this module.
1041139f7f9bSDimitry Andric     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1042139f7f9bSDimitry Andric                                         SubEnd = Mod->submodule_end();
1043139f7f9bSDimitry Andric          Sub != SubEnd; ++Sub) {
1044139f7f9bSDimitry Andric       // Skip explicit children; they need to be explicitly imported to be
1045139f7f9bSDimitry Andric       // linked against.
1046139f7f9bSDimitry Andric       if ((*Sub)->IsExplicit)
1047139f7f9bSDimitry Andric         continue;
1048139f7f9bSDimitry Andric 
104939d628a0SDimitry Andric       if (Visited.insert(*Sub).second) {
1050139f7f9bSDimitry Andric         Stack.push_back(*Sub);
1051139f7f9bSDimitry Andric         AnyChildren = true;
1052139f7f9bSDimitry Andric       }
1053139f7f9bSDimitry Andric     }
1054139f7f9bSDimitry Andric 
1055139f7f9bSDimitry Andric     // We didn't find any children, so add this module to the list of
1056139f7f9bSDimitry Andric     // modules to link against.
1057139f7f9bSDimitry Andric     if (!AnyChildren) {
1058139f7f9bSDimitry Andric       LinkModules.insert(Mod);
1059139f7f9bSDimitry Andric     }
1060139f7f9bSDimitry Andric   }
1061139f7f9bSDimitry Andric 
1062139f7f9bSDimitry Andric   // Add link options for all of the imported modules in reverse topological
1063f785676fSDimitry Andric   // order.  We don't do anything to try to order import link flags with respect
1064f785676fSDimitry Andric   // to linker options inserted by things like #pragma comment().
106539d628a0SDimitry Andric   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1066139f7f9bSDimitry Andric   Visited.clear();
10678f0fd8f6SDimitry Andric   for (Module *M : LinkModules)
10688f0fd8f6SDimitry Andric     if (Visited.insert(M).second)
10698f0fd8f6SDimitry Andric       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1070139f7f9bSDimitry Andric   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1071f785676fSDimitry Andric   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1072139f7f9bSDimitry Andric 
1073139f7f9bSDimitry Andric   // Add the linker options metadata flag.
1074139f7f9bSDimitry Andric   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1075f785676fSDimitry Andric                             llvm::MDNode::get(getLLVMContext(),
1076f785676fSDimitry Andric                                               LinkerOptionsMetadata));
1077139f7f9bSDimitry Andric }
1078139f7f9bSDimitry Andric 
1079f22ef01cSRoman Divacky void CodeGenModule::EmitDeferred() {
1080f22ef01cSRoman Divacky   // Emit code for any potentially referenced deferred decls.  Since a
1081f22ef01cSRoman Divacky   // previously unused static decl may become used during the generation of code
1082f22ef01cSRoman Divacky   // for a static function, iterate until no changes are made.
1083f22ef01cSRoman Divacky 
1084f22ef01cSRoman Divacky   if (!DeferredVTables.empty()) {
1085139f7f9bSDimitry Andric     EmitDeferredVTables();
1086139f7f9bSDimitry Andric 
1087139f7f9bSDimitry Andric     // Emitting a v-table doesn't directly cause more v-tables to
1088139f7f9bSDimitry Andric     // become deferred, although it can cause functions to be
1089139f7f9bSDimitry Andric     // emitted that then need those v-tables.
1090139f7f9bSDimitry Andric     assert(DeferredVTables.empty());
1091f22ef01cSRoman Divacky   }
1092f22ef01cSRoman Divacky 
1093139f7f9bSDimitry Andric   // Stop if we're out of both deferred v-tables and deferred declarations.
109433956c43SDimitry Andric   if (DeferredDeclsToEmit.empty())
109533956c43SDimitry Andric     return;
1096139f7f9bSDimitry Andric 
109733956c43SDimitry Andric   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
109833956c43SDimitry Andric   // work, it will not interfere with this.
109933956c43SDimitry Andric   std::vector<DeferredGlobal> CurDeclsToEmit;
110033956c43SDimitry Andric   CurDeclsToEmit.swap(DeferredDeclsToEmit);
110133956c43SDimitry Andric 
110233956c43SDimitry Andric   for (DeferredGlobal &G : CurDeclsToEmit) {
110359d1ed5bSDimitry Andric     GlobalDecl D = G.GD;
110459d1ed5bSDimitry Andric     llvm::GlobalValue *GV = G.GV;
110533956c43SDimitry Andric     G.GV = nullptr;
1106f22ef01cSRoman Divacky 
110739d628a0SDimitry Andric     assert(!GV || GV == GetGlobalValue(getMangledName(D)));
110839d628a0SDimitry Andric     if (!GV)
110939d628a0SDimitry Andric       GV = GetGlobalValue(getMangledName(D));
111039d628a0SDimitry Andric 
1111f22ef01cSRoman Divacky     // Check to see if we've already emitted this.  This is necessary
1112f22ef01cSRoman Divacky     // for a couple of reasons: first, decls can end up in the
1113f22ef01cSRoman Divacky     // deferred-decls queue multiple times, and second, decls can end
1114f22ef01cSRoman Divacky     // up with definitions in unusual ways (e.g. by an extern inline
1115f22ef01cSRoman Divacky     // function acquiring a strong function redefinition).  Just
1116f22ef01cSRoman Divacky     // ignore these cases.
111739d628a0SDimitry Andric     if (GV && !GV->isDeclaration())
1118f22ef01cSRoman Divacky       continue;
1119f22ef01cSRoman Divacky 
1120f22ef01cSRoman Divacky     // Otherwise, emit the definition and move on to the next one.
112159d1ed5bSDimitry Andric     EmitGlobalDefinition(D, GV);
112233956c43SDimitry Andric 
112333956c43SDimitry Andric     // If we found out that we need to emit more decls, do that recursively.
112433956c43SDimitry Andric     // This has the advantage that the decls are emitted in a DFS and related
112533956c43SDimitry Andric     // ones are close together, which is convenient for testing.
112633956c43SDimitry Andric     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
112733956c43SDimitry Andric       EmitDeferred();
112833956c43SDimitry Andric       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
112933956c43SDimitry Andric     }
1130f22ef01cSRoman Divacky   }
1131f22ef01cSRoman Divacky }
1132f22ef01cSRoman Divacky 
11336122f3e6SDimitry Andric void CodeGenModule::EmitGlobalAnnotations() {
11346122f3e6SDimitry Andric   if (Annotations.empty())
11356122f3e6SDimitry Andric     return;
11366122f3e6SDimitry Andric 
11376122f3e6SDimitry Andric   // Create a new global variable for the ConstantStruct in the Module.
11386122f3e6SDimitry Andric   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
11396122f3e6SDimitry Andric     Annotations[0]->getType(), Annotations.size()), Annotations);
114059d1ed5bSDimitry Andric   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
114159d1ed5bSDimitry Andric                                       llvm::GlobalValue::AppendingLinkage,
114259d1ed5bSDimitry Andric                                       Array, "llvm.global.annotations");
11436122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
11446122f3e6SDimitry Andric }
11456122f3e6SDimitry Andric 
1146139f7f9bSDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1147f785676fSDimitry Andric   llvm::Constant *&AStr = AnnotationStrings[Str];
1148f785676fSDimitry Andric   if (AStr)
1149f785676fSDimitry Andric     return AStr;
11506122f3e6SDimitry Andric 
11516122f3e6SDimitry Andric   // Not found yet, create a new global.
1152dff0c46cSDimitry Andric   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
115359d1ed5bSDimitry Andric   auto *gv =
115459d1ed5bSDimitry Andric       new llvm::GlobalVariable(getModule(), s->getType(), true,
115559d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, s, ".str");
11566122f3e6SDimitry Andric   gv->setSection(AnnotationSection);
11576122f3e6SDimitry Andric   gv->setUnnamedAddr(true);
1158f785676fSDimitry Andric   AStr = gv;
11596122f3e6SDimitry Andric   return gv;
11606122f3e6SDimitry Andric }
11616122f3e6SDimitry Andric 
11626122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
11636122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
11646122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
11656122f3e6SDimitry Andric   if (PLoc.isValid())
11666122f3e6SDimitry Andric     return EmitAnnotationString(PLoc.getFilename());
11676122f3e6SDimitry Andric   return EmitAnnotationString(SM.getBufferName(Loc));
11686122f3e6SDimitry Andric }
11696122f3e6SDimitry Andric 
11706122f3e6SDimitry Andric llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
11716122f3e6SDimitry Andric   SourceManager &SM = getContext().getSourceManager();
11726122f3e6SDimitry Andric   PresumedLoc PLoc = SM.getPresumedLoc(L);
11736122f3e6SDimitry Andric   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
11746122f3e6SDimitry Andric     SM.getExpansionLineNumber(L);
11756122f3e6SDimitry Andric   return llvm::ConstantInt::get(Int32Ty, LineNo);
11766122f3e6SDimitry Andric }
11776122f3e6SDimitry Andric 
1178f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1179f22ef01cSRoman Divacky                                                 const AnnotateAttr *AA,
11806122f3e6SDimitry Andric                                                 SourceLocation L) {
11816122f3e6SDimitry Andric   // Get the globals for file name, annotation, and the line number.
11826122f3e6SDimitry Andric   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
11836122f3e6SDimitry Andric                  *UnitGV = EmitAnnotationUnit(L),
11846122f3e6SDimitry Andric                  *LineNoCst = EmitAnnotationLineNo(L);
1185f22ef01cSRoman Divacky 
1186f22ef01cSRoman Divacky   // Create the ConstantStruct for the global annotation.
1187f22ef01cSRoman Divacky   llvm::Constant *Fields[4] = {
11886122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
11896122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
11906122f3e6SDimitry Andric     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
11916122f3e6SDimitry Andric     LineNoCst
1192f22ef01cSRoman Divacky   };
119317a519f9SDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
1194f22ef01cSRoman Divacky }
1195f22ef01cSRoman Divacky 
11966122f3e6SDimitry Andric void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
11976122f3e6SDimitry Andric                                          llvm::GlobalValue *GV) {
11986122f3e6SDimitry Andric   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
11996122f3e6SDimitry Andric   // Get the struct elements for these annotations.
120059d1ed5bSDimitry Andric   for (const auto *I : D->specific_attrs<AnnotateAttr>())
120159d1ed5bSDimitry Andric     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
12026122f3e6SDimitry Andric }
12036122f3e6SDimitry Andric 
120439d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
120539d628a0SDimitry Andric                                            SourceLocation Loc) const {
120639d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
120739d628a0SDimitry Andric   // Blacklist by function name.
120839d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
120939d628a0SDimitry Andric     return true;
121039d628a0SDimitry Andric   // Blacklist by location.
121139d628a0SDimitry Andric   if (!Loc.isInvalid())
121239d628a0SDimitry Andric     return SanitizerBL.isBlacklistedLocation(Loc);
121339d628a0SDimitry Andric   // If location is unknown, this may be a compiler-generated function. Assume
121439d628a0SDimitry Andric   // it's located in the main file.
121539d628a0SDimitry Andric   auto &SM = Context.getSourceManager();
121639d628a0SDimitry Andric   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
121739d628a0SDimitry Andric     return SanitizerBL.isBlacklistedFile(MainFile->getName());
121839d628a0SDimitry Andric   }
121939d628a0SDimitry Andric   return false;
122039d628a0SDimitry Andric }
122139d628a0SDimitry Andric 
122239d628a0SDimitry Andric bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
122339d628a0SDimitry Andric                                            SourceLocation Loc, QualType Ty,
122439d628a0SDimitry Andric                                            StringRef Category) const {
12258f0fd8f6SDimitry Andric   // For now globals can be blacklisted only in ASan and KASan.
12268f0fd8f6SDimitry Andric   if (!LangOpts.Sanitize.hasOneOf(
12278f0fd8f6SDimitry Andric           SanitizerKind::Address | SanitizerKind::KernelAddress))
122839d628a0SDimitry Andric     return false;
122939d628a0SDimitry Andric   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
123039d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
123139d628a0SDimitry Andric     return true;
123239d628a0SDimitry Andric   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
123339d628a0SDimitry Andric     return true;
123439d628a0SDimitry Andric   // Check global type.
123539d628a0SDimitry Andric   if (!Ty.isNull()) {
123639d628a0SDimitry Andric     // Drill down the array types: if global variable of a fixed type is
123739d628a0SDimitry Andric     // blacklisted, we also don't instrument arrays of them.
123839d628a0SDimitry Andric     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
123939d628a0SDimitry Andric       Ty = AT->getElementType();
124039d628a0SDimitry Andric     Ty = Ty.getCanonicalType().getUnqualifiedType();
124139d628a0SDimitry Andric     // We allow to blacklist only record types (classes, structs etc.)
124239d628a0SDimitry Andric     if (Ty->isRecordType()) {
124339d628a0SDimitry Andric       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
124439d628a0SDimitry Andric       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
124539d628a0SDimitry Andric         return true;
124639d628a0SDimitry Andric     }
124739d628a0SDimitry Andric   }
124839d628a0SDimitry Andric   return false;
124939d628a0SDimitry Andric }
125039d628a0SDimitry Andric 
125139d628a0SDimitry Andric bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1252e580952dSDimitry Andric   // Never defer when EmitAllDecls is specified.
1253dff0c46cSDimitry Andric   if (LangOpts.EmitAllDecls)
125439d628a0SDimitry Andric     return true;
125539d628a0SDimitry Andric 
125639d628a0SDimitry Andric   return getContext().DeclMustBeEmitted(Global);
125739d628a0SDimitry Andric }
125839d628a0SDimitry Andric 
125939d628a0SDimitry Andric bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
126039d628a0SDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
126139d628a0SDimitry Andric     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
126239d628a0SDimitry Andric       // Implicit template instantiations may change linkage if they are later
126339d628a0SDimitry Andric       // explicitly instantiated, so they should not be emitted eagerly.
1264f22ef01cSRoman Divacky       return false;
1265875ed548SDimitry Andric   // If OpenMP is enabled and threadprivates must be generated like TLS, delay
1266875ed548SDimitry Andric   // codegen for global variables, because they may be marked as threadprivate.
1267875ed548SDimitry Andric   if (LangOpts.OpenMP && LangOpts.OpenMPUseTLS &&
1268875ed548SDimitry Andric       getContext().getTargetInfo().isTLSSupported() && isa<VarDecl>(Global))
1269875ed548SDimitry Andric     return false;
1270f22ef01cSRoman Divacky 
127139d628a0SDimitry Andric   return true;
1272f22ef01cSRoman Divacky }
1273f22ef01cSRoman Divacky 
12743861d79fSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
12753861d79fSDimitry Andric     const CXXUuidofExpr* E) {
12763861d79fSDimitry Andric   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
12773861d79fSDimitry Andric   // well-formed.
1278f785676fSDimitry Andric   StringRef Uuid = E->getUuidAsStringRef(Context);
1279f785676fSDimitry Andric   std::string Name = "_GUID_" + Uuid.lower();
1280f785676fSDimitry Andric   std::replace(Name.begin(), Name.end(), '-', '_');
12813861d79fSDimitry Andric 
12823861d79fSDimitry Andric   // Look for an existing global.
12833861d79fSDimitry Andric   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
12843861d79fSDimitry Andric     return GV;
12853861d79fSDimitry Andric 
128639d628a0SDimitry Andric   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
12873861d79fSDimitry Andric   assert(Init && "failed to initialize as constant");
12883861d79fSDimitry Andric 
128959d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
1290f785676fSDimitry Andric       getModule(), Init->getType(),
1291f785676fSDimitry Andric       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
129233956c43SDimitry Andric   if (supportsCOMDAT())
129333956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
12943861d79fSDimitry Andric   return GV;
12953861d79fSDimitry Andric }
12963861d79fSDimitry Andric 
1297f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1298f22ef01cSRoman Divacky   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1299f22ef01cSRoman Divacky   assert(AA && "No alias?");
1300f22ef01cSRoman Divacky 
13016122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1302f22ef01cSRoman Divacky 
1303f22ef01cSRoman Divacky   // See if there is already something with the target's name in the module.
1304f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
13053861d79fSDimitry Andric   if (Entry) {
13063861d79fSDimitry Andric     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
13073861d79fSDimitry Andric     return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
13083861d79fSDimitry Andric   }
1309f22ef01cSRoman Divacky 
1310f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
1311f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
13123861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
13133861d79fSDimitry Andric                                       GlobalDecl(cast<FunctionDecl>(VD)),
13142754fe60SDimitry Andric                                       /*ForVTable=*/false);
1315f22ef01cSRoman Divacky   else
1316f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
131759d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
131859d1ed5bSDimitry Andric                                     nullptr);
13193861d79fSDimitry Andric 
132059d1ed5bSDimitry Andric   auto *F = cast<llvm::GlobalValue>(Aliasee);
1321f22ef01cSRoman Divacky   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1322f22ef01cSRoman Divacky   WeakRefReferences.insert(F);
1323f22ef01cSRoman Divacky 
1324f22ef01cSRoman Divacky   return Aliasee;
1325f22ef01cSRoman Divacky }
1326f22ef01cSRoman Divacky 
1327f22ef01cSRoman Divacky void CodeGenModule::EmitGlobal(GlobalDecl GD) {
132859d1ed5bSDimitry Andric   const auto *Global = cast<ValueDecl>(GD.getDecl());
1329f22ef01cSRoman Divacky 
1330f22ef01cSRoman Divacky   // Weak references don't produce any output by themselves.
1331f22ef01cSRoman Divacky   if (Global->hasAttr<WeakRefAttr>())
1332f22ef01cSRoman Divacky     return;
1333f22ef01cSRoman Divacky 
1334f22ef01cSRoman Divacky   // If this is an alias definition (which otherwise looks like a declaration)
1335f22ef01cSRoman Divacky   // emit it now.
1336f22ef01cSRoman Divacky   if (Global->hasAttr<AliasAttr>())
1337f22ef01cSRoman Divacky     return EmitAliasDefinition(GD);
1338f22ef01cSRoman Divacky 
13396122f3e6SDimitry Andric   // If this is CUDA, be selective about which declarations we emit.
1340dff0c46cSDimitry Andric   if (LangOpts.CUDA) {
134133956c43SDimitry Andric     if (LangOpts.CUDAIsDevice) {
13426122f3e6SDimitry Andric       if (!Global->hasAttr<CUDADeviceAttr>() &&
13436122f3e6SDimitry Andric           !Global->hasAttr<CUDAGlobalAttr>() &&
13446122f3e6SDimitry Andric           !Global->hasAttr<CUDAConstantAttr>() &&
13456122f3e6SDimitry Andric           !Global->hasAttr<CUDASharedAttr>())
13466122f3e6SDimitry Andric         return;
13476122f3e6SDimitry Andric     } else {
13486122f3e6SDimitry Andric       if (!Global->hasAttr<CUDAHostAttr>() && (
13496122f3e6SDimitry Andric             Global->hasAttr<CUDADeviceAttr>() ||
13506122f3e6SDimitry Andric             Global->hasAttr<CUDAConstantAttr>() ||
13516122f3e6SDimitry Andric             Global->hasAttr<CUDASharedAttr>()))
13526122f3e6SDimitry Andric         return;
1353e580952dSDimitry Andric     }
1354e580952dSDimitry Andric   }
1355e580952dSDimitry Andric 
13566122f3e6SDimitry Andric   // Ignore declarations, they will be emitted on their first use.
135759d1ed5bSDimitry Andric   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1358f22ef01cSRoman Divacky     // Forward declarations are emitted lazily on first use.
13596122f3e6SDimitry Andric     if (!FD->doesThisDeclarationHaveABody()) {
13606122f3e6SDimitry Andric       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1361f22ef01cSRoman Divacky         return;
13626122f3e6SDimitry Andric 
13636122f3e6SDimitry Andric       StringRef MangledName = getMangledName(GD);
136459d1ed5bSDimitry Andric 
136559d1ed5bSDimitry Andric       // Compute the function info and LLVM type.
136659d1ed5bSDimitry Andric       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
136759d1ed5bSDimitry Andric       llvm::Type *Ty = getTypes().GetFunctionType(FI);
136859d1ed5bSDimitry Andric 
136959d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
137059d1ed5bSDimitry Andric                               /*DontDefer=*/false);
13716122f3e6SDimitry Andric       return;
13726122f3e6SDimitry Andric     }
1373f22ef01cSRoman Divacky   } else {
137459d1ed5bSDimitry Andric     const auto *VD = cast<VarDecl>(Global);
1375f22ef01cSRoman Divacky     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1376f22ef01cSRoman Divacky 
137759d1ed5bSDimitry Andric     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
137859d1ed5bSDimitry Andric         !Context.isMSStaticDataMemberInlineDefinition(VD))
1379f22ef01cSRoman Divacky       return;
1380f22ef01cSRoman Divacky   }
1381f22ef01cSRoman Divacky 
138239d628a0SDimitry Andric   // Defer code generation to first use when possible, e.g. if this is an inline
138339d628a0SDimitry Andric   // function. If the global must always be emitted, do it eagerly if possible
138439d628a0SDimitry Andric   // to benefit from cache locality.
138539d628a0SDimitry Andric   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1386f22ef01cSRoman Divacky     // Emit the definition if it can't be deferred.
1387f22ef01cSRoman Divacky     EmitGlobalDefinition(GD);
1388f22ef01cSRoman Divacky     return;
1389f22ef01cSRoman Divacky   }
1390f22ef01cSRoman Divacky 
1391e580952dSDimitry Andric   // If we're deferring emission of a C++ variable with an
1392e580952dSDimitry Andric   // initializer, remember the order in which it appeared in the file.
1393dff0c46cSDimitry Andric   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1394e580952dSDimitry Andric       cast<VarDecl>(Global)->hasInit()) {
1395e580952dSDimitry Andric     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
139659d1ed5bSDimitry Andric     CXXGlobalInits.push_back(nullptr);
1397e580952dSDimitry Andric   }
1398e580952dSDimitry Andric 
13996122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
140039d628a0SDimitry Andric   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
140139d628a0SDimitry Andric     // The value has already been used and should therefore be emitted.
140259d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, GD);
140339d628a0SDimitry Andric   } else if (MustBeEmitted(Global)) {
140439d628a0SDimitry Andric     // The value must be emitted, but cannot be emitted eagerly.
140539d628a0SDimitry Andric     assert(!MayBeEmittedEagerly(Global));
140639d628a0SDimitry Andric     addDeferredDeclToEmit(/*GV=*/nullptr, GD);
140739d628a0SDimitry Andric   } else {
1408f22ef01cSRoman Divacky     // Otherwise, remember that we saw a deferred decl with this name.  The
1409f22ef01cSRoman Divacky     // first use of the mangled name will cause it to move into
1410f22ef01cSRoman Divacky     // DeferredDeclsToEmit.
1411f22ef01cSRoman Divacky     DeferredDecls[MangledName] = GD;
1412f22ef01cSRoman Divacky   }
1413f22ef01cSRoman Divacky }
1414f22ef01cSRoman Divacky 
1415f8254f43SDimitry Andric namespace {
1416f8254f43SDimitry Andric   struct FunctionIsDirectlyRecursive :
1417f8254f43SDimitry Andric     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1418f8254f43SDimitry Andric     const StringRef Name;
1419dff0c46cSDimitry Andric     const Builtin::Context &BI;
1420f8254f43SDimitry Andric     bool Result;
1421dff0c46cSDimitry Andric     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1422dff0c46cSDimitry Andric       Name(N), BI(C), Result(false) {
1423f8254f43SDimitry Andric     }
1424f8254f43SDimitry Andric     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1425f8254f43SDimitry Andric 
1426f8254f43SDimitry Andric     bool TraverseCallExpr(CallExpr *E) {
1427dff0c46cSDimitry Andric       const FunctionDecl *FD = E->getDirectCallee();
1428dff0c46cSDimitry Andric       if (!FD)
1429f8254f43SDimitry Andric         return true;
1430dff0c46cSDimitry Andric       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1431dff0c46cSDimitry Andric       if (Attr && Name == Attr->getLabel()) {
1432dff0c46cSDimitry Andric         Result = true;
1433dff0c46cSDimitry Andric         return false;
1434dff0c46cSDimitry Andric       }
1435dff0c46cSDimitry Andric       unsigned BuiltinID = FD->getBuiltinID();
14363dac3a9bSDimitry Andric       if (!BuiltinID || !BI.isLibFunction(BuiltinID))
1437f8254f43SDimitry Andric         return true;
1438dff0c46cSDimitry Andric       StringRef BuiltinName = BI.GetName(BuiltinID);
1439dff0c46cSDimitry Andric       if (BuiltinName.startswith("__builtin_") &&
1440dff0c46cSDimitry Andric           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1441f8254f43SDimitry Andric         Result = true;
1442f8254f43SDimitry Andric         return false;
1443f8254f43SDimitry Andric       }
1444f8254f43SDimitry Andric       return true;
1445f8254f43SDimitry Andric     }
1446f8254f43SDimitry Andric   };
1447f8254f43SDimitry Andric }
1448f8254f43SDimitry Andric 
1449dff0c46cSDimitry Andric // isTriviallyRecursive - Check if this function calls another
1450dff0c46cSDimitry Andric // decl that, because of the asm attribute or the other decl being a builtin,
1451dff0c46cSDimitry Andric // ends up pointing to itself.
1452f8254f43SDimitry Andric bool
1453dff0c46cSDimitry Andric CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1454dff0c46cSDimitry Andric   StringRef Name;
1455dff0c46cSDimitry Andric   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1456dff0c46cSDimitry Andric     // asm labels are a special kind of mangling we have to support.
1457dff0c46cSDimitry Andric     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1458dff0c46cSDimitry Andric     if (!Attr)
1459f8254f43SDimitry Andric       return false;
1460dff0c46cSDimitry Andric     Name = Attr->getLabel();
1461dff0c46cSDimitry Andric   } else {
1462dff0c46cSDimitry Andric     Name = FD->getName();
1463dff0c46cSDimitry Andric   }
1464f8254f43SDimitry Andric 
1465dff0c46cSDimitry Andric   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1466dff0c46cSDimitry Andric   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1467f8254f43SDimitry Andric   return Walker.Result;
1468f8254f43SDimitry Andric }
1469f8254f43SDimitry Andric 
1470f8254f43SDimitry Andric bool
1471f785676fSDimitry Andric CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1472f785676fSDimitry Andric   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1473f8254f43SDimitry Andric     return true;
147459d1ed5bSDimitry Andric   const auto *F = cast<FunctionDecl>(GD.getDecl());
147559d1ed5bSDimitry Andric   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1476f8254f43SDimitry Andric     return false;
1477f8254f43SDimitry Andric   // PR9614. Avoid cases where the source code is lying to us. An available
1478f8254f43SDimitry Andric   // externally function should have an equivalent function somewhere else,
1479f8254f43SDimitry Andric   // but a function that calls itself is clearly not equivalent to the real
1480f8254f43SDimitry Andric   // implementation.
1481f8254f43SDimitry Andric   // This happens in glibc's btowc and in some configure checks.
1482dff0c46cSDimitry Andric   return !isTriviallyRecursive(F);
1483f8254f43SDimitry Andric }
1484f8254f43SDimitry Andric 
1485f785676fSDimitry Andric /// If the type for the method's class was generated by
1486f785676fSDimitry Andric /// CGDebugInfo::createContextChain(), the cache contains only a
1487f785676fSDimitry Andric /// limited DIType without any declarations. Since EmitFunctionStart()
1488f785676fSDimitry Andric /// needs to find the canonical declaration for each method, we need
1489f785676fSDimitry Andric /// to construct the complete type prior to emitting the method.
1490f785676fSDimitry Andric void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1491f785676fSDimitry Andric   if (!D->isInstance())
1492f785676fSDimitry Andric     return;
1493f785676fSDimitry Andric 
1494f785676fSDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
1495f785676fSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
149659d1ed5bSDimitry Andric       const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1497f785676fSDimitry Andric       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1498f785676fSDimitry Andric     }
1499f785676fSDimitry Andric }
1500f785676fSDimitry Andric 
150159d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
150259d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
1503f22ef01cSRoman Divacky 
1504f22ef01cSRoman Divacky   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1505f22ef01cSRoman Divacky                                  Context.getSourceManager(),
1506f22ef01cSRoman Divacky                                  "Generating code for declaration");
1507f22ef01cSRoman Divacky 
1508f785676fSDimitry Andric   if (isa<FunctionDecl>(D)) {
1509ffd1746dSEd Schouten     // At -O0, don't generate IR for functions with available_externally
1510ffd1746dSEd Schouten     // linkage.
1511f785676fSDimitry Andric     if (!shouldEmitFunction(GD))
1512ffd1746dSEd Schouten       return;
1513ffd1746dSEd Schouten 
151459d1ed5bSDimitry Andric     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1515f785676fSDimitry Andric       CompleteDIClassType(Method);
1516bd5abe19SDimitry Andric       // Make sure to emit the definition(s) before we emit the thunks.
1517bd5abe19SDimitry Andric       // This is necessary for the generation of certain thunks.
151859d1ed5bSDimitry Andric       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
151939d628a0SDimitry Andric         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
152059d1ed5bSDimitry Andric       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
152139d628a0SDimitry Andric         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1522bd5abe19SDimitry Andric       else
152359d1ed5bSDimitry Andric         EmitGlobalFunctionDefinition(GD, GV);
1524bd5abe19SDimitry Andric 
1525f22ef01cSRoman Divacky       if (Method->isVirtual())
1526f22ef01cSRoman Divacky         getVTables().EmitThunks(GD);
1527f22ef01cSRoman Divacky 
1528bd5abe19SDimitry Andric       return;
1529ffd1746dSEd Schouten     }
1530f22ef01cSRoman Divacky 
153159d1ed5bSDimitry Andric     return EmitGlobalFunctionDefinition(GD, GV);
1532ffd1746dSEd Schouten   }
1533f22ef01cSRoman Divacky 
153459d1ed5bSDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
1535f22ef01cSRoman Divacky     return EmitGlobalVarDefinition(VD);
1536f22ef01cSRoman Divacky 
15376122f3e6SDimitry Andric   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1538f22ef01cSRoman Divacky }
1539f22ef01cSRoman Divacky 
1540f22ef01cSRoman Divacky /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1541f22ef01cSRoman Divacky /// module, create and return an llvm Function with the specified type. If there
1542f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
1543f22ef01cSRoman Divacky /// bitcasted to the right type.
1544f22ef01cSRoman Divacky ///
1545f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
1546f22ef01cSRoman Divacky /// to set the attributes on the function when it is first created.
1547f22ef01cSRoman Divacky llvm::Constant *
15486122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
15496122f3e6SDimitry Andric                                        llvm::Type *Ty,
1550f785676fSDimitry Andric                                        GlobalDecl GD, bool ForVTable,
155139d628a0SDimitry Andric                                        bool DontDefer, bool IsThunk,
1552139f7f9bSDimitry Andric                                        llvm::AttributeSet ExtraAttrs) {
1553f785676fSDimitry Andric   const Decl *D = GD.getDecl();
1554f785676fSDimitry Andric 
1555f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
1556f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1557f22ef01cSRoman Divacky   if (Entry) {
15583861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
1559f785676fSDimitry Andric       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1560f22ef01cSRoman Divacky       if (FD && !FD->hasAttr<WeakAttr>())
1561f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
1562f22ef01cSRoman Divacky     }
1563f22ef01cSRoman Divacky 
156439d628a0SDimitry Andric     // Handle dropped DLL attributes.
156539d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
156639d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
156739d628a0SDimitry Andric 
1568f22ef01cSRoman Divacky     if (Entry->getType()->getElementType() == Ty)
1569f22ef01cSRoman Divacky       return Entry;
1570f22ef01cSRoman Divacky 
1571f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
157217a519f9SDimitry Andric     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1573f22ef01cSRoman Divacky   }
1574f22ef01cSRoman Divacky 
1575f22ef01cSRoman Divacky   // This function doesn't have a complete type (for example, the return
1576f22ef01cSRoman Divacky   // type is an incomplete struct). Use a fake type instead, and make
1577f22ef01cSRoman Divacky   // sure not to try to set attributes.
1578f22ef01cSRoman Divacky   bool IsIncompleteFunction = false;
1579f22ef01cSRoman Divacky 
15806122f3e6SDimitry Andric   llvm::FunctionType *FTy;
1581f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(Ty)) {
1582f22ef01cSRoman Divacky     FTy = cast<llvm::FunctionType>(Ty);
1583f22ef01cSRoman Divacky   } else {
1584bd5abe19SDimitry Andric     FTy = llvm::FunctionType::get(VoidTy, false);
1585f22ef01cSRoman Divacky     IsIncompleteFunction = true;
1586f22ef01cSRoman Divacky   }
1587ffd1746dSEd Schouten 
1588f22ef01cSRoman Divacky   llvm::Function *F = llvm::Function::Create(FTy,
1589f22ef01cSRoman Divacky                                              llvm::Function::ExternalLinkage,
1590f22ef01cSRoman Divacky                                              MangledName, &getModule());
1591f22ef01cSRoman Divacky   assert(F->getName() == MangledName && "name was uniqued!");
1592f785676fSDimitry Andric   if (D)
159339d628a0SDimitry Andric     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1594139f7f9bSDimitry Andric   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1595139f7f9bSDimitry Andric     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1596139f7f9bSDimitry Andric     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1597139f7f9bSDimitry Andric                      llvm::AttributeSet::get(VMContext,
1598139f7f9bSDimitry Andric                                              llvm::AttributeSet::FunctionIndex,
1599139f7f9bSDimitry Andric                                              B));
1600139f7f9bSDimitry Andric   }
1601f22ef01cSRoman Divacky 
160259d1ed5bSDimitry Andric   if (!DontDefer) {
160359d1ed5bSDimitry Andric     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
160459d1ed5bSDimitry Andric     // each other bottoming out with the base dtor.  Therefore we emit non-base
160559d1ed5bSDimitry Andric     // dtors on usage, even if there is no dtor definition in the TU.
160659d1ed5bSDimitry Andric     if (D && isa<CXXDestructorDecl>(D) &&
160759d1ed5bSDimitry Andric         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
160859d1ed5bSDimitry Andric                                            GD.getDtorType()))
160959d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, GD);
161059d1ed5bSDimitry Andric 
1611f22ef01cSRoman Divacky     // This is the first use or definition of a mangled name.  If there is a
1612f22ef01cSRoman Divacky     // deferred decl with this name, remember that we need to emit it at the end
1613f22ef01cSRoman Divacky     // of the file.
161459d1ed5bSDimitry Andric     auto DDI = DeferredDecls.find(MangledName);
1615f22ef01cSRoman Divacky     if (DDI != DeferredDecls.end()) {
161659d1ed5bSDimitry Andric       // Move the potentially referenced deferred decl to the
161759d1ed5bSDimitry Andric       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
161859d1ed5bSDimitry Andric       // don't need it anymore).
161959d1ed5bSDimitry Andric       addDeferredDeclToEmit(F, DDI->second);
1620f22ef01cSRoman Divacky       DeferredDecls.erase(DDI);
16212754fe60SDimitry Andric 
16222754fe60SDimitry Andric       // Otherwise, there are cases we have to worry about where we're
16232754fe60SDimitry Andric       // using a declaration for which we must emit a definition but where
16242754fe60SDimitry Andric       // we might not find a top-level definition:
16252754fe60SDimitry Andric       //   - member functions defined inline in their classes
16262754fe60SDimitry Andric       //   - friend functions defined inline in some class
16272754fe60SDimitry Andric       //   - special member functions with implicit definitions
16282754fe60SDimitry Andric       // If we ever change our AST traversal to walk into class methods,
16292754fe60SDimitry Andric       // this will be unnecessary.
16302754fe60SDimitry Andric       //
163159d1ed5bSDimitry Andric       // We also don't emit a definition for a function if it's going to be an
163239d628a0SDimitry Andric       // entry in a vtable, unless it's already marked as used.
1633f785676fSDimitry Andric     } else if (getLangOpts().CPlusPlus && D) {
16342754fe60SDimitry Andric       // Look for a declaration that's lexically in a record.
163539d628a0SDimitry Andric       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
163639d628a0SDimitry Andric            FD = FD->getPreviousDecl()) {
16372754fe60SDimitry Andric         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
163839d628a0SDimitry Andric           if (FD->doesThisDeclarationHaveABody()) {
163959d1ed5bSDimitry Andric             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
16402754fe60SDimitry Andric             break;
1641f22ef01cSRoman Divacky           }
1642f22ef01cSRoman Divacky         }
164339d628a0SDimitry Andric       }
1644f22ef01cSRoman Divacky     }
164559d1ed5bSDimitry Andric   }
1646f22ef01cSRoman Divacky 
1647f22ef01cSRoman Divacky   // Make sure the result is of the requested type.
1648f22ef01cSRoman Divacky   if (!IsIncompleteFunction) {
1649f22ef01cSRoman Divacky     assert(F->getType()->getElementType() == Ty);
1650f22ef01cSRoman Divacky     return F;
1651f22ef01cSRoman Divacky   }
1652f22ef01cSRoman Divacky 
165317a519f9SDimitry Andric   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1654f22ef01cSRoman Divacky   return llvm::ConstantExpr::getBitCast(F, PTy);
1655f22ef01cSRoman Divacky }
1656f22ef01cSRoman Divacky 
1657f22ef01cSRoman Divacky /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1658f22ef01cSRoman Divacky /// non-null, then this function will use the specified type if it has to
1659f22ef01cSRoman Divacky /// create it (this occurs when we see a definition of the function).
1660f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
16616122f3e6SDimitry Andric                                                  llvm::Type *Ty,
166259d1ed5bSDimitry Andric                                                  bool ForVTable,
166359d1ed5bSDimitry Andric                                                  bool DontDefer) {
1664f22ef01cSRoman Divacky   // If there was no specific requested type, just convert it now.
1665f22ef01cSRoman Divacky   if (!Ty)
1666f22ef01cSRoman Divacky     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1667ffd1746dSEd Schouten 
16686122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
166959d1ed5bSDimitry Andric   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
1670f22ef01cSRoman Divacky }
1671f22ef01cSRoman Divacky 
1672f22ef01cSRoman Divacky /// CreateRuntimeFunction - Create a new runtime function with the specified
1673f22ef01cSRoman Divacky /// type and name.
1674f22ef01cSRoman Divacky llvm::Constant *
16756122f3e6SDimitry Andric CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
16766122f3e6SDimitry Andric                                      StringRef Name,
1677139f7f9bSDimitry Andric                                      llvm::AttributeSet ExtraAttrs) {
167859d1ed5bSDimitry Andric   llvm::Constant *C =
167959d1ed5bSDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
168039d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
168159d1ed5bSDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
1682139f7f9bSDimitry Andric     if (F->empty())
1683139f7f9bSDimitry Andric       F->setCallingConv(getRuntimeCC());
1684139f7f9bSDimitry Andric   return C;
1685f22ef01cSRoman Divacky }
1686f22ef01cSRoman Divacky 
168739d628a0SDimitry Andric /// CreateBuiltinFunction - Create a new builtin function with the specified
168839d628a0SDimitry Andric /// type and name.
168939d628a0SDimitry Andric llvm::Constant *
169039d628a0SDimitry Andric CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
169139d628a0SDimitry Andric                                      StringRef Name,
169239d628a0SDimitry Andric                                      llvm::AttributeSet ExtraAttrs) {
169339d628a0SDimitry Andric   llvm::Constant *C =
169439d628a0SDimitry Andric       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
169539d628a0SDimitry Andric                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
169639d628a0SDimitry Andric   if (auto *F = dyn_cast<llvm::Function>(C))
169739d628a0SDimitry Andric     if (F->empty())
169839d628a0SDimitry Andric       F->setCallingConv(getBuiltinCC());
169939d628a0SDimitry Andric   return C;
170039d628a0SDimitry Andric }
170139d628a0SDimitry Andric 
1702dff0c46cSDimitry Andric /// isTypeConstant - Determine whether an object of this type can be emitted
1703dff0c46cSDimitry Andric /// as a constant.
1704dff0c46cSDimitry Andric ///
1705dff0c46cSDimitry Andric /// If ExcludeCtor is true, the duration when the object's constructor runs
1706dff0c46cSDimitry Andric /// will not be considered. The caller will need to verify that the object is
1707dff0c46cSDimitry Andric /// not written to during its construction.
1708dff0c46cSDimitry Andric bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1709dff0c46cSDimitry Andric   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1710f22ef01cSRoman Divacky     return false;
1711bd5abe19SDimitry Andric 
1712dff0c46cSDimitry Andric   if (Context.getLangOpts().CPlusPlus) {
1713dff0c46cSDimitry Andric     if (const CXXRecordDecl *Record
1714dff0c46cSDimitry Andric           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1715dff0c46cSDimitry Andric       return ExcludeCtor && !Record->hasMutableFields() &&
1716dff0c46cSDimitry Andric              Record->hasTrivialDestructor();
1717f22ef01cSRoman Divacky   }
1718bd5abe19SDimitry Andric 
1719f22ef01cSRoman Divacky   return true;
1720f22ef01cSRoman Divacky }
1721f22ef01cSRoman Divacky 
1722f22ef01cSRoman Divacky /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1723f22ef01cSRoman Divacky /// create and return an llvm GlobalVariable with the specified type.  If there
1724f22ef01cSRoman Divacky /// is something in the module with the specified name, return it potentially
1725f22ef01cSRoman Divacky /// bitcasted to the right type.
1726f22ef01cSRoman Divacky ///
1727f22ef01cSRoman Divacky /// If D is non-null, it specifies a decl that correspond to this.  This is used
1728f22ef01cSRoman Divacky /// to set the attributes on the global when it is first created.
1729f22ef01cSRoman Divacky llvm::Constant *
17306122f3e6SDimitry Andric CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
17316122f3e6SDimitry Andric                                      llvm::PointerType *Ty,
173259d1ed5bSDimitry Andric                                      const VarDecl *D) {
1733f22ef01cSRoman Divacky   // Lookup the entry, lazily creating it if necessary.
1734f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1735f22ef01cSRoman Divacky   if (Entry) {
17363861d79fSDimitry Andric     if (WeakRefReferences.erase(Entry)) {
1737f22ef01cSRoman Divacky       if (D && !D->hasAttr<WeakAttr>())
1738f22ef01cSRoman Divacky         Entry->setLinkage(llvm::Function::ExternalLinkage);
1739f22ef01cSRoman Divacky     }
1740f22ef01cSRoman Divacky 
174139d628a0SDimitry Andric     // Handle dropped DLL attributes.
174239d628a0SDimitry Andric     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
174339d628a0SDimitry Andric       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
174439d628a0SDimitry Andric 
1745f22ef01cSRoman Divacky     if (Entry->getType() == Ty)
1746f22ef01cSRoman Divacky       return Entry;
1747f22ef01cSRoman Divacky 
1748f22ef01cSRoman Divacky     // Make sure the result is of the correct type.
1749f785676fSDimitry Andric     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1750f785676fSDimitry Andric       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1751f785676fSDimitry Andric 
1752f22ef01cSRoman Divacky     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1753f22ef01cSRoman Divacky   }
1754f22ef01cSRoman Divacky 
175559d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
175659d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
175759d1ed5bSDimitry Andric       getModule(), Ty->getElementType(), false,
175859d1ed5bSDimitry Andric       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
175959d1ed5bSDimitry Andric       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
176059d1ed5bSDimitry Andric 
1761f22ef01cSRoman Divacky   // This is the first use or definition of a mangled name.  If there is a
1762f22ef01cSRoman Divacky   // deferred decl with this name, remember that we need to emit it at the end
1763f22ef01cSRoman Divacky   // of the file.
176459d1ed5bSDimitry Andric   auto DDI = DeferredDecls.find(MangledName);
1765f22ef01cSRoman Divacky   if (DDI != DeferredDecls.end()) {
1766f22ef01cSRoman Divacky     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1767f22ef01cSRoman Divacky     // list, and remove it from DeferredDecls (since we don't need it anymore).
176859d1ed5bSDimitry Andric     addDeferredDeclToEmit(GV, DDI->second);
1769f22ef01cSRoman Divacky     DeferredDecls.erase(DDI);
1770f22ef01cSRoman Divacky   }
1771f22ef01cSRoman Divacky 
1772f22ef01cSRoman Divacky   // Handle things which are present even on external declarations.
1773f22ef01cSRoman Divacky   if (D) {
1774f22ef01cSRoman Divacky     // FIXME: This code is overly simple and should be merged with other global
1775f22ef01cSRoman Divacky     // handling.
1776dff0c46cSDimitry Andric     GV->setConstant(isTypeConstant(D->getType(), false));
1777f22ef01cSRoman Divacky 
177833956c43SDimitry Andric     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
177933956c43SDimitry Andric 
178059d1ed5bSDimitry Andric     setLinkageAndVisibilityForGV(GV, D);
17812754fe60SDimitry Andric 
1782284c1978SDimitry Andric     if (D->getTLSKind()) {
1783284c1978SDimitry Andric       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1784284c1978SDimitry Andric         CXXThreadLocals.push_back(std::make_pair(D, GV));
17857ae0e2c9SDimitry Andric       setTLSMode(GV, *D);
1786f22ef01cSRoman Divacky     }
1787f785676fSDimitry Andric 
1788f785676fSDimitry Andric     // If required by the ABI, treat declarations of static data members with
1789f785676fSDimitry Andric     // inline initializers as definitions.
179059d1ed5bSDimitry Andric     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
1791f785676fSDimitry Andric       EmitGlobalVarDefinition(D);
1792284c1978SDimitry Andric     }
1793f22ef01cSRoman Divacky 
179459d1ed5bSDimitry Andric     // Handle XCore specific ABI requirements.
179559d1ed5bSDimitry Andric     if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
179659d1ed5bSDimitry Andric         D->getLanguageLinkage() == CLanguageLinkage &&
179759d1ed5bSDimitry Andric         D->getType().isConstant(Context) &&
179859d1ed5bSDimitry Andric         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
179959d1ed5bSDimitry Andric       GV->setSection(".cp.rodata");
180059d1ed5bSDimitry Andric   }
180159d1ed5bSDimitry Andric 
18027ae0e2c9SDimitry Andric   if (AddrSpace != Ty->getAddressSpace())
1803f785676fSDimitry Andric     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1804f785676fSDimitry Andric 
1805f22ef01cSRoman Divacky   return GV;
1806f22ef01cSRoman Divacky }
1807f22ef01cSRoman Divacky 
1808f22ef01cSRoman Divacky 
18092754fe60SDimitry Andric llvm::GlobalVariable *
18106122f3e6SDimitry Andric CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
18116122f3e6SDimitry Andric                                       llvm::Type *Ty,
18122754fe60SDimitry Andric                                       llvm::GlobalValue::LinkageTypes Linkage) {
18132754fe60SDimitry Andric   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
181459d1ed5bSDimitry Andric   llvm::GlobalVariable *OldGV = nullptr;
18152754fe60SDimitry Andric 
18162754fe60SDimitry Andric   if (GV) {
18172754fe60SDimitry Andric     // Check if the variable has the right type.
18182754fe60SDimitry Andric     if (GV->getType()->getElementType() == Ty)
18192754fe60SDimitry Andric       return GV;
18202754fe60SDimitry Andric 
18212754fe60SDimitry Andric     // Because C++ name mangling, the only way we can end up with an already
18222754fe60SDimitry Andric     // existing global with the same name is if it has been declared extern "C".
18232754fe60SDimitry Andric     assert(GV->isDeclaration() && "Declaration has wrong type!");
18242754fe60SDimitry Andric     OldGV = GV;
18252754fe60SDimitry Andric   }
18262754fe60SDimitry Andric 
18272754fe60SDimitry Andric   // Create a new variable.
18282754fe60SDimitry Andric   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
182959d1ed5bSDimitry Andric                                 Linkage, nullptr, Name);
18302754fe60SDimitry Andric 
18312754fe60SDimitry Andric   if (OldGV) {
18322754fe60SDimitry Andric     // Replace occurrences of the old variable if needed.
18332754fe60SDimitry Andric     GV->takeName(OldGV);
18342754fe60SDimitry Andric 
18352754fe60SDimitry Andric     if (!OldGV->use_empty()) {
18362754fe60SDimitry Andric       llvm::Constant *NewPtrForOldDecl =
18372754fe60SDimitry Andric       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
18382754fe60SDimitry Andric       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
18392754fe60SDimitry Andric     }
18402754fe60SDimitry Andric 
18412754fe60SDimitry Andric     OldGV->eraseFromParent();
18422754fe60SDimitry Andric   }
18432754fe60SDimitry Andric 
184433956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker() &&
184533956c43SDimitry Andric       !GV->hasAvailableExternallyLinkage())
184633956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
184733956c43SDimitry Andric 
18482754fe60SDimitry Andric   return GV;
18492754fe60SDimitry Andric }
18502754fe60SDimitry Andric 
1851f22ef01cSRoman Divacky /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1852f22ef01cSRoman Divacky /// given global variable.  If Ty is non-null and if the global doesn't exist,
1853cb4dff85SDimitry Andric /// then it will be created with the specified type instead of whatever the
1854f22ef01cSRoman Divacky /// normal requested type would be.
1855f22ef01cSRoman Divacky llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
18566122f3e6SDimitry Andric                                                   llvm::Type *Ty) {
1857f22ef01cSRoman Divacky   assert(D->hasGlobalStorage() && "Not a global variable");
1858f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
185959d1ed5bSDimitry Andric   if (!Ty)
1860f22ef01cSRoman Divacky     Ty = getTypes().ConvertTypeForMem(ASTTy);
1861f22ef01cSRoman Divacky 
18626122f3e6SDimitry Andric   llvm::PointerType *PTy =
18633b0f4066SDimitry Andric     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1864f22ef01cSRoman Divacky 
18656122f3e6SDimitry Andric   StringRef MangledName = getMangledName(D);
1866f22ef01cSRoman Divacky   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1867f22ef01cSRoman Divacky }
1868f22ef01cSRoman Divacky 
1869f22ef01cSRoman Divacky /// CreateRuntimeVariable - Create a new runtime global variable with the
1870f22ef01cSRoman Divacky /// specified type and name.
1871f22ef01cSRoman Divacky llvm::Constant *
18726122f3e6SDimitry Andric CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
18736122f3e6SDimitry Andric                                      StringRef Name) {
187459d1ed5bSDimitry Andric   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
1875f22ef01cSRoman Divacky }
1876f22ef01cSRoman Divacky 
1877f22ef01cSRoman Divacky void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1878f22ef01cSRoman Divacky   assert(!D->getInit() && "Cannot emit definite definitions here!");
1879f22ef01cSRoman Divacky 
188039d628a0SDimitry Andric   if (!MustBeEmitted(D)) {
1881f22ef01cSRoman Divacky     // If we have not seen a reference to this variable yet, place it
1882f22ef01cSRoman Divacky     // into the deferred declarations table to be emitted if needed
1883f22ef01cSRoman Divacky     // later.
18846122f3e6SDimitry Andric     StringRef MangledName = getMangledName(D);
1885f22ef01cSRoman Divacky     if (!GetGlobalValue(MangledName)) {
1886f22ef01cSRoman Divacky       DeferredDecls[MangledName] = D;
1887f22ef01cSRoman Divacky       return;
1888f22ef01cSRoman Divacky     }
1889f22ef01cSRoman Divacky   }
1890f22ef01cSRoman Divacky 
1891f22ef01cSRoman Divacky   // The tentative definition is the only definition.
1892f22ef01cSRoman Divacky   EmitGlobalVarDefinition(D);
1893f22ef01cSRoman Divacky }
1894f22ef01cSRoman Divacky 
18956122f3e6SDimitry Andric CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
18962754fe60SDimitry Andric     return Context.toCharUnitsFromBits(
18973861d79fSDimitry Andric       TheDataLayout.getTypeStoreSizeInBits(Ty));
1898f22ef01cSRoman Divacky }
1899f22ef01cSRoman Divacky 
19007ae0e2c9SDimitry Andric unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
19017ae0e2c9SDimitry Andric                                                  unsigned AddrSpace) {
190233956c43SDimitry Andric   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
19037ae0e2c9SDimitry Andric     if (D->hasAttr<CUDAConstantAttr>())
19047ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
19057ae0e2c9SDimitry Andric     else if (D->hasAttr<CUDASharedAttr>())
19067ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
19077ae0e2c9SDimitry Andric     else
19087ae0e2c9SDimitry Andric       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
19097ae0e2c9SDimitry Andric   }
19107ae0e2c9SDimitry Andric 
19117ae0e2c9SDimitry Andric   return AddrSpace;
19127ae0e2c9SDimitry Andric }
19137ae0e2c9SDimitry Andric 
1914284c1978SDimitry Andric template<typename SomeDecl>
1915284c1978SDimitry Andric void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1916284c1978SDimitry Andric                                                llvm::GlobalValue *GV) {
1917284c1978SDimitry Andric   if (!getLangOpts().CPlusPlus)
1918284c1978SDimitry Andric     return;
1919284c1978SDimitry Andric 
1920284c1978SDimitry Andric   // Must have 'used' attribute, or else inline assembly can't rely on
1921284c1978SDimitry Andric   // the name existing.
1922284c1978SDimitry Andric   if (!D->template hasAttr<UsedAttr>())
1923284c1978SDimitry Andric     return;
1924284c1978SDimitry Andric 
1925284c1978SDimitry Andric   // Must have internal linkage and an ordinary name.
1926f785676fSDimitry Andric   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
1927284c1978SDimitry Andric     return;
1928284c1978SDimitry Andric 
1929284c1978SDimitry Andric   // Must be in an extern "C" context. Entities declared directly within
1930284c1978SDimitry Andric   // a record are not extern "C" even if the record is in such a context.
1931f785676fSDimitry Andric   const SomeDecl *First = D->getFirstDecl();
1932284c1978SDimitry Andric   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1933284c1978SDimitry Andric     return;
1934284c1978SDimitry Andric 
1935284c1978SDimitry Andric   // OK, this is an internal linkage entity inside an extern "C" linkage
1936284c1978SDimitry Andric   // specification. Make a note of that so we can give it the "expected"
1937284c1978SDimitry Andric   // mangled name if nothing else is using that name.
1938284c1978SDimitry Andric   std::pair<StaticExternCMap::iterator, bool> R =
1939284c1978SDimitry Andric       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1940284c1978SDimitry Andric 
1941284c1978SDimitry Andric   // If we have multiple internal linkage entities with the same name
1942284c1978SDimitry Andric   // in extern "C" regions, none of them gets that name.
1943284c1978SDimitry Andric   if (!R.second)
194459d1ed5bSDimitry Andric     R.first->second = nullptr;
1945284c1978SDimitry Andric }
1946284c1978SDimitry Andric 
194733956c43SDimitry Andric static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
194833956c43SDimitry Andric   if (!CGM.supportsCOMDAT())
194933956c43SDimitry Andric     return false;
195033956c43SDimitry Andric 
195133956c43SDimitry Andric   if (D.hasAttr<SelectAnyAttr>())
195233956c43SDimitry Andric     return true;
195333956c43SDimitry Andric 
195433956c43SDimitry Andric   GVALinkage Linkage;
195533956c43SDimitry Andric   if (auto *VD = dyn_cast<VarDecl>(&D))
195633956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
195733956c43SDimitry Andric   else
195833956c43SDimitry Andric     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
195933956c43SDimitry Andric 
196033956c43SDimitry Andric   switch (Linkage) {
196133956c43SDimitry Andric   case GVA_Internal:
196233956c43SDimitry Andric   case GVA_AvailableExternally:
196333956c43SDimitry Andric   case GVA_StrongExternal:
196433956c43SDimitry Andric     return false;
196533956c43SDimitry Andric   case GVA_DiscardableODR:
196633956c43SDimitry Andric   case GVA_StrongODR:
196733956c43SDimitry Andric     return true;
196833956c43SDimitry Andric   }
196933956c43SDimitry Andric   llvm_unreachable("No such linkage");
197033956c43SDimitry Andric }
197133956c43SDimitry Andric 
197233956c43SDimitry Andric void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
197333956c43SDimitry Andric                                           llvm::GlobalObject &GO) {
197433956c43SDimitry Andric   if (!shouldBeInCOMDAT(*this, D))
197533956c43SDimitry Andric     return;
197633956c43SDimitry Andric   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
197733956c43SDimitry Andric }
197833956c43SDimitry Andric 
1979f22ef01cSRoman Divacky void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
198059d1ed5bSDimitry Andric   llvm::Constant *Init = nullptr;
1981f22ef01cSRoman Divacky   QualType ASTTy = D->getType();
1982dff0c46cSDimitry Andric   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1983dff0c46cSDimitry Andric   bool NeedsGlobalCtor = false;
1984dff0c46cSDimitry Andric   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1985f22ef01cSRoman Divacky 
1986dff0c46cSDimitry Andric   const VarDecl *InitDecl;
1987dff0c46cSDimitry Andric   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1988f22ef01cSRoman Divacky 
1989f22ef01cSRoman Divacky   if (!InitExpr) {
1990f22ef01cSRoman Divacky     // This is a tentative definition; tentative definitions are
1991f22ef01cSRoman Divacky     // implicitly initialized with { 0 }.
1992f22ef01cSRoman Divacky     //
1993f22ef01cSRoman Divacky     // Note that tentative definitions are only emitted at the end of
1994f22ef01cSRoman Divacky     // a translation unit, so they should never have incomplete
1995f22ef01cSRoman Divacky     // type. In addition, EmitTentativeDefinition makes sure that we
1996f22ef01cSRoman Divacky     // never attempt to emit a tentative definition if a real one
1997f22ef01cSRoman Divacky     // exists. A use may still exists, however, so we still may need
1998f22ef01cSRoman Divacky     // to do a RAUW.
1999f22ef01cSRoman Divacky     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
2000f22ef01cSRoman Divacky     Init = EmitNullConstant(D->getType());
2001f22ef01cSRoman Divacky   } else {
20027ae0e2c9SDimitry Andric     initializedGlobalDecl = GlobalDecl(D);
2003dff0c46cSDimitry Andric     Init = EmitConstantInit(*InitDecl);
2004f785676fSDimitry Andric 
2005f22ef01cSRoman Divacky     if (!Init) {
2006f22ef01cSRoman Divacky       QualType T = InitExpr->getType();
2007f22ef01cSRoman Divacky       if (D->getType()->isReferenceType())
2008f22ef01cSRoman Divacky         T = D->getType();
2009f22ef01cSRoman Divacky 
2010dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus) {
2011f22ef01cSRoman Divacky         Init = EmitNullConstant(T);
2012dff0c46cSDimitry Andric         NeedsGlobalCtor = true;
2013f22ef01cSRoman Divacky       } else {
2014f22ef01cSRoman Divacky         ErrorUnsupported(D, "static initializer");
2015f22ef01cSRoman Divacky         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2016f22ef01cSRoman Divacky       }
2017e580952dSDimitry Andric     } else {
2018e580952dSDimitry Andric       // We don't need an initializer, so remove the entry for the delayed
2019dff0c46cSDimitry Andric       // initializer position (just in case this entry was delayed) if we
2020dff0c46cSDimitry Andric       // also don't need to register a destructor.
2021dff0c46cSDimitry Andric       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2022e580952dSDimitry Andric         DelayedCXXInitPosition.erase(D);
2023f22ef01cSRoman Divacky     }
2024f22ef01cSRoman Divacky   }
2025f22ef01cSRoman Divacky 
20266122f3e6SDimitry Andric   llvm::Type* InitType = Init->getType();
2027f22ef01cSRoman Divacky   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
2028f22ef01cSRoman Divacky 
2029f22ef01cSRoman Divacky   // Strip off a bitcast if we got one back.
203059d1ed5bSDimitry Andric   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2031f22ef01cSRoman Divacky     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2032f785676fSDimitry Andric            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2033f785676fSDimitry Andric            // All zero index gep.
2034f22ef01cSRoman Divacky            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2035f22ef01cSRoman Divacky     Entry = CE->getOperand(0);
2036f22ef01cSRoman Divacky   }
2037f22ef01cSRoman Divacky 
2038f22ef01cSRoman Divacky   // Entry is now either a Function or GlobalVariable.
203959d1ed5bSDimitry Andric   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2040f22ef01cSRoman Divacky 
2041f22ef01cSRoman Divacky   // We have a definition after a declaration with the wrong type.
2042f22ef01cSRoman Divacky   // We must make a new GlobalVariable* and update everything that used OldGV
2043f22ef01cSRoman Divacky   // (a declaration or tentative definition) with the new GlobalVariable*
2044f22ef01cSRoman Divacky   // (which will be a definition).
2045f22ef01cSRoman Divacky   //
2046f22ef01cSRoman Divacky   // This happens if there is a prototype for a global (e.g.
2047f22ef01cSRoman Divacky   // "extern int x[];") and then a definition of a different type (e.g.
2048f22ef01cSRoman Divacky   // "int x[10];"). This also happens when an initializer has a different type
2049f22ef01cSRoman Divacky   // from the type of the global (this happens with unions).
205059d1ed5bSDimitry Andric   if (!GV ||
2051f22ef01cSRoman Divacky       GV->getType()->getElementType() != InitType ||
20523b0f4066SDimitry Andric       GV->getType()->getAddressSpace() !=
20537ae0e2c9SDimitry Andric        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2054f22ef01cSRoman Divacky 
2055f22ef01cSRoman Divacky     // Move the old entry aside so that we'll create a new one.
20566122f3e6SDimitry Andric     Entry->setName(StringRef());
2057f22ef01cSRoman Divacky 
2058f22ef01cSRoman Divacky     // Make a new global with the correct type, this is now guaranteed to work.
2059f22ef01cSRoman Divacky     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
2060f22ef01cSRoman Divacky 
2061f22ef01cSRoman Divacky     // Replace all uses of the old global with the new global
2062f22ef01cSRoman Divacky     llvm::Constant *NewPtrForOldDecl =
2063f22ef01cSRoman Divacky         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2064f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2065f22ef01cSRoman Divacky 
2066f22ef01cSRoman Divacky     // Erase the old global, since it is no longer used.
2067f22ef01cSRoman Divacky     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2068f22ef01cSRoman Divacky   }
2069f22ef01cSRoman Divacky 
2070284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, GV);
2071284c1978SDimitry Andric 
20726122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
20736122f3e6SDimitry Andric     AddGlobalAnnotations(D, GV);
2074f22ef01cSRoman Divacky 
2075f22ef01cSRoman Divacky   GV->setInitializer(Init);
2076f22ef01cSRoman Divacky 
2077f22ef01cSRoman Divacky   // If it is safe to mark the global 'constant', do so now.
2078dff0c46cSDimitry Andric   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2079dff0c46cSDimitry Andric                   isTypeConstant(D->getType(), true));
2080f22ef01cSRoman Divacky 
208139d628a0SDimitry Andric   // If it is in a read-only section, mark it 'constant'.
208239d628a0SDimitry Andric   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
208339d628a0SDimitry Andric     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
208439d628a0SDimitry Andric     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
208539d628a0SDimitry Andric       GV->setConstant(true);
208639d628a0SDimitry Andric   }
208739d628a0SDimitry Andric 
2088f22ef01cSRoman Divacky   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2089f22ef01cSRoman Divacky 
2090f22ef01cSRoman Divacky   // Set the llvm linkage type as appropriate.
20912754fe60SDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
209259d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(D, GV->isConstant());
2093f785676fSDimitry Andric 
209459d1ed5bSDimitry Andric   // On Darwin, the backing variable for a C++11 thread_local variable always
209559d1ed5bSDimitry Andric   // has internal linkage; all accesses should just be calls to the
209659d1ed5bSDimitry Andric   // Itanium-specified entry point, which has the normal linkage of the
209759d1ed5bSDimitry Andric   // variable.
209839d628a0SDimitry Andric   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
209959d1ed5bSDimitry Andric       Context.getTargetInfo().getTriple().isMacOSX())
210059d1ed5bSDimitry Andric     Linkage = llvm::GlobalValue::InternalLinkage;
210159d1ed5bSDimitry Andric 
210259d1ed5bSDimitry Andric   GV->setLinkage(Linkage);
210359d1ed5bSDimitry Andric   if (D->hasAttr<DLLImportAttr>())
210459d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
210559d1ed5bSDimitry Andric   else if (D->hasAttr<DLLExportAttr>())
210659d1ed5bSDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
210739d628a0SDimitry Andric   else
210839d628a0SDimitry Andric     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2109f785676fSDimitry Andric 
21102754fe60SDimitry Andric   if (Linkage == llvm::GlobalVariable::CommonLinkage)
2111f22ef01cSRoman Divacky     // common vars aren't constant even if declared const.
2112f22ef01cSRoman Divacky     GV->setConstant(false);
2113f22ef01cSRoman Divacky 
211459d1ed5bSDimitry Andric   setNonAliasAttributes(D, GV);
2115f22ef01cSRoman Divacky 
211639d628a0SDimitry Andric   if (D->getTLSKind() && !GV->isThreadLocal()) {
211739d628a0SDimitry Andric     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
211839d628a0SDimitry Andric       CXXThreadLocals.push_back(std::make_pair(D, GV));
211939d628a0SDimitry Andric     setTLSMode(GV, *D);
212039d628a0SDimitry Andric   }
212139d628a0SDimitry Andric 
212233956c43SDimitry Andric   maybeSetTrivialComdat(*D, *GV);
212333956c43SDimitry Andric 
21242754fe60SDimitry Andric   // Emit the initializer function if necessary.
2125dff0c46cSDimitry Andric   if (NeedsGlobalCtor || NeedsGlobalDtor)
2126dff0c46cSDimitry Andric     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
21272754fe60SDimitry Andric 
212839d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
21293861d79fSDimitry Andric 
2130f22ef01cSRoman Divacky   // Emit global variable debug information.
21316122f3e6SDimitry Andric   if (CGDebugInfo *DI = getModuleDebugInfo())
21323861d79fSDimitry Andric     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2133f22ef01cSRoman Divacky       DI->EmitGlobalVariable(GV, D);
2134f22ef01cSRoman Divacky }
2135f22ef01cSRoman Divacky 
213639d628a0SDimitry Andric static bool isVarDeclStrongDefinition(const ASTContext &Context,
213733956c43SDimitry Andric                                       CodeGenModule &CGM, const VarDecl *D,
213833956c43SDimitry Andric                                       bool NoCommon) {
213959d1ed5bSDimitry Andric   // Don't give variables common linkage if -fno-common was specified unless it
214059d1ed5bSDimitry Andric   // was overridden by a NoCommon attribute.
214159d1ed5bSDimitry Andric   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
214259d1ed5bSDimitry Andric     return true;
214359d1ed5bSDimitry Andric 
214459d1ed5bSDimitry Andric   // C11 6.9.2/2:
214559d1ed5bSDimitry Andric   //   A declaration of an identifier for an object that has file scope without
214659d1ed5bSDimitry Andric   //   an initializer, and without a storage-class specifier or with the
214759d1ed5bSDimitry Andric   //   storage-class specifier static, constitutes a tentative definition.
214859d1ed5bSDimitry Andric   if (D->getInit() || D->hasExternalStorage())
214959d1ed5bSDimitry Andric     return true;
215059d1ed5bSDimitry Andric 
215159d1ed5bSDimitry Andric   // A variable cannot be both common and exist in a section.
215259d1ed5bSDimitry Andric   if (D->hasAttr<SectionAttr>())
215359d1ed5bSDimitry Andric     return true;
215459d1ed5bSDimitry Andric 
215559d1ed5bSDimitry Andric   // Thread local vars aren't considered common linkage.
215659d1ed5bSDimitry Andric   if (D->getTLSKind())
215759d1ed5bSDimitry Andric     return true;
215859d1ed5bSDimitry Andric 
215959d1ed5bSDimitry Andric   // Tentative definitions marked with WeakImportAttr are true definitions.
216059d1ed5bSDimitry Andric   if (D->hasAttr<WeakImportAttr>())
216159d1ed5bSDimitry Andric     return true;
216259d1ed5bSDimitry Andric 
216333956c43SDimitry Andric   // A variable cannot be both common and exist in a comdat.
216433956c43SDimitry Andric   if (shouldBeInCOMDAT(CGM, *D))
216533956c43SDimitry Andric     return true;
216633956c43SDimitry Andric 
216739d628a0SDimitry Andric   // Declarations with a required alignment do not have common linakge in MSVC
216839d628a0SDimitry Andric   // mode.
216933956c43SDimitry Andric   if (Context.getLangOpts().MSVCCompat) {
217033956c43SDimitry Andric     if (D->hasAttr<AlignedAttr>())
217139d628a0SDimitry Andric       return true;
217233956c43SDimitry Andric     QualType VarType = D->getType();
217333956c43SDimitry Andric     if (Context.isAlignmentRequired(VarType))
217433956c43SDimitry Andric       return true;
217533956c43SDimitry Andric 
217633956c43SDimitry Andric     if (const auto *RT = VarType->getAs<RecordType>()) {
217733956c43SDimitry Andric       const RecordDecl *RD = RT->getDecl();
217833956c43SDimitry Andric       for (const FieldDecl *FD : RD->fields()) {
217933956c43SDimitry Andric         if (FD->isBitField())
218033956c43SDimitry Andric           continue;
218133956c43SDimitry Andric         if (FD->hasAttr<AlignedAttr>())
218233956c43SDimitry Andric           return true;
218333956c43SDimitry Andric         if (Context.isAlignmentRequired(FD->getType()))
218433956c43SDimitry Andric           return true;
218533956c43SDimitry Andric       }
218633956c43SDimitry Andric     }
218733956c43SDimitry Andric   }
218839d628a0SDimitry Andric 
218959d1ed5bSDimitry Andric   return false;
219059d1ed5bSDimitry Andric }
219159d1ed5bSDimitry Andric 
219259d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
219359d1ed5bSDimitry Andric     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
21942754fe60SDimitry Andric   if (Linkage == GVA_Internal)
21952754fe60SDimitry Andric     return llvm::Function::InternalLinkage;
219659d1ed5bSDimitry Andric 
219759d1ed5bSDimitry Andric   if (D->hasAttr<WeakAttr>()) {
219859d1ed5bSDimitry Andric     if (IsConstantVariable)
219959d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakODRLinkage;
220059d1ed5bSDimitry Andric     else
220159d1ed5bSDimitry Andric       return llvm::GlobalVariable::WeakAnyLinkage;
220259d1ed5bSDimitry Andric   }
220359d1ed5bSDimitry Andric 
220459d1ed5bSDimitry Andric   // We are guaranteed to have a strong definition somewhere else,
220559d1ed5bSDimitry Andric   // so we can use available_externally linkage.
220659d1ed5bSDimitry Andric   if (Linkage == GVA_AvailableExternally)
220759d1ed5bSDimitry Andric     return llvm::Function::AvailableExternallyLinkage;
220859d1ed5bSDimitry Andric 
220959d1ed5bSDimitry Andric   // Note that Apple's kernel linker doesn't support symbol
221059d1ed5bSDimitry Andric   // coalescing, so we need to avoid linkonce and weak linkages there.
221159d1ed5bSDimitry Andric   // Normally, this means we just map to internal, but for explicit
221259d1ed5bSDimitry Andric   // instantiations we'll map to external.
221359d1ed5bSDimitry Andric 
221459d1ed5bSDimitry Andric   // In C++, the compiler has to emit a definition in every translation unit
221559d1ed5bSDimitry Andric   // that references the function.  We should use linkonce_odr because
221659d1ed5bSDimitry Andric   // a) if all references in this translation unit are optimized away, we
221759d1ed5bSDimitry Andric   // don't need to codegen it.  b) if the function persists, it needs to be
221859d1ed5bSDimitry Andric   // merged with other definitions. c) C++ has the ODR, so we know the
221959d1ed5bSDimitry Andric   // definition is dependable.
222059d1ed5bSDimitry Andric   if (Linkage == GVA_DiscardableODR)
222159d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
222259d1ed5bSDimitry Andric                                             : llvm::Function::InternalLinkage;
222359d1ed5bSDimitry Andric 
222459d1ed5bSDimitry Andric   // An explicit instantiation of a template has weak linkage, since
222559d1ed5bSDimitry Andric   // explicit instantiations can occur in multiple translation units
222659d1ed5bSDimitry Andric   // and must all be equivalent. However, we are not allowed to
222759d1ed5bSDimitry Andric   // throw away these explicit instantiations.
222859d1ed5bSDimitry Andric   if (Linkage == GVA_StrongODR)
222959d1ed5bSDimitry Andric     return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
223059d1ed5bSDimitry Andric                                             : llvm::Function::ExternalLinkage;
223159d1ed5bSDimitry Andric 
223259d1ed5bSDimitry Andric   // C++ doesn't have tentative definitions and thus cannot have common
223359d1ed5bSDimitry Andric   // linkage.
223459d1ed5bSDimitry Andric   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
223533956c43SDimitry Andric       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
223639d628a0SDimitry Andric                                  CodeGenOpts.NoCommon))
223759d1ed5bSDimitry Andric     return llvm::GlobalVariable::CommonLinkage;
223859d1ed5bSDimitry Andric 
2239f785676fSDimitry Andric   // selectany symbols are externally visible, so use weak instead of
2240f785676fSDimitry Andric   // linkonce.  MSVC optimizes away references to const selectany globals, so
2241f785676fSDimitry Andric   // all definitions should be the same and ODR linkage should be used.
2242f785676fSDimitry Andric   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
224359d1ed5bSDimitry Andric   if (D->hasAttr<SelectAnyAttr>())
2244f785676fSDimitry Andric     return llvm::GlobalVariable::WeakODRLinkage;
224559d1ed5bSDimitry Andric 
224659d1ed5bSDimitry Andric   // Otherwise, we have strong external linkage.
224759d1ed5bSDimitry Andric   assert(Linkage == GVA_StrongExternal);
22482754fe60SDimitry Andric   return llvm::GlobalVariable::ExternalLinkage;
22492754fe60SDimitry Andric }
22502754fe60SDimitry Andric 
225159d1ed5bSDimitry Andric llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
225259d1ed5bSDimitry Andric     const VarDecl *VD, bool IsConstant) {
225359d1ed5bSDimitry Andric   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
225459d1ed5bSDimitry Andric   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
225559d1ed5bSDimitry Andric }
225659d1ed5bSDimitry Andric 
2257139f7f9bSDimitry Andric /// Replace the uses of a function that was declared with a non-proto type.
2258139f7f9bSDimitry Andric /// We want to silently drop extra arguments from call sites
2259139f7f9bSDimitry Andric static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2260139f7f9bSDimitry Andric                                           llvm::Function *newFn) {
2261139f7f9bSDimitry Andric   // Fast path.
2262139f7f9bSDimitry Andric   if (old->use_empty()) return;
2263139f7f9bSDimitry Andric 
2264139f7f9bSDimitry Andric   llvm::Type *newRetTy = newFn->getReturnType();
2265139f7f9bSDimitry Andric   SmallVector<llvm::Value*, 4> newArgs;
2266139f7f9bSDimitry Andric 
2267139f7f9bSDimitry Andric   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2268139f7f9bSDimitry Andric          ui != ue; ) {
2269139f7f9bSDimitry Andric     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
227059d1ed5bSDimitry Andric     llvm::User *user = use->getUser();
2271139f7f9bSDimitry Andric 
2272139f7f9bSDimitry Andric     // Recognize and replace uses of bitcasts.  Most calls to
2273139f7f9bSDimitry Andric     // unprototyped functions will use bitcasts.
227459d1ed5bSDimitry Andric     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2275139f7f9bSDimitry Andric       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2276139f7f9bSDimitry Andric         replaceUsesOfNonProtoConstant(bitcast, newFn);
2277139f7f9bSDimitry Andric       continue;
2278139f7f9bSDimitry Andric     }
2279139f7f9bSDimitry Andric 
2280139f7f9bSDimitry Andric     // Recognize calls to the function.
2281139f7f9bSDimitry Andric     llvm::CallSite callSite(user);
2282139f7f9bSDimitry Andric     if (!callSite) continue;
228359d1ed5bSDimitry Andric     if (!callSite.isCallee(&*use)) continue;
2284139f7f9bSDimitry Andric 
2285139f7f9bSDimitry Andric     // If the return types don't match exactly, then we can't
2286139f7f9bSDimitry Andric     // transform this call unless it's dead.
2287139f7f9bSDimitry Andric     if (callSite->getType() != newRetTy && !callSite->use_empty())
2288139f7f9bSDimitry Andric       continue;
2289139f7f9bSDimitry Andric 
2290139f7f9bSDimitry Andric     // Get the call site's attribute list.
2291139f7f9bSDimitry Andric     SmallVector<llvm::AttributeSet, 8> newAttrs;
2292139f7f9bSDimitry Andric     llvm::AttributeSet oldAttrs = callSite.getAttributes();
2293139f7f9bSDimitry Andric 
2294139f7f9bSDimitry Andric     // Collect any return attributes from the call.
2295139f7f9bSDimitry Andric     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2296139f7f9bSDimitry Andric       newAttrs.push_back(
2297139f7f9bSDimitry Andric         llvm::AttributeSet::get(newFn->getContext(),
2298139f7f9bSDimitry Andric                                 oldAttrs.getRetAttributes()));
2299139f7f9bSDimitry Andric 
2300139f7f9bSDimitry Andric     // If the function was passed too few arguments, don't transform.
2301139f7f9bSDimitry Andric     unsigned newNumArgs = newFn->arg_size();
2302139f7f9bSDimitry Andric     if (callSite.arg_size() < newNumArgs) continue;
2303139f7f9bSDimitry Andric 
2304139f7f9bSDimitry Andric     // If extra arguments were passed, we silently drop them.
2305139f7f9bSDimitry Andric     // If any of the types mismatch, we don't transform.
2306139f7f9bSDimitry Andric     unsigned argNo = 0;
2307139f7f9bSDimitry Andric     bool dontTransform = false;
2308139f7f9bSDimitry Andric     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2309139f7f9bSDimitry Andric            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2310139f7f9bSDimitry Andric       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2311139f7f9bSDimitry Andric         dontTransform = true;
2312139f7f9bSDimitry Andric         break;
2313139f7f9bSDimitry Andric       }
2314139f7f9bSDimitry Andric 
2315139f7f9bSDimitry Andric       // Add any parameter attributes.
2316139f7f9bSDimitry Andric       if (oldAttrs.hasAttributes(argNo + 1))
2317139f7f9bSDimitry Andric         newAttrs.
2318139f7f9bSDimitry Andric           push_back(llvm::
2319139f7f9bSDimitry Andric                     AttributeSet::get(newFn->getContext(),
2320139f7f9bSDimitry Andric                                       oldAttrs.getParamAttributes(argNo + 1)));
2321139f7f9bSDimitry Andric     }
2322139f7f9bSDimitry Andric     if (dontTransform)
2323139f7f9bSDimitry Andric       continue;
2324139f7f9bSDimitry Andric 
2325139f7f9bSDimitry Andric     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2326139f7f9bSDimitry Andric       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2327139f7f9bSDimitry Andric                                                  oldAttrs.getFnAttributes()));
2328139f7f9bSDimitry Andric 
2329139f7f9bSDimitry Andric     // Okay, we can transform this.  Create the new call instruction and copy
2330139f7f9bSDimitry Andric     // over the required information.
2331139f7f9bSDimitry Andric     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2332139f7f9bSDimitry Andric 
2333139f7f9bSDimitry Andric     llvm::CallSite newCall;
2334139f7f9bSDimitry Andric     if (callSite.isCall()) {
2335139f7f9bSDimitry Andric       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2336139f7f9bSDimitry Andric                                        callSite.getInstruction());
2337139f7f9bSDimitry Andric     } else {
233859d1ed5bSDimitry Andric       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2339139f7f9bSDimitry Andric       newCall = llvm::InvokeInst::Create(newFn,
2340139f7f9bSDimitry Andric                                          oldInvoke->getNormalDest(),
2341139f7f9bSDimitry Andric                                          oldInvoke->getUnwindDest(),
2342139f7f9bSDimitry Andric                                          newArgs, "",
2343139f7f9bSDimitry Andric                                          callSite.getInstruction());
2344139f7f9bSDimitry Andric     }
2345139f7f9bSDimitry Andric     newArgs.clear(); // for the next iteration
2346139f7f9bSDimitry Andric 
2347139f7f9bSDimitry Andric     if (!newCall->getType()->isVoidTy())
2348139f7f9bSDimitry Andric       newCall->takeName(callSite.getInstruction());
2349139f7f9bSDimitry Andric     newCall.setAttributes(
2350139f7f9bSDimitry Andric                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2351139f7f9bSDimitry Andric     newCall.setCallingConv(callSite.getCallingConv());
2352139f7f9bSDimitry Andric 
2353139f7f9bSDimitry Andric     // Finally, remove the old call, replacing any uses with the new one.
2354139f7f9bSDimitry Andric     if (!callSite->use_empty())
2355139f7f9bSDimitry Andric       callSite->replaceAllUsesWith(newCall.getInstruction());
2356139f7f9bSDimitry Andric 
2357139f7f9bSDimitry Andric     // Copy debug location attached to CI.
235833956c43SDimitry Andric     if (callSite->getDebugLoc())
2359139f7f9bSDimitry Andric       newCall->setDebugLoc(callSite->getDebugLoc());
2360139f7f9bSDimitry Andric     callSite->eraseFromParent();
2361139f7f9bSDimitry Andric   }
2362139f7f9bSDimitry Andric }
2363139f7f9bSDimitry Andric 
2364f22ef01cSRoman Divacky /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2365f22ef01cSRoman Divacky /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2366f22ef01cSRoman Divacky /// existing call uses of the old function in the module, this adjusts them to
2367f22ef01cSRoman Divacky /// call the new function directly.
2368f22ef01cSRoman Divacky ///
2369f22ef01cSRoman Divacky /// This is not just a cleanup: the always_inline pass requires direct calls to
2370f22ef01cSRoman Divacky /// functions to be able to inline them.  If there is a bitcast in the way, it
2371f22ef01cSRoman Divacky /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2372f22ef01cSRoman Divacky /// run at -O0.
2373f22ef01cSRoman Divacky static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2374f22ef01cSRoman Divacky                                                       llvm::Function *NewFn) {
2375f22ef01cSRoman Divacky   // If we're redefining a global as a function, don't transform it.
2376139f7f9bSDimitry Andric   if (!isa<llvm::Function>(Old)) return;
2377f22ef01cSRoman Divacky 
2378139f7f9bSDimitry Andric   replaceUsesOfNonProtoConstant(Old, NewFn);
2379f22ef01cSRoman Divacky }
2380f22ef01cSRoman Divacky 
2381dff0c46cSDimitry Andric void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2382dff0c46cSDimitry Andric   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2383dff0c46cSDimitry Andric   // If we have a definition, this might be a deferred decl. If the
2384dff0c46cSDimitry Andric   // instantiation is explicit, make sure we emit it at the end.
2385dff0c46cSDimitry Andric   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2386dff0c46cSDimitry Andric     GetAddrOfGlobalVar(VD);
2387139f7f9bSDimitry Andric 
2388139f7f9bSDimitry Andric   EmitTopLevelDecl(VD);
2389dff0c46cSDimitry Andric }
2390f22ef01cSRoman Divacky 
239159d1ed5bSDimitry Andric void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
239259d1ed5bSDimitry Andric                                                  llvm::GlobalValue *GV) {
239359d1ed5bSDimitry Andric   const auto *D = cast<FunctionDecl>(GD.getDecl());
23943b0f4066SDimitry Andric 
23953b0f4066SDimitry Andric   // Compute the function info and LLVM type.
2396dff0c46cSDimitry Andric   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2397dff0c46cSDimitry Andric   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
23983b0f4066SDimitry Andric 
2399f22ef01cSRoman Divacky   // Get or create the prototype for the function.
240059d1ed5bSDimitry Andric   if (!GV) {
240159d1ed5bSDimitry Andric     llvm::Constant *C =
240259d1ed5bSDimitry Andric         GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
2403f22ef01cSRoman Divacky 
2404f22ef01cSRoman Divacky     // Strip off a bitcast if we got one back.
240559d1ed5bSDimitry Andric     if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
2406f22ef01cSRoman Divacky       assert(CE->getOpcode() == llvm::Instruction::BitCast);
240759d1ed5bSDimitry Andric       GV = cast<llvm::GlobalValue>(CE->getOperand(0));
240859d1ed5bSDimitry Andric     } else {
240959d1ed5bSDimitry Andric       GV = cast<llvm::GlobalValue>(C);
241059d1ed5bSDimitry Andric     }
2411f22ef01cSRoman Divacky   }
2412f22ef01cSRoman Divacky 
241359d1ed5bSDimitry Andric   if (!GV->isDeclaration()) {
2414f785676fSDimitry Andric     getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
241539d628a0SDimitry Andric     GlobalDecl OldGD = Manglings.lookup(GV->getName());
241639d628a0SDimitry Andric     if (auto *Prev = OldGD.getDecl())
241739d628a0SDimitry Andric       getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
2418f785676fSDimitry Andric     return;
2419f785676fSDimitry Andric   }
2420f22ef01cSRoman Divacky 
242159d1ed5bSDimitry Andric   if (GV->getType()->getElementType() != Ty) {
2422f22ef01cSRoman Divacky     // If the types mismatch then we have to rewrite the definition.
242359d1ed5bSDimitry Andric     assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
2424f22ef01cSRoman Divacky 
2425f22ef01cSRoman Divacky     // F is the Function* for the one with the wrong type, we must make a new
2426f22ef01cSRoman Divacky     // Function* and update everything that used F (a declaration) with the new
2427f22ef01cSRoman Divacky     // Function* (which will be a definition).
2428f22ef01cSRoman Divacky     //
2429f22ef01cSRoman Divacky     // This happens if there is a prototype for a function
2430f22ef01cSRoman Divacky     // (e.g. "int f()") and then a definition of a different type
2431f22ef01cSRoman Divacky     // (e.g. "int f(int x)").  Move the old function aside so that it
2432f22ef01cSRoman Divacky     // doesn't interfere with GetAddrOfFunction.
243359d1ed5bSDimitry Andric     GV->setName(StringRef());
243459d1ed5bSDimitry Andric     auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2435f22ef01cSRoman Divacky 
2436139f7f9bSDimitry Andric     // This might be an implementation of a function without a
2437139f7f9bSDimitry Andric     // prototype, in which case, try to do special replacement of
2438139f7f9bSDimitry Andric     // calls which match the new prototype.  The really key thing here
2439139f7f9bSDimitry Andric     // is that we also potentially drop arguments from the call site
2440139f7f9bSDimitry Andric     // so as to make a direct call, which makes the inliner happier
2441139f7f9bSDimitry Andric     // and suppresses a number of optimizer warnings (!) about
2442139f7f9bSDimitry Andric     // dropping arguments.
244359d1ed5bSDimitry Andric     if (!GV->use_empty()) {
244459d1ed5bSDimitry Andric       ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
244559d1ed5bSDimitry Andric       GV->removeDeadConstantUsers();
2446f22ef01cSRoman Divacky     }
2447f22ef01cSRoman Divacky 
2448f22ef01cSRoman Divacky     // Replace uses of F with the Function we will endow with a body.
244959d1ed5bSDimitry Andric     if (!GV->use_empty()) {
2450f22ef01cSRoman Divacky       llvm::Constant *NewPtrForOldDecl =
245159d1ed5bSDimitry Andric           llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
245259d1ed5bSDimitry Andric       GV->replaceAllUsesWith(NewPtrForOldDecl);
2453f22ef01cSRoman Divacky     }
2454f22ef01cSRoman Divacky 
2455f22ef01cSRoman Divacky     // Ok, delete the old function now, which is dead.
245659d1ed5bSDimitry Andric     GV->eraseFromParent();
2457f22ef01cSRoman Divacky 
245859d1ed5bSDimitry Andric     GV = NewFn;
2459f22ef01cSRoman Divacky   }
2460f22ef01cSRoman Divacky 
24612754fe60SDimitry Andric   // We need to set linkage and visibility on the function before
24622754fe60SDimitry Andric   // generating code for it because various parts of IR generation
24632754fe60SDimitry Andric   // want to propagate this information down (e.g. to local static
24642754fe60SDimitry Andric   // declarations).
246559d1ed5bSDimitry Andric   auto *Fn = cast<llvm::Function>(GV);
2466f785676fSDimitry Andric   setFunctionLinkage(GD, Fn);
246797bc6c73SDimitry Andric   setFunctionDLLStorageClass(GD, Fn);
2468f22ef01cSRoman Divacky 
246959d1ed5bSDimitry Andric   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
24702754fe60SDimitry Andric   setGlobalVisibility(Fn, D);
24712754fe60SDimitry Andric 
2472284c1978SDimitry Andric   MaybeHandleStaticInExternC(D, Fn);
2473284c1978SDimitry Andric 
247433956c43SDimitry Andric   maybeSetTrivialComdat(*D, *Fn);
247533956c43SDimitry Andric 
24763b0f4066SDimitry Andric   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2477f22ef01cSRoman Divacky 
247859d1ed5bSDimitry Andric   setFunctionDefinitionAttributes(D, Fn);
2479f22ef01cSRoman Divacky   SetLLVMFunctionAttributesForDefinition(D, Fn);
2480f22ef01cSRoman Divacky 
2481f22ef01cSRoman Divacky   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2482f22ef01cSRoman Divacky     AddGlobalCtor(Fn, CA->getPriority());
2483f22ef01cSRoman Divacky   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2484f22ef01cSRoman Divacky     AddGlobalDtor(Fn, DA->getPriority());
24856122f3e6SDimitry Andric   if (D->hasAttr<AnnotateAttr>())
24866122f3e6SDimitry Andric     AddGlobalAnnotations(D, Fn);
2487f22ef01cSRoman Divacky }
2488f22ef01cSRoman Divacky 
2489f22ef01cSRoman Divacky void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
249059d1ed5bSDimitry Andric   const auto *D = cast<ValueDecl>(GD.getDecl());
2491f22ef01cSRoman Divacky   const AliasAttr *AA = D->getAttr<AliasAttr>();
2492f22ef01cSRoman Divacky   assert(AA && "Not an alias?");
2493f22ef01cSRoman Divacky 
24946122f3e6SDimitry Andric   StringRef MangledName = getMangledName(GD);
2495f22ef01cSRoman Divacky 
24969a4b3118SDimitry Andric   if (AA->getAliasee() == MangledName) {
24979a4b3118SDimitry Andric     Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
24989a4b3118SDimitry Andric     return;
24999a4b3118SDimitry Andric   }
25009a4b3118SDimitry Andric 
2501f22ef01cSRoman Divacky   // If there is a definition in the module, then it wins over the alias.
2502f22ef01cSRoman Divacky   // This is dubious, but allow it to be safe.  Just ignore the alias.
2503f22ef01cSRoman Divacky   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2504f22ef01cSRoman Divacky   if (Entry && !Entry->isDeclaration())
2505f22ef01cSRoman Divacky     return;
2506f22ef01cSRoman Divacky 
2507f785676fSDimitry Andric   Aliases.push_back(GD);
2508f785676fSDimitry Andric 
25096122f3e6SDimitry Andric   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2510f22ef01cSRoman Divacky 
2511f22ef01cSRoman Divacky   // Create a reference to the named value.  This ensures that it is emitted
2512f22ef01cSRoman Divacky   // if a deferred decl.
2513f22ef01cSRoman Divacky   llvm::Constant *Aliasee;
2514f22ef01cSRoman Divacky   if (isa<llvm::FunctionType>(DeclTy))
25153861d79fSDimitry Andric     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
25162754fe60SDimitry Andric                                       /*ForVTable=*/false);
2517f22ef01cSRoman Divacky   else
2518f22ef01cSRoman Divacky     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
251959d1ed5bSDimitry Andric                                     llvm::PointerType::getUnqual(DeclTy),
252039d628a0SDimitry Andric                                     /*D=*/nullptr);
2521f22ef01cSRoman Divacky 
2522f22ef01cSRoman Divacky   // Create the new alias itself, but don't set a name yet.
252359d1ed5bSDimitry Andric   auto *GA = llvm::GlobalAlias::create(
252433956c43SDimitry Andric       cast<llvm::PointerType>(Aliasee->getType()),
252559d1ed5bSDimitry Andric       llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
2526f22ef01cSRoman Divacky 
2527f22ef01cSRoman Divacky   if (Entry) {
252859d1ed5bSDimitry Andric     if (GA->getAliasee() == Entry) {
252959d1ed5bSDimitry Andric       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
253059d1ed5bSDimitry Andric       return;
253159d1ed5bSDimitry Andric     }
253259d1ed5bSDimitry Andric 
2533f22ef01cSRoman Divacky     assert(Entry->isDeclaration());
2534f22ef01cSRoman Divacky 
2535f22ef01cSRoman Divacky     // If there is a declaration in the module, then we had an extern followed
2536f22ef01cSRoman Divacky     // by the alias, as in:
2537f22ef01cSRoman Divacky     //   extern int test6();
2538f22ef01cSRoman Divacky     //   ...
2539f22ef01cSRoman Divacky     //   int test6() __attribute__((alias("test7")));
2540f22ef01cSRoman Divacky     //
2541f22ef01cSRoman Divacky     // Remove it and replace uses of it with the alias.
2542f22ef01cSRoman Divacky     GA->takeName(Entry);
2543f22ef01cSRoman Divacky 
2544f22ef01cSRoman Divacky     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2545f22ef01cSRoman Divacky                                                           Entry->getType()));
2546f22ef01cSRoman Divacky     Entry->eraseFromParent();
2547f22ef01cSRoman Divacky   } else {
2548ffd1746dSEd Schouten     GA->setName(MangledName);
2549f22ef01cSRoman Divacky   }
2550f22ef01cSRoman Divacky 
2551f22ef01cSRoman Divacky   // Set attributes which are particular to an alias; this is a
2552f22ef01cSRoman Divacky   // specialization of the attributes which may be set on a global
2553f22ef01cSRoman Divacky   // variable/function.
255439d628a0SDimitry Andric   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
25553b0f4066SDimitry Andric       D->isWeakImported()) {
2556f22ef01cSRoman Divacky     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2557f22ef01cSRoman Divacky   }
2558f22ef01cSRoman Divacky 
255939d628a0SDimitry Andric   if (const auto *VD = dyn_cast<VarDecl>(D))
256039d628a0SDimitry Andric     if (VD->getTLSKind())
256139d628a0SDimitry Andric       setTLSMode(GA, *VD);
256239d628a0SDimitry Andric 
256339d628a0SDimitry Andric   setAliasAttributes(D, GA);
2564f22ef01cSRoman Divacky }
2565f22ef01cSRoman Divacky 
256617a519f9SDimitry Andric llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
25676122f3e6SDimitry Andric                                             ArrayRef<llvm::Type*> Tys) {
256817a519f9SDimitry Andric   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
256917a519f9SDimitry Andric                                          Tys);
2570f22ef01cSRoman Divacky }
2571f22ef01cSRoman Divacky 
257233956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
257333956c43SDimitry Andric GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
257433956c43SDimitry Andric                          const StringLiteral *Literal, bool TargetIsLSB,
257533956c43SDimitry Andric                          bool &IsUTF16, unsigned &StringLength) {
25766122f3e6SDimitry Andric   StringRef String = Literal->getString();
2577e580952dSDimitry Andric   unsigned NumBytes = String.size();
2578f22ef01cSRoman Divacky 
2579f22ef01cSRoman Divacky   // Check for simple case.
2580f22ef01cSRoman Divacky   if (!Literal->containsNonAsciiOrNull()) {
2581f22ef01cSRoman Divacky     StringLength = NumBytes;
258239d628a0SDimitry Andric     return *Map.insert(std::make_pair(String, nullptr)).first;
2583f22ef01cSRoman Divacky   }
2584f22ef01cSRoman Divacky 
2585dff0c46cSDimitry Andric   // Otherwise, convert the UTF8 literals into a string of shorts.
2586dff0c46cSDimitry Andric   IsUTF16 = true;
2587dff0c46cSDimitry Andric 
2588dff0c46cSDimitry Andric   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
25893861d79fSDimitry Andric   const UTF8 *FromPtr = (const UTF8 *)String.data();
2590f22ef01cSRoman Divacky   UTF16 *ToPtr = &ToBuf[0];
2591f22ef01cSRoman Divacky 
25922754fe60SDimitry Andric   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2593f22ef01cSRoman Divacky                            &ToPtr, ToPtr + NumBytes,
2594f22ef01cSRoman Divacky                            strictConversion);
2595f22ef01cSRoman Divacky 
2596f22ef01cSRoman Divacky   // ConvertUTF8toUTF16 returns the length in ToPtr.
2597f22ef01cSRoman Divacky   StringLength = ToPtr - &ToBuf[0];
2598f22ef01cSRoman Divacky 
2599dff0c46cSDimitry Andric   // Add an explicit null.
2600dff0c46cSDimitry Andric   *ToPtr = 0;
260139d628a0SDimitry Andric   return *Map.insert(std::make_pair(
260239d628a0SDimitry Andric                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
260339d628a0SDimitry Andric                                    (StringLength + 1) * 2),
260439d628a0SDimitry Andric                          nullptr)).first;
2605f22ef01cSRoman Divacky }
2606f22ef01cSRoman Divacky 
260733956c43SDimitry Andric static llvm::StringMapEntry<llvm::GlobalVariable *> &
260833956c43SDimitry Andric GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
260933956c43SDimitry Andric                        const StringLiteral *Literal, unsigned &StringLength) {
26106122f3e6SDimitry Andric   StringRef String = Literal->getString();
2611bd5abe19SDimitry Andric   StringLength = String.size();
261239d628a0SDimitry Andric   return *Map.insert(std::make_pair(String, nullptr)).first;
2613bd5abe19SDimitry Andric }
2614bd5abe19SDimitry Andric 
2615f22ef01cSRoman Divacky llvm::Constant *
2616f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2617f22ef01cSRoman Divacky   unsigned StringLength = 0;
2618f22ef01cSRoman Divacky   bool isUTF16 = false;
261933956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2620f22ef01cSRoman Divacky       GetConstantCFStringEntry(CFConstantStringMap, Literal,
262133956c43SDimitry Andric                                getDataLayout().isLittleEndian(), isUTF16,
262233956c43SDimitry Andric                                StringLength);
2623f22ef01cSRoman Divacky 
262439d628a0SDimitry Andric   if (auto *C = Entry.second)
2625f22ef01cSRoman Divacky     return C;
2626f22ef01cSRoman Divacky 
2627dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2628f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
2629284c1978SDimitry Andric   llvm::Value *V;
2630f22ef01cSRoman Divacky 
2631f22ef01cSRoman Divacky   // If we don't already have it, get __CFConstantStringClassReference.
2632f22ef01cSRoman Divacky   if (!CFConstantStringClassRef) {
26336122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2634f22ef01cSRoman Divacky     Ty = llvm::ArrayType::get(Ty, 0);
2635f22ef01cSRoman Divacky     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2636f22ef01cSRoman Divacky                                            "__CFConstantStringClassReference");
2637f22ef01cSRoman Divacky     // Decay array -> ptr
263833956c43SDimitry Andric     V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
2639284c1978SDimitry Andric     CFConstantStringClassRef = V;
2640f22ef01cSRoman Divacky   }
2641284c1978SDimitry Andric   else
2642284c1978SDimitry Andric     V = CFConstantStringClassRef;
2643f22ef01cSRoman Divacky 
2644f22ef01cSRoman Divacky   QualType CFTy = getContext().getCFConstantStringType();
2645f22ef01cSRoman Divacky 
264659d1ed5bSDimitry Andric   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2647f22ef01cSRoman Divacky 
2648dff0c46cSDimitry Andric   llvm::Constant *Fields[4];
2649f22ef01cSRoman Divacky 
2650f22ef01cSRoman Divacky   // Class pointer.
2651284c1978SDimitry Andric   Fields[0] = cast<llvm::ConstantExpr>(V);
2652f22ef01cSRoman Divacky 
2653f22ef01cSRoman Divacky   // Flags.
26546122f3e6SDimitry Andric   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2655f22ef01cSRoman Divacky   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2656f22ef01cSRoman Divacky     llvm::ConstantInt::get(Ty, 0x07C8);
2657f22ef01cSRoman Divacky 
2658f22ef01cSRoman Divacky   // String pointer.
265959d1ed5bSDimitry Andric   llvm::Constant *C = nullptr;
2660dff0c46cSDimitry Andric   if (isUTF16) {
266139d628a0SDimitry Andric     ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
266239d628a0SDimitry Andric         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
266339d628a0SDimitry Andric         Entry.first().size() / 2);
2664dff0c46cSDimitry Andric     C = llvm::ConstantDataArray::get(VMContext, Arr);
2665dff0c46cSDimitry Andric   } else {
266639d628a0SDimitry Andric     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
2667dff0c46cSDimitry Andric   }
2668f22ef01cSRoman Divacky 
2669dff0c46cSDimitry Andric   // Note: -fwritable-strings doesn't make the backing store strings of
2670dff0c46cSDimitry Andric   // CFStrings writable. (See <rdar://problem/10657500>)
267159d1ed5bSDimitry Andric   auto *GV =
2672dff0c46cSDimitry Andric       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
267359d1ed5bSDimitry Andric                                llvm::GlobalValue::PrivateLinkage, C, ".str");
26742754fe60SDimitry Andric   GV->setUnnamedAddr(true);
2675284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
2676284c1978SDimitry Andric   // of the string is via this class initializer.
267759d1ed5bSDimitry Andric   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
267859d1ed5bSDimitry Andric   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
267959d1ed5bSDimitry Andric   // that changes the section it ends in, which surprises ld64.
2680f22ef01cSRoman Divacky   if (isUTF16) {
2681f22ef01cSRoman Divacky     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2682f22ef01cSRoman Divacky     GV->setAlignment(Align.getQuantity());
268359d1ed5bSDimitry Andric     GV->setSection("__TEXT,__ustring");
26843b0f4066SDimitry Andric   } else {
26853b0f4066SDimitry Andric     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
26863b0f4066SDimitry Andric     GV->setAlignment(Align.getQuantity());
268759d1ed5bSDimitry Andric     GV->setSection("__TEXT,__cstring,cstring_literals");
2688f22ef01cSRoman Divacky   }
2689dff0c46cSDimitry Andric 
2690dff0c46cSDimitry Andric   // String.
269133956c43SDimitry Andric   Fields[2] =
269233956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2693f22ef01cSRoman Divacky 
2694dff0c46cSDimitry Andric   if (isUTF16)
2695dff0c46cSDimitry Andric     // Cast the UTF16 string to the correct type.
2696dff0c46cSDimitry Andric     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2697dff0c46cSDimitry Andric 
2698f22ef01cSRoman Divacky   // String length.
2699f22ef01cSRoman Divacky   Ty = getTypes().ConvertType(getContext().LongTy);
2700f22ef01cSRoman Divacky   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2701f22ef01cSRoman Divacky 
2702f22ef01cSRoman Divacky   // The struct.
2703f22ef01cSRoman Divacky   C = llvm::ConstantStruct::get(STy, Fields);
2704f22ef01cSRoman Divacky   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2705f22ef01cSRoman Divacky                                 llvm::GlobalVariable::PrivateLinkage, C,
2706f22ef01cSRoman Divacky                                 "_unnamed_cfstring_");
270759d1ed5bSDimitry Andric   GV->setSection("__DATA,__cfstring");
270839d628a0SDimitry Andric   Entry.second = GV;
2709f22ef01cSRoman Divacky 
2710f22ef01cSRoman Divacky   return GV;
2711f22ef01cSRoman Divacky }
2712f22ef01cSRoman Divacky 
271333956c43SDimitry Andric llvm::GlobalVariable *
27142754fe60SDimitry Andric CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2715f22ef01cSRoman Divacky   unsigned StringLength = 0;
271633956c43SDimitry Andric   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2717bd5abe19SDimitry Andric       GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2718f22ef01cSRoman Divacky 
271939d628a0SDimitry Andric   if (auto *C = Entry.second)
2720f22ef01cSRoman Divacky     return C;
2721f22ef01cSRoman Divacky 
2722dff0c46cSDimitry Andric   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2723f22ef01cSRoman Divacky   llvm::Constant *Zeros[] = { Zero, Zero };
2724284c1978SDimitry Andric   llvm::Value *V;
2725f22ef01cSRoman Divacky   // If we don't already have it, get _NSConstantStringClassReference.
27262754fe60SDimitry Andric   if (!ConstantStringClassRef) {
2727dff0c46cSDimitry Andric     std::string StringClass(getLangOpts().ObjCConstantStringClass);
27286122f3e6SDimitry Andric     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
27292754fe60SDimitry Andric     llvm::Constant *GV;
27307ae0e2c9SDimitry Andric     if (LangOpts.ObjCRuntime.isNonFragile()) {
2731bd5abe19SDimitry Andric       std::string str =
2732bd5abe19SDimitry Andric         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2733bd5abe19SDimitry Andric                             : "OBJC_CLASS_$_" + StringClass;
2734bd5abe19SDimitry Andric       GV = getObjCRuntime().GetClassGlobal(str);
2735bd5abe19SDimitry Andric       // Make sure the result is of the correct type.
27366122f3e6SDimitry Andric       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2737284c1978SDimitry Andric       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2738284c1978SDimitry Andric       ConstantStringClassRef = V;
2739bd5abe19SDimitry Andric     } else {
2740bd5abe19SDimitry Andric       std::string str =
2741bd5abe19SDimitry Andric         StringClass.empty() ? "_NSConstantStringClassReference"
2742bd5abe19SDimitry Andric                             : "_" + StringClass + "ClassReference";
27436122f3e6SDimitry Andric       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2744bd5abe19SDimitry Andric       GV = CreateRuntimeVariable(PTy, str);
2745f22ef01cSRoman Divacky       // Decay array -> ptr
274633956c43SDimitry Andric       V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
2747284c1978SDimitry Andric       ConstantStringClassRef = V;
2748f22ef01cSRoman Divacky     }
274933956c43SDimitry Andric   } else
2750284c1978SDimitry Andric     V = ConstantStringClassRef;
2751f22ef01cSRoman Divacky 
27526122f3e6SDimitry Andric   if (!NSConstantStringType) {
27536122f3e6SDimitry Andric     // Construct the type for a constant NSString.
275459d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
27556122f3e6SDimitry Andric     D->startDefinition();
2756f22ef01cSRoman Divacky 
27576122f3e6SDimitry Andric     QualType FieldTypes[3];
27586122f3e6SDimitry Andric 
27596122f3e6SDimitry Andric     // const int *isa;
27606122f3e6SDimitry Andric     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
27616122f3e6SDimitry Andric     // const char *str;
27626122f3e6SDimitry Andric     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
27636122f3e6SDimitry Andric     // unsigned int length;
27646122f3e6SDimitry Andric     FieldTypes[2] = Context.UnsignedIntTy;
27656122f3e6SDimitry Andric 
27666122f3e6SDimitry Andric     // Create fields
27676122f3e6SDimitry Andric     for (unsigned i = 0; i < 3; ++i) {
27686122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context, D,
27696122f3e6SDimitry Andric                                            SourceLocation(),
277059d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
277159d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
277259d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
27736122f3e6SDimitry Andric                                            /*Mutable=*/false,
27747ae0e2c9SDimitry Andric                                            ICIS_NoInit);
27756122f3e6SDimitry Andric       Field->setAccess(AS_public);
27766122f3e6SDimitry Andric       D->addDecl(Field);
27776122f3e6SDimitry Andric     }
27786122f3e6SDimitry Andric 
27796122f3e6SDimitry Andric     D->completeDefinition();
27806122f3e6SDimitry Andric     QualType NSTy = Context.getTagDeclType(D);
27816122f3e6SDimitry Andric     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
27826122f3e6SDimitry Andric   }
2783f22ef01cSRoman Divacky 
2784dff0c46cSDimitry Andric   llvm::Constant *Fields[3];
2785f22ef01cSRoman Divacky 
2786f22ef01cSRoman Divacky   // Class pointer.
2787284c1978SDimitry Andric   Fields[0] = cast<llvm::ConstantExpr>(V);
2788f22ef01cSRoman Divacky 
2789f22ef01cSRoman Divacky   // String pointer.
2790dff0c46cSDimitry Andric   llvm::Constant *C =
279139d628a0SDimitry Andric       llvm::ConstantDataArray::getString(VMContext, Entry.first());
2792f22ef01cSRoman Divacky 
2793f22ef01cSRoman Divacky   llvm::GlobalValue::LinkageTypes Linkage;
2794f22ef01cSRoman Divacky   bool isConstant;
2795f22ef01cSRoman Divacky   Linkage = llvm::GlobalValue::PrivateLinkage;
2796dff0c46cSDimitry Andric   isConstant = !LangOpts.WritableStrings;
2797f22ef01cSRoman Divacky 
279859d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
279959d1ed5bSDimitry Andric                                       Linkage, C, ".str");
28002754fe60SDimitry Andric   GV->setUnnamedAddr(true);
2801284c1978SDimitry Andric   // Don't enforce the target's minimum global alignment, since the only use
2802284c1978SDimitry Andric   // of the string is via this class initializer.
28033b0f4066SDimitry Andric   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
28043b0f4066SDimitry Andric   GV->setAlignment(Align.getQuantity());
280533956c43SDimitry Andric   Fields[1] =
280633956c43SDimitry Andric       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2807f22ef01cSRoman Divacky 
2808f22ef01cSRoman Divacky   // String length.
28096122f3e6SDimitry Andric   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2810f22ef01cSRoman Divacky   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2811f22ef01cSRoman Divacky 
2812f22ef01cSRoman Divacky   // The struct.
28136122f3e6SDimitry Andric   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2814f22ef01cSRoman Divacky   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2815f22ef01cSRoman Divacky                                 llvm::GlobalVariable::PrivateLinkage, C,
2816f22ef01cSRoman Divacky                                 "_unnamed_nsstring_");
281759d1ed5bSDimitry Andric   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
281859d1ed5bSDimitry Andric   const char *NSStringNonFragileABISection =
281959d1ed5bSDimitry Andric       "__DATA,__objc_stringobj,regular,no_dead_strip";
2820f22ef01cSRoman Divacky   // FIXME. Fix section.
282159d1ed5bSDimitry Andric   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
282259d1ed5bSDimitry Andric                      ? NSStringNonFragileABISection
282359d1ed5bSDimitry Andric                      : NSStringSection);
282439d628a0SDimitry Andric   Entry.second = GV;
2825f22ef01cSRoman Divacky 
2826f22ef01cSRoman Divacky   return GV;
2827f22ef01cSRoman Divacky }
2828f22ef01cSRoman Divacky 
28296122f3e6SDimitry Andric QualType CodeGenModule::getObjCFastEnumerationStateType() {
28306122f3e6SDimitry Andric   if (ObjCFastEnumerationStateType.isNull()) {
283159d1ed5bSDimitry Andric     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
28326122f3e6SDimitry Andric     D->startDefinition();
28336122f3e6SDimitry Andric 
28346122f3e6SDimitry Andric     QualType FieldTypes[] = {
28356122f3e6SDimitry Andric       Context.UnsignedLongTy,
28366122f3e6SDimitry Andric       Context.getPointerType(Context.getObjCIdType()),
28376122f3e6SDimitry Andric       Context.getPointerType(Context.UnsignedLongTy),
28386122f3e6SDimitry Andric       Context.getConstantArrayType(Context.UnsignedLongTy,
28396122f3e6SDimitry Andric                            llvm::APInt(32, 5), ArrayType::Normal, 0)
28406122f3e6SDimitry Andric     };
28416122f3e6SDimitry Andric 
28426122f3e6SDimitry Andric     for (size_t i = 0; i < 4; ++i) {
28436122f3e6SDimitry Andric       FieldDecl *Field = FieldDecl::Create(Context,
28446122f3e6SDimitry Andric                                            D,
28456122f3e6SDimitry Andric                                            SourceLocation(),
284659d1ed5bSDimitry Andric                                            SourceLocation(), nullptr,
284759d1ed5bSDimitry Andric                                            FieldTypes[i], /*TInfo=*/nullptr,
284859d1ed5bSDimitry Andric                                            /*BitWidth=*/nullptr,
28496122f3e6SDimitry Andric                                            /*Mutable=*/false,
28507ae0e2c9SDimitry Andric                                            ICIS_NoInit);
28516122f3e6SDimitry Andric       Field->setAccess(AS_public);
28526122f3e6SDimitry Andric       D->addDecl(Field);
28536122f3e6SDimitry Andric     }
28546122f3e6SDimitry Andric 
28556122f3e6SDimitry Andric     D->completeDefinition();
28566122f3e6SDimitry Andric     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
28576122f3e6SDimitry Andric   }
28586122f3e6SDimitry Andric 
28596122f3e6SDimitry Andric   return ObjCFastEnumerationStateType;
28606122f3e6SDimitry Andric }
28616122f3e6SDimitry Andric 
2862dff0c46cSDimitry Andric llvm::Constant *
2863dff0c46cSDimitry Andric CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2864dff0c46cSDimitry Andric   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2865f22ef01cSRoman Divacky 
2866dff0c46cSDimitry Andric   // Don't emit it as the address of the string, emit the string data itself
2867dff0c46cSDimitry Andric   // as an inline array.
2868dff0c46cSDimitry Andric   if (E->getCharByteWidth() == 1) {
2869dff0c46cSDimitry Andric     SmallString<64> Str(E->getString());
2870f22ef01cSRoman Divacky 
2871dff0c46cSDimitry Andric     // Resize the string to the right size, which is indicated by its type.
2872dff0c46cSDimitry Andric     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2873dff0c46cSDimitry Andric     Str.resize(CAT->getSize().getZExtValue());
2874dff0c46cSDimitry Andric     return llvm::ConstantDataArray::getString(VMContext, Str, false);
28756122f3e6SDimitry Andric   }
2876f22ef01cSRoman Divacky 
287759d1ed5bSDimitry Andric   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2878dff0c46cSDimitry Andric   llvm::Type *ElemTy = AType->getElementType();
2879dff0c46cSDimitry Andric   unsigned NumElements = AType->getNumElements();
2880f22ef01cSRoman Divacky 
2881dff0c46cSDimitry Andric   // Wide strings have either 2-byte or 4-byte elements.
2882dff0c46cSDimitry Andric   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2883dff0c46cSDimitry Andric     SmallVector<uint16_t, 32> Elements;
2884dff0c46cSDimitry Andric     Elements.reserve(NumElements);
2885dff0c46cSDimitry Andric 
2886dff0c46cSDimitry Andric     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2887dff0c46cSDimitry Andric       Elements.push_back(E->getCodeUnit(i));
2888dff0c46cSDimitry Andric     Elements.resize(NumElements);
2889dff0c46cSDimitry Andric     return llvm::ConstantDataArray::get(VMContext, Elements);
2890dff0c46cSDimitry Andric   }
2891dff0c46cSDimitry Andric 
2892dff0c46cSDimitry Andric   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2893dff0c46cSDimitry Andric   SmallVector<uint32_t, 32> Elements;
2894dff0c46cSDimitry Andric   Elements.reserve(NumElements);
2895dff0c46cSDimitry Andric 
2896dff0c46cSDimitry Andric   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2897dff0c46cSDimitry Andric     Elements.push_back(E->getCodeUnit(i));
2898dff0c46cSDimitry Andric   Elements.resize(NumElements);
2899dff0c46cSDimitry Andric   return llvm::ConstantDataArray::get(VMContext, Elements);
2900f22ef01cSRoman Divacky }
2901f22ef01cSRoman Divacky 
290259d1ed5bSDimitry Andric static llvm::GlobalVariable *
290359d1ed5bSDimitry Andric GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
290459d1ed5bSDimitry Andric                       CodeGenModule &CGM, StringRef GlobalName,
290559d1ed5bSDimitry Andric                       unsigned Alignment) {
290659d1ed5bSDimitry Andric   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
290759d1ed5bSDimitry Andric   unsigned AddrSpace = 0;
290859d1ed5bSDimitry Andric   if (CGM.getLangOpts().OpenCL)
290959d1ed5bSDimitry Andric     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2910dff0c46cSDimitry Andric 
291133956c43SDimitry Andric   llvm::Module &M = CGM.getModule();
291259d1ed5bSDimitry Andric   // Create a global variable for this string
291359d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
291433956c43SDimitry Andric       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
291533956c43SDimitry Andric       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
291659d1ed5bSDimitry Andric   GV->setAlignment(Alignment);
291759d1ed5bSDimitry Andric   GV->setUnnamedAddr(true);
291833956c43SDimitry Andric   if (GV->isWeakForLinker()) {
291933956c43SDimitry Andric     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
292033956c43SDimitry Andric     GV->setComdat(M.getOrInsertComdat(GV->getName()));
292133956c43SDimitry Andric   }
292233956c43SDimitry Andric 
292359d1ed5bSDimitry Andric   return GV;
2924f22ef01cSRoman Divacky }
2925dff0c46cSDimitry Andric 
292659d1ed5bSDimitry Andric /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
292759d1ed5bSDimitry Andric /// constant array for the given string literal.
292859d1ed5bSDimitry Andric llvm::GlobalVariable *
292939d628a0SDimitry Andric CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
293039d628a0SDimitry Andric                                                   StringRef Name) {
293159d1ed5bSDimitry Andric   auto Alignment =
293259d1ed5bSDimitry Andric       getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
2933dff0c46cSDimitry Andric 
293459d1ed5bSDimitry Andric   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
293559d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
293659d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
293759d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
293859d1ed5bSDimitry Andric     if (auto GV = *Entry) {
293959d1ed5bSDimitry Andric       if (Alignment > GV->getAlignment())
294059d1ed5bSDimitry Andric         GV->setAlignment(Alignment);
294159d1ed5bSDimitry Andric       return GV;
294259d1ed5bSDimitry Andric     }
294359d1ed5bSDimitry Andric   }
294459d1ed5bSDimitry Andric 
294559d1ed5bSDimitry Andric   SmallString<256> MangledNameBuffer;
294659d1ed5bSDimitry Andric   StringRef GlobalVariableName;
294759d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes LT;
294859d1ed5bSDimitry Andric 
294959d1ed5bSDimitry Andric   // Mangle the string literal if the ABI allows for it.  However, we cannot
295059d1ed5bSDimitry Andric   // do this if  we are compiling with ASan or -fwritable-strings because they
295159d1ed5bSDimitry Andric   // rely on strings having normal linkage.
295239d628a0SDimitry Andric   if (!LangOpts.WritableStrings &&
295339d628a0SDimitry Andric       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
295459d1ed5bSDimitry Andric       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
295559d1ed5bSDimitry Andric     llvm::raw_svector_ostream Out(MangledNameBuffer);
295659d1ed5bSDimitry Andric     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
295759d1ed5bSDimitry Andric     Out.flush();
295859d1ed5bSDimitry Andric 
295959d1ed5bSDimitry Andric     LT = llvm::GlobalValue::LinkOnceODRLinkage;
296059d1ed5bSDimitry Andric     GlobalVariableName = MangledNameBuffer;
296159d1ed5bSDimitry Andric   } else {
296259d1ed5bSDimitry Andric     LT = llvm::GlobalValue::PrivateLinkage;
296339d628a0SDimitry Andric     GlobalVariableName = Name;
296459d1ed5bSDimitry Andric   }
296559d1ed5bSDimitry Andric 
296659d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
296759d1ed5bSDimitry Andric   if (Entry)
296859d1ed5bSDimitry Andric     *Entry = GV;
296959d1ed5bSDimitry Andric 
297039d628a0SDimitry Andric   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
297139d628a0SDimitry Andric                                   QualType());
2972dff0c46cSDimitry Andric   return GV;
2973f22ef01cSRoman Divacky }
2974f22ef01cSRoman Divacky 
2975f22ef01cSRoman Divacky /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2976f22ef01cSRoman Divacky /// array for the given ObjCEncodeExpr node.
297759d1ed5bSDimitry Andric llvm::GlobalVariable *
2978f22ef01cSRoman Divacky CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2979f22ef01cSRoman Divacky   std::string Str;
2980f22ef01cSRoman Divacky   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2981f22ef01cSRoman Divacky 
2982f22ef01cSRoman Divacky   return GetAddrOfConstantCString(Str);
2983f22ef01cSRoman Divacky }
2984f22ef01cSRoman Divacky 
298559d1ed5bSDimitry Andric /// GetAddrOfConstantCString - Returns a pointer to a character array containing
298659d1ed5bSDimitry Andric /// the literal and a terminating '\0' character.
298759d1ed5bSDimitry Andric /// The result has pointer to array type.
298859d1ed5bSDimitry Andric llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
298959d1ed5bSDimitry Andric     const std::string &Str, const char *GlobalName, unsigned Alignment) {
299059d1ed5bSDimitry Andric   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
299159d1ed5bSDimitry Andric   if (Alignment == 0) {
299259d1ed5bSDimitry Andric     Alignment = getContext()
299359d1ed5bSDimitry Andric                     .getAlignOfGlobalVarInChars(getContext().CharTy)
299459d1ed5bSDimitry Andric                     .getQuantity();
2995f22ef01cSRoman Divacky   }
2996f22ef01cSRoman Divacky 
299759d1ed5bSDimitry Andric   llvm::Constant *C =
299859d1ed5bSDimitry Andric       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
299959d1ed5bSDimitry Andric 
300059d1ed5bSDimitry Andric   // Don't share any string literals if strings aren't constant.
300159d1ed5bSDimitry Andric   llvm::GlobalVariable **Entry = nullptr;
300259d1ed5bSDimitry Andric   if (!LangOpts.WritableStrings) {
300359d1ed5bSDimitry Andric     Entry = &ConstantStringMap[C];
300459d1ed5bSDimitry Andric     if (auto GV = *Entry) {
300559d1ed5bSDimitry Andric       if (Alignment > GV->getAlignment())
300659d1ed5bSDimitry Andric         GV->setAlignment(Alignment);
300759d1ed5bSDimitry Andric       return GV;
300859d1ed5bSDimitry Andric     }
300959d1ed5bSDimitry Andric   }
301059d1ed5bSDimitry Andric 
3011f22ef01cSRoman Divacky   // Get the default prefix if a name wasn't specified.
3012f22ef01cSRoman Divacky   if (!GlobalName)
3013f22ef01cSRoman Divacky     GlobalName = ".str";
3014f22ef01cSRoman Divacky   // Create a global variable for this.
301559d1ed5bSDimitry Andric   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
301659d1ed5bSDimitry Andric                                   GlobalName, Alignment);
301759d1ed5bSDimitry Andric   if (Entry)
301859d1ed5bSDimitry Andric     *Entry = GV;
30196122f3e6SDimitry Andric   return GV;
3020f22ef01cSRoman Divacky }
3021f22ef01cSRoman Divacky 
3022f785676fSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
3023f785676fSDimitry Andric     const MaterializeTemporaryExpr *E, const Expr *Init) {
3024f785676fSDimitry Andric   assert((E->getStorageDuration() == SD_Static ||
3025f785676fSDimitry Andric           E->getStorageDuration() == SD_Thread) && "not a global temporary");
302659d1ed5bSDimitry Andric   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3027f785676fSDimitry Andric 
3028f785676fSDimitry Andric   // If we're not materializing a subobject of the temporary, keep the
3029f785676fSDimitry Andric   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3030f785676fSDimitry Andric   QualType MaterializedType = Init->getType();
3031f785676fSDimitry Andric   if (Init == E->GetTemporaryExpr())
3032f785676fSDimitry Andric     MaterializedType = E->getType();
3033f785676fSDimitry Andric 
3034f785676fSDimitry Andric   llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
3035f785676fSDimitry Andric   if (Slot)
3036f785676fSDimitry Andric     return Slot;
3037f785676fSDimitry Andric 
3038f785676fSDimitry Andric   // FIXME: If an externally-visible declaration extends multiple temporaries,
3039f785676fSDimitry Andric   // we need to give each temporary the same name in every translation unit (and
3040f785676fSDimitry Andric   // we also need to make the temporaries externally-visible).
3041f785676fSDimitry Andric   SmallString<256> Name;
3042f785676fSDimitry Andric   llvm::raw_svector_ostream Out(Name);
304359d1ed5bSDimitry Andric   getCXXABI().getMangleContext().mangleReferenceTemporary(
304459d1ed5bSDimitry Andric       VD, E->getManglingNumber(), Out);
3045f785676fSDimitry Andric   Out.flush();
3046f785676fSDimitry Andric 
304759d1ed5bSDimitry Andric   APValue *Value = nullptr;
3048f785676fSDimitry Andric   if (E->getStorageDuration() == SD_Static) {
3049f785676fSDimitry Andric     // We might have a cached constant initializer for this temporary. Note
3050f785676fSDimitry Andric     // that this might have a different value from the value computed by
3051f785676fSDimitry Andric     // evaluating the initializer if the surrounding constant expression
3052f785676fSDimitry Andric     // modifies the temporary.
3053f785676fSDimitry Andric     Value = getContext().getMaterializedTemporaryValue(E, false);
3054f785676fSDimitry Andric     if (Value && Value->isUninit())
305559d1ed5bSDimitry Andric       Value = nullptr;
3056f785676fSDimitry Andric   }
3057f785676fSDimitry Andric 
3058f785676fSDimitry Andric   // Try evaluating it now, it might have a constant initializer.
3059f785676fSDimitry Andric   Expr::EvalResult EvalResult;
3060f785676fSDimitry Andric   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3061f785676fSDimitry Andric       !EvalResult.hasSideEffects())
3062f785676fSDimitry Andric     Value = &EvalResult.Val;
3063f785676fSDimitry Andric 
306459d1ed5bSDimitry Andric   llvm::Constant *InitialValue = nullptr;
3065f785676fSDimitry Andric   bool Constant = false;
3066f785676fSDimitry Andric   llvm::Type *Type;
3067f785676fSDimitry Andric   if (Value) {
3068f785676fSDimitry Andric     // The temporary has a constant initializer, use it.
306959d1ed5bSDimitry Andric     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3070f785676fSDimitry Andric     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3071f785676fSDimitry Andric     Type = InitialValue->getType();
3072f785676fSDimitry Andric   } else {
3073f785676fSDimitry Andric     // No initializer, the initialization will be provided when we
3074f785676fSDimitry Andric     // initialize the declaration which performed lifetime extension.
3075f785676fSDimitry Andric     Type = getTypes().ConvertTypeForMem(MaterializedType);
3076f785676fSDimitry Andric   }
3077f785676fSDimitry Andric 
3078f785676fSDimitry Andric   // Create a global variable for this lifetime-extended temporary.
307959d1ed5bSDimitry Andric   llvm::GlobalValue::LinkageTypes Linkage =
308059d1ed5bSDimitry Andric       getLLVMLinkageVarDefinition(VD, Constant);
308133956c43SDimitry Andric   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
308233956c43SDimitry Andric     const VarDecl *InitVD;
308333956c43SDimitry Andric     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
308433956c43SDimitry Andric         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
308533956c43SDimitry Andric       // Temporaries defined inside a class get linkonce_odr linkage because the
308633956c43SDimitry Andric       // class can be defined in multipe translation units.
308733956c43SDimitry Andric       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
308833956c43SDimitry Andric     } else {
308933956c43SDimitry Andric       // There is no need for this temporary to have external linkage if the
309033956c43SDimitry Andric       // VarDecl has external linkage.
309133956c43SDimitry Andric       Linkage = llvm::GlobalVariable::InternalLinkage;
309233956c43SDimitry Andric     }
309333956c43SDimitry Andric   }
309459d1ed5bSDimitry Andric   unsigned AddrSpace = GetGlobalVarAddressSpace(
309559d1ed5bSDimitry Andric       VD, getContext().getTargetAddressSpace(MaterializedType));
309659d1ed5bSDimitry Andric   auto *GV = new llvm::GlobalVariable(
309759d1ed5bSDimitry Andric       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
309859d1ed5bSDimitry Andric       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
309959d1ed5bSDimitry Andric       AddrSpace);
310059d1ed5bSDimitry Andric   setGlobalVisibility(GV, VD);
3101f785676fSDimitry Andric   GV->setAlignment(
3102f785676fSDimitry Andric       getContext().getTypeAlignInChars(MaterializedType).getQuantity());
310333956c43SDimitry Andric   if (supportsCOMDAT() && GV->isWeakForLinker())
310433956c43SDimitry Andric     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3105f785676fSDimitry Andric   if (VD->getTLSKind())
3106f785676fSDimitry Andric     setTLSMode(GV, *VD);
3107f785676fSDimitry Andric   Slot = GV;
3108f785676fSDimitry Andric   return GV;
3109f785676fSDimitry Andric }
3110f785676fSDimitry Andric 
3111f22ef01cSRoman Divacky /// EmitObjCPropertyImplementations - Emit information for synthesized
3112f22ef01cSRoman Divacky /// properties for an implementation.
3113f22ef01cSRoman Divacky void CodeGenModule::EmitObjCPropertyImplementations(const
3114f22ef01cSRoman Divacky                                                     ObjCImplementationDecl *D) {
311559d1ed5bSDimitry Andric   for (const auto *PID : D->property_impls()) {
3116f22ef01cSRoman Divacky     // Dynamic is just for type-checking.
3117f22ef01cSRoman Divacky     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3118f22ef01cSRoman Divacky       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3119f22ef01cSRoman Divacky 
3120f22ef01cSRoman Divacky       // Determine which methods need to be implemented, some may have
31213861d79fSDimitry Andric       // been overridden. Note that ::isPropertyAccessor is not the method
3122f22ef01cSRoman Divacky       // we want, that just indicates if the decl came from a
3123f22ef01cSRoman Divacky       // property. What we want to know is if the method is defined in
3124f22ef01cSRoman Divacky       // this implementation.
3125f22ef01cSRoman Divacky       if (!D->getInstanceMethod(PD->getGetterName()))
3126f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCGetter(
3127f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3128f22ef01cSRoman Divacky       if (!PD->isReadOnly() &&
3129f22ef01cSRoman Divacky           !D->getInstanceMethod(PD->getSetterName()))
3130f22ef01cSRoman Divacky         CodeGenFunction(*this).GenerateObjCSetter(
3131f22ef01cSRoman Divacky                                  const_cast<ObjCImplementationDecl *>(D), PID);
3132f22ef01cSRoman Divacky     }
3133f22ef01cSRoman Divacky   }
3134f22ef01cSRoman Divacky }
3135f22ef01cSRoman Divacky 
31363b0f4066SDimitry Andric static bool needsDestructMethod(ObjCImplementationDecl *impl) {
31376122f3e6SDimitry Andric   const ObjCInterfaceDecl *iface = impl->getClassInterface();
31386122f3e6SDimitry Andric   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
31393b0f4066SDimitry Andric        ivar; ivar = ivar->getNextIvar())
31403b0f4066SDimitry Andric     if (ivar->getType().isDestructedType())
31413b0f4066SDimitry Andric       return true;
31423b0f4066SDimitry Andric 
31433b0f4066SDimitry Andric   return false;
31443b0f4066SDimitry Andric }
31453b0f4066SDimitry Andric 
314639d628a0SDimitry Andric static bool AllTrivialInitializers(CodeGenModule &CGM,
314739d628a0SDimitry Andric                                    ObjCImplementationDecl *D) {
314839d628a0SDimitry Andric   CodeGenFunction CGF(CGM);
314939d628a0SDimitry Andric   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
315039d628a0SDimitry Andric        E = D->init_end(); B != E; ++B) {
315139d628a0SDimitry Andric     CXXCtorInitializer *CtorInitExp = *B;
315239d628a0SDimitry Andric     Expr *Init = CtorInitExp->getInit();
315339d628a0SDimitry Andric     if (!CGF.isTrivialInitializer(Init))
315439d628a0SDimitry Andric       return false;
315539d628a0SDimitry Andric   }
315639d628a0SDimitry Andric   return true;
315739d628a0SDimitry Andric }
315839d628a0SDimitry Andric 
3159f22ef01cSRoman Divacky /// EmitObjCIvarInitializations - Emit information for ivar initialization
3160f22ef01cSRoman Divacky /// for an implementation.
3161f22ef01cSRoman Divacky void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
31623b0f4066SDimitry Andric   // We might need a .cxx_destruct even if we don't have any ivar initializers.
31633b0f4066SDimitry Andric   if (needsDestructMethod(D)) {
3164f22ef01cSRoman Divacky     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3165f22ef01cSRoman Divacky     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
31663b0f4066SDimitry Andric     ObjCMethodDecl *DTORMethod =
31673b0f4066SDimitry Andric       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
316859d1ed5bSDimitry Andric                              cxxSelector, getContext().VoidTy, nullptr, D,
31696122f3e6SDimitry Andric                              /*isInstance=*/true, /*isVariadic=*/false,
31703861d79fSDimitry Andric                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
31716122f3e6SDimitry Andric                              /*isDefined=*/false, ObjCMethodDecl::Required);
3172f22ef01cSRoman Divacky     D->addInstanceMethod(DTORMethod);
3173f22ef01cSRoman Divacky     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
31743861d79fSDimitry Andric     D->setHasDestructors(true);
31753b0f4066SDimitry Andric   }
3176f22ef01cSRoman Divacky 
31773b0f4066SDimitry Andric   // If the implementation doesn't have any ivar initializers, we don't need
31783b0f4066SDimitry Andric   // a .cxx_construct.
317939d628a0SDimitry Andric   if (D->getNumIvarInitializers() == 0 ||
318039d628a0SDimitry Andric       AllTrivialInitializers(*this, D))
31813b0f4066SDimitry Andric     return;
31823b0f4066SDimitry Andric 
31833b0f4066SDimitry Andric   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
31843b0f4066SDimitry Andric   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3185f22ef01cSRoman Divacky   // The constructor returns 'self'.
3186f22ef01cSRoman Divacky   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3187f22ef01cSRoman Divacky                                                 D->getLocation(),
31886122f3e6SDimitry Andric                                                 D->getLocation(),
31896122f3e6SDimitry Andric                                                 cxxSelector,
319059d1ed5bSDimitry Andric                                                 getContext().getObjCIdType(),
319159d1ed5bSDimitry Andric                                                 nullptr, D, /*isInstance=*/true,
31926122f3e6SDimitry Andric                                                 /*isVariadic=*/false,
31933861d79fSDimitry Andric                                                 /*isPropertyAccessor=*/true,
31946122f3e6SDimitry Andric                                                 /*isImplicitlyDeclared=*/true,
31956122f3e6SDimitry Andric                                                 /*isDefined=*/false,
3196f22ef01cSRoman Divacky                                                 ObjCMethodDecl::Required);
3197f22ef01cSRoman Divacky   D->addInstanceMethod(CTORMethod);
3198f22ef01cSRoman Divacky   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
31993861d79fSDimitry Andric   D->setHasNonZeroConstructors(true);
3200f22ef01cSRoman Divacky }
3201f22ef01cSRoman Divacky 
3202f22ef01cSRoman Divacky /// EmitNamespace - Emit all declarations in a namespace.
3203f22ef01cSRoman Divacky void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
320459d1ed5bSDimitry Andric   for (auto *I : ND->decls()) {
320559d1ed5bSDimitry Andric     if (const auto *VD = dyn_cast<VarDecl>(I))
3206f785676fSDimitry Andric       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3207f785676fSDimitry Andric           VD->getTemplateSpecializationKind() != TSK_Undeclared)
3208f785676fSDimitry Andric         continue;
320959d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3210f22ef01cSRoman Divacky   }
3211f785676fSDimitry Andric }
3212f22ef01cSRoman Divacky 
3213f22ef01cSRoman Divacky // EmitLinkageSpec - Emit all declarations in a linkage spec.
3214f22ef01cSRoman Divacky void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3215f22ef01cSRoman Divacky   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3216f22ef01cSRoman Divacky       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3217f22ef01cSRoman Divacky     ErrorUnsupported(LSD, "linkage spec");
3218f22ef01cSRoman Divacky     return;
3219f22ef01cSRoman Divacky   }
3220f22ef01cSRoman Divacky 
322159d1ed5bSDimitry Andric   for (auto *I : LSD->decls()) {
32223861d79fSDimitry Andric     // Meta-data for ObjC class includes references to implemented methods.
32233861d79fSDimitry Andric     // Generate class's method definitions first.
322459d1ed5bSDimitry Andric     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
322559d1ed5bSDimitry Andric       for (auto *M : OID->methods())
322659d1ed5bSDimitry Andric         EmitTopLevelDecl(M);
32273861d79fSDimitry Andric     }
322859d1ed5bSDimitry Andric     EmitTopLevelDecl(I);
3229f22ef01cSRoman Divacky   }
32303861d79fSDimitry Andric }
3231f22ef01cSRoman Divacky 
3232f22ef01cSRoman Divacky /// EmitTopLevelDecl - Emit code for a single top level declaration.
3233f22ef01cSRoman Divacky void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3234f22ef01cSRoman Divacky   // Ignore dependent declarations.
3235f22ef01cSRoman Divacky   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3236f22ef01cSRoman Divacky     return;
3237f22ef01cSRoman Divacky 
3238f22ef01cSRoman Divacky   switch (D->getKind()) {
3239f22ef01cSRoman Divacky   case Decl::CXXConversion:
3240f22ef01cSRoman Divacky   case Decl::CXXMethod:
3241f22ef01cSRoman Divacky   case Decl::Function:
3242f22ef01cSRoman Divacky     // Skip function templates
32433b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
32443b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3245f22ef01cSRoman Divacky       return;
3246f22ef01cSRoman Divacky 
3247f22ef01cSRoman Divacky     EmitGlobal(cast<FunctionDecl>(D));
324839d628a0SDimitry Andric     // Always provide some coverage mapping
324939d628a0SDimitry Andric     // even for the functions that aren't emitted.
325039d628a0SDimitry Andric     AddDeferredUnusedCoverageMapping(D);
3251f22ef01cSRoman Divacky     break;
3252f22ef01cSRoman Divacky 
3253f22ef01cSRoman Divacky   case Decl::Var:
3254f785676fSDimitry Andric     // Skip variable templates
3255f785676fSDimitry Andric     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3256f785676fSDimitry Andric       return;
3257f785676fSDimitry Andric   case Decl::VarTemplateSpecialization:
3258f22ef01cSRoman Divacky     EmitGlobal(cast<VarDecl>(D));
3259f22ef01cSRoman Divacky     break;
3260f22ef01cSRoman Divacky 
32613b0f4066SDimitry Andric   // Indirect fields from global anonymous structs and unions can be
32623b0f4066SDimitry Andric   // ignored; only the actual variable requires IR gen support.
32633b0f4066SDimitry Andric   case Decl::IndirectField:
32643b0f4066SDimitry Andric     break;
32653b0f4066SDimitry Andric 
3266f22ef01cSRoman Divacky   // C++ Decls
3267f22ef01cSRoman Divacky   case Decl::Namespace:
3268f22ef01cSRoman Divacky     EmitNamespace(cast<NamespaceDecl>(D));
3269f22ef01cSRoman Divacky     break;
3270f22ef01cSRoman Divacky     // No code generation needed.
3271f22ef01cSRoman Divacky   case Decl::UsingShadow:
3272f22ef01cSRoman Divacky   case Decl::ClassTemplate:
3273f785676fSDimitry Andric   case Decl::VarTemplate:
3274f785676fSDimitry Andric   case Decl::VarTemplatePartialSpecialization:
3275f22ef01cSRoman Divacky   case Decl::FunctionTemplate:
3276bd5abe19SDimitry Andric   case Decl::TypeAliasTemplate:
3277bd5abe19SDimitry Andric   case Decl::Block:
3278139f7f9bSDimitry Andric   case Decl::Empty:
3279f22ef01cSRoman Divacky     break;
328059d1ed5bSDimitry Andric   case Decl::Using:          // using X; [C++]
328159d1ed5bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
328259d1ed5bSDimitry Andric         DI->EmitUsingDecl(cast<UsingDecl>(*D));
328359d1ed5bSDimitry Andric     return;
3284f785676fSDimitry Andric   case Decl::NamespaceAlias:
3285f785676fSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3286f785676fSDimitry Andric         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3287f785676fSDimitry Andric     return;
3288284c1978SDimitry Andric   case Decl::UsingDirective: // using namespace X; [C++]
3289284c1978SDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3290284c1978SDimitry Andric       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3291284c1978SDimitry Andric     return;
3292f22ef01cSRoman Divacky   case Decl::CXXConstructor:
3293f22ef01cSRoman Divacky     // Skip function templates
32943b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
32953b0f4066SDimitry Andric         cast<FunctionDecl>(D)->isLateTemplateParsed())
3296f22ef01cSRoman Divacky       return;
3297f22ef01cSRoman Divacky 
3298f785676fSDimitry Andric     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3299f22ef01cSRoman Divacky     break;
3300f22ef01cSRoman Divacky   case Decl::CXXDestructor:
33013b0f4066SDimitry Andric     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
33023b0f4066SDimitry Andric       return;
3303f785676fSDimitry Andric     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3304f22ef01cSRoman Divacky     break;
3305f22ef01cSRoman Divacky 
3306f22ef01cSRoman Divacky   case Decl::StaticAssert:
3307f22ef01cSRoman Divacky     // Nothing to do.
3308f22ef01cSRoman Divacky     break;
3309f22ef01cSRoman Divacky 
3310f22ef01cSRoman Divacky   // Objective-C Decls
3311f22ef01cSRoman Divacky 
3312f22ef01cSRoman Divacky   // Forward declarations, no (immediate) code generation.
3313f22ef01cSRoman Divacky   case Decl::ObjCInterface:
33147ae0e2c9SDimitry Andric   case Decl::ObjCCategory:
3315f22ef01cSRoman Divacky     break;
3316f22ef01cSRoman Divacky 
3317dff0c46cSDimitry Andric   case Decl::ObjCProtocol: {
331859d1ed5bSDimitry Andric     auto *Proto = cast<ObjCProtocolDecl>(D);
3319dff0c46cSDimitry Andric     if (Proto->isThisDeclarationADefinition())
3320dff0c46cSDimitry Andric       ObjCRuntime->GenerateProtocol(Proto);
3321f22ef01cSRoman Divacky     break;
3322dff0c46cSDimitry Andric   }
3323f22ef01cSRoman Divacky 
3324f22ef01cSRoman Divacky   case Decl::ObjCCategoryImpl:
3325f22ef01cSRoman Divacky     // Categories have properties but don't support synthesize so we
3326f22ef01cSRoman Divacky     // can ignore them here.
33276122f3e6SDimitry Andric     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3328f22ef01cSRoman Divacky     break;
3329f22ef01cSRoman Divacky 
3330f22ef01cSRoman Divacky   case Decl::ObjCImplementation: {
333159d1ed5bSDimitry Andric     auto *OMD = cast<ObjCImplementationDecl>(D);
3332f22ef01cSRoman Divacky     EmitObjCPropertyImplementations(OMD);
3333f22ef01cSRoman Divacky     EmitObjCIvarInitializations(OMD);
33346122f3e6SDimitry Andric     ObjCRuntime->GenerateClass(OMD);
3335dff0c46cSDimitry Andric     // Emit global variable debug information.
3336dff0c46cSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
3337139f7f9bSDimitry Andric       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3338139f7f9bSDimitry Andric         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3339139f7f9bSDimitry Andric             OMD->getClassInterface()), OMD->getLocation());
3340f22ef01cSRoman Divacky     break;
3341f22ef01cSRoman Divacky   }
3342f22ef01cSRoman Divacky   case Decl::ObjCMethod: {
334359d1ed5bSDimitry Andric     auto *OMD = cast<ObjCMethodDecl>(D);
3344f22ef01cSRoman Divacky     // If this is not a prototype, emit the body.
3345f22ef01cSRoman Divacky     if (OMD->getBody())
3346f22ef01cSRoman Divacky       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3347f22ef01cSRoman Divacky     break;
3348f22ef01cSRoman Divacky   }
3349f22ef01cSRoman Divacky   case Decl::ObjCCompatibleAlias:
3350dff0c46cSDimitry Andric     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3351f22ef01cSRoman Divacky     break;
3352f22ef01cSRoman Divacky 
3353f22ef01cSRoman Divacky   case Decl::LinkageSpec:
3354f22ef01cSRoman Divacky     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3355f22ef01cSRoman Divacky     break;
3356f22ef01cSRoman Divacky 
3357f22ef01cSRoman Divacky   case Decl::FileScopeAsm: {
335833956c43SDimitry Andric     // File-scope asm is ignored during device-side CUDA compilation.
335933956c43SDimitry Andric     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
336033956c43SDimitry Andric       break;
336159d1ed5bSDimitry Andric     auto *AD = cast<FileScopeAsmDecl>(D);
336233956c43SDimitry Andric     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3363f22ef01cSRoman Divacky     break;
3364f22ef01cSRoman Divacky   }
3365f22ef01cSRoman Divacky 
3366139f7f9bSDimitry Andric   case Decl::Import: {
336759d1ed5bSDimitry Andric     auto *Import = cast<ImportDecl>(D);
3368139f7f9bSDimitry Andric 
3369139f7f9bSDimitry Andric     // Ignore import declarations that come from imported modules.
337033956c43SDimitry Andric     if (clang::Module *Owner = Import->getImportedOwningModule()) {
3371139f7f9bSDimitry Andric       if (getLangOpts().CurrentModule.empty() ||
3372139f7f9bSDimitry Andric           Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3373139f7f9bSDimitry Andric         break;
3374139f7f9bSDimitry Andric     }
33753dac3a9bSDimitry Andric     if (CGDebugInfo *DI = getModuleDebugInfo())
33763dac3a9bSDimitry Andric       DI->EmitImportDecl(*Import);
3377139f7f9bSDimitry Andric 
3378139f7f9bSDimitry Andric     ImportedModules.insert(Import->getImportedModule());
3379139f7f9bSDimitry Andric     break;
3380139f7f9bSDimitry Andric   }
3381139f7f9bSDimitry Andric 
338239d628a0SDimitry Andric   case Decl::OMPThreadPrivate:
338339d628a0SDimitry Andric     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
338439d628a0SDimitry Andric     break;
338539d628a0SDimitry Andric 
338659d1ed5bSDimitry Andric   case Decl::ClassTemplateSpecialization: {
338759d1ed5bSDimitry Andric     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
338859d1ed5bSDimitry Andric     if (DebugInfo &&
338939d628a0SDimitry Andric         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
339039d628a0SDimitry Andric         Spec->hasDefinition())
339159d1ed5bSDimitry Andric       DebugInfo->completeTemplateDefinition(*Spec);
339239d628a0SDimitry Andric     break;
339359d1ed5bSDimitry Andric   }
339459d1ed5bSDimitry Andric 
3395f22ef01cSRoman Divacky   default:
3396f22ef01cSRoman Divacky     // Make sure we handled everything we should, every other kind is a
3397f22ef01cSRoman Divacky     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3398f22ef01cSRoman Divacky     // function. Need to recode Decl::Kind to do that easily.
3399f22ef01cSRoman Divacky     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
340039d628a0SDimitry Andric     break;
340139d628a0SDimitry Andric   }
340239d628a0SDimitry Andric }
340339d628a0SDimitry Andric 
340439d628a0SDimitry Andric void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
340539d628a0SDimitry Andric   // Do we need to generate coverage mapping?
340639d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
340739d628a0SDimitry Andric     return;
340839d628a0SDimitry Andric   switch (D->getKind()) {
340939d628a0SDimitry Andric   case Decl::CXXConversion:
341039d628a0SDimitry Andric   case Decl::CXXMethod:
341139d628a0SDimitry Andric   case Decl::Function:
341239d628a0SDimitry Andric   case Decl::ObjCMethod:
341339d628a0SDimitry Andric   case Decl::CXXConstructor:
341439d628a0SDimitry Andric   case Decl::CXXDestructor: {
341539d628a0SDimitry Andric     if (!cast<FunctionDecl>(D)->hasBody())
341639d628a0SDimitry Andric       return;
341739d628a0SDimitry Andric     auto I = DeferredEmptyCoverageMappingDecls.find(D);
341839d628a0SDimitry Andric     if (I == DeferredEmptyCoverageMappingDecls.end())
341939d628a0SDimitry Andric       DeferredEmptyCoverageMappingDecls[D] = true;
342039d628a0SDimitry Andric     break;
342139d628a0SDimitry Andric   }
342239d628a0SDimitry Andric   default:
342339d628a0SDimitry Andric     break;
342439d628a0SDimitry Andric   };
342539d628a0SDimitry Andric }
342639d628a0SDimitry Andric 
342739d628a0SDimitry Andric void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
342839d628a0SDimitry Andric   // Do we need to generate coverage mapping?
342939d628a0SDimitry Andric   if (!CodeGenOpts.CoverageMapping)
343039d628a0SDimitry Andric     return;
343139d628a0SDimitry Andric   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
343239d628a0SDimitry Andric     if (Fn->isTemplateInstantiation())
343339d628a0SDimitry Andric       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
343439d628a0SDimitry Andric   }
343539d628a0SDimitry Andric   auto I = DeferredEmptyCoverageMappingDecls.find(D);
343639d628a0SDimitry Andric   if (I == DeferredEmptyCoverageMappingDecls.end())
343739d628a0SDimitry Andric     DeferredEmptyCoverageMappingDecls[D] = false;
343839d628a0SDimitry Andric   else
343939d628a0SDimitry Andric     I->second = false;
344039d628a0SDimitry Andric }
344139d628a0SDimitry Andric 
344239d628a0SDimitry Andric void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
344339d628a0SDimitry Andric   std::vector<const Decl *> DeferredDecls;
344433956c43SDimitry Andric   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
344539d628a0SDimitry Andric     if (!I.second)
344639d628a0SDimitry Andric       continue;
344739d628a0SDimitry Andric     DeferredDecls.push_back(I.first);
344839d628a0SDimitry Andric   }
344939d628a0SDimitry Andric   // Sort the declarations by their location to make sure that the tests get a
345039d628a0SDimitry Andric   // predictable order for the coverage mapping for the unused declarations.
345139d628a0SDimitry Andric   if (CodeGenOpts.DumpCoverageMapping)
345239d628a0SDimitry Andric     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
345339d628a0SDimitry Andric               [] (const Decl *LHS, const Decl *RHS) {
345439d628a0SDimitry Andric       return LHS->getLocStart() < RHS->getLocStart();
345539d628a0SDimitry Andric     });
345639d628a0SDimitry Andric   for (const auto *D : DeferredDecls) {
345739d628a0SDimitry Andric     switch (D->getKind()) {
345839d628a0SDimitry Andric     case Decl::CXXConversion:
345939d628a0SDimitry Andric     case Decl::CXXMethod:
346039d628a0SDimitry Andric     case Decl::Function:
346139d628a0SDimitry Andric     case Decl::ObjCMethod: {
346239d628a0SDimitry Andric       CodeGenPGO PGO(*this);
346339d628a0SDimitry Andric       GlobalDecl GD(cast<FunctionDecl>(D));
346439d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
346539d628a0SDimitry Andric                                   getFunctionLinkage(GD));
346639d628a0SDimitry Andric       break;
346739d628a0SDimitry Andric     }
346839d628a0SDimitry Andric     case Decl::CXXConstructor: {
346939d628a0SDimitry Andric       CodeGenPGO PGO(*this);
347039d628a0SDimitry Andric       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
347139d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
347239d628a0SDimitry Andric                                   getFunctionLinkage(GD));
347339d628a0SDimitry Andric       break;
347439d628a0SDimitry Andric     }
347539d628a0SDimitry Andric     case Decl::CXXDestructor: {
347639d628a0SDimitry Andric       CodeGenPGO PGO(*this);
347739d628a0SDimitry Andric       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
347839d628a0SDimitry Andric       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
347939d628a0SDimitry Andric                                   getFunctionLinkage(GD));
348039d628a0SDimitry Andric       break;
348139d628a0SDimitry Andric     }
348239d628a0SDimitry Andric     default:
348339d628a0SDimitry Andric       break;
348439d628a0SDimitry Andric     };
3485f22ef01cSRoman Divacky   }
3486f22ef01cSRoman Divacky }
3487ffd1746dSEd Schouten 
3488ffd1746dSEd Schouten /// Turns the given pointer into a constant.
3489ffd1746dSEd Schouten static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3490ffd1746dSEd Schouten                                           const void *Ptr) {
3491ffd1746dSEd Schouten   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
34926122f3e6SDimitry Andric   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3493ffd1746dSEd Schouten   return llvm::ConstantInt::get(i64, PtrInt);
3494ffd1746dSEd Schouten }
3495ffd1746dSEd Schouten 
3496ffd1746dSEd Schouten static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3497ffd1746dSEd Schouten                                    llvm::NamedMDNode *&GlobalMetadata,
3498ffd1746dSEd Schouten                                    GlobalDecl D,
3499ffd1746dSEd Schouten                                    llvm::GlobalValue *Addr) {
3500ffd1746dSEd Schouten   if (!GlobalMetadata)
3501ffd1746dSEd Schouten     GlobalMetadata =
3502ffd1746dSEd Schouten       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3503ffd1746dSEd Schouten 
3504ffd1746dSEd Schouten   // TODO: should we report variant information for ctors/dtors?
350539d628a0SDimitry Andric   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
350639d628a0SDimitry Andric                            llvm::ConstantAsMetadata::get(GetPointerConstant(
350739d628a0SDimitry Andric                                CGM.getLLVMContext(), D.getDecl()))};
35083b0f4066SDimitry Andric   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3509ffd1746dSEd Schouten }
3510ffd1746dSEd Schouten 
3511284c1978SDimitry Andric /// For each function which is declared within an extern "C" region and marked
3512284c1978SDimitry Andric /// as 'used', but has internal linkage, create an alias from the unmangled
3513284c1978SDimitry Andric /// name to the mangled name if possible. People expect to be able to refer
3514284c1978SDimitry Andric /// to such functions with an unmangled name from inline assembly within the
3515284c1978SDimitry Andric /// same translation unit.
3516284c1978SDimitry Andric void CodeGenModule::EmitStaticExternCAliases() {
35178f0fd8f6SDimitry Andric   for (auto &I : StaticExternCValues) {
35188f0fd8f6SDimitry Andric     IdentifierInfo *Name = I.first;
35198f0fd8f6SDimitry Andric     llvm::GlobalValue *Val = I.second;
3520284c1978SDimitry Andric     if (Val && !getModule().getNamedValue(Name->getName()))
352159d1ed5bSDimitry Andric       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
3522284c1978SDimitry Andric   }
3523284c1978SDimitry Andric }
3524284c1978SDimitry Andric 
352559d1ed5bSDimitry Andric bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
352659d1ed5bSDimitry Andric                                              GlobalDecl &Result) const {
352759d1ed5bSDimitry Andric   auto Res = Manglings.find(MangledName);
352859d1ed5bSDimitry Andric   if (Res == Manglings.end())
352959d1ed5bSDimitry Andric     return false;
353059d1ed5bSDimitry Andric   Result = Res->getValue();
353159d1ed5bSDimitry Andric   return true;
353259d1ed5bSDimitry Andric }
353359d1ed5bSDimitry Andric 
3534ffd1746dSEd Schouten /// Emits metadata nodes associating all the global values in the
3535ffd1746dSEd Schouten /// current module with the Decls they came from.  This is useful for
3536ffd1746dSEd Schouten /// projects using IR gen as a subroutine.
3537ffd1746dSEd Schouten ///
3538ffd1746dSEd Schouten /// Since there's currently no way to associate an MDNode directly
3539ffd1746dSEd Schouten /// with an llvm::GlobalValue, we create a global named metadata
3540ffd1746dSEd Schouten /// with the name 'clang.global.decl.ptrs'.
3541ffd1746dSEd Schouten void CodeGenModule::EmitDeclMetadata() {
354259d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
3543ffd1746dSEd Schouten 
3544ffd1746dSEd Schouten   // StaticLocalDeclMap
354559d1ed5bSDimitry Andric   for (auto &I : MangledDeclNames) {
354659d1ed5bSDimitry Andric     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
354759d1ed5bSDimitry Andric     EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
3548ffd1746dSEd Schouten   }
3549ffd1746dSEd Schouten }
3550ffd1746dSEd Schouten 
3551ffd1746dSEd Schouten /// Emits metadata nodes for all the local variables in the current
3552ffd1746dSEd Schouten /// function.
3553ffd1746dSEd Schouten void CodeGenFunction::EmitDeclMetadata() {
3554ffd1746dSEd Schouten   if (LocalDeclMap.empty()) return;
3555ffd1746dSEd Schouten 
3556ffd1746dSEd Schouten   llvm::LLVMContext &Context = getLLVMContext();
3557ffd1746dSEd Schouten 
3558ffd1746dSEd Schouten   // Find the unique metadata ID for this name.
3559ffd1746dSEd Schouten   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3560ffd1746dSEd Schouten 
356159d1ed5bSDimitry Andric   llvm::NamedMDNode *GlobalMetadata = nullptr;
3562ffd1746dSEd Schouten 
356359d1ed5bSDimitry Andric   for (auto &I : LocalDeclMap) {
356459d1ed5bSDimitry Andric     const Decl *D = I.first;
356559d1ed5bSDimitry Andric     llvm::Value *Addr = I.second;
356659d1ed5bSDimitry Andric     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3567ffd1746dSEd Schouten       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
356839d628a0SDimitry Andric       Alloca->setMetadata(
356939d628a0SDimitry Andric           DeclPtrKind, llvm::MDNode::get(
357039d628a0SDimitry Andric                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
357159d1ed5bSDimitry Andric     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3572ffd1746dSEd Schouten       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3573ffd1746dSEd Schouten       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3574ffd1746dSEd Schouten     }
3575ffd1746dSEd Schouten   }
3576ffd1746dSEd Schouten }
3577e580952dSDimitry Andric 
3578f785676fSDimitry Andric void CodeGenModule::EmitVersionIdentMetadata() {
3579f785676fSDimitry Andric   llvm::NamedMDNode *IdentMetadata =
3580f785676fSDimitry Andric     TheModule.getOrInsertNamedMetadata("llvm.ident");
3581f785676fSDimitry Andric   std::string Version = getClangFullVersion();
3582f785676fSDimitry Andric   llvm::LLVMContext &Ctx = TheModule.getContext();
3583f785676fSDimitry Andric 
358439d628a0SDimitry Andric   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
3585f785676fSDimitry Andric   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3586f785676fSDimitry Andric }
3587f785676fSDimitry Andric 
358859d1ed5bSDimitry Andric void CodeGenModule::EmitTargetMetadata() {
358939d628a0SDimitry Andric   // Warning, new MangledDeclNames may be appended within this loop.
359039d628a0SDimitry Andric   // We rely on MapVector insertions adding new elements to the end
359139d628a0SDimitry Andric   // of the container.
359239d628a0SDimitry Andric   // FIXME: Move this loop into the one target that needs it, and only
359339d628a0SDimitry Andric   // loop over those declarations for which we couldn't emit the target
359439d628a0SDimitry Andric   // metadata when we emitted the declaration.
359539d628a0SDimitry Andric   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
359639d628a0SDimitry Andric     auto Val = *(MangledDeclNames.begin() + I);
359739d628a0SDimitry Andric     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
359839d628a0SDimitry Andric     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
359959d1ed5bSDimitry Andric     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
360059d1ed5bSDimitry Andric   }
360159d1ed5bSDimitry Andric }
360259d1ed5bSDimitry Andric 
3603bd5abe19SDimitry Andric void CodeGenModule::EmitCoverageFile() {
3604bd5abe19SDimitry Andric   if (!getCodeGenOpts().CoverageFile.empty()) {
3605bd5abe19SDimitry Andric     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3606bd5abe19SDimitry Andric       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3607bd5abe19SDimitry Andric       llvm::LLVMContext &Ctx = TheModule.getContext();
3608bd5abe19SDimitry Andric       llvm::MDString *CoverageFile =
3609bd5abe19SDimitry Andric           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3610bd5abe19SDimitry Andric       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3611bd5abe19SDimitry Andric         llvm::MDNode *CU = CUNode->getOperand(i);
361239d628a0SDimitry Andric         llvm::Metadata *Elts[] = {CoverageFile, CU};
361339d628a0SDimitry Andric         GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
3614bd5abe19SDimitry Andric       }
3615bd5abe19SDimitry Andric     }
3616bd5abe19SDimitry Andric   }
3617bd5abe19SDimitry Andric }
36183861d79fSDimitry Andric 
361939d628a0SDimitry Andric llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
36203861d79fSDimitry Andric   // Sema has checked that all uuid strings are of the form
36213861d79fSDimitry Andric   // "12345678-1234-1234-1234-1234567890ab".
36223861d79fSDimitry Andric   assert(Uuid.size() == 36);
3623f785676fSDimitry Andric   for (unsigned i = 0; i < 36; ++i) {
3624f785676fSDimitry Andric     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3625f785676fSDimitry Andric     else                                         assert(isHexDigit(Uuid[i]));
36263861d79fSDimitry Andric   }
36273861d79fSDimitry Andric 
362839d628a0SDimitry Andric   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
3629f785676fSDimitry Andric   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
36303861d79fSDimitry Andric 
3631f785676fSDimitry Andric   llvm::Constant *Field3[8];
3632f785676fSDimitry Andric   for (unsigned Idx = 0; Idx < 8; ++Idx)
3633f785676fSDimitry Andric     Field3[Idx] = llvm::ConstantInt::get(
3634f785676fSDimitry Andric         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
36353861d79fSDimitry Andric 
3636f785676fSDimitry Andric   llvm::Constant *Fields[4] = {
3637f785676fSDimitry Andric     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3638f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3639f785676fSDimitry Andric     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3640f785676fSDimitry Andric     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3641f785676fSDimitry Andric   };
3642f785676fSDimitry Andric 
3643f785676fSDimitry Andric   return llvm::ConstantStruct::getAnon(Fields);
36443861d79fSDimitry Andric }
364559d1ed5bSDimitry Andric 
364633956c43SDimitry Andric llvm::Constant *
364733956c43SDimitry Andric CodeGenModule::getAddrOfCXXCatchHandlerType(QualType Ty,
364833956c43SDimitry Andric                                             QualType CatchHandlerType) {
364933956c43SDimitry Andric   return getCXXABI().getAddrOfCXXCatchHandlerType(Ty, CatchHandlerType);
365033956c43SDimitry Andric }
365133956c43SDimitry Andric 
365259d1ed5bSDimitry Andric llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
365359d1ed5bSDimitry Andric                                                        bool ForEH) {
365459d1ed5bSDimitry Andric   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
365559d1ed5bSDimitry Andric   // FIXME: should we even be calling this method if RTTI is disabled
365659d1ed5bSDimitry Andric   // and it's not for EH?
365759d1ed5bSDimitry Andric   if (!ForEH && !getLangOpts().RTTI)
365859d1ed5bSDimitry Andric     return llvm::Constant::getNullValue(Int8PtrTy);
365959d1ed5bSDimitry Andric 
366059d1ed5bSDimitry Andric   if (ForEH && Ty->isObjCObjectPointerType() &&
366159d1ed5bSDimitry Andric       LangOpts.ObjCRuntime.isGNUFamily())
366259d1ed5bSDimitry Andric     return ObjCRuntime->GetEHType(Ty);
366359d1ed5bSDimitry Andric 
366459d1ed5bSDimitry Andric   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
366559d1ed5bSDimitry Andric }
366659d1ed5bSDimitry Andric 
366739d628a0SDimitry Andric void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
366839d628a0SDimitry Andric   for (auto RefExpr : D->varlists()) {
366939d628a0SDimitry Andric     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
367039d628a0SDimitry Andric     bool PerformInit =
367139d628a0SDimitry Andric         VD->getAnyInitializer() &&
367239d628a0SDimitry Andric         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
367339d628a0SDimitry Andric                                                         /*ForRef=*/false);
367433956c43SDimitry Andric     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
367533956c43SDimitry Andric             VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(), PerformInit))
367639d628a0SDimitry Andric       CXXGlobalInits.push_back(InitFunction);
367739d628a0SDimitry Andric   }
367839d628a0SDimitry Andric }
36798f0fd8f6SDimitry Andric 
36808f0fd8f6SDimitry Andric llvm::MDTuple *CodeGenModule::CreateVTableBitSetEntry(
36818f0fd8f6SDimitry Andric     llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD) {
36828f0fd8f6SDimitry Andric   std::string OutName;
36838f0fd8f6SDimitry Andric   llvm::raw_string_ostream Out(OutName);
36848f0fd8f6SDimitry Andric   getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
36858f0fd8f6SDimitry Andric 
36868f0fd8f6SDimitry Andric   llvm::Metadata *BitsetOps[] = {
36878f0fd8f6SDimitry Andric       llvm::MDString::get(getLLVMContext(), Out.str()),
36888f0fd8f6SDimitry Andric       llvm::ConstantAsMetadata::get(VTable),
36898f0fd8f6SDimitry Andric       llvm::ConstantAsMetadata::get(
36908f0fd8f6SDimitry Andric           llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
36918f0fd8f6SDimitry Andric   return llvm::MDTuple::get(getLLVMContext(), BitsetOps);
36928f0fd8f6SDimitry Andric }
3693