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