blob: c37b3f933e92718296d231c89acaeff3f70b9679 [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"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
Chris Lattner4347e3692007-06-06 04:54:52 +000019#include "llvm/Function.h"
20#include "llvm/GlobalVariable.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000021using namespace clang;
22using namespace CodeGen;
23
Chris Lattnerd7f58862007-06-02 05:24:33 +000024//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000025// Miscellaneous Helper Methods
26//===--------------------------------------------------------------------===//
27
Chris Lattnere9a64532007-06-22 21:44:33 +000028/// CreateTempAlloca - This creates a alloca and inserts it into the entry
29/// block.
30llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
31 const char *Name) {
32 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
33}
Chris Lattner8394d792007-06-05 20:53:16 +000034
35/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
36/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000037llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattner8394d792007-06-05 20:53:16 +000038 QualType Ty;
39 RValue Val = EmitExprWithUsualUnaryConversions(E, Ty);
40 return ConvertScalarValueToBool(Val, Ty);
41}
42
Chris Lattnere9a64532007-06-22 21:44:33 +000043/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
44/// load the real and imaginary pieces, returning them as Real/Imag.
45void CodeGenFunction::EmitLoadOfComplex(RValue V,
46 llvm::Value *&Real, llvm::Value *&Imag){
47 llvm::Value *Ptr = V.getAggregateAddr();
48
49 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
50 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
51 llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "realp");
52 llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imagp");
53
54 // FIXME: Handle volatility.
55 Real = Builder.CreateLoad(RealPtr, "real");
56 Imag = Builder.CreateLoad(ImagPtr, "imag");
57}
58
59/// EmitStoreOfComplex - Store the specified real/imag parts into the
60/// specified value pointer.
61void CodeGenFunction::EmitStoreOfComplex(llvm::Value *Real, llvm::Value *Imag,
62 llvm::Value *ResPtr) {
63 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
64 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
65 llvm::Value *RealPtr = Builder.CreateGEP(ResPtr, Zero, Zero, "real");
66 llvm::Value *ImagPtr = Builder.CreateGEP(ResPtr, Zero, One, "imag");
67
68 // FIXME: Handle volatility.
69 Builder.CreateStore(Real, RealPtr);
70 Builder.CreateStore(Imag, ImagPtr);
71}
72
Chris Lattner8394d792007-06-05 20:53:16 +000073//===--------------------------------------------------------------------===//
74// Conversions
75//===--------------------------------------------------------------------===//
76
77/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
78/// the type specified by DstTy, following the rules of C99 6.3.
79RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
Chris Lattnerf033c142007-06-22 19:05:19 +000080 QualType DstTy) {
Chris Lattner8394d792007-06-05 20:53:16 +000081 ValTy = ValTy.getCanonicalType();
82 DstTy = DstTy.getCanonicalType();
83 if (ValTy == DstTy) return Val;
Chris Lattner83b484b2007-06-06 04:39:08 +000084
85 // Handle conversions to bool first, they are special: comparisons against 0.
86 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
87 if (DestBT->getKind() == BuiltinType::Bool)
88 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
Chris Lattner8394d792007-06-05 20:53:16 +000089
Chris Lattner83b484b2007-06-06 04:39:08 +000090 // Handle pointer conversions next: pointers can only be converted to/from
91 // other pointers and integers.
Chris Lattnercf106ab2007-06-06 04:05:39 +000092 if (isa<PointerType>(DstTy)) {
Chris Lattnerf033c142007-06-22 19:05:19 +000093 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattnercf106ab2007-06-06 04:05:39 +000094
95 // The source value may be an integer, or a pointer.
96 assert(Val.isScalar() && "Can only convert from integer or pointer");
97 if (isa<llvm::PointerType>(Val.getVal()->getType()))
98 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
99 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
100 return RValue::get(Builder.CreatePtrToInt(Val.getVal(), DestTy, "conv"));
Chris Lattner83b484b2007-06-06 04:39:08 +0000101 }
102
103 if (isa<PointerType>(ValTy)) {
Chris Lattnercf106ab2007-06-06 04:05:39 +0000104 // Must be an ptr to int cast.
Chris Lattnerf033c142007-06-22 19:05:19 +0000105 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattnercf106ab2007-06-06 04:05:39 +0000106 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
107 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Chris Lattner8394d792007-06-05 20:53:16 +0000108 }
Chris Lattner83b484b2007-06-06 04:39:08 +0000109
110 // Finally, we have the arithmetic types: real int/float and complex
111 // int/float. Handle real->real conversions first, they are the most
112 // common.
113 if (Val.isScalar() && DstTy->isRealType()) {
114 // We know that these are representable as scalars in LLVM, convert to LLVM
115 // types since they are easier to reason about.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000116 llvm::Value *SrcVal = Val.getVal();
Chris Lattnerf033c142007-06-22 19:05:19 +0000117 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattner83b484b2007-06-06 04:39:08 +0000118 if (SrcVal->getType() == DestTy) return Val;
119
Chris Lattner23b7eb62007-06-15 23:05:46 +0000120 llvm::Value *Result;
Chris Lattner83b484b2007-06-06 04:39:08 +0000121 if (isa<llvm::IntegerType>(SrcVal->getType())) {
122 bool InputSigned = ValTy->isSignedIntegerType();
123 if (isa<llvm::IntegerType>(DestTy))
124 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
125 else if (InputSigned)
126 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
127 else
128 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
129 } else {
130 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
131 if (isa<llvm::IntegerType>(DestTy)) {
132 if (DstTy->isSignedIntegerType())
133 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
134 else
135 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
136 } else {
137 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
138 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
139 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
140 else
141 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
142 }
143 }
144 return RValue::get(Result);
145 }
146
147 assert(0 && "FIXME: We don't support complex conversions yet!");
Chris Lattner8394d792007-06-05 20:53:16 +0000148}
149
150
151/// ConvertScalarValueToBool - Convert the specified expression value to a
Chris Lattnerf0106d22007-06-02 19:33:17 +0000152/// boolean (i1) truth value. This is equivalent to "Val == 0".
Chris Lattner23b7eb62007-06-15 23:05:46 +0000153llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
Chris Lattnerf0106d22007-06-02 19:33:17 +0000154 Ty = Ty.getCanonicalType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000155 llvm::Value *Result;
Chris Lattnerf0106d22007-06-02 19:33:17 +0000156 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
157 switch (BT->getKind()) {
158 default: assert(0 && "Unknown scalar value");
159 case BuiltinType::Bool:
160 Result = Val.getVal();
161 // Bool is already evaluated right.
162 assert(Result->getType() == llvm::Type::Int1Ty &&
163 "Unexpected bool value type!");
164 return Result;
Chris Lattnerb16f4552007-06-03 07:25:34 +0000165 case BuiltinType::Char_S:
166 case BuiltinType::Char_U:
Chris Lattnerf0106d22007-06-02 19:33:17 +0000167 case BuiltinType::SChar:
168 case BuiltinType::UChar:
169 case BuiltinType::Short:
170 case BuiltinType::UShort:
171 case BuiltinType::Int:
172 case BuiltinType::UInt:
173 case BuiltinType::Long:
174 case BuiltinType::ULong:
175 case BuiltinType::LongLong:
176 case BuiltinType::ULongLong:
177 // Code below handles simple integers.
178 break;
179 case BuiltinType::Float:
180 case BuiltinType::Double:
181 case BuiltinType::LongDouble: {
182 // Compare against 0.0 for fp scalars.
183 Result = Val.getVal();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000184 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000185 // FIXME: llvm-gcc produces a une comparison: validate this is right.
186 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
187 return Result;
188 }
Chris Lattnerf0106d22007-06-02 19:33:17 +0000189 }
Chris Lattnerc6395932007-06-22 20:56:16 +0000190 } else if (isa<PointerType>(Ty) ||
191 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000192 // Code below handles this fine.
Chris Lattnerc6395932007-06-22 20:56:16 +0000193 } else {
194 assert(isa<ComplexType>(Ty) && "Unknwon type!");
195 assert(0 && "FIXME: comparisons against complex not implemented yet");
Chris Lattnerf0106d22007-06-02 19:33:17 +0000196 }
197
198 // Usual case for integers, pointers, and enums: compare against zero.
199 Result = Val.getVal();
Chris Lattnera45c5af2007-06-02 19:47:04 +0000200
201 // Because of the type rules of C, we often end up computing a logical value,
202 // then zero extending it to int, then wanting it as a logical value again.
203 // Optimize this common case.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000204 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
Chris Lattnera45c5af2007-06-02 19:47:04 +0000205 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
206 Result = ZI->getOperand(0);
207 ZI->eraseFromParent();
208 return Result;
209 }
210 }
211
Chris Lattner23b7eb62007-06-15 23:05:46 +0000212 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000213 return Builder.CreateICmpNE(Result, Zero, "tobool");
214}
215
Chris Lattnera45c5af2007-06-02 19:47:04 +0000216//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000217// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000218//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000219
Chris Lattner8394d792007-06-05 20:53:16 +0000220/// EmitLValue - Emit code to compute a designator that specifies the location
221/// of the expression.
222///
223/// This can return one of two things: a simple address or a bitfield
224/// reference. In either case, the LLVM Value* in the LValue structure is
225/// guaranteed to be an LLVM pointer type.
226///
227/// If this returns a bitfield reference, nothing about the pointee type of
228/// the LLVM value is known: For example, it may not be a pointer to an
229/// integer.
230///
231/// If this returns a normal address, and if the lvalue's C type is fixed
232/// size, this method guarantees that the returned pointer type will point to
233/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
234/// variable length type, this is not possible.
235///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000236LValue CodeGenFunction::EmitLValue(const Expr *E) {
237 switch (E->getStmtClass()) {
238 default:
Chris Lattner8394d792007-06-05 20:53:16 +0000239 fprintf(stderr, "Unimplemented lvalue expr!\n");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000240 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000241 return LValue::getAddr(llvm::UndefValue::get(
Chris Lattnerd7f58862007-06-02 05:24:33 +0000242 llvm::PointerType::get(llvm::Type::Int32Ty)));
243
244 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Chris Lattner946aa312007-06-05 03:59:43 +0000245 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner4347e3692007-06-06 04:54:52 +0000246 case Expr::StringLiteralClass:
247 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000248
249 case Expr::UnaryOperatorClass:
250 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000251 case Expr::ArraySubscriptExprClass:
252 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000253 }
254}
255
Chris Lattner8394d792007-06-05 20:53:16 +0000256/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
257/// this method emits the address of the lvalue, then loads the result as an
258/// rvalue, returning the rvalue.
Chris Lattner9369a562007-06-29 16:31:29 +0000259RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
260 ExprType = ExprType.getCanonicalType();
Chris Lattner8394d792007-06-05 20:53:16 +0000261
262 // FIXME: this is silly and obviously wrong for non-scalars.
263 assert(!LV.isBitfield());
Chris Lattner09153c02007-06-22 18:48:09 +0000264 llvm::Value *Ptr = LV.getAddress();
265 const llvm::Type *EltTy =
266 cast<llvm::PointerType>(Ptr->getType())->getElementType();
267
268 // Simple scalar l-value.
269 if (EltTy->isFirstClassType())
270 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
271
272 // Otherwise, we have an aggregate lvalue.
273 return RValue::getAggregate(Ptr);
Chris Lattner8394d792007-06-05 20:53:16 +0000274}
275
Chris Lattner9369a562007-06-29 16:31:29 +0000276RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
277 return EmitLoadOfLValue(EmitLValue(E), E->getType());
278}
279
280
Chris Lattner8394d792007-06-05 20:53:16 +0000281/// EmitStoreThroughLValue - Store the specified rvalue into the specified
282/// lvalue, where both are guaranteed to the have the same type, and that type
283/// is 'Ty'.
284void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
285 QualType Ty) {
Chris Lattner8394d792007-06-05 20:53:16 +0000286 assert(!Dst.isBitfield() && "FIXME: Don't support store to bitfield yet");
Chris Lattner8394d792007-06-05 20:53:16 +0000287
Chris Lattner09153c02007-06-22 18:48:09 +0000288 llvm::Value *DstAddr = Dst.getAddress();
289 if (Src.isScalar()) {
290 // FIXME: Handle volatility etc.
291 const llvm::Type *SrcTy = Src.getVal()->getType();
292 const llvm::Type *AddrTy =
293 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
294
295 if (AddrTy != SrcTy)
296 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
297 "storetmp");
298 Builder.CreateStore(Src.getVal(), DstAddr);
299 return;
300 }
Chris Lattner8394d792007-06-05 20:53:16 +0000301
Chris Lattnere9a64532007-06-22 21:44:33 +0000302 // Don't use memcpy for complex numbers.
303 if (Ty->isComplexType()) {
304 llvm::Value *Real, *Imag;
305 EmitLoadOfComplex(Src, Real, Imag);
306 EmitStoreOfComplex(Real, Imag, Dst.getAddress());
307 return;
308 }
309
Chris Lattner09153c02007-06-22 18:48:09 +0000310 // Aggregate assignment turns into llvm.memcpy.
311 const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
312 llvm::Value *SrcAddr = Src.getAggregateAddr();
313
314 if (DstAddr->getType() != SBP)
315 DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
316 if (SrcAddr->getType() != SBP)
317 SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
318
319 unsigned Align = 1; // FIXME: Compute type alignments.
320 unsigned Size = 1234; // FIXME: Compute type sizes.
321
322 // FIXME: Handle variable sized types.
323 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
324 llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
325
326 llvm::Value *MemCpyOps[4] = {
327 DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
328 };
329
330 Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, 4);
Chris Lattner8394d792007-06-05 20:53:16 +0000331}
332
Chris Lattnerd7f58862007-06-02 05:24:33 +0000333
334LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
335 const Decl *D = E->getDecl();
Chris Lattner53621a52007-06-13 20:44:40 +0000336 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000337 llvm::Value *V = LocalDeclMap[D];
Chris Lattnerd7f58862007-06-02 05:24:33 +0000338 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
339 return LValue::getAddr(V);
Chris Lattnerb6984c42007-06-20 04:44:43 +0000340 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
341 return LValue::getAddr(CGM.GetAddrOfGlobalDecl(D));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000342 }
343 assert(0 && "Unimp declref");
344}
Chris Lattnere47e4402007-06-01 18:02:12 +0000345
Chris Lattner8394d792007-06-05 20:53:16 +0000346LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
347 // __extension__ doesn't affect lvalue-ness.
348 if (E->getOpcode() == UnaryOperator::Extension)
349 return EmitLValue(E->getSubExpr());
350
351 assert(E->getOpcode() == UnaryOperator::Deref &&
352 "'*' is the only unary operator that produces an lvalue");
353 return LValue::getAddr(EmitExpr(E->getSubExpr()).getVal());
354}
355
Chris Lattner4347e3692007-06-06 04:54:52 +0000356LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
357 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
358 const char *StrData = E->getStrData();
359 unsigned Len = E->getByteLength();
360
361 // FIXME: Can cache/reuse these within the module.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000362 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
Chris Lattner4347e3692007-06-06 04:54:52 +0000363
364 // Create a global variable for this.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000365 C = new llvm::GlobalVariable(C->getType(), true,
366 llvm::GlobalValue::InternalLinkage,
Chris Lattner4347e3692007-06-06 04:54:52 +0000367 C, ".str", CurFn->getParent());
Chris Lattner23b7eb62007-06-15 23:05:46 +0000368 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
369 llvm::Constant *Zeros[] = { Zero, Zero };
370 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Chris Lattner4347e3692007-06-06 04:54:52 +0000371 return LValue::getAddr(C);
372}
373
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000374LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
375 // The base and index must be pointers or integers, neither of which are
376 // aggregates. Emit them.
377 QualType BaseTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000378 llvm::Value *Base =
379 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000380 QualType IdxTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000381 llvm::Value *Idx =
382 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000383
384 // Usually the base is the pointer type, but sometimes it is the index.
385 // Canonicalize to have the pointer as the base.
386 if (isa<llvm::PointerType>(Idx->getType())) {
387 std::swap(Base, Idx);
388 std::swap(BaseTy, IdxTy);
389 }
390
391 // The pointer is now the base. Extend or truncate the index type to 32 or
392 // 64-bits.
393 bool IdxSigned = IdxTy->isSignedIntegerType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000394 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000395 if (IdxBitwidth != LLVMPointerWidth)
Chris Lattner23b7eb62007-06-15 23:05:46 +0000396 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000397 IdxSigned, "idxprom");
398
399 // We know that the pointer points to a type of the correct size, unless the
400 // size is a VLA.
401 if (!E->getType()->isConstantSizeType())
402 assert(0 && "VLA idx not implemented");
403 return LValue::getAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
404}
405
Chris Lattnere47e4402007-06-01 18:02:12 +0000406//===--------------------------------------------------------------------===//
407// Expression Emission
408//===--------------------------------------------------------------------===//
409
Chris Lattner8394d792007-06-05 20:53:16 +0000410RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattnere47e4402007-06-01 18:02:12 +0000411 assert(E && "Null expression?");
412
413 switch (E->getStmtClass()) {
414 default:
Chris Lattner1fde0b32007-06-20 18:30:55 +0000415 fprintf(stderr, "Unimplemented expr!\n");
Chris Lattnere47e4402007-06-01 18:02:12 +0000416 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000417 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000418
419 // l-values.
Chris Lattner8394d792007-06-05 20:53:16 +0000420 case Expr::DeclRefExprClass:
Chris Lattnerf99b3f52007-06-11 03:52:52 +0000421 // DeclRef's of EnumConstantDecl's are simple rvalues.
422 if (const EnumConstantDecl *EC =
423 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
Chris Lattner23b7eb62007-06-15 23:05:46 +0000424 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
Chris Lattnerf99b3f52007-06-11 03:52:52 +0000425
426 // FALLTHROUGH
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000427 case Expr::ArraySubscriptExprClass:
Chris Lattner8394d792007-06-05 20:53:16 +0000428 return EmitLoadOfLValue(E);
Chris Lattner4347e3692007-06-06 04:54:52 +0000429 case Expr::StringLiteralClass:
430 return RValue::get(EmitLValue(E).getAddress());
Chris Lattnerd7f58862007-06-02 05:24:33 +0000431
432 // Leaf expressions.
433 case Expr::IntegerLiteralClass:
Chris Lattnere47e4402007-06-01 18:02:12 +0000434 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
Chris Lattnerdb91b162007-06-02 00:16:28 +0000435
Chris Lattnerd7f58862007-06-02 05:24:33 +0000436 // Operators.
437 case Expr::ParenExprClass:
438 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000439 case Expr::UnaryOperatorClass:
440 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000441 case Expr::CastExprClass:
442 return EmitCastExpr(cast<CastExpr>(E));
Chris Lattner2b228c92007-06-15 21:34:29 +0000443 case Expr::CallExprClass:
444 return EmitCallExpr(cast<CallExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000445 case Expr::BinaryOperatorClass:
Chris Lattnerdb91b162007-06-02 00:16:28 +0000446 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattnere47e4402007-06-01 18:02:12 +0000447 }
448
449}
450
Chris Lattner8394d792007-06-05 20:53:16 +0000451RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000452 return RValue::get(llvm::ConstantInt::get(E->getValue()));
Chris Lattnere47e4402007-06-01 18:02:12 +0000453}
454
Chris Lattner8394d792007-06-05 20:53:16 +0000455RValue CodeGenFunction::EmitCastExpr(const CastExpr *E) {
456 QualType SrcTy;
457 RValue Src = EmitExprWithUsualUnaryConversions(E->getSubExpr(), SrcTy);
458
459 // If the destination is void, just evaluate the source.
460 if (E->getType()->isVoidType())
461 return RValue::getAggregate(0);
462
Chris Lattnerf033c142007-06-22 19:05:19 +0000463 return EmitConversion(Src, SrcTy, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +0000464}
Chris Lattnerf0106d22007-06-02 19:33:17 +0000465
Chris Lattner2b228c92007-06-15 21:34:29 +0000466RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
467 QualType Ty;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000468 llvm::Value *Callee =
469 EmitExprWithUsualUnaryConversions(E->getCallee(), Ty).getVal();
Chris Lattner2b228c92007-06-15 21:34:29 +0000470
Chris Lattner23b7eb62007-06-15 23:05:46 +0000471 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattner2b228c92007-06-15 21:34:29 +0000472
473 // FIXME: Handle struct return.
474 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
475 RValue ArgVal = EmitExprWithUsualUnaryConversions(E->getArg(i), Ty);
476
477 if (ArgVal.isScalar())
478 Args.push_back(ArgVal.getVal());
479 else // Pass by-address. FIXME: Set attribute bit on call.
Chris Lattner09153c02007-06-22 18:48:09 +0000480 Args.push_back(ArgVal.getAggregateAddr());
Chris Lattner2b228c92007-06-15 21:34:29 +0000481 }
482
Chris Lattner23b7eb62007-06-15 23:05:46 +0000483 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], Args.size());
Chris Lattner2b228c92007-06-15 21:34:29 +0000484 if (V->getType() != llvm::Type::VoidTy)
485 V->setName("call");
486
487 // FIXME: Struct return;
488 return RValue::get(V);
489}
490
491
Chris Lattner8394d792007-06-05 20:53:16 +0000492//===----------------------------------------------------------------------===//
493// Unary Operator Emission
494//===----------------------------------------------------------------------===//
495
496RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
497 QualType &ResTy) {
Chris Lattner6db1fb82007-06-02 22:49:07 +0000498 ResTy = E->getType().getCanonicalType();
499
500 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
501 // Functions are promoted to their address.
502 ResTy = getContext().getPointerType(ResTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000503 return RValue::get(EmitLValue(E).getAddress());
Chris Lattner6db1fb82007-06-02 22:49:07 +0000504 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
505 // C99 6.3.2.1p3
506 ResTy = getContext().getPointerType(ary->getElementType());
507
508 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
509 // will not true when we add support for VLAs.
510 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
511
512 assert(isa<llvm::PointerType>(V->getType()) &&
513 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
514 ->getElementType()) &&
515 "Doesn't support VLAs yet!");
516 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Chris Lattner8394d792007-06-05 20:53:16 +0000517 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
Chris Lattner6db1fb82007-06-02 22:49:07 +0000518 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
519 // FIXME: this probably isn't right, pending clarification from Steve.
520 llvm::Value *Val = EmitExpr(E).getVal();
521
Chris Lattner6db1fb82007-06-02 22:49:07 +0000522 // If the input is a signed integer, sign extend to the destination.
523 if (ResTy->isSignedIntegerType()) {
524 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
525 } else {
526 // This handles unsigned types, including bool.
527 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
528 }
529 ResTy = getContext().IntTy;
530
Chris Lattner8394d792007-06-05 20:53:16 +0000531 return RValue::get(Val);
Chris Lattner6db1fb82007-06-02 22:49:07 +0000532 }
533
534 // Otherwise, this is a float, double, int, struct, etc.
535 return EmitExpr(E);
536}
537
538
Chris Lattner8394d792007-06-05 20:53:16 +0000539RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000540 switch (E->getOpcode()) {
541 default:
542 printf("Unimplemented unary expr!\n");
543 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000544 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattner8394d792007-06-05 20:53:16 +0000545 // FIXME: pre/post inc/dec
546 case UnaryOperator::AddrOf: return EmitUnaryAddrOf(E);
547 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
548 case UnaryOperator::Plus : return EmitUnaryPlus(E);
549 case UnaryOperator::Minus : return EmitUnaryMinus(E);
550 case UnaryOperator::Not : return EmitUnaryNot(E);
551 case UnaryOperator::LNot : return EmitUnaryLNot(E);
552 // FIXME: SIZEOF/ALIGNOF(expr).
553 // FIXME: real/imag
554 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000555 }
556}
557
Chris Lattner8394d792007-06-05 20:53:16 +0000558/// C99 6.5.3.2
559RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
560 // The address of the operand is just its lvalue. It cannot be a bitfield.
561 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
562}
563
564RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
565 // Unary plus just performs promotions on its arithmetic operand.
566 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000567 return EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000568}
569
570RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
571 // Unary minus performs promotions, then negates its arithmetic operand.
572 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000573 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000574
Chris Lattner8394d792007-06-05 20:53:16 +0000575 if (V.isScalar())
576 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
577
578 assert(0 && "FIXME: This doesn't handle complex operands yet");
579}
580
581RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
582 // Unary not performs promotions, then complements its integer operand.
583 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000584 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000585
586 if (V.isScalar())
587 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
588
589 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
590}
591
592
593/// C99 6.5.3.3
594RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
595 // Compare operand to zero.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000596 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000597
598 // Invert value.
Chris Lattnera45c5af2007-06-02 19:47:04 +0000599 // TODO: Could dynamically modify easy computations here. For example, if
600 // the operand is an icmp ne, turn into icmp eq.
Chris Lattnerf0106d22007-06-02 19:33:17 +0000601 BoolVal = Builder.CreateNot(BoolVal, "lnot");
602
603 // ZExt result to int.
Chris Lattner8394d792007-06-05 20:53:16 +0000604 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
Chris Lattnerf0106d22007-06-02 19:33:17 +0000605}
606
Chris Lattnere47e4402007-06-01 18:02:12 +0000607
Chris Lattnerdb91b162007-06-02 00:16:28 +0000608//===--------------------------------------------------------------------===//
609// Binary Operator Emission
610//===--------------------------------------------------------------------===//
611
612// FIXME describe.
Chris Lattnercf250242007-06-03 02:02:44 +0000613QualType CodeGenFunction::
Chris Lattner8394d792007-06-05 20:53:16 +0000614EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
615 RValue &RHS) {
Chris Lattnerc18f9d12007-06-02 22:51:30 +0000616 QualType LHSType, RHSType;
617 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
618 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
619
Chris Lattnercf250242007-06-03 02:02:44 +0000620 // If both operands have the same source type, we're done already.
621 if (LHSType == RHSType) return LHSType;
622
623 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
624 // The caller can deal with this (e.g. pointer + int).
625 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
626 return LHSType;
627
628 // At this point, we have two different arithmetic types.
629
630 // Handle complex types first (C99 6.3.1.8p1).
631 if (LHSType->isComplexType() || RHSType->isComplexType()) {
632 assert(0 && "FIXME: complex types unimp");
633#if 0
634 // if we have an integer operand, the result is the complex type.
635 if (rhs->isIntegerType())
636 return lhs;
637 if (lhs->isIntegerType())
638 return rhs;
639 return Context.maxComplexType(lhs, rhs);
640#endif
641 }
642
643 // If neither operand is complex, they must be scalars.
644 llvm::Value *LHSV = LHS.getVal();
645 llvm::Value *RHSV = RHS.getVal();
646
647 // If the LLVM types are already equal, then they only differed in sign, or it
648 // was something like char/signed char or double/long double.
649 if (LHSV->getType() == RHSV->getType())
650 return LHSType;
651
652 // Now handle "real" floating types (i.e. float, double, long double).
653 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
654 // if we have an integer operand, the result is the real floating type, and
655 // the integer converts to FP.
656 if (RHSType->isIntegerType()) {
657 // Promote the RHS to an FP type of the LHS, with the sign following the
658 // RHS.
659 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000660 RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000661 else
Chris Lattner8394d792007-06-05 20:53:16 +0000662 RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000663 return LHSType;
664 }
665
666 if (LHSType->isIntegerType()) {
667 // Promote the LHS to an FP type of the RHS, with the sign following the
668 // LHS.
669 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000670 LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000671 else
Chris Lattner8394d792007-06-05 20:53:16 +0000672 LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000673 return RHSType;
674 }
675
676 // Otherwise, they are two FP types. Promote the smaller operand to the
677 // bigger result.
678 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
679
680 if (BiggerType == LHSType)
Chris Lattner8394d792007-06-05 20:53:16 +0000681 RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000682 else
Chris Lattner8394d792007-06-05 20:53:16 +0000683 LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000684 return BiggerType;
685 }
686
687 // Finally, we have two integer types that are different according to C. Do
688 // a sign or zero extension if needed.
689
690 // Otherwise, one type is smaller than the other.
691 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
692
693 if (LHSType == ResTy) {
694 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000695 RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000696 else
Chris Lattner8394d792007-06-05 20:53:16 +0000697 RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000698 } else {
699 assert(RHSType == ResTy && "Unknown conversion");
700 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000701 LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000702 else
Chris Lattner8394d792007-06-05 20:53:16 +0000703 LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000704 }
705 return ResTy;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000706}
707
708
Chris Lattner8394d792007-06-05 20:53:16 +0000709RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
Chris Lattnerdb91b162007-06-02 00:16:28 +0000710 switch (E->getOpcode()) {
711 default:
Chris Lattner8394d792007-06-05 20:53:16 +0000712 fprintf(stderr, "Unimplemented expr!\n");
Chris Lattnerdb91b162007-06-02 00:16:28 +0000713 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000714 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattner8394d792007-06-05 20:53:16 +0000715 case BinaryOperator::Mul: return EmitBinaryMul(E);
716 case BinaryOperator::Div: return EmitBinaryDiv(E);
717 case BinaryOperator::Rem: return EmitBinaryRem(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +0000718 case BinaryOperator::Add: return EmitBinaryAdd(E);
Chris Lattner8394d792007-06-05 20:53:16 +0000719 case BinaryOperator::Sub: return EmitBinarySub(E);
720 case BinaryOperator::Shl: return EmitBinaryShl(E);
721 case BinaryOperator::Shr: return EmitBinaryShr(E);
Chris Lattner8394d792007-06-05 20:53:16 +0000722 case BinaryOperator::And: return EmitBinaryAnd(E);
723 case BinaryOperator::Xor: return EmitBinaryXor(E);
724 case BinaryOperator::Or : return EmitBinaryOr(E);
725 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
726 case BinaryOperator::LOr: return EmitBinaryLOr(E);
Chris Lattner1fde0b32007-06-20 18:30:55 +0000727 case BinaryOperator::LT:
728 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
729 llvm::ICmpInst::ICMP_SLT,
730 llvm::FCmpInst::FCMP_OLT);
731 case BinaryOperator::GT:
732 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
733 llvm::ICmpInst::ICMP_SGT,
734 llvm::FCmpInst::FCMP_OGT);
735 case BinaryOperator::LE:
736 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
737 llvm::ICmpInst::ICMP_SLE,
738 llvm::FCmpInst::FCMP_OLE);
739 case BinaryOperator::GE:
740 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
741 llvm::ICmpInst::ICMP_SGE,
742 llvm::FCmpInst::FCMP_OGE);
743 case BinaryOperator::EQ:
744 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
745 llvm::ICmpInst::ICMP_EQ,
746 llvm::FCmpInst::FCMP_OEQ);
747 case BinaryOperator::NE:
748 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
749 llvm::ICmpInst::ICMP_NE,
750 llvm::FCmpInst::FCMP_UNE);
Chris Lattner9369a562007-06-29 16:31:29 +0000751 case BinaryOperator::Assign: return EmitBinaryAssign(E);
752 case BinaryOperator::AddAssign:
753 return EmitBinaryAddAssign(cast<CompoundAssignOperator>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000754 // FIXME: Assignment.
755 case BinaryOperator::Comma: return EmitBinaryComma(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +0000756 }
757}
758
Chris Lattner8394d792007-06-05 20:53:16 +0000759RValue CodeGenFunction::EmitBinaryMul(const BinaryOperator *E) {
760 RValue LHS, RHS;
761 EmitUsualArithmeticConversions(E, LHS, RHS);
Chris Lattnerdb91b162007-06-02 00:16:28 +0000762
Chris Lattner8394d792007-06-05 20:53:16 +0000763 if (LHS.isScalar())
764 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
765
766 assert(0 && "FIXME: This doesn't handle complex operands yet");
767}
768
769RValue CodeGenFunction::EmitBinaryDiv(const BinaryOperator *E) {
770 RValue LHS, RHS;
771 EmitUsualArithmeticConversions(E, LHS, RHS);
772
773 if (LHS.isScalar()) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000774 llvm::Value *RV;
Chris Lattner8394d792007-06-05 20:53:16 +0000775 if (LHS.getVal()->getType()->isFloatingPoint())
776 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
777 else if (E->getType()->isUnsignedIntegerType())
778 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
779 else
780 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
781 return RValue::get(RV);
782 }
783 assert(0 && "FIXME: This doesn't handle complex operands yet");
784}
785
786RValue CodeGenFunction::EmitBinaryRem(const BinaryOperator *E) {
787 RValue LHS, RHS;
788 EmitUsualArithmeticConversions(E, LHS, RHS);
789
790 if (LHS.isScalar()) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000791 llvm::Value *RV;
Chris Lattner8394d792007-06-05 20:53:16 +0000792 // Rem in C can't be a floating point type: C99 6.5.5p2.
793 if (E->getType()->isUnsignedIntegerType())
794 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
795 else
796 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
797 return RValue::get(RV);
798 }
799
800 assert(0 && "FIXME: This doesn't handle complex operands yet");
801}
802
803RValue CodeGenFunction::EmitBinaryAdd(const BinaryOperator *E) {
804 RValue LHS, RHS;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000805 EmitUsualArithmeticConversions(E, LHS, RHS);
806
Chris Lattner8394d792007-06-05 20:53:16 +0000807 // FIXME: This doesn't handle ptr+int etc yet.
808
809 if (LHS.isScalar())
810 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
Chris Lattner8394d792007-06-05 20:53:16 +0000811
Chris Lattnere9a64532007-06-22 21:44:33 +0000812 // Otherwise, this must be a complex number.
813 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
814
815 EmitLoadOfComplex(LHS, LHSR, LHSI);
816 EmitLoadOfComplex(RHS, RHSR, RHSI);
817
818 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
819 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
820
821 llvm::Value *Res = CreateTempAlloca(ConvertType(E->getType()));
822 EmitStoreOfComplex(ResR, ResI, Res);
823 return RValue::getAggregate(Res);
Chris Lattner8394d792007-06-05 20:53:16 +0000824}
825
826RValue CodeGenFunction::EmitBinarySub(const BinaryOperator *E) {
827 RValue LHS, RHS;
828 EmitUsualArithmeticConversions(E, LHS, RHS);
829
830 // FIXME: This doesn't handle ptr-int or ptr-ptr, etc yet.
831
832 if (LHS.isScalar())
833 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
834
835 assert(0 && "FIXME: This doesn't handle complex operands yet");
836
837}
838
839RValue CodeGenFunction::EmitBinaryShl(const BinaryOperator *E) {
840 // For shifts, integer promotions are performed, but the usual arithmetic
841 // conversions are not. The LHS and RHS need not have the same type.
842
843 QualType ResTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000844 llvm::Value *LHS =
845 EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy).getVal();
846 llvm::Value *RHS =
847 EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy).getVal();
Chris Lattner8394d792007-06-05 20:53:16 +0000848
849 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
850 // RHS to the same size as the LHS.
851 if (LHS->getType() != RHS->getType())
852 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
853
854 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
855}
856
857RValue CodeGenFunction::EmitBinaryShr(const BinaryOperator *E) {
858 // For shifts, integer promotions are performed, but the usual arithmetic
859 // conversions are not. The LHS and RHS need not have the same type.
860
861 QualType ResTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000862 llvm::Value *LHS =
863 EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy).getVal();
864 llvm::Value *RHS =
865 EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy).getVal();
Chris Lattner8394d792007-06-05 20:53:16 +0000866
867 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
868 // RHS to the same size as the LHS.
869 if (LHS->getType() != RHS->getType())
870 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
871
872 if (E->getType()->isUnsignedIntegerType())
873 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
874 else
875 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
876}
877
Chris Lattner1fde0b32007-06-20 18:30:55 +0000878RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
879 unsigned UICmpOpc, unsigned SICmpOpc,
880 unsigned FCmpOpc) {
Chris Lattner273c63d2007-06-20 18:02:30 +0000881 RValue LHS, RHS;
882 EmitUsualArithmeticConversions(E, LHS, RHS);
883
884 llvm::Value *Result;
885 if (LHS.isScalar()) {
886 if (LHS.getVal()->getType()->isFloatingPoint()) {
Chris Lattner1fde0b32007-06-20 18:30:55 +0000887 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
888 LHS.getVal(), RHS.getVal(), "cmp");
889 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
890 // FIXME: This check isn't right for "unsigned short < int" where ushort
891 // promotes to int and does a signed compare.
892 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
893 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +0000894 } else {
Chris Lattner1fde0b32007-06-20 18:30:55 +0000895 // Signed integers and pointers.
896 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
897 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +0000898 }
899 } else {
900 // Struct/union/complex
901 assert(0 && "Aggregate comparisons not implemented yet!");
902 }
903
904 // ZExt result to int.
905 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
906}
907
Chris Lattner8394d792007-06-05 20:53:16 +0000908RValue CodeGenFunction::EmitBinaryAnd(const BinaryOperator *E) {
909 RValue LHS, RHS;
910 EmitUsualArithmeticConversions(E, LHS, RHS);
911
912 if (LHS.isScalar())
913 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
914
915 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
916}
917
918RValue CodeGenFunction::EmitBinaryXor(const BinaryOperator *E) {
919 RValue LHS, RHS;
920 EmitUsualArithmeticConversions(E, LHS, RHS);
921
922 if (LHS.isScalar())
923 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
924
925 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
926}
927
928RValue CodeGenFunction::EmitBinaryOr(const BinaryOperator *E) {
929 RValue LHS, RHS;
930 EmitUsualArithmeticConversions(E, LHS, RHS);
931
932 if (LHS.isScalar())
933 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
934
935 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
936}
937
938RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000939 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +0000940
Chris Lattner23b7eb62007-06-15 23:05:46 +0000941 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
942 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +0000943
Chris Lattner23b7eb62007-06-15 23:05:46 +0000944 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +0000945 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
946
947 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +0000948 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +0000949
950 // Reaquire the RHS block, as there may be subblocks inserted.
951 RHSBlock = Builder.GetInsertBlock();
952 EmitBlock(ContBlock);
953
954 // Create a PHI node. If we just evaluted the LHS condition, the result is
955 // false. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000956 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
Chris Lattner8394d792007-06-05 20:53:16 +0000957 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +0000958 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +0000959 PN->addIncoming(RHSCond, RHSBlock);
960
961 // ZExt result to int.
962 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
963}
964
965RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000966 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +0000967
Chris Lattner23b7eb62007-06-15 23:05:46 +0000968 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
969 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +0000970
Chris Lattner23b7eb62007-06-15 23:05:46 +0000971 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +0000972 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
973
974 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +0000975 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +0000976
977 // Reaquire the RHS block, as there may be subblocks inserted.
978 RHSBlock = Builder.GetInsertBlock();
979 EmitBlock(ContBlock);
980
981 // Create a PHI node. If we just evaluted the LHS condition, the result is
982 // true. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000983 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
Chris Lattner8394d792007-06-05 20:53:16 +0000984 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +0000985 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +0000986 PN->addIncoming(RHSCond, RHSBlock);
987
988 // ZExt result to int.
989 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
990}
991
992RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
993 LValue LHS = EmitLValue(E->getLHS());
994
995 QualType RHSTy;
996 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
997
998 // Convert the RHS to the type of the LHS.
Chris Lattnerf033c142007-06-22 19:05:19 +0000999 RHS = EmitConversion(RHS, RHSTy, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +00001000
1001 // Store the value into the LHS.
1002 EmitStoreThroughLValue(RHS, LHS, E->getType());
1003
1004 // Return the converted RHS.
1005 return RHS;
1006}
1007
Chris Lattner9369a562007-06-29 16:31:29 +00001008/// Compound assignment operations have different promotion rules than the other
1009/// binary operators. In particular, the LHS and RHS are promoted to a new type
1010/// (specified by E->getComputationType()), the binary operator is evaluated,
1011/// the result is truncated to the type of LHS, then the result is stored back
1012/// through the LHS.
1013///
1014RValue CodeGenFunction::EmitBinaryAddAssign(const CompoundAssignOperator *E) {
1015 LValue LHSLV = EmitLValue(E->getLHS());
1016
1017 // Load the LHS and RHS operands.
1018 QualType LHSTy = E->getLHS()->getType();
1019 RValue LHS = EmitLoadOfLValue(LHSLV, LHSTy);
1020 QualType RHSTy;
1021 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
1022
1023 // Convert the LHS and RHS to the common evaluation type.
1024 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
1025 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
1026
1027 // Emit the operation itself.
1028 RValue Res;
1029 if (LHS.isScalar()) {
1030 Res = RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
1031 } else {
1032 assert(0 && "FIXME: Complex add unimp!");
1033 }
1034
1035 // Truncate back to the destination type.
1036 if (E->getComputationType() != E->getType())
1037 Res = EmitConversion(Res, E->getComputationType(), E->getType());
1038
1039 // Store the result value into the LHS.
1040 EmitStoreThroughLValue(Res, LHSLV, E->getType());
1041
1042 // Return the result.
1043 return Res;
1044}
1045
Chris Lattner8394d792007-06-05 20:53:16 +00001046RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1047 EmitExpr(E->getLHS());
1048 return EmitExpr(E->getRHS());
1049}