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