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