blob: 6d735e0b5e138db91d3bbdde398a706321499fd0 [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));
256 }
257}
258
259/// EmitLoadOfLValue - Given an expression that represents a value lvalue,
260/// this method emits the address of the lvalue, then loads the result as an
261/// rvalue, returning the rvalue.
262RValue CodeGenFunction::EmitLoadOfLValue(LValue LV, QualType ExprType) {
263 ExprType = ExprType.getCanonicalType();
264
265 if (LV.isSimple()) {
266 llvm::Value *Ptr = LV.getAddress();
267 const llvm::Type *EltTy =
268 cast<llvm::PointerType>(Ptr->getType())->getElementType();
269
270 // Simple scalar l-value.
271 if (EltTy->isFirstClassType())
272 return RValue::get(Builder.CreateLoad(Ptr, "tmp"));
273
274 // Otherwise, we have an aggregate lvalue.
275 return RValue::getAggregate(Ptr);
276 }
277
278 if (LV.isVectorElt()) {
279 llvm::Value *Vec = Builder.CreateLoad(LV.getVectorAddr(), "tmp");
280 return RValue::get(Builder.CreateExtractElement(Vec, LV.getVectorIdx(),
281 "vecext"));
282 }
283
284 assert(0 && "Bitfield ref not impl!");
285}
286
287RValue CodeGenFunction::EmitLoadOfLValue(const Expr *E) {
288 return EmitLoadOfLValue(EmitLValue(E), E->getType());
289}
290
291
292/// EmitStoreThroughLValue - Store the specified rvalue into the specified
293/// lvalue, where both are guaranteed to the have the same type, and that type
294/// is 'Ty'.
295void CodeGenFunction::EmitStoreThroughLValue(RValue Src, LValue Dst,
296 QualType Ty) {
297 if (Dst.isVectorElt()) {
298 // Read/modify/write the vector, inserting the new element.
299 // FIXME: Volatility.
300 llvm::Value *Vec = Builder.CreateLoad(Dst.getVectorAddr(), "tmp");
301 Vec = Builder.CreateInsertElement(Vec, Src.getVal(),
302 Dst.getVectorIdx(), "vecins");
303 Builder.CreateStore(Vec, Dst.getVectorAddr());
304 return;
305 }
306
307 assert(Dst.isSimple() && "FIXME: Don't support store to bitfield yet");
308
309 llvm::Value *DstAddr = Dst.getAddress();
310 if (Src.isScalar()) {
311 // FIXME: Handle volatility etc.
312 const llvm::Type *SrcTy = Src.getVal()->getType();
313 const llvm::Type *AddrTy =
314 cast<llvm::PointerType>(DstAddr->getType())->getElementType();
315
316 if (AddrTy != SrcTy)
317 DstAddr = Builder.CreateBitCast(DstAddr, llvm::PointerType::get(SrcTy),
318 "storetmp");
319 Builder.CreateStore(Src.getVal(), DstAddr);
320 return;
321 }
322
323 // Don't use memcpy for complex numbers.
324 if (Ty->isComplexType()) {
325 llvm::Value *Real, *Imag;
326 EmitLoadOfComplex(Src, Real, Imag);
327 EmitStoreOfComplex(Real, Imag, Dst.getAddress());
328 return;
329 }
330
331 // Aggregate assignment turns into llvm.memcpy.
332 const llvm::Type *SBP = llvm::PointerType::get(llvm::Type::Int8Ty);
333 llvm::Value *SrcAddr = Src.getAggregateAddr();
334
335 if (DstAddr->getType() != SBP)
336 DstAddr = Builder.CreateBitCast(DstAddr, SBP, "tmp");
337 if (SrcAddr->getType() != SBP)
338 SrcAddr = Builder.CreateBitCast(SrcAddr, SBP, "tmp");
339
340 unsigned Align = 1; // FIXME: Compute type alignments.
341 unsigned Size = 1234; // FIXME: Compute type sizes.
342
343 // FIXME: Handle variable sized types.
344 const llvm::Type *IntPtr = llvm::IntegerType::get(LLVMPointerWidth);
345 llvm::Value *SizeVal = llvm::ConstantInt::get(IntPtr, Size);
346
347 llvm::Value *MemCpyOps[4] = {
348 DstAddr, SrcAddr, SizeVal,llvm::ConstantInt::get(llvm::Type::Int32Ty, Align)
349 };
350
351 Builder.CreateCall(CGM.getMemCpyFn(), MemCpyOps, 4);
352}
353
354
355LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
356 const Decl *D = E->getDecl();
357 if (isa<BlockVarDecl>(D) || isa<ParmVarDecl>(D)) {
358 llvm::Value *V = LocalDeclMap[D];
359 assert(V && "BlockVarDecl not entered in LocalDeclMap?");
360 return LValue::MakeAddr(V);
361 } else if (isa<FunctionDecl>(D) || isa<FileVarDecl>(D)) {
362 return LValue::MakeAddr(CGM.GetAddrOfGlobalDecl(D));
363 }
364 assert(0 && "Unimp declref");
365}
366
367LValue CodeGenFunction::EmitUnaryOpLValue(const UnaryOperator *E) {
368 // __extension__ doesn't affect lvalue-ness.
369 if (E->getOpcode() == UnaryOperator::Extension)
370 return EmitLValue(E->getSubExpr());
371
372 assert(E->getOpcode() == UnaryOperator::Deref &&
373 "'*' is the only unary operator that produces an lvalue");
374 return LValue::MakeAddr(EmitExpr(E->getSubExpr()).getVal());
375}
376
377LValue CodeGenFunction::EmitStringLiteralLValue(const StringLiteral *E) {
378 assert(!E->isWide() && "FIXME: Wide strings not supported yet!");
379 const char *StrData = E->getStrData();
380 unsigned Len = E->getByteLength();
381
382 // FIXME: Can cache/reuse these within the module.
383 llvm::Constant *C=llvm::ConstantArray::get(std::string(StrData, StrData+Len));
384
385 // Create a global variable for this.
386 C = new llvm::GlobalVariable(C->getType(), true,
387 llvm::GlobalValue::InternalLinkage,
388 C, ".str", CurFn->getParent());
389 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
390 llvm::Constant *Zeros[] = { Zero, Zero };
391 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
392 return LValue::MakeAddr(C);
393}
394
Anders Carlsson22742662007-07-21 05:21:51 +0000395LValue CodeGenFunction::EmitPreDefinedLValue(const PreDefinedExpr *E) {
396 std::string FunctionName(CurFuncDecl->getName());
397 std::string GlobalVarName;
398
399 switch (E->getIdentType()) {
400 default:
401 assert(0 && "unknown pre-defined ident type");
402 case PreDefinedExpr::Func:
403 GlobalVarName = "__func__.";
404 break;
405 case PreDefinedExpr::Function:
406 GlobalVarName = "__FUNCTION__.";
407 break;
408 case PreDefinedExpr::PrettyFunction:
409 // FIXME:: Demangle C++ method names
410 GlobalVarName = "__PRETTY_FUNCTION__.";
411 break;
412 }
413
414 GlobalVarName += CurFuncDecl->getName();
415
416 // FIXME: Can cache/reuse these within the module.
417 llvm::Constant *C=llvm::ConstantArray::get(FunctionName);
418
419 // Create a global variable for this.
420 C = new llvm::GlobalVariable(C->getType(), true,
421 llvm::GlobalValue::InternalLinkage,
422 C, GlobalVarName, CurFn->getParent());
423 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
424 llvm::Constant *Zeros[] = { Zero, Zero };
425 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
426 return LValue::MakeAddr(C);
427}
428
Reid Spencer5f016e22007-07-11 17:01:13 +0000429LValue CodeGenFunction::EmitArraySubscriptExpr(const ArraySubscriptExpr *E) {
430 // The index must always be a pointer or integer, neither of which is an
431 // aggregate. Emit it.
432 QualType IdxTy;
433 llvm::Value *Idx =
434 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
435
436 // If the base is a vector type, then we are forming a vector element lvalue
437 // with this subscript.
438 if (E->getBase()->getType()->isVectorType()) {
439 // Emit the vector as an lvalue to get its address.
440 LValue Base = EmitLValue(E->getBase());
441 assert(Base.isSimple() && "Can only subscript lvalue vectors here!");
442 // FIXME: This should properly sign/zero/extend or truncate Idx to i32.
443 return LValue::MakeVectorElt(Base.getAddress(), Idx);
444 }
445
446 // At this point, the base must be a pointer or integer, neither of which are
447 // aggregates. Emit it.
448 QualType BaseTy;
449 llvm::Value *Base =
450 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
451
452 // Usually the base is the pointer type, but sometimes it is the index.
453 // Canonicalize to have the pointer as the base.
454 if (isa<llvm::PointerType>(Idx->getType())) {
455 std::swap(Base, Idx);
456 std::swap(BaseTy, IdxTy);
457 }
458
459 // The pointer is now the base. Extend or truncate the index type to 32 or
460 // 64-bits.
461 bool IdxSigned = IdxTy->isSignedIntegerType();
462 unsigned IdxBitwidth = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
463 if (IdxBitwidth != LLVMPointerWidth)
464 Idx = Builder.CreateIntCast(Idx, llvm::IntegerType::get(LLVMPointerWidth),
465 IdxSigned, "idxprom");
466
467 // We know that the pointer points to a type of the correct size, unless the
468 // size is a VLA.
Chris Lattner590b6642007-07-15 23:26:56 +0000469 if (!E->getType()->isConstantSizeType(getContext()))
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 assert(0 && "VLA idx not implemented");
471 return LValue::MakeAddr(Builder.CreateGEP(Base, Idx, "arrayidx"));
472}
473
474//===--------------------------------------------------------------------===//
475// Expression Emission
476//===--------------------------------------------------------------------===//
477
478RValue CodeGenFunction::EmitExpr(const Expr *E) {
479 assert(E && "Null expression?");
480
481 switch (E->getStmtClass()) {
482 default:
483 fprintf(stderr, "Unimplemented expr!\n");
484 E->dump();
485 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
486
487 // l-values.
488 case Expr::DeclRefExprClass:
489 // DeclRef's of EnumConstantDecl's are simple rvalues.
490 if (const EnumConstantDecl *EC =
491 dyn_cast<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
492 return RValue::get(llvm::ConstantInt::get(EC->getInitVal()));
493 return EmitLoadOfLValue(E);
494 case Expr::ArraySubscriptExprClass:
495 return EmitArraySubscriptExprRV(cast<ArraySubscriptExpr>(E));
Anders Carlsson22742662007-07-21 05:21:51 +0000496 case Expr::PreDefinedExprClass:
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 case Expr::StringLiteralClass:
498 return RValue::get(EmitLValue(E).getAddress());
499
500 // Leaf expressions.
501 case Expr::IntegerLiteralClass:
502 return EmitIntegerLiteral(cast<IntegerLiteral>(E));
503 case Expr::FloatingLiteralClass:
504 return EmitFloatingLiteral(cast<FloatingLiteral>(E));
Chris Lattnerb0a721a2007-07-13 05:18:11 +0000505 case Expr::CharacterLiteralClass:
506 return EmitCharacterLiteral(cast<CharacterLiteral>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000507
508 // Operators.
509 case Expr::ParenExprClass:
510 return EmitExpr(cast<ParenExpr>(E)->getSubExpr());
511 case Expr::UnaryOperatorClass:
512 return EmitUnaryOperator(cast<UnaryOperator>(E));
Chris Lattner5e3fbe52007-07-18 18:12:07 +0000513 case Expr::SizeOfAlignOfTypeExprClass:
514 return EmitSizeAlignOf(cast<SizeOfAlignOfTypeExpr>(E)->getArgumentType(),
515 E->getType(),
516 cast<SizeOfAlignOfTypeExpr>(E)->isSizeOf());
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000517 case Expr::ImplicitCastExprClass:
518 return EmitCastExpr(cast<ImplicitCastExpr>(E)->getSubExpr(), E->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000519 case Expr::CastExprClass:
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000520 return EmitCastExpr(cast<CastExpr>(E)->getSubExpr(), E->getType());
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 case Expr::CallExprClass:
522 return EmitCallExpr(cast<CallExpr>(E));
523 case Expr::BinaryOperatorClass:
524 return EmitBinaryOperator(cast<BinaryOperator>(E));
Chris Lattnerb0a721a2007-07-13 05:18:11 +0000525
526 case Expr::ConditionalOperatorClass:
527 return EmitConditionalOperator(cast<ConditionalOperator>(E));
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 }
529
530}
531
532RValue CodeGenFunction::EmitIntegerLiteral(const IntegerLiteral *E) {
533 return RValue::get(llvm::ConstantInt::get(E->getValue()));
534}
535RValue CodeGenFunction::EmitFloatingLiteral(const FloatingLiteral *E) {
536 return RValue::get(llvm::ConstantFP::get(ConvertType(E->getType()),
537 E->getValue()));
538}
Chris Lattnerb0a721a2007-07-13 05:18:11 +0000539RValue CodeGenFunction::EmitCharacterLiteral(const CharacterLiteral *E) {
540 return RValue::get(llvm::ConstantInt::get(ConvertType(E->getType()),
541 E->getValue()));
542}
Reid Spencer5f016e22007-07-11 17:01:13 +0000543
544RValue CodeGenFunction::EmitArraySubscriptExprRV(const ArraySubscriptExpr *E) {
545 // Emit subscript expressions in rvalue context's. For most cases, this just
546 // loads the lvalue formed by the subscript expr. However, we have to be
547 // careful, because the base of a vector subscript is occasionally an rvalue,
548 // so we can't get it as an lvalue.
549 if (!E->getBase()->getType()->isVectorType())
550 return EmitLoadOfLValue(E);
551
552 // Handle the vector case. The base must be a vector, the index must be an
553 // integer value.
554 QualType BaseTy, IdxTy;
555 llvm::Value *Base =
556 EmitExprWithUsualUnaryConversions(E->getBase(), BaseTy).getVal();
557 llvm::Value *Idx =
558 EmitExprWithUsualUnaryConversions(E->getIdx(), IdxTy).getVal();
559
560 // FIXME: Convert Idx to i32 type.
561
562 return RValue::get(Builder.CreateExtractElement(Base, Idx, "vecext"));
563}
564
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000565// EmitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
566// have to handle a more broad range of conversions than explicit casts, as they
567// handle things like function to ptr-to-function decay etc.
568RValue CodeGenFunction::EmitCastExpr(const Expr *Op, QualType DestTy) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 QualType SrcTy;
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000570 RValue Src = EmitExprWithUsualUnaryConversions(Op, SrcTy);
Reid Spencer5f016e22007-07-11 17:01:13 +0000571
572 // If the destination is void, just evaluate the source.
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000573 if (DestTy->isVoidType())
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 return RValue::getAggregate(0);
575
Chris Lattnerd07eb3b2007-07-13 20:25:53 +0000576 return EmitConversion(Src, SrcTy, DestTy);
Reid Spencer5f016e22007-07-11 17:01:13 +0000577}
578
579RValue CodeGenFunction::EmitCallExpr(const CallExpr *E) {
580 QualType CalleeTy;
581 llvm::Value *Callee =
582 EmitExprWithUsualUnaryConversions(E->getCallee(), CalleeTy).getVal();
583
584 // The callee type will always be a pointer to function type, get the function
585 // type.
586 CalleeTy = cast<PointerType>(CalleeTy.getCanonicalType())->getPointeeType();
587
588 // Get information about the argument types.
589 FunctionTypeProto::arg_type_iterator ArgTyIt = 0, ArgTyEnd = 0;
590
591 // Calling unprototyped functions provides no argument info.
592 if (const FunctionTypeProto *FTP = dyn_cast<FunctionTypeProto>(CalleeTy)) {
593 ArgTyIt = FTP->arg_type_begin();
594 ArgTyEnd = FTP->arg_type_end();
595 }
596
597 llvm::SmallVector<llvm::Value*, 16> Args;
598
599 // FIXME: Handle struct return.
600 for (unsigned i = 0, e = E->getNumArgs(); i != e; ++i) {
601 QualType ArgTy;
602 RValue ArgVal = EmitExprWithUsualUnaryConversions(E->getArg(i), ArgTy);
603
604 // If this argument has prototype information, convert it.
605 if (ArgTyIt != ArgTyEnd) {
606 ArgVal = EmitConversion(ArgVal, ArgTy, *ArgTyIt++);
607 } else {
608 // Otherwise, if passing through "..." or to a function with no prototype,
609 // perform the "default argument promotions" (C99 6.5.2.2p6), which
610 // includes the usual unary conversions, but also promotes float to
611 // double.
612 if (const BuiltinType *BT =
613 dyn_cast<BuiltinType>(ArgTy.getCanonicalType())) {
614 if (BT->getKind() == BuiltinType::Float)
615 ArgVal = RValue::get(Builder.CreateFPExt(ArgVal.getVal(),
616 llvm::Type::DoubleTy,"tmp"));
617 }
618 }
619
620
621 if (ArgVal.isScalar())
622 Args.push_back(ArgVal.getVal());
623 else // Pass by-address. FIXME: Set attribute bit on call.
624 Args.push_back(ArgVal.getAggregateAddr());
625 }
626
627 llvm::Value *V = Builder.CreateCall(Callee, &Args[0], Args.size());
628 if (V->getType() != llvm::Type::VoidTy)
629 V->setName("call");
630
631 // FIXME: Struct return;
632 return RValue::get(V);
633}
634
635
636//===----------------------------------------------------------------------===//
637// Unary Operator Emission
638//===----------------------------------------------------------------------===//
639
640RValue CodeGenFunction::EmitExprWithUsualUnaryConversions(const Expr *E,
641 QualType &ResTy) {
642 ResTy = E->getType().getCanonicalType();
643
644 if (isa<FunctionType>(ResTy)) { // C99 6.3.2.1p4
645 // Functions are promoted to their address.
646 ResTy = getContext().getPointerType(ResTy);
647 return RValue::get(EmitLValue(E).getAddress());
648 } else if (const ArrayType *ary = dyn_cast<ArrayType>(ResTy)) {
649 // C99 6.3.2.1p3
650 ResTy = getContext().getPointerType(ary->getElementType());
651
652 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
653 // will not true when we add support for VLAs.
654 llvm::Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
655
656 assert(isa<llvm::PointerType>(V->getType()) &&
657 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
658 ->getElementType()) &&
659 "Doesn't support VLAs yet!");
660 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
661 return RValue::get(Builder.CreateGEP(V, Idx0, Idx0, "arraydecay"));
662 } else if (ResTy->isPromotableIntegerType()) { // C99 6.3.1.1p2
663 // FIXME: this probably isn't right, pending clarification from Steve.
664 llvm::Value *Val = EmitExpr(E).getVal();
665
666 // If the input is a signed integer, sign extend to the destination.
667 if (ResTy->isSignedIntegerType()) {
668 Val = Builder.CreateSExt(Val, LLVMIntTy, "promote");
669 } else {
670 // This handles unsigned types, including bool.
671 Val = Builder.CreateZExt(Val, LLVMIntTy, "promote");
672 }
673 ResTy = getContext().IntTy;
674
675 return RValue::get(Val);
676 }
677
678 // Otherwise, this is a float, double, int, struct, etc.
679 return EmitExpr(E);
680}
681
682
683RValue CodeGenFunction::EmitUnaryOperator(const UnaryOperator *E) {
684 switch (E->getOpcode()) {
685 default:
686 printf("Unimplemented unary expr!\n");
687 E->dump();
688 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
Chris Lattner57274792007-07-11 23:43:46 +0000689 case UnaryOperator::PostInc:
690 case UnaryOperator::PostDec:
691 case UnaryOperator::PreInc :
692 case UnaryOperator::PreDec : return EmitUnaryIncDec(E);
693 case UnaryOperator::AddrOf : return EmitUnaryAddrOf(E);
694 case UnaryOperator::Deref : return EmitLoadOfLValue(E);
695 case UnaryOperator::Plus : return EmitUnaryPlus(E);
696 case UnaryOperator::Minus : return EmitUnaryMinus(E);
697 case UnaryOperator::Not : return EmitUnaryNot(E);
698 case UnaryOperator::LNot : return EmitUnaryLNot(E);
Chris Lattner5e3fbe52007-07-18 18:12:07 +0000699 case UnaryOperator::SizeOf :
700 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
701 case UnaryOperator::AlignOf :
702 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000703 // FIXME: real/imag
704 case UnaryOperator::Extension: return EmitExpr(E->getSubExpr());
705 }
706}
707
Chris Lattner57274792007-07-11 23:43:46 +0000708RValue CodeGenFunction::EmitUnaryIncDec(const UnaryOperator *E) {
709 LValue LV = EmitLValue(E->getSubExpr());
710 RValue InVal = EmitLoadOfLValue(LV, E->getSubExpr()->getType());
711
712 // We know the operand is real or pointer type, so it must be an LLVM scalar.
713 assert(InVal.isScalar() && "Unknown thing to increment");
714 llvm::Value *InV = InVal.getVal();
715
716 int AmountVal = 1;
717 if (E->getOpcode() == UnaryOperator::PreDec ||
718 E->getOpcode() == UnaryOperator::PostDec)
719 AmountVal = -1;
720
721 llvm::Value *NextVal;
722 if (isa<llvm::IntegerType>(InV->getType())) {
723 NextVal = llvm::ConstantInt::get(InV->getType(), AmountVal);
724 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
725 } else if (InV->getType()->isFloatingPoint()) {
726 NextVal = llvm::ConstantFP::get(InV->getType(), AmountVal);
727 NextVal = Builder.CreateAdd(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
728 } else {
729 // FIXME: This is not right for pointers to VLA types.
730 assert(isa<llvm::PointerType>(InV->getType()));
731 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
732 NextVal = Builder.CreateGEP(InV, NextVal, AmountVal == 1 ? "inc" : "dec");
733 }
734
735 RValue NextValToStore = RValue::get(NextVal);
736
737 // Store the updated result through the lvalue.
738 EmitStoreThroughLValue(NextValToStore, LV, E->getSubExpr()->getType());
739
740 // If this is a postinc, return the value read from memory, otherwise use the
741 // updated value.
742 if (E->getOpcode() == UnaryOperator::PreDec ||
743 E->getOpcode() == UnaryOperator::PreInc)
744 return NextValToStore;
745 else
746 return InVal;
747}
748
Reid Spencer5f016e22007-07-11 17:01:13 +0000749/// C99 6.5.3.2
750RValue CodeGenFunction::EmitUnaryAddrOf(const UnaryOperator *E) {
751 // The address of the operand is just its lvalue. It cannot be a bitfield.
752 return RValue::get(EmitLValue(E->getSubExpr()).getAddress());
753}
754
755RValue CodeGenFunction::EmitUnaryPlus(const UnaryOperator *E) {
756 // Unary plus just performs promotions on its arithmetic operand.
757 QualType Ty;
758 return EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
759}
760
761RValue CodeGenFunction::EmitUnaryMinus(const UnaryOperator *E) {
762 // Unary minus performs promotions, then negates its arithmetic operand.
763 QualType Ty;
764 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
765
766 if (V.isScalar())
767 return RValue::get(Builder.CreateNeg(V.getVal(), "neg"));
768
769 assert(0 && "FIXME: This doesn't handle complex operands yet");
770}
771
772RValue CodeGenFunction::EmitUnaryNot(const UnaryOperator *E) {
773 // Unary not performs promotions, then complements its integer operand.
774 QualType Ty;
775 RValue V = EmitExprWithUsualUnaryConversions(E->getSubExpr(), Ty);
776
777 if (V.isScalar())
778 return RValue::get(Builder.CreateNot(V.getVal(), "neg"));
779
780 assert(0 && "FIXME: This doesn't handle integer complex operands yet (GNU)");
781}
782
783
784/// C99 6.5.3.3
785RValue CodeGenFunction::EmitUnaryLNot(const UnaryOperator *E) {
786 // Compare operand to zero.
787 llvm::Value *BoolVal = EvaluateExprAsBool(E->getSubExpr());
788
789 // Invert value.
790 // TODO: Could dynamically modify easy computations here. For example, if
791 // the operand is an icmp ne, turn into icmp eq.
792 BoolVal = Builder.CreateNot(BoolVal, "lnot");
793
794 // ZExt result to int.
795 return RValue::get(Builder.CreateZExt(BoolVal, LLVMIntTy, "lnot.ext"));
796}
797
Chris Lattner5e3fbe52007-07-18 18:12:07 +0000798/// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
799/// an integer (RetType).
800RValue CodeGenFunction::EmitSizeAlignOf(QualType TypeToSize,
801 QualType RetType, bool isSizeOf) {
802 /// FIXME: This doesn't handle VLAs yet!
803 std::pair<uint64_t, unsigned> Info =
804 getContext().getTypeInfo(TypeToSize, SourceLocation());
805
806 uint64_t Val = isSizeOf ? Info.first : Info.second;
807 Val /= 8; // Return size in bytes, not bits.
808
809 assert(RetType->isIntegerType() && "Result type must be an integer!");
810
811 unsigned ResultWidth = getContext().getTypeSize(RetType, SourceLocation());
812 return RValue::get(llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val)));
813}
814
Reid Spencer5f016e22007-07-11 17:01:13 +0000815
816//===--------------------------------------------------------------------===//
817// Binary Operator Emission
818//===--------------------------------------------------------------------===//
819
820// FIXME describe.
821QualType CodeGenFunction::
822EmitUsualArithmeticConversions(const BinaryOperator *E, RValue &LHS,
823 RValue &RHS) {
824 QualType LHSType, RHSType;
825 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSType);
826 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSType);
827
828 // If both operands have the same source type, we're done already.
829 if (LHSType == RHSType) return LHSType;
830
831 // If either side is a non-arithmetic type (e.g. a pointer), we are done.
832 // The caller can deal with this (e.g. pointer + int).
833 if (!LHSType->isArithmeticType() || !RHSType->isArithmeticType())
834 return LHSType;
835
836 // At this point, we have two different arithmetic types.
837
838 // Handle complex types first (C99 6.3.1.8p1).
839 if (LHSType->isComplexType() || RHSType->isComplexType()) {
840 assert(0 && "FIXME: complex types unimp");
841#if 0
842 // if we have an integer operand, the result is the complex type.
843 if (rhs->isIntegerType())
844 return lhs;
845 if (lhs->isIntegerType())
846 return rhs;
847 return Context.maxComplexType(lhs, rhs);
848#endif
849 }
850
851 // If neither operand is complex, they must be scalars.
852 llvm::Value *LHSV = LHS.getVal();
853 llvm::Value *RHSV = RHS.getVal();
854
855 // If the LLVM types are already equal, then they only differed in sign, or it
856 // was something like char/signed char or double/long double.
857 if (LHSV->getType() == RHSV->getType())
858 return LHSType;
859
860 // Now handle "real" floating types (i.e. float, double, long double).
861 if (LHSType->isRealFloatingType() || RHSType->isRealFloatingType()) {
862 // if we have an integer operand, the result is the real floating type, and
863 // the integer converts to FP.
864 if (RHSType->isIntegerType()) {
865 // Promote the RHS to an FP type of the LHS, with the sign following the
866 // RHS.
867 if (RHSType->isSignedIntegerType())
868 RHS = RValue::get(Builder.CreateSIToFP(RHSV,LHSV->getType(),"promote"));
869 else
870 RHS = RValue::get(Builder.CreateUIToFP(RHSV,LHSV->getType(),"promote"));
871 return LHSType;
872 }
873
874 if (LHSType->isIntegerType()) {
875 // Promote the LHS to an FP type of the RHS, with the sign following the
876 // LHS.
877 if (LHSType->isSignedIntegerType())
878 LHS = RValue::get(Builder.CreateSIToFP(LHSV,RHSV->getType(),"promote"));
879 else
880 LHS = RValue::get(Builder.CreateUIToFP(LHSV,RHSV->getType(),"promote"));
881 return RHSType;
882 }
883
884 // Otherwise, they are two FP types. Promote the smaller operand to the
885 // bigger result.
886 QualType BiggerType = ASTContext::maxFloatingType(LHSType, RHSType);
887
888 if (BiggerType == LHSType)
889 RHS = RValue::get(Builder.CreateFPExt(RHSV, LHSV->getType(), "promote"));
890 else
891 LHS = RValue::get(Builder.CreateFPExt(LHSV, RHSV->getType(), "promote"));
892 return BiggerType;
893 }
894
895 // Finally, we have two integer types that are different according to C. Do
896 // a sign or zero extension if needed.
897
898 // Otherwise, one type is smaller than the other.
899 QualType ResTy = ASTContext::maxIntegerType(LHSType, RHSType);
900
901 if (LHSType == ResTy) {
902 if (RHSType->isSignedIntegerType())
903 RHS = RValue::get(Builder.CreateSExt(RHSV, LHSV->getType(), "promote"));
904 else
905 RHS = RValue::get(Builder.CreateZExt(RHSV, LHSV->getType(), "promote"));
906 } else {
907 assert(RHSType == ResTy && "Unknown conversion");
908 if (LHSType->isSignedIntegerType())
909 LHS = RValue::get(Builder.CreateSExt(LHSV, RHSV->getType(), "promote"));
910 else
911 LHS = RValue::get(Builder.CreateZExt(LHSV, RHSV->getType(), "promote"));
912 }
913 return ResTy;
914}
915
916/// EmitCompoundAssignmentOperands - Compound assignment operations (like +=)
917/// are strange in that the result of the operation is not the same type as the
918/// intermediate computation. This function emits the LHS and RHS operands of
919/// the compound assignment, promoting them to their common computation type.
920///
921/// Since the LHS is an lvalue, and the result is stored back through it, we
922/// return the lvalue as well as the LHS/RHS rvalues. On return, the LHS and
923/// RHS values are both in the computation type for the operator.
924void CodeGenFunction::
925EmitCompoundAssignmentOperands(const CompoundAssignOperator *E,
926 LValue &LHSLV, RValue &LHS, RValue &RHS) {
927 LHSLV = EmitLValue(E->getLHS());
928
929 // Load the LHS and RHS operands.
930 QualType LHSTy = E->getLHS()->getType();
931 LHS = EmitLoadOfLValue(LHSLV, LHSTy);
932 QualType RHSTy;
933 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
934
935 // Shift operands do the usual unary conversions, but do not do the binary
936 // conversions.
937 if (E->isShiftAssignOp()) {
938 // FIXME: This is broken. Implicit conversions should be made explicit,
939 // so that this goes away. This causes us to reload the LHS.
940 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy);
941 }
942
943 // Convert the LHS and RHS to the common evaluation type.
944 LHS = EmitConversion(LHS, LHSTy, E->getComputationType());
945 RHS = EmitConversion(RHS, RHSTy, E->getComputationType());
946}
947
948/// EmitCompoundAssignmentResult - Given a result value in the computation type,
949/// truncate it down to the actual result type, store it through the LHS lvalue,
950/// and return it.
951RValue CodeGenFunction::
952EmitCompoundAssignmentResult(const CompoundAssignOperator *E,
953 LValue LHSLV, RValue ResV) {
954
955 // Truncate back to the destination type.
956 if (E->getComputationType() != E->getType())
957 ResV = EmitConversion(ResV, E->getComputationType(), E->getType());
958
959 // Store the result value into the LHS.
960 EmitStoreThroughLValue(ResV, LHSLV, E->getType());
961
962 // Return the result.
963 return ResV;
964}
965
966
967RValue CodeGenFunction::EmitBinaryOperator(const BinaryOperator *E) {
968 RValue LHS, RHS;
969 switch (E->getOpcode()) {
970 default:
971 fprintf(stderr, "Unimplemented binary expr!\n");
972 E->dump();
973 return RValue::get(llvm::UndefValue::get(llvm::Type::Int32Ty));
974 case BinaryOperator::Mul:
975 EmitUsualArithmeticConversions(E, LHS, RHS);
976 return EmitMul(LHS, RHS, E->getType());
977 case BinaryOperator::Div:
978 EmitUsualArithmeticConversions(E, LHS, RHS);
979 return EmitDiv(LHS, RHS, E->getType());
980 case BinaryOperator::Rem:
981 EmitUsualArithmeticConversions(E, LHS, RHS);
982 return EmitRem(LHS, RHS, E->getType());
Chris Lattner8b9023b2007-07-13 03:05:23 +0000983 case BinaryOperator::Add: {
984 QualType ExprTy = E->getType();
985 if (ExprTy->isPointerType()) {
986 Expr *LHSExpr = E->getLHS();
987 QualType LHSTy;
988 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
989 Expr *RHSExpr = E->getRHS();
990 QualType RHSTy;
991 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
992 return EmitPointerAdd(LHS, LHSTy, RHS, RHSTy, ExprTy);
993 } else {
994 EmitUsualArithmeticConversions(E, LHS, RHS);
995 return EmitAdd(LHS, RHS, ExprTy);
996 }
997 }
998 case BinaryOperator::Sub: {
999 QualType ExprTy = E->getType();
1000 Expr *LHSExpr = E->getLHS();
1001 if (LHSExpr->getType()->isPointerType()) {
1002 QualType LHSTy;
1003 LHS = EmitExprWithUsualUnaryConversions(LHSExpr, LHSTy);
1004 Expr *RHSExpr = E->getRHS();
1005 QualType RHSTy;
1006 RHS = EmitExprWithUsualUnaryConversions(RHSExpr, RHSTy);
1007 return EmitPointerSub(LHS, LHSTy, RHS, RHSTy, ExprTy);
1008 } else {
1009 EmitUsualArithmeticConversions(E, LHS, RHS);
1010 return EmitSub(LHS, RHS, ExprTy);
1011 }
1012 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001013 case BinaryOperator::Shl:
1014 EmitShiftOperands(E, LHS, RHS);
1015 return EmitShl(LHS, RHS, E->getType());
1016 case BinaryOperator::Shr:
1017 EmitShiftOperands(E, LHS, RHS);
1018 return EmitShr(LHS, RHS, E->getType());
1019 case BinaryOperator::And:
1020 EmitUsualArithmeticConversions(E, LHS, RHS);
1021 return EmitAnd(LHS, RHS, E->getType());
1022 case BinaryOperator::Xor:
1023 EmitUsualArithmeticConversions(E, LHS, RHS);
1024 return EmitXor(LHS, RHS, E->getType());
1025 case BinaryOperator::Or :
1026 EmitUsualArithmeticConversions(E, LHS, RHS);
1027 return EmitOr(LHS, RHS, E->getType());
1028 case BinaryOperator::LAnd: return EmitBinaryLAnd(E);
1029 case BinaryOperator::LOr: return EmitBinaryLOr(E);
1030 case BinaryOperator::LT:
1031 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULT,
1032 llvm::ICmpInst::ICMP_SLT,
1033 llvm::FCmpInst::FCMP_OLT);
1034 case BinaryOperator::GT:
1035 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGT,
1036 llvm::ICmpInst::ICMP_SGT,
1037 llvm::FCmpInst::FCMP_OGT);
1038 case BinaryOperator::LE:
1039 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_ULE,
1040 llvm::ICmpInst::ICMP_SLE,
1041 llvm::FCmpInst::FCMP_OLE);
1042 case BinaryOperator::GE:
1043 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_UGE,
1044 llvm::ICmpInst::ICMP_SGE,
1045 llvm::FCmpInst::FCMP_OGE);
1046 case BinaryOperator::EQ:
1047 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_EQ,
1048 llvm::ICmpInst::ICMP_EQ,
1049 llvm::FCmpInst::FCMP_OEQ);
1050 case BinaryOperator::NE:
1051 return EmitBinaryCompare(E, llvm::ICmpInst::ICMP_NE,
1052 llvm::ICmpInst::ICMP_NE,
1053 llvm::FCmpInst::FCMP_UNE);
1054 case BinaryOperator::Assign:
1055 return EmitBinaryAssign(E);
1056
1057 case BinaryOperator::MulAssign: {
1058 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1059 LValue LHSLV;
1060 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1061 LHS = EmitMul(LHS, RHS, CAO->getComputationType());
1062 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1063 }
1064 case BinaryOperator::DivAssign: {
1065 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1066 LValue LHSLV;
1067 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1068 LHS = EmitDiv(LHS, RHS, CAO->getComputationType());
1069 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1070 }
1071 case BinaryOperator::RemAssign: {
1072 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1073 LValue LHSLV;
1074 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1075 LHS = EmitRem(LHS, RHS, CAO->getComputationType());
1076 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1077 }
1078 case BinaryOperator::AddAssign: {
1079 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1080 LValue LHSLV;
1081 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1082 LHS = EmitAdd(LHS, RHS, CAO->getComputationType());
1083 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1084 }
1085 case BinaryOperator::SubAssign: {
1086 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1087 LValue LHSLV;
1088 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1089 LHS = EmitSub(LHS, RHS, CAO->getComputationType());
1090 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1091 }
1092 case BinaryOperator::ShlAssign: {
1093 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1094 LValue LHSLV;
1095 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1096 LHS = EmitShl(LHS, RHS, CAO->getComputationType());
1097 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1098 }
1099 case BinaryOperator::ShrAssign: {
1100 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1101 LValue LHSLV;
1102 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1103 LHS = EmitShr(LHS, RHS, CAO->getComputationType());
1104 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1105 }
1106 case BinaryOperator::AndAssign: {
1107 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1108 LValue LHSLV;
1109 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1110 LHS = EmitAnd(LHS, RHS, CAO->getComputationType());
1111 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1112 }
1113 case BinaryOperator::OrAssign: {
1114 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1115 LValue LHSLV;
1116 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1117 LHS = EmitOr(LHS, RHS, CAO->getComputationType());
1118 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1119 }
1120 case BinaryOperator::XorAssign: {
1121 const CompoundAssignOperator *CAO = cast<CompoundAssignOperator>(E);
1122 LValue LHSLV;
1123 EmitCompoundAssignmentOperands(CAO, LHSLV, LHS, RHS);
1124 LHS = EmitXor(LHS, RHS, CAO->getComputationType());
1125 return EmitCompoundAssignmentResult(CAO, LHSLV, LHS);
1126 }
1127 case BinaryOperator::Comma: return EmitBinaryComma(E);
1128 }
1129}
1130
1131RValue CodeGenFunction::EmitMul(RValue LHS, RValue RHS, QualType ResTy) {
1132 if (LHS.isScalar())
1133 return RValue::get(Builder.CreateMul(LHS.getVal(), RHS.getVal(), "mul"));
1134
Gabor Greif4db18f22007-07-13 23:33:18 +00001135 // Otherwise, this must be a complex number.
1136 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1137
1138 EmitLoadOfComplex(LHS, LHSR, LHSI);
1139 EmitLoadOfComplex(RHS, RHSR, RHSI);
1140
1141 llvm::Value *ResRl = Builder.CreateMul(LHSR, RHSR, "mul.rl");
1142 llvm::Value *ResRr = Builder.CreateMul(LHSI, RHSI, "mul.rr");
1143 llvm::Value *ResR = Builder.CreateSub(ResRl, ResRr, "mul.r");
1144
1145 llvm::Value *ResIl = Builder.CreateMul(LHSI, RHSR, "mul.il");
1146 llvm::Value *ResIr = Builder.CreateMul(LHSR, RHSI, "mul.ir");
1147 llvm::Value *ResI = Builder.CreateAdd(ResIl, ResIr, "mul.i");
1148
1149 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1150 EmitStoreOfComplex(ResR, ResI, Res);
1151 return RValue::getAggregate(Res);
Reid Spencer5f016e22007-07-11 17:01:13 +00001152}
1153
1154RValue CodeGenFunction::EmitDiv(RValue LHS, RValue RHS, QualType ResTy) {
1155 if (LHS.isScalar()) {
1156 llvm::Value *RV;
1157 if (LHS.getVal()->getType()->isFloatingPoint())
1158 RV = Builder.CreateFDiv(LHS.getVal(), RHS.getVal(), "div");
1159 else if (ResTy->isUnsignedIntegerType())
1160 RV = Builder.CreateUDiv(LHS.getVal(), RHS.getVal(), "div");
1161 else
1162 RV = Builder.CreateSDiv(LHS.getVal(), RHS.getVal(), "div");
1163 return RValue::get(RV);
1164 }
1165 assert(0 && "FIXME: This doesn't handle complex operands yet");
1166}
1167
1168RValue CodeGenFunction::EmitRem(RValue LHS, RValue RHS, QualType ResTy) {
1169 if (LHS.isScalar()) {
1170 llvm::Value *RV;
1171 // Rem in C can't be a floating point type: C99 6.5.5p2.
1172 if (ResTy->isUnsignedIntegerType())
1173 RV = Builder.CreateURem(LHS.getVal(), RHS.getVal(), "rem");
1174 else
1175 RV = Builder.CreateSRem(LHS.getVal(), RHS.getVal(), "rem");
1176 return RValue::get(RV);
1177 }
1178
1179 assert(0 && "FIXME: This doesn't handle complex operands yet");
1180}
1181
1182RValue CodeGenFunction::EmitAdd(RValue LHS, RValue RHS, QualType ResTy) {
1183 if (LHS.isScalar())
1184 return RValue::get(Builder.CreateAdd(LHS.getVal(), RHS.getVal(), "add"));
1185
1186 // Otherwise, this must be a complex number.
1187 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI;
1188
1189 EmitLoadOfComplex(LHS, LHSR, LHSI);
1190 EmitLoadOfComplex(RHS, RHSR, RHSI);
1191
1192 llvm::Value *ResR = Builder.CreateAdd(LHSR, RHSR, "add.r");
1193 llvm::Value *ResI = Builder.CreateAdd(LHSI, RHSI, "add.i");
1194
1195 llvm::Value *Res = CreateTempAlloca(ConvertType(ResTy));
1196 EmitStoreOfComplex(ResR, ResI, Res);
1197 return RValue::getAggregate(Res);
1198}
1199
Chris Lattner8b9023b2007-07-13 03:05:23 +00001200RValue CodeGenFunction::EmitPointerAdd(RValue LHS, QualType LHSTy,
1201 RValue RHS, QualType RHSTy,
1202 QualType ResTy) {
1203 llvm::Value *LHSValue = LHS.getVal();
1204 llvm::Value *RHSValue = RHS.getVal();
1205 if (LHSTy->isPointerType()) {
1206 // pointer + int
1207 return RValue::get(Builder.CreateGEP(LHSValue, RHSValue, "add.ptr"));
1208 } else {
1209 // int + pointer
1210 return RValue::get(Builder.CreateGEP(RHSValue, LHSValue, "add.ptr"));
1211 }
1212}
1213
Reid Spencer5f016e22007-07-11 17:01:13 +00001214RValue CodeGenFunction::EmitSub(RValue LHS, RValue RHS, QualType ResTy) {
1215 if (LHS.isScalar())
1216 return RValue::get(Builder.CreateSub(LHS.getVal(), RHS.getVal(), "sub"));
1217
1218 assert(0 && "FIXME: This doesn't handle complex operands yet");
1219}
1220
Chris Lattner8b9023b2007-07-13 03:05:23 +00001221RValue CodeGenFunction::EmitPointerSub(RValue LHS, QualType LHSTy,
1222 RValue RHS, QualType RHSTy,
1223 QualType ResTy) {
1224 llvm::Value *LHSValue = LHS.getVal();
1225 llvm::Value *RHSValue = RHS.getVal();
1226 if (const PointerType *RHSPtrType =
1227 dyn_cast<PointerType>(RHSTy.getTypePtr())) {
1228 // pointer - pointer
1229 const PointerType *LHSPtrType = cast<PointerType>(LHSTy.getTypePtr());
1230 QualType LHSElementType = LHSPtrType->getPointeeType();
1231 assert(LHSElementType == RHSPtrType->getPointeeType() &&
1232 "can't subtract pointers with differing element types");
Chris Lattner99e0d792007-07-16 05:43:05 +00001233 uint64_t ElementSize = getContext().getTypeSize(LHSElementType,
Chris Lattnerd2d2a112007-07-14 01:29:45 +00001234 SourceLocation()) / 8;
Chris Lattner8b9023b2007-07-13 03:05:23 +00001235 const llvm::Type *ResultType = ConvertType(ResTy);
1236 llvm::Value *CastLHS = Builder.CreatePtrToInt(LHSValue, ResultType,
1237 "sub.ptr.lhs.cast");
1238 llvm::Value *CastRHS = Builder.CreatePtrToInt(RHSValue, ResultType,
1239 "sub.ptr.rhs.cast");
1240 llvm::Value *BytesBetween = Builder.CreateSub(CastLHS, CastRHS,
1241 "sub.ptr.sub");
Chris Lattner99e0d792007-07-16 05:43:05 +00001242
1243 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1244 // remainder. As such, we handle common power-of-two cases here to generate
1245 // better code.
1246 if (llvm::isPowerOf2_64(ElementSize)) {
1247 llvm::Value *ShAmt =
1248 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
1249 return RValue::get(Builder.CreateAShr(BytesBetween, ShAmt,"sub.ptr.shr"));
1250 } else {
1251 // Otherwise, do a full sdiv.
1252 llvm::Value *BytesPerElement =
1253 llvm::ConstantInt::get(ResultType, ElementSize);
1254 return RValue::get(Builder.CreateSDiv(BytesBetween, BytesPerElement,
1255 "sub.ptr.div"));
1256 }
Chris Lattner8b9023b2007-07-13 03:05:23 +00001257 } else {
1258 // pointer - int
1259 llvm::Value *NegatedRHS = Builder.CreateNeg(RHSValue, "sub.ptr.neg");
1260 return RValue::get(Builder.CreateGEP(LHSValue, NegatedRHS, "sub.ptr"));
1261 }
1262}
1263
Reid Spencer5f016e22007-07-11 17:01:13 +00001264void CodeGenFunction::EmitShiftOperands(const BinaryOperator *E,
1265 RValue &LHS, RValue &RHS) {
1266 // For shifts, integer promotions are performed, but the usual arithmetic
1267 // conversions are not. The LHS and RHS need not have the same type.
1268 QualType ResTy;
1269 LHS = EmitExprWithUsualUnaryConversions(E->getLHS(), ResTy);
1270 RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), ResTy);
1271}
1272
1273
1274RValue CodeGenFunction::EmitShl(RValue LHSV, RValue RHSV, QualType ResTy) {
1275 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1276
1277 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1278 // RHS to the same size as the LHS.
1279 if (LHS->getType() != RHS->getType())
1280 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1281
1282 return RValue::get(Builder.CreateShl(LHS, RHS, "shl"));
1283}
1284
1285RValue CodeGenFunction::EmitShr(RValue LHSV, RValue RHSV, QualType ResTy) {
1286 llvm::Value *LHS = LHSV.getVal(), *RHS = RHSV.getVal();
1287
1288 // LLVM requires the LHS and RHS to be the same type, promote or truncate the
1289 // RHS to the same size as the LHS.
1290 if (LHS->getType() != RHS->getType())
1291 RHS = Builder.CreateIntCast(RHS, LHS->getType(), false, "sh_prom");
1292
1293 if (ResTy->isUnsignedIntegerType())
1294 return RValue::get(Builder.CreateLShr(LHS, RHS, "shr"));
1295 else
1296 return RValue::get(Builder.CreateAShr(LHS, RHS, "shr"));
1297}
1298
1299RValue CodeGenFunction::EmitBinaryCompare(const BinaryOperator *E,
1300 unsigned UICmpOpc, unsigned SICmpOpc,
1301 unsigned FCmpOpc) {
1302 RValue LHS, RHS;
1303 EmitUsualArithmeticConversions(E, LHS, RHS);
1304
1305 llvm::Value *Result;
1306 if (LHS.isScalar()) {
1307 if (LHS.getVal()->getType()->isFloatingPoint()) {
1308 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1309 LHS.getVal(), RHS.getVal(), "cmp");
1310 } else if (E->getLHS()->getType()->isUnsignedIntegerType()) {
1311 // FIXME: This check isn't right for "unsigned short < int" where ushort
1312 // promotes to int and does a signed compare.
1313 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1314 LHS.getVal(), RHS.getVal(), "cmp");
1315 } else {
1316 // Signed integers and pointers.
1317 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1318 LHS.getVal(), RHS.getVal(), "cmp");
1319 }
1320 } else {
1321 // Struct/union/complex
Gabor Greif4db18f22007-07-13 23:33:18 +00001322 llvm::Value *LHSR, *LHSI, *RHSR, *RHSI, *ResultR, *ResultI;
1323 EmitLoadOfComplex(LHS, LHSR, LHSI);
1324 EmitLoadOfComplex(RHS, RHSR, RHSI);
1325
Gabor Greifd5e0d982007-07-14 20:05:18 +00001326 // FIXME: need to consider _Complex over integers too!
1327
Gabor Greif4db18f22007-07-13 23:33:18 +00001328 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1329 LHSR, RHSR, "cmp.r");
1330 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1331 LHSI, RHSI, "cmp.i");
1332 if (BinaryOperator::EQ == E->getOpcode()) {
1333 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1334 } else if (BinaryOperator::NE == E->getOpcode()) {
1335 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1336 } else {
1337 assert(0 && "Complex comparison other than == or != ?");
1338 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 }
Gabor Greif4db18f22007-07-13 23:33:18 +00001340
Reid Spencer5f016e22007-07-11 17:01:13 +00001341 // ZExt result to int.
1342 return RValue::get(Builder.CreateZExt(Result, LLVMIntTy, "cmp.ext"));
1343}
1344
1345RValue CodeGenFunction::EmitAnd(RValue LHS, RValue RHS, QualType ResTy) {
1346 if (LHS.isScalar())
1347 return RValue::get(Builder.CreateAnd(LHS.getVal(), RHS.getVal(), "and"));
1348
1349 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1350}
1351
1352RValue CodeGenFunction::EmitXor(RValue LHS, RValue RHS, QualType ResTy) {
1353 if (LHS.isScalar())
1354 return RValue::get(Builder.CreateXor(LHS.getVal(), RHS.getVal(), "xor"));
1355
1356 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1357}
1358
1359RValue CodeGenFunction::EmitOr(RValue LHS, RValue RHS, QualType ResTy) {
1360 if (LHS.isScalar())
1361 return RValue::get(Builder.CreateOr(LHS.getVal(), RHS.getVal(), "or"));
1362
1363 assert(0 && "FIXME: This doesn't handle complex integer operands yet (GNU)");
1364}
1365
1366RValue CodeGenFunction::EmitBinaryLAnd(const BinaryOperator *E) {
1367 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1368
1369 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
1370 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
1371
1372 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1373 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
1374
1375 EmitBlock(RHSBlock);
1376 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1377
1378 // Reaquire the RHS block, as there may be subblocks inserted.
1379 RHSBlock = Builder.GetInsertBlock();
1380 EmitBlock(ContBlock);
1381
1382 // Create a PHI node. If we just evaluted the LHS condition, the result is
1383 // false. If we evaluated both, the result is the RHS condition.
1384 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
1385 PN->reserveOperandSpace(2);
1386 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
1387 PN->addIncoming(RHSCond, RHSBlock);
1388
1389 // ZExt result to int.
1390 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "land.ext"));
1391}
1392
1393RValue CodeGenFunction::EmitBinaryLOr(const BinaryOperator *E) {
1394 llvm::Value *LHSCond = EvaluateExprAsBool(E->getLHS());
1395
1396 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
1397 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
1398
1399 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
1400 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
1401
1402 EmitBlock(RHSBlock);
1403 llvm::Value *RHSCond = EvaluateExprAsBool(E->getRHS());
1404
1405 // Reaquire the RHS block, as there may be subblocks inserted.
1406 RHSBlock = Builder.GetInsertBlock();
1407 EmitBlock(ContBlock);
1408
1409 // Create a PHI node. If we just evaluted the LHS condition, the result is
1410 // true. If we evaluated both, the result is the RHS condition.
1411 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
1412 PN->reserveOperandSpace(2);
1413 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
1414 PN->addIncoming(RHSCond, RHSBlock);
1415
1416 // ZExt result to int.
1417 return RValue::get(Builder.CreateZExt(PN, LLVMIntTy, "lor.ext"));
1418}
1419
1420RValue CodeGenFunction::EmitBinaryAssign(const BinaryOperator *E) {
1421 LValue LHS = EmitLValue(E->getLHS());
1422
1423 QualType RHSTy;
1424 RValue RHS = EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy);
1425
1426 // Convert the RHS to the type of the LHS.
1427 RHS = EmitConversion(RHS, RHSTy, E->getType());
1428
1429 // Store the value into the LHS.
1430 EmitStoreThroughLValue(RHS, LHS, E->getType());
1431
1432 // Return the converted RHS.
1433 return RHS;
1434}
1435
1436
1437RValue CodeGenFunction::EmitBinaryComma(const BinaryOperator *E) {
1438 EmitExpr(E->getLHS());
1439 return EmitExpr(E->getRHS());
1440}
Chris Lattnerb0a721a2007-07-13 05:18:11 +00001441
1442RValue CodeGenFunction::EmitConditionalOperator(const ConditionalOperator *E) {
1443 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
1444 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
1445 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
1446
1447 llvm::Value *Cond = EvaluateExprAsBool(E->getCond());
1448 Builder.CreateCondBr(Cond, LHSBlock, RHSBlock);
1449
Chris Lattner06c8d962007-07-14 00:01:01 +00001450 // FIXME: Implement this for aggregate values.
1451
Chris Lattnerb0a721a2007-07-13 05:18:11 +00001452 // FIXME: LHS & RHS need the "usual arithmetic conversions" but
1453 // that's not possible with the current design.
1454
1455 EmitBlock(LHSBlock);
1456 QualType LHSTy;
1457 llvm::Value *LHSValue = E->getLHS() ? // GNU extension
1458 EmitExprWithUsualUnaryConversions(E->getLHS(), LHSTy).getVal() :
1459 Cond;
1460 Builder.CreateBr(ContBlock);
1461 LHSBlock = Builder.GetInsertBlock();
1462
1463 EmitBlock(RHSBlock);
1464 QualType RHSTy;
1465 llvm::Value *RHSValue =
1466 EmitExprWithUsualUnaryConversions(E->getRHS(), RHSTy).getVal();
1467 Builder.CreateBr(ContBlock);
1468 RHSBlock = Builder.GetInsertBlock();
1469
1470 const llvm::Type *LHSType = LHSValue->getType();
1471 assert(LHSType == RHSValue->getType() && "?: LHS & RHS must have same type");
1472
1473 EmitBlock(ContBlock);
1474 llvm::PHINode *PN = Builder.CreatePHI(LHSType, "cond");
1475 PN->reserveOperandSpace(2);
1476 PN->addIncoming(LHSValue, LHSBlock);
1477 PN->addIncoming(RHSValue, RHSBlock);
1478
1479 return RValue::get(PN);
1480}