blob: 71216a5d63d4fc1c51785b6d9536aaa97c3bf376 [file] [log] [blame]
Anders Carlsson3b1d57b2008-01-26 01:36:00 +00001//===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===//
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 contains code to emit Constant Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000016#include "CGObjCRuntime.h"
Chris Lattnerf6b24ea2008-10-06 05:59:01 +000017#include "clang/AST/APValue.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/StmtVisitor.h"
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000020#include "llvm/Constants.h"
21#include "llvm/Function.h"
22#include "llvm/GlobalVariable.h"
23#include "llvm/Support/Compiler.h"
Eli Friedmana8234002008-05-30 10:24:46 +000024#include "llvm/Target/TargetData.h"
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000025using namespace clang;
26using namespace CodeGen;
27
28namespace {
Anders Carlsson84005b42008-01-26 04:30:23 +000029class VISIBILITY_HIDDEN ConstExprEmitter :
30 public StmtVisitor<ConstExprEmitter, llvm::Constant*> {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000031 CodeGenModule &CGM;
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000032 CodeGenFunction *CGF;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000033public:
Lauro Ramos Venancio81373352008-02-26 21:41:45 +000034 ConstExprEmitter(CodeGenModule &cgm, CodeGenFunction *cgf)
35 : CGM(cgm), CGF(cgf) {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000036 }
37
38 //===--------------------------------------------------------------------===//
39 // Visitor Methods
40 //===--------------------------------------------------------------------===//
41
42 llvm::Constant *VisitStmt(Stmt *S) {
Daniel Dunbar488e9932008-08-16 00:56:44 +000043 CGM.ErrorUnsupported(S, "constant expression");
Chris Lattner98be4942008-03-05 18:54:05 +000044 QualType T = cast<Expr>(S)->getType();
45 return llvm::UndefValue::get(CGM.getTypes().ConvertType(T));
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000046 }
47
48 llvm::Constant *VisitParenExpr(ParenExpr *PE) {
49 return Visit(PE->getSubExpr());
50 }
51
Chris Lattner13fd7e52008-06-21 21:44:18 +000052 llvm::Constant *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
Daniel Dunbarbbce49b2008-08-12 00:12:39 +000053 std::string S(E->getString()->getStrData(),
54 E->getString()->getByteLength());
55 llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(S);
56 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner13fd7e52008-06-21 21:44:18 +000057 }
Anders Carlssonbcf62252008-11-22 02:34:39 +000058
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000059 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
60 return Visit(E->getInitializer());
61 }
62
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +000063 llvm::Constant *VisitCastExpr(CastExpr* E) {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +000064 llvm::Constant *C = Visit(E->getSubExpr());
65
66 return EmitConversion(C, E->getSubExpr()->getType(), E->getType());
67 }
Devang Pateleae15602008-02-05 02:39:50 +000068
Chris Lattner04421082008-04-08 04:40:51 +000069 llvm::Constant *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
70 return Visit(DAE->getExpr());
71 }
72
Eli Friedmana8234002008-05-30 10:24:46 +000073 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE) {
Eli Friedman4d1c0182008-02-21 17:45:41 +000074 std::vector<llvm::Constant*> Elts;
Eli Friedmana8234002008-05-30 10:24:46 +000075 const llvm::ArrayType *AType =
76 cast<llvm::ArrayType>(ConvertType(ILE->getType()));
Eli Friedman4d1c0182008-02-21 17:45:41 +000077 unsigned NumInitElements = ILE->getNumInits();
78 // FIXME: Check for wide strings
79 if (NumInitElements > 0 && isa<StringLiteral>(ILE->getInit(0)) &&
Chris Lattnerc63a1f22008-08-04 07:31:14 +000080 ILE->getType()->getArrayElementTypeNoTypeQual()->isCharType())
Eli Friedman4d1c0182008-02-21 17:45:41 +000081 return Visit(ILE->getInit(0));
Devang Pateleae15602008-02-05 02:39:50 +000082 const llvm::Type *ElemTy = AType->getElementType();
83 unsigned NumElements = AType->getNumElements();
84
85 // Initialising an array requires us to automatically
86 // initialise any elements that have not been initialised explicitly
87 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
88
89 // Copy initializer elements.
90 unsigned i = 0;
Eli Friedmana04a1532008-05-30 19:58:50 +000091 bool RewriteType = false;
Devang Pateleae15602008-02-05 02:39:50 +000092 for (; i < NumInitableElts; ++i) {
Anders Carlssonaa432562008-11-17 01:58:55 +000093 llvm::Constant *C = CGM.EmitConstantExpr(ILE->getInit(i), CGF);
Eli Friedmana04a1532008-05-30 19:58:50 +000094 RewriteType |= (C->getType() != ElemTy);
Devang Pateleae15602008-02-05 02:39:50 +000095 Elts.push_back(C);
96 }
Eli Friedmana04a1532008-05-30 19:58:50 +000097
Devang Pateleae15602008-02-05 02:39:50 +000098 // Initialize remaining array elements.
99 for (; i < NumElements; ++i)
100 Elts.push_back(llvm::Constant::getNullValue(ElemTy));
101
Eli Friedmana04a1532008-05-30 19:58:50 +0000102 if (RewriteType) {
103 // FIXME: Try to avoid packing the array
104 std::vector<const llvm::Type*> Types;
105 for (unsigned i = 0; i < Elts.size(); ++i)
106 Types.push_back(Elts[i]->getType());
107 const llvm::StructType *SType = llvm::StructType::get(Types, true);
108 return llvm::ConstantStruct::get(SType, Elts);
109 }
110
Devang Pateleae15602008-02-05 02:39:50 +0000111 return llvm::ConstantArray::get(AType, Elts);
112 }
113
Eli Friedmana8234002008-05-30 10:24:46 +0000114 void InsertBitfieldIntoStruct(std::vector<llvm::Constant*>& Elts,
115 FieldDecl* Field, Expr* E) {
116 // Calculate the value to insert
Anders Carlssonaa432562008-11-17 01:58:55 +0000117 llvm::Constant *C = CGM.EmitConstantExpr(E, CGF);
Eli Friedmana8234002008-05-30 10:24:46 +0000118 llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C);
119 if (!CI) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000120 CGM.ErrorUnsupported(E, "bitfield initialization");
Eli Friedmana8234002008-05-30 10:24:46 +0000121 return;
122 }
123 llvm::APInt V = CI->getValue();
Devang Pateleae15602008-02-05 02:39:50 +0000124
Eli Friedmana8234002008-05-30 10:24:46 +0000125 // Calculate information about the relevant field
126 const llvm::Type* Ty = CI->getType();
Daniel Dunbar9ca8bb02008-08-10 07:00:24 +0000127 const llvm::TargetData &TD = CGM.getTypes().getTargetData();
128 unsigned size = TD.getTypeStoreSizeInBits(Ty);
Eli Friedmana8234002008-05-30 10:24:46 +0000129 unsigned fieldOffset = CGM.getTypes().getLLVMFieldNo(Field) * size;
130 CodeGenTypes::BitFieldInfo bitFieldInfo =
131 CGM.getTypes().getBitFieldInfo(Field);
132 fieldOffset += bitFieldInfo.Begin;
133
134 // Find where to start the insertion
135 // FIXME: This is O(n^2) in the number of bit-fields!
136 // FIXME: This won't work if the struct isn't completely packed!
137 unsigned offset = 0, i = 0;
138 while (offset < (fieldOffset & -8))
Daniel Dunbar9ca8bb02008-08-10 07:00:24 +0000139 offset += TD.getTypeStoreSizeInBits(Elts[i++]->getType());
140
141 // Advance over 0 sized elements (must terminate in bounds since
142 // the bitfield must have a size).
143 while (TD.getTypeStoreSizeInBits(Elts[i]->getType()) == 0)
144 ++i;
Eli Friedmana8234002008-05-30 10:24:46 +0000145
Daniel Dunbar1f3846e2008-07-17 21:07:48 +0000146 // Promote the size of V if necessary
147 // FIXME: This should never occur, but currently it can because
148 // initializer constants are cast to bool, and because clang is
149 // not enforcing bitfield width limits.
150 if (bitFieldInfo.Size > V.getBitWidth())
151 V.zext(bitFieldInfo.Size);
152
Eli Friedmana8234002008-05-30 10:24:46 +0000153 // Insert the bits into the struct
154 // FIXME: This algorthm is only correct on X86!
155 // FIXME: THis algorthm assumes bit-fields only have byte-size elements!
156 unsigned bitsToInsert = bitFieldInfo.Size;
157 unsigned curBits = std::min(8 - (fieldOffset & 7), bitsToInsert);
158 unsigned byte = V.getLoBits(curBits).getZExtValue() << (fieldOffset & 7);
159 do {
160 llvm::Constant* byteC = llvm::ConstantInt::get(llvm::Type::Int8Ty, byte);
161 Elts[i] = llvm::ConstantExpr::getOr(Elts[i], byteC);
162 ++i;
163 V = V.lshr(curBits);
164 bitsToInsert -= curBits;
165
166 if (!bitsToInsert)
167 break;
168
169 curBits = bitsToInsert > 8 ? 8 : bitsToInsert;
170 byte = V.getLoBits(curBits).getZExtValue();
171 } while (true);
172 }
173
174 llvm::Constant *EmitStructInitialization(InitListExpr *ILE) {
175 const llvm::StructType *SType =
176 cast<llvm::StructType>(ConvertType(ILE->getType()));
Eli Friedman017cbdf2008-05-20 00:11:07 +0000177 RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
Devang Pateleae15602008-02-05 02:39:50 +0000178 std::vector<llvm::Constant*> Elts;
Devang Pateleae15602008-02-05 02:39:50 +0000179
Eli Friedman017cbdf2008-05-20 00:11:07 +0000180 // Initialize the whole structure to zero.
181 for (unsigned i = 0; i < SType->getNumElements(); ++i) {
Devang Pateleae15602008-02-05 02:39:50 +0000182 const llvm::Type *FieldTy = SType->getElementType(i);
183 Elts.push_back(llvm::Constant::getNullValue(FieldTy));
184 }
Eli Friedman017cbdf2008-05-20 00:11:07 +0000185
186 // Copy initializer elements. Skip padding fields.
187 unsigned EltNo = 0; // Element no in ILE
188 int FieldNo = 0; // Field no in RecordDecl
Eli Friedmana04a1532008-05-30 19:58:50 +0000189 bool RewriteType = false;
Douglas Gregor44b43212008-12-11 16:49:14 +0000190 for (RecordDecl::field_iterator Field = RD->field_begin(),
191 FieldEnd = RD->field_end();
192 EltNo < ILE->getNumInits() && Field != FieldEnd; ++Field) {
Eli Friedman017cbdf2008-05-20 00:11:07 +0000193 FieldNo++;
Douglas Gregor44b43212008-12-11 16:49:14 +0000194 if (!Field->getIdentifier())
Eli Friedman017cbdf2008-05-20 00:11:07 +0000195 continue;
196
Douglas Gregor44b43212008-12-11 16:49:14 +0000197 if (Field->isBitField()) {
198 InsertBitfieldIntoStruct(Elts, *Field, ILE->getInit(EltNo));
Eli Friedman017cbdf2008-05-20 00:11:07 +0000199 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000200 unsigned FieldNo = CGM.getTypes().getLLVMFieldNo(*Field);
Anders Carlssonaa432562008-11-17 01:58:55 +0000201 llvm::Constant *C = CGM.EmitConstantExpr(ILE->getInit(EltNo), CGF);
Eli Friedmana04a1532008-05-30 19:58:50 +0000202 RewriteType |= (C->getType() != Elts[FieldNo]->getType());
203 Elts[FieldNo] = C;
Eli Friedman017cbdf2008-05-20 00:11:07 +0000204 }
205 EltNo++;
206 }
207
Eli Friedmana04a1532008-05-30 19:58:50 +0000208 if (RewriteType) {
209 // FIXME: Make this work for non-packed structs
210 assert(SType->isPacked() && "Cannot recreate unpacked structs");
211 std::vector<const llvm::Type*> Types;
212 for (unsigned i = 0; i < Elts.size(); ++i)
213 Types.push_back(Elts[i]->getType());
214 SType = llvm::StructType::get(Types, true);
215 }
216
Devang Pateleae15602008-02-05 02:39:50 +0000217 return llvm::ConstantStruct::get(SType, Elts);
218 }
219
Eli Friedmana8234002008-05-30 10:24:46 +0000220 llvm::Constant *EmitUnionInitialization(InitListExpr *ILE) {
Eli Friedmana8234002008-05-30 10:24:46 +0000221 RecordDecl *RD = ILE->getType()->getAsRecordType()->getDecl();
222 const llvm::Type *Ty = ConvertType(ILE->getType());
223
224 // Find the field decl we're initializing, if any
225 int FieldNo = 0; // Field no in RecordDecl
Eli Friedmanc55f98d2008-06-06 20:12:37 +0000226 FieldDecl* curField = 0;
Douglas Gregor44b43212008-12-11 16:49:14 +0000227 for (RecordDecl::field_iterator Field = RD->field_begin(),
228 FieldEnd = RD->field_end();
229 Field != FieldEnd; ++Field) {
230 curField = *Field;
Eli Friedmana8234002008-05-30 10:24:46 +0000231 FieldNo++;
Eli Friedmanc55f98d2008-06-06 20:12:37 +0000232 if (curField->getIdentifier())
233 break;
234 }
Eli Friedmana8234002008-05-30 10:24:46 +0000235
Eli Friedmanc55f98d2008-06-06 20:12:37 +0000236 if (!curField || !curField->getIdentifier() || ILE->getNumInits() == 0)
Eli Friedmana8234002008-05-30 10:24:46 +0000237 return llvm::Constant::getNullValue(Ty);
238
239 if (curField->isBitField()) {
240 // Create a dummy struct for bit-field insertion
241 unsigned NumElts = CGM.getTargetData().getABITypeSize(Ty) / 8;
242 llvm::Constant* NV = llvm::Constant::getNullValue(llvm::Type::Int8Ty);
243 std::vector<llvm::Constant*> Elts(NumElts, NV);
244
245 InsertBitfieldIntoStruct(Elts, curField, ILE->getInit(0));
246 const llvm::ArrayType *RetTy =
247 llvm::ArrayType::get(NV->getType(), NumElts);
248 return llvm::ConstantArray::get(RetTy, Elts);
249 }
250
Anders Carlssonaa432562008-11-17 01:58:55 +0000251 llvm::Constant *C = CGM.EmitConstantExpr(ILE->getInit(0), CGF);
Eli Friedmana8234002008-05-30 10:24:46 +0000252
253 // Build a struct with the union sub-element as the first member,
254 // and padded to the appropriate size
255 std::vector<llvm::Constant*> Elts;
256 std::vector<const llvm::Type*> Types;
257 Elts.push_back(C);
258 Types.push_back(C->getType());
259 unsigned CurSize = CGM.getTargetData().getTypeStoreSize(C->getType());
260 unsigned TotalSize = CGM.getTargetData().getTypeStoreSize(Ty);
261 while (CurSize < TotalSize) {
262 Elts.push_back(llvm::Constant::getNullValue(llvm::Type::Int8Ty));
263 Types.push_back(llvm::Type::Int8Ty);
264 CurSize++;
265 }
266
267 // This always generates a packed struct
268 // FIXME: Try to generate an unpacked struct when we can
269 llvm::StructType* STy = llvm::StructType::get(Types, true);
270 return llvm::ConstantStruct::get(STy, Elts);
271 }
272
273 llvm::Constant *EmitVectorInitialization(InitListExpr *ILE) {
274 const llvm::VectorType *VType =
275 cast<llvm::VectorType>(ConvertType(ILE->getType()));
Eli Friedmancfb313b2008-05-30 12:02:14 +0000276 const llvm::Type *ElemTy = VType->getElementType();
277 std::vector<llvm::Constant*> Elts;
Devang Pateleae15602008-02-05 02:39:50 +0000278 unsigned NumElements = VType->getNumElements();
Eli Friedmancfb313b2008-05-30 12:02:14 +0000279 unsigned NumInitElements = ILE->getNumInits();
Devang Pateleae15602008-02-05 02:39:50 +0000280
Eli Friedmancfb313b2008-05-30 12:02:14 +0000281 unsigned NumInitableElts = std::min(NumInitElements, NumElements);
282
Devang Pateleae15602008-02-05 02:39:50 +0000283 // Copy initializer elements.
284 unsigned i = 0;
Eli Friedmancfb313b2008-05-30 12:02:14 +0000285 for (; i < NumInitableElts; ++i) {
Anders Carlssonaa432562008-11-17 01:58:55 +0000286 llvm::Constant *C = CGM.EmitConstantExpr(ILE->getInit(i), CGF);
Devang Pateleae15602008-02-05 02:39:50 +0000287 Elts.push_back(C);
288 }
289
Eli Friedmancfb313b2008-05-30 12:02:14 +0000290 for (; i < NumElements; ++i)
291 Elts.push_back(llvm::Constant::getNullValue(ElemTy));
292
Devang Pateleae15602008-02-05 02:39:50 +0000293 return llvm::ConstantVector::get(VType, Elts);
294 }
295
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000296 llvm::Constant *VisitInitListExpr(InitListExpr *ILE) {
Eli Friedmana8234002008-05-30 10:24:46 +0000297 if (ILE->getType()->isScalarType()) {
298 // We have a scalar in braces. Just use the first element.
299 if (ILE->getNumInits() > 0)
Anders Carlssonaa432562008-11-17 01:58:55 +0000300 return CGM.EmitConstantExpr(ILE->getInit(0), CGF);
Eli Friedmana8234002008-05-30 10:24:46 +0000301
302 const llvm::Type* RetTy = CGM.getTypes().ConvertType(ILE->getType());
303 return llvm::Constant::getNullValue(RetTy);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000304 }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000305
306 // FIXME: We don't codegen or sema designators yet.
307 if (ILE->hadDesignators()) {
308 CGM.ErrorUnsupported(ILE, "initializer list with designators");
309 return llvm::UndefValue::get(ConvertType(ILE->getType()));
310 }
Devang Patel47fb6972008-01-29 23:23:18 +0000311
Eli Friedmana8234002008-05-30 10:24:46 +0000312 if (ILE->getType()->isArrayType())
313 return EmitArrayInitialization(ILE);
Devang Patel47fb6972008-01-29 23:23:18 +0000314
Eli Friedmana8234002008-05-30 10:24:46 +0000315 if (ILE->getType()->isStructureType())
316 return EmitStructInitialization(ILE);
317
318 if (ILE->getType()->isUnionType())
319 return EmitUnionInitialization(ILE);
320
321 if (ILE->getType()->isVectorType())
322 return EmitVectorInitialization(ILE);
323
Devang Pateleae15602008-02-05 02:39:50 +0000324 assert(0 && "Unable to handle InitListExpr");
Chris Lattner2b94fe32008-03-01 08:45:05 +0000325 // Get rid of control reaches end of void function warning.
326 // Not reached.
327 return 0;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000328 }
Eli Friedman3b707e72008-02-21 17:57:49 +0000329
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000330 llvm::Constant *VisitImplicitCastExpr(ImplicitCastExpr *ICExpr) {
Eli Friedman3b707e72008-02-21 17:57:49 +0000331 Expr* SExpr = ICExpr->getSubExpr();
332 QualType SType = SExpr->getType();
333 llvm::Constant *C; // the intermediate expression
334 QualType T; // the type of the intermediate expression
335 if (SType->isArrayType()) {
336 // Arrays decay to a pointer to the first element
337 // VLAs would require special handling, but they can't occur here
338 C = EmitLValue(SExpr);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000339 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000340 llvm::Constant *Ops[] = {Idx0, Idx0};
341 C = llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000342 T = CGM.getContext().getArrayDecayedType(SType);
Eli Friedman3b707e72008-02-21 17:57:49 +0000343 } else if (SType->isFunctionType()) {
344 // Function types decay to a pointer to the function
345 C = EmitLValue(SExpr);
346 T = CGM.getContext().getPointerType(SType);
347 } else {
348 C = Visit(SExpr);
349 T = SType;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000350 }
Eli Friedman3b707e72008-02-21 17:57:49 +0000351
352 // Perform the conversion; note that an implicit cast can both promote
353 // and convert an array/function
354 return EmitConversion(C, T, ICExpr->getType());
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000355 }
Eli Friedman3b707e72008-02-21 17:57:49 +0000356
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000357 llvm::Constant *VisitStringLiteral(StringLiteral *E) {
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000358 assert(!E->getType()->isPointerType() && "Strings are always arrays");
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000359
360 // Otherwise this must be a string initializing an array in a static
361 // initializer. Don't emit it as the address of the string, emit the string
362 // data itself as an inline array.
Daniel Dunbar61432932008-08-13 23:20:05 +0000363 return llvm::ConstantArray::get(CGM.GetStringForStringLiteral(E), false);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000364 }
365
Daniel Dunbar54d19092008-08-16 01:41:47 +0000366 llvm::Constant *VisitAddrLabelExpr(const AddrLabelExpr *E) {
367 assert(CGF && "Invalid address of label expression outside function.");
368 llvm::Constant *C =
369 llvm::ConstantInt::get(llvm::Type::Int32Ty,
370 CGF->GetIDForAddrOfLabel(E->getLabel()));
371 return llvm::ConstantExpr::getIntToPtr(C, ConvertType(E->getType()));
372 }
373
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000374 llvm::Constant *VisitUnaryAddrOf(const UnaryOperator *E) {
375 return EmitLValue(E->getSubExpr());
376 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000377 llvm::Constant *VisitUnaryOffsetOf(const UnaryOperator *E) {
378 int64_t Val = E->evaluateOffsetOf(CGM.getContext());
379
380 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
381
Chris Lattner98be4942008-03-05 18:54:05 +0000382 uint32_t ResultWidth =
383 static_cast<uint32_t>(CGM.getContext().getTypeSize(E->getType()));
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000384 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
385 }
Eli Friedmanbc5ed6e2008-05-29 11:22:45 +0000386
387 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E) {
388 return Visit(E->getSubExpr());
389 }
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000390
Anders Carlssonce6237e2008-01-29 01:33:32 +0000391 // Binary operators
Anders Carlsson2ea2b5e2008-08-25 03:27:15 +0000392
393 llvm::Constant *VisitCallExpr(const CallExpr *E) {
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000394 Expr::EvalResult Result;
Chris Lattner6ee7aa12008-11-16 21:24:15 +0000395 if (E->Evaluate(Result, CGM.getContext())) {
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000396 if (Result.Val.isInt())
397 return llvm::ConstantInt::get(Result.Val.getInt());
398 if (Result.Val.isFloat())
399 return llvm::ConstantFP::get(Result.Val.getFloat());
Chris Lattnerf6b24ea2008-10-06 05:59:01 +0000400 }
Anders Carlsson2ea2b5e2008-08-25 03:27:15 +0000401
Chris Lattner506ff882008-10-06 07:26:43 +0000402 // Handle __builtin___CFStringMakeConstantString.
403 if (E->isBuiltinCall() ==Builtin::BI__builtin___CFStringMakeConstantString){
Anders Carlssond114ade2008-11-15 18:52:06 +0000404 const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
Chris Lattner506ff882008-10-06 07:26:43 +0000405
406 const StringLiteral *Literal = cast<StringLiteral>(Arg);
407 std::string S(Literal->getStrData(), Literal->getByteLength());
408 return CGM.GetAddrOfConstantCFString(S);
409 }
410
Anders Carlsson2ea2b5e2008-08-25 03:27:15 +0000411 CGM.ErrorUnsupported(E, "constant call expression");
412 return llvm::Constant::getNullValue(ConvertType(E->getType()));
413 }
Anders Carlsson7be3d012008-02-05 20:54:21 +0000414
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000415 // Utility methods
416 const llvm::Type *ConvertType(QualType T) {
417 return CGM.getTypes().ConvertType(T);
418 }
419
420 llvm::Constant *EmitConversionToBool(llvm::Constant *Src, QualType SrcType) {
421 assert(SrcType->isCanonical() && "EmitConversion strips typedefs");
422
423 if (SrcType->isRealFloatingType()) {
424 // Compare against 0.0 for fp scalars.
425 llvm::Constant *Zero = llvm::Constant::getNullValue(Src->getType());
426 return llvm::ConstantExpr::getFCmp(llvm::FCmpInst::FCMP_UNE, Src, Zero);
427 }
428
429 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
430 "Unknown scalar type to convert");
431
432 // Compare against an integer or pointer null.
433 llvm::Constant *Zero = llvm::Constant::getNullValue(Src->getType());
434 return llvm::ConstantExpr::getICmp(llvm::ICmpInst::ICMP_NE, Src, Zero);
435 }
436
437 llvm::Constant *EmitConversion(llvm::Constant *Src, QualType SrcType,
438 QualType DstType) {
Chris Lattnerd394cc62008-07-26 22:39:33 +0000439 SrcType = CGM.getContext().getCanonicalType(SrcType);
440 DstType = CGM.getContext().getCanonicalType(DstType);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000441 if (SrcType == DstType) return Src;
442
443 // Handle conversions to bool first, they are special: comparisons against 0.
444 if (DstType->isBooleanType())
445 return EmitConversionToBool(Src, SrcType);
446
447 const llvm::Type *DstTy = ConvertType(DstType);
448
449 // Ignore conversions like int -> uint.
450 if (Src->getType() == DstTy)
451 return Src;
452
453 // Handle pointer conversions next: pointers can only be converted to/from
454 // other pointers and integers.
Eli Friedmanc53296e2008-06-07 17:27:51 +0000455 if (isa<llvm::PointerType>(DstTy)) {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000456 // The source value may be an integer, or a pointer.
457 if (isa<llvm::PointerType>(Src->getType()))
458 return llvm::ConstantExpr::getBitCast(Src, DstTy);
Anders Carlsson84005b42008-01-26 04:30:23 +0000459 assert(SrcType->isIntegerType() &&"Not ptr->ptr or int->ptr conversion?");
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000460 return llvm::ConstantExpr::getIntToPtr(Src, DstTy);
461 }
462
Eli Friedmanc53296e2008-06-07 17:27:51 +0000463 if (isa<llvm::PointerType>(Src->getType())) {
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000464 // Must be an ptr to int cast.
465 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
466 return llvm::ConstantExpr::getPtrToInt(Src, DstTy);
467 }
468
469 // A scalar source can be splatted to a vector of the same element type
470 if (isa<llvm::VectorType>(DstTy) && !isa<VectorType>(SrcType)) {
Chris Lattner3304e552008-10-12 00:31:50 +0000471 assert((cast<llvm::VectorType>(DstTy)->getElementType()
472 == Src->getType()) &&
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000473 "Vector element type must match scalar type to splat.");
474 unsigned NumElements = DstType->getAsVectorType()->getNumElements();
475 llvm::SmallVector<llvm::Constant*, 16> Elements;
476 for (unsigned i = 0; i < NumElements; i++)
477 Elements.push_back(Src);
478
479 return llvm::ConstantVector::get(&Elements[0], NumElements);
480 }
481
482 if (isa<llvm::VectorType>(Src->getType()) ||
483 isa<llvm::VectorType>(DstTy)) {
484 return llvm::ConstantExpr::getBitCast(Src, DstTy);
485 }
486
487 // Finally, we have the arithmetic types: real int/float.
488 if (isa<llvm::IntegerType>(Src->getType())) {
489 bool InputSigned = SrcType->isSignedIntegerType();
490 if (isa<llvm::IntegerType>(DstTy))
491 return llvm::ConstantExpr::getIntegerCast(Src, DstTy, InputSigned);
492 else if (InputSigned)
493 return llvm::ConstantExpr::getSIToFP(Src, DstTy);
494 else
495 return llvm::ConstantExpr::getUIToFP(Src, DstTy);
496 }
497
498 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
499 if (isa<llvm::IntegerType>(DstTy)) {
500 if (DstType->isSignedIntegerType())
501 return llvm::ConstantExpr::getFPToSI(Src, DstTy);
502 else
503 return llvm::ConstantExpr::getFPToUI(Src, DstTy);
504 }
505
506 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
507 if (DstTy->getTypeID() < Src->getType()->getTypeID())
508 return llvm::ConstantExpr::getFPTrunc(Src, DstTy);
509 else
510 return llvm::ConstantExpr::getFPExtend(Src, DstTy);
511 }
512
513 llvm::Constant *EmitSizeAlignOf(QualType TypeToSize,
514 QualType RetType, bool isSizeOf) {
515 std::pair<uint64_t, unsigned> Info =
Chris Lattner98be4942008-03-05 18:54:05 +0000516 CGM.getContext().getTypeInfo(TypeToSize);
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000517
518 uint64_t Val = isSizeOf ? Info.first : Info.second;
519 Val /= 8; // Return size in bytes, not bits.
520
521 assert(RetType->isIntegerType() && "Result type must be an integer!");
522
Chris Lattner98be4942008-03-05 18:54:05 +0000523 uint32_t ResultWidth =
524 static_cast<uint32_t>(CGM.getContext().getTypeSize(RetType));
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000525 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
526 }
Anders Carlsson84005b42008-01-26 04:30:23 +0000527
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000528public:
Anders Carlsson84005b42008-01-26 04:30:23 +0000529 llvm::Constant *EmitLValue(Expr *E) {
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000530 switch (E->getStmtClass()) {
Eli Friedman546d94c2008-02-11 00:23:10 +0000531 default: break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000532 case Expr::ParenExprClass:
533 // Elide parenthesis
534 return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
535 case Expr::CompoundLiteralExprClass: {
536 // Note that due to the nature of compound literals, this is guaranteed
537 // to be the only use of the variable, so we just generate it here.
Anders Carlsson84005b42008-01-26 04:30:23 +0000538 CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
539 llvm::Constant* C = Visit(CLE->getInitializer());
Chris Lattnera7ad98f2008-02-11 00:02:17 +0000540 C = new llvm::GlobalVariable(C->getType(),E->getType().isConstQualified(),
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000541 llvm::GlobalValue::InternalLinkage,
542 C, ".compoundliteral", &CGM.getModule());
543 return C;
Anders Carlsson84005b42008-01-26 04:30:23 +0000544 }
Douglas Gregor1a49af92009-01-06 05:10:23 +0000545 case Expr::DeclRefExprClass:
546 case Expr::QualifiedDeclRefExprClass: {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000547 NamedDecl *Decl = cast<DeclRefExpr>(E)->getDecl();
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000548 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Decl))
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000549 return CGM.GetAddrOfFunction(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000550 if (const VarDecl* VD = dyn_cast<VarDecl>(Decl)) {
551 if (VD->isFileVarDecl())
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000552 return CGM.GetAddrOfGlobalVar(VD);
Steve Naroff248a7532008-04-15 22:42:06 +0000553 else if (VD->isBlockVarDecl()) {
554 assert(CGF && "Can't access static local vars without CGF");
555 return CGF->GetAddrOfStaticLocalVar(VD);
556 }
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000557 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000558 break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000559 }
560 case Expr::MemberExprClass: {
Anders Carlsson84005b42008-01-26 04:30:23 +0000561 MemberExpr* ME = cast<MemberExpr>(E);
Anders Carlsson84005b42008-01-26 04:30:23 +0000562 llvm::Constant *Base;
563 if (ME->isArrow())
564 Base = Visit(ME->getBase());
565 else
566 Base = EmitLValue(ME->getBase());
Lauro Ramos Venancio5bfe18c2008-01-30 21:23:20 +0000567
Douglas Gregor86f19402008-12-20 23:49:58 +0000568 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl());
569 // FIXME: Handle other kinds of member expressions.
570 assert(Field && "No code generation for non-field member expressions");
571 unsigned FieldNumber = CGM.getTypes().getLLVMFieldNo(Field);
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000572 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
573 llvm::Constant *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty,
574 FieldNumber);
575 llvm::Value *Ops[] = {Zero, Idx};
576 return llvm::ConstantExpr::getGetElementPtr(Base, Ops, 2);
577 }
578 case Expr::ArraySubscriptExprClass: {
Anders Carlsson84005b42008-01-26 04:30:23 +0000579 ArraySubscriptExpr* ASExpr = cast<ArraySubscriptExpr>(E);
580 llvm::Constant *Base = Visit(ASExpr->getBase());
581 llvm::Constant *Index = Visit(ASExpr->getIdx());
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000582 assert(!ASExpr->getBase()->getType()->isVectorType() &&
583 "Taking the address of a vector component is illegal!");
584 return llvm::ConstantExpr::getGetElementPtr(Base, &Index, 1);
585 }
Daniel Dunbar61432932008-08-13 23:20:05 +0000586 case Expr::StringLiteralClass:
587 return CGM.GetAddrOfConstantStringFromLiteral(cast<StringLiteral>(E));
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000588 case Expr::ObjCStringLiteralClass: {
589 ObjCStringLiteral* SL = cast<ObjCStringLiteral>(E);
590 std::string S(SL->getString()->getStrData(),
591 SL->getString()->getByteLength());
592 llvm::Constant *C = CGM.getObjCRuntime().GenerateConstantString(S);
593 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
594 }
Anders Carlsson84005b42008-01-26 04:30:23 +0000595 case Expr::UnaryOperatorClass: {
596 UnaryOperator *Exp = cast<UnaryOperator>(E);
597 switch (Exp->getOpcode()) {
Eli Friedman546d94c2008-02-11 00:23:10 +0000598 default: break;
599 case UnaryOperator::Extension:
Anders Carlsson84005b42008-01-26 04:30:23 +0000600 // Extension is just a wrapper for expressions
601 return EmitLValue(Exp->getSubExpr());
602 case UnaryOperator::Real:
603 case UnaryOperator::Imag: {
604 // The address of __real or __imag is just a GEP off the address
605 // of the internal expression
606 llvm::Constant* C = EmitLValue(Exp->getSubExpr());
607 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
608 llvm::Constant *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty,
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000609 Exp->getOpcode() == UnaryOperator::Imag);
Anders Carlsson84005b42008-01-26 04:30:23 +0000610 llvm::Value *Ops[] = {Zero, Idx};
611 return llvm::ConstantExpr::getGetElementPtr(C, Ops, 2);
612 }
613 case UnaryOperator::Deref:
614 // The address of a deref is just the value of the expression
615 return Visit(Exp->getSubExpr());
616 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000617 break;
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000618 }
Chris Lattner35345642008-12-12 05:18:02 +0000619
620 case Expr::PredefinedExprClass: {
621 // __func__/__FUNCTION__ -> "". __PRETTY_FUNCTION__ -> "top level".
622 std::string Str;
623 if (cast<PredefinedExpr>(E)->getIdentType() ==
624 PredefinedExpr::PrettyFunction)
625 Str = "top level";
626
627 return CGM.GetAddrOfConstantCString(Str, ".tmp");
628 }
Eli Friedman546d94c2008-02-11 00:23:10 +0000629 }
Daniel Dunbar488e9932008-08-16 00:56:44 +0000630 CGM.ErrorUnsupported(E, "constant l-value expression");
Eli Friedman546d94c2008-02-11 00:23:10 +0000631 llvm::Type *Ty = llvm::PointerType::getUnqual(ConvertType(E->getType()));
632 return llvm::UndefValue::get(Ty);
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000633 }
Anders Carlssone3d3b7d2008-01-26 02:08:50 +0000634};
635
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000636} // end anonymous namespace.
637
Lauro Ramos Venancio81373352008-02-26 21:41:45 +0000638llvm::Constant *CodeGenModule::EmitConstantExpr(const Expr *E,
Chris Lattner96196622008-07-26 22:37:01 +0000639 CodeGenFunction *CGF) {
640 QualType type = Context.getCanonicalType(E->getType());
Eli Friedman7dfa6392008-06-01 15:31:44 +0000641
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000642 Expr::EvalResult Result;
643
644 if (E->Evaluate(Result, Context)) {
645 assert(!Result.HasSideEffects &&
646 "Constant expr should not have any side effects!");
647 switch (Result.Val.getKind()) {
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000648 default: assert(0 && "unhandled value kind!");
649 case APValue::LValue: {
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000650 llvm::Constant *Offset =
651 llvm::ConstantInt::get(llvm::Type::Int64Ty,
652 Result.Val.getLValueOffset());
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000653
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000654 if (const Expr *LVBase = Result.Val.getLValueBase()) {
Anders Carlssonaa432562008-11-17 01:58:55 +0000655 llvm::Constant *C =
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000656 ConstExprEmitter(*this, CGF).EmitLValue(const_cast<Expr*>(LVBase));
657
Anders Carlssonaa432562008-11-17 01:58:55 +0000658 const llvm::Type *Type =
659 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Eli Friedman7b30b1c2008-11-17 03:57:28 +0000660 const llvm::Type *DestType = getTypes().ConvertTypeForMem(E->getType());
Anders Carlssonaa432562008-11-17 01:58:55 +0000661
662 // FIXME: It's a little ugly that we need to cast to a pointer,
663 // apply the GEP and then cast back.
664 C = llvm::ConstantExpr::getBitCast(C, Type);
665 C = llvm::ConstantExpr::getGetElementPtr(C, &Offset, 1);
666
667 return llvm::ConstantExpr::getBitCast(C, DestType);
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000668 }
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000669
Anders Carlsson5ea7d072008-11-16 06:23:45 +0000670 return llvm::ConstantExpr::getIntToPtr(Offset,
671 getTypes().ConvertType(type));
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000672 }
Eli Friedman7b30b1c2008-11-17 03:57:28 +0000673 case APValue::Int: {
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000674 llvm::Constant *C = llvm::ConstantInt::get(Result.Val.getInt());
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000675
676 if (C->getType() == llvm::Type::Int1Ty) {
677 const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
678 C = llvm::ConstantExpr::getZExt(C, BoolTy);
679 }
680 return C;
Eli Friedman7b30b1c2008-11-17 03:57:28 +0000681 }
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000682 case APValue::Float:
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000683 return llvm::ConstantFP::get(Result.Val.getFloat());
Anders Carlssonaa432562008-11-17 01:58:55 +0000684 case APValue::ComplexFloat: {
685 llvm::Constant *Complex[2];
686
Anders Carlsson4b3f9c02008-12-01 02:42:14 +0000687 Complex[0] = llvm::ConstantFP::get(Result.Val.getComplexFloatReal());
688 Complex[1] = llvm::ConstantFP::get(Result.Val.getComplexFloatImag());
Anders Carlssonaa432562008-11-17 01:58:55 +0000689
690 return llvm::ConstantStruct::get(Complex, 2);
691 }
Anders Carlsson5a9a4572008-11-15 20:45:50 +0000692 }
693 }
Eli Friedman7dfa6392008-06-01 15:31:44 +0000694
695 llvm::Constant* C = ConstExprEmitter(*this, CGF).Visit(const_cast<Expr*>(E));
696 if (C->getType() == llvm::Type::Int1Ty) {
697 const llvm::Type *BoolTy = getTypes().ConvertTypeForMem(E->getType());
698 C = llvm::ConstantExpr::getZExt(C, BoolTy);
699 }
700 return C;
Anders Carlsson3b1d57b2008-01-26 01:36:00 +0000701}