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