xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 6859a1b961d808484cd77473ed6e1eceef193c8d)
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 "clang/AST/ASTContext.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "llvm/CallingConv.h"
24 #include "llvm/Constants.h"
25 #include "llvm/DerivedTypes.h"
26 #include "llvm/Module.h"
27 #include "llvm/Intrinsics.h"
28 #include "llvm/Analysis/Verifier.h"
29 #include <algorithm>
30 using namespace clang;
31 using namespace CodeGen;
32 
33 
34 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
35                              llvm::Module &M, const llvm::TargetData &TD,
36                              Diagnostic &diags, bool GenerateDebugInfo)
37   : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
38     Types(C, M, TD), MemCpyFn(0), MemMoveFn(0), MemSetFn(0),
39     CFConstantStringClassRef(0) {
40   //TODO: Make this selectable at runtime
41   Runtime = CreateObjCRuntime(M,
42       getTypes().ConvertType(getContext().IntTy),
43       getTypes().ConvertType(getContext().LongTy));
44 
45   // If debug info generation is enabled, create the CGDebugInfo object.
46   if (GenerateDebugInfo)
47     DebugInfo = new CGDebugInfo(this);
48   else
49     DebugInfo = NULL;
50 }
51 
52 CodeGenModule::~CodeGenModule() {
53   llvm::Function *ObjCInitFunction = Runtime->ModuleInitFunction();
54   if (ObjCInitFunction)
55     AddGlobalCtor(ObjCInitFunction);
56   EmitStatics();
57   EmitGlobalCtors();
58   EmitAnnotations();
59   delete Runtime;
60   delete DebugInfo;
61   // Run the verifier to check that the generated code is consistent.
62   assert(!verifyModule(TheModule));
63 }
64 
65 /// WarnUnsupported - Print out a warning that codegen doesn't support the
66 /// specified stmt yet.
67 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
68   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
69                                                "cannot codegen this %0 yet");
70   SourceRange Range = S->getSourceRange();
71   std::string Msg = Type;
72   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
73                     &Msg, 1, &Range, 1);
74 }
75 
76 /// WarnUnsupported - Print out a warning that codegen doesn't support the
77 /// specified decl yet.
78 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
79   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
80                                                "cannot codegen this %0 yet");
81   std::string Msg = Type;
82   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
83                     &Msg, 1);
84 }
85 
86 /// setVisibility - Set the visibility for the given LLVM GlobalValue
87 /// according to the given clang AST visibility value.
88 void CodeGenModule::setVisibility(llvm::GlobalValue *GV,
89                                   VisibilityAttr::VisibilityTypes Vis) {
90   switch (Vis) {
91   default: assert(0 && "Unknown visibility!");
92   case VisibilityAttr::DefaultVisibility:
93     GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
94     break;
95   case VisibilityAttr::HiddenVisibility:
96     GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
97     break;
98   case VisibilityAttr::ProtectedVisibility:
99     GV->setVisibility(llvm::GlobalValue::ProtectedVisibility);
100     break;
101   }
102 }
103 
104 /// AddGlobalCtor - Add a function to the list that will be called before
105 /// main() runs.
106 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
107   // TODO: Type coercion of void()* types.
108   GlobalCtors.push_back(Ctor);
109 }
110 
111 /// EmitGlobalCtors - Generates the array of contsturctor functions to be
112 /// called on module load, if any have been registered with AddGlobalCtor.
113 void CodeGenModule::EmitGlobalCtors() {
114   if (GlobalCtors.empty()) return;
115 
116   // Get the type of @llvm.global_ctors
117   std::vector<const llvm::Type*> CtorFields;
118   CtorFields.push_back(llvm::IntegerType::get(32));
119   // Constructor function type
120   std::vector<const llvm::Type*> VoidArgs;
121   llvm::FunctionType* CtorFuncTy =
122     llvm::FunctionType::get(llvm::Type::VoidTy, VoidArgs, false);
123 
124   // i32, function type pair
125   const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
126   llvm::StructType* CtorStructTy =
127   llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
128   // Array of fields
129   llvm::ArrayType* GlobalCtorsTy =
130     llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
131 
132   // Define the global variable
133   llvm::GlobalVariable *GlobalCtorsVal =
134     new llvm::GlobalVariable(GlobalCtorsTy, false,
135                              llvm::GlobalValue::AppendingLinkage,
136                              (llvm::Constant*)0, "llvm.global_ctors",
137                              &TheModule);
138 
139   // Populate the array
140   std::vector<llvm::Constant*> CtorValues;
141   llvm::Constant *MagicNumber =
142     llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
143   std::vector<llvm::Constant*> StructValues;
144   for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
145        E = GlobalCtors.end(); I != E; ++I) {
146     StructValues.clear();
147     StructValues.push_back(MagicNumber);
148     StructValues.push_back(*I);
149 
150     CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
151   }
152 
153   GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
154                                                           CtorValues));
155 }
156 
157 
158 
159 void CodeGenModule::EmitAnnotations() {
160   if (Annotations.empty())
161     return;
162 
163   // Create a new global variable for the ConstantStruct in the Module.
164   llvm::Constant *Array =
165   llvm::ConstantArray::get(llvm::ArrayType::get(Annotations[0]->getType(),
166                                                 Annotations.size()),
167                            Annotations);
168   llvm::GlobalValue *gv =
169   new llvm::GlobalVariable(Array->getType(), false,
170                            llvm::GlobalValue::AppendingLinkage, Array,
171                            "llvm.global.annotations", &TheModule);
172   gv->setSection("llvm.metadata");
173 }
174 
175 /// ReplaceMapValuesWith - This is a really slow and bad function that
176 /// searches for any entries in GlobalDeclMap that point to OldVal, changing
177 /// them to point to NewVal.  This is badbadbad, FIXME!
178 void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
179                                          llvm::Constant *NewVal) {
180   for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
181        I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
182     if (I->second == OldVal) I->second = NewVal;
183 }
184 
185 
186 llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
187                                                      bool isDefinition) {
188   // See if it is already in the map.  If so, just return it.
189   llvm::Constant *&Entry = GlobalDeclMap[D];
190   if (!isDefinition && Entry) return Entry;
191 
192   const llvm::Type *Ty = getTypes().ConvertType(D->getType());
193 
194   // Check to see if the function already exists.
195   llvm::Function *F = getModule().getFunction(D->getName());
196   const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
197 
198   // If it doesn't already exist, just create and return an entry.
199   if (F == 0) {
200     // FIXME: param attributes for sext/zext etc.
201     F = llvm::Function::Create(FTy, llvm::Function::ExternalLinkage,
202                                D->getName(), &getModule());
203 
204     // Set the appropriate calling convention for the Function.
205     if (D->getAttr<FastCallAttr>())
206       F->setCallingConv(llvm::CallingConv::Fast);
207     return Entry = F;
208   }
209 
210   // If the pointer type matches, just return it.
211   llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
212   if (PFTy == F->getType()) return Entry = F;
213 
214   // If this isn't a definition, just return it casted to the right type.
215   if (!isDefinition)
216     return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
217 
218   // Otherwise, we have a definition after a prototype with the wrong type.
219   // F is the Function* for the one with the wrong type, we must make a new
220   // Function* and update everything that used F (a declaration) with the new
221   // Function* (which will be a definition).
222   //
223   // This happens if there is a prototype for a function (e.g. "int f()") and
224   // then a definition of a different type (e.g. "int f(int x)").  Start by
225   // making a new function of the correct type, RAUW, then steal the name.
226   llvm::Function *NewFn = llvm::Function::Create(FTy,
227                                              llvm::Function::ExternalLinkage,
228                                              "", &getModule());
229   NewFn->takeName(F);
230 
231   // Replace uses of F with the Function we will endow with a body.
232   llvm::Constant *NewPtrForOldDecl =
233     llvm::ConstantExpr::getBitCast(NewFn, F->getType());
234   F->replaceAllUsesWith(NewPtrForOldDecl);
235 
236   // FIXME: Update the globaldeclmap for the previous decl of this name.  We
237   // really want a way to walk all of these, but we don't have it yet.  This
238   // is incredibly slow!
239   ReplaceMapValuesWith(F, NewPtrForOldDecl);
240 
241   // Ok, delete the old function now, which is dead.
242   assert(F->isDeclaration() && "Shouldn't replace non-declaration");
243   F->eraseFromParent();
244 
245   // Return the new function which has the right type.
246   return Entry = NewFn;
247 }
248 
249 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
250                                                   bool isDefinition) {
251   assert(D->hasGlobalStorage() && "Not a global variable");
252   assert(!isDefinition && "This shouldn't be called for definitions!");
253 
254   // See if it is already in the map.
255   llvm::Constant *&Entry = GlobalDeclMap[D];
256   if (Entry) return Entry;
257 
258   QualType ASTTy = D->getType();
259   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
260 
261   // Check to see if the global already exists.
262   llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
263 
264   // If it doesn't already exist, just create and return an entry.
265   if (GV == 0) {
266     return Entry = new llvm::GlobalVariable(Ty, false,
267                                             llvm::GlobalValue::ExternalLinkage,
268                                             0, D->getName(), &getModule(), 0,
269                                             ASTTy.getAddressSpace());
270   }
271 
272   // Otherwise, it already exists; return the existing version
273   llvm::PointerType *PTy = llvm::PointerType::get(Ty, ASTTy.getAddressSpace());
274   return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
275 }
276 
277 void CodeGenModule::EmitObjCMethod(const ObjCMethodDecl *OMD) {
278   // If this is not a prototype, emit the body.
279   if (OMD->getBody())
280     CodeGenFunction(*this).GenerateObjCMethod(OMD);
281 }
282 
283 void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
284   // If this is not a prototype, emit the body.
285   if (!FD->isThisDeclarationADefinition())
286     return;
287 
288   // If the function is a static, defer code generation until later so we can
289   // easily omit unused statics.
290   if (FD->getStorageClass() != FunctionDecl::Static) {
291     CodeGenFunction(*this).GenerateCode(FD);
292     return;
293   }
294 
295   StaticDecls.push_back(FD);
296 }
297 
298 void CodeGenModule::EmitStatics() {
299   // Emit code for each used static decl encountered.  Since a previously unused
300   // static decl may become used during the generation of code for a static
301   // function, iterate until no changes are made.
302   bool Changed;
303   do {
304     Changed = false;
305     for (unsigned i = 0, e = StaticDecls.size(); i != e; ++i) {
306       const Decl *D = StaticDecls[i];
307 
308       // Check if we have used a decl with the same name
309       // FIXME: The AST should have some sort of aggregate decls or
310       // global symbol map.
311       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
312         if (!getModule().getFunction(FD->getName()))
313           continue;
314       } else {
315         if (!getModule().getNamedGlobal(cast<VarDecl>(D)->getName()))
316           continue;
317       }
318 
319       // If this is a function decl, generate code for the static function if it
320       // has a body.  Otherwise, we must have a var decl for a static global
321       // variable.
322       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
323         if (FD->getBody())
324           CodeGenFunction(*this).GenerateCode(FD);
325       } else {
326         EmitGlobalVarInit(cast<VarDecl>(D));
327       }
328       // Erase the used decl from the list.
329       StaticDecls[i] = StaticDecls.back();
330       StaticDecls.pop_back();
331       --i;
332       --e;
333 
334       // Remember that we made a change.
335       Changed = true;
336     }
337   } while (Changed);
338 }
339 
340 llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
341   return EmitConstantExpr(Expr);
342 }
343 
344 /// EmitAnnotateAttr - Generate the llvm::ConstantStruct which contains the
345 /// annotation information for a given GlobalValue.  The annotation struct is
346 /// {i8 *, i8 *, i8 *, i32}.  The first field is a constant expression, the
347 /// GlobalValue being annotated.  The second filed is thee constant string
348 /// created from the AnnotateAttr's annotation.  The third field is a constant
349 /// string containing the name of the translation unit.  The fourth field is
350 /// the line number in the file of the annotated value declaration.
351 ///
352 /// FIXME: this does not unique the annotation string constants, as llvm-gcc
353 ///        appears to.
354 ///
355 llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
356                                                 const AnnotateAttr *AA,
357                                                 unsigned LineNo) {
358   llvm::Module *M = &getModule();
359 
360   // get [N x i8] constants for the annotation string, and the filename string
361   // which are the 2nd and 3rd elements of the global annotation structure.
362   const llvm::Type *SBP = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
363   llvm::Constant *anno = llvm::ConstantArray::get(AA->getAnnotation(), true);
364   llvm::Constant *unit = llvm::ConstantArray::get(M->getModuleIdentifier(),
365                                                   true);
366 
367   // Get the two global values corresponding to the ConstantArrays we just
368   // created to hold the bytes of the strings.
369   llvm::GlobalValue *annoGV =
370   new llvm::GlobalVariable(anno->getType(), false,
371                            llvm::GlobalValue::InternalLinkage, anno,
372                            GV->getName() + ".str", M);
373   // translation unit name string, emitted into the llvm.metadata section.
374   llvm::GlobalValue *unitGV =
375   new llvm::GlobalVariable(unit->getType(), false,
376                            llvm::GlobalValue::InternalLinkage, unit, ".str", M);
377 
378   // Create the ConstantStruct that is the global annotion.
379   llvm::Constant *Fields[4] = {
380     llvm::ConstantExpr::getBitCast(GV, SBP),
381     llvm::ConstantExpr::getBitCast(annoGV, SBP),
382     llvm::ConstantExpr::getBitCast(unitGV, SBP),
383     llvm::ConstantInt::get(llvm::Type::Int32Ty, LineNo)
384   };
385   return llvm::ConstantStruct::get(Fields, 4, false);
386 }
387 
388 void CodeGenModule::EmitGlobalVar(const VarDecl *D) {
389   // If the VarDecl is a static, defer code generation until later so we can
390   // easily omit unused statics.
391   if (D->getStorageClass() == VarDecl::Static) {
392     StaticDecls.push_back(D);
393     return;
394   }
395 
396   // If this is just a forward declaration of the variable, don't emit it now,
397   // allow it to be emitted lazily on its first use.
398   if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
399     return;
400 
401   EmitGlobalVarInit(D);
402 }
403 
404 void CodeGenModule::EmitGlobalVarInit(const VarDecl *D) {
405   assert(D->hasGlobalStorage() && "Not a global variable");
406 
407   llvm::Constant *Init = 0;
408   QualType ASTTy = D->getType();
409   const llvm::Type *VarTy = getTypes().ConvertTypeForMem(ASTTy);
410   const llvm::Type *VarPtrTy =
411       llvm::PointerType::get(VarTy, ASTTy.getAddressSpace());
412 
413   if (D->getInit() == 0) {
414     // This is a tentative definition; tentative definitions are
415     // implicitly initialized with { 0 }
416     const llvm::Type* InitTy;
417     if (ASTTy->isIncompleteArrayType()) {
418       // An incomplete array is normally [ TYPE x 0 ], but we need
419       // to fix it to [ TYPE x 1 ].
420       const llvm::ArrayType* ATy = cast<llvm::ArrayType>(VarTy);
421       InitTy = llvm::ArrayType::get(ATy->getElementType(), 1);
422     } else {
423       InitTy = VarTy;
424     }
425     Init = llvm::Constant::getNullValue(InitTy);
426   } else {
427     Init = EmitGlobalInit(D->getInit());
428   }
429   const llvm::Type* InitType = Init->getType();
430 
431   llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
432 
433   if (!GV) {
434     GV = new llvm::GlobalVariable(InitType, false,
435                                   llvm::GlobalValue::ExternalLinkage,
436                                   0, D->getName(), &getModule(), 0,
437                                   ASTTy.getAddressSpace());
438   } else if (GV->getType()->getElementType() != InitType ||
439              GV->getType()->getAddressSpace() != ASTTy.getAddressSpace()) {
440     // We have a definition after a prototype with the wrong type.
441     // We must make a new GlobalVariable* and update everything that used OldGV
442     // (a declaration or tentative definition) with the new GlobalVariable*
443     // (which will be a definition).
444     //
445     // This happens if there is a prototype for a global (e.g. "extern int x[];")
446     // and then a definition of a different type (e.g. "int x[10];"). This also
447     // happens when an initializer has a different type from the type of the
448     // global (this happens with unions).
449     //
450     // FIXME: This also ends up happening if there's a definition followed by
451     // a tentative definition!  (Although Sema rejects that construct
452     // at the moment.)
453 
454     // Save the old global
455     llvm::GlobalVariable *OldGV = GV;
456 
457     // Make a new global with the correct type
458     GV = new llvm::GlobalVariable(InitType, false,
459                                   llvm::GlobalValue::ExternalLinkage,
460                                   0, D->getName(), &getModule(), 0,
461                                   ASTTy.getAddressSpace());
462     // Steal the name of the old global
463     GV->takeName(OldGV);
464 
465     // Replace all uses of the old global with the new global
466     llvm::Constant *NewPtrForOldDecl =
467         llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
468     OldGV->replaceAllUsesWith(NewPtrForOldDecl);
469     // Make sure we don't keep around any stale references to globals
470     // FIXME: This is really slow; we need a better way to walk all
471     // the decls with the same name
472     ReplaceMapValuesWith(OldGV, NewPtrForOldDecl);
473 
474     // Erase the old global, since it is no longer used.
475     OldGV->eraseFromParent();
476   }
477 
478   GlobalDeclMap[D] = llvm::ConstantExpr::getBitCast(GV, VarPtrTy);
479 
480   if (const AnnotateAttr *AA = D->getAttr<AnnotateAttr>()) {
481     SourceManager &SM = Context.getSourceManager();
482     AddAnnotation(EmitAnnotateAttr(GV, AA,
483                                    SM.getLogicalLineNumber(D->getLocation())));
484   }
485 
486   GV->setInitializer(Init);
487 
488   // FIXME: This is silly; getTypeAlign should just work for incomplete arrays
489   unsigned Align;
490   if (const IncompleteArrayType* IAT = D->getType()->getAsIncompleteArrayType())
491     Align = Context.getTypeAlign(IAT->getElementType());
492   else
493     Align = Context.getTypeAlign(D->getType());
494   if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) {
495     Align = std::max(Align, AA->getAlignment());
496   }
497   GV->setAlignment(Align / 8);
498 
499   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
500     setVisibility(GV, attr->getVisibility());
501   // FIXME: else handle -fvisibility
502 
503   // Set the llvm linkage type as appropriate.
504   if (D->getStorageClass() == VarDecl::Static)
505     GV->setLinkage(llvm::Function::InternalLinkage);
506   else if (D->getAttr<DLLImportAttr>())
507     GV->setLinkage(llvm::Function::DLLImportLinkage);
508   else if (D->getAttr<DLLExportAttr>())
509     GV->setLinkage(llvm::Function::DLLExportLinkage);
510   else if (D->getAttr<WeakAttr>())
511     GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
512   else {
513     // FIXME: This isn't right.  This should handle common linkage and other
514     // stuff.
515     switch (D->getStorageClass()) {
516     case VarDecl::Static: assert(0 && "This case handled above");
517     case VarDecl::Auto:
518     case VarDecl::Register:
519       assert(0 && "Can't have auto or register globals");
520     case VarDecl::None:
521       if (!D->getInit())
522         GV->setLinkage(llvm::GlobalVariable::CommonLinkage);
523       break;
524     case VarDecl::Extern:
525     case VarDecl::PrivateExtern:
526       // todo: common
527       break;
528     }
529   }
530 }
531 
532 /// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
533 /// declarator chain.
534 void CodeGenModule::EmitGlobalVarDeclarator(const VarDecl *D) {
535   for (; D; D = cast_or_null<VarDecl>(D->getNextDeclarator()))
536     if (D->isFileVarDecl())
537       EmitGlobalVar(D);
538 }
539 
540 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
541   // Make sure that this type is translated.
542   Types.UpdateCompletedType(TD);
543 }
544 
545 
546 /// getBuiltinLibFunction
547 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
548   if (BuiltinID > BuiltinFunctions.size())
549     BuiltinFunctions.resize(BuiltinID);
550 
551   // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
552   // a slot for it.
553   assert(BuiltinID && "Invalid Builtin ID");
554   llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
555   if (FunctionSlot)
556     return FunctionSlot;
557 
558   assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
559 
560   // Get the name, skip over the __builtin_ prefix.
561   const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
562 
563   // Get the type for the builtin.
564   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
565   const llvm::FunctionType *Ty =
566     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
567 
568   // FIXME: This has a serious problem with code like this:
569   //  void abs() {}
570   //    ... __builtin_abs(x);
571   // The two versions of abs will collide.  The fix is for the builtin to win,
572   // and for the existing one to be turned into a constantexpr cast of the
573   // builtin.  In the case where the existing one is a static function, it
574   // should just be renamed.
575   if (llvm::Function *Existing = getModule().getFunction(Name)) {
576     if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
577       return FunctionSlot = Existing;
578     assert(Existing == 0 && "FIXME: Name collision");
579   }
580 
581   // FIXME: param attributes for sext/zext etc.
582   return FunctionSlot =
583     llvm::Function::Create(Ty, llvm::Function::ExternalLinkage, Name,
584                            &getModule());
585 }
586 
587 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
588                                             unsigned NumTys) {
589   return llvm::Intrinsic::getDeclaration(&getModule(),
590                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
591 }
592 
593 llvm::Function *CodeGenModule::getMemCpyFn() {
594   if (MemCpyFn) return MemCpyFn;
595   llvm::Intrinsic::ID IID;
596   switch (Context.Target.getPointerWidth(0)) {
597   default: assert(0 && "Unknown ptr width");
598   case 32: IID = llvm::Intrinsic::memcpy_i32; break;
599   case 64: IID = llvm::Intrinsic::memcpy_i64; break;
600   }
601   return MemCpyFn = getIntrinsic(IID);
602 }
603 
604 llvm::Function *CodeGenModule::getMemMoveFn() {
605   if (MemMoveFn) return MemMoveFn;
606   llvm::Intrinsic::ID IID;
607   switch (Context.Target.getPointerWidth(0)) {
608   default: assert(0 && "Unknown ptr width");
609   case 32: IID = llvm::Intrinsic::memmove_i32; break;
610   case 64: IID = llvm::Intrinsic::memmove_i64; break;
611   }
612   return MemMoveFn = getIntrinsic(IID);
613 }
614 
615 llvm::Function *CodeGenModule::getMemSetFn() {
616   if (MemSetFn) return MemSetFn;
617   llvm::Intrinsic::ID IID;
618   switch (Context.Target.getPointerWidth(0)) {
619   default: assert(0 && "Unknown ptr width");
620   case 32: IID = llvm::Intrinsic::memset_i32; break;
621   case 64: IID = llvm::Intrinsic::memset_i64; break;
622   }
623   return MemSetFn = getIntrinsic(IID);
624 }
625 
626 llvm::Constant *CodeGenModule::
627 GetAddrOfConstantCFString(const std::string &str) {
628   llvm::StringMapEntry<llvm::Constant *> &Entry =
629     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
630 
631   if (Entry.getValue())
632     return Entry.getValue();
633 
634   std::vector<llvm::Constant*> Fields;
635 
636   if (!CFConstantStringClassRef) {
637     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
638     Ty = llvm::ArrayType::get(Ty, 0);
639 
640     CFConstantStringClassRef =
641       new llvm::GlobalVariable(Ty, false,
642                                llvm::GlobalVariable::ExternalLinkage, 0,
643                                "__CFConstantStringClassReference",
644                                &getModule());
645   }
646 
647   // Class pointer.
648   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
649   llvm::Constant *Zeros[] = { Zero, Zero };
650   llvm::Constant *C =
651     llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
652   Fields.push_back(C);
653 
654   // Flags.
655   const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
656   Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
657 
658   // String pointer.
659   C = llvm::ConstantArray::get(str);
660   C = new llvm::GlobalVariable(C->getType(), true,
661                                llvm::GlobalValue::InternalLinkage,
662                                C, ".str", &getModule());
663 
664   C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
665   Fields.push_back(C);
666 
667   // String length.
668   Ty = getTypes().ConvertType(getContext().LongTy);
669   Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
670 
671   // The struct.
672   Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
673   C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
674   llvm::GlobalVariable *GV =
675     new llvm::GlobalVariable(C->getType(), true,
676                              llvm::GlobalVariable::InternalLinkage,
677                              C, "", &getModule());
678   GV->setSection("__DATA,__cfstring");
679   Entry.setValue(GV);
680   return GV;
681 }
682 
683 /// GenerateWritableString -- Creates storage for a string literal.
684 static llvm::Constant *GenerateStringLiteral(const std::string &str,
685                                              bool constant,
686                                              CodeGenModule &CGM) {
687   // Create Constant for this string literal
688   llvm::Constant *C=llvm::ConstantArray::get(str);
689 
690   // Create a global variable for this string
691   C = new llvm::GlobalVariable(C->getType(), constant,
692                                llvm::GlobalValue::InternalLinkage,
693                                C, ".str", &CGM.getModule());
694   return C;
695 }
696 
697 /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
698 /// array containing the literal.  The result is pointer to array type.
699 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
700   // Don't share any string literals if writable-strings is turned on.
701   if (Features.WritableStrings)
702     return GenerateStringLiteral(str, false, *this);
703 
704   llvm::StringMapEntry<llvm::Constant *> &Entry =
705   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
706 
707   if (Entry.getValue())
708       return Entry.getValue();
709 
710   // Create a global variable for this.
711   llvm::Constant *C = GenerateStringLiteral(str, true, *this);
712   Entry.setValue(C);
713   return C;
714 }
715