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