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