blob: dad4b86a46f154a600e013d5a45436e62200b35f [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- CGExpr.cpp - Emit LLVM Code from Expressions ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file was developed by Chris Lattner and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
15#include "CodeGenModule.h"
16#include "clang/AST/AST.h"
17#include "llvm/Constants.h"
18#include "llvm/DerivedTypes.h"
19#include "llvm/Function.h"
20#include "llvm/GlobalVariable.h"
21#include "llvm/Support/MathExtras.h"
22using namespace clang;
23using namespace CodeGen;
24
25//===--------------------------------------------------------------------===//
26// Miscellaneous Helper Methods
27//===--------------------------------------------------------------------===//
28
29/// 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}
35
36/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
37/// expression and compare the result against zero, returning an Int1Ty value.
38llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
39 QualType Ty;
40 RValue Val = EmitExprWithUsualUnaryConversions(E, Ty);
41 return ConvertScalarValueToBool(Val, Ty);
42}
43
44/// 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
74//===--------------------------------------------------------------------===//
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,
81 QualType DstTy) {
82 ValTy = ValTy.getCanonicalType();
83 DstTy = DstTy.getCanonicalType();
84 if (ValTy == DstTy) return Val;
85
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));
90
91 // Handle pointer conversions next: pointers can only be converted to/from
92 // other pointers and integers.
93 if (isa<PointerType>(DstTy)) {
94 const llvm::Type *DestTy = ConvertType(DstTy);
95
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?");
101 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
102 }
103
104 if (isa<PointerType>(ValTy)) {
105 // Must be an ptr to int cast.
106 const llvm::Type *DestTy = ConvertType(DstTy);
107 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
108 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
109 }
110
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.
117 llvm::Value *SrcVal = Val.getVal();
118 const llvm::Type *DestTy = ConvertType(DstTy);
119 if (SrcVal->getType() == DestTy) return Val;
120
121 llvm::Value *Result;
122 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!");
149}
150
151
152/// ConvertScalarValueToBool - Convert the specified expression value to a
153/// boolean (i1) truth value. This is equivalent to "Val == 0".
154llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
155 Ty = Ty.getCanonicalType();
156 llvm::Value *Result;
157 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;
166 case BuiltinType::Char_S:
167 case BuiltinType::Char_U:
168 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();
185 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
186 // FIXME: llvm-gcc produces a une comparison: validate this is right.
187 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
188 return Result;
189 }
190 }
191 } else if (isa<PointerType>(Ty) ||
192 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
193 // Code below handles this fine.
194 } else {
195 assert(isa<ComplexType>(Ty) && "Unknwon type!");
196 assert(0 && "FIXME: comparisons against complex not implemented yet");
197 }
198
199 // Usual case for integers, pointers, and enums: compare against zero.
200 Result = Val.getVal();
201
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.
205 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
206 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
207 Result = ZI->getOperand(0);
208 ZI->eraseFromParent();
209 return Result;
210 }
211 }
212
213 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
214 return Builder.CreateICmpNE(Result, Zero, "tobool");
215}
216
217//===----------------------------------------------------------------------===//
218// LValue Expression Emission
219//===----------------------------------------------------------------------===//
220
221/// 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///
237LValue CodeGenFunction::EmitLValue(const Expr *E) {
238 switch (E->getStmtClass()) {
239 default:
240 fprintf(stderr, "Unimplemented lvalue expr!\n");
241 E->dump();
242 return LValue::MakeAddr(llvm::UndefValue::get(
243 llvm::PointerType::get(llvm::Type::Int32Ty)));
244
245 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
246 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
247 case Expr::PreDefinedExprClass:
248 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
249 case Expr::StringLiteralClass:
250 return EmitStringLiteralLValue(cast<StringLiteral>(E));
251
252 case Expr::UnaryOperatorClass:
253 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
254 case Expr::ArraySubscriptExprClass:
255 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattner65520192007-08-02 23:37:31 +0000256 case Expr::OCUVectorComponentClass:
257 return EmitOCUVectorComponentExpr(cast<OCUVectorComponent>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000258 }
259}
260
261/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
262/// this method emits the address of the lvalue, then loads the result as an
263/// rvalue, returning the rvalue.
264RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
265 ExprType = ExprType.getCanonicalType();
266
267 if (LV.isSimple()) {
268 llvm::Value *Ptr = LV.getAddress();
269 const llvm::Type *EltTy =
270 cast<llvm::PointerType>(Ptr->getType())->getElementType();
271
272 // Simple scalar l-value.
273 if (EltTy->isFirstClassType())
274 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
275
276 // Otherwise, we have an aggregate lvalue.
277 return RValue::getAggregate(Ptr);
278 }
279
280 if (LV.isVectorElt()) {
281 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
282 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
283 "vecext"));
284 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000285
286 // If this is a reference to a subset of the elements of a vector, either
287 // shuffle the input or extract/insert them as appropriate.
288 if (LV.isOCUVectorComp()) {
289 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
Chris Lattner4759d342007-08-03 15:52:31 +0000290
291 unsigned EncFields = LV.getOCUVectorComp();
292
293 // If the result of the expression is a non-vector type, we must be
294 // extracting a single element. Just codegen as an extractelement.
295 if (!isa<VectorType>(ExprType)) {
296 unsigned InIdx = OCUVectorComponent::getAccessedFieldNo(0, EncFields);
297 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
298 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
299 }
300
Chris Lattner2ef10ab2007-08-03 16:09:33 +0000301 // If the source and destination have the same number of elements, use a
302 // vector shuffle instead of insert/extracts.
303 unsigned NumResultElts = cast<VectorType>(ExprType)->getNumElements();
304 unsigned NumSourceElts =
305 cast<llvm::VectorType>(Vec->getType())->getNumElements();
Chris Lattner4759d342007-08-03 15:52:31 +0000306
Chris Lattner2ef10ab2007-08-03 16:09:33 +0000307 if (NumResultElts == NumSourceElts) {
308 llvm::SmallVector<llvm::Constant*, 4> Mask;
309 for (unsigned i = 0; i != NumResultElts; ++i) {
310 unsigned InIdx = OCUVectorComponent::getAccessedFieldNo(i, EncFields);
311 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
312 }
313
314 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
315 Vec = Builder.CreateShuffleVector(Vec,
316 llvm::UndefValue::get(Vec->getType()),
317 MaskV, "tmp");
318 return RValue::get(Vec);
319 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000320
321 // Start out with an undef of the result type.
322 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
323
Chris Lattnera735fac2007-08-03 00:16:29 +0000324 // Extract/Insert each element of the result.
Chris Lattner2ef10ab2007-08-03 16:09:33 +0000325 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera735fac2007-08-03 00:16:29 +0000326 unsigned InIdx = OCUVectorComponent::getAccessedFieldNo(i, EncFields);
327 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
328 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
329
330 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
331 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
332 }
333
334 return RValue::get(Result);
335 }
Chris Lattner4b009652007-07-25 00:24:17 +0000336
337 assert(0 && "Bitfield ref not impl!");
338}
339
340RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
341 return EmitLoadOfLValue(EmitLValue(E), E->getType());
342}
343
344
345/// EmitStoreThroughLValue - Store the specified rvalue into the specified
346/// lvalue, where both are guaranteed to the have the same type, and that type
347/// is 'Ty'.
348void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
349 QualType Ty) {
350 if (Dst.isVectorElt()) {
351 // Read/modify/write the vector, inserting the new element.
352 // FIXME: Volatility.
353 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
354 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
355 Dst.getVectorIdx(), "vecins");
356 Builder.CreateStore(Vec, Dst.getVectorAddr());
357 return;
358 }
359
360 assert(Dst.isSimple() && "FIXME: Don't support store to bitfield yet");
361
362 llvm::Value *DstAddr = Dst.getAddress();
363 if (Src.isScalar()) {
364 // FIXME: Handle volatility etc.
365 const llvm::Type *SrcTy = Src.getVal()->getType();
366 const llvm::Type *AddrTy =
367 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
368
369 if (AddrTy != SrcTy)
370 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
371 "storetmp");
372 Builder.CreateStore(Src.getVal(), DstAddr);
373 return;
374 }
375
376 // Don't use memcpy for complex numbers.
377 if (Ty->isComplexType()) {
378 llvm::Value *Real, *Imag;
379 EmitLoadOfComplex(Src, Real, Imag);
380 EmitStoreOfComplex(Real, Imag, Dst.getAddress());
381 return;
382 }
383
384 // Aggregate assignment turns into llvm.memcpy.
385 const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
386 llvm::Value *SrcAddr = Src.getAggregateAddr();
387
388 if (DstAddr->getType() != SBP)
389 DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
390 if (SrcAddr->getType() != SBP)
391 SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
392
393 unsigned Align = 1; // FIXME: Compute type alignments.
394 unsigned Size = 1234; // FIXME: Compute type sizes.
395
396 // FIXME: Handle variable sized types.
397 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
398 llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
399
400 llvm::Value *MemCpyOps[4] = {
401 DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
402 };
403
Chris Lattnera9572252007-08-01 06:24:52 +0000404 Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, MemCpyOps+4);
Chris Lattner4b009652007-07-25 00:24:17 +0000405}
406
407
408LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
409 const Decl *D = E->getDecl();
410 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
411 llvm::Value *V = LocalDeclMap[D];
412 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
413 return LValue::MakeAddr(V);
414 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
415 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
416 }
417 assert(0 && "Unimp declref");
418}
419
420LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
421 // __extension__ doesn't affect lvalue-ness.
422 if (E->getOpcode() == UnaryOperator::Extension)
423 return EmitLValue(E->getSubExpr());
424
425 assert(E->getOpcode() == UnaryOperator::Deref &&
426 "'*' is the only unary operator that produces an lvalue");
427 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
428}
429
430LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
431 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
432 const char *StrData = E->getStrData();
433 unsigned Len = E->getByteLength();
434
435 // FIXME: Can cache/reuse these within the module.
436 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
437
438 // Create a global variable for this.
439 C = new llvm::GlobalVariable(C->getType(), true,
440 llvm::GlobalValue::InternalLinkage,
441 C, ".str", CurFn->getParent());
442 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
443 llvm::Constant *Zeros[] = { Zero, Zero };
444 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
445 return LValue::MakeAddr(C);
446}
447
448LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
449 std::string FunctionName(CurFuncDecl->getName());
450 std::string GlobalVarName;
451
452 switch (E->getIdentType()) {
453 default:
454 assert(0 && "unknown pre-defined ident type");
455 case PreDefinedExpr::Func:
456 GlobalVarName = "__func__.";
457 break;
458 case PreDefinedExpr::Function:
459 GlobalVarName = "__FUNCTION__.";
460 break;
461 case PreDefinedExpr::PrettyFunction:
462 // FIXME:: Demangle C++ method names
463 GlobalVarName = "__PRETTY_FUNCTION__.";
464 break;
465 }
466
467 GlobalVarName += CurFuncDecl->getName();
468
469 // FIXME: Can cache/reuse these within the module.
470 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
471
472 // Create a global variable for this.
473 C = new llvm::GlobalVariable(C->getType(), true,
474 llvm::GlobalValue::InternalLinkage,
475 C, GlobalVarName, CurFn->getParent());
476 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
477 llvm::Constant *Zeros[] = { Zero, Zero };
478 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
479 return LValue::MakeAddr(C);
480}
481
482LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
483 // The index must always be a pointer or integer, neither of which is an
484 // aggregate. Emit it.
485 QualType IdxTy;
486 llvm::Value *Idx =
487 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
488
489 // If the base is a vector type, then we are forming a vector element lvalue
490 // with this subscript.
491 if (E->getBase()->getType()->isVectorType()) {
492 // Emit the vector as an lvalue to get its address.
493 LValue Base = EmitLValue(E->getBase());
494 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
495 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
496 return LValue::MakeVectorElt(Base.getAddress(), Idx);
497 }
498
499 // At this point, the base must be a pointer or integer, neither of which are
500 // aggregates. Emit it.
501 QualType BaseTy;
502 llvm::Value *Base =
503 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
504
505 // Usually the base is the pointer type, but sometimes it is the index.
506 // Canonicalize to have the pointer as the base.
507 if (isa<llvm::PointerType>(Idx->getType())) {
508 std::swap(Base, Idx);
509 std::swap(BaseTy, IdxTy);
510 }
511
512 // The pointer is now the base. Extend or truncate the index type to 32 or
513 // 64-bits.
514 bool IdxSigned = IdxTy->isSignedIntegerType();
515 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
516 if (IdxBitwidth != LLVMPointerWidth)
517 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
518 IdxSigned, "idxprom");
519
520 // We know that the pointer points to a type of the correct size, unless the
521 // size is a VLA.
522 if (!E->getType()->isConstantSizeType(getContext()))
523 assert(0 && "VLA idx not implemented");
524 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
525}
526
Chris Lattner65520192007-08-02 23:37:31 +0000527LValue CodeGenFunction::
528EmitOCUVectorComponentExpr(const OCUVectorComponent *E) {
529 // Emit the base vector as an l-value.
530 LValue Base = EmitLValue(E->getBase());
531 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
532
533 return LValue::MakeOCUVectorComp(Base.getAddress(),
534 E->getEncodedElementAccess());
535}
536
Chris Lattner4b009652007-07-25 00:24:17 +0000537//===--------------------------------------------------------------------===//
538// Expression Emission
539//===--------------------------------------------------------------------===//
540
541RValue CodeGenFunction::EmitExpr(const Expr *E) {
542 assert(E && "Null expression?");
543
544 switch (E->getStmtClass()) {
545 default:
546 fprintf(stderr, "Unimplemented expr!\n");
547 E->dump();
548 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
549
550 // l-values.
551 case Expr::DeclRefExprClass:
552 // DeclRef's of EnumConstantDecl's are simple rvalues.
553 if (const EnumConstantDecl *EC =
554 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
555 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
556 return EmitLoadOfLValue(E);
557 case Expr::ArraySubscriptExprClass:
558 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Chris Lattnera735fac2007-08-03 00:16:29 +0000559 case Expr::OCUVectorComponentClass:
560 return EmitLoadOfLValue(E);
Chris Lattner4b009652007-07-25 00:24:17 +0000561 case Expr::PreDefinedExprClass:
562 case Expr::StringLiteralClass:
563 return RValue::get(EmitLValue(E).getAddress());
564
565 // Leaf expressions.
566 case Expr::IntegerLiteralClass:
567 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
568 case Expr::FloatingLiteralClass:
569 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
570 case Expr::CharacterLiteralClass:
571 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
572
573 // Operators.
574 case Expr::ParenExprClass:
575 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
576 case Expr::UnaryOperatorClass:
577 return EmitUnaryOperator(cast<UnaryOperator>(E));
578 case Expr::SizeOfAlignOfTypeExprClass:
579 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
580 E->getType(),
581 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
582 case Expr::ImplicitCastExprClass:
583 return EmitCastExpr(cast<ImplicitCastExpr>(E)->getSubExpr(), E->getType());
584 case Expr::CastExprClass:
585 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
586 case Expr::CallExprClass:
587 return EmitCallExpr(cast<CallExpr>(E));
588 case Expr::BinaryOperatorClass:
589 return EmitBinaryOperator(cast<BinaryOperator>(E));
590
591 case Expr::ConditionalOperatorClass:
592 return EmitConditionalOperator(cast<ConditionalOperator>(E));
593 }
594
595}
596
597RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
598 return RValue::get(llvm::ConstantInt::get(E->getValue()));
599}
600RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
601 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
602 E->getValue()));
603}
604RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
605 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
606 E->getValue()));
607}
608
609RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
610 // Emit subscript expressions in rvalue context's. For most cases, this just
611 // loads the lvalue formed by the subscript expr. However, we have to be
612 // careful, because the base of a vector subscript is occasionally an rvalue,
613 // so we can't get it as an lvalue.
614 if (!E->getBase()->getType()->isVectorType())
615 return EmitLoadOfLValue(E);
616
617 // Handle the vector case. The base must be a vector, the index must be an
618 // integer value.
619 QualType BaseTy, IdxTy;
620 llvm::Value *Base =
621 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
622 llvm::Value *Idx =
623 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
624
625 // FIXME: Convert Idx to i32 type.
626
627 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
628}
629
630// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
631// have to handle a more broad range of conversions than explicit casts, as they
632// handle things like function to ptr-to-function decay etc.
633RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
634 QualType SrcTy;
635 RValue Src = EmitExprWithUsualUnaryConversions(Op, SrcTy);
636
637 // If the destination is void, just evaluate the source.
638 if (DestTy->isVoidType())
639 return RValue::getAggregate(0);
640
641 return EmitConversion(Src, SrcTy, DestTy);
642}
643
644RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
645 QualType CalleeTy;
646 llvm::Value *Callee =
647 EmitExprWithUsualUnaryConversions(E->getCallee(), CalleeTy).getVal();
648
649 // The callee type will always be a pointer to function type, get the function
650 // type.
651 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
652
653 // Get information about the argument types.
654 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
655
656 // Calling unprototyped functions provides no argument info.
657 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
658 ArgTyIt = FTP->arg_type_begin();
659 ArgTyEnd = FTP->arg_type_end();
660 }
661
662 llvm::SmallVector<llvm::Value*, 16> Args;
663
664 // FIXME: Handle struct return.
665 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
666 QualType ArgTy;
667 RValue ArgVal = EmitExprWithUsualUnaryConversions(E->getArg(i), ArgTy);
668
669 // If this argument has prototype information, convert it.
670 if (ArgTyIt != ArgTyEnd) {
671 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
672 } else {
673 // Otherwise, if passing through "..." or to a function with no prototype,
674 // perform the "default argument promotions" (C99 6.5.2.2p6), which
675 // includes the usual unary conversions, but also promotes float to
676 // double.
677 if (const BuiltinType *BT =
678 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
679 if (BT->getKind() == BuiltinType::Float)
680 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
681 llvm::Type::DoubleTy,"tmp"));
682 }
683 }
684
685
686 if (ArgVal.isScalar())
687 Args.push_back(ArgVal.getVal());
688 else // Pass by-address. FIXME: Set attribute bit on call.
689 Args.push_back(ArgVal.getAggregateAddr());
690 }
691
Chris Lattnera9572252007-08-01 06:24:52 +0000692 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000693 if (V->getType() != llvm::Type::VoidTy)
694 V->setName("call");
695
696 // FIXME: Struct return;
697 return RValue::get(V);
698}
699
700
701//===----------------------------------------------------------------------===//
702// Unary Operator Emission
703//===----------------------------------------------------------------------===//
704
705RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
706 QualType &ResTy) {
707 ResTy = E->getType().getCanonicalType();
708
709 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
710 // Functions are promoted to their address.
711 ResTy = getContext().getPointerType(ResTy);
712 return RValue::get(EmitLValue(E).getAddress());
713 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
714 // C99 6.3.2.1p3
715 ResTy = getContext().getPointerType(ary->getElementType());
716
717 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
718 // will not true when we add support for VLAs.
719 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
720
721 assert(isa<llvm::PointerType>(V->getType()) &&
722 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
723 ->getElementType()) &&
724 "Doesn't support VLAs yet!");
725 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
726 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
727 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
728 // FIXME: this probably isn't right, pending clarification from Steve.
729 llvm::Value *Val = EmitExpr(E).getVal();
730
731 // If the input is a signed integer, sign extend to the destination.
732 if (ResTy->isSignedIntegerType()) {
733 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
734 } else {
735 // This handles unsigned types, including bool.
736 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
737 }
738 ResTy = getContext().IntTy;
739
740 return RValue::get(Val);
741 }
742
743 // Otherwise, this is a float, double, int, struct, etc.
744 return EmitExpr(E);
745}
746
747
748RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
749 switch (E->getOpcode()) {
750 default:
751 printf("Unimplemented unary expr!\n");
752 E->dump();
753 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
754 case UnaryOperator::PostInc:
755 case UnaryOperator::PostDec:
756 case UnaryOperator::PreInc :
757 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
758 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
759 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
760 case UnaryOperator::Plus : return EmitUnaryPlus(E);
761 case UnaryOperator::Minus : return EmitUnaryMinus(E);
762 case UnaryOperator::Not : return EmitUnaryNot(E);
763 case UnaryOperator::LNot : return EmitUnaryLNot(E);
764 case UnaryOperator::SizeOf :
765 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
766 case UnaryOperator::AlignOf :
767 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
768 // FIXME: real/imag
769 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
770 }
771}
772
773RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
774 LValue LV = EmitLValue(E->getSubExpr());
775 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
776
777 // We know the operand is real or pointer type, so it must be an LLVM scalar.
778 assert(InVal.isScalar() && "Unknown thing to increment");
779 llvm::Value *InV = InVal.getVal();
780
781 int AmountVal = 1;
782 if (E->getOpcode() == UnaryOperator::PreDec ||
783 E->getOpcode() == UnaryOperator::PostDec)
784 AmountVal = -1;
785
786 llvm::Value *NextVal;
787 if (isa<llvm::IntegerType>(InV->getType())) {
788 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
789 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
790 } else if (InV->getType()->isFloatingPoint()) {
791 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
792 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
793 } else {
794 // FIXME: This is not right for pointers to VLA types.
795 assert(isa<llvm::PointerType>(InV->getType()));
796 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
797 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
798 }
799
800 RValue NextValToStore = RValue::get(NextVal);
801
802 // Store the updated result through the lvalue.
803 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
804
805 // If this is a postinc, return the value read from memory, otherwise use the
806 // updated value.
807 if (E->getOpcode() == UnaryOperator::PreDec ||
808 E->getOpcode() == UnaryOperator::PreInc)
809 return NextValToStore;
810 else
811 return InVal;
812}
813
814/// C99 6.5.3.2
815RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
816 // The address of the operand is just its lvalue. It cannot be a bitfield.
817 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
818}
819
820RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
821 // Unary plus just performs promotions on its arithmetic operand.
822 QualType Ty;
823 return EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
824}
825
826RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
827 // Unary minus performs promotions, then negates its arithmetic operand.
828 QualType Ty;
829 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
830
831 if (V.isScalar())
832 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
833
834 assert(0 && "FIXME: This doesn't handle complex operands yet");
835}
836
837RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
838 // Unary not performs promotions, then complements its integer operand.
839 QualType Ty;
840 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
841
842 if (V.isScalar())
843 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
844
845 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
846}
847
848
849/// C99 6.5.3.3
850RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
851 // Compare operand to zero.
852 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
853
854 // Invert value.
855 // TODO: Could dynamically modify easy computations here. For example, if
856 // the operand is an icmp ne, turn into icmp eq.
857 BoolVal = Builder.CreateNot(BoolVal, "lnot");
858
859 // ZExt result to int.
860 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
861}
862
863/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
864/// an integer (RetType).
865RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
866 QualType RetType, bool isSizeOf) {
867 /// FIXME: This doesn't handle VLAs yet!
868 std::pair<uint64_t, unsigned> Info =
869 getContext().getTypeInfo(TypeToSize, SourceLocation());
870
871 uint64_t Val = isSizeOf ? Info.first : Info.second;
872 Val /= 8; // Return size in bytes, not bits.
873
874 assert(RetType->isIntegerType() && "Result type must be an integer!");
875
876 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
877 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
878}
879
880
881//===--------------------------------------------------------------------===//
882// Binary Operator Emission
883//===--------------------------------------------------------------------===//
884
885// FIXME describe.
886QualType CodeGenFunction::
887EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
888 RValue &RHS) {
889 QualType LHSType, RHSType;
890 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
891 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
892
893 // If both operands have the same source type, we're done already.
894 if (LHSType == RHSType) return LHSType;
895
896 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
897 // The caller can deal with this (e.g. pointer + int).
898 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
899 return LHSType;
900
901 // At this point, we have two different arithmetic types.
902
903 // Handle complex types first (C99 6.3.1.8p1).
904 if (LHSType->isComplexType() || RHSType->isComplexType()) {
905 assert(0 && "FIXME: complex types unimp");
906#if 0
907 // if we have an integer operand, the result is the complex type.
908 if (rhs->isIntegerType())
909 return lhs;
910 if (lhs->isIntegerType())
911 return rhs;
912 return Context.maxComplexType(lhs, rhs);
913#endif
914 }
915
916 // If neither operand is complex, they must be scalars.
917 llvm::Value *LHSV = LHS.getVal();
918 llvm::Value *RHSV = RHS.getVal();
919
920 // If the LLVM types are already equal, then they only differed in sign, or it
921 // was something like char/signed char or double/long double.
922 if (LHSV->getType() == RHSV->getType())
923 return LHSType;
924
925 // Now handle "real" floating types (i.e. float, double, long double).
926 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
927 // if we have an integer operand, the result is the real floating type, and
928 // the integer converts to FP.
929 if (RHSType->isIntegerType()) {
930 // Promote the RHS to an FP type of the LHS, with the sign following the
931 // RHS.
932 if (RHSType->isSignedIntegerType())
933 RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
934 else
935 RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
936 return LHSType;
937 }
938
939 if (LHSType->isIntegerType()) {
940 // Promote the LHS to an FP type of the RHS, with the sign following the
941 // LHS.
942 if (LHSType->isSignedIntegerType())
943 LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
944 else
945 LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
946 return RHSType;
947 }
948
949 // Otherwise, they are two FP types. Promote the smaller operand to the
950 // bigger result.
951 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
952
953 if (BiggerType == LHSType)
954 RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
955 else
956 LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
957 return BiggerType;
958 }
959
960 // Finally, we have two integer types that are different according to C. Do
961 // a sign or zero extension if needed.
962
963 // Otherwise, one type is smaller than the other.
964 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
965
966 if (LHSType == ResTy) {
967 if (RHSType->isSignedIntegerType())
968 RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
969 else
970 RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
971 } else {
972 assert(RHSType == ResTy && "Unknown conversion");
973 if (LHSType->isSignedIntegerType())
974 LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
975 else
976 LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
977 }
978 return ResTy;
979}
980
981/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
982/// are strange in that the result of the operation is not the same type as the
983/// intermediate computation. This function emits the LHS and RHS operands of
984/// the compound assignment, promoting them to their common computation type.
985///
986/// Since the LHS is an lvalue, and the result is stored back through it, we
987/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
988/// RHS values are both in the computation type for the operator.
989void CodeGenFunction::
990EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
991 LValue &LHSLV, RValue &LHS, RValue &RHS) {
992 LHSLV = EmitLValue(E->getLHS());
993
994 // Load the LHS and RHS operands.
995 QualType LHSTy = E->getLHS()->getType();
996 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
997 QualType RHSTy;
998 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
999
1000 // Shift operands do the usual unary conversions, but do not do the binary
1001 // conversions.
1002 if (E->isShiftAssignOp()) {
1003 // FIXME: This is broken. Implicit conversions should be made explicit,
1004 // so that this goes away. This causes us to reload the LHS.
1005 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy);
1006 }
1007
1008 // Convert the LHS and RHS to the common evaluation type.
1009 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
1010 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
1011}
1012
1013/// EmitCompoundAssignmentResult - Given a result value in the computation type,
1014/// truncate it down to the actual result type, store it through the LHS lvalue,
1015/// and return it.
1016RValue CodeGenFunction::
1017EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
1018 LValue LHSLV, RValue ResV) {
1019
1020 // Truncate back to the destination type.
1021 if (E->getComputationType() != E->getType())
1022 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
1023
1024 // Store the result value into the LHS.
1025 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
1026
1027 // Return the result.
1028 return ResV;
1029}
1030
1031
1032RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
1033 RValue LHS, RHS;
1034 switch (E->getOpcode()) {
1035 default:
1036 fprintf(stderr, "Unimplemented binary expr!\n");
1037 E->dump();
1038 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
1039 case BinaryOperator::Mul:
1040 EmitUsualArithmeticConversions(E, LHS, RHS);
1041 return EmitMul(LHS, RHS, E->getType());
1042 case BinaryOperator::Div:
1043 EmitUsualArithmeticConversions(E, LHS, RHS);
1044 return EmitDiv(LHS, RHS, E->getType());
1045 case BinaryOperator::Rem:
1046 EmitUsualArithmeticConversions(E, LHS, RHS);
1047 return EmitRem(LHS, RHS, E->getType());
1048 case BinaryOperator::Add: {
1049 QualType ExprTy = E->getType();
1050 if (ExprTy->isPointerType()) {
1051 Expr *LHSExpr = E->getLHS();
1052 QualType LHSTy;
1053 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
1054 Expr *RHSExpr = E->getRHS();
1055 QualType RHSTy;
1056 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
1057 return EmitPointerAdd(LHS, LHSTy, RHS, RHSTy, ExprTy);
1058 } else {
1059 EmitUsualArithmeticConversions(E, LHS, RHS);
1060 return EmitAdd(LHS, RHS, ExprTy);
1061 }
1062 }
1063 case BinaryOperator::Sub: {
1064 QualType ExprTy = E->getType();
1065 Expr *LHSExpr = E->getLHS();
1066 if (LHSExpr->getType()->isPointerType()) {
1067 QualType LHSTy;
1068 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
1069 Expr *RHSExpr = E->getRHS();
1070 QualType RHSTy;
1071 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
1072 return EmitPointerSub(LHS, LHSTy, RHS, RHSTy, ExprTy);
1073 } else {
1074 EmitUsualArithmeticConversions(E, LHS, RHS);
1075 return EmitSub(LHS, RHS, ExprTy);
1076 }
1077 }
1078 case BinaryOperator::Shl:
1079 EmitShiftOperands(E, LHS, RHS);
1080 return EmitShl(LHS, RHS, E->getType());
1081 case BinaryOperator::Shr:
1082 EmitShiftOperands(E, LHS, RHS);
1083 return EmitShr(LHS, RHS, E->getType());
1084 case BinaryOperator::And:
1085 EmitUsualArithmeticConversions(E, LHS, RHS);
1086 return EmitAnd(LHS, RHS, E->getType());
1087 case BinaryOperator::Xor:
1088 EmitUsualArithmeticConversions(E, LHS, RHS);
1089 return EmitXor(LHS, RHS, E->getType());
1090 case BinaryOperator::Or :
1091 EmitUsualArithmeticConversions(E, LHS, RHS);
1092 return EmitOr(LHS, RHS, E->getType());
1093 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1094 case BinaryOperator::LOr: return EmitBinaryLOr(E);
1095 case BinaryOperator::LT:
1096 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1097 llvm::ICmpInst::ICMP_SLT,
1098 llvm::FCmpInst::FCMP_OLT);
1099 case BinaryOperator::GT:
1100 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1101 llvm::ICmpInst::ICMP_SGT,
1102 llvm::FCmpInst::FCMP_OGT);
1103 case BinaryOperator::LE:
1104 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1105 llvm::ICmpInst::ICMP_SLE,
1106 llvm::FCmpInst::FCMP_OLE);
1107 case BinaryOperator::GE:
1108 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1109 llvm::ICmpInst::ICMP_SGE,
1110 llvm::FCmpInst::FCMP_OGE);
1111 case BinaryOperator::EQ:
1112 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1113 llvm::ICmpInst::ICMP_EQ,
1114 llvm::FCmpInst::FCMP_OEQ);
1115 case BinaryOperator::NE:
1116 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1117 llvm::ICmpInst::ICMP_NE,
1118 llvm::FCmpInst::FCMP_UNE);
1119 case BinaryOperator::Assign:
1120 return EmitBinaryAssign(E);
1121
1122 case BinaryOperator::MulAssign: {
1123 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1124 LValue LHSLV;
1125 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1126 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1127 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1128 }
1129 case BinaryOperator::DivAssign: {
1130 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1131 LValue LHSLV;
1132 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1133 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1134 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1135 }
1136 case BinaryOperator::RemAssign: {
1137 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1138 LValue LHSLV;
1139 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1140 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1141 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1142 }
1143 case BinaryOperator::AddAssign: {
1144 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1145 LValue LHSLV;
1146 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1147 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1148 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1149 }
1150 case BinaryOperator::SubAssign: {
1151 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1152 LValue LHSLV;
1153 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1154 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1155 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1156 }
1157 case BinaryOperator::ShlAssign: {
1158 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1159 LValue LHSLV;
1160 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1161 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1162 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1163 }
1164 case BinaryOperator::ShrAssign: {
1165 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1166 LValue LHSLV;
1167 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1168 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1169 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1170 }
1171 case BinaryOperator::AndAssign: {
1172 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1173 LValue LHSLV;
1174 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1175 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1176 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1177 }
1178 case BinaryOperator::OrAssign: {
1179 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1180 LValue LHSLV;
1181 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1182 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1183 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1184 }
1185 case BinaryOperator::XorAssign: {
1186 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1187 LValue LHSLV;
1188 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1189 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1190 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1191 }
1192 case BinaryOperator::Comma: return EmitBinaryComma(E);
1193 }
1194}
1195
1196RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
1197 if (LHS.isScalar())
1198 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1199
1200 // Otherwise, this must be a complex number.
1201 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1202
1203 EmitLoadOfComplex(LHS, LHSR, LHSI);
1204 EmitLoadOfComplex(RHS, RHSR, RHSI);
1205
1206 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1207 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1208 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1209
1210 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1211 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1212 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1213
1214 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1215 EmitStoreOfComplex(ResR, ResI, Res);
1216 return RValue::getAggregate(Res);
1217}
1218
1219RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
1220 if (LHS.isScalar()) {
1221 llvm::Value *RV;
1222 if (LHS.getVal()->getType()->isFloatingPoint())
1223 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
1224 else if (ResTy->isUnsignedIntegerType())
1225 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1226 else
1227 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1228 return RValue::get(RV);
1229 }
1230 assert(0 && "FIXME: This doesn't handle complex operands yet");
1231}
1232
1233RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
1234 if (LHS.isScalar()) {
1235 llvm::Value *RV;
1236 // Rem in C can't be a floating point type: C99 6.5.5p2.
1237 if (ResTy->isUnsignedIntegerType())
1238 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1239 else
1240 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1241 return RValue::get(RV);
1242 }
1243
1244 assert(0 && "FIXME: This doesn't handle complex operands yet");
1245}
1246
1247RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
1248 if (LHS.isScalar())
1249 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
1250
1251 // Otherwise, this must be a complex number.
1252 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1253
1254 EmitLoadOfComplex(LHS, LHSR, LHSI);
1255 EmitLoadOfComplex(RHS, RHSR, RHSI);
1256
1257 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1258 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1259
1260 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1261 EmitStoreOfComplex(ResR, ResI, Res);
1262 return RValue::getAggregate(Res);
1263}
1264
1265RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1266 RValue RHS, QualType RHSTy,
1267 QualType ResTy) {
1268 llvm::Value *LHSValue = LHS.getVal();
1269 llvm::Value *RHSValue = RHS.getVal();
1270 if (LHSTy->isPointerType()) {
1271 // pointer + int
1272 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1273 } else {
1274 // int + pointer
1275 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1276 }
1277}
1278
1279RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
1280 if (LHS.isScalar())
1281 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1282
1283 assert(0 && "FIXME: This doesn't handle complex operands yet");
1284}
1285
1286RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1287 RValue RHS, QualType RHSTy,
1288 QualType ResTy) {
1289 llvm::Value *LHSValue = LHS.getVal();
1290 llvm::Value *RHSValue = RHS.getVal();
1291 if (const PointerType *RHSPtrType =
1292 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1293 // pointer - pointer
1294 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1295 QualType LHSElementType = LHSPtrType->getPointeeType();
1296 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1297 "can't subtract pointers with differing element types");
1298 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
1299 SourceLocation()) / 8;
1300 const llvm::Type *ResultType = ConvertType(ResTy);
1301 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1302 "sub.ptr.lhs.cast");
1303 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1304 "sub.ptr.rhs.cast");
1305 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1306 "sub.ptr.sub");
1307
1308 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1309 // remainder. As such, we handle common power-of-two cases here to generate
1310 // better code.
1311 if (llvm::isPowerOf2_64(ElementSize)) {
1312 llvm::Value *ShAmt =
1313 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1314 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1315 } else {
1316 // Otherwise, do a full sdiv.
1317 llvm::Value *BytesPerElement =
1318 llvm::ConstantInt::get(ResultType, ElementSize);
1319 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1320 "sub.ptr.div"));
1321 }
1322 } else {
1323 // pointer - int
1324 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1325 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1326 }
1327}
1328
1329void CodeGenFunction::EmitShiftOperands(const BinaryOperator *E,
1330 RValue &LHS, RValue &RHS) {
1331 // For shifts, integer promotions are performed, but the usual arithmetic
1332 // conversions are not. The LHS and RHS need not have the same type.
1333 QualType ResTy;
1334 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy);
1335 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy);
1336}
1337
1338
1339RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1340 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1341
1342 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1343 // RHS to the same size as the LHS.
1344 if (LHS->getType() != RHS->getType())
1345 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1346
1347 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1348}
1349
1350RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1351 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1352
1353 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1354 // RHS to the same size as the LHS.
1355 if (LHS->getType() != RHS->getType())
1356 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1357
1358 if (ResTy->isUnsignedIntegerType())
1359 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1360 else
1361 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1362}
1363
1364RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1365 unsigned UICmpOpc, unsigned SICmpOpc,
1366 unsigned FCmpOpc) {
1367 RValue LHS, RHS;
1368 EmitUsualArithmeticConversions(E, LHS, RHS);
1369
1370 llvm::Value *Result;
1371 if (LHS.isScalar()) {
1372 if (LHS.getVal()->getType()->isFloatingPoint()) {
1373 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1374 LHS.getVal(), RHS.getVal(), "cmp");
1375 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1376 // FIXME: This check isn't right for "unsigned short < int" where ushort
1377 // promotes to int and does a signed compare.
1378 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1379 LHS.getVal(), RHS.getVal(), "cmp");
1380 } else {
1381 // Signed integers and pointers.
1382 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1383 LHS.getVal(), RHS.getVal(), "cmp");
1384 }
1385 } else {
1386 // Struct/union/complex
1387 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1388 EmitLoadOfComplex(LHS, LHSR, LHSI);
1389 EmitLoadOfComplex(RHS, RHSR, RHSI);
1390
1391 // FIXME: need to consider _Complex over integers too!
1392
1393 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1394 LHSR, RHSR, "cmp.r");
1395 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1396 LHSI, RHSI, "cmp.i");
1397 if (BinaryOperator::EQ == E->getOpcode()) {
1398 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1399 } else if (BinaryOperator::NE == E->getOpcode()) {
1400 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1401 } else {
1402 assert(0 && "Complex comparison other than == or != ?");
1403 }
1404 }
1405
1406 // ZExt result to int.
1407 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1408}
1409
1410RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
1411 if (LHS.isScalar())
1412 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1413
1414 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1415}
1416
1417RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
1418 if (LHS.isScalar())
1419 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1420
1421 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1422}
1423
1424RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
1425 if (LHS.isScalar())
1426 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1427
1428 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1429}
1430
1431RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1432 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1433
1434 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1435 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1436
1437 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1438 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1439
1440 EmitBlock(RHSBlock);
1441 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1442
1443 // Reaquire the RHS block, as there may be subblocks inserted.
1444 RHSBlock = Builder.GetInsertBlock();
1445 EmitBlock(ContBlock);
1446
1447 // Create a PHI node. If we just evaluted the LHS condition, the result is
1448 // false. If we evaluated both, the result is the RHS condition.
1449 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1450 PN->reserveOperandSpace(2);
1451 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1452 PN->addIncoming(RHSCond, RHSBlock);
1453
1454 // ZExt result to int.
1455 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1456}
1457
1458RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1459 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1460
1461 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1462 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1463
1464 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1465 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1466
1467 EmitBlock(RHSBlock);
1468 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1469
1470 // Reaquire the RHS block, as there may be subblocks inserted.
1471 RHSBlock = Builder.GetInsertBlock();
1472 EmitBlock(ContBlock);
1473
1474 // Create a PHI node. If we just evaluted the LHS condition, the result is
1475 // true. If we evaluated both, the result is the RHS condition.
1476 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1477 PN->reserveOperandSpace(2);
1478 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1479 PN->addIncoming(RHSCond, RHSBlock);
1480
1481 // ZExt result to int.
1482 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1483}
1484
1485RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
1486 LValue LHS = EmitLValue(E->getLHS());
1487
1488 QualType RHSTy;
1489 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
1490
1491 // Convert the RHS to the type of the LHS.
1492 RHS = EmitConversion(RHS, RHSTy, E->getType());
1493
1494 // Store the value into the LHS.
1495 EmitStoreThroughLValue(RHS, LHS, E->getType());
1496
1497 // Return the converted RHS.
1498 return RHS;
1499}
1500
1501
1502RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1503 EmitExpr(E->getLHS());
1504 return EmitExpr(E->getRHS());
1505}
1506
1507RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1508 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1509 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1510 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1511
1512 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1513 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1514
1515 // FIXME: Implement this for aggregate values.
1516
1517 // FIXME: LHS & RHS need the "usual arithmetic conversions" but
1518 // that's not possible with the current design.
1519
1520 EmitBlock(LHSBlock);
1521 QualType LHSTy;
1522 llvm::Value *LHSValue = E->getLHS() ? // GNU extension
1523 EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy).getVal() :
1524 Cond;
1525 Builder.CreateBr(ContBlock);
1526 LHSBlock = Builder.GetInsertBlock();
1527
1528 EmitBlock(RHSBlock);
1529 QualType RHSTy;
1530 llvm::Value *RHSValue =
1531 EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy).getVal();
1532 Builder.CreateBr(ContBlock);
1533 RHSBlock = Builder.GetInsertBlock();
1534
1535 const llvm::Type *LHSType = LHSValue->getType();
1536 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1537
1538 EmitBlock(ContBlock);
1539 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1540 PN->reserveOperandSpace(2);
1541 PN->addIncoming(LHSValue, LHSBlock);
1542 PN->addIncoming(RHSValue, RHSBlock);
1543
1544 return RValue::get(PN);
1545}