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