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