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