1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
15 #include "CodeGenModule.h"
16 #include "clang/AST/AST.h"
17 #include "llvm/Constants.h"
18 #include "llvm/Function.h"
19 #include "llvm/GlobalVariable.h"
20 #include "llvm/Intrinsics.h"
21 #include "llvm/Support/Compiler.h"
24 using namespace clang;
25 using namespace CodeGen;
28 //===----------------------------------------------------------------------===//
29 // Scalar Expression Emitter
30 //===----------------------------------------------------------------------===//
35 QualType Ty; // Computation Type.
36 const BinaryOperator *E;
40 class VISIBILITY_HIDDEN ScalarExprEmitter
41 : public StmtVisitor<ScalarExprEmitter, Value*> {
43 llvm::LLVMFoldingBuilder &Builder;
46 ScalarExprEmitter(CodeGenFunction &cgf) : CGF(cgf), Builder(CGF.Builder) {
50 //===--------------------------------------------------------------------===//
52 //===--------------------------------------------------------------------===//
54 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
55 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
57 Value *EmitLoadOfLValue(LValue LV, QualType T) {
58 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
61 /// EmitLoadOfLValue - Given an expression with complex type that represents a
62 /// value l-value, this method emits the address of the l-value, then loads
63 /// and returns the result.
64 Value *EmitLoadOfLValue(const Expr *E) {
66 return EmitLoadOfLValue(EmitLValue(E), E->getType());
69 /// EmitConversionToBool - Convert the specified expression value to a
70 /// boolean (i1) truth value. This is equivalent to "Val != 0".
71 Value *EmitConversionToBool(Value *Src, QualType DstTy);
73 /// EmitScalarConversion - Emit a conversion from the specified type to the
74 /// specified destination type, both of which are LLVM scalar types.
75 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
77 /// EmitComplexToScalarConversion - Emit a conversion from the specified
78 /// complex type to the specified destination type, where the destination
79 /// type is an LLVM scalar type.
80 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
81 QualType SrcTy, QualType DstTy);
83 //===--------------------------------------------------------------------===//
85 //===--------------------------------------------------------------------===//
87 Value *VisitStmt(Stmt *S) {
88 S->dump(CGF.getContext().getSourceManager());
89 assert(0 && "Stmt can't have complex result type!");
92 Value *VisitExpr(Expr *S);
93 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
96 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
97 return llvm::ConstantInt::get(E->getValue());
99 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
100 return llvm::ConstantFP::get(ConvertType(E->getType()), E->getValue());
102 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
103 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
105 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
106 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
108 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
109 return llvm::ConstantInt::get(ConvertType(E->getType()),
110 CGF.getContext().typesAreCompatible(
111 E->getArgType1(), E->getArgType2()));
113 Value *VisitSizeOfAlignOfTypeExpr(const SizeOfAlignOfTypeExpr *E) {
114 return EmitSizeAlignOf(E->getArgumentType(), E->getType(), E->isSizeOf());
118 Value *VisitDeclRefExpr(DeclRefExpr *E) {
119 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
120 return llvm::ConstantInt::get(EC->getInitVal());
121 return EmitLoadOfLValue(E);
123 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
124 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
125 Value *VisitOCUVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
126 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
127 Value *VisitPreDefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
129 Value *VisitInitListExpr(InitListExpr *E) {
130 unsigned NumInitElements = E->getNumInits();
132 const llvm::VectorType *VType =
133 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
135 // We have a scalar in braces. Just use the first element.
137 return Visit(E->getInit(0));
139 unsigned NumVectorElements = VType->getNumElements();
140 const llvm::Type *ElementType = VType->getElementType();
142 // Emit individual vector element stores.
143 llvm::Value *V = llvm::UndefValue::get(VType);
147 for (i = 0; i < NumInitElements; ++i) {
148 Value *NewV = Visit(E->getInit(i));
149 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
150 V = Builder.CreateInsertElement(V, NewV, Idx);
153 // Emit remaining default initializers
154 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
155 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
156 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
157 V = Builder.CreateInsertElement(V, NewV, Idx);
163 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
164 return Visit(E->getInitializer());
167 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
168 Value *VisitCastExpr(const CastExpr *E) {
169 return EmitCastExpr(E->getSubExpr(), E->getType());
171 Value *EmitCastExpr(const Expr *E, QualType T);
173 Value *VisitCallExpr(const CallExpr *E) {
174 return CGF.EmitCallExpr(E).getScalarVal();
177 Value *VisitStmtExpr(const StmtExpr *E);
180 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
181 Value *VisitUnaryPostDec(const UnaryOperator *E) {
182 return VisitPrePostIncDec(E, false, false);
184 Value *VisitUnaryPostInc(const UnaryOperator *E) {
185 return VisitPrePostIncDec(E, true, false);
187 Value *VisitUnaryPreDec(const UnaryOperator *E) {
188 return VisitPrePostIncDec(E, false, true);
190 Value *VisitUnaryPreInc(const UnaryOperator *E) {
191 return VisitPrePostIncDec(E, true, true);
193 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
194 return EmitLValue(E->getSubExpr()).getAddress();
196 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
197 Value *VisitUnaryPlus(const UnaryOperator *E) {
198 return Visit(E->getSubExpr());
200 Value *VisitUnaryMinus (const UnaryOperator *E);
201 Value *VisitUnaryNot (const UnaryOperator *E);
202 Value *VisitUnaryLNot (const UnaryOperator *E);
203 Value *VisitUnarySizeOf (const UnaryOperator *E) {
204 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), true);
206 Value *VisitUnaryAlignOf (const UnaryOperator *E) {
207 return EmitSizeAlignOf(E->getSubExpr()->getType(), E->getType(), false);
209 Value *EmitSizeAlignOf(QualType TypeToSize, QualType RetType,
211 Value *VisitUnaryReal (const UnaryOperator *E);
212 Value *VisitUnaryImag (const UnaryOperator *E);
213 Value *VisitUnaryExtension(const UnaryOperator *E) {
214 return Visit(E->getSubExpr());
216 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
219 Value *EmitMul(const BinOpInfo &Ops) {
220 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
222 Value *EmitDiv(const BinOpInfo &Ops);
223 Value *EmitRem(const BinOpInfo &Ops);
224 Value *EmitAdd(const BinOpInfo &Ops);
225 Value *EmitSub(const BinOpInfo &Ops);
226 Value *EmitShl(const BinOpInfo &Ops);
227 Value *EmitShr(const BinOpInfo &Ops);
228 Value *EmitAnd(const BinOpInfo &Ops) {
229 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
231 Value *EmitXor(const BinOpInfo &Ops) {
232 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
234 Value *EmitOr (const BinOpInfo &Ops) {
235 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
238 BinOpInfo EmitBinOps(const BinaryOperator *E);
239 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
240 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
242 // Binary operators and binary compound assignment operators.
243 #define HANDLEBINOP(OP) \
244 Value *VisitBin ## OP(const BinaryOperator *E) { \
245 return Emit ## OP(EmitBinOps(E)); \
247 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
248 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
254 // (Sub) - Sub is handled specially below for ptr-ptr subtract.
261 Value *VisitBinSub(const BinaryOperator *E);
262 Value *VisitBinSubAssign(const CompoundAssignOperator *E) {
263 return EmitCompoundAssign(E, &ScalarExprEmitter::EmitSub);
267 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
268 unsigned SICmpOpc, unsigned FCmpOpc);
269 #define VISITCOMP(CODE, UI, SI, FP) \
270 Value *VisitBin##CODE(const BinaryOperator *E) { \
271 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
272 llvm::FCmpInst::FP); }
273 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
274 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
275 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
276 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
277 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
278 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
281 Value *VisitBinAssign (const BinaryOperator *E);
283 Value *VisitBinLAnd (const BinaryOperator *E);
284 Value *VisitBinLOr (const BinaryOperator *E);
285 Value *VisitBinComma (const BinaryOperator *E);
288 Value *VisitConditionalOperator(const ConditionalOperator *CO);
289 Value *VisitChooseExpr(ChooseExpr *CE);
290 Value *VisitOverloadExpr(OverloadExpr *OE);
291 Value *VisitVAArgExpr(VAArgExpr *VE);
292 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
293 return CGF.EmitObjCStringLiteral(E);
295 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
297 } // end anonymous namespace.
299 //===----------------------------------------------------------------------===//
301 //===----------------------------------------------------------------------===//
303 /// EmitConversionToBool - Convert the specified expression value to a
304 /// boolean (i1) truth value. This is equivalent to "Val != 0".
305 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
306 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
308 if (SrcType->isRealFloatingType()) {
309 // Compare against 0.0 for fp scalars.
310 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
311 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
314 assert((SrcType->isIntegerType() || SrcType->isPointerType()) &&
315 "Unknown scalar type to convert");
317 // Because of the type rules of C, we often end up computing a logical value,
318 // then zero extending it to int, then wanting it as a logical value again.
319 // Optimize this common case.
320 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
321 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
322 Value *Result = ZI->getOperand(0);
323 // If there aren't any more uses, zap the instruction to save space.
324 // Note that there can be more uses, for example if this
325 // is the result of an assignment.
327 ZI->eraseFromParent();
332 // Compare against an integer or pointer null.
333 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
334 return Builder.CreateICmpNE(Src, Zero, "tobool");
337 /// EmitScalarConversion - Emit a conversion from the specified type to the
338 /// specified destination type, both of which are LLVM scalar types.
339 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
341 SrcType = SrcType.getCanonicalType();
342 DstType = DstType.getCanonicalType();
343 if (SrcType == DstType) return Src;
345 if (DstType->isVoidType()) return 0;
347 // Handle conversions to bool first, they are special: comparisons against 0.
348 if (DstType->isBooleanType())
349 return EmitConversionToBool(Src, SrcType);
351 const llvm::Type *DstTy = ConvertType(DstType);
353 // Ignore conversions like int -> uint.
354 if (Src->getType() == DstTy)
357 // Handle pointer conversions next: pointers can only be converted to/from
358 // other pointers and integers.
359 if (isa<PointerType>(DstType)) {
360 // The source value may be an integer, or a pointer.
361 if (isa<llvm::PointerType>(Src->getType()))
362 return Builder.CreateBitCast(Src, DstTy, "conv");
363 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
364 return Builder.CreateIntToPtr(Src, DstTy, "conv");
367 if (isa<PointerType>(SrcType)) {
368 // Must be an ptr to int cast.
369 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
370 return Builder.CreatePtrToInt(Src, DstTy, "conv");
373 // A scalar source can be splatted to an OCU vector of the same element type
374 if (DstType->isOCUVectorType() && !isa<VectorType>(SrcType) &&
375 cast<llvm::VectorType>(DstTy)->getElementType() == Src->getType())
376 return CGF.EmitVector(&Src, DstType->getAsVectorType()->getNumElements(),
379 // Allow bitcast from vector to integer/fp of the same size.
380 if (isa<llvm::VectorType>(Src->getType()) ||
381 isa<llvm::VectorType>(DstTy))
382 return Builder.CreateBitCast(Src, DstTy, "conv");
384 // Finally, we have the arithmetic types: real int/float.
385 if (isa<llvm::IntegerType>(Src->getType())) {
386 bool InputSigned = SrcType->isSignedIntegerType();
387 if (isa<llvm::IntegerType>(DstTy))
388 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
389 else if (InputSigned)
390 return Builder.CreateSIToFP(Src, DstTy, "conv");
392 return Builder.CreateUIToFP(Src, DstTy, "conv");
395 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
396 if (isa<llvm::IntegerType>(DstTy)) {
397 if (DstType->isSignedIntegerType())
398 return Builder.CreateFPToSI(Src, DstTy, "conv");
400 return Builder.CreateFPToUI(Src, DstTy, "conv");
403 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
404 if (DstTy->getTypeID() < Src->getType()->getTypeID())
405 return Builder.CreateFPTrunc(Src, DstTy, "conv");
407 return Builder.CreateFPExt(Src, DstTy, "conv");
410 /// EmitComplexToScalarConversion - Emit a conversion from the specified
411 /// complex type to the specified destination type, where the destination
412 /// type is an LLVM scalar type.
413 Value *ScalarExprEmitter::
414 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
415 QualType SrcTy, QualType DstTy) {
416 // Get the source element type.
417 SrcTy = cast<ComplexType>(SrcTy.getCanonicalType())->getElementType();
419 // Handle conversions to bool first, they are special: comparisons against 0.
420 if (DstTy->isBooleanType()) {
421 // Complex != 0 -> (Real != 0) | (Imag != 0)
422 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
423 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
424 return Builder.CreateOr(Src.first, Src.second, "tobool");
427 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
428 // the imaginary part of the complex value is discarded and the value of the
429 // real part is converted according to the conversion rules for the
430 // corresponding real type.
431 return EmitScalarConversion(Src.first, SrcTy, DstTy);
435 //===----------------------------------------------------------------------===//
437 //===----------------------------------------------------------------------===//
439 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
440 CGF.WarnUnsupported(E, "scalar expression");
441 if (E->getType()->isVoidType())
443 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
446 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
447 // Emit subscript expressions in rvalue context's. For most cases, this just
448 // loads the lvalue formed by the subscript expr. However, we have to be
449 // careful, because the base of a vector subscript is occasionally an rvalue,
450 // so we can't get it as an lvalue.
451 if (!E->getBase()->getType()->isVectorType())
452 return EmitLoadOfLValue(E);
454 // Handle the vector case. The base must be a vector, the index must be an
456 Value *Base = Visit(E->getBase());
457 Value *Idx = Visit(E->getIdx());
459 // FIXME: Convert Idx to i32 type.
460 return Builder.CreateExtractElement(Base, Idx, "vecext");
463 /// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
464 /// also handle things like function to pointer-to-function decay, and array to
466 Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
467 const Expr *Op = E->getSubExpr();
469 // If this is due to array->pointer conversion, emit the array expression as
471 if (Op->getType()->isArrayType()) {
472 // FIXME: For now we assume that all source arrays map to LLVM arrays. This
473 // will not true when we add support for VLAs.
474 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
476 assert(isa<llvm::PointerType>(V->getType()) &&
477 isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
478 ->getElementType()) &&
479 "Doesn't support VLAs yet!");
480 llvm::Constant *Idx0 = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
482 llvm::Value *Ops[] = {Idx0, Idx0};
483 V = Builder.CreateGEP(V, Ops, Ops+2, "arraydecay");
485 // The resultant pointer type can be implicitly casted to other pointer
486 // types as well, for example void*.
487 const llvm::Type *DestPTy = ConvertType(E->getType());
488 assert(isa<llvm::PointerType>(DestPTy) &&
489 "Only expect implicit cast to pointer");
490 if (V->getType() != DestPTy)
491 V = Builder.CreateBitCast(V, DestPTy, "ptrconv");
494 } else if (E->getType()->isReferenceType()) {
495 assert(cast<ReferenceType>(E->getType().getCanonicalType())->
496 getReferenceeType() ==
497 Op->getType().getCanonicalType() && "Incompatible types!");
499 return EmitLValue(Op).getAddress();
502 return EmitCastExpr(Op, E->getType());
506 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
507 // have to handle a more broad range of conversions than explicit casts, as they
508 // handle things like function to ptr-to-function decay etc.
509 Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
510 // Handle cases where the source is an non-complex type.
512 if (!CGF.hasAggregateLLVMType(E->getType())) {
513 Value *Src = Visit(const_cast<Expr*>(E));
515 // Use EmitScalarConversion to perform the conversion.
516 return EmitScalarConversion(Src, E->getType(), DestTy);
519 if (E->getType()->isComplexType()) {
520 // Handle cases where the source is a complex type.
521 return EmitComplexToScalarConversion(CGF.EmitComplexExpr(E), E->getType(),
525 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
526 // evaluate the result and return.
527 CGF.EmitAggExpr(E, 0, false);
531 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
532 return CGF.EmitCompoundStmt(*E->getSubStmt(), true).getScalarVal();
536 //===----------------------------------------------------------------------===//
538 //===----------------------------------------------------------------------===//
540 Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
541 bool isInc, bool isPre) {
542 LValue LV = EmitLValue(E->getSubExpr());
543 // FIXME: Handle volatile!
544 Value *InVal = CGF.EmitLoadOfLValue(LV, // false
545 E->getSubExpr()->getType()).getScalarVal();
547 int AmountVal = isInc ? 1 : -1;
550 if (isa<llvm::PointerType>(InVal->getType())) {
551 // FIXME: This isn't right for VLAs.
552 NextVal = llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
553 NextVal = Builder.CreateGEP(InVal, NextVal);
555 // Add the inc/dec to the real part.
556 if (isa<llvm::IntegerType>(InVal->getType()))
557 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
558 else if (InVal->getType() == llvm::Type::FloatTy)
559 // FIXME: Handle long double.
561 llvm::ConstantFP::get(InVal->getType(),
562 llvm::APFloat(static_cast<float>(AmountVal)));
564 // FIXME: Handle long double.
565 assert(InVal->getType() == llvm::Type::DoubleTy);
567 llvm::ConstantFP::get(InVal->getType(),
568 llvm::APFloat(static_cast<double>(AmountVal)));
570 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
573 // Store the updated result through the lvalue.
574 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV,
575 E->getSubExpr()->getType());
577 // If this is a postinc, return the value read from memory, otherwise use the
579 return isPre ? NextVal : InVal;
583 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
584 Value *Op = Visit(E->getSubExpr());
585 return Builder.CreateNeg(Op, "neg");
588 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
589 Value *Op = Visit(E->getSubExpr());
590 return Builder.CreateNot(Op, "neg");
593 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
594 // Compare operand to zero.
595 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
598 // TODO: Could dynamically modify easy computations here. For example, if
599 // the operand is an icmp ne, turn into icmp eq.
600 BoolVal = Builder.CreateNot(BoolVal, "lnot");
602 // ZExt result to int.
603 return Builder.CreateZExt(BoolVal, CGF.LLVMIntTy, "lnot.ext");
606 /// EmitSizeAlignOf - Return the size or alignment of the 'TypeToSize' type as
607 /// an integer (RetType).
608 Value *ScalarExprEmitter::EmitSizeAlignOf(QualType TypeToSize,
609 QualType RetType,bool isSizeOf){
610 /// FIXME: This doesn't handle VLAs yet!
611 std::pair<uint64_t, unsigned> Info =
612 CGF.getContext().getTypeInfo(TypeToSize, SourceLocation());
614 uint64_t Val = isSizeOf ? Info.first : Info.second;
615 Val /= 8; // Return size in bytes, not bits.
617 assert(RetType->isIntegerType() && "Result type must be an integer!");
619 uint32_t ResultWidth = static_cast<uint32_t>(
620 CGF.getContext().getTypeSize(RetType, SourceLocation()));
621 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
624 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
625 Expr *Op = E->getSubExpr();
626 if (Op->getType()->isComplexType())
627 return CGF.EmitComplexExpr(Op).first;
630 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
631 Expr *Op = E->getSubExpr();
632 if (Op->getType()->isComplexType())
633 return CGF.EmitComplexExpr(Op).second;
635 // __imag on a scalar returns zero. Emit it the subexpr to ensure side
636 // effects are evaluated.
637 CGF.EmitScalarExpr(Op);
638 return llvm::Constant::getNullValue(ConvertType(E->getType()));
641 Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
643 int64_t Val = E->evaluateOffsetOf(CGF.getContext());
645 assert(E->getType()->isIntegerType() && "Result type must be an integer!");
647 uint32_t ResultWidth = static_cast<uint32_t>(
648 CGF.getContext().getTypeSize(E->getType(), SourceLocation()));
649 return llvm::ConstantInt::get(llvm::APInt(ResultWidth, Val));
652 //===----------------------------------------------------------------------===//
654 //===----------------------------------------------------------------------===//
656 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
658 Result.LHS = Visit(E->getLHS());
659 Result.RHS = Visit(E->getRHS());
660 Result.Ty = E->getType();
665 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
666 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
667 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
671 // Load the LHS and RHS operands.
672 LValue LHSLV = EmitLValue(E->getLHS());
673 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
675 // Determine the computation type. If the RHS is complex, then this is one of
676 // the add/sub/mul/div operators. All of these operators can be computed in
677 // with just their real component even though the computation domain really is
679 QualType ComputeType = E->getComputationType();
681 // If the computation type is complex, then the RHS is complex. Emit the RHS.
682 if (const ComplexType *CT = ComputeType->getAsComplexType()) {
683 ComputeType = CT->getElementType();
685 // Emit the RHS, only keeping the real component.
686 OpInfo.RHS = CGF.EmitComplexExpr(E->getRHS()).first;
687 RHSTy = RHSTy->getAsComplexType()->getElementType();
689 // Otherwise the RHS is a simple scalar value.
690 OpInfo.RHS = Visit(E->getRHS());
693 // Convert the LHS/RHS values to the computation type.
694 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, ComputeType);
696 // Do not merge types for -= or += where the LHS is a pointer.
697 if (!(E->getOpcode() == BinaryOperator::SubAssign ||
698 E->getOpcode() == BinaryOperator::AddAssign) ||
699 !E->getLHS()->getType()->isPointerType()) {
700 OpInfo.RHS = EmitScalarConversion(OpInfo.RHS, RHSTy, ComputeType);
702 OpInfo.Ty = ComputeType;
705 // Expand the binary operator.
706 Value *Result = (this->*Func)(OpInfo);
708 // Truncate the result back to the LHS type.
709 Result = EmitScalarConversion(Result, ComputeType, LHSTy);
711 // Store the result value into the LHS lvalue.
712 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, E->getType());
718 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
719 if (Ops.LHS->getType()->isFPOrFPVector())
720 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
721 else if (Ops.Ty->isUnsignedIntegerType())
722 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
724 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
727 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
728 // Rem in C can't be a floating point type: C99 6.5.5p2.
729 if (Ops.Ty->isUnsignedIntegerType())
730 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
732 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
736 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
737 if (!Ops.Ty->isPointerType())
738 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
740 // FIXME: What about a pointer to a VLA?
743 if (isa<llvm::PointerType>(Ops.LHS->getType())) { // pointer + int
746 IdxExp = Ops.E->getRHS();
747 } else { // int + pointer
750 IdxExp = Ops.E->getLHS();
753 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
754 if (Width < CGF.LLVMPointerWidth) {
755 // Zero or sign extend the pointer value based on whether the index is
757 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
758 if (IdxExp->getType().getCanonicalType()->isSignedIntegerType())
759 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
761 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
764 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
767 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
768 if (!isa<llvm::PointerType>(Ops.LHS->getType()))
769 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
772 assert(!isa<llvm::PointerType>(Ops.RHS->getType()) &&
773 "ptr-ptr shouldn't get here");
774 // FIXME: The pointer could point to a VLA.
775 Value *Idx = Builder.CreateNeg(Ops.RHS, "sub.ptr.neg");
777 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
778 if (Width < CGF.LLVMPointerWidth) {
779 // Zero or sign extend the pointer value based on whether the index is
781 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
782 if (Ops.E->getRHS()->getType().getCanonicalType()->isSignedIntegerType())
783 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
785 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
788 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
791 Value *ScalarExprEmitter::VisitBinSub(const BinaryOperator *E) {
792 // "X - Y" is different from "X -= Y" in one case: when Y is a pointer. In
793 // the compound assignment case it is invalid, so just handle it here.
794 if (!E->getRHS()->getType()->isPointerType())
795 return EmitSub(EmitBinOps(E));
798 Value *LHS = Visit(E->getLHS());
799 Value *RHS = Visit(E->getRHS());
801 const QualType LHSType = E->getLHS()->getType().getCanonicalType();
802 const QualType LHSElementType = cast<PointerType>(LHSType)->getPointeeType();
803 uint64_t ElementSize = CGF.getContext().getTypeSize(LHSElementType,
804 SourceLocation()) / 8;
806 const llvm::Type *ResultType = ConvertType(E->getType());
807 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
808 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
809 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
811 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
812 // remainder. As such, we handle common power-of-two cases here to generate
814 if (llvm::isPowerOf2_64(ElementSize)) {
816 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
817 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
820 // Otherwise, do a full sdiv.
821 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
822 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
826 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
827 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
828 // RHS to the same size as the LHS.
829 Value *RHS = Ops.RHS;
830 if (Ops.LHS->getType() != RHS->getType())
831 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
833 return Builder.CreateShl(Ops.LHS, RHS, "shl");
836 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
837 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
838 // RHS to the same size as the LHS.
839 Value *RHS = Ops.RHS;
840 if (Ops.LHS->getType() != RHS->getType())
841 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
843 if (Ops.Ty->isUnsignedIntegerType())
844 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
845 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
848 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
849 unsigned SICmpOpc, unsigned FCmpOpc) {
851 QualType LHSTy = E->getLHS()->getType();
852 if (!LHSTy->isComplexType()) {
853 Value *LHS = Visit(E->getLHS());
854 Value *RHS = Visit(E->getRHS());
856 if (LHS->getType()->isFloatingPoint()) {
857 Result = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
859 } else if (LHSTy->isUnsignedIntegerType()) {
860 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
863 // Signed integers and pointers.
864 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
868 // Complex Comparison: can only be an equality comparison.
869 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
870 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
873 cast<ComplexType>(LHSTy.getCanonicalType())->getElementType();
875 Value *ResultR, *ResultI;
876 if (CETy->isRealFloatingType()) {
877 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
878 LHS.first, RHS.first, "cmp.r");
879 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
880 LHS.second, RHS.second, "cmp.i");
882 // Complex comparisons can only be equality comparisons. As such, signed
883 // and unsigned opcodes are the same.
884 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
885 LHS.first, RHS.first, "cmp.r");
886 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
887 LHS.second, RHS.second, "cmp.i");
890 if (E->getOpcode() == BinaryOperator::EQ) {
891 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
893 assert(E->getOpcode() == BinaryOperator::NE &&
894 "Complex comparison other than == or != ?");
895 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
899 // ZExt result to int.
900 return Builder.CreateZExt(Result, CGF.LLVMIntTy, "cmp.ext");
903 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
904 LValue LHS = EmitLValue(E->getLHS());
905 Value *RHS = Visit(E->getRHS());
907 // Store the value into the LHS.
908 // FIXME: Volatility!
909 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
915 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
916 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
918 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("land_cont");
919 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("land_rhs");
921 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
922 Builder.CreateCondBr(LHSCond, RHSBlock, ContBlock);
924 CGF.EmitBlock(RHSBlock);
925 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
927 // Reaquire the RHS block, as there may be subblocks inserted.
928 RHSBlock = Builder.GetInsertBlock();
929 CGF.EmitBlock(ContBlock);
931 // Create a PHI node. If we just evaluted the LHS condition, the result is
932 // false. If we evaluated both, the result is the RHS condition.
933 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "land");
934 PN->reserveOperandSpace(2);
935 PN->addIncoming(llvm::ConstantInt::getFalse(), OrigBlock);
936 PN->addIncoming(RHSCond, RHSBlock);
938 // ZExt result to int.
939 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
942 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
943 Value *LHSCond = CGF.EvaluateExprAsBool(E->getLHS());
945 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("lor_cont");
946 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("lor_rhs");
948 llvm::BasicBlock *OrigBlock = Builder.GetInsertBlock();
949 Builder.CreateCondBr(LHSCond, ContBlock, RHSBlock);
951 CGF.EmitBlock(RHSBlock);
952 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
954 // Reaquire the RHS block, as there may be subblocks inserted.
955 RHSBlock = Builder.GetInsertBlock();
956 CGF.EmitBlock(ContBlock);
958 // Create a PHI node. If we just evaluted the LHS condition, the result is
959 // true. If we evaluated both, the result is the RHS condition.
960 llvm::PHINode *PN = Builder.CreatePHI(llvm::Type::Int1Ty, "lor");
961 PN->reserveOperandSpace(2);
962 PN->addIncoming(llvm::ConstantInt::getTrue(), OrigBlock);
963 PN->addIncoming(RHSCond, RHSBlock);
965 // ZExt result to int.
966 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
969 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
970 CGF.EmitStmt(E->getLHS());
971 return Visit(E->getRHS());
974 //===----------------------------------------------------------------------===//
976 //===----------------------------------------------------------------------===//
978 Value *ScalarExprEmitter::
979 VisitConditionalOperator(const ConditionalOperator *E) {
980 llvm::BasicBlock *LHSBlock = new llvm::BasicBlock("cond.?");
981 llvm::BasicBlock *RHSBlock = new llvm::BasicBlock("cond.:");
982 llvm::BasicBlock *ContBlock = new llvm::BasicBlock("cond.cont");
984 // Evaluate the conditional, then convert it to bool. We do this explicitly
985 // because we need the unconverted value if this is a GNU ?: expression with
986 // missing middle value.
987 Value *CondVal = CGF.EmitScalarExpr(E->getCond());
988 Value *CondBoolVal =CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
989 CGF.getContext().BoolTy);
990 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
992 CGF.EmitBlock(LHSBlock);
994 // Handle the GNU extension for missing LHS.
997 LHS = Visit(E->getLHS());
998 else // Perform promotions, to handle cases like "short ?: int"
999 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1001 Builder.CreateBr(ContBlock);
1002 LHSBlock = Builder.GetInsertBlock();
1004 CGF.EmitBlock(RHSBlock);
1006 Value *RHS = Visit(E->getRHS());
1007 Builder.CreateBr(ContBlock);
1008 RHSBlock = Builder.GetInsertBlock();
1010 CGF.EmitBlock(ContBlock);
1013 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1017 // Create a PHI node for the real part.
1018 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1019 PN->reserveOperandSpace(2);
1020 PN->addIncoming(LHS, LHSBlock);
1021 PN->addIncoming(RHS, RHSBlock);
1025 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
1026 // Emit the LHS or RHS as appropriate.
1028 Visit(E->isConditionTrue(CGF.getContext()) ? E->getLHS() : E->getRHS());
1031 Value *ScalarExprEmitter::VisitOverloadExpr(OverloadExpr *E) {
1032 return CGF.EmitCallExpr(E->getFn(), E->arg_begin(),
1033 E->getNumArgs(CGF.getContext())).getScalarVal();
1036 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
1037 llvm::Value *ArgValue = EmitLValue(VE->getSubExpr()).getAddress();
1039 llvm::Value *V = Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1043 Value *ScalarExprEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
1045 llvm::SmallVector<const RecordType *, 8> EncodingRecordTypes;
1046 CGF.getContext().getObjCEncodingForType(E->getEncodedType(), str,
1047 EncodingRecordTypes);
1049 llvm::Constant *C = llvm::ConstantArray::get(str);
1050 C = new llvm::GlobalVariable(C->getType(), true,
1051 llvm::GlobalValue::InternalLinkage,
1052 C, ".str", &CGF.CGM.getModule());
1053 llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty);
1054 llvm::Constant *Zeros[] = { Zero, Zero };
1055 C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2);
1060 //===----------------------------------------------------------------------===//
1061 // Entry Point into this File
1062 //===----------------------------------------------------------------------===//
1064 /// EmitComplexExpr - Emit the computation of the specified expression of
1065 /// complex type, ignoring the result.
1066 Value *CodeGenFunction::EmitScalarExpr(const Expr *E) {
1067 assert(E && !hasAggregateLLVMType(E->getType()) &&
1068 "Invalid scalar expression to emit");
1070 return ScalarExprEmitter(*this).Visit(const_cast<Expr*>(E));
1073 /// EmitScalarConversion - Emit a conversion from the specified type to the
1074 /// specified destination type, both of which are LLVM scalar types.
1075 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1077 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1078 "Invalid scalar expression to emit");
1079 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1082 /// EmitComplexToScalarConversion - Emit a conversion from the specified
1083 /// complex type to the specified destination type, where the destination
1084 /// type is an LLVM scalar type.
1085 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1088 assert(SrcTy->isComplexType() && !hasAggregateLLVMType(DstTy) &&
1089 "Invalid complex -> scalar conversion");
1090 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1094 Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1095 assert(V1->getType() == V2->getType() &&
1096 "Vector operands must be of the same type");
1098 unsigned NumElements =
1099 cast<llvm::VectorType>(V1->getType())->getNumElements();
1104 llvm::SmallVector<llvm::Constant*, 16> Args;
1106 for (unsigned i = 0; i < NumElements; i++) {
1107 int n = va_arg(va, int);
1109 assert(n >= 0 && n < (int)NumElements * 2 &&
1110 "Vector shuffle index out of bounds!");
1112 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
1115 const char *Name = va_arg(va, const char *);
1118 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1120 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1123 llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
1124 unsigned NumVals, bool isSplat)
1127 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
1129 for (unsigned i = 0, e = NumVals ; i != e; ++i) {
1130 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
1131 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
1132 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");