blob: b5f4c8d1ff50690ed8b8bb4c9b79215d1ebba008 [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());
Devang Patel0f2a8fb2007-10-30 20:59:40 +000086 const llvm::ArrayType *AType =
87 cast<llvm::ArrayType>(APType->getElementType());
Devang Patel8b5f5302007-10-26 16:31:40 +000088
89 // Copy initializer elements.
90 unsigned i = 0;
91 for (i = 0; i < NumInitElements; ++i) {
92 assert (ILE->getInit(i)->getType()->isIntegerType()
93 && "Only IntegerType global array initializers are supported");
Devang Patel0f2a8fb2007-10-30 20:59:40 +000094 llvm::APSInt
95 Value(static_cast<uint32_t>
96 (getContext().getTypeSize(ILE->getInit(i)->getType(),
97 SourceLocation())));
Devang Patel8b5f5302007-10-26 16:31:40 +000098 if (ILE->getInit(i)->isIntegerConstantExpr(Value, Context)) {
99 llvm::Constant *C = llvm::ConstantInt::get(Value);
100 ArrayElts.push_back(C);
101 }
102 }
103
104 // Initialize remaining array elements.
105 unsigned NumArrayElements = AType->getNumElements();
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000106 const llvm::Type *AElemTy = AType->getElementType();
Devang Patel8b5f5302007-10-26 16:31:40 +0000107 for (; i < NumArrayElements; ++i)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000108 ArrayElts.push_back(llvm::Constant::getNullValue(AElemTy));
Devang Patel8b5f5302007-10-26 16:31:40 +0000109
110 Init = llvm::ConstantArray::get(AType, ArrayElts);
111 } else
112 assert(Init && "FIXME: Global variable initializers unimp!");
113 }
Chris Lattner4b009652007-07-25 00:24:17 +0000114
115 GV->setInitializer(Init);
116
117 // Set the llvm linkage type as appropriate.
118 // FIXME: This isn't right. This should handle common linkage and other
119 // stuff.
120 switch (D->getStorageClass()) {
121 case VarDecl::Auto:
122 case VarDecl::Register:
123 assert(0 && "Can't have auto or register globals");
124 case VarDecl::None:
125 case VarDecl::Extern:
126 // todo: common
127 break;
128 case VarDecl::Static:
129 GV->setLinkage(llvm::GlobalVariable::InternalLinkage);
130 break;
131 }
132}
133
134/// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified
135/// declarator chain.
136void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) {
137 for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator()))
138 EmitGlobalVar(D);
139}
140
Chris Lattnerab862cc2007-08-31 04:31:45 +0000141/// getBuiltinLibFunction
142llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) {
143 if (BuiltinFunctions.size() <= BuiltinID)
144 BuiltinFunctions.resize(BuiltinID);
145
146 // Already available?
147 llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID];
148 if (FunctionSlot)
149 return FunctionSlot;
150
151 assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn");
152
153 // Get the name, skip over the __builtin_ prefix.
154 const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10;
155
156 // Get the type for the builtin.
157 QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context);
158 const llvm::FunctionType *Ty =
159 cast<llvm::FunctionType>(getTypes().ConvertType(Type));
160
161 // FIXME: This has a serious problem with code like this:
162 // void abs() {}
163 // ... __builtin_abs(x);
164 // The two versions of abs will collide. The fix is for the builtin to win,
165 // and for the existing one to be turned into a constantexpr cast of the
166 // builtin. In the case where the existing one is a static function, it
167 // should just be renamed.
Chris Lattner02c60f52007-08-31 04:44:06 +0000168 if (llvm::Function *Existing = getModule().getFunction(Name)) {
169 if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage())
170 return FunctionSlot = Existing;
171 assert(Existing == 0 && "FIXME: Name collision");
172 }
Chris Lattnerab862cc2007-08-31 04:31:45 +0000173
174 // FIXME: param attributes for sext/zext etc.
175 return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage,
176 Name, &getModule());
177}
178
179
Chris Lattner4b009652007-07-25 00:24:17 +0000180llvm::Function *CodeGenModule::getMemCpyFn() {
181 if (MemCpyFn) return MemCpyFn;
182 llvm::Intrinsic::ID IID;
183 uint64_t Size; unsigned Align;
184 Context.Target.getPointerInfo(Size, Align, SourceLocation());
185 switch (Size) {
186 default: assert(0 && "Unknown ptr width");
187 case 32: IID = llvm::Intrinsic::memcpy_i32; break;
188 case 64: IID = llvm::Intrinsic::memcpy_i64; break;
189 }
190 return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID);
191}
Anders Carlsson36a04872007-08-21 00:21:21 +0000192
Chris Lattnerab862cc2007-08-31 04:31:45 +0000193llvm::Constant *CodeGenModule::
194GetAddrOfConstantCFString(const std::string &str) {
Anders Carlsson36a04872007-08-21 00:21:21 +0000195 llvm::StringMapEntry<llvm::Constant *> &Entry =
196 CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]);
197
198 if (Entry.getValue())
199 return Entry.getValue();
200
201 std::vector<llvm::Constant*> Fields;
202
203 if (!CFConstantStringClassRef) {
204 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
205 Ty = llvm::ArrayType::get(Ty, 0);
206
207 CFConstantStringClassRef =
208 new llvm::GlobalVariable(Ty, false,
209 llvm::GlobalVariable::ExternalLinkage, 0,
210 "__CFConstantStringClassReference",
211 &getModule());
212 }
213
214 // Class pointer.
215 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
216 llvm::Constant *Zeros[] = { Zero, Zero };
217 llvm::Constant *C =
218 llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2);
219 Fields.push_back(C);
220
221 // Flags.
222 const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
223 Fields.push_back(llvm::ConstantInt::get(Ty, 1992));
224
225 // String pointer.
226 C = llvm::ConstantArray::get(str);
227 C = new llvm::GlobalVariable(C->getType(), true,
228 llvm::GlobalValue::InternalLinkage,
229 C, ".str", &getModule());
230
231 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
232 Fields.push_back(C);
233
234 // String length.
235 Ty = getTypes().ConvertType(getContext().LongTy);
236 Fields.push_back(llvm::ConstantInt::get(Ty, str.length()));
237
238 // The struct.
239 Ty = getTypes().ConvertType(getContext().getCFConstantStringType());
240 C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields);
241 C = new llvm::GlobalVariable(C->getType(), true,
242 llvm::GlobalVariable::InternalLinkage,
243 C, "", &getModule());
244
245 Entry.setValue(C);
246 return C;
247}