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