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