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