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