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