blob: 9256a5d77348bdedc1efc74d7d79f5a82bdf4f4e [file] [log] [blame]
Chris Lattnere47e4402007-06-01 18:02:12 +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"
Chris Lattnerb6984c42007-06-20 04:44:43 +000015#include "CodeGenModule.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000016#include "clang/AST/AST.h"
Anders Carlsson1d8e5212007-08-20 18:05:56 +000017#include "clang/Lex/IdentifierTable.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
Chris Lattner4347e3692007-06-06 04:54:52 +000020#include "llvm/Function.h"
21#include "llvm/GlobalVariable.h"
Chris Lattner651f0e92007-07-16 05:43:05 +000022#include "llvm/Support/MathExtras.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000023using namespace clang;
24using namespace CodeGen;
25
Chris Lattnerd7f58862007-06-02 05:24:33 +000026//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000027// Miscellaneous Helper Methods
28//===--------------------------------------------------------------------===//
29
Chris Lattnere9a64532007-06-22 21:44:33 +000030/// 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}
Chris Lattner8394d792007-06-05 20:53:16 +000036
37/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
38/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000039llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattner8ad56702007-08-24 00:01:20 +000040 return ConvertScalarValueToBool(EmitAnyExpr(E), E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +000041}
42
43//===--------------------------------------------------------------------===//
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,
Chris Lattnerf033c142007-06-22 19:05:19 +000050 QualType DstTy) {
Chris Lattner8394d792007-06-05 20:53:16 +000051 ValTy = ValTy.getCanonicalType();
52 DstTy = DstTy.getCanonicalType();
53 if (ValTy == DstTy) return Val;
Chris Lattner83b484b2007-06-06 04:39:08 +000054
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));
Chris Lattner8394d792007-06-05 20:53:16 +000059
Chris Lattner83b484b2007-06-06 04:39:08 +000060 // Handle pointer conversions next: pointers can only be converted to/from
61 // other pointers and integers.
Chris Lattnercf106ab2007-06-06 04:05:39 +000062 if (isa<PointerType>(DstTy)) {
Chris Lattnerf033c142007-06-22 19:05:19 +000063 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattnercf106ab2007-06-06 04:05:39 +000064
Chris Lattner02697702007-08-10 16:33:59 +000065 if (Val.getVal()->getType() == DestTy)
66 return Val;
67
Chris Lattnercf106ab2007-06-06 04:05:39 +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?");
Chris Lattnerfc7634f2007-07-13 03:25:53 +000073 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Chris Lattner83b484b2007-06-06 04:39:08 +000074 }
75
76 if (isa<PointerType>(ValTy)) {
Chris Lattnercf106ab2007-06-06 04:05:39 +000077 // Must be an ptr to int cast.
Chris Lattnerf033c142007-06-22 19:05:19 +000078 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattnercf106ab2007-06-06 04:05:39 +000079 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
80 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Chris Lattner8394d792007-06-05 20:53:16 +000081 }
Chris Lattner83b484b2007-06-06 04:39:08 +000082
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.
Chris Lattner23b7eb62007-06-15 23:05:46 +000089 llvm::Value *SrcVal = Val.getVal();
Chris Lattnerf033c142007-06-22 19:05:19 +000090 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattner83b484b2007-06-06 04:39:08 +000091 if (SrcVal->getType() == DestTy) return Val;
92
Chris Lattner23b7eb62007-06-15 23:05:46 +000093 llvm::Value *Result;
Chris Lattner83b484b2007-06-06 04:39:08 +000094 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!");
Chris Lattner8394d792007-06-05 20:53:16 +0000121}
122
123
124/// ConvertScalarValueToBool - Convert the specified expression value to a
Chris Lattnerf0106d22007-06-02 19:33:17 +0000125/// boolean (i1) truth value. This is equivalent to "Val == 0".
Chris Lattner23b7eb62007-06-15 23:05:46 +0000126llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
Chris Lattnerf0106d22007-06-02 19:33:17 +0000127 Ty = Ty.getCanonicalType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000128 llvm::Value *Result;
Chris Lattnerf0106d22007-06-02 19:33:17 +0000129 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;
Chris Lattnerb16f4552007-06-03 07:25:34 +0000138 case BuiltinType::Char_S:
139 case BuiltinType::Char_U:
Chris Lattnerf0106d22007-06-02 19:33:17 +0000140 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();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000157 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000158 // FIXME: llvm-gcc produces a une comparison: validate this is right.
159 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
160 return Result;
161 }
Chris Lattnerf0106d22007-06-02 19:33:17 +0000162 }
Chris Lattner8ad56702007-08-24 00:01:20 +0000163 } else if (isa<ComplexType>(Ty)) {
164 assert(0 && "implement complex -> bool");
165
Chris Lattnerc6395932007-06-22 20:56:16 +0000166 } else {
Chris Lattner8ad56702007-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 Lattnerf0106d22007-06-02 19:33:17 +0000172 }
173
174 // Usual case for integers, pointers, and enums: compare against zero.
175 Result = Val.getVal();
Chris Lattnera45c5af2007-06-02 19:47:04 +0000176
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.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000180 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
Chris Lattnera45c5af2007-06-02 19:47:04 +0000181 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
182 Result = ZI->getOperand(0);
183 ZI->eraseFromParent();
184 return Result;
185 }
186 }
187
Chris Lattner23b7eb62007-06-15 23:05:46 +0000188 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000189 return Builder.CreateICmpNE(Result, Zero, "tobool");
190}
191
Chris Lattnera45c5af2007-06-02 19:47:04 +0000192//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000193// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000194//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000195
Chris Lattner8394d792007-06-05 20:53:16 +0000196/// 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///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000212LValue CodeGenFunction::EmitLValue(const Expr *E) {
213 switch (E->getStmtClass()) {
Chris Lattnerc7f06ca2007-08-26 05:06:40 +0000214 default: {
Chris Lattner8394d792007-06-05 20:53:16 +0000215 fprintf(stderr, "Unimplemented lvalue expr!\n");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000216 E->dump();
Chris Lattnerc7f06ca2007-08-26 05:06:40 +0000217 llvm::Type *Ty = llvm::PointerType::get(ConvertType(E->getType()));
218 return LValue::MakeAddr(llvm::UndefValue::get(Ty));
219 }
Chris Lattnerd7f58862007-06-02 05:24:33 +0000220
221 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Chris Lattner946aa312007-06-05 03:59:43 +0000222 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Anders Carlsson625bfc82007-07-21 05:21:51 +0000223 case Expr::PreDefinedExprClass:
224 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000225 case Expr::StringLiteralClass:
226 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000227
228 case Expr::UnaryOperatorClass:
229 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000230 case Expr::ArraySubscriptExprClass:
231 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000232 case Expr::OCUVectorElementExprClass:
233 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000234 }
235}
236
Chris Lattner8394d792007-06-05 20:53:16 +0000237/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
238/// this method emits the address of the lvalue, then loads the result as an
239/// rvalue, returning the rvalue.
Chris Lattner9369a562007-06-29 16:31:29 +0000240RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000241 if (LV.isSimple()) {
242 llvm::Value *Ptr = LV.getAddress();
243 const llvm::Type *EltTy =
244 cast<llvm::PointerType>(Ptr->getType())->getElementType();
245
246 // Simple scalar l-value.
247 if (EltTy->isFirstClassType())
248 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
249
Chris Lattner6278e6a2007-08-11 00:04:45 +0000250 assert(ExprType->isFunctionType() && "Unknown scalar value");
251 return RValue::get(Ptr);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000252 }
Chris Lattner09153c02007-06-22 18:48:09 +0000253
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000254 if (LV.isVectorElt()) {
255 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
256 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
257 "vecext"));
258 }
Chris Lattner73ab9b32007-08-03 00:16:29 +0000259
260 // If this is a reference to a subset of the elements of a vector, either
261 // shuffle the input or extract/insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000262 if (LV.isOCUVectorElt())
263 return EmitLoadOfOCUElementLValue(LV, ExprType);
Chris Lattner09153c02007-06-22 18:48:09 +0000264
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000265 assert(0 && "Bitfield ref not impl!");
Chris Lattner8394d792007-06-05 20:53:16 +0000266}
267
Chris Lattner40ff7012007-08-03 16:18:34 +0000268// If this is a reference to a subset of the elements of a vector, either
269// shuffle the input or extract/insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000270RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000271 QualType ExprType) {
Chris Lattner40ff7012007-08-03 16:18:34 +0000272 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
273
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000274 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner40ff7012007-08-03 16:18:34 +0000275
276 // If the result of the expression is a non-vector type, we must be
277 // extracting a single element. Just codegen as an extractelement.
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000278 const VectorType *ExprVT = ExprType->getAsVectorType();
279 if (!ExprVT) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000280 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000281 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
282 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
283 }
284
285 // If the source and destination have the same number of elements, use a
286 // vector shuffle instead of insert/extracts.
Chris Lattner8eab8ff2007-08-10 17:10:08 +0000287 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner40ff7012007-08-03 16:18:34 +0000288 unsigned NumSourceElts =
289 cast<llvm::VectorType>(Vec->getType())->getNumElements();
290
291 if (NumResultElts == NumSourceElts) {
292 llvm::SmallVector<llvm::Constant*, 4> Mask;
293 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000294 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000295 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
296 }
297
298 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
299 Vec = Builder.CreateShuffleVector(Vec,
300 llvm::UndefValue::get(Vec->getType()),
301 MaskV, "tmp");
302 return RValue::get(Vec);
303 }
304
305 // Start out with an undef of the result type.
306 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
307
308 // Extract/Insert each element of the result.
309 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000310 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner40ff7012007-08-03 16:18:34 +0000311 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
312 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
313
314 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
315 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
316 }
317
318 return RValue::get(Result);
319}
320
321
Chris Lattner9369a562007-06-29 16:31:29 +0000322RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
323 return EmitLoadOfLValue(EmitLValue(E), E->getType());
324}
325
326
Chris Lattner8394d792007-06-05 20:53:16 +0000327/// EmitStoreThroughLValue - Store the specified rvalue into the specified
328/// lvalue, where both are guaranteed to the have the same type, and that type
329/// is 'Ty'.
330void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
331 QualType Ty) {
Chris Lattner41d480e2007-08-03 16:28:33 +0000332 if (!Dst.isSimple()) {
333 if (Dst.isVectorElt()) {
334 // Read/modify/write the vector, inserting the new element.
335 // FIXME: Volatility.
336 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
337 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
338 Dst.getVectorIdx(), "vecins");
339 Builder.CreateStore(Vec, Dst.getVectorAddr());
340 return;
341 }
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000342
Chris Lattner41d480e2007-08-03 16:28:33 +0000343 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000344 if (Dst.isOCUVectorElt())
Chris Lattner41d480e2007-08-03 16:28:33 +0000345 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
346
347 assert(0 && "FIXME: Don't support store to bitfield yet");
348 }
Chris Lattner8394d792007-06-05 20:53:16 +0000349
Chris Lattner09153c02007-06-22 18:48:09 +0000350 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattner6278e6a2007-08-11 00:04:45 +0000351 assert(Src.isScalar() && "Can't emit an agg store with this method");
352 // FIXME: Handle volatility etc.
353 const llvm::Type *SrcTy = Src.getVal()->getType();
354 const llvm::Type *AddrTy =
355 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
Chris Lattner8394d792007-06-05 20:53:16 +0000356
Chris Lattner6278e6a2007-08-11 00:04:45 +0000357 if (AddrTy != SrcTy)
358 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
359 "storetmp");
360 Builder.CreateStore(Src.getVal(), DstAddr);
Chris Lattner8394d792007-06-05 20:53:16 +0000361}
362
Chris Lattner41d480e2007-08-03 16:28:33 +0000363void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
364 QualType Ty) {
365 // This access turns into a read/modify/write of the vector. Load the input
366 // value now.
367 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
368 // FIXME: Volatility.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000369 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner41d480e2007-08-03 16:28:33 +0000370
371 llvm::Value *SrcVal = Src.getVal();
372
Chris Lattner3a44aa72007-08-03 16:37:04 +0000373 if (const VectorType *VTy = Ty->getAsVectorType()) {
374 unsigned NumSrcElts = VTy->getNumElements();
375
376 // Extract/Insert each element.
377 for (unsigned i = 0; i != NumSrcElts; ++i) {
378 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
379 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
380
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000381 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner3a44aa72007-08-03 16:37:04 +0000382 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
383 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
384 }
385 } else {
386 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000387 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner41d480e2007-08-03 16:28:33 +0000388 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
389 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner41d480e2007-08-03 16:28:33 +0000390 }
391
Chris Lattner41d480e2007-08-03 16:28:33 +0000392 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
393}
394
Chris Lattnerd7f58862007-06-02 05:24:33 +0000395
396LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
397 const Decl *D = E->getDecl();
Chris Lattner53621a52007-06-13 20:44:40 +0000398 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000399 llvm::Value *V = LocalDeclMap[D];
Chris Lattnerd7f58862007-06-02 05:24:33 +0000400 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000401 return LValue::MakeAddr(V);
Chris Lattnerb6984c42007-06-20 04:44:43 +0000402 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000403 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000404 }
405 assert(0 && "Unimp declref");
406}
Chris Lattnere47e4402007-06-01 18:02:12 +0000407
Chris Lattner8394d792007-06-05 20:53:16 +0000408LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
409 // __extension__ doesn't affect lvalue-ness.
410 if (E->getOpcode() == UnaryOperator::Extension)
411 return EmitLValue(E->getSubExpr());
412
413 assert(E->getOpcode() == UnaryOperator::Deref &&
414 "'*' is the only unary operator that produces an lvalue");
Chris Lattner2da04b32007-08-24 05:35:26 +0000415 return LValue::MakeAddr(EmitScalarExpr(E->getSubExpr()));
Chris Lattner8394d792007-06-05 20:53:16 +0000416}
417
Chris Lattner4347e3692007-06-06 04:54:52 +0000418LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
419 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
420 const char *StrData = E->getStrData();
421 unsigned Len = E->getByteLength();
422
423 // FIXME: Can cache/reuse these within the module.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000424 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
Chris Lattner4347e3692007-06-06 04:54:52 +0000425
426 // Create a global variable for this.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000427 C = new llvm::GlobalVariable(C->getType(), true,
428 llvm::GlobalValue::InternalLinkage,
Chris Lattner4347e3692007-06-06 04:54:52 +0000429 C, ".str", CurFn->getParent());
Chris Lattner23b7eb62007-06-15 23:05:46 +0000430 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
431 llvm::Constant *Zeros[] = { Zero, Zero };
432 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000433 return LValue::MakeAddr(C);
Chris Lattner4347e3692007-06-06 04:54:52 +0000434}
435
Anders Carlsson625bfc82007-07-21 05:21:51 +0000436LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
437 std::string FunctionName(CurFuncDecl->getName());
438 std::string GlobalVarName;
439
440 switch (E->getIdentType()) {
441 default:
442 assert(0 && "unknown pre-defined ident type");
443 case PreDefinedExpr::Func:
444 GlobalVarName = "__func__.";
445 break;
446 case PreDefinedExpr::Function:
447 GlobalVarName = "__FUNCTION__.";
448 break;
449 case PreDefinedExpr::PrettyFunction:
450 // FIXME:: Demangle C++ method names
451 GlobalVarName = "__PRETTY_FUNCTION__.";
452 break;
453 }
454
455 GlobalVarName += CurFuncDecl->getName();
456
457 // FIXME: Can cache/reuse these within the module.
458 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
459
460 // Create a global variable for this.
461 C = new llvm::GlobalVariable(C->getType(), true,
462 llvm::GlobalValue::InternalLinkage,
463 C, GlobalVarName, CurFn->getParent());
464 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
465 llvm::Constant *Zeros[] = { Zero, Zero };
466 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
467 return LValue::MakeAddr(C);
468}
469
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000470LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenekc81614d2007-08-20 16:18:38 +0000471 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +0000472 llvm::Value *Idx = EmitScalarExpr(E->getIdx());
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000473
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000474 // If the base is a vector type, then we are forming a vector element lvalue
475 // with this subscript.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000476 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000477 // Emit the vector as an lvalue to get its address.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000478 LValue LHS = EmitLValue(E->getLHS());
479 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000480 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenekc81614d2007-08-20 16:18:38 +0000481 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000482 }
483
Ted Kremenekc81614d2007-08-20 16:18:38 +0000484 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner2da04b32007-08-24 05:35:26 +0000485 llvm::Value *Base = EmitScalarExpr(E->getBase());
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000486
Ted Kremenekc81614d2007-08-20 16:18:38 +0000487 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000488 QualType IdxTy = E->getIdx()->getType();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000489 bool IdxSigned = IdxTy->isSignedIntegerType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000490 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000491 if (IdxBitwidth != LLVMPointerWidth)
Chris Lattner23b7eb62007-06-15 23:05:46 +0000492 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000493 IdxSigned, "idxprom");
494
495 // We know that the pointer points to a type of the correct size, unless the
496 // size is a VLA.
Chris Lattner0e9d6222007-07-15 23:26:56 +0000497 if (!E->getType()->isConstantSizeType(getContext()))
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000498 assert(0 && "VLA idx not implemented");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000499 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000500}
501
Chris Lattner9e751ca2007-08-02 23:37:31 +0000502LValue CodeGenFunction::
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000503EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner9e751ca2007-08-02 23:37:31 +0000504 // Emit the base vector as an l-value.
505 LValue Base = EmitLValue(E->getBase());
506 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
507
Chris Lattnerd268a7a2007-08-03 17:31:20 +0000508 return LValue::MakeOCUVectorElt(Base.getAddress(),
509 E->getEncodedElementAccess());
Chris Lattner9e751ca2007-08-02 23:37:31 +0000510}
511
Chris Lattnere47e4402007-06-01 18:02:12 +0000512//===--------------------------------------------------------------------===//
513// Expression Emission
514//===--------------------------------------------------------------------===//
515
Chris Lattner08b15df2007-08-23 23:43:33 +0000516/// EmitAnyExpr - Emit an expression of any type: scalar, complex, aggregate,
517/// returning an rvalue corresponding to it. If NeedResult is false, the
518/// result of the expression doesn't need to be generated into memory.
519RValue CodeGenFunction::EmitAnyExpr(const Expr *E, bool NeedResult) {
520 if (!hasAggregateLLVMType(E->getType()))
Chris Lattner2da04b32007-08-24 05:35:26 +0000521 return RValue::get(EmitScalarExpr(E));
Chris Lattner08b15df2007-08-23 23:43:33 +0000522
523 llvm::Value *DestMem = 0;
524 if (NeedResult)
525 DestMem = CreateTempAlloca(ConvertType(E->getType()));
526
527 if (!E->getType()->isComplexType()) {
528 EmitAggExpr(E, DestMem, false);
529 } else if (NeedResult)
530 EmitComplexExprIntoAddr(E, DestMem);
531 else
532 EmitComplexExpr(E);
533
534 return RValue::getAggregate(DestMem);
535}
536
Chris Lattner76ba8492007-08-20 22:37:10 +0000537
Chris Lattner2b228c92007-06-15 21:34:29 +0000538RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson1d8e5212007-08-20 18:05:56 +0000539 if (const ImplicitCastExpr *IcExpr =
540 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
541 if (const DeclRefExpr *DRExpr =
542 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
543 if (const FunctionDecl *FDecl =
544 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
545 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
546 return EmitBuiltinExpr(builtinID, E);
547
Chris Lattner2da04b32007-08-24 05:35:26 +0000548 llvm::Value *Callee = EmitScalarExpr(E->getCallee());
Chris Lattnerc14236b2007-07-10 22:18:37 +0000549
550 // The callee type will always be a pointer to function type, get the function
551 // type.
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000552 QualType CalleeTy = E->getCallee()->getType();
Chris Lattnerc14236b2007-07-10 22:18:37 +0000553 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
554
555 // Get information about the argument types.
556 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
557
558 // Calling unprototyped functions provides no argument info.
559 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
560 ArgTyIt = FTP->arg_type_begin();
561 ArgTyEnd = FTP->arg_type_end();
562 }
Chris Lattner2b228c92007-06-15 21:34:29 +0000563
Chris Lattner23b7eb62007-06-15 23:05:46 +0000564 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattner2b228c92007-06-15 21:34:29 +0000565
Chris Lattner90d91202007-08-10 17:02:28 +0000566 // Handle struct-return functions by passing a pointer to the location that
567 // we would like to return into.
568 if (hasAggregateLLVMType(E->getType())) {
569 // Create a temporary alloca to hold the result of the call. :(
570 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
571 // FIXME: set the stret attribute on the argument.
572 }
573
Chris Lattner2b228c92007-06-15 21:34:29 +0000574 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner5ebb2fe2007-08-08 17:43:05 +0000575 QualType ArgTy = E->getArg(i)->getType();
Chris Lattner08b15df2007-08-23 23:43:33 +0000576 RValue ArgVal = EmitAnyExpr(E->getArg(i));
Chris Lattnerc14236b2007-07-10 22:18:37 +0000577
578 // If this argument has prototype information, convert it.
579 if (ArgTyIt != ArgTyEnd) {
580 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
581 } else {
582 // Otherwise, if passing through "..." or to a function with no prototype,
583 // perform the "default argument promotions" (C99 6.5.2.2p6), which
584 // includes the usual unary conversions, but also promotes float to
585 // double.
586 if (const BuiltinType *BT =
587 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
588 if (BT->getKind() == BuiltinType::Float)
589 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
590 llvm::Type::DoubleTy,"tmp"));
591 }
592 }
593
Chris Lattner2b228c92007-06-15 21:34:29 +0000594 if (ArgVal.isScalar())
595 Args.push_back(ArgVal.getVal());
596 else // Pass by-address. FIXME: Set attribute bit on call.
Chris Lattner09153c02007-06-22 18:48:09 +0000597 Args.push_back(ArgVal.getAggregateAddr());
Chris Lattner2b228c92007-06-15 21:34:29 +0000598 }
599
Chris Lattner7b9f04e2007-08-01 06:24:52 +0000600 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner2b228c92007-06-15 21:34:29 +0000601 if (V->getType() != llvm::Type::VoidTy)
602 V->setName("call");
Chris Lattner90d91202007-08-10 17:02:28 +0000603 else if (hasAggregateLLVMType(E->getType()))
604 // Struct return.
605 return RValue::getAggregate(Args[0]);
606
Chris Lattner2b228c92007-06-15 21:34:29 +0000607 return RValue::get(V);
608}