blob: dbb7029272d32fdd8f32ca3147ebf4f84ab6cdbd [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
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 contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "clang/AST/AST.h"
Anders Carlsson49865302007-08-20 18:05:56 +000017#include "clang/Lex/IdentifierTable.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
21#include "llvm/GlobalVariable.h"
22#include "llvm/Support/MathExtras.h"
23using namespace clang;
24using namespace CodeGen;
25
26//===--------------------------------------------------------------------===//
27// Miscellaneous Helper Methods
28//===--------------------------------------------------------------------===//
29
30/// CreateTempAlloca - This creates a alloca and inserts it into the entry
31/// block.
32llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
33 const char *Name) {
34 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
35}
36
37/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
38/// expression and compare the result against zero, returning an Int1Ty value.
39llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattner5ac222c2007-08-24 00:01:20 +000040 return ConvertScalarValueToBool(EmitAnyExpr(E), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +000041}
42
Chris Lattner4b009652007-07-25 00:24:17 +000043//===--------------------------------------------------------------------===//
44// Conversions
45//===--------------------------------------------------------------------===//
46
47/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
48/// the type specified by DstTy, following the rules of C99 6.3.
49RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
50 QualType DstTy) {
51 ValTy = ValTy.getCanonicalType();
52 DstTy = DstTy.getCanonicalType();
53 if (ValTy == DstTy) return Val;
54
55 // Handle conversions to bool first, they are special: comparisons against 0.
56 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
57 if (DestBT->getKind() == BuiltinType::Bool)
58 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
59
60 // Handle pointer conversions next: pointers can only be converted to/from
61 // other pointers and integers.
62 if (isa<PointerType>(DstTy)) {
63 const llvm::Type *DestTy = ConvertType(DstTy);
64
Chris Lattner2a420172007-08-10 16:33:59 +000065 if (Val.getVal()->getType() == DestTy)
66 return Val;
67
Chris Lattner4b009652007-07-25 00:24:17 +000068 // The source value may be an integer, or a pointer.
69 assert(Val.isScalar() && "Can only convert from integer or pointer");
70 if (isa<llvm::PointerType>(Val.getVal()->getType()))
71 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
72 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
73 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
74 }
75
76 if (isa<PointerType>(ValTy)) {
77 // Must be an ptr to int cast.
78 const llvm::Type *DestTy = ConvertType(DstTy);
79 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
80 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
81 }
82
83 // Finally, we have the arithmetic types: real int/float and complex
84 // int/float. Handle real->real conversions first, they are the most
85 // common.
86 if (Val.isScalar() && DstTy->isRealType()) {
87 // We know that these are representable as scalars in LLVM, convert to LLVM
88 // types since they are easier to reason about.
89 llvm::Value *SrcVal = Val.getVal();
90 const llvm::Type *DestTy = ConvertType(DstTy);
91 if (SrcVal->getType() == DestTy) return Val;
92
93 llvm::Value *Result;
94 if (isa<llvm::IntegerType>(SrcVal->getType())) {
95 bool InputSigned = ValTy->isSignedIntegerType();
96 if (isa<llvm::IntegerType>(DestTy))
97 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
98 else if (InputSigned)
99 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
100 else
101 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
102 } else {
103 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
104 if (isa<llvm::IntegerType>(DestTy)) {
105 if (DstTy->isSignedIntegerType())
106 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
107 else
108 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
109 } else {
110 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
111 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
112 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
113 else
114 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
115 }
116 }
117 return RValue::get(Result);
118 }
119
120 assert(0 && "FIXME: We don't support complex conversions yet!");
121}
122
123
124/// ConvertScalarValueToBool - Convert the specified expression value to a
125/// boolean (i1) truth value. This is equivalent to "Val == 0".
126llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
127 Ty = Ty.getCanonicalType();
128 llvm::Value *Result;
129 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
130 switch (BT->getKind()) {
131 default: assert(0 && "Unknown scalar value");
132 case BuiltinType::Bool:
133 Result = Val.getVal();
134 // Bool is already evaluated right.
135 assert(Result->getType() == llvm::Type::Int1Ty &&
136 "Unexpected bool value type!");
137 return Result;
138 case BuiltinType::Char_S:
139 case BuiltinType::Char_U:
140 case BuiltinType::SChar:
141 case BuiltinType::UChar:
142 case BuiltinType::Short:
143 case BuiltinType::UShort:
144 case BuiltinType::Int:
145 case BuiltinType::UInt:
146 case BuiltinType::Long:
147 case BuiltinType::ULong:
148 case BuiltinType::LongLong:
149 case BuiltinType::ULongLong:
150 // Code below handles simple integers.
151 break;
152 case BuiltinType::Float:
153 case BuiltinType::Double:
154 case BuiltinType::LongDouble: {
155 // Compare against 0.0 for fp scalars.
156 Result = Val.getVal();
157 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
158 // FIXME: llvm-gcc produces a une comparison: validate this is right.
159 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
160 return Result;
161 }
162 }
Chris Lattner5ac222c2007-08-24 00:01:20 +0000163 } else if (isa<ComplexType>(Ty)) {
164 assert(0 && "implement complex -> bool");
165
Chris Lattner4b009652007-07-25 00:24:17 +0000166 } else {
Chris Lattner5ac222c2007-08-24 00:01:20 +0000167 assert((isa<PointerType>(Ty) ||
168 (isa<TagType>(Ty) &&
169 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum)) &&
170 "Unknown Type");
171 // Code below handles this case fine.
Chris Lattner4b009652007-07-25 00:24:17 +0000172 }
173
174 // Usual case for integers, pointers, and enums: compare against zero.
175 Result = Val.getVal();
176
177 // Because of the type rules of C, we often end up computing a logical value,
178 // then zero extending it to int, then wanting it as a logical value again.
179 // Optimize this common case.
180 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
181 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
182 Result = ZI->getOperand(0);
183 ZI->eraseFromParent();
184 return Result;
185 }
186 }
187
188 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
189 return Builder.CreateICmpNE(Result, Zero, "tobool");
190}
191
192//===----------------------------------------------------------------------===//
193// LValue Expression Emission
194//===----------------------------------------------------------------------===//
195
196/// EmitLValue - Emit code to compute a designator that specifies the location
197/// of the expression.
198///
199/// This can return one of two things: a simple address or a bitfield
200/// reference. In either case, the LLVM Value* in the LValue structure is
201/// guaranteed to be an LLVM pointer type.
202///
203/// If this returns a bitfield reference, nothing about the pointee type of
204/// the LLVM value is known: For example, it may not be a pointer to an
205/// integer.
206///
207/// If this returns a normal address, and if the lvalue's C type is fixed
208/// size, this method guarantees that the returned pointer type will point to
209/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
210/// variable length type, this is not possible.
211///
212LValue CodeGenFunction::EmitLValue(const Expr *E) {
213 switch (E->getStmtClass()) {
214 default:
215 fprintf(stderr, "Unimplemented lvalue expr!\n");
216 E->dump();
217 return LValue::MakeAddr(llvm::UndefValue::get(
218 llvm::PointerType::get(llvm::Type::Int32Ty)));
219
220 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
221 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
222 case Expr::PreDefinedExprClass:
223 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
224 case Expr::StringLiteralClass:
225 return EmitStringLiteralLValue(cast<StringLiteral>(E));
226
227 case Expr::UnaryOperatorClass:
228 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
229 case Expr::ArraySubscriptExprClass:
230 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000231 case Expr::OCUVectorElementExprClass:
232 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000233 }
234}
235
236/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
237/// this method emits the address of the lvalue, then loads the result as an
238/// rvalue, returning the rvalue.
239RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner4b009652007-07-25 00:24:17 +0000240 if (LV.isSimple()) {
241 llvm::Value *Ptr = LV.getAddress();
242 const llvm::Type *EltTy =
243 cast<llvm::PointerType>(Ptr->getType())->getElementType();
244
245 // Simple scalar l-value.
246 if (EltTy->isFirstClassType())
247 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
248
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000249 assert(ExprType->isFunctionType() && "Unknown scalar value");
250 return RValue::get(Ptr);
Chris Lattner4b009652007-07-25 00:24:17 +0000251 }
252
253 if (LV.isVectorElt()) {
254 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
255 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
256 "vecext"));
257 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000258
259 // If this is a reference to a subset of the elements of a vector, either
260 // shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000261 if (LV.isOCUVectorElt())
262 return EmitLoadOfOCUElementLValue(LV, ExprType);
Chris Lattner4b009652007-07-25 00:24:17 +0000263
264 assert(0 && "Bitfield ref not impl!");
265}
266
Chris Lattner944f7962007-08-03 16:18:34 +0000267// If this is a reference to a subset of the elements of a vector, either
268// shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000269RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner4b492962007-08-10 17:10:08 +0000270 QualType ExprType) {
Chris Lattner944f7962007-08-03 16:18:34 +0000271 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
272
Chris Lattnera0d03a72007-08-03 17:31:20 +0000273 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner944f7962007-08-03 16:18:34 +0000274
275 // If the result of the expression is a non-vector type, we must be
276 // extracting a single element. Just codegen as an extractelement.
Chris Lattner4b492962007-08-10 17:10:08 +0000277 const VectorType *ExprVT = ExprType->getAsVectorType();
278 if (!ExprVT) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000279 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000280 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
281 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
282 }
283
284 // If the source and destination have the same number of elements, use a
285 // vector shuffle instead of insert/extracts.
Chris Lattner4b492962007-08-10 17:10:08 +0000286 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner944f7962007-08-03 16:18:34 +0000287 unsigned NumSourceElts =
288 cast<llvm::VectorType>(Vec->getType())->getNumElements();
289
290 if (NumResultElts == NumSourceElts) {
291 llvm::SmallVector<llvm::Constant*, 4> Mask;
292 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000293 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000294 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
295 }
296
297 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
298 Vec = Builder.CreateShuffleVector(Vec,
299 llvm::UndefValue::get(Vec->getType()),
300 MaskV, "tmp");
301 return RValue::get(Vec);
302 }
303
304 // Start out with an undef of the result type.
305 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
306
307 // Extract/Insert each element of the result.
308 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000309 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000310 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
311 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
312
313 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
314 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
315 }
316
317 return RValue::get(Result);
318}
319
320
Chris Lattner4b009652007-07-25 00:24:17 +0000321RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
322 return EmitLoadOfLValue(EmitLValue(E), E->getType());
323}
324
325
326/// EmitStoreThroughLValue - Store the specified rvalue into the specified
327/// lvalue, where both are guaranteed to the have the same type, and that type
328/// is 'Ty'.
329void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
330 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000331 if (!Dst.isSimple()) {
332 if (Dst.isVectorElt()) {
333 // Read/modify/write the vector, inserting the new element.
334 // FIXME: Volatility.
335 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
336 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
337 Dst.getVectorIdx(), "vecins");
338 Builder.CreateStore(Vec, Dst.getVectorAddr());
339 return;
340 }
Chris Lattner4b009652007-07-25 00:24:17 +0000341
Chris Lattner5bfdd232007-08-03 16:28:33 +0000342 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000343 if (Dst.isOCUVectorElt())
Chris Lattner5bfdd232007-08-03 16:28:33 +0000344 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
345
346 assert(0 && "FIXME: Don't support store to bitfield yet");
347 }
Chris Lattner4b009652007-07-25 00:24:17 +0000348
349 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000350 assert(Src.isScalar() && "Can't emit an agg store with this method");
351 // FIXME: Handle volatility etc.
352 const llvm::Type *SrcTy = Src.getVal()->getType();
353 const llvm::Type *AddrTy =
354 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
Chris Lattner4b009652007-07-25 00:24:17 +0000355
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000356 if (AddrTy != SrcTy)
357 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
358 "storetmp");
359 Builder.CreateStore(Src.getVal(), DstAddr);
Chris Lattner4b009652007-07-25 00:24:17 +0000360}
361
Chris Lattner5bfdd232007-08-03 16:28:33 +0000362void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
363 QualType Ty) {
364 // This access turns into a read/modify/write of the vector. Load the input
365 // value now.
366 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
367 // FIXME: Volatility.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000368 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000369
370 llvm::Value *SrcVal = Src.getVal();
371
Chris Lattner940966d2007-08-03 16:37:04 +0000372 if (const VectorType *VTy = Ty->getAsVectorType()) {
373 unsigned NumSrcElts = VTy->getNumElements();
374
375 // Extract/Insert each element.
376 for (unsigned i = 0; i != NumSrcElts; ++i) {
377 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
378 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
379
Chris Lattnera0d03a72007-08-03 17:31:20 +0000380 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner940966d2007-08-03 16:37:04 +0000381 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
382 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
383 }
384 } else {
385 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000386 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner5bfdd232007-08-03 16:28:33 +0000387 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
388 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000389 }
390
Chris Lattner5bfdd232007-08-03 16:28:33 +0000391 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
392}
393
Chris Lattner4b009652007-07-25 00:24:17 +0000394
395LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
396 const Decl *D = E->getDecl();
397 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
398 llvm::Value *V = LocalDeclMap[D];
399 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
400 return LValue::MakeAddr(V);
401 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
402 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
403 }
404 assert(0 && "Unimp declref");
405}
406
407LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
408 // __extension__ doesn't affect lvalue-ness.
409 if (E->getOpcode() == UnaryOperator::Extension)
410 return EmitLValue(E->getSubExpr());
411
412 assert(E->getOpcode() == UnaryOperator::Deref &&
413 "'*' is the only unary operator that produces an lvalue");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000414 return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()));
Chris Lattner4b009652007-07-25 00:24:17 +0000415}
416
417LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
418 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
419 const char *StrData = E->getStrData();
420 unsigned Len = E->getByteLength();
421
422 // FIXME: Can cache/reuse these within the module.
423 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
424
425 // Create a global variable for this.
426 C = new llvm::GlobalVariable(C->getType(), true,
427 llvm::GlobalValue::InternalLinkage,
428 C, ".str", CurFn->getParent());
429 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
430 llvm::Constant *Zeros[] = { Zero, Zero };
431 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
432 return LValue::MakeAddr(C);
433}
434
435LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
436 std::string FunctionName(CurFuncDecl->getName());
437 std::string GlobalVarName;
438
439 switch (E->getIdentType()) {
440 default:
441 assert(0 && "unknown pre-defined ident type");
442 case PreDefinedExpr::Func:
443 GlobalVarName = "__func__.";
444 break;
445 case PreDefinedExpr::Function:
446 GlobalVarName = "__FUNCTION__.";
447 break;
448 case PreDefinedExpr::PrettyFunction:
449 // FIXME:: Demangle C++ method names
450 GlobalVarName = "__PRETTY_FUNCTION__.";
451 break;
452 }
453
454 GlobalVarName += CurFuncDecl->getName();
455
456 // FIXME: Can cache/reuse these within the module.
457 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
458
459 // Create a global variable for this.
460 C = new llvm::GlobalVariable(C->getType(), true,
461 llvm::GlobalValue::InternalLinkage,
462 C, GlobalVarName, CurFn->getParent());
463 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
464 llvm::Constant *Zeros[] = { Zero, Zero };
465 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
466 return LValue::MakeAddr(C);
467}
468
469LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000470 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000471 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Chris Lattner4b009652007-07-25 00:24:17 +0000472
473 // If the base is a vector type, then we are forming a vector element lvalue
474 // with this subscript.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000475 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000476 // Emit the vector as an lvalue to get its address.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000477 LValue LHS = EmitLValue(E->getLHS());
478 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner4b009652007-07-25 00:24:17 +0000479 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000480 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner4b009652007-07-25 00:24:17 +0000481 }
482
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000483 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000484 llvm::Value *Base = EmitScalarExpr(E->getBase());
Chris Lattner4b009652007-07-25 00:24:17 +0000485
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000486 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000487 QualType IdxTy = E->getIdx()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000488 bool IdxSigned = IdxTy->isSignedIntegerType();
489 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
490 if (IdxBitwidth != LLVMPointerWidth)
491 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
492 IdxSigned, "idxprom");
493
494 // We know that the pointer points to a type of the correct size, unless the
495 // size is a VLA.
496 if (!E->getType()->isConstantSizeType(getContext()))
497 assert(0 && "VLA idx not implemented");
498 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
499}
500
Chris Lattner65520192007-08-02 23:37:31 +0000501LValue CodeGenFunction::
Chris Lattnera0d03a72007-08-03 17:31:20 +0000502EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner65520192007-08-02 23:37:31 +0000503 // Emit the base vector as an l-value.
504 LValue Base = EmitLValue(E->getBase());
505 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
506
Chris Lattnera0d03a72007-08-03 17:31:20 +0000507 return LValue::MakeOCUVectorElt(Base.getAddress(),
508 E->getEncodedElementAccess());
Chris Lattner65520192007-08-02 23:37:31 +0000509}
510
Chris Lattner4b009652007-07-25 00:24:17 +0000511//===--------------------------------------------------------------------===//
512// Expression Emission
513//===--------------------------------------------------------------------===//
514
Chris Lattner348c8a22007-08-23 23:43:33 +0000515/// EmitAnyExpr - Emit an expression of any type: scalar, complex, aggregate,
516/// returning an rvalue corresponding to it. If NeedResult is false, the
517/// result of the expression doesn't need to be generated into memory.
518RValue CodeGenFunction::EmitAnyExpr(const Expr *E, bool NeedResult) {
519 if (!hasAggregateLLVMType(E->getType()))
Chris Lattner9fba49a2007-08-24 05:35:26 +0000520 return RValue::get(EmitScalarExpr(E));
Chris Lattner348c8a22007-08-23 23:43:33 +0000521
522 llvm::Value *DestMem = 0;
523 if (NeedResult)
524 DestMem = CreateTempAlloca(ConvertType(E->getType()));
525
526 if (!E->getType()->isComplexType()) {
527 EmitAggExpr(E, DestMem, false);
528 } else if (NeedResult)
529 EmitComplexExprIntoAddr(E, DestMem);
530 else
531 EmitComplexExpr(E);
532
533 return RValue::getAggregate(DestMem);
534}
535
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000536
Chris Lattner4b009652007-07-25 00:24:17 +0000537RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson49865302007-08-20 18:05:56 +0000538 if (const ImplicitCastExpr *IcExpr =
539 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
540 if (const DeclRefExpr *DRExpr =
541 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
542 if (const FunctionDecl *FDecl =
543 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
544 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
545 return EmitBuiltinExpr(builtinID, E);
546
Chris Lattner9fba49a2007-08-24 05:35:26 +0000547 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Chris Lattner4b009652007-07-25 00:24:17 +0000548
549 // The callee type will always be a pointer to function type, get the function
550 // type.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000551 QualType CalleeTy = E->getCallee()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000552 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
553
554 // Get information about the argument types.
555 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
556
557 // Calling unprototyped functions provides no argument info.
558 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
559 ArgTyIt = FTP->arg_type_begin();
560 ArgTyEnd = FTP->arg_type_end();
561 }
562
563 llvm::SmallVector<llvm::Value*, 16> Args;
564
Chris Lattner59802042007-08-10 17:02:28 +0000565 // Handle struct-return functions by passing a pointer to the location that
566 // we would like to return into.
567 if (hasAggregateLLVMType(E->getType())) {
568 // Create a temporary alloca to hold the result of the call. :(
569 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
570 // FIXME: set the stret attribute on the argument.
571 }
572
Chris Lattner4b009652007-07-25 00:24:17 +0000573 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000574 QualType ArgTy = E->getArg(i)->getType();
Chris Lattner348c8a22007-08-23 23:43:33 +0000575 RValue ArgVal = EmitAnyExpr(E->getArg(i));
Chris Lattner4b009652007-07-25 00:24:17 +0000576
577 // If this argument has prototype information, convert it.
578 if (ArgTyIt != ArgTyEnd) {
579 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
580 } else {
581 // Otherwise, if passing through "..." or to a function with no prototype,
582 // perform the "default argument promotions" (C99 6.5.2.2p6), which
583 // includes the usual unary conversions, but also promotes float to
584 // double.
585 if (const BuiltinType *BT =
586 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
587 if (BT->getKind() == BuiltinType::Float)
588 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
589 llvm::Type::DoubleTy,"tmp"));
590 }
591 }
592
Chris Lattner4b009652007-07-25 00:24:17 +0000593 if (ArgVal.isScalar())
594 Args.push_back(ArgVal.getVal());
595 else // Pass by-address. FIXME: Set attribute bit on call.
596 Args.push_back(ArgVal.getAggregateAddr());
597 }
598
Chris Lattnera9572252007-08-01 06:24:52 +0000599 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000600 if (V->getType() != llvm::Type::VoidTy)
601 V->setName("call");
Chris Lattner59802042007-08-10 17:02:28 +0000602 else if (hasAggregateLLVMType(E->getType()))
603 // Struct return.
604 return RValue::getAggregate(Args[0]);
605
Chris Lattner4b009652007-07-25 00:24:17 +0000606 return RValue::get(V);
607}