xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision ab9db51042d1b821d324a209f3ba37e5ee7525a7)
1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This coordinates the per-module state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CodeGenModule.h"
15 #include "CGCUDARuntime.h"
16 #include "CGCXXABI.h"
17 #include "CGCall.h"
18 #include "CGDebugInfo.h"
19 #include "CGObjCRuntime.h"
20 #include "CGOpenCLRuntime.h"
21 #include "CGOpenMPRuntime.h"
22 #include "CodeGenFunction.h"
23 #include "CodeGenPGO.h"
24 #include "CodeGenTBAA.h"
25 #include "CoverageMappingGen.h"
26 #include "TargetInfo.h"
27 #include "clang/AST/ASTContext.h"
28 #include "clang/AST/CharUnits.h"
29 #include "clang/AST/DeclCXX.h"
30 #include "clang/AST/DeclObjC.h"
31 #include "clang/AST/DeclTemplate.h"
32 #include "clang/AST/Mangle.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/RecursiveASTVisitor.h"
35 #include "clang/Basic/Builtins.h"
36 #include "clang/Basic/CharInfo.h"
37 #include "clang/Basic/Diagnostic.h"
38 #include "clang/Basic/Module.h"
39 #include "clang/Basic/SourceManager.h"
40 #include "clang/Basic/TargetInfo.h"
41 #include "clang/Basic/Version.h"
42 #include "clang/Frontend/CodeGenOptions.h"
43 #include "clang/Sema/SemaDiagnostic.h"
44 #include "llvm/ADT/APSInt.h"
45 #include "llvm/ADT/Triple.h"
46 #include "llvm/IR/CallSite.h"
47 #include "llvm/IR/CallingConv.h"
48 #include "llvm/IR/DataLayout.h"
49 #include "llvm/IR/Intrinsics.h"
50 #include "llvm/IR/LLVMContext.h"
51 #include "llvm/IR/Module.h"
52 #include "llvm/ProfileData/InstrProfReader.h"
53 #include "llvm/Support/ConvertUTF.h"
54 #include "llvm/Support/ErrorHandling.h"
55 
56 using namespace clang;
57 using namespace CodeGen;
58 
59 static const char AnnotationSection[] = "llvm.metadata";
60 
61 static CGCXXABI *createCXXABI(CodeGenModule &CGM) {
62   switch (CGM.getTarget().getCXXABI().getKind()) {
63   case TargetCXXABI::GenericAArch64:
64   case TargetCXXABI::GenericARM:
65   case TargetCXXABI::iOS:
66   case TargetCXXABI::iOS64:
67   case TargetCXXABI::GenericMIPS:
68   case TargetCXXABI::GenericItanium:
69     return CreateItaniumCXXABI(CGM);
70   case TargetCXXABI::Microsoft:
71     return CreateMicrosoftCXXABI(CGM);
72   }
73 
74   llvm_unreachable("invalid C++ ABI kind");
75 }
76 
77 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
78                              llvm::Module &M, const llvm::DataLayout &TD,
79                              DiagnosticsEngine &diags,
80                              CoverageSourceInfo *CoverageInfo)
81     : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
82       Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
83       ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(nullptr),
84       TheTargetCodeGenInfo(nullptr), Types(*this), VTables(*this),
85       ObjCRuntime(nullptr), OpenCLRuntime(nullptr), OpenMPRuntime(nullptr),
86       CUDARuntime(nullptr), DebugInfo(nullptr), ARCData(nullptr),
87       NoObjCARCExceptionsMetadata(nullptr), RRData(nullptr), PGOReader(nullptr),
88       CFConstantStringClassRef(nullptr), ConstantStringClassRef(nullptr),
89       NSConstantStringType(nullptr), NSConcreteGlobalBlock(nullptr),
90       NSConcreteStackBlock(nullptr), BlockObjectAssign(nullptr),
91       BlockObjectDispose(nullptr), BlockDescriptorType(nullptr),
92       GenericBlockLiteralType(nullptr), LifetimeStartFn(nullptr),
93       LifetimeEndFn(nullptr), SanitizerMD(new SanitizerMetadata(*this)) {
94 
95   // Initialize the type cache.
96   llvm::LLVMContext &LLVMContext = M.getContext();
97   VoidTy = llvm::Type::getVoidTy(LLVMContext);
98   Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
99   Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
100   Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
101   Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
102   FloatTy = llvm::Type::getFloatTy(LLVMContext);
103   DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
104   PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
105   PointerAlignInBytes =
106   C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
107   IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
108   IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
109   Int8PtrTy = Int8Ty->getPointerTo(0);
110   Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
111 
112   RuntimeCC = getTargetCodeGenInfo().getABIInfo().getRuntimeCC();
113   BuiltinCC = getTargetCodeGenInfo().getABIInfo().getBuiltinCC();
114 
115   if (LangOpts.ObjC1)
116     createObjCRuntime();
117   if (LangOpts.OpenCL)
118     createOpenCLRuntime();
119   if (LangOpts.OpenMP)
120     createOpenMPRuntime();
121   if (LangOpts.CUDA)
122     createCUDARuntime();
123 
124   // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
125   if (LangOpts.Sanitize.has(SanitizerKind::Thread) ||
126       (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
127     TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
128                            getCXXABI().getMangleContext());
129 
130   // If debug info or coverage generation is enabled, create the CGDebugInfo
131   // object.
132   if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
133       CodeGenOpts.EmitGcovArcs ||
134       CodeGenOpts.EmitGcovNotes)
135     DebugInfo = new CGDebugInfo(*this);
136 
137   Block.GlobalUniqueCount = 0;
138 
139   if (C.getLangOpts().ObjCAutoRefCount)
140     ARCData = new ARCEntrypoints();
141   RRData = new RREntrypoints();
142 
143   if (!CodeGenOpts.InstrProfileInput.empty()) {
144     auto ReaderOrErr =
145         llvm::IndexedInstrProfReader::create(CodeGenOpts.InstrProfileInput);
146     if (std::error_code EC = ReaderOrErr.getError()) {
147       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
148                                               "Could not read profile: %0");
149       getDiags().Report(DiagID) << EC.message();
150     } else
151       PGOReader = std::move(ReaderOrErr.get());
152   }
153 
154   // If coverage mapping generation is enabled, create the
155   // CoverageMappingModuleGen object.
156   if (CodeGenOpts.CoverageMapping)
157     CoverageMapping.reset(new CoverageMappingModuleGen(*this, *CoverageInfo));
158 }
159 
160 CodeGenModule::~CodeGenModule() {
161   delete ObjCRuntime;
162   delete OpenCLRuntime;
163   delete OpenMPRuntime;
164   delete CUDARuntime;
165   delete TheTargetCodeGenInfo;
166   delete TBAA;
167   delete DebugInfo;
168   delete ARCData;
169   delete RRData;
170 }
171 
172 void CodeGenModule::createObjCRuntime() {
173   // This is just isGNUFamily(), but we want to force implementors of
174   // new ABIs to decide how best to do this.
175   switch (LangOpts.ObjCRuntime.getKind()) {
176   case ObjCRuntime::GNUstep:
177   case ObjCRuntime::GCC:
178   case ObjCRuntime::ObjFW:
179     ObjCRuntime = CreateGNUObjCRuntime(*this);
180     return;
181 
182   case ObjCRuntime::FragileMacOSX:
183   case ObjCRuntime::MacOSX:
184   case ObjCRuntime::iOS:
185     ObjCRuntime = CreateMacObjCRuntime(*this);
186     return;
187   }
188   llvm_unreachable("bad runtime kind");
189 }
190 
191 void CodeGenModule::createOpenCLRuntime() {
192   OpenCLRuntime = new CGOpenCLRuntime(*this);
193 }
194 
195 void CodeGenModule::createOpenMPRuntime() {
196   OpenMPRuntime = new CGOpenMPRuntime(*this);
197 }
198 
199 void CodeGenModule::createCUDARuntime() {
200   CUDARuntime = CreateNVCUDARuntime(*this);
201 }
202 
203 void CodeGenModule::addReplacement(StringRef Name, llvm::Constant *C) {
204   Replacements[Name] = C;
205 }
206 
207 void CodeGenModule::applyReplacements() {
208   for (auto &I : Replacements) {
209     StringRef MangledName = I.first();
210     llvm::Constant *Replacement = I.second;
211     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
212     if (!Entry)
213       continue;
214     auto *OldF = cast<llvm::Function>(Entry);
215     auto *NewF = dyn_cast<llvm::Function>(Replacement);
216     if (!NewF) {
217       if (auto *Alias = dyn_cast<llvm::GlobalAlias>(Replacement)) {
218         NewF = dyn_cast<llvm::Function>(Alias->getAliasee());
219       } else {
220         auto *CE = cast<llvm::ConstantExpr>(Replacement);
221         assert(CE->getOpcode() == llvm::Instruction::BitCast ||
222                CE->getOpcode() == llvm::Instruction::GetElementPtr);
223         NewF = dyn_cast<llvm::Function>(CE->getOperand(0));
224       }
225     }
226 
227     // Replace old with new, but keep the old order.
228     OldF->replaceAllUsesWith(Replacement);
229     if (NewF) {
230       NewF->removeFromParent();
231       OldF->getParent()->getFunctionList().insertAfter(OldF, NewF);
232     }
233     OldF->eraseFromParent();
234   }
235 }
236 
237 // This is only used in aliases that we created and we know they have a
238 // linear structure.
239 static const llvm::GlobalObject *getAliasedGlobal(const llvm::GlobalAlias &GA) {
240   llvm::SmallPtrSet<const llvm::GlobalAlias*, 4> Visited;
241   const llvm::Constant *C = &GA;
242   for (;;) {
243     C = C->stripPointerCasts();
244     if (auto *GO = dyn_cast<llvm::GlobalObject>(C))
245       return GO;
246     // stripPointerCasts will not walk over weak aliases.
247     auto *GA2 = dyn_cast<llvm::GlobalAlias>(C);
248     if (!GA2)
249       return nullptr;
250     if (!Visited.insert(GA2).second)
251       return nullptr;
252     C = GA2->getAliasee();
253   }
254 }
255 
256 void CodeGenModule::checkAliases() {
257   // Check if the constructed aliases are well formed. It is really unfortunate
258   // that we have to do this in CodeGen, but we only construct mangled names
259   // and aliases during codegen.
260   bool Error = false;
261   DiagnosticsEngine &Diags = getDiags();
262   for (const GlobalDecl &GD : Aliases) {
263     const auto *D = cast<ValueDecl>(GD.getDecl());
264     const AliasAttr *AA = D->getAttr<AliasAttr>();
265     StringRef MangledName = getMangledName(GD);
266     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
267     auto *Alias = cast<llvm::GlobalAlias>(Entry);
268     const llvm::GlobalValue *GV = getAliasedGlobal(*Alias);
269     if (!GV) {
270       Error = true;
271       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
272     } else if (GV->isDeclaration()) {
273       Error = true;
274       Diags.Report(AA->getLocation(), diag::err_alias_to_undefined);
275     }
276 
277     llvm::Constant *Aliasee = Alias->getAliasee();
278     llvm::GlobalValue *AliaseeGV;
279     if (auto CE = dyn_cast<llvm::ConstantExpr>(Aliasee))
280       AliaseeGV = cast<llvm::GlobalValue>(CE->getOperand(0));
281     else
282       AliaseeGV = cast<llvm::GlobalValue>(Aliasee);
283 
284     if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
285       StringRef AliasSection = SA->getName();
286       if (AliasSection != AliaseeGV->getSection())
287         Diags.Report(SA->getLocation(), diag::warn_alias_with_section)
288             << AliasSection;
289     }
290 
291     // We have to handle alias to weak aliases in here. LLVM itself disallows
292     // this since the object semantics would not match the IL one. For
293     // compatibility with gcc we implement it by just pointing the alias
294     // to its aliasee's aliasee. We also warn, since the user is probably
295     // expecting the link to be weak.
296     if (auto GA = dyn_cast<llvm::GlobalAlias>(AliaseeGV)) {
297       if (GA->mayBeOverridden()) {
298         Diags.Report(AA->getLocation(), diag::warn_alias_to_weak_alias)
299             << GV->getName() << GA->getName();
300         Aliasee = llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
301             GA->getAliasee(), Alias->getType());
302         Alias->setAliasee(Aliasee);
303       }
304     }
305   }
306   if (!Error)
307     return;
308 
309   for (const GlobalDecl &GD : Aliases) {
310     StringRef MangledName = getMangledName(GD);
311     llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
312     auto *Alias = cast<llvm::GlobalAlias>(Entry);
313     Alias->replaceAllUsesWith(llvm::UndefValue::get(Alias->getType()));
314     Alias->eraseFromParent();
315   }
316 }
317 
318 void CodeGenModule::clear() {
319   DeferredDeclsToEmit.clear();
320   if (OpenMPRuntime)
321     OpenMPRuntime->clear();
322 }
323 
324 void InstrProfStats::reportDiagnostics(DiagnosticsEngine &Diags,
325                                        StringRef MainFile) {
326   if (!hasDiagnostics())
327     return;
328   if (VisitedInMainFile > 0 && VisitedInMainFile == MissingInMainFile) {
329     if (MainFile.empty())
330       MainFile = "<stdin>";
331     Diags.Report(diag::warn_profile_data_unprofiled) << MainFile;
332   } else
333     Diags.Report(diag::warn_profile_data_out_of_date) << Visited << Missing
334                                                       << Mismatched;
335 }
336 
337 void CodeGenModule::Release() {
338   EmitDeferred();
339   applyReplacements();
340   checkAliases();
341   EmitCXXGlobalInitFunc();
342   EmitCXXGlobalDtorFunc();
343   EmitCXXThreadLocalInitFunc();
344   if (ObjCRuntime)
345     if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
346       AddGlobalCtor(ObjCInitFunction);
347   if (Context.getLangOpts().CUDA && !Context.getLangOpts().CUDAIsDevice &&
348       CUDARuntime) {
349     if (llvm::Function *CudaCtorFunction = CUDARuntime->makeModuleCtorFunction())
350       AddGlobalCtor(CudaCtorFunction);
351     if (llvm::Function *CudaDtorFunction = CUDARuntime->makeModuleDtorFunction())
352       AddGlobalDtor(CudaDtorFunction);
353   }
354   if (PGOReader && PGOStats.hasDiagnostics())
355     PGOStats.reportDiagnostics(getDiags(), getCodeGenOpts().MainFileName);
356   EmitCtorList(GlobalCtors, "llvm.global_ctors");
357   EmitCtorList(GlobalDtors, "llvm.global_dtors");
358   EmitGlobalAnnotations();
359   EmitStaticExternCAliases();
360   EmitDeferredUnusedCoverageMappings();
361   if (CoverageMapping)
362     CoverageMapping->emit();
363   emitLLVMUsed();
364 
365   if (CodeGenOpts.Autolink &&
366       (Context.getLangOpts().Modules || !LinkerOptionsMetadata.empty())) {
367     EmitModuleLinkOptions();
368   }
369   if (CodeGenOpts.DwarfVersion)
370     // We actually want the latest version when there are conflicts.
371     // We can change from Warning to Latest if such mode is supported.
372     getModule().addModuleFlag(llvm::Module::Warning, "Dwarf Version",
373                               CodeGenOpts.DwarfVersion);
374   if (DebugInfo)
375     // We support a single version in the linked module. The LLVM
376     // parser will drop debug info with a different version number
377     // (and warn about it, too).
378     getModule().addModuleFlag(llvm::Module::Warning, "Debug Info Version",
379                               llvm::DEBUG_METADATA_VERSION);
380 
381   // We need to record the widths of enums and wchar_t, so that we can generate
382   // the correct build attributes in the ARM backend.
383   llvm::Triple::ArchType Arch = Context.getTargetInfo().getTriple().getArch();
384   if (   Arch == llvm::Triple::arm
385       || Arch == llvm::Triple::armeb
386       || Arch == llvm::Triple::thumb
387       || Arch == llvm::Triple::thumbeb) {
388     // Width of wchar_t in bytes
389     uint64_t WCharWidth =
390         Context.getTypeSizeInChars(Context.getWideCharType()).getQuantity();
391     getModule().addModuleFlag(llvm::Module::Error, "wchar_size", WCharWidth);
392 
393     // The minimum width of an enum in bytes
394     uint64_t EnumWidth = Context.getLangOpts().ShortEnums ? 1 : 4;
395     getModule().addModuleFlag(llvm::Module::Error, "min_enum_size", EnumWidth);
396   }
397 
398   if (uint32_t PLevel = Context.getLangOpts().PICLevel) {
399     llvm::PICLevel::Level PL = llvm::PICLevel::Default;
400     switch (PLevel) {
401     case 0: break;
402     case 1: PL = llvm::PICLevel::Small; break;
403     case 2: PL = llvm::PICLevel::Large; break;
404     default: llvm_unreachable("Invalid PIC Level");
405     }
406 
407     getModule().setPICLevel(PL);
408   }
409 
410   SimplifyPersonality();
411 
412   if (getCodeGenOpts().EmitDeclMetadata)
413     EmitDeclMetadata();
414 
415   if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
416     EmitCoverageFile();
417 
418   if (DebugInfo)
419     DebugInfo->finalize();
420 
421   EmitVersionIdentMetadata();
422 
423   EmitTargetMetadata();
424 }
425 
426 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
427   // Make sure that this type is translated.
428   Types.UpdateCompletedType(TD);
429 }
430 
431 llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
432   if (!TBAA)
433     return nullptr;
434   return TBAA->getTBAAInfo(QTy);
435 }
436 
437 llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
438   if (!TBAA)
439     return nullptr;
440   return TBAA->getTBAAInfoForVTablePtr();
441 }
442 
443 llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
444   if (!TBAA)
445     return nullptr;
446   return TBAA->getTBAAStructInfo(QTy);
447 }
448 
449 llvm::MDNode *CodeGenModule::getTBAAStructTypeInfo(QualType QTy) {
450   if (!TBAA)
451     return nullptr;
452   return TBAA->getTBAAStructTypeInfo(QTy);
453 }
454 
455 llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
456                                                   llvm::MDNode *AccessN,
457                                                   uint64_t O) {
458   if (!TBAA)
459     return nullptr;
460   return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
461 }
462 
463 /// Decorate the instruction with a TBAA tag. For both scalar TBAA
464 /// and struct-path aware TBAA, the tag has the same format:
465 /// base type, access type and offset.
466 /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
467 void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
468                                         llvm::MDNode *TBAAInfo,
469                                         bool ConvertTypeToTag) {
470   if (ConvertTypeToTag && TBAA)
471     Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
472                       TBAA->getTBAAScalarTagInfo(TBAAInfo));
473   else
474     Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
475 }
476 
477 void CodeGenModule::Error(SourceLocation loc, StringRef message) {
478   unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, "%0");
479   getDiags().Report(Context.getFullLoc(loc), diagID) << message;
480 }
481 
482 /// ErrorUnsupported - Print out an error that codegen doesn't support the
483 /// specified stmt yet.
484 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type) {
485   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
486                                                "cannot compile this %0 yet");
487   std::string Msg = Type;
488   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
489     << Msg << S->getSourceRange();
490 }
491 
492 /// ErrorUnsupported - Print out an error that codegen doesn't support the
493 /// specified decl yet.
494 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type) {
495   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
496                                                "cannot compile this %0 yet");
497   std::string Msg = Type;
498   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
499 }
500 
501 llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
502   return llvm::ConstantInt::get(SizeTy, size.getQuantity());
503 }
504 
505 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
506                                         const NamedDecl *D) const {
507   // Internal definitions always have default visibility.
508   if (GV->hasLocalLinkage()) {
509     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
510     return;
511   }
512 
513   // Set visibility for definitions.
514   LinkageInfo LV = D->getLinkageAndVisibility();
515   if (LV.isVisibilityExplicit() || !GV->hasAvailableExternallyLinkage())
516     GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
517 }
518 
519 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
520   return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
521       .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
522       .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
523       .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
524       .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
525 }
526 
527 static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
528     CodeGenOptions::TLSModel M) {
529   switch (M) {
530   case CodeGenOptions::GeneralDynamicTLSModel:
531     return llvm::GlobalVariable::GeneralDynamicTLSModel;
532   case CodeGenOptions::LocalDynamicTLSModel:
533     return llvm::GlobalVariable::LocalDynamicTLSModel;
534   case CodeGenOptions::InitialExecTLSModel:
535     return llvm::GlobalVariable::InitialExecTLSModel;
536   case CodeGenOptions::LocalExecTLSModel:
537     return llvm::GlobalVariable::LocalExecTLSModel;
538   }
539   llvm_unreachable("Invalid TLS model!");
540 }
541 
542 void CodeGenModule::setTLSMode(llvm::GlobalValue *GV, const VarDecl &D) const {
543   assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
544 
545   llvm::GlobalValue::ThreadLocalMode TLM;
546   TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
547 
548   // Override the TLS model if it is explicitly specified.
549   if (const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>()) {
550     TLM = GetLLVMTLSModel(Attr->getModel());
551   }
552 
553   GV->setThreadLocalMode(TLM);
554 }
555 
556 StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
557   StringRef &FoundStr = MangledDeclNames[GD.getCanonicalDecl()];
558   if (!FoundStr.empty())
559     return FoundStr;
560 
561   const auto *ND = cast<NamedDecl>(GD.getDecl());
562   SmallString<256> Buffer;
563   StringRef Str;
564   if (getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
565     llvm::raw_svector_ostream Out(Buffer);
566     if (const auto *D = dyn_cast<CXXConstructorDecl>(ND))
567       getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
568     else if (const auto *D = dyn_cast<CXXDestructorDecl>(ND))
569       getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
570     else
571       getCXXABI().getMangleContext().mangleName(ND, Out);
572     Str = Out.str();
573   } else {
574     IdentifierInfo *II = ND->getIdentifier();
575     assert(II && "Attempt to mangle unnamed decl.");
576     Str = II->getName();
577   }
578 
579   // Keep the first result in the case of a mangling collision.
580   auto Result = Manglings.insert(std::make_pair(Str, GD));
581   return FoundStr = Result.first->first();
582 }
583 
584 StringRef CodeGenModule::getBlockMangledName(GlobalDecl GD,
585                                              const BlockDecl *BD) {
586   MangleContext &MangleCtx = getCXXABI().getMangleContext();
587   const Decl *D = GD.getDecl();
588 
589   SmallString<256> Buffer;
590   llvm::raw_svector_ostream Out(Buffer);
591   if (!D)
592     MangleCtx.mangleGlobalBlock(BD,
593       dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
594   else if (const auto *CD = dyn_cast<CXXConstructorDecl>(D))
595     MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
596   else if (const auto *DD = dyn_cast<CXXDestructorDecl>(D))
597     MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
598   else
599     MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
600 
601   auto Result = Manglings.insert(std::make_pair(Out.str(), BD));
602   return Result.first->first();
603 }
604 
605 llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
606   return getModule().getNamedValue(Name);
607 }
608 
609 /// AddGlobalCtor - Add a function to the list that will be called before
610 /// main() runs.
611 void CodeGenModule::AddGlobalCtor(llvm::Function *Ctor, int Priority,
612                                   llvm::Constant *AssociatedData) {
613   // FIXME: Type coercion of void()* types.
614   GlobalCtors.push_back(Structor(Priority, Ctor, AssociatedData));
615 }
616 
617 /// AddGlobalDtor - Add a function to the list that will be called
618 /// when the module is unloaded.
619 void CodeGenModule::AddGlobalDtor(llvm::Function *Dtor, int Priority) {
620   // FIXME: Type coercion of void()* types.
621   GlobalDtors.push_back(Structor(Priority, Dtor, nullptr));
622 }
623 
624 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
625   // Ctor function type is void()*.
626   llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
627   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
628 
629   // Get the type of a ctor entry, { i32, void ()*, i8* }.
630   llvm::StructType *CtorStructTy = llvm::StructType::get(
631       Int32Ty, llvm::PointerType::getUnqual(CtorFTy), VoidPtrTy, nullptr);
632 
633   // Construct the constructor and destructor arrays.
634   SmallVector<llvm::Constant *, 8> Ctors;
635   for (const auto &I : Fns) {
636     llvm::Constant *S[] = {
637         llvm::ConstantInt::get(Int32Ty, I.Priority, false),
638         llvm::ConstantExpr::getBitCast(I.Initializer, CtorPFTy),
639         (I.AssociatedData
640              ? llvm::ConstantExpr::getBitCast(I.AssociatedData, VoidPtrTy)
641              : llvm::Constant::getNullValue(VoidPtrTy))};
642     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
643   }
644 
645   if (!Ctors.empty()) {
646     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
647     new llvm::GlobalVariable(TheModule, AT, false,
648                              llvm::GlobalValue::AppendingLinkage,
649                              llvm::ConstantArray::get(AT, Ctors),
650                              GlobalName);
651   }
652 }
653 
654 llvm::GlobalValue::LinkageTypes
655 CodeGenModule::getFunctionLinkage(GlobalDecl GD) {
656   const auto *D = cast<FunctionDecl>(GD.getDecl());
657 
658   GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
659 
660   if (isa<CXXDestructorDecl>(D) &&
661       getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
662                                          GD.getDtorType())) {
663     // Destructor variants in the Microsoft C++ ABI are always internal or
664     // linkonce_odr thunks emitted on an as-needed basis.
665     return Linkage == GVA_Internal ? llvm::GlobalValue::InternalLinkage
666                                    : llvm::GlobalValue::LinkOnceODRLinkage;
667   }
668 
669   return getLLVMLinkageForDeclarator(D, Linkage, /*isConstantVariable=*/false);
670 }
671 
672 void CodeGenModule::setFunctionDLLStorageClass(GlobalDecl GD, llvm::Function *F) {
673   const auto *FD = cast<FunctionDecl>(GD.getDecl());
674 
675   if (const auto *Dtor = dyn_cast_or_null<CXXDestructorDecl>(FD)) {
676     if (getCXXABI().useThunkForDtorVariant(Dtor, GD.getDtorType())) {
677       // Don't dllexport/import destructor thunks.
678       F->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
679       return;
680     }
681   }
682 
683   if (FD->hasAttr<DLLImportAttr>())
684     F->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
685   else if (FD->hasAttr<DLLExportAttr>())
686     F->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
687   else
688     F->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
689 }
690 
691 void CodeGenModule::setFunctionDefinitionAttributes(const FunctionDecl *D,
692                                                     llvm::Function *F) {
693   setNonAliasAttributes(D, F);
694 }
695 
696 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
697                                               const CGFunctionInfo &Info,
698                                               llvm::Function *F) {
699   unsigned CallingConv;
700   AttributeListType AttributeList;
701   ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
702   F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
703   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
704 }
705 
706 /// Determines whether the language options require us to model
707 /// unwind exceptions.  We treat -fexceptions as mandating this
708 /// except under the fragile ObjC ABI with only ObjC exceptions
709 /// enabled.  This means, for example, that C with -fexceptions
710 /// enables this.
711 static bool hasUnwindExceptions(const LangOptions &LangOpts) {
712   // If exceptions are completely disabled, obviously this is false.
713   if (!LangOpts.Exceptions) return false;
714 
715   // If C++ exceptions are enabled, this is true.
716   if (LangOpts.CXXExceptions) return true;
717 
718   // If ObjC exceptions are enabled, this depends on the ABI.
719   if (LangOpts.ObjCExceptions) {
720     return LangOpts.ObjCRuntime.hasUnwindExceptions();
721   }
722 
723   return true;
724 }
725 
726 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
727                                                            llvm::Function *F) {
728   llvm::AttrBuilder B;
729 
730   if (CodeGenOpts.UnwindTables)
731     B.addAttribute(llvm::Attribute::UWTable);
732 
733   if (!hasUnwindExceptions(LangOpts))
734     B.addAttribute(llvm::Attribute::NoUnwind);
735 
736   if (D->hasAttr<NakedAttr>()) {
737     // Naked implies noinline: we should not be inlining such functions.
738     B.addAttribute(llvm::Attribute::Naked);
739     B.addAttribute(llvm::Attribute::NoInline);
740   } else if (D->hasAttr<NoDuplicateAttr>()) {
741     B.addAttribute(llvm::Attribute::NoDuplicate);
742   } else if (D->hasAttr<NoInlineAttr>()) {
743     B.addAttribute(llvm::Attribute::NoInline);
744   } else if (D->hasAttr<AlwaysInlineAttr>() &&
745              !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
746                                               llvm::Attribute::NoInline)) {
747     // (noinline wins over always_inline, and we can't specify both in IR)
748     B.addAttribute(llvm::Attribute::AlwaysInline);
749   }
750 
751   if (D->hasAttr<ColdAttr>()) {
752     if (!D->hasAttr<OptimizeNoneAttr>())
753       B.addAttribute(llvm::Attribute::OptimizeForSize);
754     B.addAttribute(llvm::Attribute::Cold);
755   }
756 
757   if (D->hasAttr<MinSizeAttr>())
758     B.addAttribute(llvm::Attribute::MinSize);
759 
760   if (LangOpts.getStackProtector() == LangOptions::SSPOn)
761     B.addAttribute(llvm::Attribute::StackProtect);
762   else if (LangOpts.getStackProtector() == LangOptions::SSPStrong)
763     B.addAttribute(llvm::Attribute::StackProtectStrong);
764   else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
765     B.addAttribute(llvm::Attribute::StackProtectReq);
766 
767   F->addAttributes(llvm::AttributeSet::FunctionIndex,
768                    llvm::AttributeSet::get(
769                        F->getContext(), llvm::AttributeSet::FunctionIndex, B));
770 
771   if (D->hasAttr<OptimizeNoneAttr>()) {
772     // OptimizeNone implies noinline; we should not be inlining such functions.
773     F->addFnAttr(llvm::Attribute::OptimizeNone);
774     F->addFnAttr(llvm::Attribute::NoInline);
775 
776     // OptimizeNone wins over OptimizeForSize, MinSize, AlwaysInline.
777     assert(!F->hasFnAttribute(llvm::Attribute::OptimizeForSize) &&
778            "OptimizeNone and OptimizeForSize on same function!");
779     assert(!F->hasFnAttribute(llvm::Attribute::MinSize) &&
780            "OptimizeNone and MinSize on same function!");
781     assert(!F->hasFnAttribute(llvm::Attribute::AlwaysInline) &&
782            "OptimizeNone and AlwaysInline on same function!");
783 
784     // Attribute 'inlinehint' has no effect on 'optnone' functions.
785     // Explicitly remove it from the set of function attributes.
786     F->removeFnAttr(llvm::Attribute::InlineHint);
787   }
788 
789   if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
790     F->setUnnamedAddr(true);
791   else if (const auto *MD = dyn_cast<CXXMethodDecl>(D))
792     if (MD->isVirtual())
793       F->setUnnamedAddr(true);
794 
795   unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
796   if (alignment)
797     F->setAlignment(alignment);
798 
799   // C++ ABI requires 2-byte alignment for member functions.
800   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
801     F->setAlignment(2);
802 }
803 
804 void CodeGenModule::SetCommonAttributes(const Decl *D,
805                                         llvm::GlobalValue *GV) {
806   if (const auto *ND = dyn_cast<NamedDecl>(D))
807     setGlobalVisibility(GV, ND);
808   else
809     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
810 
811   if (D->hasAttr<UsedAttr>())
812     addUsedGlobal(GV);
813 }
814 
815 void CodeGenModule::setAliasAttributes(const Decl *D,
816                                        llvm::GlobalValue *GV) {
817   SetCommonAttributes(D, GV);
818 
819   // Process the dllexport attribute based on whether the original definition
820   // (not necessarily the aliasee) was exported.
821   if (D->hasAttr<DLLExportAttr>())
822     GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
823 }
824 
825 void CodeGenModule::setNonAliasAttributes(const Decl *D,
826                                           llvm::GlobalObject *GO) {
827   SetCommonAttributes(D, GO);
828 
829   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
830     GO->setSection(SA->getName());
831 
832   getTargetCodeGenInfo().setTargetAttributes(D, GO, *this);
833 }
834 
835 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
836                                                   llvm::Function *F,
837                                                   const CGFunctionInfo &FI) {
838   SetLLVMFunctionAttributes(D, FI, F);
839   SetLLVMFunctionAttributesForDefinition(D, F);
840 
841   F->setLinkage(llvm::Function::InternalLinkage);
842 
843   setNonAliasAttributes(D, F);
844 }
845 
846 static void setLinkageAndVisibilityForGV(llvm::GlobalValue *GV,
847                                          const NamedDecl *ND) {
848   // Set linkage and visibility in case we never see a definition.
849   LinkageInfo LV = ND->getLinkageAndVisibility();
850   if (LV.getLinkage() != ExternalLinkage) {
851     // Don't set internal linkage on declarations.
852   } else {
853     if (ND->hasAttr<DLLImportAttr>()) {
854       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
855       GV->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
856     } else if (ND->hasAttr<DLLExportAttr>()) {
857       GV->setLinkage(llvm::GlobalValue::ExternalLinkage);
858       GV->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
859     } else if (ND->hasAttr<WeakAttr>() || ND->isWeakImported()) {
860       // "extern_weak" is overloaded in LLVM; we probably should have
861       // separate linkage types for this.
862       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
863     }
864 
865     // Set visibility on a declaration only if it's explicit.
866     if (LV.isVisibilityExplicit())
867       GV->setVisibility(CodeGenModule::GetLLVMVisibility(LV.getVisibility()));
868   }
869 }
870 
871 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD, llvm::Function *F,
872                                           bool IsIncompleteFunction,
873                                           bool IsThunk) {
874   if (llvm::Intrinsic::ID IID = F->getIntrinsicID()) {
875     // If this is an intrinsic function, set the function's attributes
876     // to the intrinsic's attributes.
877     F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(), IID));
878     return;
879   }
880 
881   const auto *FD = cast<FunctionDecl>(GD.getDecl());
882 
883   if (!IsIncompleteFunction)
884     SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
885 
886   // Add the Returned attribute for "this", except for iOS 5 and earlier
887   // where substantial code, including the libstdc++ dylib, was compiled with
888   // GCC and does not actually return "this".
889   if (!IsThunk && getCXXABI().HasThisReturn(GD) &&
890       !(getTarget().getTriple().isiOS() &&
891         getTarget().getTriple().isOSVersionLT(6))) {
892     assert(!F->arg_empty() &&
893            F->arg_begin()->getType()
894              ->canLosslesslyBitCastTo(F->getReturnType()) &&
895            "unexpected this return");
896     F->addAttribute(1, llvm::Attribute::Returned);
897   }
898 
899   // Only a few attributes are set on declarations; these may later be
900   // overridden by a definition.
901 
902   setLinkageAndVisibilityForGV(F, FD);
903 
904   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
905     F->setSection(SA->getName());
906 
907   // A replaceable global allocation function does not act like a builtin by
908   // default, only if it is invoked by a new-expression or delete-expression.
909   if (FD->isReplaceableGlobalAllocationFunction())
910     F->addAttribute(llvm::AttributeSet::FunctionIndex,
911                     llvm::Attribute::NoBuiltin);
912 }
913 
914 void CodeGenModule::addUsedGlobal(llvm::GlobalValue *GV) {
915   assert(!GV->isDeclaration() &&
916          "Only globals with definition can force usage.");
917   LLVMUsed.emplace_back(GV);
918 }
919 
920 void CodeGenModule::addCompilerUsedGlobal(llvm::GlobalValue *GV) {
921   assert(!GV->isDeclaration() &&
922          "Only globals with definition can force usage.");
923   LLVMCompilerUsed.emplace_back(GV);
924 }
925 
926 static void emitUsed(CodeGenModule &CGM, StringRef Name,
927                      std::vector<llvm::WeakVH> &List) {
928   // Don't create llvm.used if there is no need.
929   if (List.empty())
930     return;
931 
932   // Convert List to what ConstantArray needs.
933   SmallVector<llvm::Constant*, 8> UsedArray;
934   UsedArray.resize(List.size());
935   for (unsigned i = 0, e = List.size(); i != e; ++i) {
936     UsedArray[i] =
937         llvm::ConstantExpr::getPointerBitCastOrAddrSpaceCast(
938             cast<llvm::Constant>(&*List[i]), CGM.Int8PtrTy);
939   }
940 
941   if (UsedArray.empty())
942     return;
943   llvm::ArrayType *ATy = llvm::ArrayType::get(CGM.Int8PtrTy, UsedArray.size());
944 
945   auto *GV = new llvm::GlobalVariable(
946       CGM.getModule(), ATy, false, llvm::GlobalValue::AppendingLinkage,
947       llvm::ConstantArray::get(ATy, UsedArray), Name);
948 
949   GV->setSection("llvm.metadata");
950 }
951 
952 void CodeGenModule::emitLLVMUsed() {
953   emitUsed(*this, "llvm.used", LLVMUsed);
954   emitUsed(*this, "llvm.compiler.used", LLVMCompilerUsed);
955 }
956 
957 void CodeGenModule::AppendLinkerOptions(StringRef Opts) {
958   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opts);
959   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
960 }
961 
962 void CodeGenModule::AddDetectMismatch(StringRef Name, StringRef Value) {
963   llvm::SmallString<32> Opt;
964   getTargetCodeGenInfo().getDetectMismatchOption(Name, Value, Opt);
965   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
966   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
967 }
968 
969 void CodeGenModule::AddDependentLib(StringRef Lib) {
970   llvm::SmallString<24> Opt;
971   getTargetCodeGenInfo().getDependentLibraryOption(Lib, Opt);
972   auto *MDOpts = llvm::MDString::get(getLLVMContext(), Opt);
973   LinkerOptionsMetadata.push_back(llvm::MDNode::get(getLLVMContext(), MDOpts));
974 }
975 
976 /// \brief Add link options implied by the given module, including modules
977 /// it depends on, using a postorder walk.
978 static void addLinkOptionsPostorder(CodeGenModule &CGM, Module *Mod,
979                                     SmallVectorImpl<llvm::Metadata *> &Metadata,
980                                     llvm::SmallPtrSet<Module *, 16> &Visited) {
981   // Import this module's parent.
982   if (Mod->Parent && Visited.insert(Mod->Parent).second) {
983     addLinkOptionsPostorder(CGM, Mod->Parent, Metadata, Visited);
984   }
985 
986   // Import this module's dependencies.
987   for (unsigned I = Mod->Imports.size(); I > 0; --I) {
988     if (Visited.insert(Mod->Imports[I - 1]).second)
989       addLinkOptionsPostorder(CGM, Mod->Imports[I-1], Metadata, Visited);
990   }
991 
992   // Add linker options to link against the libraries/frameworks
993   // described by this module.
994   llvm::LLVMContext &Context = CGM.getLLVMContext();
995   for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
996     // Link against a framework.  Frameworks are currently Darwin only, so we
997     // don't to ask TargetCodeGenInfo for the spelling of the linker option.
998     if (Mod->LinkLibraries[I-1].IsFramework) {
999       llvm::Metadata *Args[2] = {
1000           llvm::MDString::get(Context, "-framework"),
1001           llvm::MDString::get(Context, Mod->LinkLibraries[I - 1].Library)};
1002 
1003       Metadata.push_back(llvm::MDNode::get(Context, Args));
1004       continue;
1005     }
1006 
1007     // Link against a library.
1008     llvm::SmallString<24> Opt;
1009     CGM.getTargetCodeGenInfo().getDependentLibraryOption(
1010       Mod->LinkLibraries[I-1].Library, Opt);
1011     auto *OptString = llvm::MDString::get(Context, Opt);
1012     Metadata.push_back(llvm::MDNode::get(Context, OptString));
1013   }
1014 }
1015 
1016 void CodeGenModule::EmitModuleLinkOptions() {
1017   // Collect the set of all of the modules we want to visit to emit link
1018   // options, which is essentially the imported modules and all of their
1019   // non-explicit child modules.
1020   llvm::SetVector<clang::Module *> LinkModules;
1021   llvm::SmallPtrSet<clang::Module *, 16> Visited;
1022   SmallVector<clang::Module *, 16> Stack;
1023 
1024   // Seed the stack with imported modules.
1025   for (Module *M : ImportedModules)
1026     if (Visited.insert(M).second)
1027       Stack.push_back(M);
1028 
1029   // Find all of the modules to import, making a little effort to prune
1030   // non-leaf modules.
1031   while (!Stack.empty()) {
1032     clang::Module *Mod = Stack.pop_back_val();
1033 
1034     bool AnyChildren = false;
1035 
1036     // Visit the submodules of this module.
1037     for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
1038                                         SubEnd = Mod->submodule_end();
1039          Sub != SubEnd; ++Sub) {
1040       // Skip explicit children; they need to be explicitly imported to be
1041       // linked against.
1042       if ((*Sub)->IsExplicit)
1043         continue;
1044 
1045       if (Visited.insert(*Sub).second) {
1046         Stack.push_back(*Sub);
1047         AnyChildren = true;
1048       }
1049     }
1050 
1051     // We didn't find any children, so add this module to the list of
1052     // modules to link against.
1053     if (!AnyChildren) {
1054       LinkModules.insert(Mod);
1055     }
1056   }
1057 
1058   // Add link options for all of the imported modules in reverse topological
1059   // order.  We don't do anything to try to order import link flags with respect
1060   // to linker options inserted by things like #pragma comment().
1061   SmallVector<llvm::Metadata *, 16> MetadataArgs;
1062   Visited.clear();
1063   for (Module *M : LinkModules)
1064     if (Visited.insert(M).second)
1065       addLinkOptionsPostorder(*this, M, MetadataArgs, Visited);
1066   std::reverse(MetadataArgs.begin(), MetadataArgs.end());
1067   LinkerOptionsMetadata.append(MetadataArgs.begin(), MetadataArgs.end());
1068 
1069   // Add the linker options metadata flag.
1070   getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
1071                             llvm::MDNode::get(getLLVMContext(),
1072                                               LinkerOptionsMetadata));
1073 }
1074 
1075 void CodeGenModule::EmitDeferred() {
1076   // Emit code for any potentially referenced deferred decls.  Since a
1077   // previously unused static decl may become used during the generation of code
1078   // for a static function, iterate until no changes are made.
1079 
1080   if (!DeferredVTables.empty()) {
1081     EmitDeferredVTables();
1082 
1083     // Emitting a v-table doesn't directly cause more v-tables to
1084     // become deferred, although it can cause functions to be
1085     // emitted that then need those v-tables.
1086     assert(DeferredVTables.empty());
1087   }
1088 
1089   // Stop if we're out of both deferred v-tables and deferred declarations.
1090   if (DeferredDeclsToEmit.empty())
1091     return;
1092 
1093   // Grab the list of decls to emit. If EmitGlobalDefinition schedules more
1094   // work, it will not interfere with this.
1095   std::vector<DeferredGlobal> CurDeclsToEmit;
1096   CurDeclsToEmit.swap(DeferredDeclsToEmit);
1097 
1098   for (DeferredGlobal &G : CurDeclsToEmit) {
1099     GlobalDecl D = G.GD;
1100     llvm::GlobalValue *GV = G.GV;
1101     G.GV = nullptr;
1102 
1103     assert(!GV || GV == GetGlobalValue(getMangledName(D)));
1104     if (!GV)
1105       GV = GetGlobalValue(getMangledName(D));
1106 
1107     // Check to see if we've already emitted this.  This is necessary
1108     // for a couple of reasons: first, decls can end up in the
1109     // deferred-decls queue multiple times, and second, decls can end
1110     // up with definitions in unusual ways (e.g. by an extern inline
1111     // function acquiring a strong function redefinition).  Just
1112     // ignore these cases.
1113     if (GV && !GV->isDeclaration())
1114       continue;
1115 
1116     // Otherwise, emit the definition and move on to the next one.
1117     EmitGlobalDefinition(D, GV);
1118 
1119     // If we found out that we need to emit more decls, do that recursively.
1120     // This has the advantage that the decls are emitted in a DFS and related
1121     // ones are close together, which is convenient for testing.
1122     if (!DeferredVTables.empty() || !DeferredDeclsToEmit.empty()) {
1123       EmitDeferred();
1124       assert(DeferredVTables.empty() && DeferredDeclsToEmit.empty());
1125     }
1126   }
1127 }
1128 
1129 void CodeGenModule::EmitGlobalAnnotations() {
1130   if (Annotations.empty())
1131     return;
1132 
1133   // Create a new global variable for the ConstantStruct in the Module.
1134   llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
1135     Annotations[0]->getType(), Annotations.size()), Annotations);
1136   auto *gv = new llvm::GlobalVariable(getModule(), Array->getType(), false,
1137                                       llvm::GlobalValue::AppendingLinkage,
1138                                       Array, "llvm.global.annotations");
1139   gv->setSection(AnnotationSection);
1140 }
1141 
1142 llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
1143   llvm::Constant *&AStr = AnnotationStrings[Str];
1144   if (AStr)
1145     return AStr;
1146 
1147   // Not found yet, create a new global.
1148   llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
1149   auto *gv =
1150       new llvm::GlobalVariable(getModule(), s->getType(), true,
1151                                llvm::GlobalValue::PrivateLinkage, s, ".str");
1152   gv->setSection(AnnotationSection);
1153   gv->setUnnamedAddr(true);
1154   AStr = gv;
1155   return gv;
1156 }
1157 
1158 llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
1159   SourceManager &SM = getContext().getSourceManager();
1160   PresumedLoc PLoc = SM.getPresumedLoc(Loc);
1161   if (PLoc.isValid())
1162     return EmitAnnotationString(PLoc.getFilename());
1163   return EmitAnnotationString(SM.getBufferName(Loc));
1164 }
1165 
1166 llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
1167   SourceManager &SM = getContext().getSourceManager();
1168   PresumedLoc PLoc = SM.getPresumedLoc(L);
1169   unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
1170     SM.getExpansionLineNumber(L);
1171   return llvm::ConstantInt::get(Int32Ty, LineNo);
1172 }
1173 
1174 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
1175                                                 const AnnotateAttr *AA,
1176                                                 SourceLocation L) {
1177   // Get the globals for file name, annotation, and the line number.
1178   llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
1179                  *UnitGV = EmitAnnotationUnit(L),
1180                  *LineNoCst = EmitAnnotationLineNo(L);
1181 
1182   // Create the ConstantStruct for the global annotation.
1183   llvm::Constant *Fields[4] = {
1184     llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
1185     llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
1186     llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
1187     LineNoCst
1188   };
1189   return llvm::ConstantStruct::getAnon(Fields);
1190 }
1191 
1192 void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
1193                                          llvm::GlobalValue *GV) {
1194   assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
1195   // Get the struct elements for these annotations.
1196   for (const auto *I : D->specific_attrs<AnnotateAttr>())
1197     Annotations.push_back(EmitAnnotateAttr(GV, I, D->getLocation()));
1198 }
1199 
1200 bool CodeGenModule::isInSanitizerBlacklist(llvm::Function *Fn,
1201                                            SourceLocation Loc) const {
1202   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1203   // Blacklist by function name.
1204   if (SanitizerBL.isBlacklistedFunction(Fn->getName()))
1205     return true;
1206   // Blacklist by location.
1207   if (!Loc.isInvalid())
1208     return SanitizerBL.isBlacklistedLocation(Loc);
1209   // If location is unknown, this may be a compiler-generated function. Assume
1210   // it's located in the main file.
1211   auto &SM = Context.getSourceManager();
1212   if (const auto *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
1213     return SanitizerBL.isBlacklistedFile(MainFile->getName());
1214   }
1215   return false;
1216 }
1217 
1218 bool CodeGenModule::isInSanitizerBlacklist(llvm::GlobalVariable *GV,
1219                                            SourceLocation Loc, QualType Ty,
1220                                            StringRef Category) const {
1221   // For now globals can be blacklisted only in ASan and KASan.
1222   if (!LangOpts.Sanitize.hasOneOf(
1223           SanitizerKind::Address | SanitizerKind::KernelAddress))
1224     return false;
1225   const auto &SanitizerBL = getContext().getSanitizerBlacklist();
1226   if (SanitizerBL.isBlacklistedGlobal(GV->getName(), Category))
1227     return true;
1228   if (SanitizerBL.isBlacklistedLocation(Loc, Category))
1229     return true;
1230   // Check global type.
1231   if (!Ty.isNull()) {
1232     // Drill down the array types: if global variable of a fixed type is
1233     // blacklisted, we also don't instrument arrays of them.
1234     while (auto AT = dyn_cast<ArrayType>(Ty.getTypePtr()))
1235       Ty = AT->getElementType();
1236     Ty = Ty.getCanonicalType().getUnqualifiedType();
1237     // We allow to blacklist only record types (classes, structs etc.)
1238     if (Ty->isRecordType()) {
1239       std::string TypeStr = Ty.getAsString(getContext().getPrintingPolicy());
1240       if (SanitizerBL.isBlacklistedType(TypeStr, Category))
1241         return true;
1242     }
1243   }
1244   return false;
1245 }
1246 
1247 bool CodeGenModule::MustBeEmitted(const ValueDecl *Global) {
1248   // Never defer when EmitAllDecls is specified.
1249   if (LangOpts.EmitAllDecls)
1250     return true;
1251 
1252   return getContext().DeclMustBeEmitted(Global);
1253 }
1254 
1255 bool CodeGenModule::MayBeEmittedEagerly(const ValueDecl *Global) {
1256   if (const auto *FD = dyn_cast<FunctionDecl>(Global))
1257     if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1258       // Implicit template instantiations may change linkage if they are later
1259       // explicitly instantiated, so they should not be emitted eagerly.
1260       return false;
1261 
1262   return true;
1263 }
1264 
1265 llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
1266     const CXXUuidofExpr* E) {
1267   // Sema has verified that IIDSource has a __declspec(uuid()), and that its
1268   // well-formed.
1269   StringRef Uuid = E->getUuidAsStringRef(Context);
1270   std::string Name = "_GUID_" + Uuid.lower();
1271   std::replace(Name.begin(), Name.end(), '-', '_');
1272 
1273   // Look for an existing global.
1274   if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
1275     return GV;
1276 
1277   llvm::Constant *Init = EmitUuidofInitializer(Uuid);
1278   assert(Init && "failed to initialize as constant");
1279 
1280   auto *GV = new llvm::GlobalVariable(
1281       getModule(), Init->getType(),
1282       /*isConstant=*/true, llvm::GlobalValue::LinkOnceODRLinkage, Init, Name);
1283   if (supportsCOMDAT())
1284     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1285   return GV;
1286 }
1287 
1288 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1289   const AliasAttr *AA = VD->getAttr<AliasAttr>();
1290   assert(AA && "No alias?");
1291 
1292   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
1293 
1294   // See if there is already something with the target's name in the module.
1295   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
1296   if (Entry) {
1297     unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1298     return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1299   }
1300 
1301   llvm::Constant *Aliasee;
1302   if (isa<llvm::FunctionType>(DeclTy))
1303     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1304                                       GlobalDecl(cast<FunctionDecl>(VD)),
1305                                       /*ForVTable=*/false);
1306   else
1307     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1308                                     llvm::PointerType::getUnqual(DeclTy),
1309                                     nullptr);
1310 
1311   auto *F = cast<llvm::GlobalValue>(Aliasee);
1312   F->setLinkage(llvm::Function::ExternalWeakLinkage);
1313   WeakRefReferences.insert(F);
1314 
1315   return Aliasee;
1316 }
1317 
1318 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
1319   const auto *Global = cast<ValueDecl>(GD.getDecl());
1320 
1321   // Weak references don't produce any output by themselves.
1322   if (Global->hasAttr<WeakRefAttr>())
1323     return;
1324 
1325   // If this is an alias definition (which otherwise looks like a declaration)
1326   // emit it now.
1327   if (Global->hasAttr<AliasAttr>())
1328     return EmitAliasDefinition(GD);
1329 
1330   // If this is CUDA, be selective about which declarations we emit.
1331   if (LangOpts.CUDA) {
1332     if (LangOpts.CUDAIsDevice) {
1333       if (!Global->hasAttr<CUDADeviceAttr>() &&
1334           !Global->hasAttr<CUDAGlobalAttr>() &&
1335           !Global->hasAttr<CUDAConstantAttr>() &&
1336           !Global->hasAttr<CUDASharedAttr>())
1337         return;
1338     } else {
1339       if (!Global->hasAttr<CUDAHostAttr>() && (
1340             Global->hasAttr<CUDADeviceAttr>() ||
1341             Global->hasAttr<CUDAConstantAttr>() ||
1342             Global->hasAttr<CUDASharedAttr>()))
1343         return;
1344     }
1345   }
1346 
1347   // Ignore declarations, they will be emitted on their first use.
1348   if (const auto *FD = dyn_cast<FunctionDecl>(Global)) {
1349     // Forward declarations are emitted lazily on first use.
1350     if (!FD->doesThisDeclarationHaveABody()) {
1351       if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1352         return;
1353 
1354       StringRef MangledName = getMangledName(GD);
1355 
1356       // Compute the function info and LLVM type.
1357       const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1358       llvm::Type *Ty = getTypes().GetFunctionType(FI);
1359 
1360       GetOrCreateLLVMFunction(MangledName, Ty, GD, /*ForVTable=*/false,
1361                               /*DontDefer=*/false);
1362       return;
1363     }
1364   } else {
1365     const auto *VD = cast<VarDecl>(Global);
1366     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1367 
1368     if (VD->isThisDeclarationADefinition() != VarDecl::Definition &&
1369         !Context.isMSStaticDataMemberInlineDefinition(VD))
1370       return;
1371   }
1372 
1373   // Defer code generation to first use when possible, e.g. if this is an inline
1374   // function. If the global must always be emitted, do it eagerly if possible
1375   // to benefit from cache locality.
1376   if (MustBeEmitted(Global) && MayBeEmittedEagerly(Global)) {
1377     // Emit the definition if it can't be deferred.
1378     EmitGlobalDefinition(GD);
1379     return;
1380   }
1381 
1382   // If we're deferring emission of a C++ variable with an
1383   // initializer, remember the order in which it appeared in the file.
1384   if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
1385       cast<VarDecl>(Global)->hasInit()) {
1386     DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1387     CXXGlobalInits.push_back(nullptr);
1388   }
1389 
1390   StringRef MangledName = getMangledName(GD);
1391   if (llvm::GlobalValue *GV = GetGlobalValue(MangledName)) {
1392     // The value has already been used and should therefore be emitted.
1393     addDeferredDeclToEmit(GV, GD);
1394   } else if (MustBeEmitted(Global)) {
1395     // The value must be emitted, but cannot be emitted eagerly.
1396     assert(!MayBeEmittedEagerly(Global));
1397     addDeferredDeclToEmit(/*GV=*/nullptr, GD);
1398   } else {
1399     // Otherwise, remember that we saw a deferred decl with this name.  The
1400     // first use of the mangled name will cause it to move into
1401     // DeferredDeclsToEmit.
1402     DeferredDecls[MangledName] = GD;
1403   }
1404 }
1405 
1406 namespace {
1407   struct FunctionIsDirectlyRecursive :
1408     public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1409     const StringRef Name;
1410     const Builtin::Context &BI;
1411     bool Result;
1412     FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1413       Name(N), BI(C), Result(false) {
1414     }
1415     typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1416 
1417     bool TraverseCallExpr(CallExpr *E) {
1418       const FunctionDecl *FD = E->getDirectCallee();
1419       if (!FD)
1420         return true;
1421       AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1422       if (Attr && Name == Attr->getLabel()) {
1423         Result = true;
1424         return false;
1425       }
1426       unsigned BuiltinID = FD->getBuiltinID();
1427       if (!BuiltinID)
1428         return true;
1429       StringRef BuiltinName = BI.GetName(BuiltinID);
1430       if (BuiltinName.startswith("__builtin_") &&
1431           Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
1432         Result = true;
1433         return false;
1434       }
1435       return true;
1436     }
1437   };
1438 }
1439 
1440 // isTriviallyRecursive - Check if this function calls another
1441 // decl that, because of the asm attribute or the other decl being a builtin,
1442 // ends up pointing to itself.
1443 bool
1444 CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1445   StringRef Name;
1446   if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
1447     // asm labels are a special kind of mangling we have to support.
1448     AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1449     if (!Attr)
1450       return false;
1451     Name = Attr->getLabel();
1452   } else {
1453     Name = FD->getName();
1454   }
1455 
1456   FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1457   Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
1458   return Walker.Result;
1459 }
1460 
1461 bool
1462 CodeGenModule::shouldEmitFunction(GlobalDecl GD) {
1463   if (getFunctionLinkage(GD) != llvm::Function::AvailableExternallyLinkage)
1464     return true;
1465   const auto *F = cast<FunctionDecl>(GD.getDecl());
1466   if (CodeGenOpts.OptimizationLevel == 0 && !F->hasAttr<AlwaysInlineAttr>())
1467     return false;
1468   // PR9614. Avoid cases where the source code is lying to us. An available
1469   // externally function should have an equivalent function somewhere else,
1470   // but a function that calls itself is clearly not equivalent to the real
1471   // implementation.
1472   // This happens in glibc's btowc and in some configure checks.
1473   return !isTriviallyRecursive(F);
1474 }
1475 
1476 /// If the type for the method's class was generated by
1477 /// CGDebugInfo::createContextChain(), the cache contains only a
1478 /// limited DIType without any declarations. Since EmitFunctionStart()
1479 /// needs to find the canonical declaration for each method, we need
1480 /// to construct the complete type prior to emitting the method.
1481 void CodeGenModule::CompleteDIClassType(const CXXMethodDecl* D) {
1482   if (!D->isInstance())
1483     return;
1484 
1485   if (CGDebugInfo *DI = getModuleDebugInfo())
1486     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo) {
1487       const auto *ThisPtr = cast<PointerType>(D->getThisType(getContext()));
1488       DI->getOrCreateRecordType(ThisPtr->getPointeeType(), D->getLocation());
1489     }
1490 }
1491 
1492 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD, llvm::GlobalValue *GV) {
1493   const auto *D = cast<ValueDecl>(GD.getDecl());
1494 
1495   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
1496                                  Context.getSourceManager(),
1497                                  "Generating code for declaration");
1498 
1499   if (isa<FunctionDecl>(D)) {
1500     // At -O0, don't generate IR for functions with available_externally
1501     // linkage.
1502     if (!shouldEmitFunction(GD))
1503       return;
1504 
1505     if (const auto *Method = dyn_cast<CXXMethodDecl>(D)) {
1506       CompleteDIClassType(Method);
1507       // Make sure to emit the definition(s) before we emit the thunks.
1508       // This is necessary for the generation of certain thunks.
1509       if (const auto *CD = dyn_cast<CXXConstructorDecl>(Method))
1510         ABI->emitCXXStructor(CD, getFromCtorType(GD.getCtorType()));
1511       else if (const auto *DD = dyn_cast<CXXDestructorDecl>(Method))
1512         ABI->emitCXXStructor(DD, getFromDtorType(GD.getDtorType()));
1513       else
1514         EmitGlobalFunctionDefinition(GD, GV);
1515 
1516       if (Method->isVirtual())
1517         getVTables().EmitThunks(GD);
1518 
1519       return;
1520     }
1521 
1522     return EmitGlobalFunctionDefinition(GD, GV);
1523   }
1524 
1525   if (const auto *VD = dyn_cast<VarDecl>(D))
1526     return EmitGlobalVarDefinition(VD);
1527 
1528   llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
1529 }
1530 
1531 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1532 /// module, create and return an llvm Function with the specified type. If there
1533 /// is something in the module with the specified name, return it potentially
1534 /// bitcasted to the right type.
1535 ///
1536 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1537 /// to set the attributes on the function when it is first created.
1538 llvm::Constant *
1539 CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
1540                                        llvm::Type *Ty,
1541                                        GlobalDecl GD, bool ForVTable,
1542                                        bool DontDefer, bool IsThunk,
1543                                        llvm::AttributeSet ExtraAttrs) {
1544   const Decl *D = GD.getDecl();
1545 
1546   // Lookup the entry, lazily creating it if necessary.
1547   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1548   if (Entry) {
1549     if (WeakRefReferences.erase(Entry)) {
1550       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D);
1551       if (FD && !FD->hasAttr<WeakAttr>())
1552         Entry->setLinkage(llvm::Function::ExternalLinkage);
1553     }
1554 
1555     // Handle dropped DLL attributes.
1556     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1557       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1558 
1559     if (Entry->getType()->getElementType() == Ty)
1560       return Entry;
1561 
1562     // Make sure the result is of the correct type.
1563     return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
1564   }
1565 
1566   // This function doesn't have a complete type (for example, the return
1567   // type is an incomplete struct). Use a fake type instead, and make
1568   // sure not to try to set attributes.
1569   bool IsIncompleteFunction = false;
1570 
1571   llvm::FunctionType *FTy;
1572   if (isa<llvm::FunctionType>(Ty)) {
1573     FTy = cast<llvm::FunctionType>(Ty);
1574   } else {
1575     FTy = llvm::FunctionType::get(VoidTy, false);
1576     IsIncompleteFunction = true;
1577   }
1578 
1579   llvm::Function *F = llvm::Function::Create(FTy,
1580                                              llvm::Function::ExternalLinkage,
1581                                              MangledName, &getModule());
1582   assert(F->getName() == MangledName && "name was uniqued!");
1583   if (D)
1584     SetFunctionAttributes(GD, F, IsIncompleteFunction, IsThunk);
1585   if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1586     llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
1587     F->addAttributes(llvm::AttributeSet::FunctionIndex,
1588                      llvm::AttributeSet::get(VMContext,
1589                                              llvm::AttributeSet::FunctionIndex,
1590                                              B));
1591   }
1592 
1593   if (!DontDefer) {
1594     // All MSVC dtors other than the base dtor are linkonce_odr and delegate to
1595     // each other bottoming out with the base dtor.  Therefore we emit non-base
1596     // dtors on usage, even if there is no dtor definition in the TU.
1597     if (D && isa<CXXDestructorDecl>(D) &&
1598         getCXXABI().useThunkForDtorVariant(cast<CXXDestructorDecl>(D),
1599                                            GD.getDtorType()))
1600       addDeferredDeclToEmit(F, GD);
1601 
1602     // This is the first use or definition of a mangled name.  If there is a
1603     // deferred decl with this name, remember that we need to emit it at the end
1604     // of the file.
1605     auto DDI = DeferredDecls.find(MangledName);
1606     if (DDI != DeferredDecls.end()) {
1607       // Move the potentially referenced deferred decl to the
1608       // DeferredDeclsToEmit list, and remove it from DeferredDecls (since we
1609       // don't need it anymore).
1610       addDeferredDeclToEmit(F, DDI->second);
1611       DeferredDecls.erase(DDI);
1612 
1613       // Otherwise, there are cases we have to worry about where we're
1614       // using a declaration for which we must emit a definition but where
1615       // we might not find a top-level definition:
1616       //   - member functions defined inline in their classes
1617       //   - friend functions defined inline in some class
1618       //   - special member functions with implicit definitions
1619       // If we ever change our AST traversal to walk into class methods,
1620       // this will be unnecessary.
1621       //
1622       // We also don't emit a definition for a function if it's going to be an
1623       // entry in a vtable, unless it's already marked as used.
1624     } else if (getLangOpts().CPlusPlus && D) {
1625       // Look for a declaration that's lexically in a record.
1626       for (const auto *FD = cast<FunctionDecl>(D)->getMostRecentDecl(); FD;
1627            FD = FD->getPreviousDecl()) {
1628         if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
1629           if (FD->doesThisDeclarationHaveABody()) {
1630             addDeferredDeclToEmit(F, GD.getWithDecl(FD));
1631             break;
1632           }
1633         }
1634       }
1635     }
1636   }
1637 
1638   // Make sure the result is of the requested type.
1639   if (!IsIncompleteFunction) {
1640     assert(F->getType()->getElementType() == Ty);
1641     return F;
1642   }
1643 
1644   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
1645   return llvm::ConstantExpr::getBitCast(F, PTy);
1646 }
1647 
1648 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
1649 /// non-null, then this function will use the specified type if it has to
1650 /// create it (this occurs when we see a definition of the function).
1651 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
1652                                                  llvm::Type *Ty,
1653                                                  bool ForVTable,
1654                                                  bool DontDefer) {
1655   // If there was no specific requested type, just convert it now.
1656   if (!Ty)
1657     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
1658 
1659   StringRef MangledName = getMangledName(GD);
1660   return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable, DontDefer);
1661 }
1662 
1663 /// CreateRuntimeFunction - Create a new runtime function with the specified
1664 /// type and name.
1665 llvm::Constant *
1666 CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
1667                                      StringRef Name,
1668                                      llvm::AttributeSet ExtraAttrs) {
1669   llvm::Constant *C =
1670       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1671                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1672   if (auto *F = dyn_cast<llvm::Function>(C))
1673     if (F->empty())
1674       F->setCallingConv(getRuntimeCC());
1675   return C;
1676 }
1677 
1678 /// CreateBuiltinFunction - Create a new builtin function with the specified
1679 /// type and name.
1680 llvm::Constant *
1681 CodeGenModule::CreateBuiltinFunction(llvm::FunctionType *FTy,
1682                                      StringRef Name,
1683                                      llvm::AttributeSet ExtraAttrs) {
1684   llvm::Constant *C =
1685       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1686                               /*DontDefer=*/false, /*IsThunk=*/false, ExtraAttrs);
1687   if (auto *F = dyn_cast<llvm::Function>(C))
1688     if (F->empty())
1689       F->setCallingConv(getBuiltinCC());
1690   return C;
1691 }
1692 
1693 /// isTypeConstant - Determine whether an object of this type can be emitted
1694 /// as a constant.
1695 ///
1696 /// If ExcludeCtor is true, the duration when the object's constructor runs
1697 /// will not be considered. The caller will need to verify that the object is
1698 /// not written to during its construction.
1699 bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1700   if (!Ty.isConstant(Context) && !Ty->isReferenceType())
1701     return false;
1702 
1703   if (Context.getLangOpts().CPlusPlus) {
1704     if (const CXXRecordDecl *Record
1705           = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1706       return ExcludeCtor && !Record->hasMutableFields() &&
1707              Record->hasTrivialDestructor();
1708   }
1709 
1710   return true;
1711 }
1712 
1713 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1714 /// create and return an llvm GlobalVariable with the specified type.  If there
1715 /// is something in the module with the specified name, return it potentially
1716 /// bitcasted to the right type.
1717 ///
1718 /// If D is non-null, it specifies a decl that correspond to this.  This is used
1719 /// to set the attributes on the global when it is first created.
1720 llvm::Constant *
1721 CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
1722                                      llvm::PointerType *Ty,
1723                                      const VarDecl *D) {
1724   // Lookup the entry, lazily creating it if necessary.
1725   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1726   if (Entry) {
1727     if (WeakRefReferences.erase(Entry)) {
1728       if (D && !D->hasAttr<WeakAttr>())
1729         Entry->setLinkage(llvm::Function::ExternalLinkage);
1730     }
1731 
1732     // Handle dropped DLL attributes.
1733     if (D && !D->hasAttr<DLLImportAttr>() && !D->hasAttr<DLLExportAttr>())
1734       Entry->setDLLStorageClass(llvm::GlobalValue::DefaultStorageClass);
1735 
1736     if (Entry->getType() == Ty)
1737       return Entry;
1738 
1739     // Make sure the result is of the correct type.
1740     if (Entry->getType()->getAddressSpace() != Ty->getAddressSpace())
1741       return llvm::ConstantExpr::getAddrSpaceCast(Entry, Ty);
1742 
1743     return llvm::ConstantExpr::getBitCast(Entry, Ty);
1744   }
1745 
1746   unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
1747   auto *GV = new llvm::GlobalVariable(
1748       getModule(), Ty->getElementType(), false,
1749       llvm::GlobalValue::ExternalLinkage, nullptr, MangledName, nullptr,
1750       llvm::GlobalVariable::NotThreadLocal, AddrSpace);
1751 
1752   // This is the first use or definition of a mangled name.  If there is a
1753   // deferred decl with this name, remember that we need to emit it at the end
1754   // of the file.
1755   auto DDI = DeferredDecls.find(MangledName);
1756   if (DDI != DeferredDecls.end()) {
1757     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1758     // list, and remove it from DeferredDecls (since we don't need it anymore).
1759     addDeferredDeclToEmit(GV, DDI->second);
1760     DeferredDecls.erase(DDI);
1761   }
1762 
1763   // Handle things which are present even on external declarations.
1764   if (D) {
1765     // FIXME: This code is overly simple and should be merged with other global
1766     // handling.
1767     GV->setConstant(isTypeConstant(D->getType(), false));
1768 
1769     GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1770 
1771     setLinkageAndVisibilityForGV(GV, D);
1772 
1773     if (D->getTLSKind()) {
1774       if (D->getTLSKind() == VarDecl::TLS_Dynamic)
1775         CXXThreadLocals.push_back(std::make_pair(D, GV));
1776       setTLSMode(GV, *D);
1777     }
1778 
1779     // If required by the ABI, treat declarations of static data members with
1780     // inline initializers as definitions.
1781     if (getContext().isMSStaticDataMemberInlineDefinition(D)) {
1782       EmitGlobalVarDefinition(D);
1783     }
1784 
1785     // Handle XCore specific ABI requirements.
1786     if (getTarget().getTriple().getArch() == llvm::Triple::xcore &&
1787         D->getLanguageLinkage() == CLanguageLinkage &&
1788         D->getType().isConstant(Context) &&
1789         isExternallyVisible(D->getLinkageAndVisibility().getLinkage()))
1790       GV->setSection(".cp.rodata");
1791   }
1792 
1793   if (AddrSpace != Ty->getAddressSpace())
1794     return llvm::ConstantExpr::getAddrSpaceCast(GV, Ty);
1795 
1796   return GV;
1797 }
1798 
1799 
1800 llvm::GlobalVariable *
1801 CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
1802                                       llvm::Type *Ty,
1803                                       llvm::GlobalValue::LinkageTypes Linkage) {
1804   llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1805   llvm::GlobalVariable *OldGV = nullptr;
1806 
1807   if (GV) {
1808     // Check if the variable has the right type.
1809     if (GV->getType()->getElementType() == Ty)
1810       return GV;
1811 
1812     // Because C++ name mangling, the only way we can end up with an already
1813     // existing global with the same name is if it has been declared extern "C".
1814     assert(GV->isDeclaration() && "Declaration has wrong type!");
1815     OldGV = GV;
1816   }
1817 
1818   // Create a new variable.
1819   GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1820                                 Linkage, nullptr, Name);
1821 
1822   if (OldGV) {
1823     // Replace occurrences of the old variable if needed.
1824     GV->takeName(OldGV);
1825 
1826     if (!OldGV->use_empty()) {
1827       llvm::Constant *NewPtrForOldDecl =
1828       llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1829       OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1830     }
1831 
1832     OldGV->eraseFromParent();
1833   }
1834 
1835   if (supportsCOMDAT() && GV->isWeakForLinker() &&
1836       !GV->hasAvailableExternallyLinkage())
1837     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
1838 
1839   return GV;
1840 }
1841 
1842 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1843 /// given global variable.  If Ty is non-null and if the global doesn't exist,
1844 /// then it will be created with the specified type instead of whatever the
1845 /// normal requested type would be.
1846 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
1847                                                   llvm::Type *Ty) {
1848   assert(D->hasGlobalStorage() && "Not a global variable");
1849   QualType ASTTy = D->getType();
1850   if (!Ty)
1851     Ty = getTypes().ConvertTypeForMem(ASTTy);
1852 
1853   llvm::PointerType *PTy =
1854     llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
1855 
1856   StringRef MangledName = getMangledName(D);
1857   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
1858 }
1859 
1860 /// CreateRuntimeVariable - Create a new runtime global variable with the
1861 /// specified type and name.
1862 llvm::Constant *
1863 CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
1864                                      StringRef Name) {
1865   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), nullptr);
1866 }
1867 
1868 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1869   assert(!D->getInit() && "Cannot emit definite definitions here!");
1870 
1871   if (!MustBeEmitted(D)) {
1872     // If we have not seen a reference to this variable yet, place it
1873     // into the deferred declarations table to be emitted if needed
1874     // later.
1875     StringRef MangledName = getMangledName(D);
1876     if (!GetGlobalValue(MangledName)) {
1877       DeferredDecls[MangledName] = D;
1878       return;
1879     }
1880   }
1881 
1882   // The tentative definition is the only definition.
1883   EmitGlobalVarDefinition(D);
1884 }
1885 
1886 CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
1887     return Context.toCharUnitsFromBits(
1888       TheDataLayout.getTypeStoreSizeInBits(Ty));
1889 }
1890 
1891 unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1892                                                  unsigned AddrSpace) {
1893   if (LangOpts.CUDA && LangOpts.CUDAIsDevice) {
1894     if (D->hasAttr<CUDAConstantAttr>())
1895       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1896     else if (D->hasAttr<CUDASharedAttr>())
1897       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1898     else
1899       AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1900   }
1901 
1902   return AddrSpace;
1903 }
1904 
1905 template<typename SomeDecl>
1906 void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
1907                                                llvm::GlobalValue *GV) {
1908   if (!getLangOpts().CPlusPlus)
1909     return;
1910 
1911   // Must have 'used' attribute, or else inline assembly can't rely on
1912   // the name existing.
1913   if (!D->template hasAttr<UsedAttr>())
1914     return;
1915 
1916   // Must have internal linkage and an ordinary name.
1917   if (!D->getIdentifier() || D->getFormalLinkage() != InternalLinkage)
1918     return;
1919 
1920   // Must be in an extern "C" context. Entities declared directly within
1921   // a record are not extern "C" even if the record is in such a context.
1922   const SomeDecl *First = D->getFirstDecl();
1923   if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
1924     return;
1925 
1926   // OK, this is an internal linkage entity inside an extern "C" linkage
1927   // specification. Make a note of that so we can give it the "expected"
1928   // mangled name if nothing else is using that name.
1929   std::pair<StaticExternCMap::iterator, bool> R =
1930       StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
1931 
1932   // If we have multiple internal linkage entities with the same name
1933   // in extern "C" regions, none of them gets that name.
1934   if (!R.second)
1935     R.first->second = nullptr;
1936 }
1937 
1938 static bool shouldBeInCOMDAT(CodeGenModule &CGM, const Decl &D) {
1939   if (!CGM.supportsCOMDAT())
1940     return false;
1941 
1942   if (D.hasAttr<SelectAnyAttr>())
1943     return true;
1944 
1945   GVALinkage Linkage;
1946   if (auto *VD = dyn_cast<VarDecl>(&D))
1947     Linkage = CGM.getContext().GetGVALinkageForVariable(VD);
1948   else
1949     Linkage = CGM.getContext().GetGVALinkageForFunction(cast<FunctionDecl>(&D));
1950 
1951   switch (Linkage) {
1952   case GVA_Internal:
1953   case GVA_AvailableExternally:
1954   case GVA_StrongExternal:
1955     return false;
1956   case GVA_DiscardableODR:
1957   case GVA_StrongODR:
1958     return true;
1959   }
1960   llvm_unreachable("No such linkage");
1961 }
1962 
1963 void CodeGenModule::maybeSetTrivialComdat(const Decl &D,
1964                                           llvm::GlobalObject &GO) {
1965   if (!shouldBeInCOMDAT(*this, D))
1966     return;
1967   GO.setComdat(TheModule.getOrInsertComdat(GO.getName()));
1968 }
1969 
1970 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1971   llvm::Constant *Init = nullptr;
1972   QualType ASTTy = D->getType();
1973   CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1974   bool NeedsGlobalCtor = false;
1975   bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
1976 
1977   const VarDecl *InitDecl;
1978   const Expr *InitExpr = D->getAnyInitializer(InitDecl);
1979 
1980   if (!InitExpr) {
1981     // This is a tentative definition; tentative definitions are
1982     // implicitly initialized with { 0 }.
1983     //
1984     // Note that tentative definitions are only emitted at the end of
1985     // a translation unit, so they should never have incomplete
1986     // type. In addition, EmitTentativeDefinition makes sure that we
1987     // never attempt to emit a tentative definition if a real one
1988     // exists. A use may still exists, however, so we still may need
1989     // to do a RAUW.
1990     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1991     Init = EmitNullConstant(D->getType());
1992   } else {
1993     initializedGlobalDecl = GlobalDecl(D);
1994     Init = EmitConstantInit(*InitDecl);
1995 
1996     if (!Init) {
1997       QualType T = InitExpr->getType();
1998       if (D->getType()->isReferenceType())
1999         T = D->getType();
2000 
2001       if (getLangOpts().CPlusPlus) {
2002         Init = EmitNullConstant(T);
2003         NeedsGlobalCtor = true;
2004       } else {
2005         ErrorUnsupported(D, "static initializer");
2006         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
2007       }
2008     } else {
2009       // We don't need an initializer, so remove the entry for the delayed
2010       // initializer position (just in case this entry was delayed) if we
2011       // also don't need to register a destructor.
2012       if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
2013         DelayedCXXInitPosition.erase(D);
2014     }
2015   }
2016 
2017   llvm::Type* InitType = Init->getType();
2018   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
2019 
2020   // Strip off a bitcast if we got one back.
2021   if (auto *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2022     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
2023            CE->getOpcode() == llvm::Instruction::AddrSpaceCast ||
2024            // All zero index gep.
2025            CE->getOpcode() == llvm::Instruction::GetElementPtr);
2026     Entry = CE->getOperand(0);
2027   }
2028 
2029   // Entry is now either a Function or GlobalVariable.
2030   auto *GV = dyn_cast<llvm::GlobalVariable>(Entry);
2031 
2032   // We have a definition after a declaration with the wrong type.
2033   // We must make a new GlobalVariable* and update everything that used OldGV
2034   // (a declaration or tentative definition) with the new GlobalVariable*
2035   // (which will be a definition).
2036   //
2037   // This happens if there is a prototype for a global (e.g.
2038   // "extern int x[];") and then a definition of a different type (e.g.
2039   // "int x[10];"). This also happens when an initializer has a different type
2040   // from the type of the global (this happens with unions).
2041   if (!GV ||
2042       GV->getType()->getElementType() != InitType ||
2043       GV->getType()->getAddressSpace() !=
2044        GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
2045 
2046     // Move the old entry aside so that we'll create a new one.
2047     Entry->setName(StringRef());
2048 
2049     // Make a new global with the correct type, this is now guaranteed to work.
2050     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
2051 
2052     // Replace all uses of the old global with the new global
2053     llvm::Constant *NewPtrForOldDecl =
2054         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
2055     Entry->replaceAllUsesWith(NewPtrForOldDecl);
2056 
2057     // Erase the old global, since it is no longer used.
2058     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
2059   }
2060 
2061   MaybeHandleStaticInExternC(D, GV);
2062 
2063   if (D->hasAttr<AnnotateAttr>())
2064     AddGlobalAnnotations(D, GV);
2065 
2066   GV->setInitializer(Init);
2067 
2068   // If it is safe to mark the global 'constant', do so now.
2069   GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
2070                   isTypeConstant(D->getType(), true));
2071 
2072   // If it is in a read-only section, mark it 'constant'.
2073   if (const SectionAttr *SA = D->getAttr<SectionAttr>()) {
2074     const ASTContext::SectionInfo &SI = Context.SectionInfos[SA->getName()];
2075     if ((SI.SectionFlags & ASTContext::PSF_Write) == 0)
2076       GV->setConstant(true);
2077   }
2078 
2079   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
2080 
2081   // Set the llvm linkage type as appropriate.
2082   llvm::GlobalValue::LinkageTypes Linkage =
2083       getLLVMLinkageVarDefinition(D, GV->isConstant());
2084 
2085   // On Darwin, the backing variable for a C++11 thread_local variable always
2086   // has internal linkage; all accesses should just be calls to the
2087   // Itanium-specified entry point, which has the normal linkage of the
2088   // variable.
2089   if (!D->isStaticLocal() && D->getTLSKind() == VarDecl::TLS_Dynamic &&
2090       Context.getTargetInfo().getTriple().isMacOSX())
2091     Linkage = llvm::GlobalValue::InternalLinkage;
2092 
2093   GV->setLinkage(Linkage);
2094   if (D->hasAttr<DLLImportAttr>())
2095     GV->setDLLStorageClass(llvm::GlobalVariable::DLLImportStorageClass);
2096   else if (D->hasAttr<DLLExportAttr>())
2097     GV->setDLLStorageClass(llvm::GlobalVariable::DLLExportStorageClass);
2098   else
2099     GV->setDLLStorageClass(llvm::GlobalVariable::DefaultStorageClass);
2100 
2101   if (Linkage == llvm::GlobalVariable::CommonLinkage)
2102     // common vars aren't constant even if declared const.
2103     GV->setConstant(false);
2104 
2105   setNonAliasAttributes(D, GV);
2106 
2107   if (D->getTLSKind() && !GV->isThreadLocal()) {
2108     if (D->getTLSKind() == VarDecl::TLS_Dynamic)
2109       CXXThreadLocals.push_back(std::make_pair(D, GV));
2110     setTLSMode(GV, *D);
2111   }
2112 
2113   maybeSetTrivialComdat(*D, *GV);
2114 
2115   // Emit the initializer function if necessary.
2116   if (NeedsGlobalCtor || NeedsGlobalDtor)
2117     EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
2118 
2119   SanitizerMD->reportGlobalToASan(GV, *D, NeedsGlobalCtor);
2120 
2121   // Emit global variable debug information.
2122   if (CGDebugInfo *DI = getModuleDebugInfo())
2123     if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2124       DI->EmitGlobalVariable(GV, D);
2125 }
2126 
2127 static bool isVarDeclStrongDefinition(const ASTContext &Context,
2128                                       CodeGenModule &CGM, const VarDecl *D,
2129                                       bool NoCommon) {
2130   // Don't give variables common linkage if -fno-common was specified unless it
2131   // was overridden by a NoCommon attribute.
2132   if ((NoCommon || D->hasAttr<NoCommonAttr>()) && !D->hasAttr<CommonAttr>())
2133     return true;
2134 
2135   // C11 6.9.2/2:
2136   //   A declaration of an identifier for an object that has file scope without
2137   //   an initializer, and without a storage-class specifier or with the
2138   //   storage-class specifier static, constitutes a tentative definition.
2139   if (D->getInit() || D->hasExternalStorage())
2140     return true;
2141 
2142   // A variable cannot be both common and exist in a section.
2143   if (D->hasAttr<SectionAttr>())
2144     return true;
2145 
2146   // Thread local vars aren't considered common linkage.
2147   if (D->getTLSKind())
2148     return true;
2149 
2150   // Tentative definitions marked with WeakImportAttr are true definitions.
2151   if (D->hasAttr<WeakImportAttr>())
2152     return true;
2153 
2154   // A variable cannot be both common and exist in a comdat.
2155   if (shouldBeInCOMDAT(CGM, *D))
2156     return true;
2157 
2158   // Declarations with a required alignment do not have common linakge in MSVC
2159   // mode.
2160   if (Context.getLangOpts().MSVCCompat) {
2161     if (D->hasAttr<AlignedAttr>())
2162       return true;
2163     QualType VarType = D->getType();
2164     if (Context.isAlignmentRequired(VarType))
2165       return true;
2166 
2167     if (const auto *RT = VarType->getAs<RecordType>()) {
2168       const RecordDecl *RD = RT->getDecl();
2169       for (const FieldDecl *FD : RD->fields()) {
2170         if (FD->isBitField())
2171           continue;
2172         if (FD->hasAttr<AlignedAttr>())
2173           return true;
2174         if (Context.isAlignmentRequired(FD->getType()))
2175           return true;
2176       }
2177     }
2178   }
2179 
2180   return false;
2181 }
2182 
2183 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageForDeclarator(
2184     const DeclaratorDecl *D, GVALinkage Linkage, bool IsConstantVariable) {
2185   if (Linkage == GVA_Internal)
2186     return llvm::Function::InternalLinkage;
2187 
2188   if (D->hasAttr<WeakAttr>()) {
2189     if (IsConstantVariable)
2190       return llvm::GlobalVariable::WeakODRLinkage;
2191     else
2192       return llvm::GlobalVariable::WeakAnyLinkage;
2193   }
2194 
2195   // We are guaranteed to have a strong definition somewhere else,
2196   // so we can use available_externally linkage.
2197   if (Linkage == GVA_AvailableExternally)
2198     return llvm::Function::AvailableExternallyLinkage;
2199 
2200   // Note that Apple's kernel linker doesn't support symbol
2201   // coalescing, so we need to avoid linkonce and weak linkages there.
2202   // Normally, this means we just map to internal, but for explicit
2203   // instantiations we'll map to external.
2204 
2205   // In C++, the compiler has to emit a definition in every translation unit
2206   // that references the function.  We should use linkonce_odr because
2207   // a) if all references in this translation unit are optimized away, we
2208   // don't need to codegen it.  b) if the function persists, it needs to be
2209   // merged with other definitions. c) C++ has the ODR, so we know the
2210   // definition is dependable.
2211   if (Linkage == GVA_DiscardableODR)
2212     return !Context.getLangOpts().AppleKext ? llvm::Function::LinkOnceODRLinkage
2213                                             : llvm::Function::InternalLinkage;
2214 
2215   // An explicit instantiation of a template has weak linkage, since
2216   // explicit instantiations can occur in multiple translation units
2217   // and must all be equivalent. However, we are not allowed to
2218   // throw away these explicit instantiations.
2219   if (Linkage == GVA_StrongODR)
2220     return !Context.getLangOpts().AppleKext ? llvm::Function::WeakODRLinkage
2221                                             : llvm::Function::ExternalLinkage;
2222 
2223   // C++ doesn't have tentative definitions and thus cannot have common
2224   // linkage.
2225   if (!getLangOpts().CPlusPlus && isa<VarDecl>(D) &&
2226       !isVarDeclStrongDefinition(Context, *this, cast<VarDecl>(D),
2227                                  CodeGenOpts.NoCommon))
2228     return llvm::GlobalVariable::CommonLinkage;
2229 
2230   // selectany symbols are externally visible, so use weak instead of
2231   // linkonce.  MSVC optimizes away references to const selectany globals, so
2232   // all definitions should be the same and ODR linkage should be used.
2233   // http://msdn.microsoft.com/en-us/library/5tkz6s71.aspx
2234   if (D->hasAttr<SelectAnyAttr>())
2235     return llvm::GlobalVariable::WeakODRLinkage;
2236 
2237   // Otherwise, we have strong external linkage.
2238   assert(Linkage == GVA_StrongExternal);
2239   return llvm::GlobalVariable::ExternalLinkage;
2240 }
2241 
2242 llvm::GlobalValue::LinkageTypes CodeGenModule::getLLVMLinkageVarDefinition(
2243     const VarDecl *VD, bool IsConstant) {
2244   GVALinkage Linkage = getContext().GetGVALinkageForVariable(VD);
2245   return getLLVMLinkageForDeclarator(VD, Linkage, IsConstant);
2246 }
2247 
2248 /// Replace the uses of a function that was declared with a non-proto type.
2249 /// We want to silently drop extra arguments from call sites
2250 static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
2251                                           llvm::Function *newFn) {
2252   // Fast path.
2253   if (old->use_empty()) return;
2254 
2255   llvm::Type *newRetTy = newFn->getReturnType();
2256   SmallVector<llvm::Value*, 4> newArgs;
2257 
2258   for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
2259          ui != ue; ) {
2260     llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
2261     llvm::User *user = use->getUser();
2262 
2263     // Recognize and replace uses of bitcasts.  Most calls to
2264     // unprototyped functions will use bitcasts.
2265     if (auto *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
2266       if (bitcast->getOpcode() == llvm::Instruction::BitCast)
2267         replaceUsesOfNonProtoConstant(bitcast, newFn);
2268       continue;
2269     }
2270 
2271     // Recognize calls to the function.
2272     llvm::CallSite callSite(user);
2273     if (!callSite) continue;
2274     if (!callSite.isCallee(&*use)) continue;
2275 
2276     // If the return types don't match exactly, then we can't
2277     // transform this call unless it's dead.
2278     if (callSite->getType() != newRetTy && !callSite->use_empty())
2279       continue;
2280 
2281     // Get the call site's attribute list.
2282     SmallVector<llvm::AttributeSet, 8> newAttrs;
2283     llvm::AttributeSet oldAttrs = callSite.getAttributes();
2284 
2285     // Collect any return attributes from the call.
2286     if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
2287       newAttrs.push_back(
2288         llvm::AttributeSet::get(newFn->getContext(),
2289                                 oldAttrs.getRetAttributes()));
2290 
2291     // If the function was passed too few arguments, don't transform.
2292     unsigned newNumArgs = newFn->arg_size();
2293     if (callSite.arg_size() < newNumArgs) continue;
2294 
2295     // If extra arguments were passed, we silently drop them.
2296     // If any of the types mismatch, we don't transform.
2297     unsigned argNo = 0;
2298     bool dontTransform = false;
2299     for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
2300            ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
2301       if (callSite.getArgument(argNo)->getType() != ai->getType()) {
2302         dontTransform = true;
2303         break;
2304       }
2305 
2306       // Add any parameter attributes.
2307       if (oldAttrs.hasAttributes(argNo + 1))
2308         newAttrs.
2309           push_back(llvm::
2310                     AttributeSet::get(newFn->getContext(),
2311                                       oldAttrs.getParamAttributes(argNo + 1)));
2312     }
2313     if (dontTransform)
2314       continue;
2315 
2316     if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
2317       newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
2318                                                  oldAttrs.getFnAttributes()));
2319 
2320     // Okay, we can transform this.  Create the new call instruction and copy
2321     // over the required information.
2322     newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
2323 
2324     llvm::CallSite newCall;
2325     if (callSite.isCall()) {
2326       newCall = llvm::CallInst::Create(newFn, newArgs, "",
2327                                        callSite.getInstruction());
2328     } else {
2329       auto *oldInvoke = cast<llvm::InvokeInst>(callSite.getInstruction());
2330       newCall = llvm::InvokeInst::Create(newFn,
2331                                          oldInvoke->getNormalDest(),
2332                                          oldInvoke->getUnwindDest(),
2333                                          newArgs, "",
2334                                          callSite.getInstruction());
2335     }
2336     newArgs.clear(); // for the next iteration
2337 
2338     if (!newCall->getType()->isVoidTy())
2339       newCall->takeName(callSite.getInstruction());
2340     newCall.setAttributes(
2341                      llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2342     newCall.setCallingConv(callSite.getCallingConv());
2343 
2344     // Finally, remove the old call, replacing any uses with the new one.
2345     if (!callSite->use_empty())
2346       callSite->replaceAllUsesWith(newCall.getInstruction());
2347 
2348     // Copy debug location attached to CI.
2349     if (callSite->getDebugLoc())
2350       newCall->setDebugLoc(callSite->getDebugLoc());
2351     callSite->eraseFromParent();
2352   }
2353 }
2354 
2355 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2356 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
2357 /// existing call uses of the old function in the module, this adjusts them to
2358 /// call the new function directly.
2359 ///
2360 /// This is not just a cleanup: the always_inline pass requires direct calls to
2361 /// functions to be able to inline them.  If there is a bitcast in the way, it
2362 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
2363 /// run at -O0.
2364 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2365                                                       llvm::Function *NewFn) {
2366   // If we're redefining a global as a function, don't transform it.
2367   if (!isa<llvm::Function>(Old)) return;
2368 
2369   replaceUsesOfNonProtoConstant(Old, NewFn);
2370 }
2371 
2372 void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2373   TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2374   // If we have a definition, this might be a deferred decl. If the
2375   // instantiation is explicit, make sure we emit it at the end.
2376   if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2377     GetAddrOfGlobalVar(VD);
2378 
2379   EmitTopLevelDecl(VD);
2380 }
2381 
2382 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD,
2383                                                  llvm::GlobalValue *GV) {
2384   const auto *D = cast<FunctionDecl>(GD.getDecl());
2385 
2386   // Compute the function info and LLVM type.
2387   const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2388   llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
2389 
2390   // Get or create the prototype for the function.
2391   if (!GV) {
2392     llvm::Constant *C =
2393         GetAddrOfFunction(GD, Ty, /*ForVTable=*/false, /*DontDefer*/ true);
2394 
2395     // Strip off a bitcast if we got one back.
2396     if (auto *CE = dyn_cast<llvm::ConstantExpr>(C)) {
2397       assert(CE->getOpcode() == llvm::Instruction::BitCast);
2398       GV = cast<llvm::GlobalValue>(CE->getOperand(0));
2399     } else {
2400       GV = cast<llvm::GlobalValue>(C);
2401     }
2402   }
2403 
2404   if (!GV->isDeclaration()) {
2405     getDiags().Report(D->getLocation(), diag::err_duplicate_mangled_name);
2406     GlobalDecl OldGD = Manglings.lookup(GV->getName());
2407     if (auto *Prev = OldGD.getDecl())
2408       getDiags().Report(Prev->getLocation(), diag::note_previous_definition);
2409     return;
2410   }
2411 
2412   if (GV->getType()->getElementType() != Ty) {
2413     // If the types mismatch then we have to rewrite the definition.
2414     assert(GV->isDeclaration() && "Shouldn't replace non-declaration");
2415 
2416     // F is the Function* for the one with the wrong type, we must make a new
2417     // Function* and update everything that used F (a declaration) with the new
2418     // Function* (which will be a definition).
2419     //
2420     // This happens if there is a prototype for a function
2421     // (e.g. "int f()") and then a definition of a different type
2422     // (e.g. "int f(int x)").  Move the old function aside so that it
2423     // doesn't interfere with GetAddrOfFunction.
2424     GV->setName(StringRef());
2425     auto *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
2426 
2427     // This might be an implementation of a function without a
2428     // prototype, in which case, try to do special replacement of
2429     // calls which match the new prototype.  The really key thing here
2430     // is that we also potentially drop arguments from the call site
2431     // so as to make a direct call, which makes the inliner happier
2432     // and suppresses a number of optimizer warnings (!) about
2433     // dropping arguments.
2434     if (!GV->use_empty()) {
2435       ReplaceUsesOfNonProtoTypeWithRealFunction(GV, NewFn);
2436       GV->removeDeadConstantUsers();
2437     }
2438 
2439     // Replace uses of F with the Function we will endow with a body.
2440     if (!GV->use_empty()) {
2441       llvm::Constant *NewPtrForOldDecl =
2442           llvm::ConstantExpr::getBitCast(NewFn, GV->getType());
2443       GV->replaceAllUsesWith(NewPtrForOldDecl);
2444     }
2445 
2446     // Ok, delete the old function now, which is dead.
2447     GV->eraseFromParent();
2448 
2449     GV = NewFn;
2450   }
2451 
2452   // We need to set linkage and visibility on the function before
2453   // generating code for it because various parts of IR generation
2454   // want to propagate this information down (e.g. to local static
2455   // declarations).
2456   auto *Fn = cast<llvm::Function>(GV);
2457   setFunctionLinkage(GD, Fn);
2458   setFunctionDLLStorageClass(GD, Fn);
2459 
2460   // FIXME: this is redundant with part of setFunctionDefinitionAttributes
2461   setGlobalVisibility(Fn, D);
2462 
2463   MaybeHandleStaticInExternC(D, Fn);
2464 
2465   maybeSetTrivialComdat(*D, *Fn);
2466 
2467   CodeGenFunction(*this).GenerateCode(D, Fn, FI);
2468 
2469   setFunctionDefinitionAttributes(D, Fn);
2470   SetLLVMFunctionAttributesForDefinition(D, Fn);
2471 
2472   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
2473     AddGlobalCtor(Fn, CA->getPriority());
2474   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
2475     AddGlobalDtor(Fn, DA->getPriority());
2476   if (D->hasAttr<AnnotateAttr>())
2477     AddGlobalAnnotations(D, Fn);
2478 }
2479 
2480 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2481   const auto *D = cast<ValueDecl>(GD.getDecl());
2482   const AliasAttr *AA = D->getAttr<AliasAttr>();
2483   assert(AA && "Not an alias?");
2484 
2485   StringRef MangledName = getMangledName(GD);
2486 
2487   // If there is a definition in the module, then it wins over the alias.
2488   // This is dubious, but allow it to be safe.  Just ignore the alias.
2489   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2490   if (Entry && !Entry->isDeclaration())
2491     return;
2492 
2493   Aliases.push_back(GD);
2494 
2495   llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
2496 
2497   // Create a reference to the named value.  This ensures that it is emitted
2498   // if a deferred decl.
2499   llvm::Constant *Aliasee;
2500   if (isa<llvm::FunctionType>(DeclTy))
2501     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
2502                                       /*ForVTable=*/false);
2503   else
2504     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
2505                                     llvm::PointerType::getUnqual(DeclTy),
2506                                     /*D=*/nullptr);
2507 
2508   // Create the new alias itself, but don't set a name yet.
2509   auto *GA = llvm::GlobalAlias::create(
2510       cast<llvm::PointerType>(Aliasee->getType()),
2511       llvm::Function::ExternalLinkage, "", Aliasee, &getModule());
2512 
2513   if (Entry) {
2514     if (GA->getAliasee() == Entry) {
2515       Diags.Report(AA->getLocation(), diag::err_cyclic_alias);
2516       return;
2517     }
2518 
2519     assert(Entry->isDeclaration());
2520 
2521     // If there is a declaration in the module, then we had an extern followed
2522     // by the alias, as in:
2523     //   extern int test6();
2524     //   ...
2525     //   int test6() __attribute__((alias("test7")));
2526     //
2527     // Remove it and replace uses of it with the alias.
2528     GA->takeName(Entry);
2529 
2530     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
2531                                                           Entry->getType()));
2532     Entry->eraseFromParent();
2533   } else {
2534     GA->setName(MangledName);
2535   }
2536 
2537   // Set attributes which are particular to an alias; this is a
2538   // specialization of the attributes which may be set on a global
2539   // variable/function.
2540   if (D->hasAttr<WeakAttr>() || D->hasAttr<WeakRefAttr>() ||
2541       D->isWeakImported()) {
2542     GA->setLinkage(llvm::Function::WeakAnyLinkage);
2543   }
2544 
2545   if (const auto *VD = dyn_cast<VarDecl>(D))
2546     if (VD->getTLSKind())
2547       setTLSMode(GA, *VD);
2548 
2549   setAliasAttributes(D, GA);
2550 }
2551 
2552 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
2553                                             ArrayRef<llvm::Type*> Tys) {
2554   return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
2555                                          Tys);
2556 }
2557 
2558 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2559 GetConstantCFStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2560                          const StringLiteral *Literal, bool TargetIsLSB,
2561                          bool &IsUTF16, unsigned &StringLength) {
2562   StringRef String = Literal->getString();
2563   unsigned NumBytes = String.size();
2564 
2565   // Check for simple case.
2566   if (!Literal->containsNonAsciiOrNull()) {
2567     StringLength = NumBytes;
2568     return *Map.insert(std::make_pair(String, nullptr)).first;
2569   }
2570 
2571   // Otherwise, convert the UTF8 literals into a string of shorts.
2572   IsUTF16 = true;
2573 
2574   SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
2575   const UTF8 *FromPtr = (const UTF8 *)String.data();
2576   UTF16 *ToPtr = &ToBuf[0];
2577 
2578   (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2579                            &ToPtr, ToPtr + NumBytes,
2580                            strictConversion);
2581 
2582   // ConvertUTF8toUTF16 returns the length in ToPtr.
2583   StringLength = ToPtr - &ToBuf[0];
2584 
2585   // Add an explicit null.
2586   *ToPtr = 0;
2587   return *Map.insert(std::make_pair(
2588                          StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2589                                    (StringLength + 1) * 2),
2590                          nullptr)).first;
2591 }
2592 
2593 static llvm::StringMapEntry<llvm::GlobalVariable *> &
2594 GetConstantStringEntry(llvm::StringMap<llvm::GlobalVariable *> &Map,
2595                        const StringLiteral *Literal, unsigned &StringLength) {
2596   StringRef String = Literal->getString();
2597   StringLength = String.size();
2598   return *Map.insert(std::make_pair(String, nullptr)).first;
2599 }
2600 
2601 llvm::Constant *
2602 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2603   unsigned StringLength = 0;
2604   bool isUTF16 = false;
2605   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2606       GetConstantCFStringEntry(CFConstantStringMap, Literal,
2607                                getDataLayout().isLittleEndian(), isUTF16,
2608                                StringLength);
2609 
2610   if (auto *C = Entry.second)
2611     return C;
2612 
2613   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2614   llvm::Constant *Zeros[] = { Zero, Zero };
2615   llvm::Value *V;
2616 
2617   // If we don't already have it, get __CFConstantStringClassReference.
2618   if (!CFConstantStringClassRef) {
2619     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2620     Ty = llvm::ArrayType::get(Ty, 0);
2621     llvm::Constant *GV = CreateRuntimeVariable(Ty,
2622                                            "__CFConstantStringClassReference");
2623     // Decay array -> ptr
2624     V = llvm::ConstantExpr::getGetElementPtr(Ty, GV, Zeros);
2625     CFConstantStringClassRef = V;
2626   }
2627   else
2628     V = CFConstantStringClassRef;
2629 
2630   QualType CFTy = getContext().getCFConstantStringType();
2631 
2632   auto *STy = cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2633 
2634   llvm::Constant *Fields[4];
2635 
2636   // Class pointer.
2637   Fields[0] = cast<llvm::ConstantExpr>(V);
2638 
2639   // Flags.
2640   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2641   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
2642     llvm::ConstantInt::get(Ty, 0x07C8);
2643 
2644   // String pointer.
2645   llvm::Constant *C = nullptr;
2646   if (isUTF16) {
2647     ArrayRef<uint16_t> Arr = llvm::makeArrayRef<uint16_t>(
2648         reinterpret_cast<uint16_t *>(const_cast<char *>(Entry.first().data())),
2649         Entry.first().size() / 2);
2650     C = llvm::ConstantDataArray::get(VMContext, Arr);
2651   } else {
2652     C = llvm::ConstantDataArray::getString(VMContext, Entry.first());
2653   }
2654 
2655   // Note: -fwritable-strings doesn't make the backing store strings of
2656   // CFStrings writable. (See <rdar://problem/10657500>)
2657   auto *GV =
2658       new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2659                                llvm::GlobalValue::PrivateLinkage, C, ".str");
2660   GV->setUnnamedAddr(true);
2661   // Don't enforce the target's minimum global alignment, since the only use
2662   // of the string is via this class initializer.
2663   // FIXME: We set the section explicitly to avoid a bug in ld64 224.1. Without
2664   // it LLVM can merge the string with a non unnamed_addr one during LTO. Doing
2665   // that changes the section it ends in, which surprises ld64.
2666   if (isUTF16) {
2667     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2668     GV->setAlignment(Align.getQuantity());
2669     GV->setSection("__TEXT,__ustring");
2670   } else {
2671     CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2672     GV->setAlignment(Align.getQuantity());
2673     GV->setSection("__TEXT,__cstring,cstring_literals");
2674   }
2675 
2676   // String.
2677   Fields[2] =
2678       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2679 
2680   if (isUTF16)
2681     // Cast the UTF16 string to the correct type.
2682     Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2683 
2684   // String length.
2685   Ty = getTypes().ConvertType(getContext().LongTy);
2686   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
2687 
2688   // The struct.
2689   C = llvm::ConstantStruct::get(STy, Fields);
2690   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2691                                 llvm::GlobalVariable::PrivateLinkage, C,
2692                                 "_unnamed_cfstring_");
2693   GV->setSection("__DATA,__cfstring");
2694   Entry.second = GV;
2695 
2696   return GV;
2697 }
2698 
2699 llvm::GlobalVariable *
2700 CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
2701   unsigned StringLength = 0;
2702   llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
2703       GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
2704 
2705   if (auto *C = Entry.second)
2706     return C;
2707 
2708   llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
2709   llvm::Constant *Zeros[] = { Zero, Zero };
2710   llvm::Value *V;
2711   // If we don't already have it, get _NSConstantStringClassReference.
2712   if (!ConstantStringClassRef) {
2713     std::string StringClass(getLangOpts().ObjCConstantStringClass);
2714     llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
2715     llvm::Constant *GV;
2716     if (LangOpts.ObjCRuntime.isNonFragile()) {
2717       std::string str =
2718         StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2719                             : "OBJC_CLASS_$_" + StringClass;
2720       GV = getObjCRuntime().GetClassGlobal(str);
2721       // Make sure the result is of the correct type.
2722       llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
2723       V = llvm::ConstantExpr::getBitCast(GV, PTy);
2724       ConstantStringClassRef = V;
2725     } else {
2726       std::string str =
2727         StringClass.empty() ? "_NSConstantStringClassReference"
2728                             : "_" + StringClass + "ClassReference";
2729       llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
2730       GV = CreateRuntimeVariable(PTy, str);
2731       // Decay array -> ptr
2732       V = llvm::ConstantExpr::getGetElementPtr(PTy, GV, Zeros);
2733       ConstantStringClassRef = V;
2734     }
2735   } else
2736     V = ConstantStringClassRef;
2737 
2738   if (!NSConstantStringType) {
2739     // Construct the type for a constant NSString.
2740     RecordDecl *D = Context.buildImplicitRecord("__builtin_NSString");
2741     D->startDefinition();
2742 
2743     QualType FieldTypes[3];
2744 
2745     // const int *isa;
2746     FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2747     // const char *str;
2748     FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2749     // unsigned int length;
2750     FieldTypes[2] = Context.UnsignedIntTy;
2751 
2752     // Create fields
2753     for (unsigned i = 0; i < 3; ++i) {
2754       FieldDecl *Field = FieldDecl::Create(Context, D,
2755                                            SourceLocation(),
2756                                            SourceLocation(), nullptr,
2757                                            FieldTypes[i], /*TInfo=*/nullptr,
2758                                            /*BitWidth=*/nullptr,
2759                                            /*Mutable=*/false,
2760                                            ICIS_NoInit);
2761       Field->setAccess(AS_public);
2762       D->addDecl(Field);
2763     }
2764 
2765     D->completeDefinition();
2766     QualType NSTy = Context.getTagDeclType(D);
2767     NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2768   }
2769 
2770   llvm::Constant *Fields[3];
2771 
2772   // Class pointer.
2773   Fields[0] = cast<llvm::ConstantExpr>(V);
2774 
2775   // String pointer.
2776   llvm::Constant *C =
2777       llvm::ConstantDataArray::getString(VMContext, Entry.first());
2778 
2779   llvm::GlobalValue::LinkageTypes Linkage;
2780   bool isConstant;
2781   Linkage = llvm::GlobalValue::PrivateLinkage;
2782   isConstant = !LangOpts.WritableStrings;
2783 
2784   auto *GV = new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
2785                                       Linkage, C, ".str");
2786   GV->setUnnamedAddr(true);
2787   // Don't enforce the target's minimum global alignment, since the only use
2788   // of the string is via this class initializer.
2789   CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2790   GV->setAlignment(Align.getQuantity());
2791   Fields[1] =
2792       llvm::ConstantExpr::getGetElementPtr(GV->getValueType(), GV, Zeros);
2793 
2794   // String length.
2795   llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
2796   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2797 
2798   // The struct.
2799   C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
2800   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2801                                 llvm::GlobalVariable::PrivateLinkage, C,
2802                                 "_unnamed_nsstring_");
2803   const char *NSStringSection = "__OBJC,__cstring_object,regular,no_dead_strip";
2804   const char *NSStringNonFragileABISection =
2805       "__DATA,__objc_stringobj,regular,no_dead_strip";
2806   // FIXME. Fix section.
2807   GV->setSection(LangOpts.ObjCRuntime.isNonFragile()
2808                      ? NSStringNonFragileABISection
2809                      : NSStringSection);
2810   Entry.second = GV;
2811 
2812   return GV;
2813 }
2814 
2815 QualType CodeGenModule::getObjCFastEnumerationStateType() {
2816   if (ObjCFastEnumerationStateType.isNull()) {
2817     RecordDecl *D = Context.buildImplicitRecord("__objcFastEnumerationState");
2818     D->startDefinition();
2819 
2820     QualType FieldTypes[] = {
2821       Context.UnsignedLongTy,
2822       Context.getPointerType(Context.getObjCIdType()),
2823       Context.getPointerType(Context.UnsignedLongTy),
2824       Context.getConstantArrayType(Context.UnsignedLongTy,
2825                            llvm::APInt(32, 5), ArrayType::Normal, 0)
2826     };
2827 
2828     for (size_t i = 0; i < 4; ++i) {
2829       FieldDecl *Field = FieldDecl::Create(Context,
2830                                            D,
2831                                            SourceLocation(),
2832                                            SourceLocation(), nullptr,
2833                                            FieldTypes[i], /*TInfo=*/nullptr,
2834                                            /*BitWidth=*/nullptr,
2835                                            /*Mutable=*/false,
2836                                            ICIS_NoInit);
2837       Field->setAccess(AS_public);
2838       D->addDecl(Field);
2839     }
2840 
2841     D->completeDefinition();
2842     ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2843   }
2844 
2845   return ObjCFastEnumerationStateType;
2846 }
2847 
2848 llvm::Constant *
2849 CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2850   assert(!E->getType()->isPointerType() && "Strings are always arrays");
2851 
2852   // Don't emit it as the address of the string, emit the string data itself
2853   // as an inline array.
2854   if (E->getCharByteWidth() == 1) {
2855     SmallString<64> Str(E->getString());
2856 
2857     // Resize the string to the right size, which is indicated by its type.
2858     const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2859     Str.resize(CAT->getSize().getZExtValue());
2860     return llvm::ConstantDataArray::getString(VMContext, Str, false);
2861   }
2862 
2863   auto *AType = cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2864   llvm::Type *ElemTy = AType->getElementType();
2865   unsigned NumElements = AType->getNumElements();
2866 
2867   // Wide strings have either 2-byte or 4-byte elements.
2868   if (ElemTy->getPrimitiveSizeInBits() == 16) {
2869     SmallVector<uint16_t, 32> Elements;
2870     Elements.reserve(NumElements);
2871 
2872     for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2873       Elements.push_back(E->getCodeUnit(i));
2874     Elements.resize(NumElements);
2875     return llvm::ConstantDataArray::get(VMContext, Elements);
2876   }
2877 
2878   assert(ElemTy->getPrimitiveSizeInBits() == 32);
2879   SmallVector<uint32_t, 32> Elements;
2880   Elements.reserve(NumElements);
2881 
2882   for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2883     Elements.push_back(E->getCodeUnit(i));
2884   Elements.resize(NumElements);
2885   return llvm::ConstantDataArray::get(VMContext, Elements);
2886 }
2887 
2888 static llvm::GlobalVariable *
2889 GenerateStringLiteral(llvm::Constant *C, llvm::GlobalValue::LinkageTypes LT,
2890                       CodeGenModule &CGM, StringRef GlobalName,
2891                       unsigned Alignment) {
2892   // OpenCL v1.2 s6.5.3: a string literal is in the constant address space.
2893   unsigned AddrSpace = 0;
2894   if (CGM.getLangOpts().OpenCL)
2895     AddrSpace = CGM.getContext().getTargetAddressSpace(LangAS::opencl_constant);
2896 
2897   llvm::Module &M = CGM.getModule();
2898   // Create a global variable for this string
2899   auto *GV = new llvm::GlobalVariable(
2900       M, C->getType(), !CGM.getLangOpts().WritableStrings, LT, C, GlobalName,
2901       nullptr, llvm::GlobalVariable::NotThreadLocal, AddrSpace);
2902   GV->setAlignment(Alignment);
2903   GV->setUnnamedAddr(true);
2904   if (GV->isWeakForLinker()) {
2905     assert(CGM.supportsCOMDAT() && "Only COFF uses weak string literals");
2906     GV->setComdat(M.getOrInsertComdat(GV->getName()));
2907   }
2908 
2909   return GV;
2910 }
2911 
2912 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2913 /// constant array for the given string literal.
2914 llvm::GlobalVariable *
2915 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S,
2916                                                   StringRef Name) {
2917   auto Alignment =
2918       getContext().getAlignOfGlobalVarInChars(S->getType()).getQuantity();
2919 
2920   llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2921   llvm::GlobalVariable **Entry = nullptr;
2922   if (!LangOpts.WritableStrings) {
2923     Entry = &ConstantStringMap[C];
2924     if (auto GV = *Entry) {
2925       if (Alignment > GV->getAlignment())
2926         GV->setAlignment(Alignment);
2927       return GV;
2928     }
2929   }
2930 
2931   SmallString<256> MangledNameBuffer;
2932   StringRef GlobalVariableName;
2933   llvm::GlobalValue::LinkageTypes LT;
2934 
2935   // Mangle the string literal if the ABI allows for it.  However, we cannot
2936   // do this if  we are compiling with ASan or -fwritable-strings because they
2937   // rely on strings having normal linkage.
2938   if (!LangOpts.WritableStrings &&
2939       !LangOpts.Sanitize.has(SanitizerKind::Address) &&
2940       getCXXABI().getMangleContext().shouldMangleStringLiteral(S)) {
2941     llvm::raw_svector_ostream Out(MangledNameBuffer);
2942     getCXXABI().getMangleContext().mangleStringLiteral(S, Out);
2943     Out.flush();
2944 
2945     LT = llvm::GlobalValue::LinkOnceODRLinkage;
2946     GlobalVariableName = MangledNameBuffer;
2947   } else {
2948     LT = llvm::GlobalValue::PrivateLinkage;
2949     GlobalVariableName = Name;
2950   }
2951 
2952   auto GV = GenerateStringLiteral(C, LT, *this, GlobalVariableName, Alignment);
2953   if (Entry)
2954     *Entry = GV;
2955 
2956   SanitizerMD->reportGlobalToASan(GV, S->getStrTokenLoc(0), "<string literal>",
2957                                   QualType());
2958   return GV;
2959 }
2960 
2961 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2962 /// array for the given ObjCEncodeExpr node.
2963 llvm::GlobalVariable *
2964 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2965   std::string Str;
2966   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
2967 
2968   return GetAddrOfConstantCString(Str);
2969 }
2970 
2971 /// GetAddrOfConstantCString - Returns a pointer to a character array containing
2972 /// the literal and a terminating '\0' character.
2973 /// The result has pointer to array type.
2974 llvm::GlobalVariable *CodeGenModule::GetAddrOfConstantCString(
2975     const std::string &Str, const char *GlobalName, unsigned Alignment) {
2976   StringRef StrWithNull(Str.c_str(), Str.size() + 1);
2977   if (Alignment == 0) {
2978     Alignment = getContext()
2979                     .getAlignOfGlobalVarInChars(getContext().CharTy)
2980                     .getQuantity();
2981   }
2982 
2983   llvm::Constant *C =
2984       llvm::ConstantDataArray::getString(getLLVMContext(), StrWithNull, false);
2985 
2986   // Don't share any string literals if strings aren't constant.
2987   llvm::GlobalVariable **Entry = nullptr;
2988   if (!LangOpts.WritableStrings) {
2989     Entry = &ConstantStringMap[C];
2990     if (auto GV = *Entry) {
2991       if (Alignment > GV->getAlignment())
2992         GV->setAlignment(Alignment);
2993       return GV;
2994     }
2995   }
2996 
2997   // Get the default prefix if a name wasn't specified.
2998   if (!GlobalName)
2999     GlobalName = ".str";
3000   // Create a global variable for this.
3001   auto GV = GenerateStringLiteral(C, llvm::GlobalValue::PrivateLinkage, *this,
3002                                   GlobalName, Alignment);
3003   if (Entry)
3004     *Entry = GV;
3005   return GV;
3006 }
3007 
3008 llvm::Constant *CodeGenModule::GetAddrOfGlobalTemporary(
3009     const MaterializeTemporaryExpr *E, const Expr *Init) {
3010   assert((E->getStorageDuration() == SD_Static ||
3011           E->getStorageDuration() == SD_Thread) && "not a global temporary");
3012   const auto *VD = cast<VarDecl>(E->getExtendingDecl());
3013 
3014   // If we're not materializing a subobject of the temporary, keep the
3015   // cv-qualifiers from the type of the MaterializeTemporaryExpr.
3016   QualType MaterializedType = Init->getType();
3017   if (Init == E->GetTemporaryExpr())
3018     MaterializedType = E->getType();
3019 
3020   llvm::Constant *&Slot = MaterializedGlobalTemporaryMap[E];
3021   if (Slot)
3022     return Slot;
3023 
3024   // FIXME: If an externally-visible declaration extends multiple temporaries,
3025   // we need to give each temporary the same name in every translation unit (and
3026   // we also need to make the temporaries externally-visible).
3027   SmallString<256> Name;
3028   llvm::raw_svector_ostream Out(Name);
3029   getCXXABI().getMangleContext().mangleReferenceTemporary(
3030       VD, E->getManglingNumber(), Out);
3031   Out.flush();
3032 
3033   APValue *Value = nullptr;
3034   if (E->getStorageDuration() == SD_Static) {
3035     // We might have a cached constant initializer for this temporary. Note
3036     // that this might have a different value from the value computed by
3037     // evaluating the initializer if the surrounding constant expression
3038     // modifies the temporary.
3039     Value = getContext().getMaterializedTemporaryValue(E, false);
3040     if (Value && Value->isUninit())
3041       Value = nullptr;
3042   }
3043 
3044   // Try evaluating it now, it might have a constant initializer.
3045   Expr::EvalResult EvalResult;
3046   if (!Value && Init->EvaluateAsRValue(EvalResult, getContext()) &&
3047       !EvalResult.hasSideEffects())
3048     Value = &EvalResult.Val;
3049 
3050   llvm::Constant *InitialValue = nullptr;
3051   bool Constant = false;
3052   llvm::Type *Type;
3053   if (Value) {
3054     // The temporary has a constant initializer, use it.
3055     InitialValue = EmitConstantValue(*Value, MaterializedType, nullptr);
3056     Constant = isTypeConstant(MaterializedType, /*ExcludeCtor*/Value);
3057     Type = InitialValue->getType();
3058   } else {
3059     // No initializer, the initialization will be provided when we
3060     // initialize the declaration which performed lifetime extension.
3061     Type = getTypes().ConvertTypeForMem(MaterializedType);
3062   }
3063 
3064   // Create a global variable for this lifetime-extended temporary.
3065   llvm::GlobalValue::LinkageTypes Linkage =
3066       getLLVMLinkageVarDefinition(VD, Constant);
3067   if (Linkage == llvm::GlobalVariable::ExternalLinkage) {
3068     const VarDecl *InitVD;
3069     if (VD->isStaticDataMember() && VD->getAnyInitializer(InitVD) &&
3070         isa<CXXRecordDecl>(InitVD->getLexicalDeclContext())) {
3071       // Temporaries defined inside a class get linkonce_odr linkage because the
3072       // class can be defined in multipe translation units.
3073       Linkage = llvm::GlobalVariable::LinkOnceODRLinkage;
3074     } else {
3075       // There is no need for this temporary to have external linkage if the
3076       // VarDecl has external linkage.
3077       Linkage = llvm::GlobalVariable::InternalLinkage;
3078     }
3079   }
3080   unsigned AddrSpace = GetGlobalVarAddressSpace(
3081       VD, getContext().getTargetAddressSpace(MaterializedType));
3082   auto *GV = new llvm::GlobalVariable(
3083       getModule(), Type, Constant, Linkage, InitialValue, Name.c_str(),
3084       /*InsertBefore=*/nullptr, llvm::GlobalVariable::NotThreadLocal,
3085       AddrSpace);
3086   setGlobalVisibility(GV, VD);
3087   GV->setAlignment(
3088       getContext().getTypeAlignInChars(MaterializedType).getQuantity());
3089   if (supportsCOMDAT() && GV->isWeakForLinker())
3090     GV->setComdat(TheModule.getOrInsertComdat(GV->getName()));
3091   if (VD->getTLSKind())
3092     setTLSMode(GV, *VD);
3093   Slot = GV;
3094   return GV;
3095 }
3096 
3097 /// EmitObjCPropertyImplementations - Emit information for synthesized
3098 /// properties for an implementation.
3099 void CodeGenModule::EmitObjCPropertyImplementations(const
3100                                                     ObjCImplementationDecl *D) {
3101   for (const auto *PID : D->property_impls()) {
3102     // Dynamic is just for type-checking.
3103     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
3104       ObjCPropertyDecl *PD = PID->getPropertyDecl();
3105 
3106       // Determine which methods need to be implemented, some may have
3107       // been overridden. Note that ::isPropertyAccessor is not the method
3108       // we want, that just indicates if the decl came from a
3109       // property. What we want to know is if the method is defined in
3110       // this implementation.
3111       if (!D->getInstanceMethod(PD->getGetterName()))
3112         CodeGenFunction(*this).GenerateObjCGetter(
3113                                  const_cast<ObjCImplementationDecl *>(D), PID);
3114       if (!PD->isReadOnly() &&
3115           !D->getInstanceMethod(PD->getSetterName()))
3116         CodeGenFunction(*this).GenerateObjCSetter(
3117                                  const_cast<ObjCImplementationDecl *>(D), PID);
3118     }
3119   }
3120 }
3121 
3122 static bool needsDestructMethod(ObjCImplementationDecl *impl) {
3123   const ObjCInterfaceDecl *iface = impl->getClassInterface();
3124   for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
3125        ivar; ivar = ivar->getNextIvar())
3126     if (ivar->getType().isDestructedType())
3127       return true;
3128 
3129   return false;
3130 }
3131 
3132 static bool AllTrivialInitializers(CodeGenModule &CGM,
3133                                    ObjCImplementationDecl *D) {
3134   CodeGenFunction CGF(CGM);
3135   for (ObjCImplementationDecl::init_iterator B = D->init_begin(),
3136        E = D->init_end(); B != E; ++B) {
3137     CXXCtorInitializer *CtorInitExp = *B;
3138     Expr *Init = CtorInitExp->getInit();
3139     if (!CGF.isTrivialInitializer(Init))
3140       return false;
3141   }
3142   return true;
3143 }
3144 
3145 /// EmitObjCIvarInitializations - Emit information for ivar initialization
3146 /// for an implementation.
3147 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
3148   // We might need a .cxx_destruct even if we don't have any ivar initializers.
3149   if (needsDestructMethod(D)) {
3150     IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
3151     Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3152     ObjCMethodDecl *DTORMethod =
3153       ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
3154                              cxxSelector, getContext().VoidTy, nullptr, D,
3155                              /*isInstance=*/true, /*isVariadic=*/false,
3156                           /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
3157                              /*isDefined=*/false, ObjCMethodDecl::Required);
3158     D->addInstanceMethod(DTORMethod);
3159     CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
3160     D->setHasDestructors(true);
3161   }
3162 
3163   // If the implementation doesn't have any ivar initializers, we don't need
3164   // a .cxx_construct.
3165   if (D->getNumIvarInitializers() == 0 ||
3166       AllTrivialInitializers(*this, D))
3167     return;
3168 
3169   IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
3170   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
3171   // The constructor returns 'self'.
3172   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
3173                                                 D->getLocation(),
3174                                                 D->getLocation(),
3175                                                 cxxSelector,
3176                                                 getContext().getObjCIdType(),
3177                                                 nullptr, D, /*isInstance=*/true,
3178                                                 /*isVariadic=*/false,
3179                                                 /*isPropertyAccessor=*/true,
3180                                                 /*isImplicitlyDeclared=*/true,
3181                                                 /*isDefined=*/false,
3182                                                 ObjCMethodDecl::Required);
3183   D->addInstanceMethod(CTORMethod);
3184   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
3185   D->setHasNonZeroConstructors(true);
3186 }
3187 
3188 /// EmitNamespace - Emit all declarations in a namespace.
3189 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
3190   for (auto *I : ND->decls()) {
3191     if (const auto *VD = dyn_cast<VarDecl>(I))
3192       if (VD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
3193           VD->getTemplateSpecializationKind() != TSK_Undeclared)
3194         continue;
3195     EmitTopLevelDecl(I);
3196   }
3197 }
3198 
3199 // EmitLinkageSpec - Emit all declarations in a linkage spec.
3200 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
3201   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
3202       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
3203     ErrorUnsupported(LSD, "linkage spec");
3204     return;
3205   }
3206 
3207   for (auto *I : LSD->decls()) {
3208     // Meta-data for ObjC class includes references to implemented methods.
3209     // Generate class's method definitions first.
3210     if (auto *OID = dyn_cast<ObjCImplDecl>(I)) {
3211       for (auto *M : OID->methods())
3212         EmitTopLevelDecl(M);
3213     }
3214     EmitTopLevelDecl(I);
3215   }
3216 }
3217 
3218 /// EmitTopLevelDecl - Emit code for a single top level declaration.
3219 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
3220   // Ignore dependent declarations.
3221   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
3222     return;
3223 
3224   switch (D->getKind()) {
3225   case Decl::CXXConversion:
3226   case Decl::CXXMethod:
3227   case Decl::Function:
3228     // Skip function templates
3229     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3230         cast<FunctionDecl>(D)->isLateTemplateParsed())
3231       return;
3232 
3233     EmitGlobal(cast<FunctionDecl>(D));
3234     // Always provide some coverage mapping
3235     // even for the functions that aren't emitted.
3236     AddDeferredUnusedCoverageMapping(D);
3237     break;
3238 
3239   case Decl::Var:
3240     // Skip variable templates
3241     if (cast<VarDecl>(D)->getDescribedVarTemplate())
3242       return;
3243   case Decl::VarTemplateSpecialization:
3244     EmitGlobal(cast<VarDecl>(D));
3245     break;
3246 
3247   // Indirect fields from global anonymous structs and unions can be
3248   // ignored; only the actual variable requires IR gen support.
3249   case Decl::IndirectField:
3250     break;
3251 
3252   // C++ Decls
3253   case Decl::Namespace:
3254     EmitNamespace(cast<NamespaceDecl>(D));
3255     break;
3256     // No code generation needed.
3257   case Decl::UsingShadow:
3258   case Decl::ClassTemplate:
3259   case Decl::VarTemplate:
3260   case Decl::VarTemplatePartialSpecialization:
3261   case Decl::FunctionTemplate:
3262   case Decl::TypeAliasTemplate:
3263   case Decl::Block:
3264   case Decl::Empty:
3265     break;
3266   case Decl::Using:          // using X; [C++]
3267     if (CGDebugInfo *DI = getModuleDebugInfo())
3268         DI->EmitUsingDecl(cast<UsingDecl>(*D));
3269     return;
3270   case Decl::NamespaceAlias:
3271     if (CGDebugInfo *DI = getModuleDebugInfo())
3272         DI->EmitNamespaceAlias(cast<NamespaceAliasDecl>(*D));
3273     return;
3274   case Decl::UsingDirective: // using namespace X; [C++]
3275     if (CGDebugInfo *DI = getModuleDebugInfo())
3276       DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
3277     return;
3278   case Decl::CXXConstructor:
3279     // Skip function templates
3280     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
3281         cast<FunctionDecl>(D)->isLateTemplateParsed())
3282       return;
3283 
3284     getCXXABI().EmitCXXConstructors(cast<CXXConstructorDecl>(D));
3285     break;
3286   case Decl::CXXDestructor:
3287     if (cast<FunctionDecl>(D)->isLateTemplateParsed())
3288       return;
3289     getCXXABI().EmitCXXDestructors(cast<CXXDestructorDecl>(D));
3290     break;
3291 
3292   case Decl::StaticAssert:
3293     // Nothing to do.
3294     break;
3295 
3296   // Objective-C Decls
3297 
3298   // Forward declarations, no (immediate) code generation.
3299   case Decl::ObjCInterface:
3300   case Decl::ObjCCategory:
3301     break;
3302 
3303   case Decl::ObjCProtocol: {
3304     auto *Proto = cast<ObjCProtocolDecl>(D);
3305     if (Proto->isThisDeclarationADefinition())
3306       ObjCRuntime->GenerateProtocol(Proto);
3307     break;
3308   }
3309 
3310   case Decl::ObjCCategoryImpl:
3311     // Categories have properties but don't support synthesize so we
3312     // can ignore them here.
3313     ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
3314     break;
3315 
3316   case Decl::ObjCImplementation: {
3317     auto *OMD = cast<ObjCImplementationDecl>(D);
3318     EmitObjCPropertyImplementations(OMD);
3319     EmitObjCIvarInitializations(OMD);
3320     ObjCRuntime->GenerateClass(OMD);
3321     // Emit global variable debug information.
3322     if (CGDebugInfo *DI = getModuleDebugInfo())
3323       if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
3324         DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
3325             OMD->getClassInterface()), OMD->getLocation());
3326     break;
3327   }
3328   case Decl::ObjCMethod: {
3329     auto *OMD = cast<ObjCMethodDecl>(D);
3330     // If this is not a prototype, emit the body.
3331     if (OMD->getBody())
3332       CodeGenFunction(*this).GenerateObjCMethod(OMD);
3333     break;
3334   }
3335   case Decl::ObjCCompatibleAlias:
3336     ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
3337     break;
3338 
3339   case Decl::LinkageSpec:
3340     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
3341     break;
3342 
3343   case Decl::FileScopeAsm: {
3344     // File-scope asm is ignored during device-side CUDA compilation.
3345     if (LangOpts.CUDA && LangOpts.CUDAIsDevice)
3346       break;
3347     auto *AD = cast<FileScopeAsmDecl>(D);
3348     getModule().appendModuleInlineAsm(AD->getAsmString()->getString());
3349     break;
3350   }
3351 
3352   case Decl::Import: {
3353     auto *Import = cast<ImportDecl>(D);
3354 
3355     // Ignore import declarations that come from imported modules.
3356     if (clang::Module *Owner = Import->getImportedOwningModule()) {
3357       if (getLangOpts().CurrentModule.empty() ||
3358           Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
3359         break;
3360     }
3361 
3362     ImportedModules.insert(Import->getImportedModule());
3363     break;
3364   }
3365 
3366   case Decl::OMPThreadPrivate:
3367     EmitOMPThreadPrivateDecl(cast<OMPThreadPrivateDecl>(D));
3368     break;
3369 
3370   case Decl::ClassTemplateSpecialization: {
3371     const auto *Spec = cast<ClassTemplateSpecializationDecl>(D);
3372     if (DebugInfo &&
3373         Spec->getSpecializationKind() == TSK_ExplicitInstantiationDefinition &&
3374         Spec->hasDefinition())
3375       DebugInfo->completeTemplateDefinition(*Spec);
3376     break;
3377   }
3378 
3379   default:
3380     // Make sure we handled everything we should, every other kind is a
3381     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
3382     // function. Need to recode Decl::Kind to do that easily.
3383     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
3384     break;
3385   }
3386 }
3387 
3388 void CodeGenModule::AddDeferredUnusedCoverageMapping(Decl *D) {
3389   // Do we need to generate coverage mapping?
3390   if (!CodeGenOpts.CoverageMapping)
3391     return;
3392   switch (D->getKind()) {
3393   case Decl::CXXConversion:
3394   case Decl::CXXMethod:
3395   case Decl::Function:
3396   case Decl::ObjCMethod:
3397   case Decl::CXXConstructor:
3398   case Decl::CXXDestructor: {
3399     if (!cast<FunctionDecl>(D)->hasBody())
3400       return;
3401     auto I = DeferredEmptyCoverageMappingDecls.find(D);
3402     if (I == DeferredEmptyCoverageMappingDecls.end())
3403       DeferredEmptyCoverageMappingDecls[D] = true;
3404     break;
3405   }
3406   default:
3407     break;
3408   };
3409 }
3410 
3411 void CodeGenModule::ClearUnusedCoverageMapping(const Decl *D) {
3412   // Do we need to generate coverage mapping?
3413   if (!CodeGenOpts.CoverageMapping)
3414     return;
3415   if (const auto *Fn = dyn_cast<FunctionDecl>(D)) {
3416     if (Fn->isTemplateInstantiation())
3417       ClearUnusedCoverageMapping(Fn->getTemplateInstantiationPattern());
3418   }
3419   auto I = DeferredEmptyCoverageMappingDecls.find(D);
3420   if (I == DeferredEmptyCoverageMappingDecls.end())
3421     DeferredEmptyCoverageMappingDecls[D] = false;
3422   else
3423     I->second = false;
3424 }
3425 
3426 void CodeGenModule::EmitDeferredUnusedCoverageMappings() {
3427   std::vector<const Decl *> DeferredDecls;
3428   for (const auto &I : DeferredEmptyCoverageMappingDecls) {
3429     if (!I.second)
3430       continue;
3431     DeferredDecls.push_back(I.first);
3432   }
3433   // Sort the declarations by their location to make sure that the tests get a
3434   // predictable order for the coverage mapping for the unused declarations.
3435   if (CodeGenOpts.DumpCoverageMapping)
3436     std::sort(DeferredDecls.begin(), DeferredDecls.end(),
3437               [] (const Decl *LHS, const Decl *RHS) {
3438       return LHS->getLocStart() < RHS->getLocStart();
3439     });
3440   for (const auto *D : DeferredDecls) {
3441     switch (D->getKind()) {
3442     case Decl::CXXConversion:
3443     case Decl::CXXMethod:
3444     case Decl::Function:
3445     case Decl::ObjCMethod: {
3446       CodeGenPGO PGO(*this);
3447       GlobalDecl GD(cast<FunctionDecl>(D));
3448       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3449                                   getFunctionLinkage(GD));
3450       break;
3451     }
3452     case Decl::CXXConstructor: {
3453       CodeGenPGO PGO(*this);
3454       GlobalDecl GD(cast<CXXConstructorDecl>(D), Ctor_Base);
3455       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3456                                   getFunctionLinkage(GD));
3457       break;
3458     }
3459     case Decl::CXXDestructor: {
3460       CodeGenPGO PGO(*this);
3461       GlobalDecl GD(cast<CXXDestructorDecl>(D), Dtor_Base);
3462       PGO.emitEmptyCounterMapping(D, getMangledName(GD),
3463                                   getFunctionLinkage(GD));
3464       break;
3465     }
3466     default:
3467       break;
3468     };
3469   }
3470 }
3471 
3472 /// Turns the given pointer into a constant.
3473 static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
3474                                           const void *Ptr) {
3475   uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
3476   llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
3477   return llvm::ConstantInt::get(i64, PtrInt);
3478 }
3479 
3480 static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
3481                                    llvm::NamedMDNode *&GlobalMetadata,
3482                                    GlobalDecl D,
3483                                    llvm::GlobalValue *Addr) {
3484   if (!GlobalMetadata)
3485     GlobalMetadata =
3486       CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
3487 
3488   // TODO: should we report variant information for ctors/dtors?
3489   llvm::Metadata *Ops[] = {llvm::ConstantAsMetadata::get(Addr),
3490                            llvm::ConstantAsMetadata::get(GetPointerConstant(
3491                                CGM.getLLVMContext(), D.getDecl()))};
3492   GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
3493 }
3494 
3495 /// For each function which is declared within an extern "C" region and marked
3496 /// as 'used', but has internal linkage, create an alias from the unmangled
3497 /// name to the mangled name if possible. People expect to be able to refer
3498 /// to such functions with an unmangled name from inline assembly within the
3499 /// same translation unit.
3500 void CodeGenModule::EmitStaticExternCAliases() {
3501   for (auto &I : StaticExternCValues) {
3502     IdentifierInfo *Name = I.first;
3503     llvm::GlobalValue *Val = I.second;
3504     if (Val && !getModule().getNamedValue(Name->getName()))
3505       addUsedGlobal(llvm::GlobalAlias::create(Name->getName(), Val));
3506   }
3507 }
3508 
3509 bool CodeGenModule::lookupRepresentativeDecl(StringRef MangledName,
3510                                              GlobalDecl &Result) const {
3511   auto Res = Manglings.find(MangledName);
3512   if (Res == Manglings.end())
3513     return false;
3514   Result = Res->getValue();
3515   return true;
3516 }
3517 
3518 /// Emits metadata nodes associating all the global values in the
3519 /// current module with the Decls they came from.  This is useful for
3520 /// projects using IR gen as a subroutine.
3521 ///
3522 /// Since there's currently no way to associate an MDNode directly
3523 /// with an llvm::GlobalValue, we create a global named metadata
3524 /// with the name 'clang.global.decl.ptrs'.
3525 void CodeGenModule::EmitDeclMetadata() {
3526   llvm::NamedMDNode *GlobalMetadata = nullptr;
3527 
3528   // StaticLocalDeclMap
3529   for (auto &I : MangledDeclNames) {
3530     llvm::GlobalValue *Addr = getModule().getNamedValue(I.second);
3531     EmitGlobalDeclMetadata(*this, GlobalMetadata, I.first, Addr);
3532   }
3533 }
3534 
3535 /// Emits metadata nodes for all the local variables in the current
3536 /// function.
3537 void CodeGenFunction::EmitDeclMetadata() {
3538   if (LocalDeclMap.empty()) return;
3539 
3540   llvm::LLVMContext &Context = getLLVMContext();
3541 
3542   // Find the unique metadata ID for this name.
3543   unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
3544 
3545   llvm::NamedMDNode *GlobalMetadata = nullptr;
3546 
3547   for (auto &I : LocalDeclMap) {
3548     const Decl *D = I.first;
3549     llvm::Value *Addr = I.second;
3550     if (auto *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
3551       llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
3552       Alloca->setMetadata(
3553           DeclPtrKind, llvm::MDNode::get(
3554                            Context, llvm::ValueAsMetadata::getConstant(DAddr)));
3555     } else if (auto *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
3556       GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
3557       EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
3558     }
3559   }
3560 }
3561 
3562 void CodeGenModule::EmitVersionIdentMetadata() {
3563   llvm::NamedMDNode *IdentMetadata =
3564     TheModule.getOrInsertNamedMetadata("llvm.ident");
3565   std::string Version = getClangFullVersion();
3566   llvm::LLVMContext &Ctx = TheModule.getContext();
3567 
3568   llvm::Metadata *IdentNode[] = {llvm::MDString::get(Ctx, Version)};
3569   IdentMetadata->addOperand(llvm::MDNode::get(Ctx, IdentNode));
3570 }
3571 
3572 void CodeGenModule::EmitTargetMetadata() {
3573   // Warning, new MangledDeclNames may be appended within this loop.
3574   // We rely on MapVector insertions adding new elements to the end
3575   // of the container.
3576   // FIXME: Move this loop into the one target that needs it, and only
3577   // loop over those declarations for which we couldn't emit the target
3578   // metadata when we emitted the declaration.
3579   for (unsigned I = 0; I != MangledDeclNames.size(); ++I) {
3580     auto Val = *(MangledDeclNames.begin() + I);
3581     const Decl *D = Val.first.getDecl()->getMostRecentDecl();
3582     llvm::GlobalValue *GV = GetGlobalValue(Val.second);
3583     getTargetCodeGenInfo().emitTargetMD(D, GV, *this);
3584   }
3585 }
3586 
3587 void CodeGenModule::EmitCoverageFile() {
3588   if (!getCodeGenOpts().CoverageFile.empty()) {
3589     if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
3590       llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
3591       llvm::LLVMContext &Ctx = TheModule.getContext();
3592       llvm::MDString *CoverageFile =
3593           llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
3594       for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
3595         llvm::MDNode *CU = CUNode->getOperand(i);
3596         llvm::Metadata *Elts[] = {CoverageFile, CU};
3597         GCov->addOperand(llvm::MDNode::get(Ctx, Elts));
3598       }
3599     }
3600   }
3601 }
3602 
3603 llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid) {
3604   // Sema has checked that all uuid strings are of the form
3605   // "12345678-1234-1234-1234-1234567890ab".
3606   assert(Uuid.size() == 36);
3607   for (unsigned i = 0; i < 36; ++i) {
3608     if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuid[i] == '-');
3609     else                                         assert(isHexDigit(Uuid[i]));
3610   }
3611 
3612   // The starts of all bytes of Field3 in Uuid. Field 3 is "1234-1234567890ab".
3613   const unsigned Field3ValueOffsets[8] = { 19, 21, 24, 26, 28, 30, 32, 34 };
3614 
3615   llvm::Constant *Field3[8];
3616   for (unsigned Idx = 0; Idx < 8; ++Idx)
3617     Field3[Idx] = llvm::ConstantInt::get(
3618         Int8Ty, Uuid.substr(Field3ValueOffsets[Idx], 2), 16);
3619 
3620   llvm::Constant *Fields[4] = {
3621     llvm::ConstantInt::get(Int32Ty, Uuid.substr(0,  8), 16),
3622     llvm::ConstantInt::get(Int16Ty, Uuid.substr(9,  4), 16),
3623     llvm::ConstantInt::get(Int16Ty, Uuid.substr(14, 4), 16),
3624     llvm::ConstantArray::get(llvm::ArrayType::get(Int8Ty, 8), Field3)
3625   };
3626 
3627   return llvm::ConstantStruct::getAnon(Fields);
3628 }
3629 
3630 llvm::Constant *
3631 CodeGenModule::getAddrOfCXXCatchHandlerType(QualType Ty,
3632                                             QualType CatchHandlerType) {
3633   return getCXXABI().getAddrOfCXXCatchHandlerType(Ty, CatchHandlerType);
3634 }
3635 
3636 llvm::Constant *CodeGenModule::GetAddrOfRTTIDescriptor(QualType Ty,
3637                                                        bool ForEH) {
3638   // Return a bogus pointer if RTTI is disabled, unless it's for EH.
3639   // FIXME: should we even be calling this method if RTTI is disabled
3640   // and it's not for EH?
3641   if (!ForEH && !getLangOpts().RTTI)
3642     return llvm::Constant::getNullValue(Int8PtrTy);
3643 
3644   if (ForEH && Ty->isObjCObjectPointerType() &&
3645       LangOpts.ObjCRuntime.isGNUFamily())
3646     return ObjCRuntime->GetEHType(Ty);
3647 
3648   return getCXXABI().getAddrOfRTTIDescriptor(Ty);
3649 }
3650 
3651 void CodeGenModule::EmitOMPThreadPrivateDecl(const OMPThreadPrivateDecl *D) {
3652   for (auto RefExpr : D->varlists()) {
3653     auto *VD = cast<VarDecl>(cast<DeclRefExpr>(RefExpr)->getDecl());
3654     bool PerformInit =
3655         VD->getAnyInitializer() &&
3656         !VD->getAnyInitializer()->isConstantInitializer(getContext(),
3657                                                         /*ForRef=*/false);
3658     if (auto InitFunction = getOpenMPRuntime().emitThreadPrivateVarDefinition(
3659             VD, GetAddrOfGlobalVar(VD), RefExpr->getLocStart(), PerformInit))
3660       CXXGlobalInits.push_back(InitFunction);
3661   }
3662 }
3663 
3664 llvm::MDTuple *CodeGenModule::CreateVTableBitSetEntry(
3665     llvm::GlobalVariable *VTable, CharUnits Offset, const CXXRecordDecl *RD) {
3666   std::string OutName;
3667   llvm::raw_string_ostream Out(OutName);
3668   getCXXABI().getMangleContext().mangleCXXVTableBitSet(RD, Out);
3669 
3670   llvm::Metadata *BitsetOps[] = {
3671       llvm::MDString::get(getLLVMContext(), Out.str()),
3672       llvm::ConstantAsMetadata::get(VTable),
3673       llvm::ConstantAsMetadata::get(
3674           llvm::ConstantInt::get(Int64Ty, Offset.getQuantity()))};
3675   return llvm::MDTuple::get(getLLVMContext(), BitsetOps);
3676 }
3677