1 //===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This coordinates the per-module state used while generating code.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "CGDebugInfo.h"
15 #include "CodeGenModule.h"
16 #include "CodeGenFunction.h"
17 #include "CGCall.h"
18 #include "CGObjCRuntime.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/Basic/Diagnostic.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "llvm/CallingConv.h"
25 #include "llvm/Module.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/Target/TargetData.h"
28 #include "llvm/Analysis/Verifier.h"
29 using namespace clang;
30 using namespace CodeGen;
31 
32 
33 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
34                              llvm::Module &M, const llvm::TargetData &TD,
35                              Diagnostic &diags, bool GenerateDebugInfo)
36   : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
37     Types(C, M, TD), Runtime(0), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
38     CFConstantStringClassRef(0) {
39 
40   if (Features.ObjC1) {
41     if (Features.NeXTRuntime) {
42       Runtime = CreateMacObjCRuntime(*this);
43     } else {
44       Runtime = CreateGNUObjCRuntime(*this);
45     }
46   }
47 
48   // If debug info generation is enabled, create the CGDebugInfo object.
49   DebugInfo = GenerateDebugInfo ? new CGDebugInfo(this) : 0;
50 }
51 
52 CodeGenModule::~CodeGenModule() {
53   delete Runtime;
54   delete DebugInfo;
55 }
56 
57 void CodeGenModule::Release() {
58   EmitStatics();
59   EmitAliases();
60   if (Runtime)
61     if (llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction())
62       AddGlobalCtor(ObjCInitFunction);
63   EmitCtorList(GlobalCtors, "llvm.global_ctors");
64   EmitCtorList(GlobalDtors, "llvm.global_dtors");
65   EmitAnnotations();
66   BindRuntimeFunctions();
67   // Run the verifier to check that the generated code is consistent.
68   if (verifyModule(TheModule, llvm::PrintMessageAction)) {
69     TheModule.dump();
70     assert(0 && "Module failed verification!");
71   }
72 }
73 
74 void CodeGenModule::BindRuntimeFunctions() {
75   // Deal with protecting runtime function names.
76   for (unsigned i = 0, e = RuntimeFunctions.size(); i < e; ++i) {
77     llvm::Function *Fn = RuntimeFunctions[i].first;
78     const std::string &Name = RuntimeFunctions[i].second;
79 
80     // See if there is a conflict against a function.
81     llvm::Function *Conflict = TheModule.getFunction(Name);
82     if (Conflict) {
83       // Decide which version to take. If the conflict is a definition
84       // we are forced to take that, otherwise assume the runtime
85       // knows best.
86       if (!Conflict->isDeclaration()) {
87         llvm::Value *Casted =
88           llvm::ConstantExpr::getBitCast(Conflict, Fn->getType());
89         Fn->replaceAllUsesWith(Casted);
90         Fn->eraseFromParent();
91       } else {
92         Fn->takeName(Conflict);
93         llvm::Value *Casted =
94           llvm::ConstantExpr::getBitCast(Fn, Conflict->getType());
95         Conflict->replaceAllUsesWith(Casted);
96         Conflict->eraseFromParent();
97       }
98     } else {
99       // FIXME: There still may be conflicts with aliases and
100       // variables.
101       Fn->setName(Name);
102     }
103   }
104 }
105 
106 /// ErrorUnsupported - Print out an error that codegen doesn't support the
107 /// specified stmt yet.
108 void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
109                                      bool OmitOnError) {
110   if (OmitOnError && getDiags().hasErrorOccurred())
111     return;
112   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Error,
113                                                "cannot codegen this %0 yet");
114   SourceRange Range = S->getSourceRange();
115   std::string Msg = Type;
116   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
117                     &Msg, 1, &Range, 1);
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,
130                     &Msg, 1);
131 }
132 
133 /// setGlobalVisibility - Set the visibility for the given LLVM
134 /// GlobalValue according to the given clang AST visibility value.
135 static void setGlobalVisibility(llvm::GlobalValue *GV,
136                                 VisibilityAttr::VisibilityTypes Vis) {
137   switch (Vis) {
138   default: assert(0 && "Unknown visibility!");
139   case VisibilityAttr::DefaultVisibility:
140     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
141     break;
142   case VisibilityAttr::HiddenVisibility:
143     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
144     break;
145   case VisibilityAttr::ProtectedVisibility:
146     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
147     break;
148   }
149 }
150 
151 /// AddGlobalCtor - Add a function to the list that will be called before
152 /// main() runs.
153 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
154   // TODO: Type coercion of void()* types.
155   GlobalCtors.push_back(std::make_pair(Ctor, Priority));
156 }
157 
158 /// AddGlobalDtor - Add a function to the list that will be called
159 /// when the module is unloaded.
160 void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
161   // TODO: Type coercion of void()* types.
162   GlobalDtors.push_back(std::make_pair(Dtor, Priority));
163 }
164 
165 void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
166   // Ctor function type is void()*.
167   llvm::FunctionType* CtorFTy =
168     llvm::FunctionType::get(llvm::Type::VoidTy,
169                             std::vector<const llvm::Type*>(),
170                             false);
171   llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
172 
173   // Get the type of a ctor entry, { i32, void ()* }.
174   llvm::StructType* CtorStructTy =
175     llvm::StructType::get(llvm::Type::Int32Ty,
176                           llvm::PointerType::getUnqual(CtorFTy), NULL);
177 
178   // Construct the constructor and destructor arrays.
179   std::vector<llvm::Constant*> Ctors;
180   for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
181     std::vector<llvm::Constant*> S;
182     S.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, I->second, false));
183     S.push_back(llvm::ConstantExpr::getBitCast(I->first, CtorPFTy));
184     Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
185   }
186 
187   if (!Ctors.empty()) {
188     llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
189     new llvm::GlobalVariable(AT, false,
190                              llvm::GlobalValue::AppendingLinkage,
191                              llvm::ConstantArray::get(AT, Ctors),
192                              GlobalName,
193                              &TheModule);
194   }
195 }
196 
197 void CodeGenModule::EmitAnnotations() {
198   if (Annotations.empty())
199     return;
200 
201   // Create a new global variable for the ConstantStruct in the Module.
202   llvm::Constant *Array =
203   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
204                                                 Annotations.size()),
205                            Annotations);
206   llvm::GlobalValue *gv =
207   new llvm::GlobalVariable(Array->getType(), false,
208                            llvm::GlobalValue::AppendingLinkage, Array,
209                            "llvm.global.annotations", &TheModule);
210   gv->setSection("llvm.metadata");
211 }
212 
213 static void SetGlobalValueAttributes(const Decl *D,
214                                      bool IsInternal,
215                                      bool IsInline,
216                                      llvm::GlobalValue *GV,
217                                      bool ForDefinition) {
218   // TODO: Set up linkage and many other things.  Note, this is a simple
219   // approximation of what we really want.
220   if (!ForDefinition) {
221     // Only a few attributes are set on declarations.
222     if (D->getAttr<DLLImportAttr>())
223       GV->setLinkage(llvm::Function::DLLImportLinkage);
224   } else {
225     if (IsInternal) {
226       GV->setLinkage(llvm::Function::InternalLinkage);
227     } else {
228       if (D->getAttr<DLLImportAttr>())
229         GV->setLinkage(llvm::Function::DLLImportLinkage);
230       else if (D->getAttr<DLLExportAttr>())
231         GV->setLinkage(llvm::Function::DLLExportLinkage);
232       else if (D->getAttr<WeakAttr>() || IsInline)
233         GV->setLinkage(llvm::Function::WeakLinkage);
234     }
235   }
236 
237   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
238     setGlobalVisibility(GV, attr->getVisibility());
239   // FIXME: else handle -fvisibility
240 
241   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
242     // Prefaced with special LLVM marker to indicate that the name
243     // should not be munged.
244     GV->setName("\01" + ALA->getLabel());
245   }
246 }
247 
248 void CodeGenModule::SetFunctionAttributes(const Decl *D,
249                                           const CGFunctionInfo &Info,
250                                           llvm::Function *F) {
251   AttributeListType AttributeList;
252   ConstructAttributeList(D, Info.argtypes_begin(), Info.argtypes_end(),
253                          AttributeList);
254 
255   F->setAttributes(llvm::AttrListPtr::get(AttributeList.begin(),
256                                         AttributeList.size()));
257 
258   // Set the appropriate calling convention for the Function.
259   if (D->getAttr<FastCallAttr>())
260     F->setCallingConv(llvm::CallingConv::Fast);
261 }
262 
263 /// SetFunctionAttributesForDefinition - Set function attributes
264 /// specific to a function definition.
265 void CodeGenModule::SetFunctionAttributesForDefinition(const Decl *D,
266                                                        llvm::Function *F) {
267   if (isa<ObjCMethodDecl>(D)) {
268     SetGlobalValueAttributes(D, true, false, F, true);
269   } else {
270     const FunctionDecl *FD = cast<FunctionDecl>(D);
271     SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
272                              FD->isInline(), F, true);
273   }
274 
275   if (!Features.Exceptions)
276     F->addFnAttr(llvm::Attribute::NoUnwind);
277 }
278 
279 void CodeGenModule::SetMethodAttributes(const ObjCMethodDecl *MD,
280                                         llvm::Function *F) {
281   SetFunctionAttributes(MD, CGFunctionInfo(MD, Context), F);
282 
283   SetFunctionAttributesForDefinition(MD, F);
284 }
285 
286 void CodeGenModule::SetFunctionAttributes(const FunctionDecl *FD,
287                                           llvm::Function *F) {
288   SetFunctionAttributes(FD, CGFunctionInfo(FD), F);
289 
290   SetGlobalValueAttributes(FD, FD->getStorageClass() == FunctionDecl::Static,
291                            FD->isInline(), F, false);
292 }
293 
294 
295 void CodeGenModule::EmitAliases() {
296   for (unsigned i = 0, e = Aliases.size(); i != e; ++i) {
297     const FunctionDecl *D = Aliases[i];
298     const AliasAttr *AA = D->getAttr<AliasAttr>();
299 
300     // This is something of a hack, if the FunctionDecl got overridden
301     // then its attributes will be moved to the new declaration. In
302     // this case the current decl has no alias attribute, but we will
303     // eventually see it.
304     if (!AA)
305       continue;
306 
307     const std::string& aliaseeName = AA->getAliasee();
308     llvm::Function *aliasee = getModule().getFunction(aliaseeName);
309     if (!aliasee) {
310       // FIXME: This isn't unsupported, this is just an error, which
311       // sema should catch, but...
312       ErrorUnsupported(D, "alias referencing a missing function");
313       continue;
314     }
315 
316     llvm::GlobalValue *GA =
317       new llvm::GlobalAlias(aliasee->getType(),
318                             llvm::Function::ExternalLinkage,
319                             D->getName(),
320                             aliasee,
321                             &getModule());
322 
323     llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
324     if (Entry) {
325       // If we created a dummy function for this then replace it.
326       GA->takeName(Entry);
327 
328       llvm::Value *Casted =
329         llvm::ConstantExpr::getBitCast(GA, Entry->getType());
330       Entry->replaceAllUsesWith(Casted);
331       Entry->eraseFromParent();
332 
333       Entry = GA;
334     }
335 
336     // Alias should never be internal or inline.
337     SetGlobalValueAttributes(D, false, false, GA, true);
338   }
339 }
340 
341 void CodeGenModule::EmitStatics() {
342   // Emit code for each used static decl encountered.  Since a previously unused
343   // static decl may become used during the generation of code for a static
344   // function, iterate until no changes are made.
345   bool Changed;
346   do {
347     Changed = false;
348     for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
349       const ValueDecl *D = StaticDecls[i];
350 
351       // Check if we have used a decl with the same name
352       // FIXME: The AST should have some sort of aggregate decls or
353       // global symbol map.
354       // FIXME: This is missing some important cases. For example, we
355       // need to check for uses in an alias and in a constructor.
356       if (!GlobalDeclMap.count(D->getIdentifier()))
357         continue;
358 
359       // Emit the definition.
360       EmitGlobalDefinition(D);
361 
362       // Erase the used decl from the list.
363       StaticDecls[i] = StaticDecls.back();
364       StaticDecls.pop_back();
365       --i;
366       --e;
367 
368       // Remember that we made a change.
369       Changed = true;
370     }
371   } while (Changed);
372 }
373 
374 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
375 /// annotation information for a given GlobalValue.  The annotation struct is
376 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
377 /// GlobalValue being annotated.  The second field is the constant string
378 /// created from the AnnotateAttr's annotation.  The third field is a constant
379 /// string containing the name of the translation unit.  The fourth field is
380 /// the line number in the file of the annotated value declaration.
381 ///
382 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
383 ///        appears to.
384 ///
385 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
386                                                 const AnnotateAttr *AA,
387                                                 unsigned LineNo) {
388   llvm::Module *M = &getModule();
389 
390   // get [N x i8] constants for the annotation string, and the filename string
391   // which are the 2nd and 3rd elements of the global annotation structure.
392   const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
393   llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
394   llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
395                                                   true);
396 
397   // Get the two global values corresponding to the ConstantArrays we just
398   // created to hold the bytes of the strings.
399   llvm::GlobalValue *annoGV =
400   new llvm::GlobalVariable(anno->getType(), false,
401                            llvm::GlobalValue::InternalLinkage, anno,
402                            GV->getName() + ".str", M);
403   // translation unit name string, emitted into the llvm.metadata section.
404   llvm::GlobalValue *unitGV =
405   new llvm::GlobalVariable(unit->getType(), false,
406                            llvm::GlobalValue::InternalLinkage, unit, ".str", M);
407 
408   // Create the ConstantStruct that is the global annotion.
409   llvm::Constant *Fields[4] = {
410     llvm::ConstantExpr::getBitCast(GV, SBP),
411     llvm::ConstantExpr::getBitCast(annoGV, SBP),
412     llvm::ConstantExpr::getBitCast(unitGV, SBP),
413     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
414   };
415   return llvm::ConstantStruct::get(Fields, 4, false);
416 }
417 
418 void CodeGenModule::EmitGlobal(const ValueDecl *Global) {
419   bool isDef, isStatic;
420 
421   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
422     // Aliases are deferred until code for everything else has been
423     // emitted.
424     if (FD->getAttr<AliasAttr>()) {
425       assert(!FD->isThisDeclarationADefinition() &&
426              "Function alias cannot have a definition!");
427       Aliases.push_back(FD);
428       return;
429     }
430 
431     isDef = FD->isThisDeclarationADefinition();
432     isStatic = FD->getStorageClass() == FunctionDecl::Static;
433   } else if (const VarDecl *VD = cast<VarDecl>(Global)) {
434     assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
435 
436     isDef = !(VD->getStorageClass() == VarDecl::Extern && VD->getInit() == 0);
437     isStatic = VD->getStorageClass() == VarDecl::Static;
438   } else {
439     assert(0 && "Invalid argument to EmitGlobal");
440     return;
441   }
442 
443   // Forward declarations are emitted lazily on first use.
444   if (!isDef)
445     return;
446 
447   // If the global is a static, defer code generation until later so
448   // we can easily omit unused statics.
449   if (isStatic) {
450     StaticDecls.push_back(Global);
451     return;
452   }
453 
454   // Otherwise emit the definition.
455   EmitGlobalDefinition(Global);
456 }
457 
458 void CodeGenModule::EmitGlobalDefinition(const ValueDecl *D) {
459   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
460     EmitGlobalFunctionDefinition(FD);
461   } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
462     EmitGlobalVarDefinition(VD);
463   } else {
464     assert(0 && "Invalid argument to EmitGlobalDefinition()");
465   }
466 }
467 
468  llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D) {
469   assert(D->hasGlobalStorage() && "Not a global variable");
470 
471   QualType ASTTy = D->getType();
472   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
473   const llvm::Type *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
474 
475   // Lookup the entry, lazily creating it if necessary.
476   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
477   if (!Entry)
478     Entry = new llvm::GlobalVariable(Ty, false,
479                                      llvm::GlobalValue::ExternalLinkage,
480                                      0, D->getName(), &getModule(), 0,
481                                      ASTTy.getAddressSpace());
482 
483   // Make sure the result is of the correct type.
484   return llvm::ConstantExpr::getBitCast(Entry, PTy);
485 }
486 
487 void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
488   llvm::Constant *Init = 0;
489   QualType ASTTy = D->getType();
490   const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
491 
492   if (D->getInit() == 0) {
493     // This is a tentative definition; tentative definitions are
494     // implicitly initialized with { 0 }
495     const llvm::Type* InitTy;
496     if (ASTTy->isIncompleteArrayType()) {
497       // An incomplete array is normally [ TYPE x 0 ], but we need
498       // to fix it to [ TYPE x 1 ].
499       const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
500       InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
501     } else {
502       InitTy = VarTy;
503     }
504     Init = llvm::Constant::getNullValue(InitTy);
505   } else {
506     Init = EmitConstantExpr(D->getInit());
507   }
508   const llvm::Type* InitType = Init->getType();
509 
510   llvm::GlobalValue *&Entry = GlobalDeclMap[D->getIdentifier()];
511   llvm::GlobalVariable *GV = cast_or_null<llvm::GlobalVariable>(Entry);
512 
513   if (!GV) {
514     GV = new llvm::GlobalVariable(InitType, false,
515                                   llvm::GlobalValue::ExternalLinkage,
516                                   0, D->getName(), &getModule(), 0,
517                                   ASTTy.getAddressSpace());
518   } else if (GV->getType() !=
519              llvm::PointerType::get(InitType, ASTTy.getAddressSpace())) {
520     // We have a definition after a prototype with the wrong type.
521     // We must make a new GlobalVariable* and update everything that used OldGV
522     // (a declaration or tentative definition) with the new GlobalVariable*
523     // (which will be a definition).
524     //
525     // This happens if there is a prototype for a global (e.g. "extern int x[];")
526     // and then a definition of a different type (e.g. "int x[10];"). This also
527     // happens when an initializer has a different type from the type of the
528     // global (this happens with unions).
529     //
530     // FIXME: This also ends up happening if there's a definition followed by
531     // a tentative definition!  (Although Sema rejects that construct
532     // at the moment.)
533 
534     // Save the old global
535     llvm::GlobalVariable *OldGV = GV;
536 
537     // Make a new global with the correct type
538     GV = new llvm::GlobalVariable(InitType, false,
539                                   llvm::GlobalValue::ExternalLinkage,
540                                   0, D->getName(), &getModule(), 0,
541                                   ASTTy.getAddressSpace());
542     // Steal the name of the old global
543     GV->takeName(OldGV);
544 
545     // Replace all uses of the old global with the new global
546     llvm::Constant *NewPtrForOldDecl =
547         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
548     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
549 
550     // Erase the old global, since it is no longer used.
551     OldGV->eraseFromParent();
552   }
553 
554   Entry = GV;
555 
556   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
557     SourceManager &SM = Context.getSourceManager();
558     AddAnnotation(EmitAnnotateAttr(GV, AA,
559                                    SM.getLogicalLineNumber(D->getLocation())));
560   }
561 
562   GV->setInitializer(Init);
563   GV->setConstant(D->getType().isConstant(Context));
564 
565   // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
566   unsigned Align;
567   if (const IncompleteArrayType* IAT =
568         Context.getAsIncompleteArrayType(D->getType()))
569     Align = Context.getTypeAlign(IAT->getElementType());
570   else
571     Align = Context.getTypeAlign(D->getType());
572   if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
573     Align = std::max(Align, AA->getAlignment());
574   }
575   GV->setAlignment(Align / 8);
576 
577   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
578     setGlobalVisibility(GV, attr->getVisibility());
579   // FIXME: else handle -fvisibility
580 
581   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
582     // Prefaced with special LLVM marker to indicate that the name
583     // should not be munged.
584     GV->setName("\01" + ALA->getLabel());
585   }
586 
587   // Set the llvm linkage type as appropriate.
588   if (D->getStorageClass() == VarDecl::Static)
589     GV->setLinkage(llvm::Function::InternalLinkage);
590   else if (D->getAttr<DLLImportAttr>())
591     GV->setLinkage(llvm::Function::DLLImportLinkage);
592   else if (D->getAttr<DLLExportAttr>())
593     GV->setLinkage(llvm::Function::DLLExportLinkage);
594   else if (D->getAttr<WeakAttr>())
595     GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
596   else {
597     // FIXME: This isn't right.  This should handle common linkage and other
598     // stuff.
599     switch (D->getStorageClass()) {
600     case VarDecl::Static: assert(0 && "This case handled above");
601     case VarDecl::Auto:
602     case VarDecl::Register:
603       assert(0 && "Can't have auto or register globals");
604     case VarDecl::None:
605       if (!D->getInit())
606         GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
607       break;
608     case VarDecl::Extern:
609     case VarDecl::PrivateExtern:
610       // todo: common
611       break;
612     }
613   }
614 
615   // Emit global variable debug information.
616   CGDebugInfo *DI = getDebugInfo();
617   if(DI) {
618     if(D->getLocation().isValid())
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   // Create Constant for this string literal. Don't add a '\0'.
891   llvm::Constant *C = llvm::ConstantArray::get(str, false);
892 
893   // Create a global variable for this string
894   C = new llvm::GlobalVariable(C->getType(), constant,
895                                llvm::GlobalValue::InternalLinkage,
896                                C, ".str", &CGM.getModule());
897 
898   return C;
899 }
900 
901 /// GetAddrOfConstantString - Returns a pointer to a character array
902 /// containing the literal. This contents are exactly that of the
903 /// given string, i.e. it will not be null terminated automatically;
904 /// see GetAddrOfConstantCString. Note that whether the result is
905 /// actually a pointer to an LLVM constant depends on
906 /// Feature.WriteableStrings.
907 ///
908 /// The result has pointer to array type.
909 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
910   // Don't share any string literals if writable-strings is turned on.
911   if (Features.WritableStrings)
912     return GenerateStringLiteral(str, false, *this);
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);
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   return GetAddrOfConstantString(str + "\0");
931 }
932 
933 /// EmitObjCPropertyImplementations - Emit information for synthesized
934 /// properties for an implementation.
935 void CodeGenModule::EmitObjCPropertyImplementations(const
936                                                     ObjCImplementationDecl *D) {
937   for (ObjCImplementationDecl::propimpl_iterator i = D->propimpl_begin(),
938          e = D->propimpl_end(); i != e; ++i) {
939     ObjCPropertyImplDecl *PID = *i;
940 
941     // Dynamic is just for type-checking.
942     if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
943       ObjCPropertyDecl *PD = PID->getPropertyDecl();
944 
945       // Determine which methods need to be implemented, some may have
946       // been overridden. Note that ::isSynthesized is not the method
947       // we want, that just indicates if the decl came from a
948       // property. What we want to know is if the method is defined in
949       // this implementation.
950       if (!D->getInstanceMethod(PD->getGetterName()))
951         CodeGenFunction(*this).GenerateObjCGetter(PID);
952       if (!PD->isReadOnly() &&
953           !D->getInstanceMethod(PD->getSetterName()))
954         CodeGenFunction(*this).GenerateObjCSetter(PID);
955     }
956   }
957 }
958 
959 /// EmitTopLevelDecl - Emit code for a single top level declaration.
960 void CodeGenModule::EmitTopLevelDecl(Decl *D) {
961   // If an error has occurred, stop code generation, but continue
962   // parsing and semantic analysis (to ensure all warnings and errors
963   // are emitted).
964   if (Diags.hasErrorOccurred())
965     return;
966 
967   switch (D->getKind()) {
968   case Decl::Function:
969   case Decl::Var:
970     EmitGlobal(cast<ValueDecl>(D));
971     break;
972 
973   case Decl::Namespace:
974     ErrorUnsupported(D, "namespace");
975     break;
976 
977     // Objective-C Decls
978 
979     // Forward declarations, no (immediate) code generation.
980   case Decl::ObjCClass:
981   case Decl::ObjCCategory:
982   case Decl::ObjCForwardProtocol:
983   case Decl::ObjCInterface:
984     break;
985 
986   case Decl::ObjCProtocol:
987     Runtime->GenerateProtocol(cast<ObjCProtocolDecl>(D));
988     break;
989 
990   case Decl::ObjCCategoryImpl:
991     // Categories have properties but don't support synthesize so we
992     // can ignore them here.
993 
994     Runtime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
995     break;
996 
997   case Decl::ObjCImplementation: {
998     ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
999     EmitObjCPropertyImplementations(OMD);
1000     Runtime->GenerateClass(OMD);
1001     break;
1002   }
1003   case Decl::ObjCMethod: {
1004     ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
1005     // If this is not a prototype, emit the body.
1006     if (OMD->getBody())
1007       CodeGenFunction(*this).GenerateObjCMethod(OMD);
1008     break;
1009   }
1010   case Decl::ObjCCompatibleAlias:
1011     ErrorUnsupported(D, "Objective-C compatible alias");
1012     break;
1013 
1014   case Decl::LinkageSpec: {
1015     LinkageSpecDecl *LSD = cast<LinkageSpecDecl>(D);
1016     if (LSD->getLanguage() == LinkageSpecDecl::lang_cxx)
1017       ErrorUnsupported(LSD, "linkage spec");
1018     // FIXME: implement C++ linkage, C linkage works mostly by C
1019     // language reuse already.
1020     break;
1021   }
1022 
1023   case Decl::FileScopeAsm: {
1024     FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
1025     std::string AsmString(AD->getAsmString()->getStrData(),
1026                           AD->getAsmString()->getByteLength());
1027 
1028     const std::string &S = getModule().getModuleInlineAsm();
1029     if (S.empty())
1030       getModule().setModuleInlineAsm(AsmString);
1031     else
1032       getModule().setModuleInlineAsm(S + '\n' + AsmString);
1033     break;
1034   }
1035 
1036   default:
1037     // Make sure we handled everything we should, every other kind is
1038     // a non-top-level decl.  FIXME: Would be nice to have an
1039     // isTopLevelDeclKind function. Need to recode Decl::Kind to do
1040     // that easily.
1041     assert(isa<TypeDecl>(D) && "Unsupported decl kind");
1042   }
1043 }
1044 
1045