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 "clang/Frontend/CompileOptions.h"
21 #include "clang/AST/ASTContext.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/Basic/Builtins.h"
25 #include "clang/Basic/Diagnostic.h"
26 #include "clang/Basic/SourceManager.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Basic/ConvertUTF.h"
29 #include "llvm/CallingConv.h"
30 #include "llvm/Module.h"
31 #include "llvm/Intrinsics.h"
32 #include "llvm/Target/TargetData.h"
33 using namespace clang;
34 using namespace CodeGen;
35 
36 
37 CodeGenModule::CodeGenModule(ASTContext &C, const CompileOptions &compileOpts,
38                              llvm::Module &M, const llvm::TargetData &TD,
39                              Diagnostic &diags)
40   : BlockModule(C, M, TD, Types, *this), Context(C),
41     Features(C.getLangOptions()), CompileOpts(compileOpts), TheModule(M),
42     TheTargetData(TD), Diags(diags), Types(C, M, TD), Runtime(0),
43     MemCpyFn(0), MemMoveFn(0), MemSetFn(0), CFConstantStringClassRef(0),
44     VMContext(M.getContext()) {
45 
46   if (!Features.ObjC1)
47     Runtime = 0;
48   else if (!Features.NeXTRuntime)
49     Runtime = CreateGNUObjCRuntime(*this);
50   else if (Features.ObjCNonFragileABI)
51     Runtime = CreateMacNonFragileABIObjCRuntime(*this);
52   else
53     Runtime = CreateMacObjCRuntime(*this);
54 
55   // If debug info generation is enabled, create the CGDebugInfo object.
56   DebugInfo = CompileOpts.DebugInfo ? new CGDebugInfo(this) : 0;
57 }
58 
59 CodeGenModule::~CodeGenModule() {
60   delete Runtime;
61   delete DebugInfo;
62 }
63 
64 void CodeGenModule::Release() {
65   EmitDeferred();
66   if (Runtime)
67     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
68       AddGlobalCtor(ObjCInitFunction);
69   EmitCtorList(GlobalCtors, "llvm.global_ctors");
70   EmitCtorList(GlobalDtors, "llvm.global_dtors");
71   EmitAnnotations();
72   EmitLLVMUsed();
73 }
74 
75 /// ErrorUnsupported - Print out an error that codegen doesn't support the
76 /// specified stmt yet.
77 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
78                                      bool OmitOnError) {
79   if (OmitOnError && getDiags().hasErrorOccurred())
80     return;
81   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
82                                                "cannot compile this %0 yet");
83   std::string Msg = Type;
84   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
85     << Msg << S->getSourceRange();
86 }
87 
88 /// ErrorUnsupported - Print out an error that codegen doesn't support the
89 /// specified decl yet.
90 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
91                                      bool OmitOnError) {
92   if (OmitOnError && getDiags().hasErrorOccurred())
93     return;
94   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
95                                                "cannot compile this %0 yet");
96   std::string Msg = Type;
97   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
98 }
99 
100 LangOptions::VisibilityMode
101 CodeGenModule::getDeclVisibilityMode(const Decl *D) const {
102   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
103     if (VD->getStorageClass() == VarDecl::PrivateExtern)
104       return LangOptions::Hidden;
105 
106   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>()) {
107     switch (attr->getVisibility()) {
108     default: assert(0 && "Unknown visibility!");
109     case VisibilityAttr::DefaultVisibility:
110       return LangOptions::Default;
111     case VisibilityAttr::HiddenVisibility:
112       return LangOptions::Hidden;
113     case VisibilityAttr::ProtectedVisibility:
114       return LangOptions::Protected;
115     }
116   }
117 
118   return getLangOptions().getVisibilityMode();
119 }
120 
121 void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
122                                         const Decl *D) const {
123   // Internal definitions always have default visibility.
124   if (GV->hasLocalLinkage()) {
125     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
126     return;
127   }
128 
129   switch (getDeclVisibilityMode(D)) {
130   default: assert(0 && "Unknown visibility!");
131   case LangOptions::Default:
132     return GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
133   case LangOptions::Hidden:
134     return GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
135   case LangOptions::Protected:
136     return GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
137   }
138 }
139 
140 const char *CodeGenModule::getMangledName(const GlobalDecl &GD) {
141   const NamedDecl *ND = GD.getDecl();
142 
143   if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
144     return getMangledCXXCtorName(D, GD.getCtorType());
145   if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
146     return getMangledCXXDtorName(D, GD.getDtorType());
147 
148   return getMangledName(ND);
149 }
150 
151 /// \brief Retrieves the mangled name for the given declaration.
152 ///
153 /// If the given declaration requires a mangled name, returns an
154 /// const char* containing the mangled name.  Otherwise, returns
155 /// the unmangled name.
156 ///
157 const char *CodeGenModule::getMangledName(const NamedDecl *ND) {
158   // In C, functions with no attributes never need to be mangled. Fastpath them.
159   if (!getLangOptions().CPlusPlus && !ND->hasAttrs()) {
160     assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
161     return ND->getNameAsCString();
162   }
163 
164   llvm::SmallString<256> Name;
165   llvm::raw_svector_ostream Out(Name);
166   if (!mangleName(ND, Context, Out)) {
167     assert(ND->getIdentifier() && "Attempt to mangle unnamed decl.");
168     return ND->getNameAsCString();
169   }
170 
171   Name += '\0';
172   return UniqueMangledName(Name.begin(), Name.end());
173 }
174 
175 const char *CodeGenModule::UniqueMangledName(const char *NameStart,
176                                              const char *NameEnd) {
177   assert(*(NameEnd - 1) == '\0' && "Mangled name must be null terminated!");
178 
179   return MangledNames.GetOrCreateValue(NameStart, NameEnd).getKeyData();
180 }
181 
182 /// AddGlobalCtor - Add a function to the list that will be called before
183 /// main() runs.
184 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
185   // FIXME: Type coercion of void()* types.
186   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
187 }
188 
189 /// AddGlobalDtor - Add a function to the list that will be called
190 /// when the module is unloaded.
191 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
192   // FIXME: Type coercion of void()* types.
193   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
194 }
195 
196 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
197   // Ctor function type is void()*.
198   llvm::FunctionType* CtorFTy =
199     VMContext.getFunctionType(llvm::Type::VoidTy,
200                             std::vector<const llvm::Type*>(),
201                             false);
202   llvm::Type *CtorPFTy = VMContext.getPointerTypeUnqual(CtorFTy);
203 
204   // Get the type of a ctor entry, { i32, void ()* }.
205   llvm::StructType* CtorStructTy =
206     VMContext.getStructType(llvm::Type::Int32Ty,
207                           VMContext.getPointerTypeUnqual(CtorFTy), NULL);
208 
209   // Construct the constructor and destructor arrays.
210   std::vector<llvm::Constant*> Ctors;
211   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
212     std::vector<llvm::Constant*> S;
213     S.push_back(
214       VMContext.getConstantInt(llvm::Type::Int32Ty, I->second, false));
215     S.push_back(VMContext.getConstantExprBitCast(I->first, CtorPFTy));
216     Ctors.push_back(VMContext.getConstantStruct(CtorStructTy, S));
217   }
218 
219   if (!Ctors.empty()) {
220     llvm::ArrayType *AT = VMContext.getArrayType(CtorStructTy, Ctors.size());
221     new llvm::GlobalVariable(TheModule, AT, false,
222                              llvm::GlobalValue::AppendingLinkage,
223                              VMContext.getConstantArray(AT, Ctors),
224                              GlobalName);
225   }
226 }
227 
228 void CodeGenModule::EmitAnnotations() {
229   if (Annotations.empty())
230     return;
231 
232   // Create a new global variable for the ConstantStruct in the Module.
233   llvm::Constant *Array =
234   VMContext.getConstantArray(VMContext.getArrayType(Annotations[0]->getType(),
235                                                 Annotations.size()),
236                            Annotations);
237   llvm::GlobalValue *gv =
238   new llvm::GlobalVariable(TheModule, Array->getType(), false,
239                            llvm::GlobalValue::AppendingLinkage, Array,
240                            "llvm.global.annotations");
241   gv->setSection("llvm.metadata");
242 }
243 
244 static CodeGenModule::GVALinkage
245 GetLinkageForFunction(ASTContext &Context, const FunctionDecl *FD,
246                       const LangOptions &Features) {
247   // The kind of external linkage this function will have, if it is not
248   // inline or static.
249   CodeGenModule::GVALinkage External = CodeGenModule::GVA_StrongExternal;
250   if (Context.getLangOptions().CPlusPlus &&
251       (FD->getPrimaryTemplate() || FD->getInstantiatedFromMemberFunction()) &&
252       !FD->isExplicitSpecialization())
253     External = CodeGenModule::GVA_TemplateInstantiation;
254 
255   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
256     // C++ member functions defined inside the class are always inline.
257     if (MD->isInline() || !MD->isOutOfLine())
258       return CodeGenModule::GVA_CXXInline;
259 
260     return External;
261   }
262 
263   // "static" functions get internal linkage.
264   if (FD->getStorageClass() == FunctionDecl::Static)
265     return CodeGenModule::GVA_Internal;
266 
267   if (!FD->isInline())
268     return External;
269 
270   // If the inline function explicitly has the GNU inline attribute on it, or if
271   // this is C89 mode, we use to GNU semantics.
272   if (!Features.C99 && !Features.CPlusPlus) {
273     // extern inline in GNU mode is like C99 inline.
274     if (FD->getStorageClass() == FunctionDecl::Extern)
275       return CodeGenModule::GVA_C99Inline;
276     // Normal inline is a strong symbol.
277     return CodeGenModule::GVA_StrongExternal;
278   } else if (FD->hasActiveGNUInlineAttribute(Context)) {
279     // GCC in C99 mode seems to use a different decision-making
280     // process for extern inline, which factors in previous
281     // declarations.
282     if (FD->isExternGNUInline(Context))
283       return CodeGenModule::GVA_C99Inline;
284     // Normal inline is a strong symbol.
285     return External;
286   }
287 
288   // The definition of inline changes based on the language.  Note that we
289   // have already handled "static inline" above, with the GVA_Internal case.
290   if (Features.CPlusPlus)  // inline and extern inline.
291     return CodeGenModule::GVA_CXXInline;
292 
293   assert(Features.C99 && "Must be in C99 mode if not in C89 or C++ mode");
294   if (FD->isC99InlineDefinition())
295     return CodeGenModule::GVA_C99Inline;
296 
297   return CodeGenModule::GVA_StrongExternal;
298 }
299 
300 /// SetFunctionDefinitionAttributes - Set attributes for a global.
301 ///
302 /// FIXME: This is currently only done for aliases and functions, but not for
303 /// variables (these details are set in EmitGlobalVarDefinition for variables).
304 void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
305                                                     llvm::GlobalValue *GV) {
306   GVALinkage Linkage = GetLinkageForFunction(getContext(), D, Features);
307 
308   if (Linkage == GVA_Internal) {
309     GV->setLinkage(llvm::Function::InternalLinkage);
310   } else if (D->hasAttr<DLLExportAttr>()) {
311     GV->setLinkage(llvm::Function::DLLExportLinkage);
312   } else if (D->hasAttr<WeakAttr>()) {
313     GV->setLinkage(llvm::Function::WeakAnyLinkage);
314   } else if (Linkage == GVA_C99Inline) {
315     // In C99 mode, 'inline' functions are guaranteed to have a strong
316     // definition somewhere else, so we can use available_externally linkage.
317     GV->setLinkage(llvm::Function::AvailableExternallyLinkage);
318   } else if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) {
319     // In C++, the compiler has to emit a definition in every translation unit
320     // that references the function.  We should use linkonce_odr because
321     // a) if all references in this translation unit are optimized away, we
322     // don't need to codegen it.  b) if the function persists, it needs to be
323     // merged with other definitions. c) C++ has the ODR, so we know the
324     // definition is dependable.
325     GV->setLinkage(llvm::Function::LinkOnceODRLinkage);
326   } else {
327     assert(Linkage == GVA_StrongExternal);
328     // Otherwise, we have strong external linkage.
329     GV->setLinkage(llvm::Function::ExternalLinkage);
330   }
331 
332   SetCommonAttributes(D, GV);
333 }
334 
335 void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
336                                               const CGFunctionInfo &Info,
337                                               llvm::Function *F) {
338   AttributeListType AttributeList;
339   ConstructAttributeList(Info, D, AttributeList);
340 
341   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
342                                         AttributeList.size()));
343 
344   // Set the appropriate calling convention for the Function.
345   if (D->hasAttr<FastCallAttr>())
346     F->setCallingConv(llvm::CallingConv::X86_FastCall);
347 
348   if (D->hasAttr<StdCallAttr>())
349     F->setCallingConv(llvm::CallingConv::X86_StdCall);
350 }
351 
352 void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
353                                                            llvm::Function *F) {
354   if (!Features.Exceptions && !Features.ObjCNonFragileABI)
355     F->addFnAttr(llvm::Attribute::NoUnwind);
356 
357   if (D->hasAttr<AlwaysInlineAttr>())
358     F->addFnAttr(llvm::Attribute::AlwaysInline);
359 
360   if (D->hasAttr<NoinlineAttr>())
361     F->addFnAttr(llvm::Attribute::NoInline);
362 }
363 
364 void CodeGenModule::SetCommonAttributes(const Decl *D,
365                                         llvm::GlobalValue *GV) {
366   setGlobalVisibility(GV, D);
367 
368   if (D->hasAttr<UsedAttr>())
369     AddUsedGlobal(GV);
370 
371   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
372     GV->setSection(SA->getName());
373 }
374 
375 void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
376                                                   llvm::Function *F,
377                                                   const CGFunctionInfo &FI) {
378   SetLLVMFunctionAttributes(D, FI, F);
379   SetLLVMFunctionAttributesForDefinition(D, F);
380 
381   F->setLinkage(llvm::Function::InternalLinkage);
382 
383   SetCommonAttributes(D, F);
384 }
385 
386 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
387                                           llvm::Function *F,
388                                           bool IsIncompleteFunction) {
389   if (!IsIncompleteFunction)
390     SetLLVMFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
391 
392   // Only a few attributes are set on declarations; these may later be
393   // overridden by a definition.
394 
395   if (FD->hasAttr<DLLImportAttr>()) {
396     F->setLinkage(llvm::Function::DLLImportLinkage);
397   } else if (FD->hasAttr<WeakAttr>() ||
398              FD->hasAttr<WeakImportAttr>()) {
399     // "extern_weak" is overloaded in LLVM; we probably should have
400     // separate linkage types for this.
401     F->setLinkage(llvm::Function::ExternalWeakLinkage);
402   } else {
403     F->setLinkage(llvm::Function::ExternalLinkage);
404   }
405 
406   if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
407     F->setSection(SA->getName());
408 }
409 
410 void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
411   assert(!GV->isDeclaration() &&
412          "Only globals with definition can force usage.");
413   LLVMUsed.push_back(GV);
414 }
415 
416 void CodeGenModule::EmitLLVMUsed() {
417   // Don't create llvm.used if there is no need.
418   // FIXME. Runtime indicates that there might be more 'used' symbols; but not
419   // necessariy. So, this test is not accurate for emptiness.
420   if (LLVMUsed.empty() && !Runtime)
421     return;
422 
423   llvm::Type *i8PTy = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
424 
425   // Convert LLVMUsed to what ConstantArray needs.
426   std::vector<llvm::Constant*> UsedArray;
427   UsedArray.resize(LLVMUsed.size());
428   for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
429     UsedArray[i] =
430      VMContext.getConstantExprBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
431                                       i8PTy);
432   }
433 
434   if (Runtime)
435     Runtime->MergeMetadataGlobals(UsedArray);
436   if (UsedArray.empty())
437     return;
438   llvm::ArrayType *ATy = VMContext.getArrayType(i8PTy, UsedArray.size());
439 
440   llvm::GlobalVariable *GV =
441     new llvm::GlobalVariable(getModule(), ATy, false,
442                              llvm::GlobalValue::AppendingLinkage,
443                              VMContext.getConstantArray(ATy, UsedArray),
444                              "llvm.used");
445 
446   GV->setSection("llvm.metadata");
447 }
448 
449 void CodeGenModule::EmitDeferred() {
450   // Emit code for any potentially referenced deferred decls.  Since a
451   // previously unused static decl may become used during the generation of code
452   // for a static function, iterate until no  changes are made.
453   while (!DeferredDeclsToEmit.empty()) {
454     GlobalDecl D = DeferredDeclsToEmit.back();
455     DeferredDeclsToEmit.pop_back();
456 
457     // The mangled name for the decl must have been emitted in GlobalDeclMap.
458     // Look it up to see if it was defined with a stronger definition (e.g. an
459     // extern inline function with a strong function redefinition).  If so,
460     // just ignore the deferred decl.
461     llvm::GlobalValue *CGRef = GlobalDeclMap[getMangledName(D)];
462     assert(CGRef && "Deferred decl wasn't referenced?");
463 
464     if (!CGRef->isDeclaration())
465       continue;
466 
467     // Otherwise, emit the definition and move on to the next one.
468     EmitGlobalDefinition(D);
469   }
470 }
471 
472 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
473 /// annotation information for a given GlobalValue.  The annotation struct is
474 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
475 /// GlobalValue being annotated.  The second field is the constant string
476 /// created from the AnnotateAttr's annotation.  The third field is a constant
477 /// string containing the name of the translation unit.  The fourth field is
478 /// the line number in the file of the annotated value declaration.
479 ///
480 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
481 ///        appears to.
482 ///
483 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
484                                                 const AnnotateAttr *AA,
485                                                 unsigned LineNo) {
486   llvm::Module *M = &getModule();
487 
488   // get [N x i8] constants for the annotation string, and the filename string
489   // which are the 2nd and 3rd elements of the global annotation structure.
490   const llvm::Type *SBP = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
491   llvm::Constant *anno = VMContext.getConstantArray(AA->getAnnotation(), true);
492   llvm::Constant *unit = VMContext.getConstantArray(M->getModuleIdentifier(),
493                                                   true);
494 
495   // Get the two global values corresponding to the ConstantArrays we just
496   // created to hold the bytes of the strings.
497   const char *StringPrefix = getContext().Target.getStringSymbolPrefix(true);
498   llvm::GlobalValue *annoGV =
499   new llvm::GlobalVariable(*M, anno->getType(), false,
500                            llvm::GlobalValue::InternalLinkage, anno,
501                            GV->getName() + StringPrefix);
502   // translation unit name string, emitted into the llvm.metadata section.
503   llvm::GlobalValue *unitGV =
504   new llvm::GlobalVariable(*M, unit->getType(), false,
505                            llvm::GlobalValue::InternalLinkage, unit,
506                            StringPrefix);
507 
508   // Create the ConstantStruct for the global annotation.
509   llvm::Constant *Fields[4] = {
510     VMContext.getConstantExprBitCast(GV, SBP),
511     VMContext.getConstantExprBitCast(annoGV, SBP),
512     VMContext.getConstantExprBitCast(unitGV, SBP),
513     VMContext.getConstantInt(llvm::Type::Int32Ty, LineNo)
514   };
515   return VMContext.getConstantStruct(Fields, 4, false);
516 }
517 
518 bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
519   // Never defer when EmitAllDecls is specified or the decl has
520   // attribute used.
521   if (Features.EmitAllDecls || Global->hasAttr<UsedAttr>())
522     return false;
523 
524   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
525     // Constructors and destructors should never be deferred.
526     if (FD->hasAttr<ConstructorAttr>() ||
527         FD->hasAttr<DestructorAttr>())
528       return false;
529 
530     GVALinkage Linkage = GetLinkageForFunction(getContext(), FD, Features);
531 
532     // static, static inline, always_inline, and extern inline functions can
533     // always be deferred.  Normal inline functions can be deferred in C99/C++.
534     if (Linkage == GVA_Internal || Linkage == GVA_C99Inline ||
535         Linkage == GVA_CXXInline)
536       return true;
537     return false;
538   }
539 
540   const VarDecl *VD = cast<VarDecl>(Global);
541   assert(VD->isFileVarDecl() && "Invalid decl");
542 
543   return VD->getStorageClass() == VarDecl::Static;
544 }
545 
546 void CodeGenModule::EmitGlobal(GlobalDecl GD) {
547   const ValueDecl *Global = GD.getDecl();
548 
549   // If this is an alias definition (which otherwise looks like a declaration)
550   // emit it now.
551   if (Global->hasAttr<AliasAttr>())
552     return EmitAliasDefinition(Global);
553 
554   // Ignore declarations, they will be emitted on their first use.
555   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
556     // Forward declarations are emitted lazily on first use.
557     if (!FD->isThisDeclarationADefinition())
558       return;
559   } else {
560     const VarDecl *VD = cast<VarDecl>(Global);
561     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
562 
563     // In C++, if this is marked "extern", defer code generation.
564     if (getLangOptions().CPlusPlus && !VD->getInit() &&
565         (VD->getStorageClass() == VarDecl::Extern ||
566          VD->isExternC(getContext())))
567       return;
568 
569     // In C, if this isn't a definition, defer code generation.
570     if (!getLangOptions().CPlusPlus && !VD->getInit())
571       return;
572   }
573 
574   // Defer code generation when possible if this is a static definition, inline
575   // function etc.  These we only want to emit if they are used.
576   if (MayDeferGeneration(Global)) {
577     // If the value has already been used, add it directly to the
578     // DeferredDeclsToEmit list.
579     const char *MangledName = getMangledName(GD);
580     if (GlobalDeclMap.count(MangledName))
581       DeferredDeclsToEmit.push_back(GD);
582     else {
583       // Otherwise, remember that we saw a deferred decl with this name.  The
584       // first use of the mangled name will cause it to move into
585       // DeferredDeclsToEmit.
586       DeferredDecls[MangledName] = GD;
587     }
588     return;
589   }
590 
591   // Otherwise emit the definition.
592   EmitGlobalDefinition(GD);
593 }
594 
595 void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
596   const ValueDecl *D = GD.getDecl();
597 
598   if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
599     EmitCXXConstructor(CD, GD.getCtorType());
600   else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
601     EmitCXXDestructor(DD, GD.getDtorType());
602   else if (isa<FunctionDecl>(D))
603     EmitGlobalFunctionDefinition(GD);
604   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
605     EmitGlobalVarDefinition(VD);
606   else {
607     assert(0 && "Invalid argument to EmitGlobalDefinition()");
608   }
609 }
610 
611 /// GetOrCreateLLVMFunction - If the specified mangled name is not in the
612 /// module, create and return an llvm Function with the specified type. If there
613 /// is something in the module with the specified name, return it potentially
614 /// bitcasted to the right type.
615 ///
616 /// If D is non-null, it specifies a decl that correspond to this.  This is used
617 /// to set the attributes on the function when it is first created.
618 llvm::Constant *CodeGenModule::GetOrCreateLLVMFunction(const char *MangledName,
619                                                        const llvm::Type *Ty,
620                                                        GlobalDecl D) {
621   // Lookup the entry, lazily creating it if necessary.
622   llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
623   if (Entry) {
624     if (Entry->getType()->getElementType() == Ty)
625       return Entry;
626 
627     // Make sure the result is of the correct type.
628     const llvm::Type *PTy = VMContext.getPointerTypeUnqual(Ty);
629     return VMContext.getConstantExprBitCast(Entry, PTy);
630   }
631 
632   // This is the first use or definition of a mangled name.  If there is a
633   // deferred decl with this name, remember that we need to emit it at the end
634   // of the file.
635   llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
636     DeferredDecls.find(MangledName);
637   if (DDI != DeferredDecls.end()) {
638     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
639     // list, and remove it from DeferredDecls (since we don't need it anymore).
640     DeferredDeclsToEmit.push_back(DDI->second);
641     DeferredDecls.erase(DDI);
642   } else if (const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl())) {
643     // If this the first reference to a C++ inline function in a class, queue up
644     // the deferred function body for emission.  These are not seen as
645     // top-level declarations.
646     if (FD->isThisDeclarationADefinition() && MayDeferGeneration(FD))
647       DeferredDeclsToEmit.push_back(D);
648   }
649 
650   // This function doesn't have a complete type (for example, the return
651   // type is an incomplete struct). Use a fake type instead, and make
652   // sure not to try to set attributes.
653   bool IsIncompleteFunction = false;
654   if (!isa<llvm::FunctionType>(Ty)) {
655     Ty = VMContext.getFunctionType(llvm::Type::VoidTy,
656                                  std::vector<const llvm::Type*>(), false);
657     IsIncompleteFunction = true;
658   }
659   llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
660                                              llvm::Function::ExternalLinkage,
661                                              "", &getModule());
662   F->setName(MangledName);
663   if (D.getDecl())
664     SetFunctionAttributes(cast<FunctionDecl>(D.getDecl()), F,
665                           IsIncompleteFunction);
666   Entry = F;
667   return F;
668 }
669 
670 /// GetAddrOfFunction - Return the address of the given function.  If Ty is
671 /// non-null, then this function will use the specified type if it has to
672 /// create it (this occurs when we see a definition of the function).
673 llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
674                                                  const llvm::Type *Ty) {
675   // If there was no specific requested type, just convert it now.
676   if (!Ty)
677     Ty = getTypes().ConvertType(GD.getDecl()->getType());
678   return GetOrCreateLLVMFunction(getMangledName(GD.getDecl()), Ty, GD);
679 }
680 
681 /// CreateRuntimeFunction - Create a new runtime function with the specified
682 /// type and name.
683 llvm::Constant *
684 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
685                                      const char *Name) {
686   // Convert Name to be a uniqued string from the IdentifierInfo table.
687   Name = getContext().Idents.get(Name).getName();
688   return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl());
689 }
690 
691 /// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
692 /// create and return an llvm GlobalVariable with the specified type.  If there
693 /// is something in the module with the specified name, return it potentially
694 /// bitcasted to the right type.
695 ///
696 /// If D is non-null, it specifies a decl that correspond to this.  This is used
697 /// to set the attributes on the global when it is first created.
698 llvm::Constant *CodeGenModule::GetOrCreateLLVMGlobal(const char *MangledName,
699                                                      const llvm::PointerType*Ty,
700                                                      const VarDecl *D) {
701   // Lookup the entry, lazily creating it if necessary.
702   llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
703   if (Entry) {
704     if (Entry->getType() == Ty)
705       return Entry;
706 
707     // Make sure the result is of the correct type.
708     return VMContext.getConstantExprBitCast(Entry, Ty);
709   }
710 
711   // This is the first use or definition of a mangled name.  If there is a
712   // deferred decl with this name, remember that we need to emit it at the end
713   // of the file.
714   llvm::DenseMap<const char*, GlobalDecl>::iterator DDI =
715     DeferredDecls.find(MangledName);
716   if (DDI != DeferredDecls.end()) {
717     // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
718     // list, and remove it from DeferredDecls (since we don't need it anymore).
719     DeferredDeclsToEmit.push_back(DDI->second);
720     DeferredDecls.erase(DDI);
721   }
722 
723   llvm::GlobalVariable *GV =
724     new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
725                              llvm::GlobalValue::ExternalLinkage,
726                              0, "", 0,
727                              false, Ty->getAddressSpace());
728   GV->setName(MangledName);
729 
730   // Handle things which are present even on external declarations.
731   if (D) {
732     // FIXME: This code is overly simple and should be merged with other global
733     // handling.
734     GV->setConstant(D->getType().isConstant(Context));
735 
736     // FIXME: Merge with other attribute handling code.
737     if (D->getStorageClass() == VarDecl::PrivateExtern)
738       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
739 
740     if (D->hasAttr<WeakAttr>() ||
741         D->hasAttr<WeakImportAttr>())
742       GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
743 
744     GV->setThreadLocal(D->isThreadSpecified());
745   }
746 
747   return Entry = GV;
748 }
749 
750 
751 /// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
752 /// given global variable.  If Ty is non-null and if the global doesn't exist,
753 /// then it will be greated with the specified type instead of whatever the
754 /// normal requested type would be.
755 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
756                                                   const llvm::Type *Ty) {
757   assert(D->hasGlobalStorage() && "Not a global variable");
758   QualType ASTTy = D->getType();
759   if (Ty == 0)
760     Ty = getTypes().ConvertTypeForMem(ASTTy);
761 
762   const llvm::PointerType *PTy =
763     VMContext.getPointerType(Ty, ASTTy.getAddressSpace());
764   return GetOrCreateLLVMGlobal(getMangledName(D), PTy, D);
765 }
766 
767 /// CreateRuntimeVariable - Create a new runtime global variable with the
768 /// specified type and name.
769 llvm::Constant *
770 CodeGenModule::CreateRuntimeVariable(const llvm::Type *Ty,
771                                      const char *Name) {
772   // Convert Name to be a uniqued string from the IdentifierInfo table.
773   Name = getContext().Idents.get(Name).getName();
774   return GetOrCreateLLVMGlobal(Name, VMContext.getPointerTypeUnqual(Ty), 0);
775 }
776 
777 void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
778   assert(!D->getInit() && "Cannot emit definite definitions here!");
779 
780   if (MayDeferGeneration(D)) {
781     // If we have not seen a reference to this variable yet, place it
782     // into the deferred declarations table to be emitted if needed
783     // later.
784     const char *MangledName = getMangledName(D);
785     if (GlobalDeclMap.count(MangledName) == 0) {
786       DeferredDecls[MangledName] = GlobalDecl(D);
787       return;
788     }
789   }
790 
791   // The tentative definition is the only definition.
792   EmitGlobalVarDefinition(D);
793 }
794 
795 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
796   llvm::Constant *Init = 0;
797   QualType ASTTy = D->getType();
798 
799   if (D->getInit() == 0) {
800     // This is a tentative definition; tentative definitions are
801     // implicitly initialized with { 0 }.
802     //
803     // Note that tentative definitions are only emitted at the end of
804     // a translation unit, so they should never have incomplete
805     // type. In addition, EmitTentativeDefinition makes sure that we
806     // never attempt to emit a tentative definition if a real one
807     // exists. A use may still exists, however, so we still may need
808     // to do a RAUW.
809     assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
810     Init = getLLVMContext().getNullValue(getTypes().ConvertTypeForMem(ASTTy));
811   } else {
812     Init = EmitConstantExpr(D->getInit(), D->getType());
813     if (!Init) {
814       ErrorUnsupported(D, "static initializer");
815       QualType T = D->getInit()->getType();
816       Init = VMContext.getUndef(getTypes().ConvertType(T));
817     }
818   }
819 
820   const llvm::Type* InitType = Init->getType();
821   llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
822 
823   // Strip off a bitcast if we got one back.
824   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
825     assert(CE->getOpcode() == llvm::Instruction::BitCast);
826     Entry = CE->getOperand(0);
827   }
828 
829   // Entry is now either a Function or GlobalVariable.
830   llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
831 
832   // We have a definition after a declaration with the wrong type.
833   // We must make a new GlobalVariable* and update everything that used OldGV
834   // (a declaration or tentative definition) with the new GlobalVariable*
835   // (which will be a definition).
836   //
837   // This happens if there is a prototype for a global (e.g.
838   // "extern int x[];") and then a definition of a different type (e.g.
839   // "int x[10];"). This also happens when an initializer has a different type
840   // from the type of the global (this happens with unions).
841   if (GV == 0 ||
842       GV->getType()->getElementType() != InitType ||
843       GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
844 
845     // Remove the old entry from GlobalDeclMap so that we'll create a new one.
846     GlobalDeclMap.erase(getMangledName(D));
847 
848     // Make a new global with the correct type, this is now guaranteed to work.
849     GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
850     GV->takeName(cast<llvm::GlobalValue>(Entry));
851 
852     // Replace all uses of the old global with the new global
853     llvm::Constant *NewPtrForOldDecl =
854         VMContext.getConstantExprBitCast(GV, Entry->getType());
855     Entry->replaceAllUsesWith(NewPtrForOldDecl);
856 
857     // Erase the old global, since it is no longer used.
858     cast<llvm::GlobalValue>(Entry)->eraseFromParent();
859   }
860 
861   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
862     SourceManager &SM = Context.getSourceManager();
863     AddAnnotation(EmitAnnotateAttr(GV, AA,
864                               SM.getInstantiationLineNumber(D->getLocation())));
865   }
866 
867   GV->setInitializer(Init);
868   GV->setConstant(D->getType().isConstant(Context));
869   GV->setAlignment(getContext().getDeclAlignInBytes(D));
870 
871   // Set the llvm linkage type as appropriate.
872   if (D->getStorageClass() == VarDecl::Static)
873     GV->setLinkage(llvm::Function::InternalLinkage);
874   else if (D->hasAttr<DLLImportAttr>())
875     GV->setLinkage(llvm::Function::DLLImportLinkage);
876   else if (D->hasAttr<DLLExportAttr>())
877     GV->setLinkage(llvm::Function::DLLExportLinkage);
878   else if (D->hasAttr<WeakAttr>())
879     GV->setLinkage(llvm::GlobalVariable::WeakAnyLinkage);
880   else if (!CompileOpts.NoCommon &&
881            (!D->hasExternalStorage() && !D->getInit()))
882     GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
883   else
884     GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
885 
886   SetCommonAttributes(D, GV);
887 
888   // Emit global variable debug information.
889   if (CGDebugInfo *DI = getDebugInfo()) {
890     DI->setLocation(D->getLocation());
891     DI->EmitGlobalVariable(GV, D);
892   }
893 }
894 
895 /// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
896 /// implement a function with no prototype, e.g. "int foo() {}".  If there are
897 /// existing call uses of the old function in the module, this adjusts them to
898 /// call the new function directly.
899 ///
900 /// This is not just a cleanup: the always_inline pass requires direct calls to
901 /// functions to be able to inline them.  If there is a bitcast in the way, it
902 /// won't inline them.  Instcombine normally deletes these calls, but it isn't
903 /// run at -O0.
904 static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
905                                                       llvm::Function *NewFn) {
906   // If we're redefining a global as a function, don't transform it.
907   llvm::Function *OldFn = dyn_cast<llvm::Function>(Old);
908   if (OldFn == 0) return;
909 
910   const llvm::Type *NewRetTy = NewFn->getReturnType();
911   llvm::SmallVector<llvm::Value*, 4> ArgList;
912 
913   for (llvm::Value::use_iterator UI = OldFn->use_begin(), E = OldFn->use_end();
914        UI != E; ) {
915     // TODO: Do invokes ever occur in C code?  If so, we should handle them too.
916     unsigned OpNo = UI.getOperandNo();
917     llvm::CallInst *CI = dyn_cast<llvm::CallInst>(*UI++);
918     if (!CI || OpNo != 0) continue;
919 
920     // If the return types don't match exactly, and if the call isn't dead, then
921     // we can't transform this call.
922     if (CI->getType() != NewRetTy && !CI->use_empty())
923       continue;
924 
925     // If the function was passed too few arguments, don't transform.  If extra
926     // arguments were passed, we silently drop them.  If any of the types
927     // mismatch, we don't transform.
928     unsigned ArgNo = 0;
929     bool DontTransform = false;
930     for (llvm::Function::arg_iterator AI = NewFn->arg_begin(),
931          E = NewFn->arg_end(); AI != E; ++AI, ++ArgNo) {
932       if (CI->getNumOperands()-1 == ArgNo ||
933           CI->getOperand(ArgNo+1)->getType() != AI->getType()) {
934         DontTransform = true;
935         break;
936       }
937     }
938     if (DontTransform)
939       continue;
940 
941     // Okay, we can transform this.  Create the new call instruction and copy
942     // over the required information.
943     ArgList.append(CI->op_begin()+1, CI->op_begin()+1+ArgNo);
944     llvm::CallInst *NewCall = llvm::CallInst::Create(NewFn, ArgList.begin(),
945                                                      ArgList.end(), "", CI);
946     ArgList.clear();
947     if (NewCall->getType() != llvm::Type::VoidTy)
948       NewCall->takeName(CI);
949     NewCall->setCallingConv(CI->getCallingConv());
950     NewCall->setAttributes(CI->getAttributes());
951 
952     // Finally, remove the old call, replacing any uses with the new one.
953     if (!CI->use_empty())
954       CI->replaceAllUsesWith(NewCall);
955     CI->eraseFromParent();
956   }
957 }
958 
959 
960 void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
961   const llvm::FunctionType *Ty;
962   const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
963 
964   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
965     bool isVariadic = D->getType()->getAsFunctionProtoType()->isVariadic();
966 
967     Ty = getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), isVariadic);
968   } else {
969     Ty = cast<llvm::FunctionType>(getTypes().ConvertType(D->getType()));
970 
971     // As a special case, make sure that definitions of K&R function
972     // "type foo()" aren't declared as varargs (which forces the backend
973     // to do unnecessary work).
974     if (D->getType()->isFunctionNoProtoType()) {
975       assert(Ty->isVarArg() && "Didn't lower type as expected");
976       // Due to stret, the lowered function could have arguments.
977       // Just create the same type as was lowered by ConvertType
978       // but strip off the varargs bit.
979       std::vector<const llvm::Type*> Args(Ty->param_begin(), Ty->param_end());
980       Ty = VMContext.getFunctionType(Ty->getReturnType(), Args, false);
981     }
982   }
983 
984   // Get or create the prototype for the function.
985   llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
986 
987   // Strip off a bitcast if we got one back.
988   if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
989     assert(CE->getOpcode() == llvm::Instruction::BitCast);
990     Entry = CE->getOperand(0);
991   }
992 
993 
994   if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
995     llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
996 
997     // If the types mismatch then we have to rewrite the definition.
998     assert(OldFn->isDeclaration() &&
999            "Shouldn't replace non-declaration");
1000 
1001     // F is the Function* for the one with the wrong type, we must make a new
1002     // Function* and update everything that used F (a declaration) with the new
1003     // Function* (which will be a definition).
1004     //
1005     // This happens if there is a prototype for a function
1006     // (e.g. "int f()") and then a definition of a different type
1007     // (e.g. "int f(int x)").  Start by making a new function of the
1008     // correct type, RAUW, then steal the name.
1009     GlobalDeclMap.erase(getMangledName(D));
1010     llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
1011     NewFn->takeName(OldFn);
1012 
1013     // If this is an implementation of a function without a prototype, try to
1014     // replace any existing uses of the function (which may be calls) with uses
1015     // of the new function
1016     if (D->getType()->isFunctionNoProtoType()) {
1017       ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
1018       OldFn->removeDeadConstantUsers();
1019     }
1020 
1021     // Replace uses of F with the Function we will endow with a body.
1022     if (!Entry->use_empty()) {
1023       llvm::Constant *NewPtrForOldDecl =
1024         VMContext.getConstantExprBitCast(NewFn, Entry->getType());
1025       Entry->replaceAllUsesWith(NewPtrForOldDecl);
1026     }
1027 
1028     // Ok, delete the old function now, which is dead.
1029     OldFn->eraseFromParent();
1030 
1031     Entry = NewFn;
1032   }
1033 
1034   llvm::Function *Fn = cast<llvm::Function>(Entry);
1035 
1036   CodeGenFunction(*this).GenerateCode(D, Fn);
1037 
1038   SetFunctionDefinitionAttributes(D, Fn);
1039   SetLLVMFunctionAttributesForDefinition(D, Fn);
1040 
1041   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
1042     AddGlobalCtor(Fn, CA->getPriority());
1043   if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
1044     AddGlobalDtor(Fn, DA->getPriority());
1045 }
1046 
1047 void CodeGenModule::EmitAliasDefinition(const ValueDecl *D) {
1048   const AliasAttr *AA = D->getAttr<AliasAttr>();
1049   assert(AA && "Not an alias?");
1050 
1051   const llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
1052 
1053   // Unique the name through the identifier table.
1054   const char *AliaseeName = AA->getAliasee().c_str();
1055   AliaseeName = getContext().Idents.get(AliaseeName).getName();
1056 
1057   // Create a reference to the named value.  This ensures that it is emitted
1058   // if a deferred decl.
1059   llvm::Constant *Aliasee;
1060   if (isa<llvm::FunctionType>(DeclTy))
1061     Aliasee = GetOrCreateLLVMFunction(AliaseeName, DeclTy, GlobalDecl());
1062   else
1063     Aliasee = GetOrCreateLLVMGlobal(AliaseeName,
1064                                     VMContext.getPointerTypeUnqual(DeclTy), 0);
1065 
1066   // Create the new alias itself, but don't set a name yet.
1067   llvm::GlobalValue *GA =
1068     new llvm::GlobalAlias(Aliasee->getType(),
1069                           llvm::Function::ExternalLinkage,
1070                           "", Aliasee, &getModule());
1071 
1072   // See if there is already something with the alias' name in the module.
1073   const char *MangledName = getMangledName(D);
1074   llvm::GlobalValue *&Entry = GlobalDeclMap[MangledName];
1075 
1076   if (Entry && !Entry->isDeclaration()) {
1077     // If there is a definition in the module, then it wins over the alias.
1078     // This is dubious, but allow it to be safe.  Just ignore the alias.
1079     GA->eraseFromParent();
1080     return;
1081   }
1082 
1083   if (Entry) {
1084     // If there is a declaration in the module, then we had an extern followed
1085     // by the alias, as in:
1086     //   extern int test6();
1087     //   ...
1088     //   int test6() __attribute__((alias("test7")));
1089     //
1090     // Remove it and replace uses of it with the alias.
1091 
1092     Entry->replaceAllUsesWith(VMContext.getConstantExprBitCast(GA,
1093                                                           Entry->getType()));
1094     Entry->eraseFromParent();
1095   }
1096 
1097   // Now we know that there is no conflict, set the name.
1098   Entry = GA;
1099   GA->setName(MangledName);
1100 
1101   // Set attributes which are particular to an alias; this is a
1102   // specialization of the attributes which may be set on a global
1103   // variable/function.
1104   if (D->hasAttr<DLLExportAttr>()) {
1105     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1106       // The dllexport attribute is ignored for undefined symbols.
1107       if (FD->getBody())
1108         GA->setLinkage(llvm::Function::DLLExportLinkage);
1109     } else {
1110       GA->setLinkage(llvm::Function::DLLExportLinkage);
1111     }
1112   } else if (D->hasAttr<WeakAttr>() ||
1113              D->hasAttr<WeakImportAttr>()) {
1114     GA->setLinkage(llvm::Function::WeakAnyLinkage);
1115   }
1116 
1117   SetCommonAttributes(D, GA);
1118 }
1119 
1120 /// getBuiltinLibFunction - Given a builtin id for a function like
1121 /// "__builtin_fabsf", return a Function* for "fabsf".
1122 llvm::Value *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
1123   assert((Context.BuiltinInfo.isLibFunction(BuiltinID) ||
1124           Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) &&
1125          "isn't a lib fn");
1126 
1127   // Get the name, skip over the __builtin_ prefix (if necessary).
1128   const char *Name = Context.BuiltinInfo.GetName(BuiltinID);
1129   if (Context.BuiltinInfo.isLibFunction(BuiltinID))
1130     Name += 10;
1131 
1132   // Get the type for the builtin.
1133   ASTContext::GetBuiltinTypeError Error;
1134   QualType Type = Context.GetBuiltinType(BuiltinID, Error);
1135   assert(Error == ASTContext::GE_None && "Can't get builtin type");
1136 
1137   const llvm::FunctionType *Ty =
1138     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
1139 
1140   // Unique the name through the identifier table.
1141   Name = getContext().Idents.get(Name).getName();
1142   // FIXME: param attributes for sext/zext etc.
1143   return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl());
1144 }
1145 
1146 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
1147                                             unsigned NumTys) {
1148   return llvm::Intrinsic::getDeclaration(&getModule(),
1149                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
1150 }
1151 
1152 llvm::Function *CodeGenModule::getMemCpyFn() {
1153   if (MemCpyFn) return MemCpyFn;
1154   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1155   return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
1156 }
1157 
1158 llvm::Function *CodeGenModule::getMemMoveFn() {
1159   if (MemMoveFn) return MemMoveFn;
1160   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1161   return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
1162 }
1163 
1164 llvm::Function *CodeGenModule::getMemSetFn() {
1165   if (MemSetFn) return MemSetFn;
1166   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
1167   return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
1168 }
1169 
1170 static void appendFieldAndPadding(CodeGenModule &CGM,
1171                                   std::vector<llvm::Constant*>& Fields,
1172                                   FieldDecl *FieldD, FieldDecl *NextFieldD,
1173                                   llvm::Constant* Field,
1174                                   RecordDecl* RD, const llvm::StructType *STy) {
1175   // Append the field.
1176   Fields.push_back(Field);
1177 
1178   int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
1179 
1180   int NextStructFieldNo;
1181   if (!NextFieldD) {
1182     NextStructFieldNo = STy->getNumElements();
1183   } else {
1184     NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
1185   }
1186 
1187   // Append padding
1188   for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
1189     llvm::Constant *C =
1190       CGM.getLLVMContext().getNullValue(STy->getElementType(StructFieldNo + 1));
1191 
1192     Fields.push_back(C);
1193   }
1194 }
1195 
1196 llvm::Constant *CodeGenModule::
1197 GetAddrOfConstantCFString(const StringLiteral *Literal) {
1198   std::string str;
1199   unsigned StringLength = 0;
1200 
1201   bool isUTF16 = false;
1202   if (Literal->containsNonAsciiOrNull()) {
1203     // Convert from UTF-8 to UTF-16.
1204     llvm::SmallVector<UTF16, 128> ToBuf(Literal->getByteLength());
1205     const UTF8 *FromPtr = (UTF8 *)Literal->getStrData();
1206     UTF16 *ToPtr = &ToBuf[0];
1207 
1208     ConversionResult Result;
1209     Result = ConvertUTF8toUTF16(&FromPtr, FromPtr+Literal->getByteLength(),
1210                                 &ToPtr, ToPtr+Literal->getByteLength(),
1211                                 strictConversion);
1212     if (Result == conversionOK) {
1213       // FIXME: Storing UTF-16 in a C string is a hack to test Unicode strings
1214       // without doing more surgery to this routine. Since we aren't explicitly
1215       // checking for endianness here, it's also a bug (when generating code for
1216       // a target that doesn't match the host endianness). Modeling this as an
1217       // i16 array is likely the cleanest solution.
1218       StringLength = ToPtr-&ToBuf[0];
1219       str.assign((char *)&ToBuf[0], StringLength*2);// Twice as many UTF8 chars.
1220       isUTF16 = true;
1221     } else if (Result == sourceIllegal) {
1222       // FIXME: Have Sema::CheckObjCString() validate the UTF-8 string.
1223       str.assign(Literal->getStrData(), Literal->getByteLength());
1224       StringLength = str.length();
1225     } else
1226       assert(Result == conversionOK && "UTF-8 to UTF-16 conversion failed");
1227 
1228   } else {
1229     str.assign(Literal->getStrData(), Literal->getByteLength());
1230     StringLength = str.length();
1231   }
1232   llvm::StringMapEntry<llvm::Constant *> &Entry =
1233     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1234 
1235   if (llvm::Constant *C = Entry.getValue())
1236     return C;
1237 
1238   llvm::Constant *Zero = getLLVMContext().getNullValue(llvm::Type::Int32Ty);
1239   llvm::Constant *Zeros[] = { Zero, Zero };
1240 
1241   if (!CFConstantStringClassRef) {
1242     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
1243     Ty = VMContext.getArrayType(Ty, 0);
1244 
1245     // FIXME: This is fairly broken if __CFConstantStringClassReference is
1246     // already defined, in that it will get renamed and the user will most
1247     // likely see an opaque error message. This is a general issue with relying
1248     // on particular names.
1249     llvm::GlobalVariable *GV =
1250       new llvm::GlobalVariable(getModule(), Ty, false,
1251                                llvm::GlobalVariable::ExternalLinkage, 0,
1252                                "__CFConstantStringClassReference");
1253 
1254     // Decay array -> ptr
1255     CFConstantStringClassRef =
1256       VMContext.getConstantExprGetElementPtr(GV, Zeros, 2);
1257   }
1258 
1259   QualType CFTy = getContext().getCFConstantStringType();
1260   RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
1261 
1262   const llvm::StructType *STy =
1263     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
1264 
1265   std::vector<llvm::Constant*> Fields;
1266   RecordDecl::field_iterator Field = CFRD->field_begin();
1267 
1268   // Class pointer.
1269   FieldDecl *CurField = *Field++;
1270   FieldDecl *NextField = *Field++;
1271   appendFieldAndPadding(*this, Fields, CurField, NextField,
1272                         CFConstantStringClassRef, CFRD, STy);
1273 
1274   // Flags.
1275   CurField = NextField;
1276   NextField = *Field++;
1277   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
1278   appendFieldAndPadding(*this, Fields, CurField, NextField,
1279                         isUTF16 ? VMContext.getConstantInt(Ty, 0x07d0)
1280                                 : VMContext.getConstantInt(Ty, 0x07C8),
1281                         CFRD, STy);
1282 
1283   // String pointer.
1284   CurField = NextField;
1285   NextField = *Field++;
1286   llvm::Constant *C = VMContext.getConstantArray(str);
1287 
1288   const char *Sect, *Prefix;
1289   bool isConstant;
1290   if (isUTF16) {
1291     Prefix = getContext().Target.getUnicodeStringSymbolPrefix();
1292     Sect = getContext().Target.getUnicodeStringSection();
1293     // FIXME: Why does GCC not set constant here?
1294     isConstant = false;
1295   } else {
1296     Prefix = getContext().Target.getStringSymbolPrefix(true);
1297     Sect = getContext().Target.getCFStringDataSection();
1298     // FIXME: -fwritable-strings should probably affect this, but we
1299     // are following gcc here.
1300     isConstant = true;
1301   }
1302   llvm::GlobalVariable *GV =
1303     new llvm::GlobalVariable(getModule(), C->getType(), isConstant,
1304                              llvm::GlobalValue::InternalLinkage,
1305                              C, Prefix);
1306   if (Sect)
1307     GV->setSection(Sect);
1308   if (isUTF16) {
1309     unsigned Align = getContext().getTypeAlign(getContext().ShortTy)/8;
1310     GV->setAlignment(Align);
1311   }
1312   appendFieldAndPadding(*this, Fields, CurField, NextField,
1313                         VMContext.getConstantExprGetElementPtr(GV, Zeros, 2),
1314                         CFRD, STy);
1315 
1316   // String length.
1317   CurField = NextField;
1318   NextField = 0;
1319   Ty = getTypes().ConvertType(getContext().LongTy);
1320   appendFieldAndPadding(*this, Fields, CurField, NextField,
1321                         VMContext.getConstantInt(Ty, StringLength), CFRD, STy);
1322 
1323   // The struct.
1324   C = VMContext.getConstantStruct(STy, Fields);
1325   GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
1326                                 llvm::GlobalVariable::InternalLinkage, C,
1327                                 getContext().Target.getCFStringSymbolPrefix());
1328   if (const char *Sect = getContext().Target.getCFStringSection())
1329     GV->setSection(Sect);
1330   Entry.setValue(GV);
1331 
1332   return GV;
1333 }
1334 
1335 /// GetStringForStringLiteral - Return the appropriate bytes for a
1336 /// string literal, properly padded to match the literal type.
1337 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
1338   const char *StrData = E->getStrData();
1339   unsigned Len = E->getByteLength();
1340 
1341   const ConstantArrayType *CAT =
1342     getContext().getAsConstantArrayType(E->getType());
1343   assert(CAT && "String isn't pointer or array!");
1344 
1345   // Resize the string to the right size.
1346   std::string Str(StrData, StrData+Len);
1347   uint64_t RealLen = CAT->getSize().getZExtValue();
1348 
1349   if (E->isWide())
1350     RealLen *= getContext().Target.getWCharWidth()/8;
1351 
1352   Str.resize(RealLen, '\0');
1353 
1354   return Str;
1355 }
1356 
1357 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
1358 /// constant array for the given string literal.
1359 llvm::Constant *
1360 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
1361   // FIXME: This can be more efficient.
1362   return GetAddrOfConstantString(GetStringForStringLiteral(S));
1363 }
1364 
1365 /// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
1366 /// array for the given ObjCEncodeExpr node.
1367 llvm::Constant *
1368 CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
1369   std::string Str;
1370   getContext().getObjCEncodingForType(E->getEncodedType(), Str);
1371 
1372   return GetAddrOfConstantCString(Str);
1373 }
1374 
1375 
1376 /// GenerateWritableString -- Creates storage for a string literal.
1377 static llvm::Constant *GenerateStringLiteral(const std::string &str,
1378                                              bool constant,
1379                                              CodeGenModule &CGM,
1380                                              const char *GlobalName) {
1381   // Create Constant for this string literal. Don't add a '\0'.
1382   llvm::Constant *C = CGM.getLLVMContext().getConstantArray(str, false);
1383 
1384   // Create a global variable for this string
1385   return new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
1386                                   llvm::GlobalValue::InternalLinkage,
1387                                   C, GlobalName);
1388 }
1389 
1390 /// GetAddrOfConstantString - Returns a pointer to a character array
1391 /// containing the literal. This contents are exactly that of the
1392 /// given string, i.e. it will not be null terminated automatically;
1393 /// see GetAddrOfConstantCString. Note that whether the result is
1394 /// actually a pointer to an LLVM constant depends on
1395 /// Feature.WriteableStrings.
1396 ///
1397 /// The result has pointer to array type.
1398 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1399                                                        const char *GlobalName) {
1400   bool IsConstant = !Features.WritableStrings;
1401 
1402   // Get the default prefix if a name wasn't specified.
1403   if (!GlobalName)
1404     GlobalName = getContext().Target.getStringSymbolPrefix(IsConstant);
1405 
1406   // Don't share any string literals if strings aren't constant.
1407   if (!IsConstant)
1408     return GenerateStringLiteral(str, false, *this, GlobalName);
1409 
1410   llvm::StringMapEntry<llvm::Constant *> &Entry =
1411   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1412 
1413   if (Entry.getValue())
1414     return Entry.getValue();
1415 
1416   // Create a global variable for this.
1417   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1418   Entry.setValue(C);
1419   return C;
1420 }
1421 
1422 /// GetAddrOfConstantCString - Returns a pointer to a character
1423 /// array containing the literal and a terminating '\-'
1424 /// character. The result has pointer to array type.
1425 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1426                                                         const char *GlobalName){
1427   return GetAddrOfConstantString(str + '\0', GlobalName);
1428 }
1429 
1430 /// EmitObjCPropertyImplementations - Emit information for synthesized
1431 /// properties for an implementation.
1432 void CodeGenModule::EmitObjCPropertyImplementations(const
1433                                                     ObjCImplementationDecl *D) {
1434   for (ObjCImplementationDecl::propimpl_iterator
1435          i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1436     ObjCPropertyImplDecl *PID = *i;
1437 
1438     // Dynamic is just for type-checking.
1439     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1440       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1441 
1442       // Determine which methods need to be implemented, some may have
1443       // been overridden. Note that ::isSynthesized is not the method
1444       // we want, that just indicates if the decl came from a
1445       // property. What we want to know is if the method is defined in
1446       // this implementation.
1447       if (!D->getInstanceMethod(PD->getGetterName()))
1448         CodeGenFunction(*this).GenerateObjCGetter(
1449                                  const_cast<ObjCImplementationDecl *>(D), PID);
1450       if (!PD->isReadOnly() &&
1451           !D->getInstanceMethod(PD->getSetterName()))
1452         CodeGenFunction(*this).GenerateObjCSetter(
1453                                  const_cast<ObjCImplementationDecl *>(D), PID);
1454     }
1455   }
1456 }
1457 
1458 /// EmitNamespace - Emit all declarations in a namespace.
1459 void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
1460   for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
1461        I != E; ++I)
1462     EmitTopLevelDecl(*I);
1463 }
1464 
1465 // EmitLinkageSpec - Emit all declarations in a linkage spec.
1466 void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
1467   if (LSD->getLanguage() != LinkageSpecDecl::lang_c) {
1468     ErrorUnsupported(LSD, "linkage spec");
1469     return;
1470   }
1471 
1472   for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
1473        I != E; ++I)
1474     EmitTopLevelDecl(*I);
1475 }
1476 
1477 /// EmitTopLevelDecl - Emit code for a single top level declaration.
1478 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1479   // If an error has occurred, stop code generation, but continue
1480   // parsing and semantic analysis (to ensure all warnings and errors
1481   // are emitted).
1482   if (Diags.hasErrorOccurred())
1483     return;
1484 
1485   // Ignore dependent declarations.
1486   if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
1487     return;
1488 
1489   switch (D->getKind()) {
1490   case Decl::CXXMethod:
1491   case Decl::Function:
1492     // Skip function templates
1493     if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate())
1494       return;
1495 
1496     // Fall through
1497 
1498   case Decl::Var:
1499     EmitGlobal(GlobalDecl(cast<ValueDecl>(D)));
1500     break;
1501 
1502   // C++ Decls
1503   case Decl::Namespace:
1504     EmitNamespace(cast<NamespaceDecl>(D));
1505     break;
1506     // No code generation needed.
1507   case Decl::Using:
1508   case Decl::ClassTemplate:
1509   case Decl::FunctionTemplate:
1510     break;
1511   case Decl::CXXConstructor:
1512     EmitCXXConstructors(cast<CXXConstructorDecl>(D));
1513     break;
1514   case Decl::CXXDestructor:
1515     EmitCXXDestructors(cast<CXXDestructorDecl>(D));
1516     break;
1517 
1518   case Decl::StaticAssert:
1519     // Nothing to do.
1520     break;
1521 
1522   // Objective-C Decls
1523 
1524   // Forward declarations, no (immediate) code generation.
1525   case Decl::ObjCClass:
1526   case Decl::ObjCForwardProtocol:
1527   case Decl::ObjCCategory:
1528   case Decl::ObjCInterface:
1529     break;
1530 
1531   case Decl::ObjCProtocol:
1532     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1533     break;
1534 
1535   case Decl::ObjCCategoryImpl:
1536     // Categories have properties but don't support synthesize so we
1537     // can ignore them here.
1538     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1539     break;
1540 
1541   case Decl::ObjCImplementation: {
1542     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1543     EmitObjCPropertyImplementations(OMD);
1544     Runtime->GenerateClass(OMD);
1545     break;
1546   }
1547   case Decl::ObjCMethod: {
1548     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1549     // If this is not a prototype, emit the body.
1550     if (OMD->getBody())
1551       CodeGenFunction(*this).GenerateObjCMethod(OMD);
1552     break;
1553   }
1554   case Decl::ObjCCompatibleAlias:
1555     // compatibility-alias is a directive and has no code gen.
1556     break;
1557 
1558   case Decl::LinkageSpec:
1559     EmitLinkageSpec(cast<LinkageSpecDecl>(D));
1560     break;
1561 
1562   case Decl::FileScopeAsm: {
1563     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1564     std::string AsmString(AD->getAsmString()->getStrData(),
1565                           AD->getAsmString()->getByteLength());
1566 
1567     const std::string &S = getModule().getModuleInlineAsm();
1568     if (S.empty())
1569       getModule().setModuleInlineAsm(AsmString);
1570     else
1571       getModule().setModuleInlineAsm(S + '\n' + AsmString);
1572     break;
1573   }
1574 
1575   default:
1576     // Make sure we handled everything we should, every other kind is a
1577     // non-top-level decl.  FIXME: Would be nice to have an isTopLevelDeclKind
1578     // function. Need to recode Decl::Kind to do that easily.
1579     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1580   }
1581 }
1582