blob: a596c08528dd828a8735a555bf8d94c4e3f8ccd0 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source 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/TargetInfo.h"
19#include "llvm/Constants.h"
20#include "llvm/DerivedTypes.h"
Chris Lattnerab862cc2007-08-31 04:31:45 +000021#include "llvm/Module.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "llvm/Intrinsics.h"
23using namespace clang;
24using namespace CodeGen;
25
26
27CodeGenModule::CodeGenModule(ASTContext &C, llvm::Module &M)
Anders Carlsson36a04872007-08-21 00:21:21 +000028 : Context(C), TheModule(M), Types(C, M), CFConstantStringClassRef(0) {}
Chris Lattner4b009652007-07-25 00:24:17 +000029
Steve Naroffcb597472007-09-13 21:41:19 +000030llvm::Constant *CodeGenModule::GetAddrOfGlobalDecl(const ValueDecl *D) {
Chris Lattner4b009652007-07-25 00:24:17 +000031 // See if it is already in the map.
32 llvm::Constant *&Entry = GlobalDeclMap[D];
33 if (Entry) return Entry;
34
35 QualType ASTTy = cast<ValueDecl>(D)->getType();
36 const llvm::Type *Ty = getTypes().ConvertType(ASTTy);
37 if (isa<FunctionDecl>(D)) {
38 const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
39 // FIXME: param attributes for sext/zext etc.
40 return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage,
41 D->getName(), &getModule());
42 }
43
44 assert(isa<FileVarDecl>(D) && "Unknown global decl!");
45
46 return Entry = new llvm::GlobalVariable(Ty, false,
47 llvm::GlobalValue::ExternalLinkage,
48 0, D->getName(), &getModule());
49}
50
51void CodeGenModule::EmitFunction(const FunctionDecl *FD) {
52 // If this is not a prototype, emit the body.
53 if (FD->getBody())
54 CodeGenFunction(*this).GenerateCode(FD);
55}
56
Devang Patel08a10cc2007-10-30 21:27:20 +000057llvm::Constant *CodeGenModule::EmitGlobalInit(const FileVarDecl *D,
58 llvm::GlobalVariable *GV) {
59
60 const InitListExpr *ILE = dyn_cast<InitListExpr>(D->getInit());
61 if (!ILE)
62 return 0;
63
64 unsigned NumInitElements = ILE->getNumInits();
65
66 assert ( ILE->getType()->isArrayType()
67 && "FIXME: Only Array initializers are supported");
68
69 std::vector<llvm::Constant*> ArrayElts;
70 const llvm::PointerType *APType = cast<llvm::PointerType>(GV->getType());
71 const llvm::ArrayType *AType =
72 cast<llvm::ArrayType>(APType->getElementType());
73
74 // Copy initializer elements.
75 unsigned i = 0;
76 for (i = 0; i < NumInitElements; ++i) {
77 assert (ILE->getInit(i)->getType()->isIntegerType()
78 && "Only IntegerType global array initializers are supported");
79 llvm::APSInt
80 Value(static_cast<uint32_t>
81 (getContext().getTypeSize(ILE->getInit(i)->getType(),
82 SourceLocation())));
83 if (ILE->getInit(i)->isIntegerConstantExpr(Value, Context)) {
84 llvm::Constant *C = llvm::ConstantInt::get(Value);
85 ArrayElts.push_back(C);
86 }
87 }
88
89 // Initialize remaining array elements.
90 unsigned NumArrayElements = AType->getNumElements();
91 const llvm::Type *AElemTy = AType->getElementType();
92 for (; i < NumArrayElements; ++i)
93 ArrayElts.push_back(llvm::Constant::getNullValue(AElemTy));
94
95 return llvm::ConstantArray::get(AType, ArrayElts);
96}
97
Chris Lattner4b009652007-07-25 00:24:17 +000098void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
99 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalDecl(D));
100
101 // If the storage class is external and there is no initializer, just leave it
102 // as a declaration.
103 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
104 return;
105
106 // Otherwise, convert the initializer, or use zero if appropriate.
107 llvm::Constant *Init = 0;
108 if (D->getInit() == 0) {
109 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
110 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +0000111 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +0000112 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +0000113 if (D->getInit()->isIntegerConstantExpr(Value, Context))
114 Init = llvm::ConstantInt::get(Value);
115 }
Devang Patel8b5f5302007-10-26 16:31:40 +0000116
Devang Patel08a10cc2007-10-30 21:27:20 +0000117 if (!Init)
118 Init = EmitGlobalInit(D, GV);
Devang Patel8b5f5302007-10-26 16:31:40 +0000119
Devang Patel08a10cc2007-10-30 21:27:20 +0000120 assert(Init && "FIXME: Global variable initializers unimp!");
Chris Lattner4b009652007-07-25 00:24:17 +0000121
122 GV->setInitializer(Init);
123
124 // Set the llvm linkage type as appropriate.
125 // FIXME: This isn't right. This should handle common linkage and other
126 // stuff.
127 switch (D->getStorageClass()) {
128 case VarDecl::Auto:
129 case VarDecl::Register:
130 assert(0 && "Can't have auto or register globals");
131 case VarDecl::None:
132 case VarDecl::Extern:
133 // todo: common
134 break;
135 case VarDecl::Static:
136 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
137 break;
138 }
139}
140
141/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
142/// declarator chain.
143void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
144 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
145 EmitGlobalVar(D);
146}
147
Chris Lattnerab862cc2007-08-31 04:31:45 +0000148/// getBuiltinLibFunction
149llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
150 if (BuiltinFunctions.size() <= BuiltinID)
151 BuiltinFunctions.resize(BuiltinID);
152
153 // Already available?
154 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
155 if (FunctionSlot)
156 return FunctionSlot;
157
158 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
159
160 // Get the name, skip over the __builtin_ prefix.
161 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
162
163 // Get the type for the builtin.
164 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
165 const llvm::FunctionType *Ty =
166 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
167
168 // FIXME: This has a serious problem with code like this:
169 // void abs() {}
170 // ... __builtin_abs(x);
171 // The two versions of abs will collide. The fix is for the builtin to win,
172 // and for the existing one to be turned into a constantexpr cast of the
173 // builtin. In the case where the existing one is a static function, it
174 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000175 if (llvm::Function *Existing = getModule().getFunction(Name)) {
176 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
177 return FunctionSlot = Existing;
178 assert(Existing == 0 && "FIXME: Name collision");
179 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000180
181 // FIXME: param attributes for sext/zext etc.
182 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
183 Name, &getModule());
184}
185
186
Chris Lattner4b009652007-07-25 00:24:17 +0000187llvm::Function *CodeGenModule::getMemCpyFn() {
188 if (MemCpyFn) return MemCpyFn;
189 llvm::Intrinsic::ID IID;
190 uint64_t Size; unsigned Align;
191 Context.Target.getPointerInfo(Size, Align, SourceLocation());
192 switch (Size) {
193 default: assert(0 && "Unknown ptr width");
194 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
195 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
196 }
197 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
198}
Anders Carlsson36a04872007-08-21 00:21:21 +0000199
Chris Lattnerab862cc2007-08-31 04:31:45 +0000200llvm::Constant *CodeGenModule::
201GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000202 llvm::StringMapEntry<llvm::Constant *> &Entry =
203 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
204
205 if (Entry.getValue())
206 return Entry.getValue();
207
208 std::vector<llvm::Constant*> Fields;
209
210 if (!CFConstantStringClassRef) {
211 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
212 Ty = llvm::ArrayType::get(Ty, 0);
213
214 CFConstantStringClassRef =
215 new llvm::GlobalVariable(Ty, false,
216 llvm::GlobalVariable::ExternalLinkage, 0,
217 "__CFConstantStringClassReference",
218 &getModule());
219 }
220
221 // Class pointer.
222 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
223 llvm::Constant *Zeros[] = { Zero, Zero };
224 llvm::Constant *C =
225 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
226 Fields.push_back(C);
227
228 // Flags.
229 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
230 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
231
232 // String pointer.
233 C = llvm::ConstantArray::get(str);
234 C = new llvm::GlobalVariable(C->getType(), true,
235 llvm::GlobalValue::InternalLinkage,
236 C, ".str", &getModule());
237
238 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
239 Fields.push_back(C);
240
241 // String length.
242 Ty = getTypes().ConvertType(getContext().LongTy);
243 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
244
245 // The struct.
246 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
247 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
248 C = new llvm::GlobalVariable(C->getType(), true,
249 llvm::GlobalVariable::InternalLinkage,
250 C, "", &getModule());
251
252 Entry.setValue(C);
253 return C;
254}