blob: 9f535b5352745f1aa5c4d6996085450474cbab7b [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?");
Chris Lattnerfc7634f2007-07-13 03:25:53 +0000100 return RValue::get(Builder.CreateIntToPtr(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 Lattner08c4b9f2007-07-10 21:17:59 +0000241 return LValue::MakeAddr(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
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000262 if (LV.isSimple()) {
263 llvm::Value *Ptr = LV.getAddress();
264 const llvm::Type *EltTy =
265 cast<llvm::PointerType>(Ptr->getType())->getElementType();
266
267 // Simple scalar l-value.
268 if (EltTy->isFirstClassType())
269 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
270
271 // Otherwise, we have an aggregate lvalue.
272 return RValue::getAggregate(Ptr);
273 }
Chris Lattner09153c02007-06-22 18:48:09 +0000274
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000275 if (LV.isVectorElt()) {
276 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
277 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
278 "vecext"));
279 }
Chris Lattner09153c02007-06-22 18:48:09 +0000280
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000281 assert(0 && "Bitfield ref not impl!");
Chris Lattner8394d792007-06-05 20:53:16 +0000282}
283
Chris Lattner9369a562007-06-29 16:31:29 +0000284RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
285 return EmitLoadOfLValue(EmitLValue(E), E->getType());
286}
287
288
Chris Lattner8394d792007-06-05 20:53:16 +0000289/// EmitStoreThroughLValue - Store the specified rvalue into the specified
290/// lvalue, where both are guaranteed to the have the same type, and that type
291/// is 'Ty'.
292void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
293 QualType Ty) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000294 if (Dst.isVectorElt()) {
295 // Read/modify/write the vector, inserting the new element.
296 // FIXME: Volatility.
297 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
298 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
299 Dst.getVectorIdx(), "vecins");
300 Builder.CreateStore(Vec, Dst.getVectorAddr());
301 return;
302 }
303
304 assert(Dst.isSimple() && "FIXME: Don't support store to bitfield yet");
Chris Lattner8394d792007-06-05 20:53:16 +0000305
Chris Lattner09153c02007-06-22 18:48:09 +0000306 llvm::Value *DstAddr = Dst.getAddress();
307 if (Src.isScalar()) {
308 // FIXME: Handle volatility etc.
309 const llvm::Type *SrcTy = Src.getVal()->getType();
310 const llvm::Type *AddrTy =
311 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
312
313 if (AddrTy != SrcTy)
314 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
315 "storetmp");
316 Builder.CreateStore(Src.getVal(), DstAddr);
317 return;
318 }
Chris Lattner8394d792007-06-05 20:53:16 +0000319
Chris Lattnere9a64532007-06-22 21:44:33 +0000320 // Don't use memcpy for complex numbers.
321 if (Ty->isComplexType()) {
322 llvm::Value *Real, *Imag;
323 EmitLoadOfComplex(Src, Real, Imag);
324 EmitStoreOfComplex(Real, Imag, Dst.getAddress());
325 return;
326 }
327
Chris Lattner09153c02007-06-22 18:48:09 +0000328 // Aggregate assignment turns into llvm.memcpy.
329 const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
330 llvm::Value *SrcAddr = Src.getAggregateAddr();
331
332 if (DstAddr->getType() != SBP)
333 DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
334 if (SrcAddr->getType() != SBP)
335 SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
336
337 unsigned Align = 1; // FIXME: Compute type alignments.
338 unsigned Size = 1234; // FIXME: Compute type sizes.
339
340 // FIXME: Handle variable sized types.
341 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
342 llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
343
344 llvm::Value *MemCpyOps[4] = {
345 DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
346 };
347
348 Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, 4);
Chris Lattner8394d792007-06-05 20:53:16 +0000349}
350
Chris Lattnerd7f58862007-06-02 05:24:33 +0000351
352LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
353 const Decl *D = E->getDecl();
Chris Lattner53621a52007-06-13 20:44:40 +0000354 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000355 llvm::Value *V = LocalDeclMap[D];
Chris Lattnerd7f58862007-06-02 05:24:33 +0000356 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000357 return LValue::MakeAddr(V);
Chris Lattnerb6984c42007-06-20 04:44:43 +0000358 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000359 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000360 }
361 assert(0 && "Unimp declref");
362}
Chris Lattnere47e4402007-06-01 18:02:12 +0000363
Chris Lattner8394d792007-06-05 20:53:16 +0000364LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
365 // __extension__ doesn't affect lvalue-ness.
366 if (E->getOpcode() == UnaryOperator::Extension)
367 return EmitLValue(E->getSubExpr());
368
369 assert(E->getOpcode() == UnaryOperator::Deref &&
370 "'*' is the only unary operator that produces an lvalue");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000371 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
Chris Lattner8394d792007-06-05 20:53:16 +0000372}
373
Chris Lattner4347e3692007-06-06 04:54:52 +0000374LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
375 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
376 const char *StrData = E->getStrData();
377 unsigned Len = E->getByteLength();
378
379 // FIXME: Can cache/reuse these within the module.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000380 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
Chris Lattner4347e3692007-06-06 04:54:52 +0000381
382 // Create a global variable for this.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000383 C = new llvm::GlobalVariable(C->getType(), true,
384 llvm::GlobalValue::InternalLinkage,
Chris Lattner4347e3692007-06-06 04:54:52 +0000385 C, ".str", CurFn->getParent());
Chris Lattner23b7eb62007-06-15 23:05:46 +0000386 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
387 llvm::Constant *Zeros[] = { Zero, Zero };
388 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000389 return LValue::MakeAddr(C);
Chris Lattner4347e3692007-06-06 04:54:52 +0000390}
391
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000392LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000393 // The index must always be a pointer or integer, neither of which is an
394 // aggregate. Emit it.
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000395 QualType IdxTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000396 llvm::Value *Idx =
397 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000398
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000399 // If the base is a vector type, then we are forming a vector element lvalue
400 // with this subscript.
401 if (E->getBase()->getType()->isVectorType()) {
402 // Emit the vector as an lvalue to get its address.
403 LValue Base = EmitLValue(E->getBase());
404 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
405 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
406 return LValue::MakeVectorElt(Base.getAddress(), Idx);
407 }
408
409 // At this point, the base must be a pointer or integer, neither of which are
410 // aggregates. Emit it.
411 QualType BaseTy;
412 llvm::Value *Base =
413 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
414
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000415 // Usually the base is the pointer type, but sometimes it is the index.
416 // Canonicalize to have the pointer as the base.
417 if (isa<llvm::PointerType>(Idx->getType())) {
418 std::swap(Base, Idx);
419 std::swap(BaseTy, IdxTy);
420 }
421
422 // The pointer is now the base. Extend or truncate the index type to 32 or
423 // 64-bits.
424 bool IdxSigned = IdxTy->isSignedIntegerType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000425 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000426 if (IdxBitwidth != LLVMPointerWidth)
Chris Lattner23b7eb62007-06-15 23:05:46 +0000427 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000428 IdxSigned, "idxprom");
429
430 // We know that the pointer points to a type of the correct size, unless the
431 // size is a VLA.
432 if (!E->getType()->isConstantSizeType())
433 assert(0 && "VLA idx not implemented");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000434 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000435}
436
Chris Lattnere47e4402007-06-01 18:02:12 +0000437//===--------------------------------------------------------------------===//
438// Expression Emission
439//===--------------------------------------------------------------------===//
440
Chris Lattner8394d792007-06-05 20:53:16 +0000441RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattnere47e4402007-06-01 18:02:12 +0000442 assert(E && "Null expression?");
443
444 switch (E->getStmtClass()) {
445 default:
Chris Lattner1fde0b32007-06-20 18:30:55 +0000446 fprintf(stderr, "Unimplemented expr!\n");
Chris Lattnere47e4402007-06-01 18:02:12 +0000447 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000448 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000449
450 // l-values.
Chris Lattner8394d792007-06-05 20:53:16 +0000451 case Expr::DeclRefExprClass:
Chris Lattnerf99b3f52007-06-11 03:52:52 +0000452 // DeclRef's of EnumConstantDecl's are simple rvalues.
453 if (const EnumConstantDecl *EC =
454 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
Chris Lattner23b7eb62007-06-15 23:05:46 +0000455 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
Chris Lattner8394d792007-06-05 20:53:16 +0000456 return EmitLoadOfLValue(E);
Chris Lattnera779b3d2007-07-10 21:58:36 +0000457 case Expr::ArraySubscriptExprClass:
458 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000459 case Expr::StringLiteralClass:
460 return RValue::get(EmitLValue(E).getAddress());
Chris Lattnerd7f58862007-06-02 05:24:33 +0000461
462 // Leaf expressions.
463 case Expr::IntegerLiteralClass:
Chris Lattnere47e4402007-06-01 18:02:12 +0000464 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
Chris Lattner2ada32e2007-07-09 23:03:16 +0000465 case Expr::FloatingLiteralClass:
466 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000467 case Expr::CharacterLiteralClass:
468 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattnerdb91b162007-06-02 00:16:28 +0000469
Chris Lattnerd7f58862007-06-02 05:24:33 +0000470 // Operators.
471 case Expr::ParenExprClass:
472 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000473 case Expr::UnaryOperatorClass:
474 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner388cf762007-07-13 20:25:53 +0000475 case Expr::ImplicitCastExprClass:
476 return EmitCastExpr(cast<ImplicitCastExpr>(E)->getSubExpr(), E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +0000477 case Expr::CastExprClass:
Chris Lattner388cf762007-07-13 20:25:53 +0000478 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
Chris Lattner2b228c92007-06-15 21:34:29 +0000479 case Expr::CallExprClass:
480 return EmitCallExpr(cast<CallExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000481 case Expr::BinaryOperatorClass:
Chris Lattnerdb91b162007-06-02 00:16:28 +0000482 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000483
484 case Expr::ConditionalOperatorClass:
485 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Chris Lattnere47e4402007-06-01 18:02:12 +0000486 }
487
488}
489
Chris Lattner8394d792007-06-05 20:53:16 +0000490RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000491 return RValue::get(llvm::ConstantInt::get(E->getValue()));
Chris Lattnere47e4402007-06-01 18:02:12 +0000492}
Chris Lattner2ada32e2007-07-09 23:03:16 +0000493RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
494 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
495 E->getValue()));
496}
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000497RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
498 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
499 E->getValue()));
500}
Chris Lattnera779b3d2007-07-10 21:58:36 +0000501
502RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
503 // Emit subscript expressions in rvalue context's. For most cases, this just
504 // loads the lvalue formed by the subscript expr. However, we have to be
505 // careful, because the base of a vector subscript is occasionally an rvalue,
506 // so we can't get it as an lvalue.
507 if (!E->getBase()->getType()->isVectorType())
508 return EmitLoadOfLValue(E);
509
510 // Handle the vector case. The base must be a vector, the index must be an
511 // integer value.
512 QualType BaseTy, IdxTy;
513 llvm::Value *Base =
514 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
515 llvm::Value *Idx =
516 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
517
518 // FIXME: Convert Idx to i32 type.
519
520 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
521}
522
Chris Lattner388cf762007-07-13 20:25:53 +0000523// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
524// have to handle a more broad range of conversions than explicit casts, as they
525// handle things like function to ptr-to-function decay etc.
526RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattner8394d792007-06-05 20:53:16 +0000527 QualType SrcTy;
Chris Lattner388cf762007-07-13 20:25:53 +0000528 RValue Src = EmitExprWithUsualUnaryConversions(Op, SrcTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000529
530 // If the destination is void, just evaluate the source.
Chris Lattner388cf762007-07-13 20:25:53 +0000531 if (DestTy->isVoidType())
Chris Lattner8394d792007-06-05 20:53:16 +0000532 return RValue::getAggregate(0);
533
Chris Lattner388cf762007-07-13 20:25:53 +0000534 return EmitConversion(Src, SrcTy, DestTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000535}
Chris Lattnerf0106d22007-06-02 19:33:17 +0000536
Chris Lattner2b228c92007-06-15 21:34:29 +0000537RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Chris Lattnerc14236b2007-07-10 22:18:37 +0000538 QualType CalleeTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000539 llvm::Value *Callee =
Chris Lattnerc14236b2007-07-10 22:18:37 +0000540 EmitExprWithUsualUnaryConversions(E->getCallee(), CalleeTy).getVal();
541
542 // The callee type will always be a pointer to function type, get the function
543 // type.
544 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
545
546 // Get information about the argument types.
547 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
548
549 // Calling unprototyped functions provides no argument info.
550 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
551 ArgTyIt = FTP->arg_type_begin();
552 ArgTyEnd = FTP->arg_type_end();
553 }
Chris Lattner2b228c92007-06-15 21:34:29 +0000554
Chris Lattner23b7eb62007-06-15 23:05:46 +0000555 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattner2b228c92007-06-15 21:34:29 +0000556
557 // FIXME: Handle struct return.
558 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattnerc14236b2007-07-10 22:18:37 +0000559 QualType ArgTy;
560 RValue ArgVal = EmitExprWithUsualUnaryConversions(E->getArg(i), ArgTy);
561
562 // If this argument has prototype information, convert it.
563 if (ArgTyIt != ArgTyEnd) {
564 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
565 } else {
566 // Otherwise, if passing through "..." or to a function with no prototype,
567 // perform the "default argument promotions" (C99 6.5.2.2p6), which
568 // includes the usual unary conversions, but also promotes float to
569 // double.
570 if (const BuiltinType *BT =
571 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
572 if (BT->getKind() == BuiltinType::Float)
573 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
574 llvm::Type::DoubleTy,"tmp"));
575 }
576 }
577
Chris Lattner2b228c92007-06-15 21:34:29 +0000578
579 if (ArgVal.isScalar())
580 Args.push_back(ArgVal.getVal());
581 else // Pass by-address. FIXME: Set attribute bit on call.
Chris Lattner09153c02007-06-22 18:48:09 +0000582 Args.push_back(ArgVal.getAggregateAddr());
Chris Lattner2b228c92007-06-15 21:34:29 +0000583 }
584
Chris Lattner23b7eb62007-06-15 23:05:46 +0000585 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], Args.size());
Chris Lattner2b228c92007-06-15 21:34:29 +0000586 if (V->getType() != llvm::Type::VoidTy)
587 V->setName("call");
588
589 // FIXME: Struct return;
590 return RValue::get(V);
591}
592
593
Chris Lattner8394d792007-06-05 20:53:16 +0000594//===----------------------------------------------------------------------===//
595// Unary Operator Emission
596//===----------------------------------------------------------------------===//
597
598RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
599 QualType &ResTy) {
Chris Lattner6db1fb82007-06-02 22:49:07 +0000600 ResTy = E->getType().getCanonicalType();
601
602 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
603 // Functions are promoted to their address.
604 ResTy = getContext().getPointerType(ResTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000605 return RValue::get(EmitLValue(E).getAddress());
Chris Lattner6db1fb82007-06-02 22:49:07 +0000606 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
607 // C99 6.3.2.1p3
608 ResTy = getContext().getPointerType(ary->getElementType());
609
610 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
611 // will not true when we add support for VLAs.
612 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
613
614 assert(isa<llvm::PointerType>(V->getType()) &&
615 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
616 ->getElementType()) &&
617 "Doesn't support VLAs yet!");
618 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Chris Lattner8394d792007-06-05 20:53:16 +0000619 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
Chris Lattner6db1fb82007-06-02 22:49:07 +0000620 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
621 // FIXME: this probably isn't right, pending clarification from Steve.
622 llvm::Value *Val = EmitExpr(E).getVal();
623
Chris Lattner6db1fb82007-06-02 22:49:07 +0000624 // If the input is a signed integer, sign extend to the destination.
625 if (ResTy->isSignedIntegerType()) {
626 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
627 } else {
628 // This handles unsigned types, including bool.
629 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
630 }
631 ResTy = getContext().IntTy;
632
Chris Lattner8394d792007-06-05 20:53:16 +0000633 return RValue::get(Val);
Chris Lattner6db1fb82007-06-02 22:49:07 +0000634 }
635
636 // Otherwise, this is a float, double, int, struct, etc.
637 return EmitExpr(E);
638}
639
640
Chris Lattner8394d792007-06-05 20:53:16 +0000641RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000642 switch (E->getOpcode()) {
643 default:
644 printf("Unimplemented unary expr!\n");
645 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000646 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerdcca4872007-07-11 23:43:46 +0000647 case UnaryOperator::PostInc:
648 case UnaryOperator::PostDec:
649 case UnaryOperator::PreInc :
650 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
651 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
652 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
653 case UnaryOperator::Plus : return EmitUnaryPlus(E);
654 case UnaryOperator::Minus : return EmitUnaryMinus(E);
655 case UnaryOperator::Not : return EmitUnaryNot(E);
656 case UnaryOperator::LNot : return EmitUnaryLNot(E);
Chris Lattner8394d792007-06-05 20:53:16 +0000657 // FIXME: SIZEOF/ALIGNOF(expr).
658 // FIXME: real/imag
659 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000660 }
661}
662
Chris Lattnerdcca4872007-07-11 23:43:46 +0000663RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
664 LValue LV = EmitLValue(E->getSubExpr());
665 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
666
667 // We know the operand is real or pointer type, so it must be an LLVM scalar.
668 assert(InVal.isScalar() && "Unknown thing to increment");
669 llvm::Value *InV = InVal.getVal();
670
671 int AmountVal = 1;
672 if (E->getOpcode() == UnaryOperator::PreDec ||
673 E->getOpcode() == UnaryOperator::PostDec)
674 AmountVal = -1;
675
676 llvm::Value *NextVal;
677 if (isa<llvm::IntegerType>(InV->getType())) {
678 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
679 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
680 } else if (InV->getType()->isFloatingPoint()) {
681 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
682 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
683 } else {
684 // FIXME: This is not right for pointers to VLA types.
685 assert(isa<llvm::PointerType>(InV->getType()));
686 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
687 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
688 }
689
690 RValue NextValToStore = RValue::get(NextVal);
691
692 // Store the updated result through the lvalue.
693 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
694
695 // If this is a postinc, return the value read from memory, otherwise use the
696 // updated value.
697 if (E->getOpcode() == UnaryOperator::PreDec ||
698 E->getOpcode() == UnaryOperator::PreInc)
699 return NextValToStore;
700 else
701 return InVal;
702}
703
Chris Lattner8394d792007-06-05 20:53:16 +0000704/// C99 6.5.3.2
705RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
706 // The address of the operand is just its lvalue. It cannot be a bitfield.
707 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
708}
709
710RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
711 // Unary plus just performs promotions on its arithmetic operand.
712 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000713 return EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000714}
715
716RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
717 // Unary minus performs promotions, then negates its arithmetic operand.
718 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000719 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000720
Chris Lattner8394d792007-06-05 20:53:16 +0000721 if (V.isScalar())
722 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
723
724 assert(0 && "FIXME: This doesn't handle complex operands yet");
725}
726
727RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
728 // Unary not performs promotions, then complements its integer operand.
729 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000730 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000731
732 if (V.isScalar())
733 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
734
735 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
736}
737
738
739/// C99 6.5.3.3
740RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
741 // Compare operand to zero.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000742 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000743
744 // Invert value.
Chris Lattnera45c5af2007-06-02 19:47:04 +0000745 // TODO: Could dynamically modify easy computations here. For example, if
746 // the operand is an icmp ne, turn into icmp eq.
Chris Lattnerf0106d22007-06-02 19:33:17 +0000747 BoolVal = Builder.CreateNot(BoolVal, "lnot");
748
749 // ZExt result to int.
Chris Lattner8394d792007-06-05 20:53:16 +0000750 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
Chris Lattnerf0106d22007-06-02 19:33:17 +0000751}
752
Chris Lattnere47e4402007-06-01 18:02:12 +0000753
Chris Lattnerdb91b162007-06-02 00:16:28 +0000754//===--------------------------------------------------------------------===//
755// Binary Operator Emission
756//===--------------------------------------------------------------------===//
757
758// FIXME describe.
Chris Lattnercf250242007-06-03 02:02:44 +0000759QualType CodeGenFunction::
Chris Lattner8394d792007-06-05 20:53:16 +0000760EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
761 RValue &RHS) {
Chris Lattnerc18f9d12007-06-02 22:51:30 +0000762 QualType LHSType, RHSType;
763 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
764 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
765
Chris Lattnercf250242007-06-03 02:02:44 +0000766 // If both operands have the same source type, we're done already.
767 if (LHSType == RHSType) return LHSType;
768
769 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
770 // The caller can deal with this (e.g. pointer + int).
771 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
772 return LHSType;
773
774 // At this point, we have two different arithmetic types.
775
776 // Handle complex types first (C99 6.3.1.8p1).
777 if (LHSType->isComplexType() || RHSType->isComplexType()) {
778 assert(0 && "FIXME: complex types unimp");
779#if 0
780 // if we have an integer operand, the result is the complex type.
781 if (rhs->isIntegerType())
782 return lhs;
783 if (lhs->isIntegerType())
784 return rhs;
785 return Context.maxComplexType(lhs, rhs);
786#endif
787 }
788
789 // If neither operand is complex, they must be scalars.
790 llvm::Value *LHSV = LHS.getVal();
791 llvm::Value *RHSV = RHS.getVal();
792
793 // If the LLVM types are already equal, then they only differed in sign, or it
794 // was something like char/signed char or double/long double.
795 if (LHSV->getType() == RHSV->getType())
796 return LHSType;
797
798 // Now handle "real" floating types (i.e. float, double, long double).
799 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
800 // if we have an integer operand, the result is the real floating type, and
801 // the integer converts to FP.
802 if (RHSType->isIntegerType()) {
803 // Promote the RHS to an FP type of the LHS, with the sign following the
804 // RHS.
805 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000806 RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000807 else
Chris Lattner8394d792007-06-05 20:53:16 +0000808 RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000809 return LHSType;
810 }
811
812 if (LHSType->isIntegerType()) {
813 // Promote the LHS to an FP type of the RHS, with the sign following the
814 // LHS.
815 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000816 LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000817 else
Chris Lattner8394d792007-06-05 20:53:16 +0000818 LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000819 return RHSType;
820 }
821
822 // Otherwise, they are two FP types. Promote the smaller operand to the
823 // bigger result.
824 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
825
826 if (BiggerType == LHSType)
Chris Lattner8394d792007-06-05 20:53:16 +0000827 RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000828 else
Chris Lattner8394d792007-06-05 20:53:16 +0000829 LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000830 return BiggerType;
831 }
832
833 // Finally, we have two integer types that are different according to C. Do
834 // a sign or zero extension if needed.
835
836 // Otherwise, one type is smaller than the other.
837 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
838
839 if (LHSType == ResTy) {
840 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000841 RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000842 else
Chris Lattner8394d792007-06-05 20:53:16 +0000843 RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000844 } else {
845 assert(RHSType == ResTy && "Unknown conversion");
846 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000847 LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000848 else
Chris Lattner8394d792007-06-05 20:53:16 +0000849 LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000850 }
851 return ResTy;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000852}
853
Chris Lattnercd215f02007-06-29 16:52:55 +0000854/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
855/// are strange in that the result of the operation is not the same type as the
856/// intermediate computation. This function emits the LHS and RHS operands of
857/// the compound assignment, promoting them to their common computation type.
858///
859/// Since the LHS is an lvalue, and the result is stored back through it, we
860/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
861/// RHS values are both in the computation type for the operator.
862void CodeGenFunction::
863EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
864 LValue &LHSLV, RValue &LHS, RValue &RHS) {
865 LHSLV = EmitLValue(E->getLHS());
866
867 // Load the LHS and RHS operands.
868 QualType LHSTy = E->getLHS()->getType();
869 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
870 QualType RHSTy;
871 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
872
Chris Lattner47c247e2007-06-29 17:26:27 +0000873 // Shift operands do the usual unary conversions, but do not do the binary
874 // conversions.
875 if (E->isShiftAssignOp()) {
876 // FIXME: This is broken. Implicit conversions should be made explicit,
877 // so that this goes away. This causes us to reload the LHS.
878 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy);
879 }
880
Chris Lattnercd215f02007-06-29 16:52:55 +0000881 // Convert the LHS and RHS to the common evaluation type.
882 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
883 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
884}
885
886/// EmitCompoundAssignmentResult - Given a result value in the computation type,
887/// truncate it down to the actual result type, store it through the LHS lvalue,
888/// and return it.
889RValue CodeGenFunction::
890EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
891 LValue LHSLV, RValue ResV) {
892
893 // Truncate back to the destination type.
894 if (E->getComputationType() != E->getType())
895 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
896
897 // Store the result value into the LHS.
898 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
899
900 // Return the result.
901 return ResV;
902}
903
Chris Lattnerdb91b162007-06-02 00:16:28 +0000904
Chris Lattner8394d792007-06-05 20:53:16 +0000905RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
Chris Lattnercd215f02007-06-29 16:52:55 +0000906 RValue LHS, RHS;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000907 switch (E->getOpcode()) {
908 default:
Chris Lattnerb25a9432007-06-29 17:03:06 +0000909 fprintf(stderr, "Unimplemented binary expr!\n");
Chris Lattnerdb91b162007-06-02 00:16:28 +0000910 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000911 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerb25a9432007-06-29 17:03:06 +0000912 case BinaryOperator::Mul:
913 EmitUsualArithmeticConversions(E, LHS, RHS);
914 return EmitMul(LHS, RHS, E->getType());
915 case BinaryOperator::Div:
916 EmitUsualArithmeticConversions(E, LHS, RHS);
917 return EmitDiv(LHS, RHS, E->getType());
918 case BinaryOperator::Rem:
919 EmitUsualArithmeticConversions(E, LHS, RHS);
920 return EmitRem(LHS, RHS, E->getType());
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000921 case BinaryOperator::Add: {
922 QualType ExprTy = E->getType();
923 if (ExprTy->isPointerType()) {
924 Expr *LHSExpr = E->getLHS();
925 QualType LHSTy;
926 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
927 Expr *RHSExpr = E->getRHS();
928 QualType RHSTy;
929 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
930 return EmitPointerAdd(LHS, LHSTy, RHS, RHSTy, ExprTy);
931 } else {
932 EmitUsualArithmeticConversions(E, LHS, RHS);
933 return EmitAdd(LHS, RHS, ExprTy);
934 }
935 }
936 case BinaryOperator::Sub: {
937 QualType ExprTy = E->getType();
938 Expr *LHSExpr = E->getLHS();
939 if (LHSExpr->getType()->isPointerType()) {
940 QualType LHSTy;
941 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
942 Expr *RHSExpr = E->getRHS();
943 QualType RHSTy;
944 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
945 return EmitPointerSub(LHS, LHSTy, RHS, RHSTy, ExprTy);
946 } else {
947 EmitUsualArithmeticConversions(E, LHS, RHS);
948 return EmitSub(LHS, RHS, ExprTy);
949 }
950 }
Chris Lattner47c247e2007-06-29 17:26:27 +0000951 case BinaryOperator::Shl:
952 EmitShiftOperands(E, LHS, RHS);
953 return EmitShl(LHS, RHS, E->getType());
954 case BinaryOperator::Shr:
955 EmitShiftOperands(E, LHS, RHS);
956 return EmitShr(LHS, RHS, E->getType());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000957 case BinaryOperator::And:
958 EmitUsualArithmeticConversions(E, LHS, RHS);
959 return EmitAnd(LHS, RHS, E->getType());
960 case BinaryOperator::Xor:
961 EmitUsualArithmeticConversions(E, LHS, RHS);
962 return EmitXor(LHS, RHS, E->getType());
963 case BinaryOperator::Or :
964 EmitUsualArithmeticConversions(E, LHS, RHS);
965 return EmitOr(LHS, RHS, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +0000966 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
967 case BinaryOperator::LOr: return EmitBinaryLOr(E);
Chris Lattner1fde0b32007-06-20 18:30:55 +0000968 case BinaryOperator::LT:
969 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
970 llvm::ICmpInst::ICMP_SLT,
971 llvm::FCmpInst::FCMP_OLT);
972 case BinaryOperator::GT:
973 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
974 llvm::ICmpInst::ICMP_SGT,
975 llvm::FCmpInst::FCMP_OGT);
976 case BinaryOperator::LE:
977 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
978 llvm::ICmpInst::ICMP_SLE,
979 llvm::FCmpInst::FCMP_OLE);
980 case BinaryOperator::GE:
981 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
982 llvm::ICmpInst::ICMP_SGE,
983 llvm::FCmpInst::FCMP_OGE);
984 case BinaryOperator::EQ:
985 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
986 llvm::ICmpInst::ICMP_EQ,
987 llvm::FCmpInst::FCMP_OEQ);
988 case BinaryOperator::NE:
989 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
990 llvm::ICmpInst::ICMP_NE,
991 llvm::FCmpInst::FCMP_UNE);
Chris Lattnercd215f02007-06-29 16:52:55 +0000992 case BinaryOperator::Assign:
993 return EmitBinaryAssign(E);
994
Chris Lattnerb25a9432007-06-29 17:03:06 +0000995 case BinaryOperator::MulAssign: {
996 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
997 LValue LHSLV;
998 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
999 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1000 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1001 }
1002 case BinaryOperator::DivAssign: {
1003 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1004 LValue LHSLV;
1005 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1006 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1007 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1008 }
1009 case BinaryOperator::RemAssign: {
1010 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1011 LValue LHSLV;
1012 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1013 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1014 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1015 }
Chris Lattnercd215f02007-06-29 16:52:55 +00001016 case BinaryOperator::AddAssign: {
1017 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1018 LValue LHSLV;
1019 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1020 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1021 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1022 }
1023 case BinaryOperator::SubAssign: {
1024 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1025 LValue LHSLV;
1026 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1027 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1028 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1029 }
Chris Lattner47c247e2007-06-29 17:26:27 +00001030 case BinaryOperator::ShlAssign: {
1031 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1032 LValue LHSLV;
1033 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1034 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1035 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1036 }
1037 case BinaryOperator::ShrAssign: {
1038 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1039 LValue LHSLV;
1040 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1041 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1042 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1043 }
Chris Lattnerb25a9432007-06-29 17:03:06 +00001044 case BinaryOperator::AndAssign: {
1045 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1046 LValue LHSLV;
1047 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1048 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1049 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1050 }
1051 case BinaryOperator::OrAssign: {
1052 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1053 LValue LHSLV;
1054 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1055 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1056 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1057 }
1058 case BinaryOperator::XorAssign: {
1059 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1060 LValue LHSLV;
1061 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1062 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1063 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1064 }
Chris Lattner8394d792007-06-05 20:53:16 +00001065 case BinaryOperator::Comma: return EmitBinaryComma(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +00001066 }
1067}
1068
Chris Lattnerb25a9432007-06-29 17:03:06 +00001069RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001070 if (LHS.isScalar())
1071 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1072
Gabor Greifd4606aa2007-07-13 23:33:18 +00001073 // Otherwise, this must be a complex number.
1074 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1075
1076 EmitLoadOfComplex(LHS, LHSR, LHSI);
1077 EmitLoadOfComplex(RHS, RHSR, RHSI);
1078
1079 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1080 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1081 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1082
1083 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1084 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1085 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1086
1087 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1088 EmitStoreOfComplex(ResR, ResI, Res);
1089 return RValue::getAggregate(Res);
Chris Lattner8394d792007-06-05 20:53:16 +00001090}
1091
Chris Lattnerb25a9432007-06-29 17:03:06 +00001092RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001093 if (LHS.isScalar()) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001094 llvm::Value *RV;
Chris Lattner8394d792007-06-05 20:53:16 +00001095 if (LHS.getVal()->getType()->isFloatingPoint())
1096 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
Chris Lattnerb25a9432007-06-29 17:03:06 +00001097 else if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001098 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1099 else
1100 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1101 return RValue::get(RV);
1102 }
1103 assert(0 && "FIXME: This doesn't handle complex operands yet");
1104}
1105
Chris Lattnerb25a9432007-06-29 17:03:06 +00001106RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001107 if (LHS.isScalar()) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001108 llvm::Value *RV;
Chris Lattner8394d792007-06-05 20:53:16 +00001109 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattnerb25a9432007-06-29 17:03:06 +00001110 if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001111 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1112 else
1113 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1114 return RValue::get(RV);
1115 }
1116
1117 assert(0 && "FIXME: This doesn't handle complex operands yet");
1118}
1119
Chris Lattnercd215f02007-06-29 16:52:55 +00001120RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001121 if (LHS.isScalar())
1122 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
Chris Lattnercd215f02007-06-29 16:52:55 +00001123
Chris Lattnere9a64532007-06-22 21:44:33 +00001124 // Otherwise, this must be a complex number.
1125 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1126
1127 EmitLoadOfComplex(LHS, LHSR, LHSI);
1128 EmitLoadOfComplex(RHS, RHSR, RHSI);
1129
1130 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1131 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1132
Chris Lattnercd215f02007-06-29 16:52:55 +00001133 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
Chris Lattnere9a64532007-06-22 21:44:33 +00001134 EmitStoreOfComplex(ResR, ResI, Res);
1135 return RValue::getAggregate(Res);
Chris Lattner8394d792007-06-05 20:53:16 +00001136}
1137
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001138RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1139 RValue RHS, QualType RHSTy,
1140 QualType ResTy) {
1141 llvm::Value *LHSValue = LHS.getVal();
1142 llvm::Value *RHSValue = RHS.getVal();
1143 if (LHSTy->isPointerType()) {
1144 // pointer + int
1145 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1146 } else {
1147 // int + pointer
1148 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1149 }
1150}
1151
Chris Lattnercd215f02007-06-29 16:52:55 +00001152RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001153 if (LHS.isScalar())
1154 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1155
1156 assert(0 && "FIXME: This doesn't handle complex operands yet");
Chris Lattner8394d792007-06-05 20:53:16 +00001157}
1158
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001159RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1160 RValue RHS, QualType RHSTy,
1161 QualType ResTy) {
1162 llvm::Value *LHSValue = LHS.getVal();
1163 llvm::Value *RHSValue = RHS.getVal();
1164 if (const PointerType *RHSPtrType =
1165 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1166 // pointer - pointer
1167 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1168 QualType LHSElementType = LHSPtrType->getPointeeType();
1169 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1170 "can't subtract pointers with differing element types");
Chris Lattner983a8bb2007-07-13 22:13:22 +00001171 unsigned ElementSize = getContext().getTypeSize(LHSElementType) / 8;
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001172 const llvm::Type *ResultType = ConvertType(ResTy);
1173 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1174 "sub.ptr.lhs.cast");
1175 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1176 "sub.ptr.rhs.cast");
1177 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1178 "sub.ptr.sub");
1179 llvm::Value *BytesPerElement = llvm::ConstantInt::get(ResultType,
1180 ElementSize);
1181 llvm::Value *ElementsBetween = Builder.CreateSDiv(BytesBetween,
1182 BytesPerElement,
1183 "sub.ptr.div");
1184 return RValue::get(ElementsBetween);
1185 } else {
1186 // pointer - int
1187 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1188 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1189 }
1190}
1191
Chris Lattner47c247e2007-06-29 17:26:27 +00001192void CodeGenFunction::EmitShiftOperands(const BinaryOperator *E,
1193 RValue &LHS, RValue &RHS) {
Chris Lattner8394d792007-06-05 20:53:16 +00001194 // For shifts, integer promotions are performed, but the usual arithmetic
1195 // conversions are not. The LHS and RHS need not have the same type.
Chris Lattner8394d792007-06-05 20:53:16 +00001196 QualType ResTy;
Chris Lattner47c247e2007-06-29 17:26:27 +00001197 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy);
1198 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy);
1199}
Chris Lattner8394d792007-06-05 20:53:16 +00001200
Chris Lattner47c247e2007-06-29 17:26:27 +00001201
1202RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1203 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1204
Chris Lattner8394d792007-06-05 20:53:16 +00001205 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1206 // RHS to the same size as the LHS.
1207 if (LHS->getType() != RHS->getType())
1208 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1209
1210 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1211}
1212
Chris Lattner47c247e2007-06-29 17:26:27 +00001213RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1214 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
Chris Lattner8394d792007-06-05 20:53:16 +00001215
1216 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1217 // RHS to the same size as the LHS.
1218 if (LHS->getType() != RHS->getType())
1219 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1220
Chris Lattner47c247e2007-06-29 17:26:27 +00001221 if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001222 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1223 else
1224 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1225}
1226
Chris Lattner1fde0b32007-06-20 18:30:55 +00001227RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1228 unsigned UICmpOpc, unsigned SICmpOpc,
1229 unsigned FCmpOpc) {
Chris Lattner273c63d2007-06-20 18:02:30 +00001230 RValue LHS, RHS;
1231 EmitUsualArithmeticConversions(E, LHS, RHS);
1232
1233 llvm::Value *Result;
1234 if (LHS.isScalar()) {
1235 if (LHS.getVal()->getType()->isFloatingPoint()) {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001236 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1237 LHS.getVal(), RHS.getVal(), "cmp");
1238 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1239 // FIXME: This check isn't right for "unsigned short < int" where ushort
1240 // promotes to int and does a signed compare.
1241 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1242 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001243 } else {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001244 // Signed integers and pointers.
1245 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1246 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001247 }
1248 } else {
1249 // Struct/union/complex
Gabor Greifd4606aa2007-07-13 23:33:18 +00001250 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1251 EmitLoadOfComplex(LHS, LHSR, LHSI);
1252 EmitLoadOfComplex(RHS, RHSR, RHSI);
1253
1254 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1255 LHSR, RHSR, "cmp.r");
1256 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1257 LHSI, RHSI, "cmp.i");
1258 if (BinaryOperator::EQ == E->getOpcode()) {
1259 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1260 } else if (BinaryOperator::NE == E->getOpcode()) {
1261 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1262 } else {
1263 assert(0 && "Complex comparison other than == or != ?");
1264 }
Chris Lattner273c63d2007-06-20 18:02:30 +00001265 }
Gabor Greifd4606aa2007-07-13 23:33:18 +00001266
Chris Lattner273c63d2007-06-20 18:02:30 +00001267 // ZExt result to int.
1268 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1269}
1270
Chris Lattnerb25a9432007-06-29 17:03:06 +00001271RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001272 if (LHS.isScalar())
1273 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1274
1275 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1276}
1277
Chris Lattnerb25a9432007-06-29 17:03:06 +00001278RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001279 if (LHS.isScalar())
1280 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1281
1282 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1283}
1284
Chris Lattnerb25a9432007-06-29 17:03:06 +00001285RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001286 if (LHS.isScalar())
1287 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1288
1289 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1290}
1291
1292RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001293 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001294
Chris Lattner23b7eb62007-06-15 23:05:46 +00001295 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1296 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001297
Chris Lattner23b7eb62007-06-15 23:05:46 +00001298 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001299 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1300
1301 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001302 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001303
1304 // Reaquire the RHS block, as there may be subblocks inserted.
1305 RHSBlock = Builder.GetInsertBlock();
1306 EmitBlock(ContBlock);
1307
1308 // Create a PHI node. If we just evaluted the LHS condition, the result is
1309 // false. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001310 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
Chris Lattner8394d792007-06-05 20:53:16 +00001311 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001312 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001313 PN->addIncoming(RHSCond, RHSBlock);
1314
1315 // ZExt result to int.
1316 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1317}
1318
1319RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001320 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001321
Chris Lattner23b7eb62007-06-15 23:05:46 +00001322 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1323 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001324
Chris Lattner23b7eb62007-06-15 23:05:46 +00001325 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001326 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1327
1328 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001329 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001330
1331 // Reaquire the RHS block, as there may be subblocks inserted.
1332 RHSBlock = Builder.GetInsertBlock();
1333 EmitBlock(ContBlock);
1334
1335 // Create a PHI node. If we just evaluted the LHS condition, the result is
1336 // true. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001337 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
Chris Lattner8394d792007-06-05 20:53:16 +00001338 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001339 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001340 PN->addIncoming(RHSCond, RHSBlock);
1341
1342 // ZExt result to int.
1343 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1344}
1345
1346RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
1347 LValue LHS = EmitLValue(E->getLHS());
1348
1349 QualType RHSTy;
1350 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
1351
1352 // Convert the RHS to the type of the LHS.
Chris Lattnerf033c142007-06-22 19:05:19 +00001353 RHS = EmitConversion(RHS, RHSTy, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +00001354
1355 // Store the value into the LHS.
1356 EmitStoreThroughLValue(RHS, LHS, E->getType());
1357
1358 // Return the converted RHS.
1359 return RHS;
1360}
1361
Chris Lattner9369a562007-06-29 16:31:29 +00001362
Chris Lattner8394d792007-06-05 20:53:16 +00001363RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1364 EmitExpr(E->getLHS());
1365 return EmitExpr(E->getRHS());
1366}
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001367
1368RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1369 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1370 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1371 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1372
1373 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1374 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1375
Chris Lattner027f21d2007-07-14 00:01:01 +00001376 // FIXME: Implement this for aggregate values.
1377
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001378 // FIXME: LHS & RHS need the "usual arithmetic conversions" but
1379 // that's not possible with the current design.
1380
1381 EmitBlock(LHSBlock);
1382 QualType LHSTy;
1383 llvm::Value *LHSValue = E->getLHS() ? // GNU extension
1384 EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy).getVal() :
1385 Cond;
1386 Builder.CreateBr(ContBlock);
1387 LHSBlock = Builder.GetInsertBlock();
1388
1389 EmitBlock(RHSBlock);
1390 QualType RHSTy;
1391 llvm::Value *RHSValue =
1392 EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy).getVal();
1393 Builder.CreateBr(ContBlock);
1394 RHSBlock = Builder.GetInsertBlock();
1395
1396 const llvm::Type *LHSType = LHSValue->getType();
1397 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1398
1399 EmitBlock(ContBlock);
1400 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1401 PN->reserveOperandSpace(2);
1402 PN->addIncoming(LHSValue, LHSBlock);
1403 PN->addIncoming(RHSValue, RHSBlock);
1404
1405 return RValue::get(PN);
1406}