blob: 1b0cbca94a8d69b7ca160cc411969301502ba15b [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) {
Chris Lattner2af72ac2007-08-08 17:43:05 +000039 return ConvertScalarValueToBool(EmitExpr(E), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +000040}
41
42/// EmitLoadOfComplex - Given an RValue reference for a complex, emit code to
43/// load the real and imaginary pieces, returning them as Real/Imag.
44void CodeGenFunction::EmitLoadOfComplex(RValue V,
45 llvm::Value *&Real, llvm::Value *&Imag){
46 llvm::Value *Ptr = V.getAggregateAddr();
47
48 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
49 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
50 llvm::Value *RealPtr = Builder.CreateGEP(Ptr, Zero, Zero, "realp");
51 llvm::Value *ImagPtr = Builder.CreateGEP(Ptr, Zero, One, "imagp");
52
53 // FIXME: Handle volatility.
54 Real = Builder.CreateLoad(RealPtr, "real");
55 Imag = Builder.CreateLoad(ImagPtr, "imag");
56}
57
58/// EmitStoreOfComplex - Store the specified real/imag parts into the
59/// specified value pointer.
60void CodeGenFunction::EmitStoreOfComplex(llvm::Value *Real, llvm::Value *Imag,
61 llvm::Value *ResPtr) {
62 llvm::Constant *Zero = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
63 llvm::Constant *One = llvm::ConstantInt::get(llvm::Type::Int32Ty, 1);
64 llvm::Value *RealPtr = Builder.CreateGEP(ResPtr, Zero, Zero, "real");
65 llvm::Value *ImagPtr = Builder.CreateGEP(ResPtr, Zero, One, "imag");
66
67 // FIXME: Handle volatility.
68 Builder.CreateStore(Real, RealPtr);
69 Builder.CreateStore(Imag, ImagPtr);
70}
71
72//===--------------------------------------------------------------------===//
73// Conversions
74//===--------------------------------------------------------------------===//
75
76/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
77/// the type specified by DstTy, following the rules of C99 6.3.
78RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
79 QualType DstTy) {
80 ValTy = ValTy.getCanonicalType();
81 DstTy = DstTy.getCanonicalType();
82 if (ValTy == DstTy) return Val;
83
84 // Handle conversions to bool first, they are special: comparisons against 0.
85 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
86 if (DestBT->getKind() == BuiltinType::Bool)
87 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
88
89 // Handle pointer conversions next: pointers can only be converted to/from
90 // other pointers and integers.
91 if (isa<PointerType>(DstTy)) {
92 const llvm::Type *DestTy = ConvertType(DstTy);
93
94 // The source value may be an integer, or a pointer.
95 assert(Val.isScalar() && "Can only convert from integer or pointer");
96 if (isa<llvm::PointerType>(Val.getVal()->getType()))
97 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
98 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
99 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
100 }
101
102 if (isa<PointerType>(ValTy)) {
103 // Must be an ptr to int cast.
104 const llvm::Type *DestTy = ConvertType(DstTy);
105 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
106 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
107 }
108
109 // Finally, we have the arithmetic types: real int/float and complex
110 // int/float. Handle real->real conversions first, they are the most
111 // common.
112 if (Val.isScalar() && DstTy->isRealType()) {
113 // We know that these are representable as scalars in LLVM, convert to LLVM
114 // types since they are easier to reason about.
115 llvm::Value *SrcVal = Val.getVal();
116 const llvm::Type *DestTy = ConvertType(DstTy);
117 if (SrcVal->getType() == DestTy) return Val;
118
119 llvm::Value *Result;
120 if (isa<llvm::IntegerType>(SrcVal->getType())) {
121 bool InputSigned = ValTy->isSignedIntegerType();
122 if (isa<llvm::IntegerType>(DestTy))
123 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
124 else if (InputSigned)
125 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
126 else
127 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
128 } else {
129 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
130 if (isa<llvm::IntegerType>(DestTy)) {
131 if (DstTy->isSignedIntegerType())
132 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
133 else
134 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
135 } else {
136 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
137 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
138 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
139 else
140 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
141 }
142 }
143 return RValue::get(Result);
144 }
145
146 assert(0 && "FIXME: We don't support complex conversions yet!");
147}
148
149
150/// ConvertScalarValueToBool - Convert the specified expression value to a
151/// boolean (i1) truth value. This is equivalent to "Val == 0".
152llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
153 Ty = Ty.getCanonicalType();
154 llvm::Value *Result;
155 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
156 switch (BT->getKind()) {
157 default: assert(0 && "Unknown scalar value");
158 case BuiltinType::Bool:
159 Result = Val.getVal();
160 // Bool is already evaluated right.
161 assert(Result->getType() == llvm::Type::Int1Ty &&
162 "Unexpected bool value type!");
163 return Result;
164 case BuiltinType::Char_S:
165 case BuiltinType::Char_U:
166 case BuiltinType::SChar:
167 case BuiltinType::UChar:
168 case BuiltinType::Short:
169 case BuiltinType::UShort:
170 case BuiltinType::Int:
171 case BuiltinType::UInt:
172 case BuiltinType::Long:
173 case BuiltinType::ULong:
174 case BuiltinType::LongLong:
175 case BuiltinType::ULongLong:
176 // Code below handles simple integers.
177 break;
178 case BuiltinType::Float:
179 case BuiltinType::Double:
180 case BuiltinType::LongDouble: {
181 // Compare against 0.0 for fp scalars.
182 Result = Val.getVal();
183 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
184 // FIXME: llvm-gcc produces a une comparison: validate this is right.
185 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
186 return Result;
187 }
188 }
189 } else if (isa<PointerType>(Ty) ||
190 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
191 // Code below handles this fine.
192 } else {
193 assert(isa<ComplexType>(Ty) && "Unknwon type!");
194 assert(0 && "FIXME: comparisons against complex not implemented yet");
195 }
196
197 // Usual case for integers, pointers, and enums: compare against zero.
198 Result = Val.getVal();
199
200 // Because of the type rules of C, we often end up computing a logical value,
201 // then zero extending it to int, then wanting it as a logical value again.
202 // Optimize this common case.
203 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
204 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
205 Result = ZI->getOperand(0);
206 ZI->eraseFromParent();
207 return Result;
208 }
209 }
210
211 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
212 return Builder.CreateICmpNE(Result, Zero, "tobool");
213}
214
215//===----------------------------------------------------------------------===//
216// LValue Expression Emission
217//===----------------------------------------------------------------------===//
218
219/// EmitLValue - Emit code to compute a designator that specifies the location
220/// of the expression.
221///
222/// This can return one of two things: a simple address or a bitfield
223/// reference. In either case, the LLVM Value* in the LValue structure is
224/// guaranteed to be an LLVM pointer type.
225///
226/// If this returns a bitfield reference, nothing about the pointee type of
227/// the LLVM value is known: For example, it may not be a pointer to an
228/// integer.
229///
230/// If this returns a normal address, and if the lvalue's C type is fixed
231/// size, this method guarantees that the returned pointer type will point to
232/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
233/// variable length type, this is not possible.
234///
235LValue CodeGenFunction::EmitLValue(const Expr *E) {
236 switch (E->getStmtClass()) {
237 default:
238 fprintf(stderr, "Unimplemented lvalue expr!\n");
239 E->dump();
240 return LValue::MakeAddr(llvm::UndefValue::get(
241 llvm::PointerType::get(llvm::Type::Int32Ty)));
242
243 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
244 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
245 case Expr::PreDefinedExprClass:
246 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
247 case Expr::StringLiteralClass:
248 return EmitStringLiteralLValue(cast<StringLiteral>(E));
249
250 case Expr::UnaryOperatorClass:
251 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
252 case Expr::ArraySubscriptExprClass:
253 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000254 case Expr::OCUVectorElementExprClass:
255 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000256 }
257}
258
259/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
260/// this method emits the address of the lvalue, then loads the result as an
261/// rvalue, returning the rvalue.
262RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
263 ExprType = ExprType.getCanonicalType();
264
265 if (LV.isSimple()) {
266 llvm::Value *Ptr = LV.getAddress();
267 const llvm::Type *EltTy =
268 cast<llvm::PointerType>(Ptr->getType())->getElementType();
269
270 // Simple scalar l-value.
271 if (EltTy->isFirstClassType())
272 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
273
274 // Otherwise, we have an aggregate lvalue.
275 return RValue::getAggregate(Ptr);
276 }
277
278 if (LV.isVectorElt()) {
279 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
280 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
281 "vecext"));
282 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000283
284 // If this is a reference to a subset of the elements of a vector, either
285 // shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000286 if (LV.isOCUVectorElt())
287 return EmitLoadOfOCUElementLValue(LV, ExprType);
Chris Lattner4b009652007-07-25 00:24:17 +0000288
289 assert(0 && "Bitfield ref not impl!");
290}
291
Chris Lattner944f7962007-08-03 16:18:34 +0000292// If this is a reference to a subset of the elements of a vector, either
293// shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000294RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner944f7962007-08-03 16:18:34 +0000295 QualType ExprType) {
296 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
297
Chris Lattnera0d03a72007-08-03 17:31:20 +0000298 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner944f7962007-08-03 16:18:34 +0000299
300 // If the result of the expression is a non-vector type, we must be
301 // extracting a single element. Just codegen as an extractelement.
302 if (!isa<VectorType>(ExprType)) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000303 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000304 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
305 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
306 }
307
308 // If the source and destination have the same number of elements, use a
309 // vector shuffle instead of insert/extracts.
310 unsigned NumResultElts = cast<VectorType>(ExprType)->getNumElements();
311 unsigned NumSourceElts =
312 cast<llvm::VectorType>(Vec->getType())->getNumElements();
313
314 if (NumResultElts == NumSourceElts) {
315 llvm::SmallVector<llvm::Constant*, 4> Mask;
316 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000317 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000318 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
319 }
320
321 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
322 Vec = Builder.CreateShuffleVector(Vec,
323 llvm::UndefValue::get(Vec->getType()),
324 MaskV, "tmp");
325 return RValue::get(Vec);
326 }
327
328 // Start out with an undef of the result type.
329 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
330
331 // Extract/Insert each element of the result.
332 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000333 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000334 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
335 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
336
337 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
338 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
339 }
340
341 return RValue::get(Result);
342}
343
344
Chris Lattner4b009652007-07-25 00:24:17 +0000345RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
346 return EmitLoadOfLValue(EmitLValue(E), E->getType());
347}
348
349
350/// EmitStoreThroughLValue - Store the specified rvalue into the specified
351/// lvalue, where both are guaranteed to the have the same type, and that type
352/// is 'Ty'.
353void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
354 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000355 if (!Dst.isSimple()) {
356 if (Dst.isVectorElt()) {
357 // Read/modify/write the vector, inserting the new element.
358 // FIXME: Volatility.
359 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
360 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
361 Dst.getVectorIdx(), "vecins");
362 Builder.CreateStore(Vec, Dst.getVectorAddr());
363 return;
364 }
Chris Lattner4b009652007-07-25 00:24:17 +0000365
Chris Lattner5bfdd232007-08-03 16:28:33 +0000366 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000367 if (Dst.isOCUVectorElt())
Chris Lattner5bfdd232007-08-03 16:28:33 +0000368 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
369
370 assert(0 && "FIXME: Don't support store to bitfield yet");
371 }
Chris Lattner4b009652007-07-25 00:24:17 +0000372
373 llvm::Value *DstAddr = Dst.getAddress();
374 if (Src.isScalar()) {
375 // FIXME: Handle volatility etc.
376 const llvm::Type *SrcTy = Src.getVal()->getType();
377 const llvm::Type *AddrTy =
378 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
379
380 if (AddrTy != SrcTy)
381 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
382 "storetmp");
383 Builder.CreateStore(Src.getVal(), DstAddr);
384 return;
385 }
386
387 // Don't use memcpy for complex numbers.
388 if (Ty->isComplexType()) {
389 llvm::Value *Real, *Imag;
390 EmitLoadOfComplex(Src, Real, Imag);
391 EmitStoreOfComplex(Real, Imag, Dst.getAddress());
392 return;
393 }
394
395 // Aggregate assignment turns into llvm.memcpy.
396 const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
397 llvm::Value *SrcAddr = Src.getAggregateAddr();
398
399 if (DstAddr->getType() != SBP)
400 DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
401 if (SrcAddr->getType() != SBP)
402 SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
403
404 unsigned Align = 1; // FIXME: Compute type alignments.
405 unsigned Size = 1234; // FIXME: Compute type sizes.
406
407 // FIXME: Handle variable sized types.
408 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
409 llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
410
411 llvm::Value *MemCpyOps[4] = {
412 DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
413 };
414
Chris Lattnera9572252007-08-01 06:24:52 +0000415 Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, MemCpyOps+4);
Chris Lattner4b009652007-07-25 00:24:17 +0000416}
417
Chris Lattner5bfdd232007-08-03 16:28:33 +0000418void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
419 QualType Ty) {
420 // This access turns into a read/modify/write of the vector. Load the input
421 // value now.
422 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
423 // FIXME: Volatility.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000424 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000425
426 llvm::Value *SrcVal = Src.getVal();
427
Chris Lattner940966d2007-08-03 16:37:04 +0000428 if (const VectorType *VTy = Ty->getAsVectorType()) {
429 unsigned NumSrcElts = VTy->getNumElements();
430
431 // Extract/Insert each element.
432 for (unsigned i = 0; i != NumSrcElts; ++i) {
433 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
434 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
435
Chris Lattnera0d03a72007-08-03 17:31:20 +0000436 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner940966d2007-08-03 16:37:04 +0000437 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
438 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
439 }
440 } else {
441 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000442 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner5bfdd232007-08-03 16:28:33 +0000443 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
444 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000445 }
446
Chris Lattner5bfdd232007-08-03 16:28:33 +0000447 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
448}
449
Chris Lattner4b009652007-07-25 00:24:17 +0000450
451LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
452 const Decl *D = E->getDecl();
453 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
454 llvm::Value *V = LocalDeclMap[D];
455 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
456 return LValue::MakeAddr(V);
457 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
458 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
459 }
460 assert(0 && "Unimp declref");
461}
462
463LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
464 // __extension__ doesn't affect lvalue-ness.
465 if (E->getOpcode() == UnaryOperator::Extension)
466 return EmitLValue(E->getSubExpr());
467
468 assert(E->getOpcode() == UnaryOperator::Deref &&
469 "'*' is the only unary operator that produces an lvalue");
470 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
471}
472
473LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
474 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
475 const char *StrData = E->getStrData();
476 unsigned Len = E->getByteLength();
477
478 // FIXME: Can cache/reuse these within the module.
479 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
480
481 // Create a global variable for this.
482 C = new llvm::GlobalVariable(C->getType(), true,
483 llvm::GlobalValue::InternalLinkage,
484 C, ".str", CurFn->getParent());
485 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
486 llvm::Constant *Zeros[] = { Zero, Zero };
487 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
488 return LValue::MakeAddr(C);
489}
490
491LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
492 std::string FunctionName(CurFuncDecl->getName());
493 std::string GlobalVarName;
494
495 switch (E->getIdentType()) {
496 default:
497 assert(0 && "unknown pre-defined ident type");
498 case PreDefinedExpr::Func:
499 GlobalVarName = "__func__.";
500 break;
501 case PreDefinedExpr::Function:
502 GlobalVarName = "__FUNCTION__.";
503 break;
504 case PreDefinedExpr::PrettyFunction:
505 // FIXME:: Demangle C++ method names
506 GlobalVarName = "__PRETTY_FUNCTION__.";
507 break;
508 }
509
510 GlobalVarName += CurFuncDecl->getName();
511
512 // FIXME: Can cache/reuse these within the module.
513 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
514
515 // Create a global variable for this.
516 C = new llvm::GlobalVariable(C->getType(), true,
517 llvm::GlobalValue::InternalLinkage,
518 C, GlobalVarName, CurFn->getParent());
519 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
520 llvm::Constant *Zeros[] = { Zero, Zero };
521 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
522 return LValue::MakeAddr(C);
523}
524
525LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
526 // The index must always be a pointer or integer, neither of which is an
527 // aggregate. Emit it.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000528 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000529
530 // If the base is a vector type, then we are forming a vector element lvalue
531 // with this subscript.
532 if (E->getBase()->getType()->isVectorType()) {
533 // Emit the vector as an lvalue to get its address.
534 LValue Base = EmitLValue(E->getBase());
535 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
536 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
537 return LValue::MakeVectorElt(Base.getAddress(), Idx);
538 }
539
540 // At this point, the base must be a pointer or integer, neither of which are
541 // aggregates. Emit it.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000542 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000543
544 // Usually the base is the pointer type, but sometimes it is the index.
545 // Canonicalize to have the pointer as the base.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000546 QualType BaseTy = E->getBase()->getType();
547 QualType IdxTy = E->getIdx()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000548 if (isa<llvm::PointerType>(Idx->getType())) {
549 std::swap(Base, Idx);
550 std::swap(BaseTy, IdxTy);
551 }
552
553 // The pointer is now the base. Extend or truncate the index type to 32 or
554 // 64-bits.
555 bool IdxSigned = IdxTy->isSignedIntegerType();
556 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
557 if (IdxBitwidth != LLVMPointerWidth)
558 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
559 IdxSigned, "idxprom");
560
561 // We know that the pointer points to a type of the correct size, unless the
562 // size is a VLA.
563 if (!E->getType()->isConstantSizeType(getContext()))
564 assert(0 && "VLA idx not implemented");
565 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
566}
567
Chris Lattner65520192007-08-02 23:37:31 +0000568LValue CodeGenFunction::
Chris Lattnera0d03a72007-08-03 17:31:20 +0000569EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner65520192007-08-02 23:37:31 +0000570 // Emit the base vector as an l-value.
571 LValue Base = EmitLValue(E->getBase());
572 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
573
Chris Lattnera0d03a72007-08-03 17:31:20 +0000574 return LValue::MakeOCUVectorElt(Base.getAddress(),
575 E->getEncodedElementAccess());
Chris Lattner65520192007-08-02 23:37:31 +0000576}
577
Chris Lattner4b009652007-07-25 00:24:17 +0000578//===--------------------------------------------------------------------===//
579// Expression Emission
580//===--------------------------------------------------------------------===//
581
582RValue CodeGenFunction::EmitExpr(const Expr *E) {
583 assert(E && "Null expression?");
584
585 switch (E->getStmtClass()) {
586 default:
587 fprintf(stderr, "Unimplemented expr!\n");
588 E->dump();
589 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
590
591 // l-values.
592 case Expr::DeclRefExprClass:
593 // DeclRef's of EnumConstantDecl's are simple rvalues.
594 if (const EnumConstantDecl *EC =
595 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
596 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
597 return EmitLoadOfLValue(E);
598 case Expr::ArraySubscriptExprClass:
599 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000600 case Expr::OCUVectorElementExprClass:
Chris Lattnera735fac2007-08-03 00:16:29 +0000601 return EmitLoadOfLValue(E);
Chris Lattner4b009652007-07-25 00:24:17 +0000602 case Expr::PreDefinedExprClass:
603 case Expr::StringLiteralClass:
604 return RValue::get(EmitLValue(E).getAddress());
605
606 // Leaf expressions.
607 case Expr::IntegerLiteralClass:
608 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
609 case Expr::FloatingLiteralClass:
610 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
611 case Expr::CharacterLiteralClass:
612 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattner4ca7e752007-08-03 17:51:03 +0000613 case Expr::TypesCompatibleExprClass:
614 return EmitTypesCompatibleExpr(cast<TypesCompatibleExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000615
616 // Operators.
617 case Expr::ParenExprClass:
618 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
619 case Expr::UnaryOperatorClass:
620 return EmitUnaryOperator(cast<UnaryOperator>(E));
621 case Expr::SizeOfAlignOfTypeExprClass:
622 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
623 E->getType(),
624 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
625 case Expr::ImplicitCastExprClass:
626 return EmitCastExpr(cast<ImplicitCastExpr>(E)->getSubExpr(), E->getType());
627 case Expr::CastExprClass:
628 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
629 case Expr::CallExprClass:
630 return EmitCallExpr(cast<CallExpr>(E));
631 case Expr::BinaryOperatorClass:
632 return EmitBinaryOperator(cast<BinaryOperator>(E));
633
634 case Expr::ConditionalOperatorClass:
635 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Chris Lattner44fcf4f2007-08-04 00:20:15 +0000636 case Expr::ChooseExprClass:
637 return EmitChooseExpr(cast<ChooseExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000638 }
639
640}
641
642RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
643 return RValue::get(llvm::ConstantInt::get(E->getValue()));
644}
645RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
646 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
647 E->getValue()));
648}
649RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
650 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
651 E->getValue()));
652}
653
Chris Lattner4ca7e752007-08-03 17:51:03 +0000654RValue CodeGenFunction::EmitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
655 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
656 E->typesAreCompatible()));
657}
658
Chris Lattner44fcf4f2007-08-04 00:20:15 +0000659/// EmitChooseExpr - Implement __builtin_choose_expr.
660RValue CodeGenFunction::EmitChooseExpr(const ChooseExpr *E) {
661 llvm::APSInt CondVal(32);
662 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, getContext());
663 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
664
665 // Emit the LHS or RHS as appropriate.
666 return EmitExpr(CondVal != 0 ? E->getLHS() : E->getRHS());
667}
668
Chris Lattner4ca7e752007-08-03 17:51:03 +0000669
Chris Lattner4b009652007-07-25 00:24:17 +0000670RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
671 // Emit subscript expressions in rvalue context's. For most cases, this just
672 // loads the lvalue formed by the subscript expr. However, we have to be
673 // careful, because the base of a vector subscript is occasionally an rvalue,
674 // so we can't get it as an lvalue.
675 if (!E->getBase()->getType()->isVectorType())
676 return EmitLoadOfLValue(E);
677
678 // Handle the vector case. The base must be a vector, the index must be an
679 // integer value.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000680 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
681 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000682
683 // FIXME: Convert Idx to i32 type.
684
685 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
686}
687
688// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
689// have to handle a more broad range of conversions than explicit casts, as they
690// handle things like function to ptr-to-function decay etc.
691RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000692 RValue Src = EmitExpr(Op);
Chris Lattner4b009652007-07-25 00:24:17 +0000693
694 // If the destination is void, just evaluate the source.
695 if (DestTy->isVoidType())
696 return RValue::getAggregate(0);
697
Chris Lattner2af72ac2007-08-08 17:43:05 +0000698 return EmitConversion(Src, Op->getType(), DestTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000699}
700
701RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000702 llvm::Value *Callee = EmitExpr(E->getCallee()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000703
704 // The callee type will always be a pointer to function type, get the function
705 // type.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000706 QualType CalleeTy = E->getCallee()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000707 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
708
709 // Get information about the argument types.
710 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
711
712 // Calling unprototyped functions provides no argument info.
713 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
714 ArgTyIt = FTP->arg_type_begin();
715 ArgTyEnd = FTP->arg_type_end();
716 }
717
718 llvm::SmallVector<llvm::Value*, 16> Args;
719
720 // FIXME: Handle struct return.
721 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000722 QualType ArgTy = E->getArg(i)->getType();
723 RValue ArgVal = EmitExpr(E->getArg(i));
Chris Lattner4b009652007-07-25 00:24:17 +0000724
725 // If this argument has prototype information, convert it.
726 if (ArgTyIt != ArgTyEnd) {
727 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
728 } else {
729 // Otherwise, if passing through "..." or to a function with no prototype,
730 // perform the "default argument promotions" (C99 6.5.2.2p6), which
731 // includes the usual unary conversions, but also promotes float to
732 // double.
733 if (const BuiltinType *BT =
734 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
735 if (BT->getKind() == BuiltinType::Float)
736 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
737 llvm::Type::DoubleTy,"tmp"));
738 }
739 }
740
741
742 if (ArgVal.isScalar())
743 Args.push_back(ArgVal.getVal());
744 else // Pass by-address. FIXME: Set attribute bit on call.
745 Args.push_back(ArgVal.getAggregateAddr());
746 }
747
Chris Lattnera9572252007-08-01 06:24:52 +0000748 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000749 if (V->getType() != llvm::Type::VoidTy)
750 V->setName("call");
751
752 // FIXME: Struct return;
753 return RValue::get(V);
754}
755
756
757//===----------------------------------------------------------------------===//
758// Unary Operator Emission
759//===----------------------------------------------------------------------===//
760
Chris Lattner4b009652007-07-25 00:24:17 +0000761RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
762 switch (E->getOpcode()) {
763 default:
764 printf("Unimplemented unary expr!\n");
765 E->dump();
766 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
767 case UnaryOperator::PostInc:
768 case UnaryOperator::PostDec:
769 case UnaryOperator::PreInc :
770 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
771 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
772 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
773 case UnaryOperator::Plus : return EmitUnaryPlus(E);
774 case UnaryOperator::Minus : return EmitUnaryMinus(E);
775 case UnaryOperator::Not : return EmitUnaryNot(E);
776 case UnaryOperator::LNot : return EmitUnaryLNot(E);
777 case UnaryOperator::SizeOf :
778 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
779 case UnaryOperator::AlignOf :
780 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
781 // FIXME: real/imag
782 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
783 }
784}
785
786RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
787 LValue LV = EmitLValue(E->getSubExpr());
788 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
789
790 // We know the operand is real or pointer type, so it must be an LLVM scalar.
791 assert(InVal.isScalar() && "Unknown thing to increment");
792 llvm::Value *InV = InVal.getVal();
793
794 int AmountVal = 1;
795 if (E->getOpcode() == UnaryOperator::PreDec ||
796 E->getOpcode() == UnaryOperator::PostDec)
797 AmountVal = -1;
798
799 llvm::Value *NextVal;
800 if (isa<llvm::IntegerType>(InV->getType())) {
801 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
802 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
803 } else if (InV->getType()->isFloatingPoint()) {
804 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
805 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
806 } else {
807 // FIXME: This is not right for pointers to VLA types.
808 assert(isa<llvm::PointerType>(InV->getType()));
809 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
810 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
811 }
812
813 RValue NextValToStore = RValue::get(NextVal);
814
815 // Store the updated result through the lvalue.
816 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
817
818 // If this is a postinc, return the value read from memory, otherwise use the
819 // updated value.
820 if (E->getOpcode() == UnaryOperator::PreDec ||
821 E->getOpcode() == UnaryOperator::PreInc)
822 return NextValToStore;
823 else
824 return InVal;
825}
826
827/// C99 6.5.3.2
828RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
829 // The address of the operand is just its lvalue. It cannot be a bitfield.
830 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
831}
832
833RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000834 assert(E->getType().getCanonicalType() ==
835 E->getSubExpr()->getType().getCanonicalType() && "Bad unary plus!");
836 // Unary plus just returns its value.
837 return EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000838}
839
840RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000841 assert(E->getType().getCanonicalType() ==
842 E->getSubExpr()->getType().getCanonicalType() && "Bad unary minus!");
843
Chris Lattner4b009652007-07-25 00:24:17 +0000844 // Unary minus performs promotions, then negates its arithmetic operand.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000845 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000846
847 if (V.isScalar())
848 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
849
850 assert(0 && "FIXME: This doesn't handle complex operands yet");
851}
852
853RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
854 // Unary not performs promotions, then complements its integer operand.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000855 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000856
857 if (V.isScalar())
858 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
859
860 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
861}
862
863
864/// C99 6.5.3.3
865RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
866 // Compare operand to zero.
867 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
868
869 // Invert value.
870 // TODO: Could dynamically modify easy computations here. For example, if
871 // the operand is an icmp ne, turn into icmp eq.
872 BoolVal = Builder.CreateNot(BoolVal, "lnot");
873
874 // ZExt result to int.
875 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
876}
877
878/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
879/// an integer (RetType).
880RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
881 QualType RetType, bool isSizeOf) {
882 /// FIXME: This doesn't handle VLAs yet!
883 std::pair<uint64_t, unsigned> Info =
884 getContext().getTypeInfo(TypeToSize, SourceLocation());
885
886 uint64_t Val = isSizeOf ? Info.first : Info.second;
887 Val /= 8; // Return size in bytes, not bits.
888
889 assert(RetType->isIntegerType() && "Result type must be an integer!");
890
891 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
892 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
893}
894
895
896//===--------------------------------------------------------------------===//
897// Binary Operator Emission
898//===--------------------------------------------------------------------===//
899
Chris Lattner4b009652007-07-25 00:24:17 +0000900
901/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
902/// are strange in that the result of the operation is not the same type as the
903/// intermediate computation. This function emits the LHS and RHS operands of
904/// the compound assignment, promoting them to their common computation type.
905///
906/// Since the LHS is an lvalue, and the result is stored back through it, we
907/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
908/// RHS values are both in the computation type for the operator.
909void CodeGenFunction::
910EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
911 LValue &LHSLV, RValue &LHS, RValue &RHS) {
912 LHSLV = EmitLValue(E->getLHS());
913
914 // Load the LHS and RHS operands.
915 QualType LHSTy = E->getLHS()->getType();
916 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner2af72ac2007-08-08 17:43:05 +0000917 RHS = EmitExpr(E->getRHS());
918 QualType RHSTy = E->getRHS()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000919
920 // Convert the LHS and RHS to the common evaluation type.
921 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
922 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
923}
924
925/// EmitCompoundAssignmentResult - Given a result value in the computation type,
926/// truncate it down to the actual result type, store it through the LHS lvalue,
927/// and return it.
928RValue CodeGenFunction::
929EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
930 LValue LHSLV, RValue ResV) {
931
932 // Truncate back to the destination type.
933 if (E->getComputationType() != E->getType())
934 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
935
936 // Store the result value into the LHS.
937 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
938
939 // Return the result.
940 return ResV;
941}
942
943
944RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
945 RValue LHS, RHS;
946 switch (E->getOpcode()) {
947 default:
948 fprintf(stderr, "Unimplemented binary expr!\n");
949 E->dump();
950 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
951 case BinaryOperator::Mul:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000952 LHS = EmitExpr(E->getLHS());
953 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000954 return EmitMul(LHS, RHS, E->getType());
955 case BinaryOperator::Div:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000956 LHS = EmitExpr(E->getLHS());
957 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000958 return EmitDiv(LHS, RHS, E->getType());
959 case BinaryOperator::Rem:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000960 LHS = EmitExpr(E->getLHS());
961 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000962 return EmitRem(LHS, RHS, E->getType());
Chris Lattnerbf49e992007-08-08 17:49:18 +0000963 case BinaryOperator::Add:
964 LHS = EmitExpr(E->getLHS());
965 RHS = EmitExpr(E->getRHS());
966 if (!E->getType()->isPointerType())
967 return EmitAdd(LHS, RHS, E->getType());
968
969 return EmitPointerAdd(LHS, E->getLHS()->getType(),
970 RHS, E->getRHS()->getType(), E->getType());
971 case BinaryOperator::Sub:
972 LHS = EmitExpr(E->getLHS());
973 RHS = EmitExpr(E->getRHS());
974
975 if (!E->getLHS()->getType()->isPointerType())
976 return EmitSub(LHS, RHS, E->getType());
977
978 return EmitPointerSub(LHS, E->getLHS()->getType(),
979 RHS, E->getRHS()->getType(), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +0000980 case BinaryOperator::Shl:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000981 LHS = EmitExpr(E->getLHS());
982 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000983 return EmitShl(LHS, RHS, E->getType());
984 case BinaryOperator::Shr:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000985 LHS = EmitExpr(E->getLHS());
986 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000987 return EmitShr(LHS, RHS, E->getType());
988 case BinaryOperator::And:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000989 LHS = EmitExpr(E->getLHS());
990 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000991 return EmitAnd(LHS, RHS, E->getType());
992 case BinaryOperator::Xor:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000993 LHS = EmitExpr(E->getLHS());
994 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000995 return EmitXor(LHS, RHS, E->getType());
996 case BinaryOperator::Or :
Chris Lattnerbf49e992007-08-08 17:49:18 +0000997 LHS = EmitExpr(E->getLHS());
998 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000999 return EmitOr(LHS, RHS, E->getType());
1000 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1001 case BinaryOperator::LOr: return EmitBinaryLOr(E);
1002 case BinaryOperator::LT:
1003 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1004 llvm::ICmpInst::ICMP_SLT,
1005 llvm::FCmpInst::FCMP_OLT);
1006 case BinaryOperator::GT:
1007 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1008 llvm::ICmpInst::ICMP_SGT,
1009 llvm::FCmpInst::FCMP_OGT);
1010 case BinaryOperator::LE:
1011 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1012 llvm::ICmpInst::ICMP_SLE,
1013 llvm::FCmpInst::FCMP_OLE);
1014 case BinaryOperator::GE:
1015 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1016 llvm::ICmpInst::ICMP_SGE,
1017 llvm::FCmpInst::FCMP_OGE);
1018 case BinaryOperator::EQ:
1019 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1020 llvm::ICmpInst::ICMP_EQ,
1021 llvm::FCmpInst::FCMP_OEQ);
1022 case BinaryOperator::NE:
1023 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1024 llvm::ICmpInst::ICMP_NE,
1025 llvm::FCmpInst::FCMP_UNE);
1026 case BinaryOperator::Assign:
1027 return EmitBinaryAssign(E);
1028
1029 case BinaryOperator::MulAssign: {
1030 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1031 LValue LHSLV;
1032 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1033 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1034 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1035 }
1036 case BinaryOperator::DivAssign: {
1037 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1038 LValue LHSLV;
1039 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1040 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1041 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1042 }
1043 case BinaryOperator::RemAssign: {
1044 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1045 LValue LHSLV;
1046 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1047 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1048 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1049 }
1050 case BinaryOperator::AddAssign: {
1051 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1052 LValue LHSLV;
1053 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1054 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1055 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1056 }
1057 case BinaryOperator::SubAssign: {
1058 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1059 LValue LHSLV;
1060 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1061 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1062 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1063 }
1064 case BinaryOperator::ShlAssign: {
1065 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1066 LValue LHSLV;
1067 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1068 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1069 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1070 }
1071 case BinaryOperator::ShrAssign: {
1072 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1073 LValue LHSLV;
1074 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1075 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1076 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1077 }
1078 case BinaryOperator::AndAssign: {
1079 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1080 LValue LHSLV;
1081 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1082 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1083 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1084 }
1085 case BinaryOperator::OrAssign: {
1086 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1087 LValue LHSLV;
1088 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1089 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1090 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1091 }
1092 case BinaryOperator::XorAssign: {
1093 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1094 LValue LHSLV;
1095 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1096 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1097 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1098 }
1099 case BinaryOperator::Comma: return EmitBinaryComma(E);
1100 }
1101}
1102
1103RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
1104 if (LHS.isScalar())
1105 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1106
1107 // Otherwise, this must be a complex number.
1108 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1109
1110 EmitLoadOfComplex(LHS, LHSR, LHSI);
1111 EmitLoadOfComplex(RHS, RHSR, RHSI);
1112
1113 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1114 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1115 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1116
1117 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1118 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1119 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1120
1121 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1122 EmitStoreOfComplex(ResR, ResI, Res);
1123 return RValue::getAggregate(Res);
1124}
1125
1126RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
1127 if (LHS.isScalar()) {
1128 llvm::Value *RV;
1129 if (LHS.getVal()->getType()->isFloatingPoint())
1130 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
1131 else if (ResTy->isUnsignedIntegerType())
1132 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1133 else
1134 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1135 return RValue::get(RV);
1136 }
1137 assert(0 && "FIXME: This doesn't handle complex operands yet");
1138}
1139
1140RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
1141 if (LHS.isScalar()) {
1142 llvm::Value *RV;
1143 // Rem in C can't be a floating point type: C99 6.5.5p2.
1144 if (ResTy->isUnsignedIntegerType())
1145 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1146 else
1147 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1148 return RValue::get(RV);
1149 }
1150
1151 assert(0 && "FIXME: This doesn't handle complex operands yet");
1152}
1153
1154RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
1155 if (LHS.isScalar())
1156 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
1157
1158 // Otherwise, this must be a complex number.
1159 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1160
1161 EmitLoadOfComplex(LHS, LHSR, LHSI);
1162 EmitLoadOfComplex(RHS, RHSR, RHSI);
1163
1164 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1165 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1166
1167 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1168 EmitStoreOfComplex(ResR, ResI, Res);
1169 return RValue::getAggregate(Res);
1170}
1171
1172RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1173 RValue RHS, QualType RHSTy,
1174 QualType ResTy) {
1175 llvm::Value *LHSValue = LHS.getVal();
1176 llvm::Value *RHSValue = RHS.getVal();
1177 if (LHSTy->isPointerType()) {
1178 // pointer + int
1179 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1180 } else {
1181 // int + pointer
1182 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1183 }
1184}
1185
1186RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
1187 if (LHS.isScalar())
1188 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1189
1190 assert(0 && "FIXME: This doesn't handle complex operands yet");
1191}
1192
1193RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1194 RValue RHS, QualType RHSTy,
1195 QualType ResTy) {
1196 llvm::Value *LHSValue = LHS.getVal();
1197 llvm::Value *RHSValue = RHS.getVal();
1198 if (const PointerType *RHSPtrType =
1199 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1200 // pointer - pointer
1201 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1202 QualType LHSElementType = LHSPtrType->getPointeeType();
1203 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1204 "can't subtract pointers with differing element types");
1205 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
1206 SourceLocation()) / 8;
1207 const llvm::Type *ResultType = ConvertType(ResTy);
1208 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1209 "sub.ptr.lhs.cast");
1210 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1211 "sub.ptr.rhs.cast");
1212 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1213 "sub.ptr.sub");
1214
1215 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1216 // remainder. As such, we handle common power-of-two cases here to generate
1217 // better code.
1218 if (llvm::isPowerOf2_64(ElementSize)) {
1219 llvm::Value *ShAmt =
1220 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1221 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1222 } else {
1223 // Otherwise, do a full sdiv.
1224 llvm::Value *BytesPerElement =
1225 llvm::ConstantInt::get(ResultType, ElementSize);
1226 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1227 "sub.ptr.div"));
1228 }
1229 } else {
1230 // pointer - int
1231 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1232 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1233 }
1234}
1235
Chris Lattner4b009652007-07-25 00:24:17 +00001236RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1237 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1238
1239 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1240 // RHS to the same size as the LHS.
1241 if (LHS->getType() != RHS->getType())
1242 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1243
1244 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1245}
1246
1247RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1248 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1249
1250 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1251 // RHS to the same size as the LHS.
1252 if (LHS->getType() != RHS->getType())
1253 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1254
1255 if (ResTy->isUnsignedIntegerType())
1256 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1257 else
1258 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1259}
1260
1261RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1262 unsigned UICmpOpc, unsigned SICmpOpc,
1263 unsigned FCmpOpc) {
Chris Lattnerbf49e992007-08-08 17:49:18 +00001264 RValue LHS = EmitExpr(E->getLHS());
1265 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001266
1267 llvm::Value *Result;
1268 if (LHS.isScalar()) {
1269 if (LHS.getVal()->getType()->isFloatingPoint()) {
1270 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1271 LHS.getVal(), RHS.getVal(), "cmp");
1272 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1273 // FIXME: This check isn't right for "unsigned short < int" where ushort
1274 // promotes to int and does a signed compare.
1275 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1276 LHS.getVal(), RHS.getVal(), "cmp");
1277 } else {
1278 // Signed integers and pointers.
1279 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1280 LHS.getVal(), RHS.getVal(), "cmp");
1281 }
1282 } else {
1283 // Struct/union/complex
1284 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1285 EmitLoadOfComplex(LHS, LHSR, LHSI);
1286 EmitLoadOfComplex(RHS, RHSR, RHSI);
1287
1288 // FIXME: need to consider _Complex over integers too!
1289
1290 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1291 LHSR, RHSR, "cmp.r");
1292 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1293 LHSI, RHSI, "cmp.i");
1294 if (BinaryOperator::EQ == E->getOpcode()) {
1295 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1296 } else if (BinaryOperator::NE == E->getOpcode()) {
1297 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1298 } else {
1299 assert(0 && "Complex comparison other than == or != ?");
1300 }
1301 }
1302
1303 // ZExt result to int.
1304 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1305}
1306
1307RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
1308 if (LHS.isScalar())
1309 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1310
1311 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1312}
1313
1314RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
1315 if (LHS.isScalar())
1316 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1317
1318 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1319}
1320
1321RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
1322 if (LHS.isScalar())
1323 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1324
1325 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1326}
1327
1328RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1329 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1330
1331 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1332 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1333
1334 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1335 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1336
1337 EmitBlock(RHSBlock);
1338 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1339
1340 // Reaquire the RHS block, as there may be subblocks inserted.
1341 RHSBlock = Builder.GetInsertBlock();
1342 EmitBlock(ContBlock);
1343
1344 // Create a PHI node. If we just evaluted the LHS condition, the result is
1345 // false. If we evaluated both, the result is the RHS condition.
1346 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1347 PN->reserveOperandSpace(2);
1348 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1349 PN->addIncoming(RHSCond, RHSBlock);
1350
1351 // ZExt result to int.
1352 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1353}
1354
1355RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1356 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1357
1358 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1359 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1360
1361 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1362 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1363
1364 EmitBlock(RHSBlock);
1365 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1366
1367 // Reaquire the RHS block, as there may be subblocks inserted.
1368 RHSBlock = Builder.GetInsertBlock();
1369 EmitBlock(ContBlock);
1370
1371 // Create a PHI node. If we just evaluted the LHS condition, the result is
1372 // true. If we evaluated both, the result is the RHS condition.
1373 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1374 PN->reserveOperandSpace(2);
1375 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1376 PN->addIncoming(RHSCond, RHSBlock);
1377
1378 // ZExt result to int.
1379 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1380}
1381
1382RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +00001383 assert(E->getLHS()->getType().getCanonicalType() ==
1384 E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
Chris Lattner4b009652007-07-25 00:24:17 +00001385 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner2af72ac2007-08-08 17:43:05 +00001386 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001387
1388 // Store the value into the LHS.
1389 EmitStoreThroughLValue(RHS, LHS, E->getType());
1390
1391 // Return the converted RHS.
1392 return RHS;
1393}
1394
1395
1396RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1397 EmitExpr(E->getLHS());
1398 return EmitExpr(E->getRHS());
1399}
1400
1401RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1402 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1403 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1404 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1405
1406 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1407 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1408
1409 // FIXME: Implement this for aggregate values.
1410
Chris Lattner4b009652007-07-25 00:24:17 +00001411 EmitBlock(LHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001412 // Handle the GNU extension for missing LHS.
1413 llvm::Value *LHSValue = E->getLHS() ? EmitExpr(E->getLHS()).getVal() : Cond;
Chris Lattner4b009652007-07-25 00:24:17 +00001414 Builder.CreateBr(ContBlock);
1415 LHSBlock = Builder.GetInsertBlock();
1416
1417 EmitBlock(RHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001418
1419 llvm::Value *RHSValue = EmitExpr(E->getRHS()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +00001420 Builder.CreateBr(ContBlock);
1421 RHSBlock = Builder.GetInsertBlock();
1422
1423 const llvm::Type *LHSType = LHSValue->getType();
1424 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1425
1426 EmitBlock(ContBlock);
1427 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1428 PN->reserveOperandSpace(2);
1429 PN->addIncoming(LHSValue, LHSBlock);
1430 PN->addIncoming(RHSValue, RHSBlock);
1431
1432 return RValue::get(PN);
1433}