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