xref: /llvm-project/clang/lib/CodeGen/CodeGenModule.cpp (revision 554221e9fb01bdeb6986313d432336e852f25039)
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 "CodeGenModule.h"
15 #include "CodeGenFunction.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/Basic/Diagnostic.h"
19 #include "clang/Basic/LangOptions.h"
20 #include "clang/Basic/TargetInfo.h"
21 #include "llvm/CallingConv.h"
22 #include "llvm/Constants.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Module.h"
25 #include "llvm/Intrinsics.h"
26 #include <algorithm>
27 using namespace clang;
28 using namespace CodeGen;
29 
30 
31 CodeGenModule::CodeGenModule(ASTContext &C, const LangOptions &LO,
32                              llvm::Module &M, const llvm::TargetData &TD,
33                              Diagnostic &diags)
34   : Context(C), Features(LO), TheModule(M), TheTargetData(TD), Diags(diags),
35     Types(C, M, TD), MemCpyFn(0), MemSetFn(0), CFConstantStringClassRef(0) {
36   //TODO: Make this selectable at runtime
37   Runtime = CreateObjCRuntime(M);
38 }
39 
40 CodeGenModule::~CodeGenModule() {
41   EmitGlobalCtors();
42   delete Runtime;
43 }
44 
45 /// WarnUnsupported - Print out a warning that codegen doesn't support the
46 /// specified stmt yet.
47 void CodeGenModule::WarnUnsupported(const Stmt *S, const char *Type) {
48   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
49                                                "cannot codegen this %0 yet");
50   SourceRange Range = S->getSourceRange();
51   std::string Msg = Type;
52   getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID,
53                     &Msg, 1, &Range, 1);
54 }
55 
56 /// WarnUnsupported - Print out a warning that codegen doesn't support the
57 /// specified decl yet.
58 void CodeGenModule::WarnUnsupported(const Decl *D, const char *Type) {
59   unsigned DiagID = getDiags().getCustomDiagID(Diagnostic::Warning,
60                                                "cannot codegen this %0 yet");
61   std::string Msg = Type;
62   getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID,
63                     &Msg, 1);
64 }
65 
66 /// AddGlobalCtor - Add a function to the list that will be called before
67 /// main() runs.
68 void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor) {
69   // TODO: Type coercion of void()* types.
70   GlobalCtors.push_back(Ctor);
71 }
72 
73 void CodeGenModule::EmitGlobalCtors() {
74   // Get the type of @llvm.global_ctors
75   std::vector<const llvm::Type*> CtorFields;
76   CtorFields.push_back(llvm::IntegerType::get(32));
77   // Constructor function type
78   std::vector<const llvm::Type*> VoidArgs;
79   llvm::FunctionType* CtorFuncTy = llvm::FunctionType::get(
80     llvm::Type::VoidTy,
81     VoidArgs,
82     false);
83   // i32, function type pair
84   const llvm::Type *FPType = llvm::PointerType::getUnqual(CtorFuncTy);
85   llvm::StructType* CtorStructTy =
86   llvm::StructType::get(llvm::Type::Int32Ty, FPType, NULL);
87   // Array of fields
88   llvm::ArrayType* GlobalCtorsTy =
89     llvm::ArrayType::get(CtorStructTy, GlobalCtors.size());
90 
91   // Define the global variable
92   llvm::GlobalVariable *GlobalCtorsVal =
93     new llvm::GlobalVariable(GlobalCtorsTy, false,
94                              llvm::GlobalValue::AppendingLinkage,
95                              (llvm::Constant*)0, "llvm.global_ctors",
96                              &TheModule);
97 
98   // Populate the array
99   std::vector<llvm::Constant*> CtorValues;
100   llvm::Constant *MagicNumber =
101     llvm::ConstantInt::get(llvm::Type::Int32Ty, 65535, false);
102   std::vector<llvm::Constant*> StructValues;
103   for (std::vector<llvm::Constant*>::iterator I = GlobalCtors.begin(),
104        E = GlobalCtors.end(); I != E; ++I) {
105     StructValues.clear();
106     StructValues.push_back(MagicNumber);
107     StructValues.push_back(*I);
108 
109     CtorValues.push_back(llvm::ConstantStruct::get(CtorStructTy, StructValues));
110   }
111 
112   GlobalCtorsVal->setInitializer(llvm::ConstantArray::get(GlobalCtorsTy,
113                                                           CtorValues));
114 
115 }
116 
117 /// ReplaceMapValuesWith - This is a really slow and bad function that
118 /// searches for any entries in GlobalDeclMap that point to OldVal, changing
119 /// them to point to NewVal.  This is badbadbad, FIXME!
120 void CodeGenModule::ReplaceMapValuesWith(llvm::Constant *OldVal,
121                                          llvm::Constant *NewVal) {
122   for (llvm::DenseMap<const Decl*, llvm::Constant*>::iterator
123        I = GlobalDeclMap.begin(), E = GlobalDeclMap.end(); I != E; ++I)
124     if (I->second == OldVal) I->second = NewVal;
125 }
126 
127 
128 llvm::Constant *CodeGenModule::GetAddrOfFunctionDecl(const FunctionDecl *D,
129                                                      bool isDefinition) {
130   // See if it is already in the map.  If so, just return it.
131   llvm::Constant *&Entry = GlobalDeclMap[D];
132   if (Entry) return Entry;
133 
134   const llvm::Type *Ty = getTypes().ConvertType(D->getType());
135 
136   // Check to see if the function already exists.
137   llvm::Function *F = getModule().getFunction(D->getName());
138   const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
139 
140   // If it doesn't already exist, just create and return an entry.
141   if (F == 0) {
142     // FIXME: param attributes for sext/zext etc.
143     F = new llvm::Function(FTy, llvm::Function::ExternalLinkage, D->getName(),
144                            &getModule());
145 
146     // Set the appropriate calling convention for the Function.
147     if (D->getAttr<FastCallAttr>())
148       F->setCallingConv(llvm::CallingConv::Fast);
149     return Entry = F;
150   }
151 
152   // If the pointer type matches, just return it.
153   llvm::Type *PFTy = llvm::PointerType::getUnqual(Ty);
154   if (PFTy == F->getType()) return Entry = F;
155 
156   // If this isn't a definition, just return it casted to the right type.
157   if (!isDefinition)
158     return Entry = llvm::ConstantExpr::getBitCast(F, PFTy);
159 
160   // Otherwise, we have a definition after a prototype with the wrong type.
161   // F is the Function* for the one with the wrong type, we must make a new
162   // Function* and update everything that used F (a declaration) with the new
163   // Function* (which will be a definition).
164   //
165   // This happens if there is a prototype for a function (e.g. "int f()") and
166   // then a definition of a different type (e.g. "int f(int x)").  Start by
167   // making a new function of the correct type, RAUW, then steal the name.
168   llvm::Function *NewFn = new llvm::Function(FTy,
169                                              llvm::Function::ExternalLinkage,
170                                              "", &getModule());
171   NewFn->takeName(F);
172 
173   // Replace uses of F with the Function we will endow with a body.
174   llvm::Constant *NewPtrForOldDecl =
175     llvm::ConstantExpr::getBitCast(NewFn, F->getType());
176   F->replaceAllUsesWith(NewPtrForOldDecl);
177 
178   // FIXME: Update the globaldeclmap for the previous decl of this name.  We
179   // really want a way to walk all of these, but we don't have it yet.  This
180   // is incredibly slow!
181   ReplaceMapValuesWith(F, NewPtrForOldDecl);
182 
183   // Ok, delete the old function now, which is dead.
184   assert(F->isDeclaration() && "Shouldn't replace non-declaration");
185   F->eraseFromParent();
186 
187   // Return the new function which has the right type.
188   return Entry = NewFn;
189 }
190 
191 static bool IsZeroElementArray(const llvm::Type *Ty) {
192   if (const llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(Ty))
193     return ATy->getNumElements() == 0;
194   return false;
195 }
196 
197 llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
198                                                   bool isDefinition) {
199   assert(D->hasGlobalStorage() && "Not a global variable");
200 
201   // See if it is already in the map.
202   llvm::Constant *&Entry = GlobalDeclMap[D];
203   if (Entry) return Entry;
204 
205   QualType ASTTy = D->getType();
206   const llvm::Type *Ty = getTypes().ConvertTypeForMem(ASTTy);
207 
208   // Check to see if the global already exists.
209   llvm::GlobalVariable *GV = getModule().getGlobalVariable(D->getName(), true);
210 
211   // If it doesn't already exist, just create and return an entry.
212   if (GV == 0) {
213     return Entry = new llvm::GlobalVariable(Ty, false,
214                                             llvm::GlobalValue::ExternalLinkage,
215                                             0, D->getName(), &getModule(), 0,
216                                             ASTTy.getAddressSpace());
217   }
218 
219   // If the pointer type matches, just return it.
220   llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
221   if (PTy == GV->getType()) return Entry = GV;
222 
223   // If this isn't a definition, just return it casted to the right type.
224   if (!isDefinition)
225     return Entry = llvm::ConstantExpr::getBitCast(GV, PTy);
226 
227 
228   // Otherwise, we have a definition after a prototype with the wrong type.
229   // GV is the GlobalVariable* for the one with the wrong type, we must make a
230   /// new GlobalVariable* and update everything that used GV (a declaration)
231   // with the new GlobalVariable* (which will be a definition).
232   //
233   // This happens if there is a prototype for a global (e.g. "extern int x[];")
234   // and then a definition of a different type (e.g. "int x[10];").  Start by
235   // making a new global of the correct type, RAUW, then steal the name.
236   llvm::GlobalVariable *NewGV =
237     new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage,
238                              0, D->getName(), &getModule(), 0,
239                              ASTTy.getAddressSpace());
240   NewGV->takeName(GV);
241 
242   // Replace uses of GV with the globalvalue we will endow with a body.
243   llvm::Constant *NewPtrForOldDecl =
244     llvm::ConstantExpr::getBitCast(NewGV, GV->getType());
245   GV->replaceAllUsesWith(NewPtrForOldDecl);
246 
247   // FIXME: Update the globaldeclmap for the previous decl of this name.  We
248   // really want a way to walk all of these, but we don't have it yet.  This
249   // is incredibly slow!
250   ReplaceMapValuesWith(GV, NewPtrForOldDecl);
251 
252   // Verify that GV was a declaration or something like x[] which turns into
253   // [0 x type].
254   assert((GV->isDeclaration() ||
255           IsZeroElementArray(GV->getType()->getElementType())) &&
256          "Shouldn't replace non-declaration");
257 
258   // Ok, delete the old global now, which is dead.
259   GV->eraseFromParent();
260 
261   // Return the new global which has the right type.
262   return Entry = NewGV;
263 }
264 
265 
266 void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
267   // If this is not a prototype, emit the body.
268   if (FD->getBody())
269     CodeGenFunction(*this).GenerateCode(FD);
270 }
271 
272 llvm::Constant *CodeGenModule::EmitGlobalInit(const Expr *Expr) {
273   return EmitConstantExpr(Expr);
274 }
275 
276 void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
277   // If this is just a forward declaration of the variable, don't emit it now,
278   // allow it to be emitted lazily on its first use.
279   if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
280     return;
281 
282   // Get the global, forcing it to be a direct reference.
283   llvm::GlobalVariable *GV =
284     cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, true));
285 
286   // Convert the initializer, or use zero if appropriate.
287   llvm::Constant *Init = 0;
288   if (D->getInit() == 0) {
289     Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
290   } else if (D->getType()->isIntegerType()) {
291     llvm::APSInt Value(static_cast<uint32_t>(
292       getContext().getTypeSize(D->getInit()->getType())));
293     if (D->getInit()->isIntegerConstantExpr(Value, Context))
294       Init = llvm::ConstantInt::get(Value);
295   }
296 
297   if (!Init)
298     Init = EmitGlobalInit(D->getInit());
299 
300   assert(GV->getType()->getElementType() == Init->getType() &&
301          "Initializer codegen type mismatch!");
302   GV->setInitializer(Init);
303 
304   if (const VisibilityAttr *attr = D->getAttr<VisibilityAttr>())
305     GV->setVisibility(attr->getVisibility());
306   // FIXME: else handle -fvisibility
307 
308   // Set the llvm linkage type as appropriate.
309   if (D->getAttr<DLLImportAttr>())
310     GV->setLinkage(llvm::Function::DLLImportLinkage);
311   else if (D->getAttr<DLLExportAttr>())
312     GV->setLinkage(llvm::Function::DLLExportLinkage);
313   else if (D->getAttr<WeakAttr>()) {
314     GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
315 
316   } else {
317     // FIXME: This isn't right.  This should handle common linkage and other
318     // stuff.
319     switch (D->getStorageClass()) {
320     case VarDecl::Auto:
321     case VarDecl::Register:
322       assert(0 && "Can't have auto or register globals");
323     case VarDecl::None:
324       if (!D->getInit())
325         GV->setLinkage(llvm::GlobalVariable::WeakLinkage);
326       break;
327     case VarDecl::Extern:
328     case VarDecl::PrivateExtern:
329       // todo: common
330       break;
331     case VarDecl::Static:
332       GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
333       break;
334     }
335   }
336 }
337 
338 /// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
339 /// declarator chain.
340 void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
341   for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
342     EmitGlobalVar(D);
343 }
344 
345 void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
346   // Make sure that this type is translated.
347   Types.UpdateCompletedType(TD);
348 }
349 
350 
351 /// getBuiltinLibFunction
352 llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
353   if (BuiltinID > BuiltinFunctions.size())
354     BuiltinFunctions.resize(BuiltinID);
355 
356   // Cache looked up functions.  Since builtin id #0 is invalid we don't reserve
357   // a slot for it.
358   assert(BuiltinID && "Invalid Builtin ID");
359   llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID-1];
360   if (FunctionSlot)
361     return FunctionSlot;
362 
363   assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
364 
365   // Get the name, skip over the __builtin_ prefix.
366   const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
367 
368   // Get the type for the builtin.
369   QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
370   const llvm::FunctionType *Ty =
371     cast<llvm::FunctionType>(getTypes().ConvertType(Type));
372 
373   // FIXME: This has a serious problem with code like this:
374   //  void abs() {}
375   //    ... __builtin_abs(x);
376   // The two versions of abs will collide.  The fix is for the builtin to win,
377   // and for the existing one to be turned into a constantexpr cast of the
378   // builtin.  In the case where the existing one is a static function, it
379   // should just be renamed.
380   if (llvm::Function *Existing = getModule().getFunction(Name)) {
381     if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
382       return FunctionSlot = Existing;
383     assert(Existing == 0 && "FIXME: Name collision");
384   }
385 
386   // FIXME: param attributes for sext/zext etc.
387   return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
388                                            Name, &getModule());
389 }
390 
391 llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,const llvm::Type **Tys,
392                                             unsigned NumTys) {
393   return llvm::Intrinsic::getDeclaration(&getModule(),
394                                          (llvm::Intrinsic::ID)IID, Tys, NumTys);
395 }
396 
397 llvm::Function *CodeGenModule::getMemCpyFn() {
398   if (MemCpyFn) return MemCpyFn;
399   llvm::Intrinsic::ID IID;
400   switch (Context.Target.getPointerWidth(0)) {
401   default: assert(0 && "Unknown ptr width");
402   case 32: IID = llvm::Intrinsic::memcpy_i32; break;
403   case 64: IID = llvm::Intrinsic::memcpy_i64; break;
404   }
405   return MemCpyFn = getIntrinsic(IID);
406 }
407 
408 llvm::Function *CodeGenModule::getMemSetFn() {
409   if (MemSetFn) return MemSetFn;
410   llvm::Intrinsic::ID IID;
411   switch (Context.Target.getPointerWidth(0)) {
412   default: assert(0 && "Unknown ptr width");
413   case 32: IID = llvm::Intrinsic::memset_i32; break;
414   case 64: IID = llvm::Intrinsic::memset_i64; break;
415   }
416   return MemSetFn = getIntrinsic(IID);
417 }
418 
419 llvm::Constant *CodeGenModule::
420 GetAddrOfConstantCFString(const std::string &str) {
421   llvm::StringMapEntry<llvm::Constant *> &Entry =
422     CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
423 
424   if (Entry.getValue())
425     return Entry.getValue();
426 
427   std::vector<llvm::Constant*> Fields;
428 
429   if (!CFConstantStringClassRef) {
430     const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
431     Ty = llvm::ArrayType::get(Ty, 0);
432 
433     CFConstantStringClassRef =
434       new llvm::GlobalVariable(Ty, false,
435                                llvm::GlobalVariable::ExternalLinkage, 0,
436                                "__CFConstantStringClassReference",
437                                &getModule());
438   }
439 
440   // Class pointer.
441   llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
442   llvm::Constant *Zeros[] = { Zero, Zero };
443   llvm::Constant *C =
444     llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
445   Fields.push_back(C);
446 
447   // Flags.
448   const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
449   Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
450 
451   // String pointer.
452   C = llvm::ConstantArray::get(str);
453   C = new llvm::GlobalVariable(C->getType(), true,
454                                llvm::GlobalValue::InternalLinkage,
455                                C, ".str", &getModule());
456 
457   C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
458   Fields.push_back(C);
459 
460   // String length.
461   Ty = getTypes().ConvertType(getContext().LongTy);
462   Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
463 
464   // The struct.
465   Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
466   C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
467   llvm::GlobalVariable *GV =
468     new llvm::GlobalVariable(C->getType(), true,
469                              llvm::GlobalVariable::InternalLinkage,
470                              C, "", &getModule());
471   GV->setSection("__DATA,__cfstring");
472   Entry.setValue(GV);
473   return GV;
474 }
475 
476 /// GenerateWritableString -- Creates storage for a string literal.
477 static llvm::Constant *GenerateStringLiteral(const std::string &str,
478                                              bool constant,
479                                              CodeGenModule &CGM) {
480   // Create Constant for this string literal
481   llvm::Constant *C=llvm::ConstantArray::get(str);
482 
483   // Create a global variable for this string
484   C = new llvm::GlobalVariable(C->getType(), constant,
485                                llvm::GlobalValue::InternalLinkage,
486                                C, ".str", &CGM.getModule());
487   return C;
488 }
489 
490 /// CodeGenModule::GetAddrOfConstantString -- returns a pointer to the character
491 /// array containing the literal.  The result is pointer to array type.
492 llvm::Constant *CodeGenModule::GetAddrOfConstantString(const std::string &str) {
493   // Don't share any string literals if writable-strings is turned on.
494   if (Features.WritableStrings)
495     return GenerateStringLiteral(str, false, *this);
496 
497   llvm::StringMapEntry<llvm::Constant *> &Entry =
498   ConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
499 
500   if (Entry.getValue())
501       return Entry.getValue();
502 
503   // Create a global variable for this.
504   llvm::Constant *C = GenerateStringLiteral(str, true, *this);
505   Entry.setValue(C);
506   return C;
507 }
508