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