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 "CGDebugInfo.h"
15 #include "CodeGenModule.h"
16 #include "CodeGenFunction.h"
17 #include "CGCall.h"
18 #include "CGObjCRuntime.h"
19 #include "Mangle.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/Basic/Diagnostic.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "llvm/CallingConv.h"
27 #include "llvm/Module.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Target/TargetData.h"
30 using namespace clang;
31 using namespace CodeGen;
32 
33 
34 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
35                              llvm::Module &M, const llvm::TargetData &TD,
36                              Diagnostic &diags, bool GenerateDebugInfo)
37   : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
38     Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
39     CFConstantStringClassRef(0), NSConcreteGlobalBlock(0),
40     BlockDescriptorType(0), GenericBlockLiteralType(0) {
41 
42   if (Features.ObjC1) {
43     if (Features.NeXTRuntime) {
44       Runtime = Features.ObjCNonFragileABI ? CreateMacNonFragileABIObjCRuntime(*this)
45                                        : CreateMacObjCRuntime(*this);
46     } else {
47       Runtime = CreateGNUObjCRuntime(*this);
48     }
49   }
50 
51   // If debug info generation is enabled, create the CGDebugInfo object.
52   DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
53 
54   Block.GlobalUniqueCount = 0;
55   Block.DescriptorUniqueCount = 0;
56 }
57 
58 CodeGenModule::~CodeGenModule() {
59   delete Runtime;
60   delete DebugInfo;
61 }
62 
63 void CodeGenModule::Release() {
64   EmitStatics();
65   EmitAliases();
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   BindRuntimeFunctions();
73 }
74 
75 void CodeGenModule::BindRuntimeFunctions() {
76   // Deal with protecting runtime function names.
77   for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
78     llvm::Function *Fn = RuntimeFunctions[i].first;
79     const std::string &Name = RuntimeFunctions[i].second;
80 
81     // Discard unused runtime functions.
82     if (Fn->use_empty()) {
83       Fn->eraseFromParent();
84       continue;
85     }
86 
87     // See if there is a conflict against a function.
88     llvm::Function *Conflict = TheModule.getFunction(Name);
89     if (Conflict) {
90       // Decide which version to take. If the conflict is a definition
91       // we are forced to take that, otherwise assume the runtime
92       // knows best.
93       if (!Conflict->isDeclaration()) {
94         llvm::Value *Casted =
95           llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
96         Fn->replaceAllUsesWith(Casted);
97         Fn->eraseFromParent();
98       } else {
99         Fn->takeName(Conflict);
100         llvm::Value *Casted =
101           llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
102         Conflict->replaceAllUsesWith(Casted);
103         Conflict->eraseFromParent();
104       }
105     } else {
106       // FIXME: There still may be conflicts with aliases and
107       // variables.
108       Fn->setName(Name);
109     }
110   }
111 }
112 
113 /// ErrorUnsupported - Print out an error that codegen doesn't support the
114 /// specified stmt yet.
115 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
116                                      bool OmitOnError) {
117   if (OmitOnError && getDiags().hasErrorOccurred())
118     return;
119   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
120                                                "cannot compile this %0 yet");
121   std::string Msg = Type;
122   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
123     << Msg << S->getSourceRange();
124 }
125 
126 /// ErrorUnsupported - Print out an error that codegen doesn't support the
127 /// specified decl yet.
128 void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
129                                      bool OmitOnError) {
130   if (OmitOnError && getDiags().hasErrorOccurred())
131     return;
132   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
133                                                "cannot compile this %0 yet");
134   std::string Msg = Type;
135   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
136 }
137 
138 /// setGlobalVisibility - Set the visibility for the given LLVM
139 /// GlobalValue according to the given clang AST visibility value.
140 static void setGlobalVisibility(llvm::GlobalValue *GV,
141                                 VisibilityAttr::VisibilityTypes Vis) {
142   switch (Vis) {
143   default: assert(0 && "Unknown visibility!");
144   case VisibilityAttr::DefaultVisibility:
145     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
146     break;
147   case VisibilityAttr::HiddenVisibility:
148     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
149     break;
150   case VisibilityAttr::ProtectedVisibility:
151     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
152     break;
153   }
154 }
155 
156 /// \brief Retrieves the mangled name for the given declaration.
157 ///
158 /// If the given declaration requires a mangled name, returns an
159 /// IdentifierInfo* containing the mangled name. Otherwise, returns
160 /// the name of the declaration as an identifier.
161 ///
162 /// FIXME: Returning an IdentifierInfo* here is a total hack. We
163 /// really need some kind of string abstraction that either stores a
164 /// mangled name or stores an IdentifierInfo*. This will require
165 /// changes to the GlobalDeclMap, too.
166 ///
167 /// FIXME: Performance here is going to be terribly until we start
168 /// caching mangled names. However, we should fix the problem above
169 /// first.
170 IdentifierInfo *CodeGenModule::getMangledName(const NamedDecl *ND) const {
171   std::string Name;
172   llvm::raw_string_ostream Out(Name);
173   if (!mangleName(ND, Context, Out))
174     return ND->getIdentifier();
175 
176   return &Context.Idents.get(Out.str());
177 }
178 
179 /// AddGlobalCtor - Add a function to the list that will be called before
180 /// main() runs.
181 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
182   // FIXME: Type coercion of void()* types.
183   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
184 }
185 
186 /// AddGlobalDtor - Add a function to the list that will be called
187 /// when the module is unloaded.
188 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
189   // FIXME: Type coercion of void()* types.
190   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
191 }
192 
193 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
194   // Ctor function type is void()*.
195   llvm::FunctionType* CtorFTy =
196     llvm::FunctionType::get(llvm::Type::VoidTy,
197                             std::vector<const llvm::Type*>(),
198                             false);
199   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
200 
201   // Get the type of a ctor entry, { i32, void ()* }.
202   llvm::StructType* CtorStructTy =
203     llvm::StructType::get(llvm::Type::Int32Ty,
204                           llvm::PointerType::getUnqual(CtorFTy), NULL);
205 
206   // Construct the constructor and destructor arrays.
207   std::vector<llvm::Constant*> Ctors;
208   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
209     std::vector<llvm::Constant*> S;
210     S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
211     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
212     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
213   }
214 
215   if (!Ctors.empty()) {
216     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
217     new llvm::GlobalVariable(AT, false,
218                              llvm::GlobalValue::AppendingLinkage,
219                              llvm::ConstantArray::get(AT, Ctors),
220                              GlobalName,
221                              &TheModule);
222   }
223 }
224 
225 void CodeGenModule::EmitAnnotations() {
226   if (Annotations.empty())
227     return;
228 
229   // Create a new global variable for the ConstantStruct in the Module.
230   llvm::Constant *Array =
231   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
232                                                 Annotations.size()),
233                            Annotations);
234   llvm::GlobalValue *gv =
235   new llvm::GlobalVariable(Array->getType(), false,
236                            llvm::GlobalValue::AppendingLinkage, Array,
237                            "llvm.global.annotations", &TheModule);
238   gv->setSection("llvm.metadata");
239 }
240 
241 static void SetGlobalValueAttributes(const Decl *D,
242                                      bool IsInternal,
243                                      bool IsInline,
244                                      llvm::GlobalValue *GV,
245                                      bool ForDefinition) {
246   // FIXME: Set up linkage and many other things.  Note, this is a simple
247   // approximation of what we really want.
248   if (!ForDefinition) {
249     // Only a few attributes are set on declarations.
250     if (D->getAttr<DLLImportAttr>()) {
251       // The dllimport attribute is overridden by a subsequent declaration as
252       // dllexport.
253       if (!D->getAttr<DLLExportAttr>()) {
254         // dllimport attribute can be applied only to function decls, not to
255         // definitions.
256         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
257           if (!FD->getBody())
258             GV->setLinkage(llvm::Function::DLLImportLinkage);
259         } else
260           GV->setLinkage(llvm::Function::DLLImportLinkage);
261       }
262     }
263   } else {
264     if (IsInternal) {
265       GV->setLinkage(llvm::Function::InternalLinkage);
266     } else {
267       if (D->getAttr<DLLExportAttr>()) {
268         if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
269           // The dllexport attribute is ignored for undefined symbols.
270           if (FD->getBody())
271             GV->setLinkage(llvm::Function::DLLExportLinkage);
272         } else
273           GV->setLinkage(llvm::Function::DLLExportLinkage);
274       } else if (D->getAttr<WeakAttr>() || IsInline)
275         GV->setLinkage(llvm::Function::WeakLinkage);
276     }
277   }
278 
279   // FIXME: Figure out the relative priority of the attribute,
280   // -fvisibility, and private_extern.
281   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
282     setGlobalVisibility(GV, attr->getVisibility());
283   // FIXME: else handle -fvisibility
284 
285   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
286     // Prefaced with special LLVM marker to indicate that the name
287     // should not be munged.
288     GV->setName("\01" + ALA->getLabel());
289   }
290 
291   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
292     GV->setSection(SA->getName());
293 }
294 
295 void CodeGenModule::SetFunctionAttributes(const Decl *D,
296                                           const CGFunctionInfo &Info,
297                                           llvm::Function *F) {
298   AttributeListType AttributeList;
299   ConstructAttributeList(Info, D, AttributeList);
300 
301   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
302                                         AttributeList.size()));
303 
304   // Set the appropriate calling convention for the Function.
305   if (D->getAttr<FastCallAttr>())
306     F->setCallingConv(llvm::CallingConv::X86_FastCall);
307 
308   if (D->getAttr<StdCallAttr>())
309     F->setCallingConv(llvm::CallingConv::X86_StdCall);
310 }
311 
312 /// SetFunctionAttributesForDefinition - Set function attributes
313 /// specific to a function definition.
314 void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
315                                                        llvm::Function *F) {
316   if (isa<ObjCMethodDecl>(D)) {
317     SetGlobalValueAttributes(D, true, false, F, true);
318   } else {
319     const FunctionDecl *FD = cast<FunctionDecl>(D);
320     SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
321                              FD->isInline(), F, true);
322   }
323 
324   if (!Features.Exceptions)
325     F->addFnAttr(llvm::Attribute::NoUnwind);
326 
327   if (D->getAttr<AlwaysInlineAttr>())
328     F->addFnAttr(llvm::Attribute::AlwaysInline);
329 }
330 
331 void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
332                                         llvm::Function *F) {
333   SetFunctionAttributes(MD, getTypes().getFunctionInfo(MD), F);
334 
335   SetFunctionAttributesForDefinition(MD, F);
336 }
337 
338 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
339                                           llvm::Function *F) {
340   SetFunctionAttributes(FD, getTypes().getFunctionInfo(FD), F);
341 
342   SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
343                            FD->isInline(), F, false);
344 }
345 
346 
347 void CodeGenModule::EmitAliases() {
348   for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
349     const FunctionDecl *D = Aliases[i];
350     const AliasAttr *AA = D->getAttr<AliasAttr>();
351 
352     // This is something of a hack, if the FunctionDecl got overridden
353     // then its attributes will be moved to the new declaration. In
354     // this case the current decl has no alias attribute, but we will
355     // eventually see it.
356     if (!AA)
357       continue;
358 
359     const std::string& aliaseeName = AA->getAliasee();
360     llvm::Function *aliasee = getModule().getFunction(aliaseeName);
361     if (!aliasee) {
362       // FIXME: This isn't unsupported, this is just an error, which
363       // sema should catch, but...
364       ErrorUnsupported(D, "alias referencing a missing function");
365       continue;
366     }
367 
368     llvm::GlobalValue *GA =
369       new llvm::GlobalAlias(aliasee->getType(),
370                             llvm::Function::ExternalLinkage,
371                             getMangledName(D)->getName(), aliasee,
372                             &getModule());
373 
374     llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
375     if (Entry) {
376       // If we created a dummy function for this then replace it.
377       GA->takeName(Entry);
378 
379       llvm::Value *Casted =
380         llvm::ConstantExpr::getBitCast(GA, Entry->getType());
381       Entry->replaceAllUsesWith(Casted);
382       Entry->eraseFromParent();
383 
384       Entry = GA;
385     }
386 
387     // Alias should never be internal or inline.
388     SetGlobalValueAttributes(D, false, false, GA, true);
389   }
390 }
391 
392 void CodeGenModule::EmitStatics() {
393   // Emit code for each used static decl encountered.  Since a previously unused
394   // static decl may become used during the generation of code for a static
395   // function, iterate until no changes are made.
396   bool Changed;
397   do {
398     Changed = false;
399 
400     for (std::list<const ValueDecl*>::iterator i = StaticDecls.begin(),
401          e = StaticDecls.end(); i != e; ) {
402       const ValueDecl *D = *i;
403 
404       // Check if we have used a decl with the same name
405       // FIXME: The AST should have some sort of aggregate decls or
406       // global symbol map.
407       // FIXME: This is missing some important cases. For example, we
408       // need to check for uses in an alias and in a constructor.
409       if (!GlobalDeclMap.count(getMangledName(D))) {
410         i++;
411         continue;
412       }
413 
414       // Emit the definition.
415       EmitGlobalDefinition(D);
416 
417       // Erase the used decl from the list.
418       i = StaticDecls.erase(i);
419 
420       // Remember that we made a change.
421       Changed = true;
422     }
423   } while (Changed);
424 }
425 
426 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
427 /// annotation information for a given GlobalValue.  The annotation struct is
428 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
429 /// GlobalValue being annotated.  The second field is the constant string
430 /// created from the AnnotateAttr's annotation.  The third field is a constant
431 /// string containing the name of the translation unit.  The fourth field is
432 /// the line number in the file of the annotated value declaration.
433 ///
434 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
435 ///        appears to.
436 ///
437 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
438                                                 const AnnotateAttr *AA,
439                                                 unsigned LineNo) {
440   llvm::Module *M = &getModule();
441 
442   // get [N x i8] constants for the annotation string, and the filename string
443   // which are the 2nd and 3rd elements of the global annotation structure.
444   const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
445   llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
446   llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
447                                                   true);
448 
449   // Get the two global values corresponding to the ConstantArrays we just
450   // created to hold the bytes of the strings.
451   llvm::GlobalValue *annoGV =
452   new llvm::GlobalVariable(anno->getType(), false,
453                            llvm::GlobalValue::InternalLinkage, anno,
454                            GV->getName() + ".str", M);
455   // translation unit name string, emitted into the llvm.metadata section.
456   llvm::GlobalValue *unitGV =
457   new llvm::GlobalVariable(unit->getType(), false,
458                            llvm::GlobalValue::InternalLinkage, unit, ".str", M);
459 
460   // Create the ConstantStruct that is the global annotion.
461   llvm::Constant *Fields[4] = {
462     llvm::ConstantExpr::getBitCast(GV, SBP),
463     llvm::ConstantExpr::getBitCast(annoGV, SBP),
464     llvm::ConstantExpr::getBitCast(unitGV, SBP),
465     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
466   };
467   return llvm::ConstantStruct::get(Fields, 4, false);
468 }
469 
470 void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
471   bool isDef, isStatic;
472 
473   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
474     // Aliases are deferred until code for everything else has been
475     // emitted.
476     if (FD->getAttr<AliasAttr>()) {
477       assert(!FD->isThisDeclarationADefinition() &&
478              "Function alias cannot have a definition!");
479       Aliases.push_back(FD);
480       return;
481     }
482 
483     isDef = FD->isThisDeclarationADefinition();
484     isStatic = FD->getStorageClass() == FunctionDecl::Static;
485   } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
486     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
487 
488     isDef = !((VD->getStorageClass() == VarDecl::Extern ||
489                VD->getStorageClass() == VarDecl::PrivateExtern) &&
490               VD->getInit() == 0);
491     isStatic = VD->getStorageClass() == VarDecl::Static;
492   } else {
493     assert(0 && "Invalid argument to EmitGlobal");
494     return;
495   }
496 
497   // Forward declarations are emitted lazily on first use.
498   if (!isDef)
499     return;
500 
501   // If the global is a static, defer code generation until later so
502   // we can easily omit unused statics.
503   if (isStatic && !Features.EmitAllDecls) {
504     StaticDecls.push_back(Global);
505     return;
506   }
507 
508   // Otherwise emit the definition.
509   EmitGlobalDefinition(Global);
510 }
511 
512 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
513   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
514     EmitGlobalFunctionDefinition(FD);
515   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
516     EmitGlobalVarDefinition(VD);
517   } else {
518     assert(0 && "Invalid argument to EmitGlobalDefinition()");
519   }
520 }
521 
522  llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
523   assert(D->hasGlobalStorage() && "Not a global variable");
524 
525   QualType ASTTy = D->getType();
526   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
527   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
528 
529   // Lookup the entry, lazily creating it if necessary.
530   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
531   if (!Entry) {
532     llvm::GlobalVariable *GV =
533       new llvm::GlobalVariable(Ty, false,
534                                llvm::GlobalValue::ExternalLinkage,
535                                0, getMangledName(D)->getName(), &getModule(),
536                                0, ASTTy.getAddressSpace());
537     Entry = GV;
538 
539     // Handle things which are present even on external declarations.
540 
541     // FIXME: This code is overly simple and should be merged with
542     // other global handling.
543 
544     GV->setConstant(D->getType().isConstant(Context));
545 
546     if (D->getStorageClass() == VarDecl::PrivateExtern)
547       setGlobalVisibility(GV, VisibilityAttr::HiddenVisibility);
548   }
549 
550   // Make sure the result is of the correct type.
551   return llvm::ConstantExpr::getBitCast(Entry, PTy);
552 }
553 
554 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
555   llvm::Constant *Init = 0;
556   QualType ASTTy = D->getType();
557   const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
558 
559   if (D->getInit() == 0) {
560     // This is a tentative definition; tentative definitions are
561     // implicitly initialized with { 0 }
562     const llvm::Type* InitTy;
563     if (ASTTy->isIncompleteArrayType()) {
564       // An incomplete array is normally [ TYPE x 0 ], but we need
565       // to fix it to [ TYPE x 1 ].
566       const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
567       InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
568     } else {
569       InitTy = VarTy;
570     }
571     Init = llvm::Constant::getNullValue(InitTy);
572   } else {
573     Init = EmitConstantExpr(D->getInit());
574   }
575   const llvm::Type* InitType = Init->getType();
576 
577   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
578   llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
579 
580   if (!GV) {
581     GV = new llvm::GlobalVariable(InitType, false,
582                                   llvm::GlobalValue::ExternalLinkage,
583                                   0, getMangledName(D)->getName(),
584                                   &getModule(), 0, ASTTy.getAddressSpace());
585   } else if (GV->getType() !=
586              llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
587     // We have a definition after a prototype with the wrong type.
588     // We must make a new GlobalVariable* and update everything that used OldGV
589     // (a declaration or tentative definition) with the new GlobalVariable*
590     // (which will be a definition).
591     //
592     // This happens if there is a prototype for a global (e.g. "extern int x[];")
593     // and then a definition of a different type (e.g. "int x[10];"). This also
594     // happens when an initializer has a different type from the type of the
595     // global (this happens with unions).
596     //
597     // FIXME: This also ends up happening if there's a definition followed by
598     // a tentative definition!  (Although Sema rejects that construct
599     // at the moment.)
600 
601     // Save the old global
602     llvm::GlobalVariable *OldGV = GV;
603 
604     // Make a new global with the correct type
605     GV = new llvm::GlobalVariable(InitType, false,
606                                   llvm::GlobalValue::ExternalLinkage,
607                                   0, getMangledName(D)->getName(),
608                                   &getModule(), 0, ASTTy.getAddressSpace());
609     // Steal the name of the old global
610     GV->takeName(OldGV);
611 
612     // Replace all uses of the old global with the new global
613     llvm::Constant *NewPtrForOldDecl =
614         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
615     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
616 
617     // Erase the old global, since it is no longer used.
618     OldGV->eraseFromParent();
619   }
620 
621   Entry = GV;
622 
623   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
624     SourceManager &SM = Context.getSourceManager();
625     AddAnnotation(EmitAnnotateAttr(GV, AA,
626                               SM.getInstantiationLineNumber(D->getLocation())));
627   }
628 
629   GV->setInitializer(Init);
630   GV->setConstant(D->getType().isConstant(Context));
631 
632   // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
633   unsigned Align;
634   if (const IncompleteArrayType* IAT =
635         Context.getAsIncompleteArrayType(D->getType()))
636     Align = Context.getTypeAlign(IAT->getElementType());
637   else
638     Align = Context.getTypeAlign(D->getType());
639   if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
640     Align = std::max(Align, AA->getAlignment());
641   }
642   GV->setAlignment(Align / 8);
643 
644   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
645     setGlobalVisibility(GV, attr->getVisibility());
646   // FIXME: else handle -fvisibility
647 
648   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
649     // Prefaced with special LLVM marker to indicate that the name
650     // should not be munged.
651     GV->setName("\01" + ALA->getLabel());
652   }
653 
654   // Set the llvm linkage type as appropriate.
655   if (D->getStorageClass() == VarDecl::Static)
656     GV->setLinkage(llvm::Function::InternalLinkage);
657   else if (D->getAttr<DLLImportAttr>())
658     GV->setLinkage(llvm::Function::DLLImportLinkage);
659   else if (D->getAttr<DLLExportAttr>())
660     GV->setLinkage(llvm::Function::DLLExportLinkage);
661   else if (D->getAttr<WeakAttr>())
662     GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
663   else {
664     // FIXME: This isn't right.  This should handle common linkage and other
665     // stuff.
666     switch (D->getStorageClass()) {
667     case VarDecl::Static: assert(0 && "This case handled above");
668     case VarDecl::Auto:
669     case VarDecl::Register:
670       assert(0 && "Can't have auto or register globals");
671     case VarDecl::None:
672       if (!D->getInit())
673         GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
674       else
675         GV->setLinkage(llvm::GlobalVariable::ExternalLinkage);
676       break;
677     case VarDecl::Extern:
678       // FIXME: common
679       break;
680 
681     case VarDecl::PrivateExtern:
682       GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
683       // FIXME: common
684       break;
685     }
686   }
687 
688   if (const SectionAttr *SA = D->getAttr<SectionAttr>())
689     GV->setSection(SA->getName());
690 
691   // Emit global variable debug information.
692   CGDebugInfo *DI = getDebugInfo();
693   if(DI) {
694     DI->setLocation(D->getLocation());
695     DI->EmitGlobalVariable(GV, D);
696   }
697 }
698 
699 llvm::GlobalValue *
700 CodeGenModule::EmitForwardFunctionDefinition(const FunctionDecl *D) {
701   const llvm::Type *Ty = getTypes().ConvertType(D->getType());
702   llvm::Function *F = llvm::Function::Create(cast<llvm::FunctionType>(Ty),
703                                              llvm::Function::ExternalLinkage,
704                                              getMangledName(D)->getName(),
705                                              &getModule());
706   SetFunctionAttributes(D, F);
707   return F;
708 }
709 
710 llvm::Constant *CodeGenModule::GetAddrOfFunction(const FunctionDecl *D) {
711   QualType ASTTy = D->getType();
712   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
713   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
714 
715   // Lookup the entry, lazily creating it if necessary.
716   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
717   if (!Entry)
718     Entry = EmitForwardFunctionDefinition(D);
719 
720   return llvm::ConstantExpr::getBitCast(Entry, PTy);
721 }
722 
723 void CodeGenModule::EmitGlobalFunctionDefinition(const FunctionDecl *D) {
724   llvm::GlobalValue *&Entry = GlobalDeclMap[getMangledName(D)];
725   if (!Entry) {
726     Entry = EmitForwardFunctionDefinition(D);
727   } else {
728     // If the types mismatch then we have to rewrite the definition.
729     const llvm::Type *Ty = getTypes().ConvertType(D->getType());
730     if (Entry->getType() != llvm::PointerType::getUnqual(Ty)) {
731       // Otherwise, we have a definition after a prototype with the wrong type.
732       // F is the Function* for the one with the wrong type, we must make a new
733       // Function* and update everything that used F (a declaration) with the new
734       // Function* (which will be a definition).
735       //
736       // This happens if there is a prototype for a function (e.g. "int f()") and
737       // then a definition of a different type (e.g. "int f(int x)").  Start by
738       // making a new function of the correct type, RAUW, then steal the name.
739       llvm::GlobalValue *NewFn = EmitForwardFunctionDefinition(D);
740       NewFn->takeName(Entry);
741 
742       // Replace uses of F with the Function we will endow with a body.
743       llvm::Constant *NewPtrForOldDecl =
744         llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
745       Entry->replaceAllUsesWith(NewPtrForOldDecl);
746 
747       // Ok, delete the old function now, which is dead.
748       assert(Entry->isDeclaration() && "Shouldn't replace non-declaration");
749       Entry->eraseFromParent();
750 
751       Entry = NewFn;
752     }
753   }
754 
755   llvm::Function *Fn = cast<llvm::Function>(Entry);
756   CodeGenFunction(*this).GenerateCode(D, Fn);
757 
758   SetFunctionAttributesForDefinition(D, Fn);
759 
760   if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>()) {
761     AddGlobalCtor(Fn, CA->getPriority());
762   } else if (const DestructorAttr *DA = D->getAttr<DestructorAttr>()) {
763     AddGlobalDtor(Fn, DA->getPriority());
764   }
765 }
766 
767 llvm::Function *
768 CodeGenModule::CreateRuntimeFunction(const llvm::FunctionType *FTy,
769                                      const std::string &Name) {
770   llvm::Function *Fn = llvm::Function::Create(FTy,
771                                               llvm::Function::ExternalLinkage,
772                                               "", &TheModule);
773   RuntimeFunctions.push_back(std::make_pair(Fn, Name));
774   return Fn;
775 }
776 
777 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
778   // Make sure that this type is translated.
779   Types.UpdateCompletedType(TD);
780 }
781 
782 
783 /// getBuiltinLibFunction
784 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
785   if (BuiltinID > BuiltinFunctions.size())
786     BuiltinFunctions.resize(BuiltinID);
787 
788   // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
789   // a slot for it.
790   assert(BuiltinID && "Invalid Builtin ID");
791   llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
792   if (FunctionSlot)
793     return FunctionSlot;
794 
795   assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
796 
797   // Get the name, skip over the __builtin_ prefix.
798   const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
799 
800   // Get the type for the builtin.
801   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
802   const llvm::FunctionType *Ty =
803     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
804 
805   // FIXME: This has a serious problem with code like this:
806   //  void abs() {}
807   //    ... __builtin_abs(x);
808   // The two versions of abs will collide.  The fix is for the builtin to win,
809   // and for the existing one to be turned into a constantexpr cast of the
810   // builtin.  In the case where the existing one is a static function, it
811   // should just be renamed.
812   if (llvm::Function *Existing = getModule().getFunction(Name)) {
813     if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
814       return FunctionSlot = Existing;
815     assert(Existing == 0 && "FIXME: Name collision");
816   }
817 
818   // FIXME: param attributes for sext/zext etc.
819   return FunctionSlot =
820     llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
821                            &getModule());
822 }
823 
824 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
825                                             unsigned NumTys) {
826   return llvm::Intrinsic::getDeclaration(&getModule(),
827                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
828 }
829 
830 llvm::Function *CodeGenModule::getMemCpyFn() {
831   if (MemCpyFn) return MemCpyFn;
832   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
833   return MemCpyFn = getIntrinsic(llvm::Intrinsic::memcpy, &IntPtr, 1);
834 }
835 
836 llvm::Function *CodeGenModule::getMemMoveFn() {
837   if (MemMoveFn) return MemMoveFn;
838   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
839   return MemMoveFn = getIntrinsic(llvm::Intrinsic::memmove, &IntPtr, 1);
840 }
841 
842 llvm::Function *CodeGenModule::getMemSetFn() {
843   if (MemSetFn) return MemSetFn;
844   const llvm::Type *IntPtr = TheTargetData.getIntPtrType();
845   return MemSetFn = getIntrinsic(llvm::Intrinsic::memset, &IntPtr, 1);
846 }
847 
848 static void appendFieldAndPadding(CodeGenModule &CGM,
849                                   std::vector<llvm::Constant*>& Fields,
850                                   FieldDecl *FieldD, FieldDecl *NextFieldD,
851                                   llvm::Constant* Field,
852                                   RecordDecl* RD, const llvm::StructType *STy)
853 {
854   // Append the field.
855   Fields.push_back(Field);
856 
857   int StructFieldNo = CGM.getTypes().getLLVMFieldNo(FieldD);
858 
859   int NextStructFieldNo;
860   if (!NextFieldD) {
861     NextStructFieldNo = STy->getNumElements();
862   } else {
863     NextStructFieldNo = CGM.getTypes().getLLVMFieldNo(NextFieldD);
864   }
865 
866   // Append padding
867   for (int i = StructFieldNo + 1; i < NextStructFieldNo; i++) {
868     llvm::Constant *C =
869       llvm::Constant::getNullValue(STy->getElementType(StructFieldNo + 1));
870 
871     Fields.push_back(C);
872   }
873 }
874 
875 // We still need to work out the details of handling UTF-16.
876 // See: <rdr://2996215>
877 llvm::Constant *CodeGenModule::
878 GetAddrOfConstantCFString(const std::string &str) {
879   llvm::StringMapEntry<llvm::Constant *> &Entry =
880     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
881 
882   if (Entry.getValue())
883     return Entry.getValue();
884 
885   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
886   llvm::Constant *Zeros[] = { Zero, Zero };
887 
888   if (!CFConstantStringClassRef) {
889     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
890     Ty = llvm::ArrayType::get(Ty, 0);
891 
892     // FIXME: This is fairly broken if
893     // __CFConstantStringClassReference is already defined, in that it
894     // will get renamed and the user will most likely see an opaque
895     // error message. This is a general issue with relying on
896     // particular names.
897     llvm::GlobalVariable *GV =
898       new llvm::GlobalVariable(Ty, false,
899                                llvm::GlobalVariable::ExternalLinkage, 0,
900                                "__CFConstantStringClassReference",
901                                &getModule());
902 
903     // Decay array -> ptr
904     CFConstantStringClassRef =
905       llvm::ConstantExpr::getGetElementPtr(GV, Zeros, 2);
906   }
907 
908   QualType CFTy = getContext().getCFConstantStringType();
909   RecordDecl *CFRD = CFTy->getAsRecordType()->getDecl();
910 
911   const llvm::StructType *STy =
912     cast<llvm::StructType>(getTypes().ConvertType(CFTy));
913 
914   std::vector<llvm::Constant*> Fields;
915   RecordDecl::field_iterator Field = CFRD->field_begin();
916 
917   // Class pointer.
918   FieldDecl *CurField = *Field++;
919   FieldDecl *NextField = *Field++;
920   appendFieldAndPadding(*this, Fields, CurField, NextField,
921                         CFConstantStringClassRef, CFRD, STy);
922 
923   // Flags.
924   CurField = NextField;
925   NextField = *Field++;
926   const llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
927   appendFieldAndPadding(*this, Fields, CurField, NextField,
928                         llvm::ConstantInt::get(Ty, 0x07C8), CFRD, STy);
929 
930   // String pointer.
931   CurField = NextField;
932   NextField = *Field++;
933   llvm::Constant *C = llvm::ConstantArray::get(str);
934   C = new llvm::GlobalVariable(C->getType(), true,
935                                llvm::GlobalValue::InternalLinkage,
936                                C, ".str", &getModule());
937   appendFieldAndPadding(*this, Fields, CurField, NextField,
938                         llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2),
939                         CFRD, STy);
940 
941   // String length.
942   CurField = NextField;
943   NextField = 0;
944   Ty = getTypes().ConvertType(getContext().LongTy);
945   appendFieldAndPadding(*this, Fields, CurField, NextField,
946                         llvm::ConstantInt::get(Ty, str.length()), CFRD, STy);
947 
948   // The struct.
949   C = llvm::ConstantStruct::get(STy, Fields);
950   llvm::GlobalVariable *GV =
951     new llvm::GlobalVariable(C->getType(), true,
952                              llvm::GlobalVariable::InternalLinkage,
953                              C, "", &getModule());
954 
955   GV->setSection("__DATA,__cfstring");
956   Entry.setValue(GV);
957 
958   return GV;
959 }
960 
961 /// GetStringForStringLiteral - Return the appropriate bytes for a
962 /// string literal, properly padded to match the literal type.
963 std::string CodeGenModule::GetStringForStringLiteral(const StringLiteral *E) {
964   if (E->isWide()) {
965     ErrorUnsupported(E, "wide string");
966     return "FIXME";
967   }
968 
969   const char *StrData = E->getStrData();
970   unsigned Len = E->getByteLength();
971 
972   const ConstantArrayType *CAT =
973     getContext().getAsConstantArrayType(E->getType());
974   assert(CAT && "String isn't pointer or array!");
975 
976   // Resize the string to the right size
977   // FIXME: What about wchar_t strings?
978   std::string Str(StrData, StrData+Len);
979   uint64_t RealLen = CAT->getSize().getZExtValue();
980   Str.resize(RealLen, '\0');
981 
982   return Str;
983 }
984 
985 /// GetAddrOfConstantStringFromLiteral - Return a pointer to a
986 /// constant array for the given string literal.
987 llvm::Constant *
988 CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
989   // FIXME: This can be more efficient.
990   return GetAddrOfConstantString(GetStringForStringLiteral(S));
991 }
992 
993 /// GenerateWritableString -- Creates storage for a string literal.
994 static llvm::Constant *GenerateStringLiteral(const std::string &str,
995                                              bool constant,
996                                              CodeGenModule &CGM,
997                                              const char *GlobalName) {
998   // Create Constant for this string literal. Don't add a '\0'.
999   llvm::Constant *C = llvm::ConstantArray::get(str, false);
1000 
1001   // Create a global variable for this string
1002   C = new llvm::GlobalVariable(C->getType(), constant,
1003                                llvm::GlobalValue::InternalLinkage,
1004                                C,
1005                                GlobalName ? GlobalName : ".str",
1006                                &CGM.getModule());
1007 
1008   return C;
1009 }
1010 
1011 /// GetAddrOfConstantString - Returns a pointer to a character array
1012 /// containing the literal. This contents are exactly that of the
1013 /// given string, i.e. it will not be null terminated automatically;
1014 /// see GetAddrOfConstantCString. Note that whether the result is
1015 /// actually a pointer to an LLVM constant depends on
1016 /// Feature.WriteableStrings.
1017 ///
1018 /// The result has pointer to array type.
1019 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str,
1020                                                        const char *GlobalName) {
1021   // Don't share any string literals if writable-strings is turned on.
1022   if (Features.WritableStrings)
1023     return GenerateStringLiteral(str, false, *this, GlobalName);
1024 
1025   llvm::StringMapEntry<llvm::Constant *> &Entry =
1026   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
1027 
1028   if (Entry.getValue())
1029       return Entry.getValue();
1030 
1031   // Create a global variable for this.
1032   llvm::Constant *C = GenerateStringLiteral(str, true, *this, GlobalName);
1033   Entry.setValue(C);
1034   return C;
1035 }
1036 
1037 /// GetAddrOfConstantCString - Returns a pointer to a character
1038 /// array containing the literal and a terminating '\-'
1039 /// character. The result has pointer to array type.
1040 llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &str,
1041                                                         const char *GlobalName){
1042   return GetAddrOfConstantString(str + '\0', GlobalName);
1043 }
1044 
1045 /// EmitObjCPropertyImplementations - Emit information for synthesized
1046 /// properties for an implementation.
1047 void CodeGenModule::EmitObjCPropertyImplementations(const
1048                                                     ObjCImplementationDecl *D) {
1049   for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
1050          e = D->propimpl_end(); i != e; ++i) {
1051     ObjCPropertyImplDecl *PID = *i;
1052 
1053     // Dynamic is just for type-checking.
1054     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
1055       ObjCPropertyDecl *PD = PID->getPropertyDecl();
1056 
1057       // Determine which methods need to be implemented, some may have
1058       // been overridden. Note that ::isSynthesized is not the method
1059       // we want, that just indicates if the decl came from a
1060       // property. What we want to know is if the method is defined in
1061       // this implementation.
1062       if (!D->getInstanceMethod(PD->getGetterName()))
1063         CodeGenFunction(*this).GenerateObjCGetter(
1064                                  const_cast<ObjCImplementationDecl *>(D), PID);
1065       if (!PD->isReadOnly() &&
1066           !D->getInstanceMethod(PD->getSetterName()))
1067         CodeGenFunction(*this).GenerateObjCSetter(
1068                                  const_cast<ObjCImplementationDecl *>(D), PID);
1069     }
1070   }
1071 }
1072 
1073 /// EmitTopLevelDecl - Emit code for a single top level declaration.
1074 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
1075   // If an error has occurred, stop code generation, but continue
1076   // parsing and semantic analysis (to ensure all warnings and errors
1077   // are emitted).
1078   if (Diags.hasErrorOccurred())
1079     return;
1080 
1081   switch (D->getKind()) {
1082   case Decl::Function:
1083   case Decl::Var:
1084     EmitGlobal(cast<ValueDecl>(D));
1085     break;
1086 
1087   case Decl::Namespace:
1088     ErrorUnsupported(D, "namespace");
1089     break;
1090 
1091     // Objective-C Decls
1092 
1093     // Forward declarations, no (immediate) code generation.
1094   case Decl::ObjCClass:
1095   case Decl::ObjCCategory:
1096   case Decl::ObjCForwardProtocol:
1097   case Decl::ObjCInterface:
1098     break;
1099 
1100   case Decl::ObjCProtocol:
1101     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
1102     break;
1103 
1104   case Decl::ObjCCategoryImpl:
1105     // Categories have properties but don't support synthesize so we
1106     // can ignore them here.
1107 
1108     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
1109     break;
1110 
1111   case Decl::ObjCImplementation: {
1112     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
1113     EmitObjCPropertyImplementations(OMD);
1114     Runtime->GenerateClass(OMD);
1115     break;
1116   }
1117   case Decl::ObjCMethod: {
1118     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1119     // If this is not a prototype, emit the body.
1120     if (OMD->getBody())
1121       CodeGenFunction(*this).GenerateObjCMethod(OMD);
1122     break;
1123   }
1124   case Decl::ObjCCompatibleAlias:
1125     // compatibility-alias is a directive and has no code gen.
1126     break;
1127 
1128   case Decl::LinkageSpec: {
1129     LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1130     if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
1131       ErrorUnsupported(LSD, "linkage spec");
1132     // FIXME: implement C++ linkage, C linkage works mostly by C
1133     // language reuse already.
1134     break;
1135   }
1136 
1137   case Decl::FileScopeAsm: {
1138     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1139     std::string AsmString(AD->getAsmString()->getStrData(),
1140                           AD->getAsmString()->getByteLength());
1141 
1142     const std::string &S = getModule().getModuleInlineAsm();
1143     if (S.empty())
1144       getModule().setModuleInlineAsm(AsmString);
1145     else
1146       getModule().setModuleInlineAsm(S + '\n' + AsmString);
1147     break;
1148   }
1149 
1150   default:
1151     // Make sure we handled everything we should, every other kind is
1152     // a non-top-level decl.  FIXME: Would be nice to have an
1153     // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1154     // that easily.
1155     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1156   }
1157 }
1158