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