xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision c2af939ab4f5f1439ab155e0177a4ce3a0796b6a)
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 "CGDebugInfo.h"
16 #include "CodeGenFunction.h"
17 #include "CGCall.h"
18 #include "CGObjCRuntime.h"
19 #include "Mangle.h"
20 #include "TargetInfo.h"
21 #include "clang/CodeGen/CodeGenOptions.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/CharUnits.h"
24 #include "clang/AST/DeclObjC.h"
25 #include "clang/AST/DeclCXX.h"
26 #include "clang/AST/RecordLayout.h"
27 #include "clang/Basic/Builtins.h"
28 #include "clang/Basic/Diagnostic.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Basic/TargetInfo.h"
31 #include "clang/Basic/ConvertUTF.h"
32 #include "llvm/CallingConv.h"
33 #include "llvm/Module.h"
34 #include "llvm/Intrinsics.h"
35 #include "llvm/LLVMContext.h"
36 #include "llvm/ADT/Triple.h"
37 #include "llvm/Target/TargetData.h"
38 #include "llvm/Support/CallSite.h"
39 #include "llvm/Support/ErrorHandling.h"
40 using namespace clang;
41 using namespace CodeGen;
42 
43 
44 CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
45                              llvm::Module &M, const llvm::TargetData &TD,
46                              Diagnostic &diags)
47   : BlockModule(C, M, TD, Types, *this), Context(C),
48     Features(C.getLangOptions()), CodeGenOpts(CGO), TheModule(M),
49     TheTargetData(TD), TheTargetCodeGenInfo(0), Diags(diags),
50     Types(C, M, TD, getTargetCodeGenInfo().getABIInfo()),
51     VTables(*this), Runtime(0), ABI(0),
52     CFConstantStringClassRef(0),
53     NSConstantStringClassRef(0),
54     VMContext(M.getContext()) {
55 
56   if (!Features.ObjC1)
57     Runtime = 0;
58   else if (!Features.NeXTRuntime)
59     Runtime = CreateGNUObjCRuntime(*this);
60   else if (Features.ObjCNonFragileABI)
61     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
62   else
63     Runtime = CreateMacObjCRuntime(*this);
64 
65   if (!Features.CPlusPlus)
66     ABI = 0;
67   else createCXXABI();
68 
69   // If debug info generation is enabled, create the CGDebugInfo object.
70   DebugInfo = CodeGenOpts.DebugInfo ? new CGDebugInfo(*this) : 0;
71 }
72 
73 CodeGenModule::~CodeGenModule() {
74   delete Runtime;
75   delete ABI;
76   delete DebugInfo;
77 }
78 
79 void CodeGenModule::createObjCRuntime() {
80   if (!Features.NeXTRuntime)
81     Runtime = CreateGNUObjCRuntime(*this);
82   else if (Features.ObjCNonFragileABI)
83     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
84   else
85     Runtime = CreateMacObjCRuntime(*this);
86 }
87 
88 void CodeGenModule::createCXXABI() {
89   // For now, just create an Itanium ABI.
90   ABI = CreateItaniumCXXABI(*this);
91 }
92 
93 void CodeGenModule::Release() {
94   EmitDeferred();
95   EmitCXXGlobalInitFunc();
96   EmitCXXGlobalDtorFunc();
97   if (Runtime)
98     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
99       AddGlobalCtor(ObjCInitFunction);
100   EmitCtorList(GlobalCtors, "llvm.global_ctors");
101   EmitCtorList(GlobalDtors, "llvm.global_dtors");
102   EmitAnnotations();
103   EmitLLVMUsed();
104 }
105 
106 bool CodeGenModule::isTargetDarwin() const {
107   return getContext().Target.getTriple().getOS() == llvm::Triple::Darwin;
108 }
109 
110 /// ErrorUnsupported - Print out an error that codegen doesn't support the
111 /// specified stmt yet.
112 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
113                                      bool OmitOnError) {
114   if (OmitOnError && getDiags().hasErrorOccurred())
115     return;
116   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
117                                                "cannot compile this %0 yet");
118   std::string Msg = Type;
119   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
120     << Msg << S->getSourceRange();
121 }
122 
123 /// ErrorUnsupported - Print out an error that codegen doesn't support the
124 /// specified decl yet.
125 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
126                                      bool OmitOnError) {
127   if (OmitOnError && getDiags().hasErrorOccurred())
128     return;
129   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
130                                                "cannot compile this %0 yet");
131   std::string Msg = Type;
132   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
133 }
134 
135 LangOptions::VisibilityMode
136 CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
137   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
138     if (VD->getStorageClass() == VarDecl::PrivateExtern)
139       return LangOptions::Hidden;
140 
141   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
142     switch (attr->getVisibility()) {
143     default: assert(0 && "Unknown visibility!");
144     case VisibilityAttr::DefaultVisibility:
145       return LangOptions::Default;
146     case VisibilityAttr::HiddenVisibility:
147       return LangOptions::Hidden;
148     case VisibilityAttr::ProtectedVisibility:
149       return LangOptions::Protected;
150     }
151   }
152 
153   // This decl should have the same visibility as its parent.
154   if (const DeclContext *DC = D->getDeclContext())
155     return getDeclVisibilityMode(cast<Decl>(DC));
156 
157   return getLangOptions().getVisibilityMode();
158 }
159 
160 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
161                                         const Decl *D) const {
162   // Internal definitions always have default visibility.
163   if (GV->hasLocalLinkage()) {
164     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
165     return;
166   }
167 
168   switch (getDeclVisibilityMode(D)) {
169   default: assert(0 && "Unknown visibility!");
170   case LangOptions::Default:
171     return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
172   case LangOptions::Hidden:
173     return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
174   case LangOptions::Protected:
175     return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
176   }
177 }
178 
179 void CodeGenModule::getMangledName(MangleBuffer &Buffer, GlobalDecl GD) {
180   const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
181 
182   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
183     return getMangledCXXCtorName(Buffer, D, GD.getCtorType());
184   if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
185     return getMangledCXXDtorName(Buffer, D, GD.getDtorType());
186 
187   return getMangledName(Buffer, ND);
188 }
189 
190 /// \brief Retrieves the mangled name for the given declaration.
191 ///
192 /// If the given declaration requires a mangled name, returns an
193 /// const char* containing the mangled name.  Otherwise, returns
194 /// the unmangled name.
195 ///
196 void CodeGenModule::getMangledName(MangleBuffer &Buffer,
197                                    const NamedDecl *ND) {
198   if (!getMangleContext().shouldMangleDeclName(ND)) {
199     assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
200     Buffer.setString(ND->getNameAsCString());
201     return;
202   }
203 
204   getMangleContext().mangleName(ND, Buffer.getBuffer());
205 }
206 
207 llvm::GlobalValue *CodeGenModule::GetGlobalValue(llvm::StringRef Name) {
208   return getModule().getNamedValue(Name);
209 }
210 
211 /// AddGlobalCtor - Add a function to the list that will be called before
212 /// main() runs.
213 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
214   // FIXME: Type coercion of void()* types.
215   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
216 }
217 
218 /// AddGlobalDtor - Add a function to the list that will be called
219 /// when the module is unloaded.
220 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
221   // FIXME: Type coercion of void()* types.
222   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
223 }
224 
225 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
226   // Ctor function type is void()*.
227   llvm::FunctionType* CtorFTy =
228     llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
229                             std::vector<const llvm::Type*>(),
230                             false);
231   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
232 
233   // Get the type of a ctor entry, { i32, void ()* }.
234   llvm::StructType* CtorStructTy =
235     llvm::StructType::get(VMContext, llvm::Type::getInt32Ty(VMContext),
236                           llvm::PointerType::getUnqual(CtorFTy), NULL);
237 
238   // Construct the constructor and destructor arrays.
239   std::vector<llvm::Constant*> Ctors;
240   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
241     std::vector<llvm::Constant*> S;
242     S.push_back(llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext),
243                 I->second, false));
244     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
245     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
246   }
247 
248   if (!Ctors.empty()) {
249     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
250     new llvm::GlobalVariable(TheModule, AT, false,
251                              llvm::GlobalValue::AppendingLinkage,
252                              llvm::ConstantArray::get(AT, Ctors),
253                              GlobalName);
254   }
255 }
256 
257 void CodeGenModule::EmitAnnotations() {
258   if (Annotations.empty())
259     return;
260 
261   // Create a new global variable for the ConstantStruct in the Module.
262   llvm::Constant *Array =
263   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
264                                                 Annotations.size()),
265                            Annotations);
266   llvm::GlobalValue *gv =
267   new llvm::GlobalVariable(TheModule, Array->getType(), false,
268                            llvm::GlobalValue::AppendingLinkage, Array,
269                            "llvm.global.annotations");
270   gv->setSection("llvm.metadata");
271 }
272 
273 static CodeGenModule::GVALinkage
274 GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
275                       const LangOptions &Features) {
276   CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
277 
278   Linkage L = FD->getLinkage();
279   if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
280       FD->getType()->getLinkage() == UniqueExternalLinkage)
281     L = UniqueExternalLinkage;
282 
283   switch (L) {
284   case NoLinkage:
285   case InternalLinkage:
286   case UniqueExternalLinkage:
287     return CodeGenModule::GVA_Internal;
288 
289   case ExternalLinkage:
290     switch (FD->getTemplateSpecializationKind()) {
291     case TSK_Undeclared:
292     case TSK_ExplicitSpecialization:
293       External = CodeGenModule::GVA_StrongExternal;
294       break;
295 
296     case TSK_ExplicitInstantiationDefinition:
297       return CodeGenModule::GVA_ExplicitTemplateInstantiation;
298 
299     case TSK_ExplicitInstantiationDeclaration:
300     case TSK_ImplicitInstantiation:
301       External = CodeGenModule::GVA_TemplateInstantiation;
302       break;
303     }
304   }
305 
306   if (!FD->isInlined())
307     return External;
308 
309   if (!Features.CPlusPlus || FD->hasAttr<GNUInlineAttr>()) {
310     // GNU or C99 inline semantics. Determine whether this symbol should be
311     // externally visible.
312     if (FD->isInlineDefinitionExternallyVisible())
313       return External;
314 
315     // C99 inline semantics, where the symbol is not externally visible.
316     return CodeGenModule::GVA_C99Inline;
317   }
318 
319   // C++0x [temp.explicit]p9:
320   //   [ Note: The intent is that an inline function that is the subject of
321   //   an explicit instantiation declaration will still be implicitly
322   //   instantiated when used so that the body can be considered for
323   //   inlining, but that no out-of-line copy of the inline function would be
324   //   generated in the translation unit. -- end note ]
325   if (FD->getTemplateSpecializationKind()
326                                        == TSK_ExplicitInstantiationDeclaration)
327     return CodeGenModule::GVA_C99Inline;
328 
329   return CodeGenModule::GVA_CXXInline;
330 }
331 
332 llvm::GlobalValue::LinkageTypes
333 CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
334   GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
335 
336   if (Linkage == GVA_Internal) {
337     return llvm::Function::InternalLinkage;
338   } else if (D->hasAttr<DLLExportAttr>()) {
339     return llvm::Function::DLLExportLinkage;
340   } else if (D->hasAttr<WeakAttr>()) {
341     return llvm::Function::WeakAnyLinkage;
342   } else if (Linkage == GVA_C99Inline) {
343     // In C99 mode, 'inline' functions are guaranteed to have a strong
344     // definition somewhere else, so we can use available_externally linkage.
345     return llvm::Function::AvailableExternallyLinkage;
346   } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) {
347     // In C++, the compiler has to emit a definition in every translation unit
348     // that references the function.  We should use linkonce_odr because
349     // a) if all references in this translation unit are optimized away, we
350     // don't need to codegen it.  b) if the function persists, it needs to be
351     // merged with other definitions. c) C++ has the ODR, so we know the
352     // definition is dependable.
353     return llvm::Function::LinkOnceODRLinkage;
354   } else if (Linkage == GVA_ExplicitTemplateInstantiation) {
355     // An explicit instantiation of a template has weak linkage, since
356     // explicit instantiations can occur in multiple translation units
357     // and must all be equivalent. However, we are not allowed to
358     // throw away these explicit instantiations.
359     return llvm::Function::WeakODRLinkage;
360   } else {
361     assert(Linkage == GVA_StrongExternal);
362     // Otherwise, we have strong external linkage.
363     return llvm::Function::ExternalLinkage;
364   }
365 }
366 
367 
368 /// SetFunctionDefinitionAttributes - Set attributes for a global.
369 ///
370 /// FIXME: This is currently only done for aliases and functions, but not for
371 /// variables (these details are set in EmitGlobalVarDefinition for variables).
372 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
373                                                     llvm::GlobalValue *GV) {
374   SetCommonAttributes(D, GV);
375 }
376 
377 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
378                                               const CGFunctionInfo &Info,
379                                               llvm::Function *F) {
380   unsigned CallingConv;
381   AttributeListType AttributeList;
382   ConstructAttributeList(Info, D, AttributeList, CallingConv);
383   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
384                                           AttributeList.size()));
385   F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
386 }
387 
388 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
389                                                            llvm::Function *F) {
390   if (!Features.Exceptions && !Features.ObjCNonFragileABI)
391     F->addFnAttr(llvm::Attribute::NoUnwind);
392 
393   if (D->hasAttr<AlwaysInlineAttr>())
394     F->addFnAttr(llvm::Attribute::AlwaysInline);
395 
396   if (D->hasAttr<NoInlineAttr>())
397     F->addFnAttr(llvm::Attribute::NoInline);
398 
399   if (Features.getStackProtectorMode() == LangOptions::SSPOn)
400     F->addFnAttr(llvm::Attribute::StackProtect);
401   else if (Features.getStackProtectorMode() == LangOptions::SSPReq)
402     F->addFnAttr(llvm::Attribute::StackProtectReq);
403 
404   if (const AlignedAttr *AA = D->getAttr<AlignedAttr>()) {
405     unsigned width = Context.Target.getCharWidth();
406     F->setAlignment(AA->getAlignment() / width);
407     while ((AA = AA->getNext<AlignedAttr>()))
408       F->setAlignment(std::max(F->getAlignment(), AA->getAlignment() / width));
409   }
410   // C++ ABI requires 2-byte alignment for member functions.
411   if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
412     F->setAlignment(2);
413 }
414 
415 void CodeGenModule::SetCommonAttributes(const Decl *D,
416                                         llvm::GlobalValue *GV) {
417   setGlobalVisibility(GV, D);
418 
419   if (D->hasAttr<UsedAttr>())
420     AddUsedGlobal(GV);
421 
422   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
423     GV->setSection(SA->getName());
424 
425   getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
426 }
427 
428 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
429                                                   llvm::Function *F,
430                                                   const CGFunctionInfo &FI) {
431   SetLLVMFunctionAttributes(D, FI, F);
432   SetLLVMFunctionAttributesForDefinition(D, F);
433 
434   F->setLinkage(llvm::Function::InternalLinkage);
435 
436   SetCommonAttributes(D, F);
437 }
438 
439 void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
440                                           llvm::Function *F,
441                                           bool IsIncompleteFunction) {
442   const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
443 
444   if (!IsIncompleteFunction)
445     SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(GD), F);
446 
447   // Only a few attributes are set on declarations; these may later be
448   // overridden by a definition.
449 
450   if (FD->hasAttr<DLLImportAttr>()) {
451     F->setLinkage(llvm::Function::DLLImportLinkage);
452   } else if (FD->hasAttr<WeakAttr>() ||
453              FD->hasAttr<WeakImportAttr>()) {
454     // "extern_weak" is overloaded in LLVM; we probably should have
455     // separate linkage types for this.
456     F->setLinkage(llvm::Function::ExternalWeakLinkage);
457   } else {
458     F->setLinkage(llvm::Function::ExternalLinkage);
459   }
460 
461   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
462     F->setSection(SA->getName());
463 }
464 
465 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
466   assert(!GV->isDeclaration() &&
467          "Only globals with definition can force usage.");
468   LLVMUsed.push_back(GV);
469 }
470 
471 void CodeGenModule::EmitLLVMUsed() {
472   // Don't create llvm.used if there is no need.
473   if (LLVMUsed.empty())
474     return;
475 
476   const llvm::Type *i8PTy = llvm::Type::getInt8PtrTy(VMContext);
477 
478   // Convert LLVMUsed to what ConstantArray needs.
479   std::vector<llvm::Constant*> UsedArray;
480   UsedArray.resize(LLVMUsed.size());
481   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
482     UsedArray[i] =
483      llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
484                                       i8PTy);
485   }
486 
487   if (UsedArray.empty())
488     return;
489   llvm::ArrayType *ATy = llvm::ArrayType::get(i8PTy, UsedArray.size());
490 
491   llvm::GlobalVariable *GV =
492     new llvm::GlobalVariable(getModule(), ATy, false,
493                              llvm::GlobalValue::AppendingLinkage,
494                              llvm::ConstantArray::get(ATy, UsedArray),
495                              "llvm.used");
496 
497   GV->setSection("llvm.metadata");
498 }
499 
500 void CodeGenModule::EmitDeferred() {
501   // Emit code for any potentially referenced deferred decls.  Since a
502   // previously unused static decl may become used during the generation of code
503   // for a static function, iterate until no  changes are made.
504 
505   while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
506     if (!DeferredVTables.empty()) {
507       const CXXRecordDecl *RD = DeferredVTables.back();
508       DeferredVTables.pop_back();
509       getVTables().GenerateClassData(getVTableLinkage(RD), RD);
510       continue;
511     }
512 
513     GlobalDecl D = DeferredDeclsToEmit.back();
514     DeferredDeclsToEmit.pop_back();
515 
516     // Check to see if we've already emitted this.  This is necessary
517     // for a couple of reasons: first, decls can end up in the
518     // deferred-decls queue multiple times, and second, decls can end
519     // up with definitions in unusual ways (e.g. by an extern inline
520     // function acquiring a strong function redefinition).  Just
521     // ignore these cases.
522     //
523     // TODO: That said, looking this up multiple times is very wasteful.
524     MangleBuffer Name;
525     getMangledName(Name, D);
526     llvm::GlobalValue *CGRef = GetGlobalValue(Name);
527     assert(CGRef && "Deferred decl wasn't referenced?");
528 
529     if (!CGRef->isDeclaration())
530       continue;
531 
532     // GlobalAlias::isDeclaration() defers to the aliasee, but for our
533     // purposes an alias counts as a definition.
534     if (isa<llvm::GlobalAlias>(CGRef))
535       continue;
536 
537     // Otherwise, emit the definition and move on to the next one.
538     EmitGlobalDefinition(D);
539   }
540 }
541 
542 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
543 /// annotation information for a given GlobalValue.  The annotation struct is
544 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
545 /// GlobalValue being annotated.  The second field is the constant string
546 /// created from the AnnotateAttr's annotation.  The third field is a constant
547 /// string containing the name of the translation unit.  The fourth field is
548 /// the line number in the file of the annotated value declaration.
549 ///
550 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
551 ///        appears to.
552 ///
553 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
554                                                 const AnnotateAttr *AA,
555                                                 unsigned LineNo) {
556   llvm::Module *M = &getModule();
557 
558   // get [N x i8] constants for the annotation string, and the filename string
559   // which are the 2nd and 3rd elements of the global annotation structure.
560   const llvm::Type *SBP = llvm::Type::getInt8PtrTy(VMContext);
561   llvm::Constant *anno = llvm::ConstantArray::get(VMContext,
562                                                   AA->getAnnotation(), true);
563   llvm::Constant *unit = llvm::ConstantArray::get(VMContext,
564                                                   M->getModuleIdentifier(),
565                                                   true);
566 
567   // Get the two global values corresponding to the ConstantArrays we just
568   // created to hold the bytes of the strings.
569   llvm::GlobalValue *annoGV =
570     new llvm::GlobalVariable(*M, anno->getType(), false,
571                              llvm::GlobalValue::PrivateLinkage, anno,
572                              GV->getName());
573   // translation unit name string, emitted into the llvm.metadata section.
574   llvm::GlobalValue *unitGV =
575     new llvm::GlobalVariable(*M, unit->getType(), false,
576                              llvm::GlobalValue::PrivateLinkage, unit,
577                              ".str");
578 
579   // Create the ConstantStruct for the global annotation.
580   llvm::Constant *Fields[4] = {
581     llvm::ConstantExpr::getBitCast(GV, SBP),
582     llvm::ConstantExpr::getBitCast(annoGV, SBP),
583     llvm::ConstantExpr::getBitCast(unitGV, SBP),
584     llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), LineNo)
585   };
586   return llvm::ConstantStruct::get(VMContext, Fields, 4, false);
587 }
588 
589 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
590   // Never defer when EmitAllDecls is specified or the decl has
591   // attribute used.
592   if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
593     return false;
594 
595   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
596     // Constructors and destructors should never be deferred.
597     if (FD->hasAttr<ConstructorAttr>() ||
598         FD->hasAttr<DestructorAttr>())
599       return false;
600 
601     // The key function for a class must never be deferred.
602     if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Global)) {
603       const CXXRecordDecl *RD = MD->getParent();
604       if (MD->isOutOfLine() && RD->isDynamicClass()) {
605         const CXXMethodDecl *KeyFunction = getContext().getKeyFunction(RD);
606         if (KeyFunction &&
607             KeyFunction->getCanonicalDecl() == MD->getCanonicalDecl())
608           return false;
609       }
610     }
611 
612     GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
613 
614     // static, static inline, always_inline, and extern inline functions can
615     // always be deferred.  Normal inline functions can be deferred in C99/C++.
616     // Implicit template instantiations can also be deferred in C++.
617     if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
618         Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
619       return true;
620     return false;
621   }
622 
623   const VarDecl *VD = cast<VarDecl>(Global);
624   assert(VD->isFileVarDecl() && "Invalid decl");
625 
626   // We never want to defer structs that have non-trivial constructors or
627   // destructors.
628 
629   // FIXME: Handle references.
630   if (const RecordType *RT = VD->getType()->getAs<RecordType>()) {
631     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
632       if (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())
633         return false;
634     }
635   }
636 
637   // Static data may be deferred, but out-of-line static data members
638   // cannot be.
639   Linkage L = VD->getLinkage();
640   if (L == ExternalLinkage && getContext().getLangOptions().CPlusPlus &&
641       VD->getType()->getLinkage() == UniqueExternalLinkage)
642     L = UniqueExternalLinkage;
643 
644   switch (L) {
645   case NoLinkage:
646   case InternalLinkage:
647   case UniqueExternalLinkage:
648     // Initializer has side effects?
649     if (VD->getInit() && VD->getInit()->HasSideEffects(Context))
650       return false;
651     return !(VD->isStaticDataMember() && VD->isOutOfLine());
652 
653   case ExternalLinkage:
654     break;
655   }
656 
657   return false;
658 }
659 
660 llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
661   const AliasAttr *AA = VD->getAttr<AliasAttr>();
662   assert(AA && "No alias?");
663 
664   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
665 
666   // See if there is already something with the target's name in the module.
667   llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
668 
669   llvm::Constant *Aliasee;
670   if (isa<llvm::FunctionType>(DeclTy))
671     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
672   else
673     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
674                                     llvm::PointerType::getUnqual(DeclTy), 0);
675   if (!Entry) {
676     llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
677     F->setLinkage(llvm::Function::ExternalWeakLinkage);
678     WeakRefReferences.insert(F);
679   }
680 
681   return Aliasee;
682 }
683 
684 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
685   const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
686 
687   // Weak references don't produce any output by themselves.
688   if (Global->hasAttr<WeakRefAttr>())
689     return;
690 
691   // If this is an alias definition (which otherwise looks like a declaration)
692   // emit it now.
693   if (Global->hasAttr<AliasAttr>())
694     return EmitAliasDefinition(GD);
695 
696   // Ignore declarations, they will be emitted on their first use.
697   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
698     // Forward declarations are emitted lazily on first use.
699     if (!FD->isThisDeclarationADefinition())
700       return;
701   } else {
702     const VarDecl *VD = cast<VarDecl>(Global);
703     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
704 
705     if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
706       return;
707   }
708 
709   // Defer code generation when possible if this is a static definition, inline
710   // function etc.  These we only want to emit if they are used.
711   if (!MayDeferGeneration(Global)) {
712     // Emit the definition if it can't be deferred.
713     EmitGlobalDefinition(GD);
714     return;
715   }
716 
717   // If the value has already been used, add it directly to the
718   // DeferredDeclsToEmit list.
719   MangleBuffer MangledName;
720   getMangledName(MangledName, GD);
721   if (GetGlobalValue(MangledName))
722     DeferredDeclsToEmit.push_back(GD);
723   else {
724     // Otherwise, remember that we saw a deferred decl with this name.  The
725     // first use of the mangled name will cause it to move into
726     // DeferredDeclsToEmit.
727     DeferredDecls[MangledName] = GD;
728   }
729 }
730 
731 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
732   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
733 
734   PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
735                                  Context.getSourceManager(),
736                                  "Generating code for declaration");
737 
738   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
739     if (Method->isVirtual())
740       getVTables().EmitThunks(GD);
741 
742   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
743     return EmitCXXConstructor(CD, GD.getCtorType());
744 
745   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
746     return EmitCXXDestructor(DD, GD.getDtorType());
747 
748   if (isa<FunctionDecl>(D))
749     return EmitGlobalFunctionDefinition(GD);
750 
751   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
752     return EmitGlobalVarDefinition(VD);
753 
754   assert(0 && "Invalid argument to EmitGlobalDefinition()");
755 }
756 
757 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
758 /// module, create and return an llvm Function with the specified type. If there
759 /// is something in the module with the specified name, return it potentially
760 /// bitcasted to the right type.
761 ///
762 /// If D is non-null, it specifies a decl that correspond to this.  This is used
763 /// to set the attributes on the function when it is first created.
764 llvm::Constant *
765 CodeGenModule::GetOrCreateLLVMFunction(llvm::StringRef MangledName,
766                                        const llvm::Type *Ty,
767                                        GlobalDecl D) {
768   // Lookup the entry, lazily creating it if necessary.
769   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
770   if (Entry) {
771     if (WeakRefReferences.count(Entry)) {
772       const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
773       if (FD && !FD->hasAttr<WeakAttr>())
774         Entry->setLinkage(llvm::Function::ExternalLinkage);
775 
776       WeakRefReferences.erase(Entry);
777     }
778 
779     if (Entry->getType()->getElementType() == Ty)
780       return Entry;
781 
782     // Make sure the result is of the correct type.
783     const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
784     return llvm::ConstantExpr::getBitCast(Entry, PTy);
785   }
786 
787   // This function doesn't have a complete type (for example, the return
788   // type is an incomplete struct). Use a fake type instead, and make
789   // sure not to try to set attributes.
790   bool IsIncompleteFunction = false;
791 
792   const llvm::FunctionType *FTy;
793   if (isa<llvm::FunctionType>(Ty)) {
794     FTy = cast<llvm::FunctionType>(Ty);
795   } else {
796     FTy = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext),
797                                   std::vector<const llvm::Type*>(), false);
798     IsIncompleteFunction = true;
799   }
800   llvm::Function *F = llvm::Function::Create(FTy,
801                                              llvm::Function::ExternalLinkage,
802                                              MangledName, &getModule());
803   assert(F->getName() == MangledName && "name was uniqued!");
804   if (D.getDecl())
805     SetFunctionAttributes(D, F, IsIncompleteFunction);
806 
807   // This is the first use or definition of a mangled name.  If there is a
808   // deferred decl with this name, remember that we need to emit it at the end
809   // of the file.
810   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
811   if (DDI != DeferredDecls.end()) {
812     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
813     // list, and remove it from DeferredDecls (since we don't need it anymore).
814     DeferredDeclsToEmit.push_back(DDI->second);
815     DeferredDecls.erase(DDI);
816   } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
817     // If this the first reference to a C++ inline function in a class, queue up
818     // the deferred function body for emission.  These are not seen as
819     // top-level declarations.
820     if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
821       DeferredDeclsToEmit.push_back(D);
822     // A called constructor which has no definition or declaration need be
823     // synthesized.
824     else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
825       if (CD->isImplicit()) {
826         assert(CD->isUsed() && "Sema doesn't consider constructor as used.");
827         DeferredDeclsToEmit.push_back(D);
828       }
829     } else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD)) {
830       if (DD->isImplicit()) {
831         assert(DD->isUsed() && "Sema doesn't consider destructor as used.");
832         DeferredDeclsToEmit.push_back(D);
833       }
834     } else if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
835       if (MD->isCopyAssignment() && MD->isImplicit()) {
836         assert(MD->isUsed() && "Sema doesn't consider CopyAssignment as used.");
837         DeferredDeclsToEmit.push_back(D);
838       }
839     }
840   }
841 
842   // Make sure the result is of the requested type.
843   if (!IsIncompleteFunction) {
844     assert(F->getType()->getElementType() == Ty);
845     return F;
846   }
847 
848   const llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
849   return llvm::ConstantExpr::getBitCast(F, PTy);
850 }
851 
852 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
853 /// non-null, then this function will use the specified type if it has to
854 /// create it (this occurs when we see a definition of the function).
855 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
856                                                  const llvm::Type *Ty) {
857   // If there was no specific requested type, just convert it now.
858   if (!Ty)
859     Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
860   MangleBuffer MangledName;
861   getMangledName(MangledName, GD);
862   return GetOrCreateLLVMFunction(MangledName, Ty, GD);
863 }
864 
865 /// CreateRuntimeFunction - Create a new runtime function with the specified
866 /// type and name.
867 llvm::Constant *
868 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
869                                      llvm::StringRef Name) {
870   return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
871 }
872 
873 static bool DeclIsConstantGlobal(ASTContext &Context, const VarDecl *D) {
874   if (!D->getType().isConstant(Context) && !D->getType()->isReferenceType())
875     return false;
876   if (Context.getLangOptions().CPlusPlus &&
877       Context.getBaseElementType(D->getType())->getAs<RecordType>()) {
878     // FIXME: We should do something fancier here!
879     return false;
880   }
881   return true;
882 }
883 
884 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
885 /// create and return an llvm GlobalVariable with the specified type.  If there
886 /// is something in the module with the specified name, return it potentially
887 /// bitcasted to the right type.
888 ///
889 /// If D is non-null, it specifies a decl that correspond to this.  This is used
890 /// to set the attributes on the global when it is first created.
891 llvm::Constant *
892 CodeGenModule::GetOrCreateLLVMGlobal(llvm::StringRef MangledName,
893                                      const llvm::PointerType *Ty,
894                                      const VarDecl *D) {
895   // Lookup the entry, lazily creating it if necessary.
896   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
897   if (Entry) {
898     if (WeakRefReferences.count(Entry)) {
899       if (D && !D->hasAttr<WeakAttr>())
900         Entry->setLinkage(llvm::Function::ExternalLinkage);
901 
902       WeakRefReferences.erase(Entry);
903     }
904 
905     if (Entry->getType() == Ty)
906       return Entry;
907 
908     // Make sure the result is of the correct type.
909     return llvm::ConstantExpr::getBitCast(Entry, Ty);
910   }
911 
912   // This is the first use or definition of a mangled name.  If there is a
913   // deferred decl with this name, remember that we need to emit it at the end
914   // of the file.
915   llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
916   if (DDI != DeferredDecls.end()) {
917     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
918     // list, and remove it from DeferredDecls (since we don't need it anymore).
919     DeferredDeclsToEmit.push_back(DDI->second);
920     DeferredDecls.erase(DDI);
921   }
922 
923   llvm::GlobalVariable *GV =
924     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
925                              llvm::GlobalValue::ExternalLinkage,
926                              0, MangledName, 0,
927                              false, Ty->getAddressSpace());
928 
929   // Handle things which are present even on external declarations.
930   if (D) {
931     // FIXME: This code is overly simple and should be merged with other global
932     // handling.
933     GV->setConstant(DeclIsConstantGlobal(Context, D));
934 
935     // FIXME: Merge with other attribute handling code.
936     if (D->getStorageClass() == VarDecl::PrivateExtern)
937       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
938 
939     if (D->hasAttr<WeakAttr>() ||
940         D->hasAttr<WeakImportAttr>())
941       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
942 
943     GV->setThreadLocal(D->isThreadSpecified());
944   }
945 
946   return GV;
947 }
948 
949 
950 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
951 /// given global variable.  If Ty is non-null and if the global doesn't exist,
952 /// then it will be greated with the specified type instead of whatever the
953 /// normal requested type would be.
954 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
955                                                   const llvm::Type *Ty) {
956   assert(D->hasGlobalStorage() && "Not a global variable");
957   QualType ASTTy = D->getType();
958   if (Ty == 0)
959     Ty = getTypes().ConvertTypeForMem(ASTTy);
960 
961   const llvm::PointerType *PTy =
962     llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
963 
964   MangleBuffer MangledName;
965   getMangledName(MangledName, D);
966   return GetOrCreateLLVMGlobal(MangledName, PTy, D);
967 }
968 
969 /// CreateRuntimeVariable - Create a new runtime global variable with the
970 /// specified type and name.
971 llvm::Constant *
972 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
973                                      llvm::StringRef Name) {
974   return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0);
975 }
976 
977 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
978   assert(!D->getInit() && "Cannot emit definite definitions here!");
979 
980   if (MayDeferGeneration(D)) {
981     // If we have not seen a reference to this variable yet, place it
982     // into the deferred declarations table to be emitted if needed
983     // later.
984     MangleBuffer MangledName;
985     getMangledName(MangledName, D);
986     if (!GetGlobalValue(MangledName)) {
987       DeferredDecls[MangledName] = D;
988       return;
989     }
990   }
991 
992   // The tentative definition is the only definition.
993   EmitGlobalVarDefinition(D);
994 }
995 
996 void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
997   if (DefinitionRequired)
998     getVTables().GenerateClassData(getVTableLinkage(Class), Class);
999 }
1000 
1001 llvm::GlobalVariable::LinkageTypes
1002 CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
1003   if (RD->isInAnonymousNamespace() || !RD->hasLinkage())
1004     return llvm::GlobalVariable::InternalLinkage;
1005 
1006   if (const CXXMethodDecl *KeyFunction
1007                                     = RD->getASTContext().getKeyFunction(RD)) {
1008     // If this class has a key function, use that to determine the linkage of
1009     // the vtable.
1010     const FunctionDecl *Def = 0;
1011     if (KeyFunction->getBody(Def))
1012       KeyFunction = cast<CXXMethodDecl>(Def);
1013 
1014     switch (KeyFunction->getTemplateSpecializationKind()) {
1015       case TSK_Undeclared:
1016       case TSK_ExplicitSpecialization:
1017         if (KeyFunction->isInlined())
1018           return llvm::GlobalVariable::WeakODRLinkage;
1019 
1020         return llvm::GlobalVariable::ExternalLinkage;
1021 
1022       case TSK_ImplicitInstantiation:
1023       case TSK_ExplicitInstantiationDefinition:
1024         return llvm::GlobalVariable::WeakODRLinkage;
1025 
1026       case TSK_ExplicitInstantiationDeclaration:
1027         // FIXME: Use available_externally linkage. However, this currently
1028         // breaks LLVM's build due to undefined symbols.
1029         //      return llvm::GlobalVariable::AvailableExternallyLinkage;
1030         return llvm::GlobalVariable::WeakODRLinkage;
1031     }
1032   }
1033 
1034   switch (RD->getTemplateSpecializationKind()) {
1035   case TSK_Undeclared:
1036   case TSK_ExplicitSpecialization:
1037   case TSK_ImplicitInstantiation:
1038   case TSK_ExplicitInstantiationDefinition:
1039     return llvm::GlobalVariable::WeakODRLinkage;
1040 
1041   case TSK_ExplicitInstantiationDeclaration:
1042     // FIXME: Use available_externally linkage. However, this currently
1043     // breaks LLVM's build due to undefined symbols.
1044     //   return llvm::GlobalVariable::AvailableExternallyLinkage;
1045     return llvm::GlobalVariable::WeakODRLinkage;
1046   }
1047 
1048   // Silence GCC warning.
1049   return llvm::GlobalVariable::WeakODRLinkage;
1050 }
1051 
1052 static CodeGenModule::GVALinkage
1053 GetLinkageForVariable(ASTContext &Context, const VarDecl *VD) {
1054   // If this is a static data member, compute the kind of template
1055   // specialization. Otherwise, this variable is not part of a
1056   // template.
1057   TemplateSpecializationKind TSK = TSK_Undeclared;
1058   if (VD->isStaticDataMember())
1059     TSK = VD->getTemplateSpecializationKind();
1060 
1061   Linkage L = VD->getLinkage();
1062   if (L == ExternalLinkage && Context.getLangOptions().CPlusPlus &&
1063       VD->getType()->getLinkage() == UniqueExternalLinkage)
1064     L = UniqueExternalLinkage;
1065 
1066   switch (L) {
1067   case NoLinkage:
1068   case InternalLinkage:
1069   case UniqueExternalLinkage:
1070     return CodeGenModule::GVA_Internal;
1071 
1072   case ExternalLinkage:
1073     switch (TSK) {
1074     case TSK_Undeclared:
1075     case TSK_ExplicitSpecialization:
1076       return CodeGenModule::GVA_StrongExternal;
1077 
1078     case TSK_ExplicitInstantiationDeclaration:
1079       llvm_unreachable("Variable should not be instantiated");
1080       // Fall through to treat this like any other instantiation.
1081 
1082     case TSK_ExplicitInstantiationDefinition:
1083       return CodeGenModule::GVA_ExplicitTemplateInstantiation;
1084 
1085     case TSK_ImplicitInstantiation:
1086       return CodeGenModule::GVA_TemplateInstantiation;
1087     }
1088   }
1089 
1090   return CodeGenModule::GVA_StrongExternal;
1091 }
1092 
1093 CharUnits CodeGenModule::GetTargetTypeStoreSize(const llvm::Type *Ty) const {
1094     return CharUnits::fromQuantity(
1095       TheTargetData.getTypeStoreSizeInBits(Ty) / Context.getCharWidth());
1096 }
1097 
1098 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
1099   llvm::Constant *Init = 0;
1100   QualType ASTTy = D->getType();
1101   bool NonConstInit = false;
1102 
1103   const Expr *InitExpr = D->getAnyInitializer();
1104 
1105   if (!InitExpr) {
1106     // This is a tentative definition; tentative definitions are
1107     // implicitly initialized with { 0 }.
1108     //
1109     // Note that tentative definitions are only emitted at the end of
1110     // a translation unit, so they should never have incomplete
1111     // type. In addition, EmitTentativeDefinition makes sure that we
1112     // never attempt to emit a tentative definition if a real one
1113     // exists. A use may still exists, however, so we still may need
1114     // to do a RAUW.
1115     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
1116     Init = EmitNullConstant(D->getType());
1117   } else {
1118     Init = EmitConstantExpr(InitExpr, D->getType());
1119     if (!Init) {
1120       QualType T = InitExpr->getType();
1121       if (D->getType()->isReferenceType())
1122         T = D->getType();
1123 
1124       if (getLangOptions().CPlusPlus) {
1125         EmitCXXGlobalVarDeclInitFunc(D);
1126         Init = EmitNullConstant(T);
1127         NonConstInit = true;
1128       } else {
1129         ErrorUnsupported(D, "static initializer");
1130         Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1131       }
1132     }
1133   }
1134 
1135   const llvm::Type* InitType = Init->getType();
1136   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
1137 
1138   // Strip off a bitcast if we got one back.
1139   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1140     assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1141            // all zero index gep.
1142            CE->getOpcode() == llvm::Instruction::GetElementPtr);
1143     Entry = CE->getOperand(0);
1144   }
1145 
1146   // Entry is now either a Function or GlobalVariable.
1147   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
1148 
1149   // We have a definition after a declaration with the wrong type.
1150   // We must make a new GlobalVariable* and update everything that used OldGV
1151   // (a declaration or tentative definition) with the new GlobalVariable*
1152   // (which will be a definition).
1153   //
1154   // This happens if there is a prototype for a global (e.g.
1155   // "extern int x[];") and then a definition of a different type (e.g.
1156   // "int x[10];"). This also happens when an initializer has a different type
1157   // from the type of the global (this happens with unions).
1158   if (GV == 0 ||
1159       GV->getType()->getElementType() != InitType ||
1160       GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
1161 
1162     // Move the old entry aside so that we'll create a new one.
1163     Entry->setName(llvm::StringRef());
1164 
1165     // Make a new global with the correct type, this is now guaranteed to work.
1166     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
1167 
1168     // Replace all uses of the old global with the new global
1169     llvm::Constant *NewPtrForOldDecl =
1170         llvm::ConstantExpr::getBitCast(GV, Entry->getType());
1171     Entry->replaceAllUsesWith(NewPtrForOldDecl);
1172 
1173     // Erase the old global, since it is no longer used.
1174     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
1175   }
1176 
1177   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
1178     SourceManager &SM = Context.getSourceManager();
1179     AddAnnotation(EmitAnnotateAttr(GV, AA,
1180                               SM.getInstantiationLineNumber(D->getLocation())));
1181   }
1182 
1183   GV->setInitializer(Init);
1184 
1185   // If it is safe to mark the global 'constant', do so now.
1186   GV->setConstant(false);
1187   if (!NonConstInit && DeclIsConstantGlobal(Context, D))
1188     GV->setConstant(true);
1189 
1190   GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
1191 
1192   // Set the llvm linkage type as appropriate.
1193   GVALinkage Linkage = GetLinkageForVariable(getContext(), D);
1194   if (Linkage == GVA_Internal)
1195     GV->setLinkage(llvm::Function::InternalLinkage);
1196   else if (D->hasAttr<DLLImportAttr>())
1197     GV->setLinkage(llvm::Function::DLLImportLinkage);
1198   else if (D->hasAttr<DLLExportAttr>())
1199     GV->setLinkage(llvm::Function::DLLExportLinkage);
1200   else if (D->hasAttr<WeakAttr>()) {
1201     if (GV->isConstant())
1202       GV->setLinkage(llvm::GlobalVariable::WeakODRLinkage);
1203     else
1204       GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1205   } else if (Linkage == GVA_TemplateInstantiation ||
1206              Linkage == GVA_ExplicitTemplateInstantiation)
1207     // FIXME: It seems like we can provide more specific linkage here
1208     // (LinkOnceODR, WeakODR).
1209     GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
1210   else if (!getLangOptions().CPlusPlus && !CodeGenOpts.NoCommon &&
1211            !D->hasExternalStorage() && !D->getInit() &&
1212            !D->getAttr<SectionAttr>()) {
1213     GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
1214     // common vars aren't constant even if declared const.
1215     GV->setConstant(false);
1216   } else
1217     GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
1218 
1219   SetCommonAttributes(D, GV);
1220 
1221   // Emit global variable debug information.
1222   if (CGDebugInfo *DI = getDebugInfo()) {
1223     DI->setLocation(D->getLocation());
1224     DI->EmitGlobalVariable(GV, D);
1225   }
1226 }
1227 
1228 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1229 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
1230 /// existing call uses of the old function in the module, this adjusts them to
1231 /// call the new function directly.
1232 ///
1233 /// This is not just a cleanup: the always_inline pass requires direct calls to
1234 /// functions to be able to inline them.  If there is a bitcast in the way, it
1235 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
1236 /// run at -O0.
1237 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1238                                                       llvm::Function *NewFn) {
1239   // If we're redefining a global as a function, don't transform it.
1240   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
1241   if (OldFn == 0) return;
1242 
1243   const llvm::Type *NewRetTy = NewFn->getReturnType();
1244   llvm::SmallVector<llvm::Value*, 4> ArgList;
1245 
1246   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
1247        UI != E; ) {
1248     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
1249     llvm::Value::use_iterator I = UI++; // Increment before the CI is erased.
1250     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*I);
1251     llvm::CallSite CS(CI);
1252     if (!CI || !CS.isCallee(I)) continue;
1253 
1254     // If the return types don't match exactly, and if the call isn't dead, then
1255     // we can't transform this call.
1256     if (CI->getType() != NewRetTy && !CI->use_empty())
1257       continue;
1258 
1259     // If the function was passed too few arguments, don't transform.  If extra
1260     // arguments were passed, we silently drop them.  If any of the types
1261     // mismatch, we don't transform.
1262     unsigned ArgNo = 0;
1263     bool DontTransform = false;
1264     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
1265          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
1266       if (CS.arg_size() == ArgNo ||
1267           CS.getArgument(ArgNo)->getType() != AI->getType()) {
1268         DontTransform = true;
1269         break;
1270       }
1271     }
1272     if (DontTransform)
1273       continue;
1274 
1275     // Okay, we can transform this.  Create the new call instruction and copy
1276     // over the required information.
1277     ArgList.append(CS.arg_begin(), CS.arg_begin() + ArgNo);
1278     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
1279                                                      ArgList.end(), "", CI);
1280     ArgList.clear();
1281     if (!NewCall->getType()->isVoidTy())
1282       NewCall->takeName(CI);
1283     NewCall->setAttributes(CI->getAttributes());
1284     NewCall->setCallingConv(CI->getCallingConv());
1285 
1286     // Finally, remove the old call, replacing any uses with the new one.
1287     if (!CI->use_empty())
1288       CI->replaceAllUsesWith(NewCall);
1289 
1290     // Copy debug location attached to CI.
1291     if (!CI->getDebugLoc().isUnknown())
1292       NewCall->setDebugLoc(CI->getDebugLoc());
1293     CI->eraseFromParent();
1294   }
1295 }
1296 
1297 
1298 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
1299   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
1300   const llvm::FunctionType *Ty = getTypes().GetFunctionType(GD);
1301   getMangleContext().mangleInitDiscriminator();
1302   // Get or create the prototype for the function.
1303   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
1304 
1305   // Strip off a bitcast if we got one back.
1306   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1307     assert(CE->getOpcode() == llvm::Instruction::BitCast);
1308     Entry = CE->getOperand(0);
1309   }
1310 
1311 
1312   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
1313     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
1314 
1315     // If the types mismatch then we have to rewrite the definition.
1316     assert(OldFn->isDeclaration() &&
1317            "Shouldn't replace non-declaration");
1318 
1319     // F is the Function* for the one with the wrong type, we must make a new
1320     // Function* and update everything that used F (a declaration) with the new
1321     // Function* (which will be a definition).
1322     //
1323     // This happens if there is a prototype for a function
1324     // (e.g. "int f()") and then a definition of a different type
1325     // (e.g. "int f(int x)").  Move the old function aside so that it
1326     // doesn't interfere with GetAddrOfFunction.
1327     OldFn->setName(llvm::StringRef());
1328     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1329 
1330     // If this is an implementation of a function without a prototype, try to
1331     // replace any existing uses of the function (which may be calls) with uses
1332     // of the new function
1333     if (D->getType()->isFunctionNoProtoType()) {
1334       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1335       OldFn->removeDeadConstantUsers();
1336     }
1337 
1338     // Replace uses of F with the Function we will endow with a body.
1339     if (!Entry->use_empty()) {
1340       llvm::Constant *NewPtrForOldDecl =
1341         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
1342       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1343     }
1344 
1345     // Ok, delete the old function now, which is dead.
1346     OldFn->eraseFromParent();
1347 
1348     Entry = NewFn;
1349   }
1350 
1351   llvm::Function *Fn = cast<llvm::Function>(Entry);
1352   setFunctionLinkage(D, Fn);
1353 
1354   CodeGenFunction(*this).GenerateCode(D, Fn);
1355 
1356   SetFunctionDefinitionAttributes(D, Fn);
1357   SetLLVMFunctionAttributesForDefinition(D, Fn);
1358 
1359   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1360     AddGlobalCtor(Fn, CA->getPriority());
1361   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1362     AddGlobalDtor(Fn, DA->getPriority());
1363 }
1364 
1365 void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
1366   const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
1367   const AliasAttr *AA = D->getAttr<AliasAttr>();
1368   assert(AA && "Not an alias?");
1369 
1370   MangleBuffer MangledName;
1371   getMangledName(MangledName, GD);
1372 
1373   // If there is a definition in the module, then it wins over the alias.
1374   // This is dubious, but allow it to be safe.  Just ignore the alias.
1375   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
1376   if (Entry && !Entry->isDeclaration())
1377     return;
1378 
1379   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1380 
1381   // Create a reference to the named value.  This ensures that it is emitted
1382   // if a deferred decl.
1383   llvm::Constant *Aliasee;
1384   if (isa<llvm::FunctionType>(DeclTy))
1385     Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GlobalDecl());
1386   else
1387     Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
1388                                     llvm::PointerType::getUnqual(DeclTy), 0);
1389 
1390   // Create the new alias itself, but don't set a name yet.
1391   llvm::GlobalValue *GA =
1392     new llvm::GlobalAlias(Aliasee->getType(),
1393                           llvm::Function::ExternalLinkage,
1394                           "", Aliasee, &getModule());
1395 
1396   if (Entry) {
1397     assert(Entry->isDeclaration());
1398 
1399     // If there is a declaration in the module, then we had an extern followed
1400     // by the alias, as in:
1401     //   extern int test6();
1402     //   ...
1403     //   int test6() __attribute__((alias("test7")));
1404     //
1405     // Remove it and replace uses of it with the alias.
1406     GA->takeName(Entry);
1407 
1408     Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
1409                                                           Entry->getType()));
1410     Entry->eraseFromParent();
1411   } else {
1412     GA->setName(MangledName.getString());
1413   }
1414 
1415   // Set attributes which are particular to an alias; this is a
1416   // specialization of the attributes which may be set on a global
1417   // variable/function.
1418   if (D->hasAttr<DLLExportAttr>()) {
1419     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1420       // The dllexport attribute is ignored for undefined symbols.
1421       if (FD->getBody())
1422         GA->setLinkage(llvm::Function::DLLExportLinkage);
1423     } else {
1424       GA->setLinkage(llvm::Function::DLLExportLinkage);
1425     }
1426   } else if (D->hasAttr<WeakAttr>() ||
1427              D->hasAttr<WeakRefAttr>() ||
1428              D->hasAttr<WeakImportAttr>()) {
1429     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1430   }
1431 
1432   SetCommonAttributes(D, GA);
1433 }
1434 
1435 /// getBuiltinLibFunction - Given a builtin id for a function like
1436 /// "__builtin_fabsf", return a Function* for "fabsf".
1437 llvm::Value *CodeGenModule::getBuiltinLibFunction(const FunctionDecl *FD,
1438                                                   unsigned BuiltinID) {
1439   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1440           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1441          "isn't a lib fn");
1442 
1443   // Get the name, skip over the __builtin_ prefix (if necessary).
1444   const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1445   if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1446     Name += 10;
1447 
1448   const llvm::FunctionType *Ty =
1449     cast<llvm::FunctionType>(getTypes().ConvertType(FD->getType()));
1450 
1451   return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl(FD));
1452 }
1453 
1454 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1455                                             unsigned NumTys) {
1456   return llvm::Intrinsic::getDeclaration(&getModule(),
1457                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
1458 }
1459 
1460 
1461 llvm::Function *CodeGenModule::getMemCpyFn(const llvm::Type *DestType,
1462                                            const llvm::Type *SrcType,
1463                                            const llvm::Type *SizeType) {
1464   const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1465   return getIntrinsic(llvm::Intrinsic::memcpy, ArgTypes, 3);
1466 }
1467 
1468 llvm::Function *CodeGenModule::getMemMoveFn(const llvm::Type *DestType,
1469                                             const llvm::Type *SrcType,
1470                                             const llvm::Type *SizeType) {
1471   const llvm::Type *ArgTypes[3] = {DestType, SrcType, SizeType };
1472   return getIntrinsic(llvm::Intrinsic::memmove, ArgTypes, 3);
1473 }
1474 
1475 llvm::Function *CodeGenModule::getMemSetFn(const llvm::Type *DestType,
1476                                            const llvm::Type *SizeType) {
1477   const llvm::Type *ArgTypes[2] = { DestType, SizeType };
1478   return getIntrinsic(llvm::Intrinsic::memset, ArgTypes, 2);
1479 }
1480 
1481 static llvm::StringMapEntry<llvm::Constant*> &
1482 GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
1483                          const StringLiteral *Literal,
1484                          bool TargetIsLSB,
1485                          bool &IsUTF16,
1486                          unsigned &StringLength) {
1487   unsigned NumBytes = Literal->getByteLength();
1488 
1489   // Check for simple case.
1490   if (!Literal->containsNonAsciiOrNull()) {
1491     StringLength = NumBytes;
1492     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1493                                                 StringLength));
1494   }
1495 
1496   // Otherwise, convert the UTF8 literals into a byte string.
1497   llvm::SmallVector<UTF16, 128> ToBuf(NumBytes);
1498   const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1499   UTF16 *ToPtr = &ToBuf[0];
1500 
1501   ConversionResult Result = ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
1502                                                &ToPtr, ToPtr + NumBytes,
1503                                                strictConversion);
1504 
1505   // Check for conversion failure.
1506   if (Result != conversionOK) {
1507     // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string and remove
1508     // this duplicate code.
1509     assert(Result == sourceIllegal && "UTF-8 to UTF-16 conversion failed");
1510     StringLength = NumBytes;
1511     return Map.GetOrCreateValue(llvm::StringRef(Literal->getStrData(),
1512                                                 StringLength));
1513   }
1514 
1515   // ConvertUTF8toUTF16 returns the length in ToPtr.
1516   StringLength = ToPtr - &ToBuf[0];
1517 
1518   // Render the UTF-16 string into a byte array and convert to the target byte
1519   // order.
1520   //
1521   // FIXME: This isn't something we should need to do here.
1522   llvm::SmallString<128> AsBytes;
1523   AsBytes.reserve(StringLength * 2);
1524   for (unsigned i = 0; i != StringLength; ++i) {
1525     unsigned short Val = ToBuf[i];
1526     if (TargetIsLSB) {
1527       AsBytes.push_back(Val & 0xFF);
1528       AsBytes.push_back(Val >> 8);
1529     } else {
1530       AsBytes.push_back(Val >> 8);
1531       AsBytes.push_back(Val & 0xFF);
1532     }
1533   }
1534   // Append one extra null character, the second is automatically added by our
1535   // caller.
1536   AsBytes.push_back(0);
1537 
1538   IsUTF16 = true;
1539   return Map.GetOrCreateValue(llvm::StringRef(AsBytes.data(), AsBytes.size()));
1540 }
1541 
1542 llvm::Constant *
1543 CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
1544   unsigned StringLength = 0;
1545   bool isUTF16 = false;
1546   llvm::StringMapEntry<llvm::Constant*> &Entry =
1547     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1548                              getTargetData().isLittleEndian(),
1549                              isUTF16, StringLength);
1550 
1551   if (llvm::Constant *C = Entry.getValue())
1552     return C;
1553 
1554   llvm::Constant *Zero =
1555       llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1556   llvm::Constant *Zeros[] = { Zero, Zero };
1557 
1558   // If we don't already have it, get __CFConstantStringClassReference.
1559   if (!CFConstantStringClassRef) {
1560     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1561     Ty = llvm::ArrayType::get(Ty, 0);
1562     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1563                                            "__CFConstantStringClassReference");
1564     // Decay array -> ptr
1565     CFConstantStringClassRef =
1566       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1567   }
1568 
1569   QualType CFTy = getContext().getCFConstantStringType();
1570 
1571   const llvm::StructType *STy =
1572     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1573 
1574   std::vector<llvm::Constant*> Fields(4);
1575 
1576   // Class pointer.
1577   Fields[0] = CFConstantStringClassRef;
1578 
1579   // Flags.
1580   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1581   Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
1582     llvm::ConstantInt::get(Ty, 0x07C8);
1583 
1584   // String pointer.
1585   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1586 
1587   llvm::GlobalValue::LinkageTypes Linkage;
1588   bool isConstant;
1589   if (isUTF16) {
1590     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1591     Linkage = llvm::GlobalValue::InternalLinkage;
1592     // Note: -fwritable-strings doesn't make unicode CFStrings writable, but
1593     // does make plain ascii ones writable.
1594     isConstant = true;
1595   } else {
1596     Linkage = llvm::GlobalValue::PrivateLinkage;
1597     isConstant = !Features.WritableStrings;
1598   }
1599 
1600   llvm::GlobalVariable *GV =
1601     new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1602                              ".str");
1603   if (isUTF16) {
1604     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1605     GV->setAlignment(Align.getQuantity());
1606   }
1607   Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1608 
1609   // String length.
1610   Ty = getTypes().ConvertType(getContext().LongTy);
1611   Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
1612 
1613   // The struct.
1614   C = llvm::ConstantStruct::get(STy, Fields);
1615   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1616                                 llvm::GlobalVariable::PrivateLinkage, C,
1617                                 "_unnamed_cfstring_");
1618   if (const char *Sect = getContext().Target.getCFStringSection())
1619     GV->setSection(Sect);
1620   Entry.setValue(GV);
1621 
1622   return GV;
1623 }
1624 
1625 llvm::Constant *
1626 CodeGenModule::GetAddrOfConstantNSString(const StringLiteral *Literal) {
1627   unsigned StringLength = 0;
1628   bool isUTF16 = false;
1629   llvm::StringMapEntry<llvm::Constant*> &Entry =
1630     GetConstantCFStringEntry(CFConstantStringMap, Literal,
1631                              getTargetData().isLittleEndian(),
1632                              isUTF16, StringLength);
1633 
1634   if (llvm::Constant *C = Entry.getValue())
1635     return C;
1636 
1637   llvm::Constant *Zero =
1638   llvm::Constant::getNullValue(llvm::Type::getInt32Ty(VMContext));
1639   llvm::Constant *Zeros[] = { Zero, Zero };
1640 
1641   // If we don't already have it, get _NSConstantStringClassReference.
1642   if (!NSConstantStringClassRef) {
1643     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1644     Ty = llvm::ArrayType::get(Ty, 0);
1645     llvm::Constant *GV = CreateRuntimeVariable(Ty,
1646                                         Features.ObjCNonFragileABI ?
1647                                         "OBJC_CLASS_$_NSConstantString" :
1648                                         "_NSConstantStringClassReference");
1649     // Decay array -> ptr
1650     NSConstantStringClassRef =
1651       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1652   }
1653 
1654   QualType NSTy = getContext().getNSConstantStringType();
1655 
1656   const llvm::StructType *STy =
1657   cast<llvm::StructType>(getTypes().ConvertType(NSTy));
1658 
1659   std::vector<llvm::Constant*> Fields(3);
1660 
1661   // Class pointer.
1662   Fields[0] = NSConstantStringClassRef;
1663 
1664   // String pointer.
1665   llvm::Constant *C = llvm::ConstantArray::get(VMContext, Entry.getKey().str());
1666 
1667   llvm::GlobalValue::LinkageTypes Linkage;
1668   bool isConstant;
1669   if (isUTF16) {
1670     // FIXME: why do utf strings get "_" labels instead of "L" labels?
1671     Linkage = llvm::GlobalValue::InternalLinkage;
1672     // Note: -fwritable-strings doesn't make unicode NSStrings writable, but
1673     // does make plain ascii ones writable.
1674     isConstant = true;
1675   } else {
1676     Linkage = llvm::GlobalValue::PrivateLinkage;
1677     isConstant = !Features.WritableStrings;
1678   }
1679 
1680   llvm::GlobalVariable *GV =
1681   new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
1682                            ".str");
1683   if (isUTF16) {
1684     CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
1685     GV->setAlignment(Align.getQuantity());
1686   }
1687   Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
1688 
1689   // String length.
1690   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1691   Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
1692 
1693   // The struct.
1694   C = llvm::ConstantStruct::get(STy, Fields);
1695   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1696                                 llvm::GlobalVariable::PrivateLinkage, C,
1697                                 "_unnamed_nsstring_");
1698   // FIXME. Fix section.
1699   if (const char *Sect =
1700         Features.ObjCNonFragileABI
1701           ? getContext().Target.getNSStringNonFragileABISection()
1702           : getContext().Target.getNSStringSection())
1703     GV->setSection(Sect);
1704   Entry.setValue(GV);
1705 
1706   return GV;
1707 }
1708 
1709 /// GetStringForStringLiteral - Return the appropriate bytes for a
1710 /// string literal, properly padded to match the literal type.
1711 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1712   const char *StrData = E->getStrData();
1713   unsigned Len = E->getByteLength();
1714 
1715   const ConstantArrayType *CAT =
1716     getContext().getAsConstantArrayType(E->getType());
1717   assert(CAT && "String isn't pointer or array!");
1718 
1719   // Resize the string to the right size.
1720   std::string Str(StrData, StrData+Len);
1721   uint64_t RealLen = CAT->getSize().getZExtValue();
1722 
1723   if (E->isWide())
1724     RealLen *= getContext().Target.getWCharWidth()/8;
1725 
1726   Str.resize(RealLen, '\0');
1727 
1728   return Str;
1729 }
1730 
1731 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1732 /// constant array for the given string literal.
1733 llvm::Constant *
1734 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1735   // FIXME: This can be more efficient.
1736   // FIXME: We shouldn't need to bitcast the constant in the wide string case.
1737   llvm::Constant *C = GetAddrOfConstantString(GetStringForStringLiteral(S));
1738   if (S->isWide()) {
1739     llvm::Type *DestTy =
1740         llvm::PointerType::getUnqual(getTypes().ConvertType(S->getType()));
1741     C = llvm::ConstantExpr::getBitCast(C, DestTy);
1742   }
1743   return C;
1744 }
1745 
1746 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1747 /// array for the given ObjCEncodeExpr node.
1748 llvm::Constant *
1749 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1750   std::string Str;
1751   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1752 
1753   return GetAddrOfConstantCString(Str);
1754 }
1755 
1756 
1757 /// GenerateWritableString -- Creates storage for a string literal.
1758 static llvm::Constant *GenerateStringLiteral(const std::string &str,
1759                                              bool constant,
1760                                              CodeGenModule &CGM,
1761                                              const char *GlobalName) {
1762   // Create Constant for this string literal. Don't add a '\0'.
1763   llvm::Constant *C =
1764       llvm::ConstantArray::get(CGM.getLLVMContext(), str, false);
1765 
1766   // Create a global variable for this string
1767   return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1768                                   llvm::GlobalValue::PrivateLinkage,
1769                                   C, GlobalName);
1770 }
1771 
1772 /// GetAddrOfConstantString - Returns a pointer to a character array
1773 /// containing the literal. This contents are exactly that of the
1774 /// given string, i.e. it will not be null terminated automatically;
1775 /// see GetAddrOfConstantCString. Note that whether the result is
1776 /// actually a pointer to an LLVM constant depends on
1777 /// Feature.WriteableStrings.
1778 ///
1779 /// The result has pointer to array type.
1780 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1781                                                        const char *GlobalName) {
1782   bool IsConstant = !Features.WritableStrings;
1783 
1784   // Get the default prefix if a name wasn't specified.
1785   if (!GlobalName)
1786     GlobalName = ".str";
1787 
1788   // Don't share any string literals if strings aren't constant.
1789   if (!IsConstant)
1790     return GenerateStringLiteral(str, false, *this, GlobalName);
1791 
1792   llvm::StringMapEntry<llvm::Constant *> &Entry =
1793     ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1794 
1795   if (Entry.getValue())
1796     return Entry.getValue();
1797 
1798   // Create a global variable for this.
1799   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1800   Entry.setValue(C);
1801   return C;
1802 }
1803 
1804 /// GetAddrOfConstantCString - Returns a pointer to a character
1805 /// array containing the literal and a terminating '\-'
1806 /// character. The result has pointer to array type.
1807 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1808                                                         const char *GlobalName){
1809   return GetAddrOfConstantString(str + '\0', GlobalName);
1810 }
1811 
1812 /// EmitObjCPropertyImplementations - Emit information for synthesized
1813 /// properties for an implementation.
1814 void CodeGenModule::EmitObjCPropertyImplementations(const
1815                                                     ObjCImplementationDecl *D) {
1816   for (ObjCImplementationDecl::propimpl_iterator
1817          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1818     ObjCPropertyImplDecl *PID = *i;
1819 
1820     // Dynamic is just for type-checking.
1821     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1822       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1823 
1824       // Determine which methods need to be implemented, some may have
1825       // been overridden. Note that ::isSynthesized is not the method
1826       // we want, that just indicates if the decl came from a
1827       // property. What we want to know is if the method is defined in
1828       // this implementation.
1829       if (!D->getInstanceMethod(PD->getGetterName()))
1830         CodeGenFunction(*this).GenerateObjCGetter(
1831                                  const_cast<ObjCImplementationDecl *>(D), PID);
1832       if (!PD->isReadOnly() &&
1833           !D->getInstanceMethod(PD->getSetterName()))
1834         CodeGenFunction(*this).GenerateObjCSetter(
1835                                  const_cast<ObjCImplementationDecl *>(D), PID);
1836     }
1837   }
1838 }
1839 
1840 /// EmitObjCIvarInitializations - Emit information for ivar initialization
1841 /// for an implementation.
1842 void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
1843   if (!Features.NeXTRuntime || D->getNumIvarInitializers() == 0)
1844     return;
1845   DeclContext* DC = const_cast<DeclContext*>(dyn_cast<DeclContext>(D));
1846   assert(DC && "EmitObjCIvarInitializations - null DeclContext");
1847   IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
1848   Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
1849   ObjCMethodDecl *DTORMethod = ObjCMethodDecl::Create(getContext(),
1850                                                   D->getLocation(),
1851                                                   D->getLocation(), cxxSelector,
1852                                                   getContext().VoidTy, 0,
1853                                                   DC, true, false, true,
1854                                                   ObjCMethodDecl::Required);
1855   D->addInstanceMethod(DTORMethod);
1856   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
1857 
1858   II = &getContext().Idents.get(".cxx_construct");
1859   cxxSelector = getContext().Selectors.getSelector(0, &II);
1860   // The constructor returns 'self'.
1861   ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
1862                                                 D->getLocation(),
1863                                                 D->getLocation(), cxxSelector,
1864                                                 getContext().getObjCIdType(), 0,
1865                                                 DC, true, false, true,
1866                                                 ObjCMethodDecl::Required);
1867   D->addInstanceMethod(CTORMethod);
1868   CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
1869 
1870 
1871 }
1872 
1873 /// EmitNamespace - Emit all declarations in a namespace.
1874 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1875   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1876        I != E; ++I)
1877     EmitTopLevelDecl(*I);
1878 }
1879 
1880 // EmitLinkageSpec - Emit all declarations in a linkage spec.
1881 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1882   if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
1883       LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
1884     ErrorUnsupported(LSD, "linkage spec");
1885     return;
1886   }
1887 
1888   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1889        I != E; ++I)
1890     EmitTopLevelDecl(*I);
1891 }
1892 
1893 /// EmitTopLevelDecl - Emit code for a single top level declaration.
1894 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1895   // If an error has occurred, stop code generation, but continue
1896   // parsing and semantic analysis (to ensure all warnings and errors
1897   // are emitted).
1898   if (Diags.hasErrorOccurred())
1899     return;
1900 
1901   // Ignore dependent declarations.
1902   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1903     return;
1904 
1905   switch (D->getKind()) {
1906   case Decl::CXXConversion:
1907   case Decl::CXXMethod:
1908   case Decl::Function:
1909     // Skip function templates
1910     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1911       return;
1912 
1913     EmitGlobal(cast<FunctionDecl>(D));
1914     break;
1915 
1916   case Decl::Var:
1917     EmitGlobal(cast<VarDecl>(D));
1918     break;
1919 
1920   // C++ Decls
1921   case Decl::Namespace:
1922     EmitNamespace(cast<NamespaceDecl>(D));
1923     break;
1924     // No code generation needed.
1925   case Decl::UsingShadow:
1926   case Decl::Using:
1927   case Decl::UsingDirective:
1928   case Decl::ClassTemplate:
1929   case Decl::FunctionTemplate:
1930   case Decl::NamespaceAlias:
1931     break;
1932   case Decl::CXXConstructor:
1933     // Skip function templates
1934     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1935       return;
1936 
1937     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1938     break;
1939   case Decl::CXXDestructor:
1940     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1941     break;
1942 
1943   case Decl::StaticAssert:
1944     // Nothing to do.
1945     break;
1946 
1947   // Objective-C Decls
1948 
1949   // Forward declarations, no (immediate) code generation.
1950   case Decl::ObjCClass:
1951   case Decl::ObjCForwardProtocol:
1952   case Decl::ObjCCategory:
1953   case Decl::ObjCInterface:
1954     break;
1955 
1956   case Decl::ObjCProtocol:
1957     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1958     break;
1959 
1960   case Decl::ObjCCategoryImpl:
1961     // Categories have properties but don't support synthesize so we
1962     // can ignore them here.
1963     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1964     break;
1965 
1966   case Decl::ObjCImplementation: {
1967     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1968     EmitObjCPropertyImplementations(OMD);
1969     EmitObjCIvarInitializations(OMD);
1970     Runtime->GenerateClass(OMD);
1971     break;
1972   }
1973   case Decl::ObjCMethod: {
1974     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1975     // If this is not a prototype, emit the body.
1976     if (OMD->getBody())
1977       CodeGenFunction(*this).GenerateObjCMethod(OMD);
1978     break;
1979   }
1980   case Decl::ObjCCompatibleAlias:
1981     // compatibility-alias is a directive and has no code gen.
1982     break;
1983 
1984   case Decl::LinkageSpec:
1985     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
1986     break;
1987 
1988   case Decl::FileScopeAsm: {
1989     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1990     llvm::StringRef AsmString = AD->getAsmString()->getString();
1991 
1992     const std::string &S = getModule().getModuleInlineAsm();
1993     if (S.empty())
1994       getModule().setModuleInlineAsm(AsmString);
1995     else
1996       getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
1997     break;
1998   }
1999 
2000   default:
2001     // Make sure we handled everything we should, every other kind is a
2002     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
2003     // function. Need to recode Decl::Kind to do that easily.
2004     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2005   }
2006 }
2007