blob: 9713cf8e1ae97e4bb9a348fb648dcb52b4673f1c [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:
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000589 return EmitImplicitCastExpr(cast<ImplicitCastExpr>(E));
Chris Lattner4b009652007-07-25 00:24:17 +0000590 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
Chris Lattnerb2cb9cb2007-08-20 22:37:10 +0000663/// EmitImplicitCastExpr - Implicit casts are the same as normal casts, but also
664/// handle things like function to pointer-to-function decay, and array to
665/// pointer decay.
666RValue CodeGenFunction::EmitImplicitCastExpr(const ImplicitCastExpr *E) {
667 const Expr *Op = E->getSubExpr();
668 QualType OpTy = Op->getType().getCanonicalType();
669
670 // If this is due to array->pointer conversion, emit the array expression as
671 // an l-value.
672 if (isa<ArrayType>(OpTy)) {
673 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
674 // will not true when we add support for VLAs.
675 llvm::Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
676
677 assert(isa<llvm::PointerType>(V->getType()) &&
678 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
679 ->getElementType()) &&
680 "Doesn't support VLAs yet!");
681 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
682 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
683 }
684
685 return EmitCastExpr(Op, E->getType());
686}
687
Chris Lattner4b009652007-07-25 00:24:17 +0000688RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
Anders Carlsson49865302007-08-20 18:05:56 +0000689 if (const ImplicitCastExpr *IcExpr =
690 dyn_cast<const ImplicitCastExpr>(E->getCallee()))
691 if (const DeclRefExpr *DRExpr =
692 dyn_cast<const DeclRefExpr>(IcExpr->getSubExpr()))
693 if (const FunctionDecl *FDecl =
694 dyn_cast<const FunctionDecl>(DRExpr->getDecl()))
695 if (unsigned builtinID = FDecl->getIdentifier()->getBuiltinID())
696 return EmitBuiltinExpr(builtinID, E);
697
Chris Lattner2af72ac2007-08-08 17:43:05 +0000698 llvm::Value *Callee = EmitExpr(E->getCallee()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +0000699
700 // The callee type will always be a pointer to function type, get the function
701 // type.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000702 QualType CalleeTy = E->getCallee()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000703 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
704
705 // Get information about the argument types.
706 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
707
708 // Calling unprototyped functions provides no argument info.
709 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
710 ArgTyIt = FTP->arg_type_begin();
711 ArgTyEnd = FTP->arg_type_end();
712 }
713
714 llvm::SmallVector<llvm::Value*, 16> Args;
715
Chris Lattner59802042007-08-10 17:02:28 +0000716 // Handle struct-return functions by passing a pointer to the location that
717 // we would like to return into.
718 if (hasAggregateLLVMType(E->getType())) {
719 // Create a temporary alloca to hold the result of the call. :(
720 Args.push_back(CreateTempAlloca(ConvertType(E->getType())));
721 // FIXME: set the stret attribute on the argument.
722 }
723
Chris Lattner4b009652007-07-25 00:24:17 +0000724 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000725 QualType ArgTy = E->getArg(i)->getType();
726 RValue ArgVal = EmitExpr(E->getArg(i));
Chris Lattner4b009652007-07-25 00:24:17 +0000727
728 // If this argument has prototype information, convert it.
729 if (ArgTyIt != ArgTyEnd) {
730 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
731 } else {
732 // Otherwise, if passing through "..." or to a function with no prototype,
733 // perform the "default argument promotions" (C99 6.5.2.2p6), which
734 // includes the usual unary conversions, but also promotes float to
735 // double.
736 if (const BuiltinType *BT =
737 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
738 if (BT->getKind() == BuiltinType::Float)
739 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
740 llvm::Type::DoubleTy,"tmp"));
741 }
742 }
743
744
745 if (ArgVal.isScalar())
746 Args.push_back(ArgVal.getVal());
747 else // Pass by-address. FIXME: Set attribute bit on call.
748 Args.push_back(ArgVal.getAggregateAddr());
749 }
750
Chris Lattnera9572252007-08-01 06:24:52 +0000751 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], &Args[0]+Args.size());
Chris Lattner4b009652007-07-25 00:24:17 +0000752 if (V->getType() != llvm::Type::VoidTy)
753 V->setName("call");
Chris Lattner59802042007-08-10 17:02:28 +0000754 else if (hasAggregateLLVMType(E->getType()))
755 // Struct return.
756 return RValue::getAggregate(Args[0]);
757
Chris Lattner4b009652007-07-25 00:24:17 +0000758 return RValue::get(V);
759}
760
761
762//===----------------------------------------------------------------------===//
763// Unary Operator Emission
764//===----------------------------------------------------------------------===//
765
Chris Lattner4b009652007-07-25 00:24:17 +0000766RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
767 switch (E->getOpcode()) {
768 default:
769 printf("Unimplemented unary expr!\n");
770 E->dump();
771 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
772 case UnaryOperator::PostInc:
773 case UnaryOperator::PostDec:
774 case UnaryOperator::PreInc :
775 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
776 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
777 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
778 case UnaryOperator::Plus : return EmitUnaryPlus(E);
779 case UnaryOperator::Minus : return EmitUnaryMinus(E);
780 case UnaryOperator::Not : return EmitUnaryNot(E);
781 case UnaryOperator::LNot : return EmitUnaryLNot(E);
782 case UnaryOperator::SizeOf :
783 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
784 case UnaryOperator::AlignOf :
785 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
786 // FIXME: real/imag
787 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
788 }
789}
790
791RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
792 LValue LV = EmitLValue(E->getSubExpr());
793 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
794
795 // We know the operand is real or pointer type, so it must be an LLVM scalar.
796 assert(InVal.isScalar() && "Unknown thing to increment");
797 llvm::Value *InV = InVal.getVal();
798
799 int AmountVal = 1;
800 if (E->getOpcode() == UnaryOperator::PreDec ||
801 E->getOpcode() == UnaryOperator::PostDec)
802 AmountVal = -1;
803
804 llvm::Value *NextVal;
805 if (isa<llvm::IntegerType>(InV->getType())) {
806 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
807 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
808 } else if (InV->getType()->isFloatingPoint()) {
809 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
810 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
811 } else {
812 // FIXME: This is not right for pointers to VLA types.
813 assert(isa<llvm::PointerType>(InV->getType()));
814 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
815 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
816 }
817
818 RValue NextValToStore = RValue::get(NextVal);
819
820 // Store the updated result through the lvalue.
821 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
822
823 // If this is a postinc, return the value read from memory, otherwise use the
824 // updated value.
825 if (E->getOpcode() == UnaryOperator::PreDec ||
826 E->getOpcode() == UnaryOperator::PreInc)
827 return NextValToStore;
828 else
829 return InVal;
830}
831
832/// C99 6.5.3.2
833RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
834 // The address of the operand is just its lvalue. It cannot be a bitfield.
835 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
836}
837
838RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000839 assert(E->getType().getCanonicalType() ==
840 E->getSubExpr()->getType().getCanonicalType() && "Bad unary plus!");
841 // Unary plus just returns its value.
842 return EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000843}
844
845RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +0000846 assert(E->getType().getCanonicalType() ==
847 E->getSubExpr()->getType().getCanonicalType() && "Bad unary minus!");
848
Chris Lattner4b009652007-07-25 00:24:17 +0000849 // Unary minus performs promotions, then negates its arithmetic 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.CreateNeg(V.getVal(), "neg"));
854
855 assert(0 && "FIXME: This doesn't handle complex operands yet");
856}
857
858RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
859 // Unary not performs promotions, then complements its integer operand.
Chris Lattner2af72ac2007-08-08 17:43:05 +0000860 RValue V = EmitExpr(E->getSubExpr());
Chris Lattner4b009652007-07-25 00:24:17 +0000861
862 if (V.isScalar())
863 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
864
865 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
866}
867
868
869/// C99 6.5.3.3
870RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
871 // Compare operand to zero.
872 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
873
874 // Invert value.
875 // TODO: Could dynamically modify easy computations here. For example, if
876 // the operand is an icmp ne, turn into icmp eq.
877 BoolVal = Builder.CreateNot(BoolVal, "lnot");
878
879 // ZExt result to int.
880 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
881}
882
883/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
884/// an integer (RetType).
885RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
886 QualType RetType, bool isSizeOf) {
887 /// FIXME: This doesn't handle VLAs yet!
888 std::pair<uint64_t, unsigned> Info =
889 getContext().getTypeInfo(TypeToSize, SourceLocation());
890
891 uint64_t Val = isSizeOf ? Info.first : Info.second;
892 Val /= 8; // Return size in bytes, not bits.
893
894 assert(RetType->isIntegerType() && "Result type must be an integer!");
895
896 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
897 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
898}
899
900
901//===--------------------------------------------------------------------===//
902// Binary Operator Emission
903//===--------------------------------------------------------------------===//
904
Chris Lattner4b009652007-07-25 00:24:17 +0000905
906/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
907/// are strange in that the result of the operation is not the same type as the
908/// intermediate computation. This function emits the LHS and RHS operands of
909/// the compound assignment, promoting them to their common computation type.
910///
911/// Since the LHS is an lvalue, and the result is stored back through it, we
912/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
913/// RHS values are both in the computation type for the operator.
914void CodeGenFunction::
915EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
916 LValue &LHSLV, RValue &LHS, RValue &RHS) {
917 LHSLV = EmitLValue(E->getLHS());
918
919 // Load the LHS and RHS operands.
920 QualType LHSTy = E->getLHS()->getType();
921 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Chris Lattner2af72ac2007-08-08 17:43:05 +0000922 RHS = EmitExpr(E->getRHS());
923 QualType RHSTy = E->getRHS()->getType();
Chris Lattner4b009652007-07-25 00:24:17 +0000924
925 // Convert the LHS and RHS to the common evaluation type.
926 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
927 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
928}
929
930/// EmitCompoundAssignmentResult - Given a result value in the computation type,
931/// truncate it down to the actual result type, store it through the LHS lvalue,
932/// and return it.
933RValue CodeGenFunction::
934EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
935 LValue LHSLV, RValue ResV) {
936
937 // Truncate back to the destination type.
938 if (E->getComputationType() != E->getType())
939 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
940
941 // Store the result value into the LHS.
942 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
943
944 // Return the result.
945 return ResV;
946}
947
948
949RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
950 RValue LHS, RHS;
951 switch (E->getOpcode()) {
952 default:
953 fprintf(stderr, "Unimplemented binary expr!\n");
954 E->dump();
955 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
956 case BinaryOperator::Mul:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000957 LHS = EmitExpr(E->getLHS());
958 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000959 return EmitMul(LHS, RHS, E->getType());
960 case BinaryOperator::Div:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000961 LHS = EmitExpr(E->getLHS());
962 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000963 return EmitDiv(LHS, RHS, E->getType());
964 case BinaryOperator::Rem:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000965 LHS = EmitExpr(E->getLHS());
966 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000967 return EmitRem(LHS, RHS, E->getType());
Chris Lattnerbf49e992007-08-08 17:49:18 +0000968 case BinaryOperator::Add:
969 LHS = EmitExpr(E->getLHS());
970 RHS = EmitExpr(E->getRHS());
971 if (!E->getType()->isPointerType())
972 return EmitAdd(LHS, RHS, E->getType());
973
974 return EmitPointerAdd(LHS, E->getLHS()->getType(),
975 RHS, E->getRHS()->getType(), E->getType());
976 case BinaryOperator::Sub:
977 LHS = EmitExpr(E->getLHS());
978 RHS = EmitExpr(E->getRHS());
979
980 if (!E->getLHS()->getType()->isPointerType())
981 return EmitSub(LHS, RHS, E->getType());
982
983 return EmitPointerSub(LHS, E->getLHS()->getType(),
984 RHS, E->getRHS()->getType(), E->getType());
Chris Lattner4b009652007-07-25 00:24:17 +0000985 case BinaryOperator::Shl:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000986 LHS = EmitExpr(E->getLHS());
987 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000988 return EmitShl(LHS, RHS, E->getType());
989 case BinaryOperator::Shr:
Chris Lattner2af72ac2007-08-08 17:43:05 +0000990 LHS = EmitExpr(E->getLHS());
991 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000992 return EmitShr(LHS, RHS, E->getType());
993 case BinaryOperator::And:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000994 LHS = EmitExpr(E->getLHS());
995 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +0000996 return EmitAnd(LHS, RHS, E->getType());
997 case BinaryOperator::Xor:
Chris Lattnerbf49e992007-08-08 17:49:18 +0000998 LHS = EmitExpr(E->getLHS());
999 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001000 return EmitXor(LHS, RHS, E->getType());
1001 case BinaryOperator::Or :
Chris Lattnerbf49e992007-08-08 17:49:18 +00001002 LHS = EmitExpr(E->getLHS());
1003 RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001004 return EmitOr(LHS, RHS, E->getType());
1005 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1006 case BinaryOperator::LOr: return EmitBinaryLOr(E);
1007 case BinaryOperator::LT:
1008 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1009 llvm::ICmpInst::ICMP_SLT,
1010 llvm::FCmpInst::FCMP_OLT);
1011 case BinaryOperator::GT:
1012 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1013 llvm::ICmpInst::ICMP_SGT,
1014 llvm::FCmpInst::FCMP_OGT);
1015 case BinaryOperator::LE:
1016 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1017 llvm::ICmpInst::ICMP_SLE,
1018 llvm::FCmpInst::FCMP_OLE);
1019 case BinaryOperator::GE:
1020 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1021 llvm::ICmpInst::ICMP_SGE,
1022 llvm::FCmpInst::FCMP_OGE);
1023 case BinaryOperator::EQ:
1024 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1025 llvm::ICmpInst::ICMP_EQ,
1026 llvm::FCmpInst::FCMP_OEQ);
1027 case BinaryOperator::NE:
1028 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1029 llvm::ICmpInst::ICMP_NE,
1030 llvm::FCmpInst::FCMP_UNE);
1031 case BinaryOperator::Assign:
1032 return EmitBinaryAssign(E);
1033
1034 case BinaryOperator::MulAssign: {
1035 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1036 LValue LHSLV;
1037 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1038 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1039 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1040 }
1041 case BinaryOperator::DivAssign: {
1042 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1043 LValue LHSLV;
1044 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1045 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1046 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1047 }
1048 case BinaryOperator::RemAssign: {
1049 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1050 LValue LHSLV;
1051 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1052 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1053 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1054 }
1055 case BinaryOperator::AddAssign: {
1056 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1057 LValue LHSLV;
1058 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1059 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1060 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1061 }
1062 case BinaryOperator::SubAssign: {
1063 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1064 LValue LHSLV;
1065 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1066 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1067 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1068 }
1069 case BinaryOperator::ShlAssign: {
1070 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1071 LValue LHSLV;
1072 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1073 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1074 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1075 }
1076 case BinaryOperator::ShrAssign: {
1077 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1078 LValue LHSLV;
1079 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1080 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1081 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1082 }
1083 case BinaryOperator::AndAssign: {
1084 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1085 LValue LHSLV;
1086 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1087 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1088 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1089 }
1090 case BinaryOperator::OrAssign: {
1091 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1092 LValue LHSLV;
1093 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1094 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1095 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1096 }
1097 case BinaryOperator::XorAssign: {
1098 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1099 LValue LHSLV;
1100 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1101 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1102 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1103 }
1104 case BinaryOperator::Comma: return EmitBinaryComma(E);
1105 }
1106}
1107
1108RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
1109 if (LHS.isScalar())
1110 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1111
1112 // Otherwise, this must be a complex number.
1113 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1114
1115 EmitLoadOfComplex(LHS, LHSR, LHSI);
1116 EmitLoadOfComplex(RHS, RHSR, RHSI);
1117
1118 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1119 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1120 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1121
1122 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1123 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1124 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1125
1126 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1127 EmitStoreOfComplex(ResR, ResI, Res);
1128 return RValue::getAggregate(Res);
1129}
1130
1131RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
1132 if (LHS.isScalar()) {
1133 llvm::Value *RV;
1134 if (LHS.getVal()->getType()->isFloatingPoint())
1135 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
1136 else if (ResTy->isUnsignedIntegerType())
1137 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1138 else
1139 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1140 return RValue::get(RV);
1141 }
1142 assert(0 && "FIXME: This doesn't handle complex operands yet");
1143}
1144
1145RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
1146 if (LHS.isScalar()) {
1147 llvm::Value *RV;
1148 // Rem in C can't be a floating point type: C99 6.5.5p2.
1149 if (ResTy->isUnsignedIntegerType())
1150 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1151 else
1152 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1153 return RValue::get(RV);
1154 }
1155
1156 assert(0 && "FIXME: This doesn't handle complex operands yet");
1157}
1158
1159RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
1160 if (LHS.isScalar())
1161 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
1162
1163 // Otherwise, this must be a complex number.
1164 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1165
1166 EmitLoadOfComplex(LHS, LHSR, LHSI);
1167 EmitLoadOfComplex(RHS, RHSR, RHSI);
1168
1169 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1170 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1171
1172 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1173 EmitStoreOfComplex(ResR, ResI, Res);
1174 return RValue::getAggregate(Res);
1175}
1176
1177RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1178 RValue RHS, QualType RHSTy,
1179 QualType ResTy) {
1180 llvm::Value *LHSValue = LHS.getVal();
1181 llvm::Value *RHSValue = RHS.getVal();
1182 if (LHSTy->isPointerType()) {
1183 // pointer + int
1184 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1185 } else {
1186 // int + pointer
1187 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1188 }
1189}
1190
1191RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
1192 if (LHS.isScalar())
1193 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1194
1195 assert(0 && "FIXME: This doesn't handle complex operands yet");
1196}
1197
1198RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1199 RValue RHS, QualType RHSTy,
1200 QualType ResTy) {
1201 llvm::Value *LHSValue = LHS.getVal();
1202 llvm::Value *RHSValue = RHS.getVal();
1203 if (const PointerType *RHSPtrType =
1204 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1205 // pointer - pointer
1206 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1207 QualType LHSElementType = LHSPtrType->getPointeeType();
1208 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1209 "can't subtract pointers with differing element types");
1210 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
1211 SourceLocation()) / 8;
1212 const llvm::Type *ResultType = ConvertType(ResTy);
1213 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1214 "sub.ptr.lhs.cast");
1215 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1216 "sub.ptr.rhs.cast");
1217 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1218 "sub.ptr.sub");
1219
1220 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1221 // remainder. As such, we handle common power-of-two cases here to generate
1222 // better code.
1223 if (llvm::isPowerOf2_64(ElementSize)) {
1224 llvm::Value *ShAmt =
1225 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1226 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1227 } else {
1228 // Otherwise, do a full sdiv.
1229 llvm::Value *BytesPerElement =
1230 llvm::ConstantInt::get(ResultType, ElementSize);
1231 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1232 "sub.ptr.div"));
1233 }
1234 } else {
1235 // pointer - int
1236 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1237 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1238 }
1239}
1240
Chris Lattner4b009652007-07-25 00:24:17 +00001241RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1242 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1243
1244 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1245 // RHS to the same size as the LHS.
1246 if (LHS->getType() != RHS->getType())
1247 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1248
1249 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1250}
1251
1252RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1253 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1254
1255 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1256 // RHS to the same size as the LHS.
1257 if (LHS->getType() != RHS->getType())
1258 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1259
1260 if (ResTy->isUnsignedIntegerType())
1261 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1262 else
1263 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1264}
1265
1266RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1267 unsigned UICmpOpc, unsigned SICmpOpc,
1268 unsigned FCmpOpc) {
Chris Lattnerbf49e992007-08-08 17:49:18 +00001269 RValue LHS = EmitExpr(E->getLHS());
1270 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001271
1272 llvm::Value *Result;
1273 if (LHS.isScalar()) {
1274 if (LHS.getVal()->getType()->isFloatingPoint()) {
1275 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1276 LHS.getVal(), RHS.getVal(), "cmp");
1277 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1278 // FIXME: This check isn't right for "unsigned short < int" where ushort
1279 // promotes to int and does a signed compare.
1280 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1281 LHS.getVal(), RHS.getVal(), "cmp");
1282 } else {
1283 // Signed integers and pointers.
1284 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1285 LHS.getVal(), RHS.getVal(), "cmp");
1286 }
1287 } else {
1288 // Struct/union/complex
1289 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1290 EmitLoadOfComplex(LHS, LHSR, LHSI);
1291 EmitLoadOfComplex(RHS, RHSR, RHSI);
1292
1293 // FIXME: need to consider _Complex over integers too!
1294
1295 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1296 LHSR, RHSR, "cmp.r");
1297 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1298 LHSI, RHSI, "cmp.i");
1299 if (BinaryOperator::EQ == E->getOpcode()) {
1300 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1301 } else if (BinaryOperator::NE == E->getOpcode()) {
1302 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1303 } else {
1304 assert(0 && "Complex comparison other than == or != ?");
1305 }
1306 }
1307
1308 // ZExt result to int.
1309 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1310}
1311
1312RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
1313 if (LHS.isScalar())
1314 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1315
1316 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1317}
1318
1319RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
1320 if (LHS.isScalar())
1321 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1322
1323 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1324}
1325
1326RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
1327 if (LHS.isScalar())
1328 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1329
1330 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1331}
1332
1333RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1334 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1335
1336 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1337 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1338
1339 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1340 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1341
1342 EmitBlock(RHSBlock);
1343 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1344
1345 // Reaquire the RHS block, as there may be subblocks inserted.
1346 RHSBlock = Builder.GetInsertBlock();
1347 EmitBlock(ContBlock);
1348
1349 // Create a PHI node. If we just evaluted the LHS condition, the result is
1350 // false. If we evaluated both, the result is the RHS condition.
1351 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1352 PN->reserveOperandSpace(2);
1353 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1354 PN->addIncoming(RHSCond, RHSBlock);
1355
1356 // ZExt result to int.
1357 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1358}
1359
1360RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1361 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1362
1363 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1364 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1365
1366 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1367 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1368
1369 EmitBlock(RHSBlock);
1370 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1371
1372 // Reaquire the RHS block, as there may be subblocks inserted.
1373 RHSBlock = Builder.GetInsertBlock();
1374 EmitBlock(ContBlock);
1375
1376 // Create a PHI node. If we just evaluted the LHS condition, the result is
1377 // true. If we evaluated both, the result is the RHS condition.
1378 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1379 PN->reserveOperandSpace(2);
1380 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1381 PN->addIncoming(RHSCond, RHSBlock);
1382
1383 // ZExt result to int.
1384 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1385}
1386
1387RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
Chris Lattner2af72ac2007-08-08 17:43:05 +00001388 assert(E->getLHS()->getType().getCanonicalType() ==
1389 E->getRHS()->getType().getCanonicalType() && "Invalid assignment");
Chris Lattner4b009652007-07-25 00:24:17 +00001390 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner2af72ac2007-08-08 17:43:05 +00001391 RValue RHS = EmitExpr(E->getRHS());
Chris Lattner4b009652007-07-25 00:24:17 +00001392
1393 // Store the value into the LHS.
1394 EmitStoreThroughLValue(RHS, LHS, E->getType());
Chris Lattnerbdb8ffb2007-08-11 00:04:45 +00001395
1396 // Return the RHS.
Chris Lattner4b009652007-07-25 00:24:17 +00001397 return RHS;
1398}
1399
1400
1401RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1402 EmitExpr(E->getLHS());
1403 return EmitExpr(E->getRHS());
1404}
1405
1406RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1407 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1408 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1409 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1410
1411 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1412 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1413
Chris Lattner4b009652007-07-25 00:24:17 +00001414 EmitBlock(LHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001415 // Handle the GNU extension for missing LHS.
1416 llvm::Value *LHSValue = E->getLHS() ? EmitExpr(E->getLHS()).getVal() : Cond;
Chris Lattner4b009652007-07-25 00:24:17 +00001417 Builder.CreateBr(ContBlock);
1418 LHSBlock = Builder.GetInsertBlock();
1419
1420 EmitBlock(RHSBlock);
Chris Lattner2af72ac2007-08-08 17:43:05 +00001421
1422 llvm::Value *RHSValue = EmitExpr(E->getRHS()).getVal();
Chris Lattner4b009652007-07-25 00:24:17 +00001423 Builder.CreateBr(ContBlock);
1424 RHSBlock = Builder.GetInsertBlock();
1425
1426 const llvm::Type *LHSType = LHSValue->getType();
1427 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1428
1429 EmitBlock(ContBlock);
1430 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1431 PN->reserveOperandSpace(2);
1432 PN->addIncoming(LHSValue, LHSBlock);
1433 PN->addIncoming(RHSValue, RHSBlock);
1434
1435 return RValue::get(PN);
1436}