blob: 40c25ae0bbda7447273704ffb4a9e4c46811b6db [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 Lattner651f0e92007-07-16 05:43:05 +000021#include "llvm/Support/MathExtras.h"
Chris Lattnere47e4402007-06-01 18:02:12 +000022using namespace clang;
23using namespace CodeGen;
24
Chris Lattnerd7f58862007-06-02 05:24:33 +000025//===--------------------------------------------------------------------===//
Chris Lattnerf0106d22007-06-02 19:33:17 +000026// Miscellaneous Helper Methods
27//===--------------------------------------------------------------------===//
28
Chris Lattnere9a64532007-06-22 21:44:33 +000029/// CreateTempAlloca - This creates a alloca and inserts it into the entry
30/// block.
31llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
32 const char *Name) {
33 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
34}
Chris Lattner8394d792007-06-05 20:53:16 +000035
36/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
37/// expression and compare the result against zero, returning an Int1Ty value.
Chris Lattner23b7eb62007-06-15 23:05:46 +000038llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattner8394d792007-06-05 20:53:16 +000039 QualType Ty;
40 RValue Val = EmitExprWithUsualUnaryConversions(E, Ty);
41 return ConvertScalarValueToBool(Val, Ty);
42}
43
Chris Lattnere9a64532007-06-22 21:44:33 +000044/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
45/// load the real and imaginary pieces, returning them as Real/Imag.
46void CodeGenFunction::EmitLoadOfComplex(RValue V,
47 llvm::Value *&Real, llvm::Value *&Imag){
48 llvm::Value *Ptr = V.getAggregateAddr();
49
50 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
51 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
52 llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "realp");
53 llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imagp");
54
55 // FIXME: Handle volatility.
56 Real = Builder.CreateLoad(RealPtr, "real");
57 Imag = Builder.CreateLoad(ImagPtr, "imag");
58}
59
60/// EmitStoreOfComplex - Store the specified real/imag parts into the
61/// specified value pointer.
62void CodeGenFunction::EmitStoreOfComplex(llvm::Value *Real, llvm::Value *Imag,
63 llvm::Value *ResPtr) {
64 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
65 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
66 llvm::Value *RealPtr = Builder.CreateGEP(ResPtr, Zero, Zero, "real");
67 llvm::Value *ImagPtr = Builder.CreateGEP(ResPtr, Zero, One, "imag");
68
69 // FIXME: Handle volatility.
70 Builder.CreateStore(Real, RealPtr);
71 Builder.CreateStore(Imag, ImagPtr);
72}
73
Chris Lattner8394d792007-06-05 20:53:16 +000074//===--------------------------------------------------------------------===//
75// Conversions
76//===--------------------------------------------------------------------===//
77
78/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
79/// the type specified by DstTy, following the rules of C99 6.3.
80RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
Chris Lattnerf033c142007-06-22 19:05:19 +000081 QualType DstTy) {
Chris Lattner8394d792007-06-05 20:53:16 +000082 ValTy = ValTy.getCanonicalType();
83 DstTy = DstTy.getCanonicalType();
84 if (ValTy == DstTy) return Val;
Chris Lattner83b484b2007-06-06 04:39:08 +000085
86 // Handle conversions to bool first, they are special: comparisons against 0.
87 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
88 if (DestBT->getKind() == BuiltinType::Bool)
89 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
Chris Lattner8394d792007-06-05 20:53:16 +000090
Chris Lattner83b484b2007-06-06 04:39:08 +000091 // Handle pointer conversions next: pointers can only be converted to/from
92 // other pointers and integers.
Chris Lattnercf106ab2007-06-06 04:05:39 +000093 if (isa<PointerType>(DstTy)) {
Chris Lattnerf033c142007-06-22 19:05:19 +000094 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattnercf106ab2007-06-06 04:05:39 +000095
96 // The source value may be an integer, or a pointer.
97 assert(Val.isScalar() && "Can only convert from integer or pointer");
98 if (isa<llvm::PointerType>(Val.getVal()->getType()))
99 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
100 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Chris Lattnerfc7634f2007-07-13 03:25:53 +0000101 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Chris Lattner83b484b2007-06-06 04:39:08 +0000102 }
103
104 if (isa<PointerType>(ValTy)) {
Chris Lattnercf106ab2007-06-06 04:05:39 +0000105 // Must be an ptr to int cast.
Chris Lattnerf033c142007-06-22 19:05:19 +0000106 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattnercf106ab2007-06-06 04:05:39 +0000107 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
108 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
Chris Lattner8394d792007-06-05 20:53:16 +0000109 }
Chris Lattner83b484b2007-06-06 04:39:08 +0000110
111 // Finally, we have the arithmetic types: real int/float and complex
112 // int/float. Handle real->real conversions first, they are the most
113 // common.
114 if (Val.isScalar() && DstTy->isRealType()) {
115 // We know that these are representable as scalars in LLVM, convert to LLVM
116 // types since they are easier to reason about.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000117 llvm::Value *SrcVal = Val.getVal();
Chris Lattnerf033c142007-06-22 19:05:19 +0000118 const llvm::Type *DestTy = ConvertType(DstTy);
Chris Lattner83b484b2007-06-06 04:39:08 +0000119 if (SrcVal->getType() == DestTy) return Val;
120
Chris Lattner23b7eb62007-06-15 23:05:46 +0000121 llvm::Value *Result;
Chris Lattner83b484b2007-06-06 04:39:08 +0000122 if (isa<llvm::IntegerType>(SrcVal->getType())) {
123 bool InputSigned = ValTy->isSignedIntegerType();
124 if (isa<llvm::IntegerType>(DestTy))
125 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
126 else if (InputSigned)
127 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
128 else
129 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
130 } else {
131 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
132 if (isa<llvm::IntegerType>(DestTy)) {
133 if (DstTy->isSignedIntegerType())
134 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
135 else
136 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
137 } else {
138 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
139 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
140 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
141 else
142 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
143 }
144 }
145 return RValue::get(Result);
146 }
147
148 assert(0 && "FIXME: We don't support complex conversions yet!");
Chris Lattner8394d792007-06-05 20:53:16 +0000149}
150
151
152/// ConvertScalarValueToBool - Convert the specified expression value to a
Chris Lattnerf0106d22007-06-02 19:33:17 +0000153/// boolean (i1) truth value. This is equivalent to "Val == 0".
Chris Lattner23b7eb62007-06-15 23:05:46 +0000154llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
Chris Lattnerf0106d22007-06-02 19:33:17 +0000155 Ty = Ty.getCanonicalType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000156 llvm::Value *Result;
Chris Lattnerf0106d22007-06-02 19:33:17 +0000157 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
158 switch (BT->getKind()) {
159 default: assert(0 && "Unknown scalar value");
160 case BuiltinType::Bool:
161 Result = Val.getVal();
162 // Bool is already evaluated right.
163 assert(Result->getType() == llvm::Type::Int1Ty &&
164 "Unexpected bool value type!");
165 return Result;
Chris Lattnerb16f4552007-06-03 07:25:34 +0000166 case BuiltinType::Char_S:
167 case BuiltinType::Char_U:
Chris Lattnerf0106d22007-06-02 19:33:17 +0000168 case BuiltinType::SChar:
169 case BuiltinType::UChar:
170 case BuiltinType::Short:
171 case BuiltinType::UShort:
172 case BuiltinType::Int:
173 case BuiltinType::UInt:
174 case BuiltinType::Long:
175 case BuiltinType::ULong:
176 case BuiltinType::LongLong:
177 case BuiltinType::ULongLong:
178 // Code below handles simple integers.
179 break;
180 case BuiltinType::Float:
181 case BuiltinType::Double:
182 case BuiltinType::LongDouble: {
183 // Compare against 0.0 for fp scalars.
184 Result = Val.getVal();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000185 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000186 // FIXME: llvm-gcc produces a une comparison: validate this is right.
187 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
188 return Result;
189 }
Chris Lattnerf0106d22007-06-02 19:33:17 +0000190 }
Chris Lattnerc6395932007-06-22 20:56:16 +0000191 } else if (isa<PointerType>(Ty) ||
192 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000193 // Code below handles this fine.
Chris Lattnerc6395932007-06-22 20:56:16 +0000194 } else {
195 assert(isa<ComplexType>(Ty) && "Unknwon type!");
196 assert(0 && "FIXME: comparisons against complex not implemented yet");
Chris Lattnerf0106d22007-06-02 19:33:17 +0000197 }
198
199 // Usual case for integers, pointers, and enums: compare against zero.
200 Result = Val.getVal();
Chris Lattnera45c5af2007-06-02 19:47:04 +0000201
202 // Because of the type rules of C, we often end up computing a logical value,
203 // then zero extending it to int, then wanting it as a logical value again.
204 // Optimize this common case.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000205 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
Chris Lattnera45c5af2007-06-02 19:47:04 +0000206 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
207 Result = ZI->getOperand(0);
208 ZI->eraseFromParent();
209 return Result;
210 }
211 }
212
Chris Lattner23b7eb62007-06-15 23:05:46 +0000213 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000214 return Builder.CreateICmpNE(Result, Zero, "tobool");
215}
216
Chris Lattnera45c5af2007-06-02 19:47:04 +0000217//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000218// LValue Expression Emission
Chris Lattnera45c5af2007-06-02 19:47:04 +0000219//===----------------------------------------------------------------------===//
Chris Lattnerd7f58862007-06-02 05:24:33 +0000220
Chris Lattner8394d792007-06-05 20:53:16 +0000221/// EmitLValue - Emit code to compute a designator that specifies the location
222/// of the expression.
223///
224/// This can return one of two things: a simple address or a bitfield
225/// reference. In either case, the LLVM Value* in the LValue structure is
226/// guaranteed to be an LLVM pointer type.
227///
228/// If this returns a bitfield reference, nothing about the pointee type of
229/// the LLVM value is known: For example, it may not be a pointer to an
230/// integer.
231///
232/// If this returns a normal address, and if the lvalue's C type is fixed
233/// size, this method guarantees that the returned pointer type will point to
234/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
235/// variable length type, this is not possible.
236///
Chris Lattnerd7f58862007-06-02 05:24:33 +0000237LValue CodeGenFunction::EmitLValue(const Expr *E) {
238 switch (E->getStmtClass()) {
239 default:
Chris Lattner8394d792007-06-05 20:53:16 +0000240 fprintf(stderr, "Unimplemented lvalue expr!\n");
Chris Lattnerd7f58862007-06-02 05:24:33 +0000241 E->dump();
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000242 return LValue::MakeAddr(llvm::UndefValue::get(
Chris Lattnerd7f58862007-06-02 05:24:33 +0000243 llvm::PointerType::get(llvm::Type::Int32Ty)));
244
245 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
Chris Lattner946aa312007-06-05 03:59:43 +0000246 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
Chris Lattner4347e3692007-06-06 04:54:52 +0000247 case Expr::StringLiteralClass:
248 return EmitStringLiteralLValue(cast<StringLiteral>(E));
Chris Lattner8394d792007-06-05 20:53:16 +0000249
250 case Expr::UnaryOperatorClass:
251 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000252 case Expr::ArraySubscriptExprClass:
253 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000254 }
255}
256
Chris Lattner8394d792007-06-05 20:53:16 +0000257/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
258/// this method emits the address of the lvalue, then loads the result as an
259/// rvalue, returning the rvalue.
Chris Lattner9369a562007-06-29 16:31:29 +0000260RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
261 ExprType = ExprType.getCanonicalType();
Chris Lattner8394d792007-06-05 20:53:16 +0000262
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000263 if (LV.isSimple()) {
264 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);
274 }
Chris Lattner09153c02007-06-22 18:48:09 +0000275
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000276 if (LV.isVectorElt()) {
277 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
278 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
279 "vecext"));
280 }
Chris Lattner09153c02007-06-22 18:48:09 +0000281
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000282 assert(0 && "Bitfield ref not impl!");
Chris Lattner8394d792007-06-05 20:53:16 +0000283}
284
Chris Lattner9369a562007-06-29 16:31:29 +0000285RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
286 return EmitLoadOfLValue(EmitLValue(E), E->getType());
287}
288
289
Chris Lattner8394d792007-06-05 20:53:16 +0000290/// EmitStoreThroughLValue - Store the specified rvalue into the specified
291/// lvalue, where both are guaranteed to the have the same type, and that type
292/// is 'Ty'.
293void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
294 QualType Ty) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000295 if (Dst.isVectorElt()) {
296 // Read/modify/write the vector, inserting the new element.
297 // FIXME: Volatility.
298 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
299 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
300 Dst.getVectorIdx(), "vecins");
301 Builder.CreateStore(Vec, Dst.getVectorAddr());
302 return;
303 }
304
305 assert(Dst.isSimple() && "FIXME: Don't support store to bitfield yet");
Chris Lattner8394d792007-06-05 20:53:16 +0000306
Chris Lattner09153c02007-06-22 18:48:09 +0000307 llvm::Value *DstAddr = Dst.getAddress();
308 if (Src.isScalar()) {
309 // FIXME: Handle volatility etc.
310 const llvm::Type *SrcTy = Src.getVal()->getType();
311 const llvm::Type *AddrTy =
312 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
313
314 if (AddrTy != SrcTy)
315 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
316 "storetmp");
317 Builder.CreateStore(Src.getVal(), DstAddr);
318 return;
319 }
Chris Lattner8394d792007-06-05 20:53:16 +0000320
Chris Lattnere9a64532007-06-22 21:44:33 +0000321 // Don't use memcpy for complex numbers.
322 if (Ty->isComplexType()) {
323 llvm::Value *Real, *Imag;
324 EmitLoadOfComplex(Src, Real, Imag);
325 EmitStoreOfComplex(Real, Imag, Dst.getAddress());
326 return;
327 }
328
Chris Lattner09153c02007-06-22 18:48:09 +0000329 // Aggregate assignment turns into llvm.memcpy.
330 const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
331 llvm::Value *SrcAddr = Src.getAggregateAddr();
332
333 if (DstAddr->getType() != SBP)
334 DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
335 if (SrcAddr->getType() != SBP)
336 SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
337
338 unsigned Align = 1; // FIXME: Compute type alignments.
339 unsigned Size = 1234; // FIXME: Compute type sizes.
340
341 // FIXME: Handle variable sized types.
342 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
343 llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
344
345 llvm::Value *MemCpyOps[4] = {
346 DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
347 };
348
349 Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, 4);
Chris Lattner8394d792007-06-05 20:53:16 +0000350}
351
Chris Lattnerd7f58862007-06-02 05:24:33 +0000352
353LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
354 const Decl *D = E->getDecl();
Chris Lattner53621a52007-06-13 20:44:40 +0000355 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000356 llvm::Value *V = LocalDeclMap[D];
Chris Lattnerd7f58862007-06-02 05:24:33 +0000357 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000358 return LValue::MakeAddr(V);
Chris Lattnerb6984c42007-06-20 04:44:43 +0000359 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000360 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000361 }
362 assert(0 && "Unimp declref");
363}
Chris Lattnere47e4402007-06-01 18:02:12 +0000364
Chris Lattner8394d792007-06-05 20:53:16 +0000365LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
366 // __extension__ doesn't affect lvalue-ness.
367 if (E->getOpcode() == UnaryOperator::Extension)
368 return EmitLValue(E->getSubExpr());
369
370 assert(E->getOpcode() == UnaryOperator::Deref &&
371 "'*' is the only unary operator that produces an lvalue");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000372 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
Chris Lattner8394d792007-06-05 20:53:16 +0000373}
374
Chris Lattner4347e3692007-06-06 04:54:52 +0000375LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
376 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
377 const char *StrData = E->getStrData();
378 unsigned Len = E->getByteLength();
379
380 // FIXME: Can cache/reuse these within the module.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000381 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
Chris Lattner4347e3692007-06-06 04:54:52 +0000382
383 // Create a global variable for this.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000384 C = new llvm::GlobalVariable(C->getType(), true,
385 llvm::GlobalValue::InternalLinkage,
Chris Lattner4347e3692007-06-06 04:54:52 +0000386 C, ".str", CurFn->getParent());
Chris Lattner23b7eb62007-06-15 23:05:46 +0000387 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
388 llvm::Constant *Zeros[] = { Zero, Zero };
389 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000390 return LValue::MakeAddr(C);
Chris Lattner4347e3692007-06-06 04:54:52 +0000391}
392
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000393LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000394 // The index must always be a pointer or integer, neither of which is an
395 // aggregate. Emit it.
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000396 QualType IdxTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000397 llvm::Value *Idx =
398 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000399
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000400 // If the base is a vector type, then we are forming a vector element lvalue
401 // with this subscript.
402 if (E->getBase()->getType()->isVectorType()) {
403 // Emit the vector as an lvalue to get its address.
404 LValue Base = EmitLValue(E->getBase());
405 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
406 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
407 return LValue::MakeVectorElt(Base.getAddress(), Idx);
408 }
409
410 // At this point, the base must be a pointer or integer, neither of which are
411 // aggregates. Emit it.
412 QualType BaseTy;
413 llvm::Value *Base =
414 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
415
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000416 // Usually the base is the pointer type, but sometimes it is the index.
417 // Canonicalize to have the pointer as the base.
418 if (isa<llvm::PointerType>(Idx->getType())) {
419 std::swap(Base, Idx);
420 std::swap(BaseTy, IdxTy);
421 }
422
423 // The pointer is now the base. Extend or truncate the index type to 32 or
424 // 64-bits.
425 bool IdxSigned = IdxTy->isSignedIntegerType();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000426 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000427 if (IdxBitwidth != LLVMPointerWidth)
Chris Lattner23b7eb62007-06-15 23:05:46 +0000428 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000429 IdxSigned, "idxprom");
430
431 // We know that the pointer points to a type of the correct size, unless the
432 // size is a VLA.
Chris Lattner0e9d6222007-07-15 23:26:56 +0000433 if (!E->getType()->isConstantSizeType(getContext()))
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000434 assert(0 && "VLA idx not implemented");
Chris Lattner08c4b9f2007-07-10 21:17:59 +0000435 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
Chris Lattnerd9d2fb12007-06-08 23:31:14 +0000436}
437
Chris Lattnere47e4402007-06-01 18:02:12 +0000438//===--------------------------------------------------------------------===//
439// Expression Emission
440//===--------------------------------------------------------------------===//
441
Chris Lattner8394d792007-06-05 20:53:16 +0000442RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattnere47e4402007-06-01 18:02:12 +0000443 assert(E && "Null expression?");
444
445 switch (E->getStmtClass()) {
446 default:
Chris Lattner1fde0b32007-06-20 18:30:55 +0000447 fprintf(stderr, "Unimplemented expr!\n");
Chris Lattnere47e4402007-06-01 18:02:12 +0000448 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000449 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000450
451 // l-values.
Chris Lattner8394d792007-06-05 20:53:16 +0000452 case Expr::DeclRefExprClass:
Chris Lattnerf99b3f52007-06-11 03:52:52 +0000453 // DeclRef's of EnumConstantDecl's are simple rvalues.
454 if (const EnumConstantDecl *EC =
455 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
Chris Lattner23b7eb62007-06-15 23:05:46 +0000456 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
Chris Lattner8394d792007-06-05 20:53:16 +0000457 return EmitLoadOfLValue(E);
Chris Lattnera779b3d2007-07-10 21:58:36 +0000458 case Expr::ArraySubscriptExprClass:
459 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Chris Lattner4347e3692007-06-06 04:54:52 +0000460 case Expr::StringLiteralClass:
461 return RValue::get(EmitLValue(E).getAddress());
Chris Lattnerd7f58862007-06-02 05:24:33 +0000462
463 // Leaf expressions.
464 case Expr::IntegerLiteralClass:
Chris Lattnere47e4402007-06-01 18:02:12 +0000465 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
Chris Lattner2ada32e2007-07-09 23:03:16 +0000466 case Expr::FloatingLiteralClass:
467 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000468 case Expr::CharacterLiteralClass:
469 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattnerdb91b162007-06-02 00:16:28 +0000470
Chris Lattnerd7f58862007-06-02 05:24:33 +0000471 // Operators.
472 case Expr::ParenExprClass:
473 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000474 case Expr::UnaryOperatorClass:
475 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner388cf762007-07-13 20:25:53 +0000476 case Expr::ImplicitCastExprClass:
477 return EmitCastExpr(cast<ImplicitCastExpr>(E)->getSubExpr(), E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +0000478 case Expr::CastExprClass:
Chris Lattner388cf762007-07-13 20:25:53 +0000479 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
Chris Lattner2b228c92007-06-15 21:34:29 +0000480 case Expr::CallExprClass:
481 return EmitCallExpr(cast<CallExpr>(E));
Chris Lattnerd7f58862007-06-02 05:24:33 +0000482 case Expr::BinaryOperatorClass:
Chris Lattnerdb91b162007-06-02 00:16:28 +0000483 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000484
485 case Expr::ConditionalOperatorClass:
486 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Chris Lattnere47e4402007-06-01 18:02:12 +0000487 }
488
489}
490
Chris Lattner8394d792007-06-05 20:53:16 +0000491RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +0000492 return RValue::get(llvm::ConstantInt::get(E->getValue()));
Chris Lattnere47e4402007-06-01 18:02:12 +0000493}
Chris Lattner2ada32e2007-07-09 23:03:16 +0000494RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
495 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
496 E->getValue()));
497}
Chris Lattner6e9d9b32007-07-13 05:18:11 +0000498RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
499 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
500 E->getValue()));
501}
Chris Lattnera779b3d2007-07-10 21:58:36 +0000502
503RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
504 // Emit subscript expressions in rvalue context's. For most cases, this just
505 // loads the lvalue formed by the subscript expr. However, we have to be
506 // careful, because the base of a vector subscript is occasionally an rvalue,
507 // so we can't get it as an lvalue.
508 if (!E->getBase()->getType()->isVectorType())
509 return EmitLoadOfLValue(E);
510
511 // Handle the vector case. The base must be a vector, the index must be an
512 // integer value.
513 QualType BaseTy, IdxTy;
514 llvm::Value *Base =
515 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
516 llvm::Value *Idx =
517 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
518
519 // FIXME: Convert Idx to i32 type.
520
521 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
522}
523
Chris Lattner388cf762007-07-13 20:25:53 +0000524// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
525// have to handle a more broad range of conversions than explicit casts, as they
526// handle things like function to ptr-to-function decay etc.
527RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattner8394d792007-06-05 20:53:16 +0000528 QualType SrcTy;
Chris Lattner388cf762007-07-13 20:25:53 +0000529 RValue Src = EmitExprWithUsualUnaryConversions(Op, SrcTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000530
531 // If the destination is void, just evaluate the source.
Chris Lattner388cf762007-07-13 20:25:53 +0000532 if (DestTy->isVoidType())
Chris Lattner8394d792007-06-05 20:53:16 +0000533 return RValue::getAggregate(0);
534
Chris Lattner388cf762007-07-13 20:25:53 +0000535 return EmitConversion(Src, SrcTy, DestTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000536}
Chris Lattnerf0106d22007-06-02 19:33:17 +0000537
Chris Lattner2b228c92007-06-15 21:34:29 +0000538RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Chris Lattnerc14236b2007-07-10 22:18:37 +0000539 QualType CalleeTy;
Chris Lattner23b7eb62007-06-15 23:05:46 +0000540 llvm::Value *Callee =
Chris Lattnerc14236b2007-07-10 22:18:37 +0000541 EmitExprWithUsualUnaryConversions(E->getCallee(), CalleeTy).getVal();
542
543 // The callee type will always be a pointer to function type, get the function
544 // type.
545 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
546
547 // Get information about the argument types.
548 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
549
550 // Calling unprototyped functions provides no argument info.
551 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
552 ArgTyIt = FTP->arg_type_begin();
553 ArgTyEnd = FTP->arg_type_end();
554 }
Chris Lattner2b228c92007-06-15 21:34:29 +0000555
Chris Lattner23b7eb62007-06-15 23:05:46 +0000556 llvm::SmallVector<llvm::Value*, 16> Args;
Chris Lattner2b228c92007-06-15 21:34:29 +0000557
558 // FIXME: Handle struct return.
559 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattnerc14236b2007-07-10 22:18:37 +0000560 QualType ArgTy;
561 RValue ArgVal = EmitExprWithUsualUnaryConversions(E->getArg(i), ArgTy);
562
563 // If this argument has prototype information, convert it.
564 if (ArgTyIt != ArgTyEnd) {
565 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
566 } else {
567 // Otherwise, if passing through "..." or to a function with no prototype,
568 // perform the "default argument promotions" (C99 6.5.2.2p6), which
569 // includes the usual unary conversions, but also promotes float to
570 // double.
571 if (const BuiltinType *BT =
572 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
573 if (BT->getKind() == BuiltinType::Float)
574 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
575 llvm::Type::DoubleTy,"tmp"));
576 }
577 }
578
Chris Lattner2b228c92007-06-15 21:34:29 +0000579
580 if (ArgVal.isScalar())
581 Args.push_back(ArgVal.getVal());
582 else // Pass by-address. FIXME: Set attribute bit on call.
Chris Lattner09153c02007-06-22 18:48:09 +0000583 Args.push_back(ArgVal.getAggregateAddr());
Chris Lattner2b228c92007-06-15 21:34:29 +0000584 }
585
Chris Lattner23b7eb62007-06-15 23:05:46 +0000586 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], Args.size());
Chris Lattner2b228c92007-06-15 21:34:29 +0000587 if (V->getType() != llvm::Type::VoidTy)
588 V->setName("call");
589
590 // FIXME: Struct return;
591 return RValue::get(V);
592}
593
594
Chris Lattner8394d792007-06-05 20:53:16 +0000595//===----------------------------------------------------------------------===//
596// Unary Operator Emission
597//===----------------------------------------------------------------------===//
598
599RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
600 QualType &ResTy) {
Chris Lattner6db1fb82007-06-02 22:49:07 +0000601 ResTy = E->getType().getCanonicalType();
602
603 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
604 // Functions are promoted to their address.
605 ResTy = getContext().getPointerType(ResTy);
Chris Lattner8394d792007-06-05 20:53:16 +0000606 return RValue::get(EmitLValue(E).getAddress());
Chris Lattner6db1fb82007-06-02 22:49:07 +0000607 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
608 // C99 6.3.2.1p3
609 ResTy = getContext().getPointerType(ary->getElementType());
610
611 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
612 // will not true when we add support for VLAs.
613 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
614
615 assert(isa<llvm::PointerType>(V->getType()) &&
616 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
617 ->getElementType()) &&
618 "Doesn't support VLAs yet!");
619 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Chris Lattner8394d792007-06-05 20:53:16 +0000620 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
Chris Lattner6db1fb82007-06-02 22:49:07 +0000621 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
622 // FIXME: this probably isn't right, pending clarification from Steve.
623 llvm::Value *Val = EmitExpr(E).getVal();
624
Chris Lattner6db1fb82007-06-02 22:49:07 +0000625 // If the input is a signed integer, sign extend to the destination.
626 if (ResTy->isSignedIntegerType()) {
627 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
628 } else {
629 // This handles unsigned types, including bool.
630 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
631 }
632 ResTy = getContext().IntTy;
633
Chris Lattner8394d792007-06-05 20:53:16 +0000634 return RValue::get(Val);
Chris Lattner6db1fb82007-06-02 22:49:07 +0000635 }
636
637 // Otherwise, this is a float, double, int, struct, etc.
638 return EmitExpr(E);
639}
640
641
Chris Lattner8394d792007-06-05 20:53:16 +0000642RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
Chris Lattnerf0106d22007-06-02 19:33:17 +0000643 switch (E->getOpcode()) {
644 default:
645 printf("Unimplemented unary expr!\n");
646 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000647 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerdcca4872007-07-11 23:43:46 +0000648 case UnaryOperator::PostInc:
649 case UnaryOperator::PostDec:
650 case UnaryOperator::PreInc :
651 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
652 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
653 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
654 case UnaryOperator::Plus : return EmitUnaryPlus(E);
655 case UnaryOperator::Minus : return EmitUnaryMinus(E);
656 case UnaryOperator::Not : return EmitUnaryNot(E);
657 case UnaryOperator::LNot : return EmitUnaryLNot(E);
Chris Lattner8394d792007-06-05 20:53:16 +0000658 // FIXME: SIZEOF/ALIGNOF(expr).
659 // FIXME: real/imag
660 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000661 }
662}
663
Chris Lattnerdcca4872007-07-11 23:43:46 +0000664RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
665 LValue LV = EmitLValue(E->getSubExpr());
666 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
667
668 // We know the operand is real or pointer type, so it must be an LLVM scalar.
669 assert(InVal.isScalar() && "Unknown thing to increment");
670 llvm::Value *InV = InVal.getVal();
671
672 int AmountVal = 1;
673 if (E->getOpcode() == UnaryOperator::PreDec ||
674 E->getOpcode() == UnaryOperator::PostDec)
675 AmountVal = -1;
676
677 llvm::Value *NextVal;
678 if (isa<llvm::IntegerType>(InV->getType())) {
679 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
680 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
681 } else if (InV->getType()->isFloatingPoint()) {
682 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
683 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
684 } else {
685 // FIXME: This is not right for pointers to VLA types.
686 assert(isa<llvm::PointerType>(InV->getType()));
687 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
688 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
689 }
690
691 RValue NextValToStore = RValue::get(NextVal);
692
693 // Store the updated result through the lvalue.
694 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
695
696 // If this is a postinc, return the value read from memory, otherwise use the
697 // updated value.
698 if (E->getOpcode() == UnaryOperator::PreDec ||
699 E->getOpcode() == UnaryOperator::PreInc)
700 return NextValToStore;
701 else
702 return InVal;
703}
704
Chris Lattner8394d792007-06-05 20:53:16 +0000705/// C99 6.5.3.2
706RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
707 // The address of the operand is just its lvalue. It cannot be a bitfield.
708 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
709}
710
711RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
712 // Unary plus just performs promotions on its arithmetic operand.
713 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000714 return EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000715}
716
717RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
718 // Unary minus performs promotions, then negates its arithmetic operand.
719 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000720 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattnerf0106d22007-06-02 19:33:17 +0000721
Chris Lattner8394d792007-06-05 20:53:16 +0000722 if (V.isScalar())
723 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
724
725 assert(0 && "FIXME: This doesn't handle complex operands yet");
726}
727
728RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
729 // Unary not performs promotions, then complements its integer operand.
730 QualType Ty;
Chris Lattnerb48238182007-06-15 21:04:38 +0000731 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
Chris Lattner8394d792007-06-05 20:53:16 +0000732
733 if (V.isScalar())
734 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
735
736 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
737}
738
739
740/// C99 6.5.3.3
741RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
742 // Compare operand to zero.
Chris Lattner23b7eb62007-06-15 23:05:46 +0000743 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
Chris Lattnerf0106d22007-06-02 19:33:17 +0000744
745 // Invert value.
Chris Lattnera45c5af2007-06-02 19:47:04 +0000746 // TODO: Could dynamically modify easy computations here. For example, if
747 // the operand is an icmp ne, turn into icmp eq.
Chris Lattnerf0106d22007-06-02 19:33:17 +0000748 BoolVal = Builder.CreateNot(BoolVal, "lnot");
749
750 // ZExt result to int.
Chris Lattner8394d792007-06-05 20:53:16 +0000751 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
Chris Lattnerf0106d22007-06-02 19:33:17 +0000752}
753
Chris Lattnere47e4402007-06-01 18:02:12 +0000754
Chris Lattnerdb91b162007-06-02 00:16:28 +0000755//===--------------------------------------------------------------------===//
756// Binary Operator Emission
757//===--------------------------------------------------------------------===//
758
759// FIXME describe.
Chris Lattnercf250242007-06-03 02:02:44 +0000760QualType CodeGenFunction::
Chris Lattner8394d792007-06-05 20:53:16 +0000761EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
762 RValue &RHS) {
Chris Lattnerc18f9d12007-06-02 22:51:30 +0000763 QualType LHSType, RHSType;
764 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
765 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
766
Chris Lattnercf250242007-06-03 02:02:44 +0000767 // If both operands have the same source type, we're done already.
768 if (LHSType == RHSType) return LHSType;
769
770 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
771 // The caller can deal with this (e.g. pointer + int).
772 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
773 return LHSType;
774
775 // At this point, we have two different arithmetic types.
776
777 // Handle complex types first (C99 6.3.1.8p1).
778 if (LHSType->isComplexType() || RHSType->isComplexType()) {
779 assert(0 && "FIXME: complex types unimp");
780#if 0
781 // if we have an integer operand, the result is the complex type.
782 if (rhs->isIntegerType())
783 return lhs;
784 if (lhs->isIntegerType())
785 return rhs;
786 return Context.maxComplexType(lhs, rhs);
787#endif
788 }
789
790 // If neither operand is complex, they must be scalars.
791 llvm::Value *LHSV = LHS.getVal();
792 llvm::Value *RHSV = RHS.getVal();
793
794 // If the LLVM types are already equal, then they only differed in sign, or it
795 // was something like char/signed char or double/long double.
796 if (LHSV->getType() == RHSV->getType())
797 return LHSType;
798
799 // Now handle "real" floating types (i.e. float, double, long double).
800 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
801 // if we have an integer operand, the result is the real floating type, and
802 // the integer converts to FP.
803 if (RHSType->isIntegerType()) {
804 // Promote the RHS to an FP type of the LHS, with the sign following the
805 // RHS.
806 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000807 RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000808 else
Chris Lattner8394d792007-06-05 20:53:16 +0000809 RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000810 return LHSType;
811 }
812
813 if (LHSType->isIntegerType()) {
814 // Promote the LHS to an FP type of the RHS, with the sign following the
815 // LHS.
816 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000817 LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000818 else
Chris Lattner8394d792007-06-05 20:53:16 +0000819 LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000820 return RHSType;
821 }
822
823 // Otherwise, they are two FP types. Promote the smaller operand to the
824 // bigger result.
825 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
826
827 if (BiggerType == LHSType)
Chris Lattner8394d792007-06-05 20:53:16 +0000828 RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000829 else
Chris Lattner8394d792007-06-05 20:53:16 +0000830 LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000831 return BiggerType;
832 }
833
834 // Finally, we have two integer types that are different according to C. Do
835 // a sign or zero extension if needed.
836
837 // Otherwise, one type is smaller than the other.
838 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
839
840 if (LHSType == ResTy) {
841 if (RHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000842 RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000843 else
Chris Lattner8394d792007-06-05 20:53:16 +0000844 RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000845 } else {
846 assert(RHSType == ResTy && "Unknown conversion");
847 if (LHSType->isSignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +0000848 LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000849 else
Chris Lattner8394d792007-06-05 20:53:16 +0000850 LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
Chris Lattnercf250242007-06-03 02:02:44 +0000851 }
852 return ResTy;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000853}
854
Chris Lattnercd215f02007-06-29 16:52:55 +0000855/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
856/// are strange in that the result of the operation is not the same type as the
857/// intermediate computation. This function emits the LHS and RHS operands of
858/// the compound assignment, promoting them to their common computation type.
859///
860/// Since the LHS is an lvalue, and the result is stored back through it, we
861/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
862/// RHS values are both in the computation type for the operator.
863void CodeGenFunction::
864EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
865 LValue &LHSLV, RValue &LHS, RValue &RHS) {
866 LHSLV = EmitLValue(E->getLHS());
867
868 // Load the LHS and RHS operands.
869 QualType LHSTy = E->getLHS()->getType();
870 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
871 QualType RHSTy;
872 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
873
Chris Lattner47c247e2007-06-29 17:26:27 +0000874 // Shift operands do the usual unary conversions, but do not do the binary
875 // conversions.
876 if (E->isShiftAssignOp()) {
877 // FIXME: This is broken. Implicit conversions should be made explicit,
878 // so that this goes away. This causes us to reload the LHS.
879 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy);
880 }
881
Chris Lattnercd215f02007-06-29 16:52:55 +0000882 // Convert the LHS and RHS to the common evaluation type.
883 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
884 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
885}
886
887/// EmitCompoundAssignmentResult - Given a result value in the computation type,
888/// truncate it down to the actual result type, store it through the LHS lvalue,
889/// and return it.
890RValue CodeGenFunction::
891EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
892 LValue LHSLV, RValue ResV) {
893
894 // Truncate back to the destination type.
895 if (E->getComputationType() != E->getType())
896 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
897
898 // Store the result value into the LHS.
899 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
900
901 // Return the result.
902 return ResV;
903}
904
Chris Lattnerdb91b162007-06-02 00:16:28 +0000905
Chris Lattner8394d792007-06-05 20:53:16 +0000906RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
Chris Lattnercd215f02007-06-29 16:52:55 +0000907 RValue LHS, RHS;
Chris Lattnerdb91b162007-06-02 00:16:28 +0000908 switch (E->getOpcode()) {
909 default:
Chris Lattnerb25a9432007-06-29 17:03:06 +0000910 fprintf(stderr, "Unimplemented binary expr!\n");
Chris Lattnerdb91b162007-06-02 00:16:28 +0000911 E->dump();
Chris Lattner23b7eb62007-06-15 23:05:46 +0000912 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattnerb25a9432007-06-29 17:03:06 +0000913 case BinaryOperator::Mul:
914 EmitUsualArithmeticConversions(E, LHS, RHS);
915 return EmitMul(LHS, RHS, E->getType());
916 case BinaryOperator::Div:
917 EmitUsualArithmeticConversions(E, LHS, RHS);
918 return EmitDiv(LHS, RHS, E->getType());
919 case BinaryOperator::Rem:
920 EmitUsualArithmeticConversions(E, LHS, RHS);
921 return EmitRem(LHS, RHS, E->getType());
Chris Lattnerd2b88ab2007-07-13 03:05:23 +0000922 case BinaryOperator::Add: {
923 QualType ExprTy = E->getType();
924 if (ExprTy->isPointerType()) {
925 Expr *LHSExpr = E->getLHS();
926 QualType LHSTy;
927 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
928 Expr *RHSExpr = E->getRHS();
929 QualType RHSTy;
930 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
931 return EmitPointerAdd(LHS, LHSTy, RHS, RHSTy, ExprTy);
932 } else {
933 EmitUsualArithmeticConversions(E, LHS, RHS);
934 return EmitAdd(LHS, RHS, ExprTy);
935 }
936 }
937 case BinaryOperator::Sub: {
938 QualType ExprTy = E->getType();
939 Expr *LHSExpr = E->getLHS();
940 if (LHSExpr->getType()->isPointerType()) {
941 QualType LHSTy;
942 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
943 Expr *RHSExpr = E->getRHS();
944 QualType RHSTy;
945 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
946 return EmitPointerSub(LHS, LHSTy, RHS, RHSTy, ExprTy);
947 } else {
948 EmitUsualArithmeticConversions(E, LHS, RHS);
949 return EmitSub(LHS, RHS, ExprTy);
950 }
951 }
Chris Lattner47c247e2007-06-29 17:26:27 +0000952 case BinaryOperator::Shl:
953 EmitShiftOperands(E, LHS, RHS);
954 return EmitShl(LHS, RHS, E->getType());
955 case BinaryOperator::Shr:
956 EmitShiftOperands(E, LHS, RHS);
957 return EmitShr(LHS, RHS, E->getType());
Chris Lattnerb25a9432007-06-29 17:03:06 +0000958 case BinaryOperator::And:
959 EmitUsualArithmeticConversions(E, LHS, RHS);
960 return EmitAnd(LHS, RHS, E->getType());
961 case BinaryOperator::Xor:
962 EmitUsualArithmeticConversions(E, LHS, RHS);
963 return EmitXor(LHS, RHS, E->getType());
964 case BinaryOperator::Or :
965 EmitUsualArithmeticConversions(E, LHS, RHS);
966 return EmitOr(LHS, RHS, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +0000967 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
968 case BinaryOperator::LOr: return EmitBinaryLOr(E);
Chris Lattner1fde0b32007-06-20 18:30:55 +0000969 case BinaryOperator::LT:
970 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
971 llvm::ICmpInst::ICMP_SLT,
972 llvm::FCmpInst::FCMP_OLT);
973 case BinaryOperator::GT:
974 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
975 llvm::ICmpInst::ICMP_SGT,
976 llvm::FCmpInst::FCMP_OGT);
977 case BinaryOperator::LE:
978 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
979 llvm::ICmpInst::ICMP_SLE,
980 llvm::FCmpInst::FCMP_OLE);
981 case BinaryOperator::GE:
982 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
983 llvm::ICmpInst::ICMP_SGE,
984 llvm::FCmpInst::FCMP_OGE);
985 case BinaryOperator::EQ:
986 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
987 llvm::ICmpInst::ICMP_EQ,
988 llvm::FCmpInst::FCMP_OEQ);
989 case BinaryOperator::NE:
990 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
991 llvm::ICmpInst::ICMP_NE,
992 llvm::FCmpInst::FCMP_UNE);
Chris Lattnercd215f02007-06-29 16:52:55 +0000993 case BinaryOperator::Assign:
994 return EmitBinaryAssign(E);
995
Chris Lattnerb25a9432007-06-29 17:03:06 +0000996 case BinaryOperator::MulAssign: {
997 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
998 LValue LHSLV;
999 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1000 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1001 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1002 }
1003 case BinaryOperator::DivAssign: {
1004 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1005 LValue LHSLV;
1006 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1007 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1008 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1009 }
1010 case BinaryOperator::RemAssign: {
1011 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1012 LValue LHSLV;
1013 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1014 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1015 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1016 }
Chris Lattnercd215f02007-06-29 16:52:55 +00001017 case BinaryOperator::AddAssign: {
1018 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1019 LValue LHSLV;
1020 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1021 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1022 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1023 }
1024 case BinaryOperator::SubAssign: {
1025 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1026 LValue LHSLV;
1027 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1028 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1029 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1030 }
Chris Lattner47c247e2007-06-29 17:26:27 +00001031 case BinaryOperator::ShlAssign: {
1032 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1033 LValue LHSLV;
1034 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1035 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1036 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1037 }
1038 case BinaryOperator::ShrAssign: {
1039 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1040 LValue LHSLV;
1041 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1042 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1043 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1044 }
Chris Lattnerb25a9432007-06-29 17:03:06 +00001045 case BinaryOperator::AndAssign: {
1046 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1047 LValue LHSLV;
1048 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1049 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1050 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1051 }
1052 case BinaryOperator::OrAssign: {
1053 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1054 LValue LHSLV;
1055 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1056 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1057 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1058 }
1059 case BinaryOperator::XorAssign: {
1060 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1061 LValue LHSLV;
1062 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1063 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1064 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1065 }
Chris Lattner8394d792007-06-05 20:53:16 +00001066 case BinaryOperator::Comma: return EmitBinaryComma(E);
Chris Lattnerdb91b162007-06-02 00:16:28 +00001067 }
1068}
1069
Chris Lattnerb25a9432007-06-29 17:03:06 +00001070RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001071 if (LHS.isScalar())
1072 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1073
Gabor Greifd4606aa2007-07-13 23:33:18 +00001074 // Otherwise, this must be a complex number.
1075 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1076
1077 EmitLoadOfComplex(LHS, LHSR, LHSI);
1078 EmitLoadOfComplex(RHS, RHSR, RHSI);
1079
1080 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1081 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1082 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1083
1084 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1085 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1086 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1087
1088 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1089 EmitStoreOfComplex(ResR, ResI, Res);
1090 return RValue::getAggregate(Res);
Chris Lattner8394d792007-06-05 20:53:16 +00001091}
1092
Chris Lattnerb25a9432007-06-29 17:03:06 +00001093RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001094 if (LHS.isScalar()) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001095 llvm::Value *RV;
Chris Lattner8394d792007-06-05 20:53:16 +00001096 if (LHS.getVal()->getType()->isFloatingPoint())
1097 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
Chris Lattnerb25a9432007-06-29 17:03:06 +00001098 else if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001099 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1100 else
1101 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1102 return RValue::get(RV);
1103 }
1104 assert(0 && "FIXME: This doesn't handle complex operands yet");
1105}
1106
Chris Lattnerb25a9432007-06-29 17:03:06 +00001107RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001108 if (LHS.isScalar()) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001109 llvm::Value *RV;
Chris Lattner8394d792007-06-05 20:53:16 +00001110 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattnerb25a9432007-06-29 17:03:06 +00001111 if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001112 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1113 else
1114 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1115 return RValue::get(RV);
1116 }
1117
1118 assert(0 && "FIXME: This doesn't handle complex operands yet");
1119}
1120
Chris Lattnercd215f02007-06-29 16:52:55 +00001121RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001122 if (LHS.isScalar())
1123 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
Chris Lattnercd215f02007-06-29 16:52:55 +00001124
Chris Lattnere9a64532007-06-22 21:44:33 +00001125 // Otherwise, this must be a complex number.
1126 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1127
1128 EmitLoadOfComplex(LHS, LHSR, LHSI);
1129 EmitLoadOfComplex(RHS, RHSR, RHSI);
1130
1131 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1132 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1133
Chris Lattnercd215f02007-06-29 16:52:55 +00001134 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
Chris Lattnere9a64532007-06-22 21:44:33 +00001135 EmitStoreOfComplex(ResR, ResI, Res);
1136 return RValue::getAggregate(Res);
Chris Lattner8394d792007-06-05 20:53:16 +00001137}
1138
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001139RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1140 RValue RHS, QualType RHSTy,
1141 QualType ResTy) {
1142 llvm::Value *LHSValue = LHS.getVal();
1143 llvm::Value *RHSValue = RHS.getVal();
1144 if (LHSTy->isPointerType()) {
1145 // pointer + int
1146 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1147 } else {
1148 // int + pointer
1149 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1150 }
1151}
1152
Chris Lattnercd215f02007-06-29 16:52:55 +00001153RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001154 if (LHS.isScalar())
1155 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1156
1157 assert(0 && "FIXME: This doesn't handle complex operands yet");
Chris Lattner8394d792007-06-05 20:53:16 +00001158}
1159
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001160RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1161 RValue RHS, QualType RHSTy,
1162 QualType ResTy) {
1163 llvm::Value *LHSValue = LHS.getVal();
1164 llvm::Value *RHSValue = RHS.getVal();
1165 if (const PointerType *RHSPtrType =
1166 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1167 // pointer - pointer
1168 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1169 QualType LHSElementType = LHSPtrType->getPointeeType();
1170 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1171 "can't subtract pointers with differing element types");
Chris Lattner651f0e92007-07-16 05:43:05 +00001172 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
Chris Lattner4481b422007-07-14 01:29:45 +00001173 SourceLocation()) / 8;
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001174 const llvm::Type *ResultType = ConvertType(ResTy);
1175 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1176 "sub.ptr.lhs.cast");
1177 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1178 "sub.ptr.rhs.cast");
1179 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1180 "sub.ptr.sub");
Chris Lattner651f0e92007-07-16 05:43:05 +00001181
1182 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1183 // remainder. As such, we handle common power-of-two cases here to generate
1184 // better code.
1185 if (llvm::isPowerOf2_64(ElementSize)) {
1186 llvm::Value *ShAmt =
1187 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1188 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1189 } else {
1190 // Otherwise, do a full sdiv.
1191 llvm::Value *BytesPerElement =
1192 llvm::ConstantInt::get(ResultType, ElementSize);
1193 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1194 "sub.ptr.div"));
1195 }
Chris Lattnerd2b88ab2007-07-13 03:05:23 +00001196 } else {
1197 // pointer - int
1198 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1199 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1200 }
1201}
1202
Chris Lattner47c247e2007-06-29 17:26:27 +00001203void CodeGenFunction::EmitShiftOperands(const BinaryOperator *E,
1204 RValue &LHS, RValue &RHS) {
Chris Lattner8394d792007-06-05 20:53:16 +00001205 // For shifts, integer promotions are performed, but the usual arithmetic
1206 // conversions are not. The LHS and RHS need not have the same type.
Chris Lattner8394d792007-06-05 20:53:16 +00001207 QualType ResTy;
Chris Lattner47c247e2007-06-29 17:26:27 +00001208 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy);
1209 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy);
1210}
Chris Lattner8394d792007-06-05 20:53:16 +00001211
Chris Lattner47c247e2007-06-29 17:26:27 +00001212
1213RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1214 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1215
Chris Lattner8394d792007-06-05 20:53:16 +00001216 // 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
1221 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1222}
1223
Chris Lattner47c247e2007-06-29 17:26:27 +00001224RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1225 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
Chris Lattner8394d792007-06-05 20:53:16 +00001226
1227 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1228 // RHS to the same size as the LHS.
1229 if (LHS->getType() != RHS->getType())
1230 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1231
Chris Lattner47c247e2007-06-29 17:26:27 +00001232 if (ResTy->isUnsignedIntegerType())
Chris Lattner8394d792007-06-05 20:53:16 +00001233 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1234 else
1235 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1236}
1237
Chris Lattner1fde0b32007-06-20 18:30:55 +00001238RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1239 unsigned UICmpOpc, unsigned SICmpOpc,
1240 unsigned FCmpOpc) {
Chris Lattner273c63d2007-06-20 18:02:30 +00001241 RValue LHS, RHS;
1242 EmitUsualArithmeticConversions(E, LHS, RHS);
1243
1244 llvm::Value *Result;
1245 if (LHS.isScalar()) {
1246 if (LHS.getVal()->getType()->isFloatingPoint()) {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001247 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1248 LHS.getVal(), RHS.getVal(), "cmp");
1249 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1250 // FIXME: This check isn't right for "unsigned short < int" where ushort
1251 // promotes to int and does a signed compare.
1252 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1253 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001254 } else {
Chris Lattner1fde0b32007-06-20 18:30:55 +00001255 // Signed integers and pointers.
1256 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1257 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner273c63d2007-06-20 18:02:30 +00001258 }
1259 } else {
1260 // Struct/union/complex
Gabor Greifd4606aa2007-07-13 23:33:18 +00001261 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1262 EmitLoadOfComplex(LHS, LHSR, LHSI);
1263 EmitLoadOfComplex(RHS, RHSR, RHSI);
1264
Gabor Greife97cd7e2007-07-14 20:05:18 +00001265 // FIXME: need to consider _Complex over integers too!
1266
Gabor Greifd4606aa2007-07-13 23:33:18 +00001267 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1268 LHSR, RHSR, "cmp.r");
1269 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1270 LHSI, RHSI, "cmp.i");
1271 if (BinaryOperator::EQ == E->getOpcode()) {
1272 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1273 } else if (BinaryOperator::NE == E->getOpcode()) {
1274 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1275 } else {
1276 assert(0 && "Complex comparison other than == or != ?");
1277 }
Chris Lattner273c63d2007-06-20 18:02:30 +00001278 }
Gabor Greifd4606aa2007-07-13 23:33:18 +00001279
Chris Lattner273c63d2007-06-20 18:02:30 +00001280 // ZExt result to int.
1281 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1282}
1283
Chris Lattnerb25a9432007-06-29 17:03:06 +00001284RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001285 if (LHS.isScalar())
1286 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1287
1288 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1289}
1290
Chris Lattnerb25a9432007-06-29 17:03:06 +00001291RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001292 if (LHS.isScalar())
1293 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1294
1295 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1296}
1297
Chris Lattnerb25a9432007-06-29 17:03:06 +00001298RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner8394d792007-06-05 20:53:16 +00001299 if (LHS.isScalar())
1300 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1301
1302 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1303}
1304
1305RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001306 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001307
Chris Lattner23b7eb62007-06-15 23:05:46 +00001308 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1309 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001310
Chris Lattner23b7eb62007-06-15 23:05:46 +00001311 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001312 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1313
1314 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001315 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001316
1317 // Reaquire the RHS block, as there may be subblocks inserted.
1318 RHSBlock = Builder.GetInsertBlock();
1319 EmitBlock(ContBlock);
1320
1321 // Create a PHI node. If we just evaluted the LHS condition, the result is
1322 // false. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001323 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
Chris Lattner8394d792007-06-05 20:53:16 +00001324 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001325 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001326 PN->addIncoming(RHSCond, RHSBlock);
1327
1328 // ZExt result to int.
1329 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1330}
1331
1332RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
Chris Lattner23b7eb62007-06-15 23:05:46 +00001333 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001334
Chris Lattner23b7eb62007-06-15 23:05:46 +00001335 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1336 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
Chris Lattner8394d792007-06-05 20:53:16 +00001337
Chris Lattner23b7eb62007-06-15 23:05:46 +00001338 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
Chris Lattner8394d792007-06-05 20:53:16 +00001339 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1340
1341 EmitBlock(RHSBlock);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001342 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
Chris Lattner8394d792007-06-05 20:53:16 +00001343
1344 // Reaquire the RHS block, as there may be subblocks inserted.
1345 RHSBlock = Builder.GetInsertBlock();
1346 EmitBlock(ContBlock);
1347
1348 // Create a PHI node. If we just evaluted the LHS condition, the result is
1349 // true. If we evaluated both, the result is the RHS condition.
Chris Lattner23b7eb62007-06-15 23:05:46 +00001350 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
Chris Lattner8394d792007-06-05 20:53:16 +00001351 PN->reserveOperandSpace(2);
Chris Lattner23b7eb62007-06-15 23:05:46 +00001352 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
Chris Lattner8394d792007-06-05 20:53:16 +00001353 PN->addIncoming(RHSCond, RHSBlock);
1354
1355 // ZExt result to int.
1356 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1357}
1358
1359RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
1360 LValue LHS = EmitLValue(E->getLHS());
1361
1362 QualType RHSTy;
1363 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
1364
1365 // Convert the RHS to the type of the LHS.
Chris Lattnerf033c142007-06-22 19:05:19 +00001366 RHS = EmitConversion(RHS, RHSTy, E->getType());
Chris Lattner8394d792007-06-05 20:53:16 +00001367
1368 // Store the value into the LHS.
1369 EmitStoreThroughLValue(RHS, LHS, E->getType());
1370
1371 // Return the converted RHS.
1372 return RHS;
1373}
1374
Chris Lattner9369a562007-06-29 16:31:29 +00001375
Chris Lattner8394d792007-06-05 20:53:16 +00001376RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1377 EmitExpr(E->getLHS());
1378 return EmitExpr(E->getRHS());
1379}
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001380
1381RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1382 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1383 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1384 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1385
1386 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1387 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1388
Chris Lattner027f21d2007-07-14 00:01:01 +00001389 // FIXME: Implement this for aggregate values.
1390
Chris Lattner6e9d9b32007-07-13 05:18:11 +00001391 // FIXME: LHS & RHS need the "usual arithmetic conversions" but
1392 // that's not possible with the current design.
1393
1394 EmitBlock(LHSBlock);
1395 QualType LHSTy;
1396 llvm::Value *LHSValue = E->getLHS() ? // GNU extension
1397 EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy).getVal() :
1398 Cond;
1399 Builder.CreateBr(ContBlock);
1400 LHSBlock = Builder.GetInsertBlock();
1401
1402 EmitBlock(RHSBlock);
1403 QualType RHSTy;
1404 llvm::Value *RHSValue =
1405 EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy).getVal();
1406 Builder.CreateBr(ContBlock);
1407 RHSBlock = Builder.GetInsertBlock();
1408
1409 const llvm::Type *LHSType = LHSValue->getType();
1410 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1411
1412 EmitBlock(ContBlock);
1413 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1414 PN->reserveOperandSpace(2);
1415 PN->addIncoming(LHSValue, LHSBlock);
1416 PN->addIncoming(RHSValue, RHSBlock);
1417
1418 return RValue::get(PN);
1419}