blob: 00c262167c67c7c15352ecbf3af07f09d92f07fa [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
57void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) {
58 llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalDecl(D));
59
60 // If the storage class is external and there is no initializer, just leave it
61 // as a declaration.
62 if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0)
63 return;
64
65 // Otherwise, convert the initializer, or use zero if appropriate.
66 llvm::Constant *Init = 0;
67 if (D->getInit() == 0) {
68 Init = llvm::Constant::getNullValue(GV->getType()->getElementType());
69 } else if (D->getType()->isIntegerType()) {
Hartmut Kaiserff08d2c2007-10-17 15:00:17 +000070 llvm::APSInt Value(static_cast<uint32_t>(
Chris Lattnera96e0d82007-09-04 02:34:27 +000071 getContext().getTypeSize(D->getInit()->getType(), SourceLocation())));
Chris Lattner4b009652007-07-25 00:24:17 +000072 if (D->getInit()->isIntegerConstantExpr(Value, Context))
73 Init = llvm::ConstantInt::get(Value);
74 }
Devang Patel8b5f5302007-10-26 16:31:40 +000075
76 if (!Init) {
77 if (const InitListExpr *ILE = dyn_cast<InitListExpr>(D->getInit())) {
78
79 unsigned NumInitElements = ILE->getNumInits();
80
81 assert ( ILE->getType()->isArrayType()
82 && "FIXME: Only Array initializers are supported");
83
84 std::vector<llvm::Constant*> ArrayElts;
85 const llvm::PointerType *APType = cast<llvm::PointerType>(GV->getType());
86 const llvm::ArrayType *AType = cast<llvm::ArrayType>(APType->getElementType());
87
88 // Copy initializer elements.
89 unsigned i = 0;
90 for (i = 0; i < NumInitElements; ++i) {
91 assert (ILE->getInit(i)->getType()->isIntegerType()
92 && "Only IntegerType global array initializers are supported");
93 llvm::APSInt Value(static_cast<uint32_t>(
94 getContext().getTypeSize(ILE->getInit(i)->getType(), SourceLocation())));
95 if (ILE->getInit(i)->isIntegerConstantExpr(Value, Context)) {
96 llvm::Constant *C = llvm::ConstantInt::get(Value);
97 ArrayElts.push_back(C);
98 }
99 }
100
101 // Initialize remaining array elements.
102 unsigned NumArrayElements = AType->getNumElements();
103 for (; i < NumArrayElements; ++i)
104 ArrayElts.push_back(llvm::Constant::getNullValue(AType->getElementType()));
105
106 Init = llvm::ConstantArray::get(AType, ArrayElts);
107 } else
108 assert(Init && "FIXME: Global variable initializers unimp!");
109 }
Chris Lattner4b009652007-07-25 00:24:17 +0000110
111 GV->setInitializer(Init);
112
113 // Set the llvm linkage type as appropriate.
114 // FIXME: This isn't right. This should handle common linkage and other
115 // stuff.
116 switch (D->getStorageClass()) {
117 case VarDecl::Auto:
118 case VarDecl::Register:
119 assert(0 && "Can't have auto or register globals");
120 case VarDecl::None:
121 case VarDecl::Extern:
122 // todo: common
123 break;
124 case VarDecl::Static:
125 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
126 break;
127 }
128}
129
130/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
131/// declarator chain.
132void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
133 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
134 EmitGlobalVar(D);
135}
136
Chris Lattnerab862cc2007-08-31 04:31:45 +0000137/// getBuiltinLibFunction
138llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
139 if (BuiltinFunctions.size() <= BuiltinID)
140 BuiltinFunctions.resize(BuiltinID);
141
142 // Already available?
143 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
144 if (FunctionSlot)
145 return FunctionSlot;
146
147 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
148
149 // Get the name, skip over the __builtin_ prefix.
150 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
151
152 // Get the type for the builtin.
153 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
154 const llvm::FunctionType *Ty =
155 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
156
157 // FIXME: This has a serious problem with code like this:
158 // void abs() {}
159 // ... __builtin_abs(x);
160 // The two versions of abs will collide. The fix is for the builtin to win,
161 // and for the existing one to be turned into a constantexpr cast of the
162 // builtin. In the case where the existing one is a static function, it
163 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000164 if (llvm::Function *Existing = getModule().getFunction(Name)) {
165 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
166 return FunctionSlot = Existing;
167 assert(Existing == 0 && "FIXME: Name collision");
168 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000169
170 // FIXME: param attributes for sext/zext etc.
171 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
172 Name, &getModule());
173}
174
175
Chris Lattner4b009652007-07-25 00:24:17 +0000176llvm::Function *CodeGenModule::getMemCpyFn() {
177 if (MemCpyFn) return MemCpyFn;
178 llvm::Intrinsic::ID IID;
179 uint64_t Size; unsigned Align;
180 Context.Target.getPointerInfo(Size, Align, SourceLocation());
181 switch (Size) {
182 default: assert(0 && "Unknown ptr width");
183 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
184 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
185 }
186 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
187}
Anders Carlsson36a04872007-08-21 00:21:21 +0000188
Chris Lattnerab862cc2007-08-31 04:31:45 +0000189llvm::Constant *CodeGenModule::
190GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000191 llvm::StringMapEntry<llvm::Constant *> &Entry =
192 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
193
194 if (Entry.getValue())
195 return Entry.getValue();
196
197 std::vector<llvm::Constant*> Fields;
198
199 if (!CFConstantStringClassRef) {
200 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
201 Ty = llvm::ArrayType::get(Ty, 0);
202
203 CFConstantStringClassRef =
204 new llvm::GlobalVariable(Ty, false,
205 llvm::GlobalVariable::ExternalLinkage, 0,
206 "__CFConstantStringClassReference",
207 &getModule());
208 }
209
210 // Class pointer.
211 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
212 llvm::Constant *Zeros[] = { Zero, Zero };
213 llvm::Constant *C =
214 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
215 Fields.push_back(C);
216
217 // Flags.
218 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
219 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
220
221 // String pointer.
222 C = llvm::ConstantArray::get(str);
223 C = new llvm::GlobalVariable(C->getType(), true,
224 llvm::GlobalValue::InternalLinkage,
225 C, ".str", &getModule());
226
227 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
228 Fields.push_back(C);
229
230 // String length.
231 Ty = getTypes().ConvertType(getContext().LongTy);
232 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
233
234 // The struct.
235 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
236 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
237 C = new llvm::GlobalVariable(C->getType(), true,
238 llvm::GlobalVariable::InternalLinkage,
239 C, "", &getModule());
240
241 Entry.setValue(C);
242 return C;
243}