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