blob: 64067e79ee7b8e951887fbe384caf10e611fbd8f [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"
Anders Carlsson49865302007-08-20 18:05:56 +000017#include "clang/Lex/IdentifierTable.h"
Chris Lattner4b009652007-07-25 00:24:17 +000018#include "llvm/Constants.h"
19#include "llvm/DerivedTypes.h"
20#include "llvm/Function.h"
21#include "llvm/GlobalVariable.h"
22#include "llvm/Support/MathExtras.h"
23using namespace clang;
24using namespace CodeGen;
25
26//===--------------------------------------------------------------------===//
27// Miscellaneous Helper Methods
28//===--------------------------------------------------------------------===//
29
30/// CreateTempAlloca - This creates a alloca and inserts it into the entry
31/// block.
32llvm::AllocaInst *CodeGenFunction::CreateTempAlloca(const llvm::Type *Ty,
33 const char *Name) {
34 return new llvm::AllocaInst(Ty, 0, Name, AllocaInsertPt);
35}
36
37/// EvaluateExprAsBool - Perform the usual unary conversions on the specified
38/// expression and compare the result against zero, returning an Int1Ty value.
39llvm::Value *CodeGenFunction::EvaluateExprAsBool(const Expr *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +000040 return ConvertScalarValueToBool(EmitExpr(E), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +000041}
42
Chris Lattner4b009652007-07-25 00:24:17 +000043//===--------------------------------------------------------------------===//
44// Conversions
45//===--------------------------------------------------------------------===//
46
47/// EmitConversion - Convert the value specied by Val, whose type is ValTy, to
48/// the type specified by DstTy, following the rules of C99 6.3.
49RValue CodeGenFunction::EmitConversion(RValue Val, QualType ValTy,
50 QualType DstTy) {
51 ValTy = ValTy.getCanonicalType();
52 DstTy = DstTy.getCanonicalType();
53 if (ValTy == DstTy) return Val;
54
55 // Handle conversions to bool first, they are special: comparisons against 0.
56 if (const BuiltinType *DestBT = dyn_cast<BuiltinType>(DstTy))
57 if (DestBT->getKind() == BuiltinType::Bool)
58 return RValue::get(ConvertScalarValueToBool(Val, ValTy));
59
60 // Handle pointer conversions next: pointers can only be converted to/from
61 // other pointers and integers.
62 if (isa<PointerType>(DstTy)) {
63 const llvm::Type *DestTy = ConvertType(DstTy);
64
Chris Lattner2a420172007-08-10 16:33:59 +000065 if (Val.getVal()->getType() == DestTy)
66 return Val;
67
Chris Lattner4b009652007-07-25 00:24:17 +000068 // The source value may be an integer, or a pointer.
69 assert(Val.isScalar() && "Can only convert from integer or pointer");
70 if (isa<llvm::PointerType>(Val.getVal()->getType()))
71 return RValue::get(Builder.CreateBitCast(Val.getVal(), DestTy, "conv"));
72 assert(ValTy->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
73 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
74 }
75
76 if (isa<PointerType>(ValTy)) {
77 // Must be an ptr to int cast.
78 const llvm::Type *DestTy = ConvertType(DstTy);
79 assert(isa<llvm::IntegerType>(DestTy) && "not ptr->int?");
80 return RValue::get(Builder.CreateIntToPtr(Val.getVal(), DestTy, "conv"));
81 }
82
83 // Finally, we have the arithmetic types: real int/float and complex
84 // int/float. Handle real->real conversions first, they are the most
85 // common.
86 if (Val.isScalar() && DstTy->isRealType()) {
87 // We know that these are representable as scalars in LLVM, convert to LLVM
88 // types since they are easier to reason about.
89 llvm::Value *SrcVal = Val.getVal();
90 const llvm::Type *DestTy = ConvertType(DstTy);
91 if (SrcVal->getType() == DestTy) return Val;
92
93 llvm::Value *Result;
94 if (isa<llvm::IntegerType>(SrcVal->getType())) {
95 bool InputSigned = ValTy->isSignedIntegerType();
96 if (isa<llvm::IntegerType>(DestTy))
97 Result = Builder.CreateIntCast(SrcVal, DestTy, InputSigned, "conv");
98 else if (InputSigned)
99 Result = Builder.CreateSIToFP(SrcVal, DestTy, "conv");
100 else
101 Result = Builder.CreateUIToFP(SrcVal, DestTy, "conv");
102 } else {
103 assert(SrcVal->getType()->isFloatingPoint() && "Unknown real conversion");
104 if (isa<llvm::IntegerType>(DestTy)) {
105 if (DstTy->isSignedIntegerType())
106 Result = Builder.CreateFPToSI(SrcVal, DestTy, "conv");
107 else
108 Result = Builder.CreateFPToUI(SrcVal, DestTy, "conv");
109 } else {
110 assert(DestTy->isFloatingPoint() && "Unknown real conversion");
111 if (DestTy->getTypeID() < SrcVal->getType()->getTypeID())
112 Result = Builder.CreateFPTrunc(SrcVal, DestTy, "conv");
113 else
114 Result = Builder.CreateFPExt(SrcVal, DestTy, "conv");
115 }
116 }
117 return RValue::get(Result);
118 }
119
120 assert(0 && "FIXME: We don't support complex conversions yet!");
121}
122
123
124/// ConvertScalarValueToBool - Convert the specified expression value to a
125/// boolean (i1) truth value. This is equivalent to "Val == 0".
126llvm::Value *CodeGenFunction::ConvertScalarValueToBool(RValue Val, QualType Ty){
127 Ty = Ty.getCanonicalType();
128 llvm::Value *Result;
129 if (const BuiltinType *BT = dyn_cast<BuiltinType>(Ty)) {
130 switch (BT->getKind()) {
131 default: assert(0 && "Unknown scalar value");
132 case BuiltinType::Bool:
133 Result = Val.getVal();
134 // Bool is already evaluated right.
135 assert(Result->getType() == llvm::Type::Int1Ty &&
136 "Unexpected bool value type!");
137 return Result;
138 case BuiltinType::Char_S:
139 case BuiltinType::Char_U:
140 case BuiltinType::SChar:
141 case BuiltinType::UChar:
142 case BuiltinType::Short:
143 case BuiltinType::UShort:
144 case BuiltinType::Int:
145 case BuiltinType::UInt:
146 case BuiltinType::Long:
147 case BuiltinType::ULong:
148 case BuiltinType::LongLong:
149 case BuiltinType::ULongLong:
150 // Code below handles simple integers.
151 break;
152 case BuiltinType::Float:
153 case BuiltinType::Double:
154 case BuiltinType::LongDouble: {
155 // Compare against 0.0 for fp scalars.
156 Result = Val.getVal();
157 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
158 // FIXME: llvm-gcc produces a une comparison: validate this is right.
159 Result = Builder.CreateFCmpUNE(Result, Zero, "tobool");
160 return Result;
161 }
162 }
163 } else if (isa<PointerType>(Ty) ||
164 cast<TagType>(Ty)->getDecl()->getKind() == Decl::Enum) {
165 // Code below handles this fine.
166 } else {
167 assert(isa<ComplexType>(Ty) && "Unknwon type!");
168 assert(0 && "FIXME: comparisons against complex not implemented yet");
169 }
170
171 // Usual case for integers, pointers, and enums: compare against zero.
172 Result = Val.getVal();
173
174 // Because of the type rules of C, we often end up computing a logical value,
175 // then zero extending it to int, then wanting it as a logical value again.
176 // Optimize this common case.
177 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Result)) {
178 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
179 Result = ZI->getOperand(0);
180 ZI->eraseFromParent();
181 return Result;
182 }
183 }
184
185 llvm::Value *Zero = llvm::Constant::getNullValue(Result->getType());
186 return Builder.CreateICmpNE(Result, Zero, "tobool");
187}
188
189//===----------------------------------------------------------------------===//
190// LValue Expression Emission
191//===----------------------------------------------------------------------===//
192
193/// EmitLValue - Emit code to compute a designator that specifies the location
194/// of the expression.
195///
196/// This can return one of two things: a simple address or a bitfield
197/// reference. In either case, the LLVM Value* in the LValue structure is
198/// guaranteed to be an LLVM pointer type.
199///
200/// If this returns a bitfield reference, nothing about the pointee type of
201/// the LLVM value is known: For example, it may not be a pointer to an
202/// integer.
203///
204/// If this returns a normal address, and if the lvalue's C type is fixed
205/// size, this method guarantees that the returned pointer type will point to
206/// an LLVM type of the same size of the lvalue's type. If the lvalue has a
207/// variable length type, this is not possible.
208///
209LValue CodeGenFunction::EmitLValue(const Expr *E) {
210 switch (E->getStmtClass()) {
211 default:
212 fprintf(stderr, "Unimplemented lvalue expr!\n");
213 E->dump();
214 return LValue::MakeAddr(llvm::UndefValue::get(
215 llvm::PointerType::get(llvm::Type::Int32Ty)));
216
217 case Expr::DeclRefExprClass: return EmitDeclRefLValue(cast<DeclRefExpr>(E));
218 case Expr::ParenExprClass:return EmitLValue(cast<ParenExpr>(E)->getSubExpr());
219 case Expr::PreDefinedExprClass:
220 return EmitPreDefinedLValue(cast<PreDefinedExpr>(E));
221 case Expr::StringLiteralClass:
222 return EmitStringLiteralLValue(cast<StringLiteral>(E));
223
224 case Expr::UnaryOperatorClass:
225 return EmitUnaryOpLValue(cast<UnaryOperator>(E));
226 case Expr::ArraySubscriptExprClass:
227 return EmitArraySubscriptExpr(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000228 case Expr::OCUVectorElementExprClass:
229 return EmitOCUVectorElementExpr(cast<OCUVectorElementExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000230 }
231}
232
233/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
234/// this method emits the address of the lvalue, then loads the result as an
235/// rvalue, returning the rvalue.
236RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
Chris Lattner4b009652007-07-25 00:24:17 +0000237 if (LV.isSimple()) {
238 llvm::Value *Ptr = LV.getAddress();
239 const llvm::Type *EltTy =
240 cast<llvm::PointerType>(Ptr->getType())->getElementType();
241
242 // Simple scalar l-value.
243 if (EltTy->isFirstClassType())
244 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
245
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000246 assert(ExprType->isFunctionType() && "Unknown scalar value");
247 return RValue::get(Ptr);
Chris Lattner4b009652007-07-25 00:24:17 +0000248 }
249
250 if (LV.isVectorElt()) {
251 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
252 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
253 "vecext"));
254 }
Chris Lattnera735fac2007-08-03 00:16:29 +0000255
256 // If this is a reference to a subset of the elements of a vector, either
257 // shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000258 if (LV.isOCUVectorElt())
259 return EmitLoadOfOCUElementLValue(LV, ExprType);
Chris Lattner4b009652007-07-25 00:24:17 +0000260
261 assert(0 && "Bitfield ref not impl!");
262}
263
Chris Lattner944f7962007-08-03 16:18:34 +0000264// If this is a reference to a subset of the elements of a vector, either
265// shuffle the input or extract/insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000266RValue CodeGenFunction::EmitLoadOfOCUElementLValue(LValue LV,
Chris Lattner4b492962007-08-10 17:10:08 +0000267 QualType ExprType) {
Chris Lattner944f7962007-08-03 16:18:34 +0000268 llvm::Value *Vec = Builder.CreateLoad(LV.getOCUVectorAddr(), "tmp");
269
Chris Lattnera0d03a72007-08-03 17:31:20 +0000270 unsigned EncFields = LV.getOCUVectorElts();
Chris Lattner944f7962007-08-03 16:18:34 +0000271
272 // If the result of the expression is a non-vector type, we must be
273 // extracting a single element. Just codegen as an extractelement.
Chris Lattner4b492962007-08-10 17:10:08 +0000274 const VectorType *ExprVT = ExprType->getAsVectorType();
275 if (!ExprVT) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000276 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000277 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
278 return RValue::get(Builder.CreateExtractElement(Vec, Elt, "tmp"));
279 }
280
281 // If the source and destination have the same number of elements, use a
282 // vector shuffle instead of insert/extracts.
Chris Lattner4b492962007-08-10 17:10:08 +0000283 unsigned NumResultElts = ExprVT->getNumElements();
Chris Lattner944f7962007-08-03 16:18:34 +0000284 unsigned NumSourceElts =
285 cast<llvm::VectorType>(Vec->getType())->getNumElements();
286
287 if (NumResultElts == NumSourceElts) {
288 llvm::SmallVector<llvm::Constant*, 4> Mask;
289 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000290 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000291 Mask.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx));
292 }
293
294 llvm::Value *MaskV = llvm::ConstantVector::get(&Mask[0], Mask.size());
295 Vec = Builder.CreateShuffleVector(Vec,
296 llvm::UndefValue::get(Vec->getType()),
297 MaskV, "tmp");
298 return RValue::get(Vec);
299 }
300
301 // Start out with an undef of the result type.
302 llvm::Value *Result = llvm::UndefValue::get(ConvertType(ExprType));
303
304 // Extract/Insert each element of the result.
305 for (unsigned i = 0; i != NumResultElts; ++i) {
Chris Lattnera0d03a72007-08-03 17:31:20 +0000306 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner944f7962007-08-03 16:18:34 +0000307 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
308 Elt = Builder.CreateExtractElement(Vec, Elt, "tmp");
309
310 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
311 Result = Builder.CreateInsertElement(Result, Elt, OutIdx, "tmp");
312 }
313
314 return RValue::get(Result);
315}
316
317
Chris Lattner4b009652007-07-25 00:24:17 +0000318RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
319 return EmitLoadOfLValue(EmitLValue(E), E->getType());
320}
321
322
323/// EmitStoreThroughLValue - Store the specified rvalue into the specified
324/// lvalue, where both are guaranteed to the have the same type, and that type
325/// is 'Ty'.
326void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
327 QualType Ty) {
Chris Lattner5bfdd232007-08-03 16:28:33 +0000328 if (!Dst.isSimple()) {
329 if (Dst.isVectorElt()) {
330 // Read/modify/write the vector, inserting the new element.
331 // FIXME: Volatility.
332 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
333 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
334 Dst.getVectorIdx(), "vecins");
335 Builder.CreateStore(Vec, Dst.getVectorAddr());
336 return;
337 }
Chris Lattner4b009652007-07-25 00:24:17 +0000338
Chris Lattner5bfdd232007-08-03 16:28:33 +0000339 // If this is an update of elements of a vector, insert them as appropriate.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000340 if (Dst.isOCUVectorElt())
Chris Lattner5bfdd232007-08-03 16:28:33 +0000341 return EmitStoreThroughOCUComponentLValue(Src, Dst, Ty);
342
343 assert(0 && "FIXME: Don't support store to bitfield yet");
344 }
Chris Lattner4b009652007-07-25 00:24:17 +0000345
346 llvm::Value *DstAddr = Dst.getAddress();
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000347 assert(Src.isScalar() && "Can't emit an agg store with this method");
348 // FIXME: Handle volatility etc.
349 const llvm::Type *SrcTy = Src.getVal()->getType();
350 const llvm::Type *AddrTy =
351 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
Chris Lattner4b009652007-07-25 00:24:17 +0000352
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000353 if (AddrTy != SrcTy)
354 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
355 "storetmp");
356 Builder.CreateStore(Src.getVal(), DstAddr);
Chris Lattner4b009652007-07-25 00:24:17 +0000357}
358
Chris Lattner5bfdd232007-08-03 16:28:33 +0000359void CodeGenFunction::EmitStoreThroughOCUComponentLValue(RValue Src, LValue Dst,
360 QualType Ty) {
361 // This access turns into a read/modify/write of the vector. Load the input
362 // value now.
363 llvm::Value *Vec = Builder.CreateLoad(Dst.getOCUVectorAddr(), "tmp");
364 // FIXME: Volatility.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000365 unsigned EncFields = Dst.getOCUVectorElts();
Chris Lattner5bfdd232007-08-03 16:28:33 +0000366
367 llvm::Value *SrcVal = Src.getVal();
368
Chris Lattner940966d2007-08-03 16:37:04 +0000369 if (const VectorType *VTy = Ty->getAsVectorType()) {
370 unsigned NumSrcElts = VTy->getNumElements();
371
372 // Extract/Insert each element.
373 for (unsigned i = 0; i != NumSrcElts; ++i) {
374 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
375 Elt = Builder.CreateExtractElement(SrcVal, Elt, "tmp");
376
Chris Lattnera0d03a72007-08-03 17:31:20 +0000377 unsigned Idx = OCUVectorElementExpr::getAccessedFieldNo(i, EncFields);
Chris Lattner940966d2007-08-03 16:37:04 +0000378 llvm::Value *OutIdx = llvm::ConstantInt::get(llvm::Type::Int32Ty, Idx);
379 Vec = Builder.CreateInsertElement(Vec, Elt, OutIdx, "tmp");
380 }
381 } else {
382 // If the Src is a scalar (not a vector) it must be updating one element.
Chris Lattnera0d03a72007-08-03 17:31:20 +0000383 unsigned InIdx = OCUVectorElementExpr::getAccessedFieldNo(0, EncFields);
Chris Lattner5bfdd232007-08-03 16:28:33 +0000384 llvm::Value *Elt = llvm::ConstantInt::get(llvm::Type::Int32Ty, InIdx);
385 Vec = Builder.CreateInsertElement(Vec, SrcVal, Elt, "tmp");
Chris Lattner5bfdd232007-08-03 16:28:33 +0000386 }
387
Chris Lattner5bfdd232007-08-03 16:28:33 +0000388 Builder.CreateStore(Vec, Dst.getOCUVectorAddr());
389}
390
Chris Lattner4b009652007-07-25 00:24:17 +0000391
392LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
393 const Decl *D = E->getDecl();
394 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
395 llvm::Value *V = LocalDeclMap[D];
396 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
397 return LValue::MakeAddr(V);
398 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
399 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
400 }
401 assert(0 && "Unimp declref");
402}
403
404LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
405 // __extension__ doesn't affect lvalue-ness.
406 if (E->getOpcode() == UnaryOperator::Extension)
407 return EmitLValue(E->getSubExpr());
408
409 assert(E->getOpcode() == UnaryOperator::Deref &&
410 "'*' is the only unary operator that produces an lvalue");
411 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
412}
413
414LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
415 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
416 const char *StrData = E->getStrData();
417 unsigned Len = E->getByteLength();
418
419 // FIXME: Can cache/reuse these within the module.
420 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
421
422 // Create a global variable for this.
423 C = new llvm::GlobalVariable(C->getType(), true,
424 llvm::GlobalValue::InternalLinkage,
425 C, ".str", CurFn->getParent());
426 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
427 llvm::Constant *Zeros[] = { Zero, Zero };
428 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
429 return LValue::MakeAddr(C);
430}
431
432LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
433 std::string FunctionName(CurFuncDecl->getName());
434 std::string GlobalVarName;
435
436 switch (E->getIdentType()) {
437 default:
438 assert(0 && "unknown pre-defined ident type");
439 case PreDefinedExpr::Func:
440 GlobalVarName = "__func__.";
441 break;
442 case PreDefinedExpr::Function:
443 GlobalVarName = "__FUNCTION__.";
444 break;
445 case PreDefinedExpr::PrettyFunction:
446 // FIXME:: Demangle C++ method names
447 GlobalVarName = "__PRETTY_FUNCTION__.";
448 break;
449 }
450
451 GlobalVarName += CurFuncDecl->getName();
452
453 // FIXME: Can cache/reuse these within the module.
454 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
455
456 // Create a global variable for this.
457 C = new llvm::GlobalVariable(C->getType(), true,
458 llvm::GlobalValue::InternalLinkage,
459 C, GlobalVarName, CurFn->getParent());
460 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
461 llvm::Constant *Zeros[] = { Zero, Zero };
462 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
463 return LValue::MakeAddr(C);
464}
465
466LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000467 // The index must always be an integer, which is not an aggregate. Emit it.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000468 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000469
470 // If the base is a vector type, then we are forming a vector element lvalue
471 // with this subscript.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000472 if (E->getLHS()->getType()->isVectorType()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000473 // Emit the vector as an lvalue to get its address.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000474 LValue LHS = EmitLValue(E->getLHS());
475 assert(LHS.isSimple() && "Can only subscript lvalue vectors here!");
Chris Lattner4b009652007-07-25 00:24:17 +0000476 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000477 return LValue::MakeVectorElt(LHS.getAddress(), Idx);
Chris Lattner4b009652007-07-25 00:24:17 +0000478 }
479
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000480 // The base must be a pointer, which is not an aggregate. Emit it.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000481 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000482
Ted Kremenek1c1700f2007-08-20 16:18:38 +0000483 // Extend or truncate the index type to 32 or 64-bits.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000484 QualType IdxTy = E->getIdx()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000485 bool IdxSigned = IdxTy->isSignedIntegerType();
486 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
487 if (IdxBitwidth != LLVMPointerWidth)
488 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
489 IdxSigned, "idxprom");
490
491 // We know that the pointer points to a type of the correct size, unless the
492 // size is a VLA.
493 if (!E->getType()->isConstantSizeType(getContext()))
494 assert(0 && "VLA idx not implemented");
495 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
496}
497
Chris Lattner65520192007-08-02 23:37:31 +0000498LValue CodeGenFunction::
Chris Lattnera0d03a72007-08-03 17:31:20 +0000499EmitOCUVectorElementExpr(const OCUVectorElementExpr *E) {
Chris Lattner65520192007-08-02 23:37:31 +0000500 // Emit the base vector as an l-value.
501 LValue Base = EmitLValue(E->getBase());
502 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
503
Chris Lattnera0d03a72007-08-03 17:31:20 +0000504 return LValue::MakeOCUVectorElt(Base.getAddress(),
505 E->getEncodedElementAccess());
Chris Lattner65520192007-08-02 23:37:31 +0000506}
507
Chris Lattner4b009652007-07-25 00:24:17 +0000508//===--------------------------------------------------------------------===//
509// Expression Emission
510//===--------------------------------------------------------------------===//
511
Chris Lattner348c8a22007-08-23 23:43:33 +0000512/// EmitAnyExpr - Emit an expression of any type: scalar, complex, aggregate,
513/// returning an rvalue corresponding to it. If NeedResult is false, the
514/// result of the expression doesn't need to be generated into memory.
515RValue CodeGenFunction::EmitAnyExpr(const Expr *E, bool NeedResult) {
516 if (!hasAggregateLLVMType(E->getType()))
517 return EmitExpr(E);
518
519 llvm::Value *DestMem = 0;
520 if (NeedResult)
521 DestMem = CreateTempAlloca(ConvertType(E->getType()));
522
523 if (!E->getType()->isComplexType()) {
524 EmitAggExpr(E, DestMem, false);
525 } else if (NeedResult)
526 EmitComplexExprIntoAddr(E, DestMem);
527 else
528 EmitComplexExpr(E);
529
530 return RValue::getAggregate(DestMem);
531}
532
Chris Lattner4b009652007-07-25 00:24:17 +0000533RValue CodeGenFunction::EmitExpr(const Expr *E) {
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +0000534 assert(E && !hasAggregateLLVMType(E->getType()) &&
535 "Invalid scalar expression to emit");
Chris Lattner4b009652007-07-25 00:24:17 +0000536
537 switch (E->getStmtClass()) {
538 default:
539 fprintf(stderr, "Unimplemented expr!\n");
540 E->dump();
541 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
542
543 // l-values.
544 case Expr::DeclRefExprClass:
545 // DeclRef's of EnumConstantDecl's are simple rvalues.
546 if (const EnumConstantDecl *EC =
547 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
548 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
549 return EmitLoadOfLValue(E);
550 case Expr::ArraySubscriptExprClass:
551 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Chris Lattnera0d03a72007-08-03 17:31:20 +0000552 case Expr::OCUVectorElementExprClass:
Chris Lattnera735fac2007-08-03 00:16:29 +0000553 return EmitLoadOfLValue(E);
Chris Lattner4b009652007-07-25 00:24:17 +0000554 case Expr::PreDefinedExprClass:
555 case Expr::StringLiteralClass:
556 return RValue::get(EmitLValue(E).getAddress());
557
558 // Leaf expressions.
559 case Expr::IntegerLiteralClass:
560 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
561 case Expr::FloatingLiteralClass:
562 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
563 case Expr::CharacterLiteralClass:
564 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Chris Lattner4ca7e752007-08-03 17:51:03 +0000565 case Expr::TypesCompatibleExprClass:
566 return EmitTypesCompatibleExpr(cast<TypesCompatibleExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000567
568 // Operators.
569 case Expr::ParenExprClass:
570 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
571 case Expr::UnaryOperatorClass:
572 return EmitUnaryOperator(cast<UnaryOperator>(E));
573 case Expr::SizeOfAlignOfTypeExprClass:
574 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
575 E->getType(),
576 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
577 case Expr::ImplicitCastExprClass:
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000578 return EmitImplicitCastExpr(cast<ImplicitCastExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000579 case Expr::CastExprClass:
580 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
581 case Expr::CallExprClass:
582 return EmitCallExpr(cast<CallExpr>(E));
583 case Expr::BinaryOperatorClass:
584 return EmitBinaryOperator(cast<BinaryOperator>(E));
585
586 case Expr::ConditionalOperatorClass:
587 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Chris Lattner44fcf4f2007-08-04 00:20:15 +0000588 case Expr::ChooseExprClass:
589 return EmitChooseExpr(cast<ChooseExpr>(E));
Anders Carlssona66cad42007-08-21 17:43:55 +0000590 case Expr::ObjCStringLiteralClass:
591 return EmitObjCStringLiteral(cast<ObjCStringLiteral>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000592 }
Chris Lattner4b009652007-07-25 00:24:17 +0000593}
594
595RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
596 return RValue::get(llvm::ConstantInt::get(E->getValue()));
597}
598RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
599 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
600 E->getValue()));
601}
602RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
603 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
604 E->getValue()));
605}
606
Chris Lattner4ca7e752007-08-03 17:51:03 +0000607RValue CodeGenFunction::EmitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
608 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
609 E->typesAreCompatible()));
610}
611
Chris Lattner44fcf4f2007-08-04 00:20:15 +0000612/// EmitChooseExpr - Implement __builtin_choose_expr.
613RValue CodeGenFunction::EmitChooseExpr(const ChooseExpr *E) {
614 llvm::APSInt CondVal(32);
615 bool IsConst = E->getCond()->isIntegerConstantExpr(CondVal, getContext());
616 assert(IsConst && "Condition of choose expr must be i-c-e"); IsConst=IsConst;
617
618 // Emit the LHS or RHS as appropriate.
619 return EmitExpr(CondVal != 0 ? E->getLHS() : E->getRHS());
620}
621
Chris Lattner4ca7e752007-08-03 17:51:03 +0000622
Chris Lattner4b009652007-07-25 00:24:17 +0000623RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
624 // Emit subscript expressions in rvalue context's. For most cases, this just
625 // loads the lvalue formed by the subscript expr. However, we have to be
626 // careful, because the base of a vector subscript is occasionally an rvalue,
627 // so we can't get it as an lvalue.
628 if (!E->getBase()->getType()->isVectorType())
629 return EmitLoadOfLValue(E);
630
631 // Handle the vector case. The base must be a vector, the index must be an
632 // integer value.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000633 llvm::Value *Base = EmitExpr(E->getBase()).getVal();
634 llvm::Value *Idx = EmitExpr(E->getIdx()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000635
636 // FIXME: Convert Idx to i32 type.
637
638 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
639}
640
641// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
642// have to handle a more broad range of conversions than explicit casts, as they
643// handle things like function to ptr-to-function decay etc.
644RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000645 RValue Src = EmitExpr(Op);
Chris Lattner4b009652007-07-25 00:24:17 +0000646
647 // If the destination is void, just evaluate the source.
648 if (DestTy->isVoidType())
649 return RValue::getAggregate(0);
650
Chris Lattner2af72ac2007-08-08 17:43:05 +0000651 return EmitConversion(Src, Op->getType(), DestTy);
Chris Lattner4b009652007-07-25 00:24:17 +0000652}
653
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000654/// EmitImplicitCastExpr - Implicit casts are the same as normal casts, but also
655/// handle things like function to pointer-to-function decay, and array to
656/// pointer decay.
657RValue CodeGenFunction::EmitImplicitCastExpr(const ImplicitCastExpr *E) {
658 const Expr *Op = E->getSubExpr();
659 QualType OpTy = Op->getType().getCanonicalType();
660
661 // If this is due to array->pointer conversion, emit the array expression as
662 // an l-value.
663 if (isa<ArrayType>(OpTy)) {
664 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
665 // will not true when we add support for VLAs.
666 llvm::Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
667
668 assert(isa<llvm::PointerType>(V->getType()) &&
669 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
670 ->getElementType()) &&
671 "Doesn't support VLAs yet!");
672 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
673 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
674 }
675
676 return EmitCastExpr(Op, E->getType());
677}
678
Chris Lattner4b009652007-07-25 00:24:17 +0000679RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson49865302007-08-20 18:05:56 +0000680 if (const ImplicitCastExpr *IcExpr =
681 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
682 if (const DeclRefExpr *DRExpr =
683 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
684 if (const FunctionDecl *FDecl =
685 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
686 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
687 return EmitBuiltinExpr(builtinID, E);
688
Chris Lattner2af72ac2007-08-08 17:43:05 +0000689 llvm::Value *Callee = EmitExpr(E->getCallee()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000690
691 // The callee type will always be a pointer to function type, get the function
692 // type.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000693 QualType CalleeTy = E->getCallee()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000694 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
695
696 // Get information about the argument types.
697 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
698
699 // Calling unprototyped functions provides no argument info.
700 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
701 ArgTyIt = FTP->arg_type_begin();
702 ArgTyEnd = FTP->arg_type_end();
703 }
704
705 llvm::SmallVector<llvm::Value*, 16> Args;
706
Chris Lattner59802042007-08-10 17:02:28 +0000707 // Handle struct-return functions by passing a pointer to the location that
708 // we would like to return into.
709 if (hasAggregateLLVMType(E->getType())) {
710 // Create a temporary alloca to hold the result of the call. :(
711 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
712 // FIXME: set the stret attribute on the argument.
713 }
714
Chris Lattner4b009652007-07-25 00:24:17 +0000715 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000716 QualType ArgTy = E->getArg(i)->getType();
Chris Lattner348c8a22007-08-23 23:43:33 +0000717 RValue ArgVal = EmitAnyExpr(E->getArg(i));
Chris Lattner4b009652007-07-25 00:24:17 +0000718
719 // If this argument has prototype information, convert it.
720 if (ArgTyIt != ArgTyEnd) {
721 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
722 } else {
723 // Otherwise, if passing through "..." or to a function with no prototype,
724 // perform the "default argument promotions" (C99 6.5.2.2p6), which
725 // includes the usual unary conversions, but also promotes float to
726 // double.
727 if (const BuiltinType *BT =
728 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
729 if (BT->getKind() == BuiltinType::Float)
730 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
731 llvm::Type::DoubleTy,"tmp"));
732 }
733 }
734
Chris Lattner4b009652007-07-25 00:24:17 +0000735 if (ArgVal.isScalar())
736 Args.push_back(ArgVal.getVal());
737 else // Pass by-address. FIXME: Set attribute bit on call.
738 Args.push_back(ArgVal.getAggregateAddr());
739 }
740
Chris Lattnera9572252007-08-01 06:24:52 +0000741 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000742 if (V->getType() != llvm::Type::VoidTy)
743 V->setName("call");
Chris Lattner59802042007-08-10 17:02:28 +0000744 else if (hasAggregateLLVMType(E->getType()))
745 // Struct return.
746 return RValue::getAggregate(Args[0]);
747
Chris Lattner4b009652007-07-25 00:24:17 +0000748 return RValue::get(V);
749}
750
751
752//===----------------------------------------------------------------------===//
753// Unary Operator Emission
754//===----------------------------------------------------------------------===//
755
Chris Lattner4b009652007-07-25 00:24:17 +0000756RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
757 switch (E->getOpcode()) {
758 default:
759 printf("Unimplemented unary expr!\n");
760 E->dump();
761 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
762 case UnaryOperator::PostInc:
763 case UnaryOperator::PostDec:
764 case UnaryOperator::PreInc :
765 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
766 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
767 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
768 case UnaryOperator::Plus : return EmitUnaryPlus(E);
769 case UnaryOperator::Minus : return EmitUnaryMinus(E);
770 case UnaryOperator::Not : return EmitUnaryNot(E);
771 case UnaryOperator::LNot : return EmitUnaryLNot(E);
772 case UnaryOperator::SizeOf :
773 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
774 case UnaryOperator::AlignOf :
775 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
776 // FIXME: real/imag
777 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
778 }
779}
780
781RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
782 LValue LV = EmitLValue(E->getSubExpr());
783 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
784
785 // We know the operand is real or pointer type, so it must be an LLVM scalar.
786 assert(InVal.isScalar() && "Unknown thing to increment");
787 llvm::Value *InV = InVal.getVal();
788
789 int AmountVal = 1;
790 if (E->getOpcode() == UnaryOperator::PreDec ||
791 E->getOpcode() == UnaryOperator::PostDec)
792 AmountVal = -1;
793
794 llvm::Value *NextVal;
795 if (isa<llvm::IntegerType>(InV->getType())) {
796 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
797 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
798 } else if (InV->getType()->isFloatingPoint()) {
799 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
800 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
801 } else {
802 // FIXME: This is not right for pointers to VLA types.
803 assert(isa<llvm::PointerType>(InV->getType()));
804 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
805 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
806 }
807
808 RValue NextValToStore = RValue::get(NextVal);
809
810 // Store the updated result through the lvalue.
811 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
812
813 // If this is a postinc, return the value read from memory, otherwise use the
814 // updated value.
815 if (E->getOpcode() == UnaryOperator::PreDec ||
816 E->getOpcode() == UnaryOperator::PreInc)
817 return NextValToStore;
818 else
819 return InVal;
820}
821
822/// C99 6.5.3.2
823RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
824 // The address of the operand is just its lvalue. It cannot be a bitfield.
825 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
826}
827
828RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000829 assert(E->getType().getCanonicalType() ==
830 E->getSubExpr()->getType().getCanonicalType() && "Bad unary plus!");
831 // Unary plus just returns its value.
832 return EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000833}
834
835RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000836 assert(E->getType().getCanonicalType() ==
837 E->getSubExpr()->getType().getCanonicalType() && "Bad unary minus!");
838
Chris Lattner4b009652007-07-25 00:24:17 +0000839 // Unary minus performs promotions, then negates its arithmetic operand.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000840 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000841
842 if (V.isScalar())
843 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
844
845 assert(0 && "FIXME: This doesn't handle complex operands yet");
846}
847
848RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
849 // Unary not performs promotions, then complements its integer operand.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000850 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000851
852 if (V.isScalar())
853 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
854
855 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
856}
857
858
859/// C99 6.5.3.3
860RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
861 // Compare operand to zero.
862 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
863
864 // Invert value.
865 // TODO: Could dynamically modify easy computations here. For example, if
866 // the operand is an icmp ne, turn into icmp eq.
867 BoolVal = Builder.CreateNot(BoolVal, "lnot");
868
869 // ZExt result to int.
870 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
871}
872
873/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
874/// an integer (RetType).
875RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
876 QualType RetType, bool isSizeOf) {
877 /// FIXME: This doesn't handle VLAs yet!
878 std::pair<uint64_t, unsigned> Info =
879 getContext().getTypeInfo(TypeToSize, SourceLocation());
880
881 uint64_t Val = isSizeOf ? Info.first : Info.second;
882 Val /= 8; // Return size in bytes, not bits.
883
884 assert(RetType->isIntegerType() && "Result type must be an integer!");
885
886 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
887 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
888}
889
890
891//===--------------------------------------------------------------------===//
892// Binary Operator Emission
893//===--------------------------------------------------------------------===//
894
Chris Lattner4b009652007-07-25 00:24:17 +0000895
896/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
897/// are strange in that the result of the operation is not the same type as the
898/// intermediate computation. This function emits the LHS and RHS operands of
899/// the compound assignment, promoting them to their common computation type.
900///
901/// Since the LHS is an lvalue, and the result is stored back through it, we
902/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
903/// RHS values are both in the computation type for the operator.
904void CodeGenFunction::
905EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
906 LValue &LHSLV, RValue &LHS, RValue &RHS) {
907 LHSLV = EmitLValue(E->getLHS());
908
909 // Load the LHS and RHS operands.
910 QualType LHSTy = E->getLHS()->getType();
911 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner2af72ac2007-08-08 17:43:05 +0000912 RHS = EmitExpr(E->getRHS());
913 QualType RHSTy = E->getRHS()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000914
915 // Convert the LHS and RHS to the common evaluation type.
916 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
917 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
918}
919
920/// EmitCompoundAssignmentResult - Given a result value in the computation type,
921/// truncate it down to the actual result type, store it through the LHS lvalue,
922/// and return it.
923RValue CodeGenFunction::
924EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
925 LValue LHSLV, RValue ResV) {
926
927 // Truncate back to the destination type.
928 if (E->getComputationType() != E->getType())
929 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
930
931 // Store the result value into the LHS.
932 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
933
934 // Return the result.
935 return ResV;
936}
937
938
939RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
940 RValue LHS, RHS;
941 switch (E->getOpcode()) {
942 default:
943 fprintf(stderr, "Unimplemented binary expr!\n");
944 E->dump();
945 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
946 case BinaryOperator::Mul:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000947 LHS = EmitExpr(E->getLHS());
948 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000949 return EmitMul(LHS, RHS, E->getType());
950 case BinaryOperator::Div:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000951 LHS = EmitExpr(E->getLHS());
952 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000953 return EmitDiv(LHS, RHS, E->getType());
954 case BinaryOperator::Rem:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000955 LHS = EmitExpr(E->getLHS());
956 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000957 return EmitRem(LHS, RHS, E->getType());
Chris Lattnerbf49e992007-08-08 17:49:18 +0000958 case BinaryOperator::Add:
959 LHS = EmitExpr(E->getLHS());
960 RHS = EmitExpr(E->getRHS());
961 if (!E->getType()->isPointerType())
962 return EmitAdd(LHS, RHS, E->getType());
963
964 return EmitPointerAdd(LHS, E->getLHS()->getType(),
965 RHS, E->getRHS()->getType(), E->getType());
966 case BinaryOperator::Sub:
967 LHS = EmitExpr(E->getLHS());
968 RHS = EmitExpr(E->getRHS());
969
970 if (!E->getLHS()->getType()->isPointerType())
971 return EmitSub(LHS, RHS, E->getType());
972
973 return EmitPointerSub(LHS, E->getLHS()->getType(),
974 RHS, E->getRHS()->getType(), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +0000975 case BinaryOperator::Shl:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000976 LHS = EmitExpr(E->getLHS());
977 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000978 return EmitShl(LHS, RHS, E->getType());
979 case BinaryOperator::Shr:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000980 LHS = EmitExpr(E->getLHS());
981 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000982 return EmitShr(LHS, RHS, E->getType());
983 case BinaryOperator::And:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000984 LHS = EmitExpr(E->getLHS());
985 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000986 return EmitAnd(LHS, RHS, E->getType());
987 case BinaryOperator::Xor:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000988 LHS = EmitExpr(E->getLHS());
989 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000990 return EmitXor(LHS, RHS, E->getType());
991 case BinaryOperator::Or :
Chris Lattnerbf49e992007-08-08 17:49:18 +0000992 LHS = EmitExpr(E->getLHS());
993 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000994 return EmitOr(LHS, RHS, E->getType());
995 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
996 case BinaryOperator::LOr: return EmitBinaryLOr(E);
997 case BinaryOperator::LT:
998 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
999 llvm::ICmpInst::ICMP_SLT,
1000 llvm::FCmpInst::FCMP_OLT);
1001 case BinaryOperator::GT:
1002 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1003 llvm::ICmpInst::ICMP_SGT,
1004 llvm::FCmpInst::FCMP_OGT);
1005 case BinaryOperator::LE:
1006 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1007 llvm::ICmpInst::ICMP_SLE,
1008 llvm::FCmpInst::FCMP_OLE);
1009 case BinaryOperator::GE:
1010 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1011 llvm::ICmpInst::ICMP_SGE,
1012 llvm::FCmpInst::FCMP_OGE);
1013 case BinaryOperator::EQ:
1014 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1015 llvm::ICmpInst::ICMP_EQ,
1016 llvm::FCmpInst::FCMP_OEQ);
1017 case BinaryOperator::NE:
1018 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1019 llvm::ICmpInst::ICMP_NE,
1020 llvm::FCmpInst::FCMP_UNE);
1021 case BinaryOperator::Assign:
1022 return EmitBinaryAssign(E);
1023
1024 case BinaryOperator::MulAssign: {
1025 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1026 LValue LHSLV;
1027 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1028 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1029 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1030 }
1031 case BinaryOperator::DivAssign: {
1032 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1033 LValue LHSLV;
1034 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1035 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1036 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1037 }
1038 case BinaryOperator::RemAssign: {
1039 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1040 LValue LHSLV;
1041 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1042 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1043 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1044 }
1045 case BinaryOperator::AddAssign: {
1046 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1047 LValue LHSLV;
1048 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1049 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1050 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1051 }
1052 case BinaryOperator::SubAssign: {
1053 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1054 LValue LHSLV;
1055 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1056 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1057 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1058 }
1059 case BinaryOperator::ShlAssign: {
1060 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1061 LValue LHSLV;
1062 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1063 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1064 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1065 }
1066 case BinaryOperator::ShrAssign: {
1067 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1068 LValue LHSLV;
1069 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1070 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1071 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1072 }
1073 case BinaryOperator::AndAssign: {
1074 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1075 LValue LHSLV;
1076 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1077 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1078 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1079 }
1080 case BinaryOperator::OrAssign: {
1081 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1082 LValue LHSLV;
1083 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1084 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1085 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1086 }
1087 case BinaryOperator::XorAssign: {
1088 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1089 LValue LHSLV;
1090 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1091 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1092 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1093 }
1094 case BinaryOperator::Comma: return EmitBinaryComma(E);
1095 }
1096}
1097
1098RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattnera7300102007-08-21 04:59:27 +00001099 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
Chris Lattner4b009652007-07-25 00:24:17 +00001100}
1101
1102RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner9a4e2c62007-08-21 16:34:16 +00001103 if (LHS.getVal()->getType()->isFloatingPoint())
1104 return RValue::get(Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div"));
1105 else if (ResTy->isUnsignedIntegerType())
1106 return RValue::get(Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div"));
1107 else
1108 return RValue::get(Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div"));
Chris Lattner4b009652007-07-25 00:24:17 +00001109}
1110
1111RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner9a4e2c62007-08-21 16:34:16 +00001112 // Rem in C can't be a floating point type: C99 6.5.5p2.
1113 if (ResTy->isUnsignedIntegerType())
1114 return RValue::get(Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem"));
1115 else
1116 return RValue::get(Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem"));
Chris Lattner4b009652007-07-25 00:24:17 +00001117}
1118
1119RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattnera7300102007-08-21 04:59:27 +00001120 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
Chris Lattner4b009652007-07-25 00:24:17 +00001121}
1122
1123RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1124 RValue RHS, QualType RHSTy,
1125 QualType ResTy) {
1126 llvm::Value *LHSValue = LHS.getVal();
1127 llvm::Value *RHSValue = RHS.getVal();
1128 if (LHSTy->isPointerType()) {
1129 // pointer + int
1130 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1131 } else {
1132 // int + pointer
1133 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1134 }
1135}
1136
1137RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner9a4e2c62007-08-21 16:34:16 +00001138 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
Chris Lattner4b009652007-07-25 00:24:17 +00001139}
1140
1141RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1142 RValue RHS, QualType RHSTy,
1143 QualType ResTy) {
1144 llvm::Value *LHSValue = LHS.getVal();
1145 llvm::Value *RHSValue = RHS.getVal();
1146 if (const PointerType *RHSPtrType =
1147 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1148 // pointer - pointer
1149 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1150 QualType LHSElementType = LHSPtrType->getPointeeType();
1151 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1152 "can't subtract pointers with differing element types");
1153 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
1154 SourceLocation()) / 8;
1155 const llvm::Type *ResultType = ConvertType(ResTy);
1156 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1157 "sub.ptr.lhs.cast");
1158 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1159 "sub.ptr.rhs.cast");
1160 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1161 "sub.ptr.sub");
1162
1163 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1164 // remainder. As such, we handle common power-of-two cases here to generate
1165 // better code.
1166 if (llvm::isPowerOf2_64(ElementSize)) {
1167 llvm::Value *ShAmt =
1168 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1169 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1170 } else {
1171 // Otherwise, do a full sdiv.
1172 llvm::Value *BytesPerElement =
1173 llvm::ConstantInt::get(ResultType, ElementSize);
1174 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1175 "sub.ptr.div"));
1176 }
1177 } else {
1178 // pointer - int
1179 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1180 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1181 }
1182}
1183
Chris Lattner4b009652007-07-25 00:24:17 +00001184RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1185 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1186
1187 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1188 // RHS to the same size as the LHS.
1189 if (LHS->getType() != RHS->getType())
1190 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1191
1192 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1193}
1194
1195RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1196 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1197
1198 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1199 // RHS to the same size as the LHS.
1200 if (LHS->getType() != RHS->getType())
1201 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1202
1203 if (ResTy->isUnsignedIntegerType())
1204 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1205 else
1206 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1207}
1208
1209RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1210 unsigned UICmpOpc, unsigned SICmpOpc,
1211 unsigned FCmpOpc) {
Chris Lattner4b009652007-07-25 00:24:17 +00001212 llvm::Value *Result;
Chris Lattner5280c5f2007-08-21 16:57:55 +00001213 QualType LHSTy = E->getLHS()->getType();
1214 if (!LHSTy->isComplexType()) {
1215 RValue LHS = EmitExpr(E->getLHS());
1216 RValue RHS = EmitExpr(E->getRHS());
1217
1218 if (LHSTy->isRealFloatingType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001219 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1220 LHS.getVal(), RHS.getVal(), "cmp");
Chris Lattner5280c5f2007-08-21 16:57:55 +00001221 } else if (LHSTy->isUnsignedIntegerType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00001222 // FIXME: This check isn't right for "unsigned short < int" where ushort
1223 // promotes to int and does a signed compare.
1224 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1225 LHS.getVal(), RHS.getVal(), "cmp");
1226 } else {
1227 // Signed integers and pointers.
1228 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1229 LHS.getVal(), RHS.getVal(), "cmp");
1230 }
1231 } else {
Chris Lattner5280c5f2007-08-21 16:57:55 +00001232 // Complex Comparison: can only be an equality comparison.
1233 ComplexPairTy LHS = EmitComplexExpr(E->getLHS());
1234 ComplexPairTy RHS = EmitComplexExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001235
Chris Lattner5280c5f2007-08-21 16:57:55 +00001236 QualType CETy =
1237 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
1238
1239 llvm::Value *ResultR, *ResultI;
1240 if (CETy->isRealFloatingType()) {
1241 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1242 LHS.first, RHS.first, "cmp.r");
1243 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1244 LHS.second, RHS.second, "cmp.i");
Chris Lattner4b009652007-07-25 00:24:17 +00001245 } else {
Chris Lattner14b0dad2007-08-21 17:03:38 +00001246 // Complex comparisons can only be equality comparisons. As such, signed
1247 // and unsigned opcodes are the same.
1248 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner5280c5f2007-08-21 16:57:55 +00001249 LHS.first, RHS.first, "cmp.r");
Chris Lattner14b0dad2007-08-21 17:03:38 +00001250 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner5280c5f2007-08-21 16:57:55 +00001251 LHS.second, RHS.second, "cmp.i");
Chris Lattner4b009652007-07-25 00:24:17 +00001252 }
Chris Lattner5280c5f2007-08-21 16:57:55 +00001253
1254 if (E->getOpcode() == BinaryOperator::EQ) {
1255 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1256 } else {
1257 assert(E->getOpcode() == BinaryOperator::NE &&
1258 "Complex comparison other than == or != ?");
1259 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1260 }
Chris Lattner4b009652007-07-25 00:24:17 +00001261 }
1262
1263 // ZExt result to int.
1264 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1265}
1266
1267RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner7c257f42007-08-21 17:12:50 +00001268 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
Chris Lattner4b009652007-07-25 00:24:17 +00001269}
1270
1271RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner7c257f42007-08-21 17:12:50 +00001272 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
Chris Lattner4b009652007-07-25 00:24:17 +00001273}
1274
1275RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
Chris Lattner7c257f42007-08-21 17:12:50 +00001276 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
Chris Lattner4b009652007-07-25 00:24:17 +00001277}
1278
1279RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1280 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1281
1282 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1283 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1284
1285 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1286 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1287
1288 EmitBlock(RHSBlock);
1289 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1290
1291 // Reaquire the RHS block, as there may be subblocks inserted.
1292 RHSBlock = Builder.GetInsertBlock();
1293 EmitBlock(ContBlock);
1294
1295 // Create a PHI node. If we just evaluted the LHS condition, the result is
1296 // false. If we evaluated both, the result is the RHS condition.
1297 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1298 PN->reserveOperandSpace(2);
1299 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1300 PN->addIncoming(RHSCond, RHSBlock);
1301
1302 // ZExt result to int.
1303 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1304}
1305
1306RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1307 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1308
1309 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1310 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1311
1312 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1313 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1314
1315 EmitBlock(RHSBlock);
1316 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1317
1318 // Reaquire the RHS block, as there may be subblocks inserted.
1319 RHSBlock = Builder.GetInsertBlock();
1320 EmitBlock(ContBlock);
1321
1322 // Create a PHI node. If we just evaluted the LHS condition, the result is
1323 // true. If we evaluated both, the result is the RHS condition.
1324 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1325 PN->reserveOperandSpace(2);
1326 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1327 PN->addIncoming(RHSCond, RHSBlock);
1328
1329 // ZExt result to int.
1330 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1331}
1332
1333RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +00001334 assert(E->getLHS()->getType().getCanonicalType() ==
1335 E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
Chris Lattner4b009652007-07-25 00:24:17 +00001336 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner2af72ac2007-08-08 17:43:05 +00001337 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001338
1339 // Store the value into the LHS.
1340 EmitStoreThroughLValue(RHS, LHS, E->getType());
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +00001341
1342 // Return the RHS.
Chris Lattner4b009652007-07-25 00:24:17 +00001343 return RHS;
1344}
1345
1346
1347RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
Chris Lattnerc15b0db2007-08-21 17:15:50 +00001348 EmitStmt(E->getLHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001349 return EmitExpr(E->getRHS());
1350}
1351
1352RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1353 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1354 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1355 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1356
1357 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1358 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1359
Chris Lattner4b009652007-07-25 00:24:17 +00001360 EmitBlock(LHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001361 // Handle the GNU extension for missing LHS.
1362 llvm::Value *LHSValue = E->getLHS() ? EmitExpr(E->getLHS()).getVal() : Cond;
Chris Lattner4b009652007-07-25 00:24:17 +00001363 Builder.CreateBr(ContBlock);
1364 LHSBlock = Builder.GetInsertBlock();
1365
1366 EmitBlock(RHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001367
1368 llvm::Value *RHSValue = EmitExpr(E->getRHS()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +00001369 Builder.CreateBr(ContBlock);
1370 RHSBlock = Builder.GetInsertBlock();
1371
1372 const llvm::Type *LHSType = LHSValue->getType();
1373 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1374
1375 EmitBlock(ContBlock);
1376 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1377 PN->reserveOperandSpace(2);
1378 PN->addIncoming(LHSValue, LHSBlock);
1379 PN->addIncoming(RHSValue, RHSBlock);
1380
1381 return RValue::get(PN);
1382}