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 "clang/Frontend/CodeGenOptions.h"
15 #include "CodeGenFunction.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenModule.h"
19 #include "CGDebugInfo.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/GlobalVariable.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Module.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Target/TargetData.h"
34 using namespace clang;
35 using namespace CodeGen;
38 //===----------------------------------------------------------------------===//
39 // Scalar Expression Emitter
40 //===----------------------------------------------------------------------===//
46 QualType Ty; // Computation Type.
47 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
48 const Expr *E; // Entire expr, for error unsupported. May not be binop.
51 static bool MustVisitNullValue(const Expr *E) {
52 // If a null pointer expression's type is the C++0x nullptr_t, then
53 // it's not necessarily a simple constant and it must be evaluated
54 // for its potential side effects.
55 return E->getType()->isNullPtrType();
58 class ScalarExprEmitter
59 : public StmtVisitor<ScalarExprEmitter, Value*> {
62 bool IgnoreResultAssign;
63 llvm::LLVMContext &VMContext;
66 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
67 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
68 VMContext(cgf.getLLVMContext()) {
71 //===--------------------------------------------------------------------===//
73 //===--------------------------------------------------------------------===//
75 bool TestAndClearIgnoreResultAssign() {
76 bool I = IgnoreResultAssign;
77 IgnoreResultAssign = false;
81 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
82 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
83 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
85 Value *EmitLoadOfLValue(LValue LV, QualType T) {
86 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
89 /// EmitLoadOfLValue - Given an expression with complex type that represents a
90 /// value l-value, this method emits the address of the l-value, then loads
91 /// and returns the result.
92 Value *EmitLoadOfLValue(const Expr *E) {
93 return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType());
96 /// EmitConversionToBool - Convert the specified expression value to a
97 /// boolean (i1) truth value. This is equivalent to "Val != 0".
98 Value *EmitConversionToBool(Value *Src, QualType DstTy);
100 /// EmitScalarConversion - Emit a conversion from the specified type to the
101 /// specified destination type, both of which are LLVM scalar types.
102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
104 /// EmitComplexToScalarConversion - Emit a conversion from the specified
105 /// complex type to the specified destination type, where the destination type
106 /// is an LLVM scalar type.
107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
108 QualType SrcTy, QualType DstTy);
110 /// EmitNullValue - Emit a value that corresponds to null for the given type.
111 Value *EmitNullValue(QualType Ty);
113 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
114 Value *EmitFloatToBoolConversion(Value *V) {
115 // Compare against 0.0 for fp scalars.
116 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
117 return Builder.CreateFCmpUNE(V, Zero, "tobool");
120 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
121 Value *EmitPointerToBoolConversion(Value *V) {
122 Value *Zero = llvm::ConstantPointerNull::get(
123 cast<llvm::PointerType>(V->getType()));
124 return Builder.CreateICmpNE(V, Zero, "tobool");
127 Value *EmitIntToBoolConversion(Value *V) {
128 // Because of the type rules of C, we often end up computing a
129 // logical value, then zero extending it to int, then wanting it
130 // as a logical value again. Optimize this common case.
131 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
132 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
133 Value *Result = ZI->getOperand(0);
134 // If there aren't any more uses, zap the instruction to save space.
135 // Note that there can be more uses, for example if this
136 // is the result of an assignment.
138 ZI->eraseFromParent();
143 return Builder.CreateIsNotNull(V, "tobool");
146 //===--------------------------------------------------------------------===//
148 //===--------------------------------------------------------------------===//
150 Value *Visit(Expr *E) {
151 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
154 Value *VisitStmt(Stmt *S) {
155 S->dump(CGF.getContext().getSourceManager());
156 assert(0 && "Stmt can't have complex result type!");
159 Value *VisitExpr(Expr *S);
161 Value *VisitParenExpr(ParenExpr *PE) {
162 return Visit(PE->getSubExpr());
164 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
165 return Visit(GE->getResultExpr());
169 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
170 return Builder.getInt(E->getValue());
172 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
173 return llvm::ConstantFP::get(VMContext, E->getValue());
175 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
176 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
178 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
179 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
181 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
182 return EmitNullValue(E->getType());
184 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
185 return EmitNullValue(E->getType());
187 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
188 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
189 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
190 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
191 return Builder.CreateBitCast(V, ConvertType(E->getType()));
194 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
195 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
198 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
200 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getType());
202 // Otherwise, assume the mapping is the scalar directly.
203 return CGF.getOpaqueRValueMapping(E).getScalarVal();
207 Value *VisitDeclRefExpr(DeclRefExpr *E) {
208 Expr::EvalResult Result;
209 if (!E->Evaluate(Result, CGF.getContext()))
210 return EmitLoadOfLValue(E);
212 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
215 if (Result.Val.isInt())
216 C = Builder.getInt(Result.Val.getInt());
217 else if (Result.Val.isFloat())
218 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
220 return EmitLoadOfLValue(E);
222 // Make sure we emit a debug reference to the global variable.
223 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
224 if (!CGF.getContext().DeclMustBeEmitted(VD))
225 CGF.EmitDeclRefExprDbgValue(E, C);
226 } else if (isa<EnumConstantDecl>(E->getDecl())) {
227 CGF.EmitDeclRefExprDbgValue(E, C);
232 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
233 return CGF.EmitObjCSelectorExpr(E);
235 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
236 return CGF.EmitObjCProtocolExpr(E);
238 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
239 return EmitLoadOfLValue(E);
241 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
242 assert(E->getObjectKind() == OK_Ordinary &&
243 "reached property reference without lvalue-to-rvalue");
244 return EmitLoadOfLValue(E);
246 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
247 if (E->getMethodDecl() &&
248 E->getMethodDecl()->getResultType()->isReferenceType())
249 return EmitLoadOfLValue(E);
250 return CGF.EmitObjCMessageExpr(E).getScalarVal();
253 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
254 LValue LV = CGF.EmitObjCIsaExpr(E);
255 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
259 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
260 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
261 Value *VisitMemberExpr(MemberExpr *E);
262 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
263 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
264 return EmitLoadOfLValue(E);
267 Value *VisitInitListExpr(InitListExpr *E);
269 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
270 return CGF.CGM.EmitNullConstant(E->getType());
272 Value *VisitCastExpr(CastExpr *E) {
273 // Make sure to evaluate VLA bounds now so that we have them for later.
274 if (E->getType()->isVariablyModifiedType())
275 CGF.EmitVLASize(E->getType());
277 return EmitCastExpr(E);
279 Value *EmitCastExpr(CastExpr *E);
281 Value *VisitCallExpr(const CallExpr *E) {
282 if (E->getCallReturnType()->isReferenceType())
283 return EmitLoadOfLValue(E);
285 return CGF.EmitCallExpr(E).getScalarVal();
288 Value *VisitStmtExpr(const StmtExpr *E);
290 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
293 Value *VisitUnaryPostDec(const UnaryOperator *E) {
294 LValue LV = EmitLValue(E->getSubExpr());
295 return EmitScalarPrePostIncDec(E, LV, false, false);
297 Value *VisitUnaryPostInc(const UnaryOperator *E) {
298 LValue LV = EmitLValue(E->getSubExpr());
299 return EmitScalarPrePostIncDec(E, LV, true, false);
301 Value *VisitUnaryPreDec(const UnaryOperator *E) {
302 LValue LV = EmitLValue(E->getSubExpr());
303 return EmitScalarPrePostIncDec(E, LV, false, true);
305 Value *VisitUnaryPreInc(const UnaryOperator *E) {
306 LValue LV = EmitLValue(E->getSubExpr());
307 return EmitScalarPrePostIncDec(E, LV, true, true);
310 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
312 llvm::Value *NextVal,
315 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
316 bool isInc, bool isPre);
319 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
320 if (isa<MemberPointerType>(E->getType())) // never sugared
321 return CGF.CGM.getMemberPointerConstant(E);
323 return EmitLValue(E->getSubExpr()).getAddress();
325 Value *VisitUnaryDeref(const UnaryOperator *E) {
326 if (E->getType()->isVoidType())
327 return Visit(E->getSubExpr()); // the actual value should be unused
328 return EmitLoadOfLValue(E);
330 Value *VisitUnaryPlus(const UnaryOperator *E) {
331 // This differs from gcc, though, most likely due to a bug in gcc.
332 TestAndClearIgnoreResultAssign();
333 return Visit(E->getSubExpr());
335 Value *VisitUnaryMinus (const UnaryOperator *E);
336 Value *VisitUnaryNot (const UnaryOperator *E);
337 Value *VisitUnaryLNot (const UnaryOperator *E);
338 Value *VisitUnaryReal (const UnaryOperator *E);
339 Value *VisitUnaryImag (const UnaryOperator *E);
340 Value *VisitUnaryExtension(const UnaryOperator *E) {
341 return Visit(E->getSubExpr());
345 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
346 return Visit(DAE->getExpr());
348 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
349 return CGF.LoadCXXThis();
352 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
353 return CGF.EmitExprWithCleanups(E).getScalarVal();
355 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
356 return CGF.EmitCXXNewExpr(E);
358 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
359 CGF.EmitCXXDeleteExpr(E);
362 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
363 return Builder.getInt1(E->getValue());
366 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
367 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
370 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
371 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
374 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
375 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
378 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
379 // C++ [expr.pseudo]p1:
380 // The result shall only be used as the operand for the function call
381 // operator (), and the result of such a call has type void. The only
382 // effect is the evaluation of the postfix-expression before the dot or
384 CGF.EmitScalarExpr(E->getBase());
388 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
389 return EmitNullValue(E->getType());
392 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
393 CGF.EmitCXXThrowExpr(E);
397 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
398 return Builder.getInt1(E->getValue());
402 Value *EmitMul(const BinOpInfo &Ops) {
403 if (Ops.Ty->hasSignedIntegerRepresentation()) {
404 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
405 case LangOptions::SOB_Undefined:
406 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
407 case LangOptions::SOB_Defined:
408 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
409 case LangOptions::SOB_Trapping:
410 return EmitOverflowCheckedBinOp(Ops);
414 if (Ops.LHS->getType()->isFPOrFPVectorTy())
415 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
416 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
418 bool isTrapvOverflowBehavior() {
419 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
420 == LangOptions::SOB_Trapping;
422 /// Create a binary op that checks for overflow.
423 /// Currently only supports +, - and *.
424 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
425 // Emit the overflow BB when -ftrapv option is activated.
426 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
427 Builder.SetInsertPoint(overflowBB);
428 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
429 Builder.CreateCall(Trap);
430 Builder.CreateUnreachable();
432 // Check for undefined division and modulus behaviors.
433 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
434 llvm::Value *Zero,bool isDiv);
435 Value *EmitDiv(const BinOpInfo &Ops);
436 Value *EmitRem(const BinOpInfo &Ops);
437 Value *EmitAdd(const BinOpInfo &Ops);
438 Value *EmitSub(const BinOpInfo &Ops);
439 Value *EmitShl(const BinOpInfo &Ops);
440 Value *EmitShr(const BinOpInfo &Ops);
441 Value *EmitAnd(const BinOpInfo &Ops) {
442 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
444 Value *EmitXor(const BinOpInfo &Ops) {
445 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
447 Value *EmitOr (const BinOpInfo &Ops) {
448 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
451 BinOpInfo EmitBinOps(const BinaryOperator *E);
452 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
453 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
456 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
457 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
459 // Binary operators and binary compound assignment operators.
460 #define HANDLEBINOP(OP) \
461 Value *VisitBin ## OP(const BinaryOperator *E) { \
462 return Emit ## OP(EmitBinOps(E)); \
464 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
465 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
480 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
481 unsigned SICmpOpc, unsigned FCmpOpc);
482 #define VISITCOMP(CODE, UI, SI, FP) \
483 Value *VisitBin##CODE(const BinaryOperator *E) { \
484 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
485 llvm::FCmpInst::FP); }
486 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
487 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
488 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
489 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
490 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
491 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
494 Value *VisitBinAssign (const BinaryOperator *E);
496 Value *VisitBinLAnd (const BinaryOperator *E);
497 Value *VisitBinLOr (const BinaryOperator *E);
498 Value *VisitBinComma (const BinaryOperator *E);
500 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
501 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
504 Value *VisitBlockExpr(const BlockExpr *BE);
505 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
506 Value *VisitChooseExpr(ChooseExpr *CE);
507 Value *VisitVAArgExpr(VAArgExpr *VE);
508 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
509 return CGF.EmitObjCStringLiteral(E);
512 } // end anonymous namespace.
514 //===----------------------------------------------------------------------===//
516 //===----------------------------------------------------------------------===//
518 /// EmitConversionToBool - Convert the specified expression value to a
519 /// boolean (i1) truth value. This is equivalent to "Val != 0".
520 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
521 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
523 if (SrcType->isRealFloatingType())
524 return EmitFloatToBoolConversion(Src);
526 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
527 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
529 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
530 "Unknown scalar type to convert");
532 if (isa<llvm::IntegerType>(Src->getType()))
533 return EmitIntToBoolConversion(Src);
535 assert(isa<llvm::PointerType>(Src->getType()));
536 return EmitPointerToBoolConversion(Src);
539 /// EmitScalarConversion - Emit a conversion from the specified type to the
540 /// specified destination type, both of which are LLVM scalar types.
541 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
543 SrcType = CGF.getContext().getCanonicalType(SrcType);
544 DstType = CGF.getContext().getCanonicalType(DstType);
545 if (SrcType == DstType) return Src;
547 if (DstType->isVoidType()) return 0;
549 // Handle conversions to bool first, they are special: comparisons against 0.
550 if (DstType->isBooleanType())
551 return EmitConversionToBool(Src, SrcType);
553 const llvm::Type *DstTy = ConvertType(DstType);
555 // Ignore conversions like int -> uint.
556 if (Src->getType() == DstTy)
559 // Handle pointer conversions next: pointers can only be converted to/from
560 // other pointers and integers. Check for pointer types in terms of LLVM, as
561 // some native types (like Obj-C id) may map to a pointer type.
562 if (isa<llvm::PointerType>(DstTy)) {
563 // The source value may be an integer, or a pointer.
564 if (isa<llvm::PointerType>(Src->getType()))
565 return Builder.CreateBitCast(Src, DstTy, "conv");
567 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
568 // First, convert to the correct width so that we control the kind of
570 const llvm::Type *MiddleTy = CGF.IntPtrTy;
571 bool InputSigned = SrcType->isSignedIntegerType();
572 llvm::Value* IntResult =
573 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
574 // Then, cast to pointer.
575 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
578 if (isa<llvm::PointerType>(Src->getType())) {
579 // Must be an ptr to int cast.
580 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
581 return Builder.CreatePtrToInt(Src, DstTy, "conv");
584 // A scalar can be splatted to an extended vector of the same element type
585 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
586 // Cast the scalar to element type
587 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
588 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
590 // Insert the element in element zero of an undef vector
591 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
592 llvm::Value *Idx = Builder.getInt32(0);
593 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
595 // Splat the element across to all elements
596 llvm::SmallVector<llvm::Constant*, 16> Args;
597 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
598 for (unsigned i = 0; i != NumElements; ++i)
599 Args.push_back(Builder.getInt32(0));
601 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
602 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
606 // Allow bitcast from vector to integer/fp of the same size.
607 if (isa<llvm::VectorType>(Src->getType()) ||
608 isa<llvm::VectorType>(DstTy))
609 return Builder.CreateBitCast(Src, DstTy, "conv");
611 // Finally, we have the arithmetic types: real int/float.
612 if (isa<llvm::IntegerType>(Src->getType())) {
613 bool InputSigned = SrcType->isSignedIntegerType();
614 if (isa<llvm::IntegerType>(DstTy))
615 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
616 else if (InputSigned)
617 return Builder.CreateSIToFP(Src, DstTy, "conv");
619 return Builder.CreateUIToFP(Src, DstTy, "conv");
622 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
623 if (isa<llvm::IntegerType>(DstTy)) {
624 if (DstType->isSignedIntegerType())
625 return Builder.CreateFPToSI(Src, DstTy, "conv");
627 return Builder.CreateFPToUI(Src, DstTy, "conv");
630 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
631 if (DstTy->getTypeID() < Src->getType()->getTypeID())
632 return Builder.CreateFPTrunc(Src, DstTy, "conv");
634 return Builder.CreateFPExt(Src, DstTy, "conv");
637 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
638 /// type to the specified destination type, where the destination type is an
639 /// LLVM scalar type.
640 Value *ScalarExprEmitter::
641 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
642 QualType SrcTy, QualType DstTy) {
643 // Get the source element type.
644 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
646 // Handle conversions to bool first, they are special: comparisons against 0.
647 if (DstTy->isBooleanType()) {
648 // Complex != 0 -> (Real != 0) | (Imag != 0)
649 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
650 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
651 return Builder.CreateOr(Src.first, Src.second, "tobool");
654 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
655 // the imaginary part of the complex value is discarded and the value of the
656 // real part is converted according to the conversion rules for the
657 // corresponding real type.
658 return EmitScalarConversion(Src.first, SrcTy, DstTy);
661 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
662 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
663 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
665 return llvm::Constant::getNullValue(ConvertType(Ty));
668 //===----------------------------------------------------------------------===//
670 //===----------------------------------------------------------------------===//
672 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
673 CGF.ErrorUnsupported(E, "scalar expression");
674 if (E->getType()->isVoidType())
676 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
679 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
681 if (E->getNumSubExprs() == 2 ||
682 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
683 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
684 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
687 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
688 unsigned LHSElts = LTy->getNumElements();
690 if (E->getNumSubExprs() == 3) {
691 Mask = CGF.EmitScalarExpr(E->getExpr(2));
693 // Shuffle LHS & RHS into one input vector.
694 llvm::SmallVector<llvm::Constant*, 32> concat;
695 for (unsigned i = 0; i != LHSElts; ++i) {
696 concat.push_back(Builder.getInt32(2*i));
697 concat.push_back(Builder.getInt32(2*i+1));
700 Value* CV = llvm::ConstantVector::get(concat);
701 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
707 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
708 llvm::Constant* EltMask;
710 // Treat vec3 like vec4.
711 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
712 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
713 (1 << llvm::Log2_32(LHSElts+2))-1);
714 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
715 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
716 (1 << llvm::Log2_32(LHSElts+1))-1);
718 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
719 (1 << llvm::Log2_32(LHSElts))-1);
721 // Mask off the high bits of each shuffle index.
722 llvm::SmallVector<llvm::Constant *, 32> MaskV;
723 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
724 MaskV.push_back(EltMask);
726 Value* MaskBits = llvm::ConstantVector::get(MaskV);
727 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
730 // mask = mask & maskbits
732 // n = extract mask i
734 // newv = insert newv, x, i
735 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
736 MTy->getNumElements());
737 Value* NewV = llvm::UndefValue::get(RTy);
738 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
739 Value *Indx = Builder.getInt32(i);
740 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
741 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
743 // Handle vec3 special since the index will be off by one for the RHS.
744 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
745 Value *cmpIndx, *newIndx;
746 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
748 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
749 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
751 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
752 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
757 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
758 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
760 // Handle vec3 special since the index will be off by one for the RHS.
761 llvm::SmallVector<llvm::Constant*, 32> indices;
762 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
763 llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
764 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
765 if (VTy->getNumElements() == 3) {
766 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
767 uint64_t cVal = CI->getZExtValue();
769 C = llvm::ConstantInt::get(C->getType(), cVal-1);
773 indices.push_back(C);
776 Value *SV = llvm::ConstantVector::get(indices);
777 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
779 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
780 Expr::EvalResult Result;
781 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
783 CGF.EmitScalarExpr(E->getBase());
785 EmitLValue(E->getBase());
786 return Builder.getInt(Result.Val.getInt());
789 // Emit debug info for aggregate now, if it was delayed to reduce
791 CGDebugInfo *DI = CGF.getDebugInfo();
792 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
793 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
794 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
795 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
796 DI->getOrCreateRecordType(PTy->getPointeeType(),
797 M->getParent()->getLocation());
799 return EmitLoadOfLValue(E);
802 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
803 TestAndClearIgnoreResultAssign();
805 // Emit subscript expressions in rvalue context's. For most cases, this just
806 // loads the lvalue formed by the subscript expr. However, we have to be
807 // careful, because the base of a vector subscript is occasionally an rvalue,
808 // so we can't get it as an lvalue.
809 if (!E->getBase()->getType()->isVectorType())
810 return EmitLoadOfLValue(E);
812 // Handle the vector case. The base must be a vector, the index must be an
814 Value *Base = Visit(E->getBase());
815 Value *Idx = Visit(E->getIdx());
816 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
817 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
818 return Builder.CreateExtractElement(Base, Idx, "vecext");
821 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
822 unsigned Off, const llvm::Type *I32Ty) {
823 int MV = SVI->getMaskValue(Idx);
825 return llvm::UndefValue::get(I32Ty);
826 return llvm::ConstantInt::get(I32Ty, Off+MV);
829 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
830 bool Ignore = TestAndClearIgnoreResultAssign();
832 assert (Ignore == false && "init list ignored");
833 unsigned NumInitElements = E->getNumInits();
835 if (E->hadArrayRangeDesignator())
836 CGF.ErrorUnsupported(E, "GNU array range designator extension");
838 const llvm::VectorType *VType =
839 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
841 // We have a scalar in braces. Just use the first element.
843 return Visit(E->getInit(0));
845 unsigned ResElts = VType->getNumElements();
847 // Loop over initializers collecting the Value for each, and remembering
848 // whether the source was swizzle (ExtVectorElementExpr). This will allow
849 // us to fold the shuffle for the swizzle into the shuffle for the vector
850 // initializer, since LLVM optimizers generally do not want to touch
853 bool VIsUndefShuffle = false;
854 llvm::Value *V = llvm::UndefValue::get(VType);
855 for (unsigned i = 0; i != NumInitElements; ++i) {
856 Expr *IE = E->getInit(i);
857 Value *Init = Visit(IE);
858 llvm::SmallVector<llvm::Constant*, 16> Args;
860 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
862 // Handle scalar elements. If the scalar initializer is actually one
863 // element of a different vector of the same width, use shuffle instead of
866 if (isa<ExtVectorElementExpr>(IE)) {
867 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
869 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
870 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
871 Value *LHS = 0, *RHS = 0;
873 // insert into undef -> shuffle (src, undef)
875 for (unsigned j = 1; j != ResElts; ++j)
876 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
878 LHS = EI->getVectorOperand();
880 VIsUndefShuffle = true;
881 } else if (VIsUndefShuffle) {
882 // insert into undefshuffle && size match -> shuffle (v, src)
883 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
884 for (unsigned j = 0; j != CurIdx; ++j)
885 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
886 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
887 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
888 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
890 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
891 RHS = EI->getVectorOperand();
892 VIsUndefShuffle = false;
895 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
896 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
902 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
904 VIsUndefShuffle = false;
909 unsigned InitElts = VVT->getNumElements();
911 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
912 // input is the same width as the vector being constructed, generate an
913 // optimized shuffle of the swizzle input into the result.
914 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
915 if (isa<ExtVectorElementExpr>(IE)) {
916 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
917 Value *SVOp = SVI->getOperand(0);
918 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
920 if (OpTy->getNumElements() == ResElts) {
921 for (unsigned j = 0; j != CurIdx; ++j) {
922 // If the current vector initializer is a shuffle with undef, merge
923 // this shuffle directly into it.
924 if (VIsUndefShuffle) {
925 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
928 Args.push_back(Builder.getInt32(j));
931 for (unsigned j = 0, je = InitElts; j != je; ++j)
932 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
933 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
934 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
937 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
943 // Extend init to result vector length, and then shuffle its contribution
944 // to the vector initializer into V.
946 for (unsigned j = 0; j != InitElts; ++j)
947 Args.push_back(Builder.getInt32(j));
948 for (unsigned j = InitElts; j != ResElts; ++j)
949 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
950 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
951 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
955 for (unsigned j = 0; j != CurIdx; ++j)
956 Args.push_back(Builder.getInt32(j));
957 for (unsigned j = 0; j != InitElts; ++j)
958 Args.push_back(Builder.getInt32(j+Offset));
959 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
960 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
963 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
964 // merging subsequent shuffles into this one.
967 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
968 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
969 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
973 // FIXME: evaluate codegen vs. shuffling against constant null vector.
974 // Emit remaining default initializers.
975 const llvm::Type *EltTy = VType->getElementType();
977 // Emit remaining default initializers
978 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
979 Value *Idx = Builder.getInt32(CurIdx);
980 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
981 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
986 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
987 const Expr *E = CE->getSubExpr();
989 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
992 if (isa<CXXThisExpr>(E)) {
993 // We always assume that 'this' is never null.
997 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
998 // And that glvalue casts are never null.
999 if (ICE->getValueKind() != VK_RValue)
1006 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1007 // have to handle a more broad range of conversions than explicit casts, as they
1008 // handle things like function to ptr-to-function decay etc.
1009 Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
1010 Expr *E = CE->getSubExpr();
1011 QualType DestTy = CE->getType();
1012 CastKind Kind = CE->getCastKind();
1014 if (!DestTy->isVoidType())
1015 TestAndClearIgnoreResultAssign();
1017 // Since almost all cast kinds apply to scalars, this switch doesn't have
1018 // a default case, so the compiler will warn on a missing case. The cases
1019 // are in the same order as in the CastKind enum.
1021 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1023 case CK_LValueBitCast:
1024 case CK_ObjCObjectLValueCast: {
1025 Value *V = EmitLValue(E).getAddress();
1026 V = Builder.CreateBitCast(V,
1027 ConvertType(CGF.getContext().getPointerType(DestTy)));
1028 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy);
1031 case CK_AnyPointerToObjCPointerCast:
1032 case CK_AnyPointerToBlockPointerCast:
1034 Value *Src = Visit(const_cast<Expr*>(E));
1035 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1038 case CK_UserDefinedConversion:
1039 return Visit(const_cast<Expr*>(E));
1041 case CK_BaseToDerived: {
1042 const CXXRecordDecl *DerivedClassDecl =
1043 DestTy->getCXXRecordDeclForPointerType();
1045 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
1046 CE->path_begin(), CE->path_end(),
1047 ShouldNullCheckClassCastValue(CE));
1049 case CK_UncheckedDerivedToBase:
1050 case CK_DerivedToBase: {
1051 const RecordType *DerivedClassTy =
1052 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1053 CXXRecordDecl *DerivedClassDecl =
1054 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1056 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
1057 CE->path_begin(), CE->path_end(),
1058 ShouldNullCheckClassCastValue(CE));
1061 Value *V = Visit(const_cast<Expr*>(E));
1062 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1063 return CGF.EmitDynamicCast(V, DCE);
1066 case CK_ArrayToPointerDecay: {
1067 assert(E->getType()->isArrayType() &&
1068 "Array to pointer decay must have array source type!");
1070 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1072 // Note that VLA pointers are always decayed, so we don't need to do
1074 if (!E->getType()->isVariableArrayType()) {
1075 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1076 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1077 ->getElementType()) &&
1078 "Expected pointer to array");
1079 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1084 case CK_FunctionToPointerDecay:
1085 return EmitLValue(E).getAddress();
1087 case CK_NullToPointer:
1088 if (MustVisitNullValue(E))
1091 return llvm::ConstantPointerNull::get(
1092 cast<llvm::PointerType>(ConvertType(DestTy)));
1094 case CK_NullToMemberPointer: {
1095 if (MustVisitNullValue(E))
1098 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1099 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1102 case CK_BaseToDerivedMemberPointer:
1103 case CK_DerivedToBaseMemberPointer: {
1104 Value *Src = Visit(E);
1106 // Note that the AST doesn't distinguish between checked and
1107 // unchecked member pointer conversions, so we always have to
1108 // implement checked conversions here. This is inefficient when
1109 // actual control flow may be required in order to perform the
1110 // check, which it is for data member pointers (but not member
1111 // function pointers on Itanium and ARM).
1112 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1115 case CK_FloatingRealToComplex:
1116 case CK_FloatingComplexCast:
1117 case CK_IntegralRealToComplex:
1118 case CK_IntegralComplexCast:
1119 case CK_IntegralComplexToFloatingComplex:
1120 case CK_FloatingComplexToIntegralComplex:
1121 case CK_ConstructorConversion:
1123 llvm_unreachable("scalar cast to non-scalar value");
1126 case CK_GetObjCProperty: {
1127 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1128 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty &&
1129 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
1130 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType());
1131 return RV.getScalarVal();
1134 case CK_LValueToRValue:
1135 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1136 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1137 return Visit(const_cast<Expr*>(E));
1139 case CK_IntegralToPointer: {
1140 Value *Src = Visit(const_cast<Expr*>(E));
1142 // First, convert to the correct width so that we control the kind of
1144 const llvm::Type *MiddleTy = CGF.IntPtrTy;
1145 bool InputSigned = E->getType()->isSignedIntegerType();
1146 llvm::Value* IntResult =
1147 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1149 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1151 case CK_PointerToIntegral: {
1152 Value *Src = Visit(const_cast<Expr*>(E));
1154 // Handle conversion to bool correctly.
1155 if (DestTy->isBooleanType())
1156 return EmitScalarConversion(Src, E->getType(), DestTy);
1158 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1161 CGF.EmitIgnoredExpr(E);
1164 case CK_VectorSplat: {
1165 const llvm::Type *DstTy = ConvertType(DestTy);
1166 Value *Elt = Visit(const_cast<Expr*>(E));
1168 // Insert the element in element zero of an undef vector
1169 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
1170 llvm::Value *Idx = Builder.getInt32(0);
1171 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1173 // Splat the element across to all elements
1174 llvm::SmallVector<llvm::Constant*, 16> Args;
1175 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1176 llvm::Constant *Zero = Builder.getInt32(0);
1177 for (unsigned i = 0; i < NumElements; i++)
1178 Args.push_back(Zero);
1180 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1181 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1185 case CK_IntegralCast:
1186 case CK_IntegralToFloating:
1187 case CK_FloatingToIntegral:
1188 case CK_FloatingCast:
1189 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1191 case CK_IntegralToBoolean:
1192 return EmitIntToBoolConversion(Visit(E));
1193 case CK_PointerToBoolean:
1194 return EmitPointerToBoolConversion(Visit(E));
1195 case CK_FloatingToBoolean:
1196 return EmitFloatToBoolConversion(Visit(E));
1197 case CK_MemberPointerToBoolean: {
1198 llvm::Value *MemPtr = Visit(E);
1199 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1200 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1203 case CK_FloatingComplexToReal:
1204 case CK_IntegralComplexToReal:
1205 return CGF.EmitComplexExpr(E, false, true).first;
1207 case CK_FloatingComplexToBoolean:
1208 case CK_IntegralComplexToBoolean: {
1209 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1211 // TODO: kill this function off, inline appropriate case here
1212 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1217 llvm_unreachable("unknown scalar cast");
1221 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1222 CodeGenFunction::StmtExprEvaluation eval(CGF);
1223 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1227 Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
1228 LValue LV = CGF.EmitBlockDeclRefLValue(E);
1229 return CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
1232 //===----------------------------------------------------------------------===//
1234 //===----------------------------------------------------------------------===//
1236 llvm::Value *ScalarExprEmitter::
1237 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1239 llvm::Value *NextVal, bool IsInc) {
1240 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1241 case LangOptions::SOB_Undefined:
1242 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1244 case LangOptions::SOB_Defined:
1245 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1247 case LangOptions::SOB_Trapping:
1250 BinOp.RHS = NextVal;
1251 BinOp.Ty = E->getType();
1252 BinOp.Opcode = BO_Add;
1254 return EmitOverflowCheckedBinOp(BinOp);
1257 assert(false && "Unknown SignedOverflowBehaviorTy");
1262 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1263 bool isInc, bool isPre) {
1265 QualType type = E->getSubExpr()->getType();
1266 llvm::Value *value = EmitLoadOfLValue(LV, type);
1267 llvm::Value *input = value;
1269 int amount = (isInc ? 1 : -1);
1271 // Special case of integer increment that we have to check first: bool++.
1272 // Due to promotion rules, we get:
1273 // bool++ -> bool = bool + 1
1274 // -> bool = (int)bool + 1
1275 // -> bool = ((int)bool + 1 != 0)
1276 // An interesting aspect of this is that increment is always true.
1277 // Decrement does not have this property.
1278 if (isInc && type->isBooleanType()) {
1279 value = Builder.getTrue();
1281 // Most common case by far: integer increment.
1282 } else if (type->isIntegerType()) {
1284 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1286 // Note that signed integer inc/dec with width less than int can't
1287 // overflow because of promotion rules; we're just eliding a few steps here.
1288 if (type->isSignedIntegerType() &&
1289 value->getType()->getPrimitiveSizeInBits() >=
1290 CGF.CGM.IntTy->getBitWidth())
1291 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1293 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1295 // Next most common: pointer increment.
1296 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1297 QualType type = ptr->getPointeeType();
1299 // VLA types don't have constant size.
1300 if (type->isVariableArrayType()) {
1301 llvm::Value *vlaSize =
1302 CGF.GetVLASize(CGF.getContext().getAsVariableArrayType(type));
1303 value = CGF.EmitCastToVoidPtr(value);
1304 if (!isInc) vlaSize = Builder.CreateNSWNeg(vlaSize, "vla.negsize");
1305 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1306 value = Builder.CreateGEP(value, vlaSize, "vla.inc");
1308 value = Builder.CreateInBoundsGEP(value, vlaSize, "vla.inc");
1309 value = Builder.CreateBitCast(value, input->getType());
1311 // Arithmetic on function pointers (!) is just +-1.
1312 } else if (type->isFunctionType()) {
1313 llvm::Value *amt = Builder.getInt32(amount);
1315 value = CGF.EmitCastToVoidPtr(value);
1316 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1317 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1319 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1320 value = Builder.CreateBitCast(value, input->getType());
1322 // For everything else, we can just do a simple increment.
1324 llvm::Value *amt = Builder.getInt32(amount);
1325 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1326 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1328 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1331 // Vector increment/decrement.
1332 } else if (type->isVectorType()) {
1333 if (type->hasIntegerRepresentation()) {
1334 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1336 if (type->hasSignedIntegerRepresentation())
1337 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1339 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1341 value = Builder.CreateFAdd(
1343 llvm::ConstantFP::get(value->getType(), amount),
1344 isInc ? "inc" : "dec");
1348 } else if (type->isRealFloatingType()) {
1349 // Add the inc/dec to the real part.
1351 if (value->getType()->isFloatTy())
1352 amt = llvm::ConstantFP::get(VMContext,
1353 llvm::APFloat(static_cast<float>(amount)));
1354 else if (value->getType()->isDoubleTy())
1355 amt = llvm::ConstantFP::get(VMContext,
1356 llvm::APFloat(static_cast<double>(amount)));
1358 llvm::APFloat F(static_cast<float>(amount));
1360 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1362 amt = llvm::ConstantFP::get(VMContext, F);
1364 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1366 // Objective-C pointer types.
1368 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1369 value = CGF.EmitCastToVoidPtr(value);
1371 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1372 if (!isInc) size = -size;
1373 llvm::Value *sizeValue =
1374 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1376 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1377 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1379 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1380 value = Builder.CreateBitCast(value, input->getType());
1383 // Store the updated result through the lvalue.
1384 if (LV.isBitField())
1385 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, type, &value);
1387 CGF.EmitStoreThroughLValue(RValue::get(value), LV, type);
1389 // If this is a postinc, return the value read from memory, otherwise use the
1391 return isPre ? value : input;
1396 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1397 TestAndClearIgnoreResultAssign();
1398 // Emit unary minus with EmitSub so we handle overflow cases etc.
1400 BinOp.RHS = Visit(E->getSubExpr());
1402 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1403 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1405 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1406 BinOp.Ty = E->getType();
1407 BinOp.Opcode = BO_Sub;
1409 return EmitSub(BinOp);
1412 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1413 TestAndClearIgnoreResultAssign();
1414 Value *Op = Visit(E->getSubExpr());
1415 return Builder.CreateNot(Op, "neg");
1418 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1419 // Compare operand to zero.
1420 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1423 // TODO: Could dynamically modify easy computations here. For example, if
1424 // the operand is an icmp ne, turn into icmp eq.
1425 BoolVal = Builder.CreateNot(BoolVal, "lnot");
1427 // ZExt result to the expr type.
1428 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1431 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1432 // Try folding the offsetof to a constant.
1433 Expr::EvalResult EvalResult;
1434 if (E->Evaluate(EvalResult, CGF.getContext()))
1435 return Builder.getInt(EvalResult.Val.getInt());
1437 // Loop over the components of the offsetof to compute the value.
1438 unsigned n = E->getNumComponents();
1439 const llvm::Type* ResultType = ConvertType(E->getType());
1440 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1441 QualType CurrentType = E->getTypeSourceInfo()->getType();
1442 for (unsigned i = 0; i != n; ++i) {
1443 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1444 llvm::Value *Offset = 0;
1445 switch (ON.getKind()) {
1446 case OffsetOfExpr::OffsetOfNode::Array: {
1447 // Compute the index
1448 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1449 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1450 bool IdxSigned = IdxExpr->getType()->isSignedIntegerType();
1451 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1453 // Save the element type
1455 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1457 // Compute the element size
1458 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1459 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1461 // Multiply out to compute the result
1462 Offset = Builder.CreateMul(Idx, ElemSize);
1466 case OffsetOfExpr::OffsetOfNode::Field: {
1467 FieldDecl *MemberDecl = ON.getField();
1468 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1469 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1471 // Compute the index of the field in its parent.
1473 // FIXME: It would be nice if we didn't have to loop here!
1474 for (RecordDecl::field_iterator Field = RD->field_begin(),
1475 FieldEnd = RD->field_end();
1476 Field != FieldEnd; (void)++Field, ++i) {
1477 if (*Field == MemberDecl)
1480 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1482 // Compute the offset to the field
1483 int64_t OffsetInt = RL.getFieldOffset(i) /
1484 CGF.getContext().getCharWidth();
1485 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1487 // Save the element type.
1488 CurrentType = MemberDecl->getType();
1492 case OffsetOfExpr::OffsetOfNode::Identifier:
1493 llvm_unreachable("dependent __builtin_offsetof");
1495 case OffsetOfExpr::OffsetOfNode::Base: {
1496 if (ON.getBase()->isVirtual()) {
1497 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1501 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1502 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1504 // Save the element type.
1505 CurrentType = ON.getBase()->getType();
1507 // Compute the offset to the base.
1508 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1509 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1510 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
1511 CGF.getContext().getCharWidth();
1512 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1516 Result = Builder.CreateAdd(Result, Offset);
1521 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1522 /// argument of the sizeof expression as an integer.
1524 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1525 const UnaryExprOrTypeTraitExpr *E) {
1526 QualType TypeToSize = E->getTypeOfArgument();
1527 if (E->getKind() == UETT_SizeOf) {
1528 if (const VariableArrayType *VAT =
1529 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1530 if (E->isArgumentType()) {
1531 // sizeof(type) - make sure to emit the VLA size.
1532 CGF.EmitVLASize(TypeToSize);
1534 // C99 6.5.3.4p2: If the argument is an expression of type
1535 // VLA, it is evaluated.
1536 CGF.EmitIgnoredExpr(E->getArgumentExpr());
1539 return CGF.GetVLASize(VAT);
1543 // If this isn't sizeof(vla), the result must be constant; use the constant
1544 // folding logic so we don't have to duplicate it here.
1545 Expr::EvalResult Result;
1546 E->Evaluate(Result, CGF.getContext());
1547 return Builder.getInt(Result.Val.getInt());
1550 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1551 Expr *Op = E->getSubExpr();
1552 if (Op->getType()->isAnyComplexType()) {
1553 // If it's an l-value, load through the appropriate subobject l-value.
1554 // Note that we have to ask E because Op might be an l-value that
1555 // this won't work for, e.g. an Obj-C property.
1557 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1560 // Otherwise, calculate and project.
1561 return CGF.EmitComplexExpr(Op, false, true).first;
1567 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1568 Expr *Op = E->getSubExpr();
1569 if (Op->getType()->isAnyComplexType()) {
1570 // If it's an l-value, load through the appropriate subobject l-value.
1571 // Note that we have to ask E because Op might be an l-value that
1572 // this won't work for, e.g. an Obj-C property.
1573 if (Op->isGLValue())
1574 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1577 // Otherwise, calculate and project.
1578 return CGF.EmitComplexExpr(Op, true, false).second;
1581 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1582 // effects are evaluated, but not the actual value.
1583 CGF.EmitScalarExpr(Op, true);
1584 return llvm::Constant::getNullValue(ConvertType(E->getType()));
1587 //===----------------------------------------------------------------------===//
1589 //===----------------------------------------------------------------------===//
1591 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1592 TestAndClearIgnoreResultAssign();
1594 Result.LHS = Visit(E->getLHS());
1595 Result.RHS = Visit(E->getRHS());
1596 Result.Ty = E->getType();
1597 Result.Opcode = E->getOpcode();
1602 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1603 const CompoundAssignOperator *E,
1604 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1606 QualType LHSTy = E->getLHS()->getType();
1609 if (E->getComputationResultType()->isAnyComplexType()) {
1610 // This needs to go through the complex expression emitter, but it's a tad
1611 // complicated to do that... I'm leaving it out for now. (Note that we do
1612 // actually need the imaginary part of the RHS for multiplication and
1614 CGF.ErrorUnsupported(E, "complex compound assignment");
1615 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1619 // Emit the RHS first. __block variables need to have the rhs evaluated
1620 // first, plus this should improve codegen a little.
1621 OpInfo.RHS = Visit(E->getRHS());
1622 OpInfo.Ty = E->getComputationResultType();
1623 OpInfo.Opcode = E->getOpcode();
1625 // Load/convert the LHS.
1626 LValue LHSLV = EmitCheckedLValue(E->getLHS());
1627 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
1628 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1629 E->getComputationLHSType());
1631 // Expand the binary operator.
1632 Result = (this->*Func)(OpInfo);
1634 // Convert the result back to the LHS type.
1635 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1637 // Store the result value into the LHS lvalue. Bit-fields are handled
1638 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1639 // 'An assignment expression has the value of the left operand after the
1641 if (LHSLV.isBitField())
1642 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1645 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
1650 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1651 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1652 bool Ignore = TestAndClearIgnoreResultAssign();
1654 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1656 // If the result is clearly ignored, return now.
1660 // The result of an assignment in C is the assigned r-value.
1661 if (!CGF.getContext().getLangOptions().CPlusPlus)
1664 // Objective-C property assignment never reloads the value following a store.
1665 if (LHS.isPropertyRef())
1668 // If the lvalue is non-volatile, return the computed value of the assignment.
1669 if (!LHS.isVolatileQualified())
1672 // Otherwise, reload the value.
1673 return EmitLoadOfLValue(LHS, E->getType());
1676 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1677 const BinOpInfo &Ops,
1678 llvm::Value *Zero, bool isDiv) {
1679 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1680 llvm::BasicBlock *contBB =
1681 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn);
1683 const llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1685 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1686 llvm::Value *IntMin =
1687 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1688 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1690 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1691 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1692 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1693 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1694 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1695 overflowBB, contBB);
1697 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1698 overflowBB, contBB);
1700 EmitOverflowBB(overflowBB);
1701 Builder.SetInsertPoint(contBB);
1704 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1705 if (isTrapvOverflowBehavior()) {
1706 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1708 if (Ops.Ty->isIntegerType())
1709 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1710 else if (Ops.Ty->isRealFloatingType()) {
1711 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1713 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn);
1714 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1715 overflowBB, DivCont);
1716 EmitOverflowBB(overflowBB);
1717 Builder.SetInsertPoint(DivCont);
1720 if (Ops.LHS->getType()->isFPOrFPVectorTy())
1721 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1722 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
1723 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1725 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1728 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1729 // Rem in C can't be a floating point type: C99 6.5.5p2.
1730 if (isTrapvOverflowBehavior()) {
1731 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1733 if (Ops.Ty->isIntegerType())
1734 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1737 if (Ops.Ty->hasUnsignedIntegerRepresentation())
1738 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1740 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1743 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1747 switch (Ops.Opcode) {
1751 IID = llvm::Intrinsic::sadd_with_overflow;
1756 IID = llvm::Intrinsic::ssub_with_overflow;
1761 IID = llvm::Intrinsic::smul_with_overflow;
1764 assert(false && "Unsupported operation for overflow detection");
1770 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1772 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1774 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1775 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1776 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1778 // Branch in case of overflow.
1779 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1780 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1781 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
1783 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1785 // Handle overflow with llvm.trap.
1786 const std::string *handlerName =
1787 &CGF.getContext().getLangOptions().OverflowHandler;
1788 if (handlerName->empty()) {
1789 EmitOverflowBB(overflowBB);
1790 Builder.SetInsertPoint(continueBB);
1794 // If an overflow handler is set, then we want to call it and then use its
1795 // result, if it returns.
1796 Builder.SetInsertPoint(overflowBB);
1798 // Get the overflow handler.
1799 const llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
1800 std::vector<const llvm::Type*> argTypes;
1801 argTypes.push_back(CGF.Int64Ty); argTypes.push_back(CGF.Int64Ty);
1802 argTypes.push_back(Int8Ty); argTypes.push_back(Int8Ty);
1803 llvm::FunctionType *handlerTy =
1804 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1805 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1807 // Sign extend the args to 64-bit, so that we can use the same handler for
1808 // all types of overflow.
1809 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1810 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1812 // Call the handler with the two arguments, the operation, and the size of
1814 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1815 Builder.getInt8(OpID),
1816 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1818 // Truncate the result back to the desired size.
1819 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1820 Builder.CreateBr(continueBB);
1822 Builder.SetInsertPoint(continueBB);
1823 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
1824 phi->addIncoming(result, initialBB);
1825 phi->addIncoming(handlerResult, overflowBB);
1830 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
1831 if (!Ops.Ty->isAnyPointerType()) {
1832 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1833 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1834 case LangOptions::SOB_Undefined:
1835 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1836 case LangOptions::SOB_Defined:
1837 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1838 case LangOptions::SOB_Trapping:
1839 return EmitOverflowCheckedBinOp(Ops);
1843 if (Ops.LHS->getType()->isFPOrFPVectorTy())
1844 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1846 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1849 // Must have binary (not unary) expr here. Unary pointer decrement doesn't
1851 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1853 if (Ops.Ty->isPointerType() &&
1854 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
1855 // The amount of the addition needs to account for the VLA size
1856 CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
1861 const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
1862 const ObjCObjectPointerType *OPT =
1863 BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
1867 IdxExp = BinOp->getRHS();
1868 } else { // int + pointer
1869 PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1870 OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
1871 assert((PT || OPT) && "Invalid add expr");
1874 IdxExp = BinOp->getLHS();
1877 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1878 if (Width < CGF.PointerWidthInBits) {
1879 // Zero or sign extend the pointer value based on whether the index is
1881 const llvm::Type *IdxType = CGF.IntPtrTy;
1882 if (IdxExp->getType()->isSignedIntegerType())
1883 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1885 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1887 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
1888 // Handle interface types, which are not represented with a concrete type.
1889 if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
1890 llvm::Value *InterfaceSize =
1891 llvm::ConstantInt::get(Idx->getType(),
1892 CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
1893 Idx = Builder.CreateMul(Idx, InterfaceSize);
1894 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1895 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1896 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1897 return Builder.CreateBitCast(Res, Ptr->getType());
1900 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1901 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1903 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1904 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1905 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1906 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1907 return Builder.CreateBitCast(Res, Ptr->getType());
1910 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1911 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
1912 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
1915 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
1916 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
1917 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1918 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1919 case LangOptions::SOB_Undefined:
1920 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1921 case LangOptions::SOB_Defined:
1922 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1923 case LangOptions::SOB_Trapping:
1924 return EmitOverflowCheckedBinOp(Ops);
1928 if (Ops.LHS->getType()->isFPOrFPVectorTy())
1929 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
1931 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1934 // Must have binary (not unary) expr here. Unary pointer increment doesn't
1936 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1938 if (BinOp->getLHS()->getType()->isPointerType() &&
1939 BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
1940 // The amount of the addition needs to account for the VLA size for
1942 // The amount of the division needs to account for the VLA size for
1944 CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
1947 const QualType LHSType = BinOp->getLHS()->getType();
1948 const QualType LHSElementType = LHSType->getPointeeType();
1949 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1951 Value *Idx = Ops.RHS;
1952 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1953 if (Width < CGF.PointerWidthInBits) {
1954 // Zero or sign extend the pointer value based on whether the index is
1956 const llvm::Type *IdxType = CGF.IntPtrTy;
1957 if (BinOp->getRHS()->getType()->isSignedIntegerType())
1958 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1960 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1962 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
1964 // Handle interface types, which are not represented with a concrete type.
1965 if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
1966 llvm::Value *InterfaceSize =
1967 llvm::ConstantInt::get(Idx->getType(),
1969 getTypeSizeInChars(OIT).getQuantity());
1970 Idx = Builder.CreateMul(Idx, InterfaceSize);
1971 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1972 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1973 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1974 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1977 // Explicitly handle GNU void* and function pointer arithmetic
1978 // extensions. The GNU void* casts amount to no-ops since our void* type is
1979 // i8*, but this is future proof.
1980 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1981 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1982 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1983 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1984 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1987 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1988 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
1989 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
1992 // pointer - pointer
1993 Value *LHS = Ops.LHS;
1994 Value *RHS = Ops.RHS;
1996 CharUnits ElementSize;
1998 // Handle GCC extension for pointer arithmetic on void* and function pointer
2000 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType())
2001 ElementSize = CharUnits::One();
2003 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
2005 const llvm::Type *ResultType = ConvertType(Ops.Ty);
2006 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
2007 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
2008 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2010 // Optimize out the shift for element size of 1.
2011 if (ElementSize.isOne())
2012 return BytesBetween;
2014 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2015 // pointer difference in C is only defined in the case where both operands
2016 // are pointing to elements of an array.
2017 Value *BytesPerElt =
2018 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
2019 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
2022 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2023 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2024 // RHS to the same size as the LHS.
2025 Value *RHS = Ops.RHS;
2026 if (Ops.LHS->getType() != RHS->getType())
2027 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2029 if (CGF.CatchUndefined
2030 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2031 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2032 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2033 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2034 llvm::ConstantInt::get(RHS->getType(), Width)),
2035 Cont, CGF.getTrapBB());
2036 CGF.EmitBlock(Cont);
2039 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2042 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2043 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2044 // RHS to the same size as the LHS.
2045 Value *RHS = Ops.RHS;
2046 if (Ops.LHS->getType() != RHS->getType())
2047 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2049 if (CGF.CatchUndefined
2050 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2051 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2052 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2053 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2054 llvm::ConstantInt::get(RHS->getType(), Width)),
2055 Cont, CGF.getTrapBB());
2056 CGF.EmitBlock(Cont);
2059 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2060 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2061 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2064 enum IntrinsicType { VCMPEQ, VCMPGT };
2065 // return corresponding comparison intrinsic for given vector type
2066 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2067 BuiltinType::Kind ElemKind) {
2069 default: assert(0 && "unexpected element type");
2070 case BuiltinType::Char_U:
2071 case BuiltinType::UChar:
2072 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2073 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2075 case BuiltinType::Char_S:
2076 case BuiltinType::SChar:
2077 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2078 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2080 case BuiltinType::UShort:
2081 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2082 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2084 case BuiltinType::Short:
2085 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2086 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2088 case BuiltinType::UInt:
2089 case BuiltinType::ULong:
2090 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2091 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2093 case BuiltinType::Int:
2094 case BuiltinType::Long:
2095 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2096 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2098 case BuiltinType::Float:
2099 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2100 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2103 return llvm::Intrinsic::not_intrinsic;
2106 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2107 unsigned SICmpOpc, unsigned FCmpOpc) {
2108 TestAndClearIgnoreResultAssign();
2110 QualType LHSTy = E->getLHS()->getType();
2111 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2112 assert(E->getOpcode() == BO_EQ ||
2113 E->getOpcode() == BO_NE);
2114 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2115 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2116 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2117 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2118 } else if (!LHSTy->isAnyComplexType()) {
2119 Value *LHS = Visit(E->getLHS());
2120 Value *RHS = Visit(E->getRHS());
2122 // If AltiVec, the comparison results in a numeric type, so we use
2123 // intrinsics comparing vectors and giving 0 or 1 as a result
2124 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2125 // constants for mapping CR6 register bits to predicate result
2126 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2128 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2130 // in several cases vector arguments order will be reversed
2131 Value *FirstVecArg = LHS,
2132 *SecondVecArg = RHS;
2134 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2135 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2136 BuiltinType::Kind ElementKind = BTy->getKind();
2138 switch(E->getOpcode()) {
2139 default: assert(0 && "is not a comparison operation");
2142 ID = GetIntrinsic(VCMPEQ, ElementKind);
2146 ID = GetIntrinsic(VCMPEQ, ElementKind);
2150 ID = GetIntrinsic(VCMPGT, ElementKind);
2151 std::swap(FirstVecArg, SecondVecArg);
2155 ID = GetIntrinsic(VCMPGT, ElementKind);
2158 if (ElementKind == BuiltinType::Float) {
2160 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2161 std::swap(FirstVecArg, SecondVecArg);
2165 ID = GetIntrinsic(VCMPGT, ElementKind);
2169 if (ElementKind == BuiltinType::Float) {
2171 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2175 ID = GetIntrinsic(VCMPGT, ElementKind);
2176 std::swap(FirstVecArg, SecondVecArg);
2181 Value *CR6Param = Builder.getInt32(CR6);
2182 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2183 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2184 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2187 if (LHS->getType()->isFPOrFPVectorTy()) {
2188 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2190 } else if (LHSTy->hasSignedIntegerRepresentation()) {
2191 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2194 // Unsigned integers and pointers.
2195 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2199 // If this is a vector comparison, sign extend the result to the appropriate
2200 // vector integer type and return it (don't convert to bool).
2201 if (LHSTy->isVectorType())
2202 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2205 // Complex Comparison: can only be an equality comparison.
2206 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2207 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
2209 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
2211 Value *ResultR, *ResultI;
2212 if (CETy->isRealFloatingType()) {
2213 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2214 LHS.first, RHS.first, "cmp.r");
2215 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2216 LHS.second, RHS.second, "cmp.i");
2218 // Complex comparisons can only be equality comparisons. As such, signed
2219 // and unsigned opcodes are the same.
2220 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2221 LHS.first, RHS.first, "cmp.r");
2222 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2223 LHS.second, RHS.second, "cmp.i");
2226 if (E->getOpcode() == BO_EQ) {
2227 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2229 assert(E->getOpcode() == BO_NE &&
2230 "Complex comparison other than == or != ?");
2231 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2235 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2238 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2239 bool Ignore = TestAndClearIgnoreResultAssign();
2241 // __block variables need to have the rhs evaluated first, plus this should
2242 // improve codegen just a little.
2243 Value *RHS = Visit(E->getRHS());
2244 LValue LHS = EmitCheckedLValue(E->getLHS());
2246 // Store the value into the LHS. Bit-fields are handled specially
2247 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2248 // 'An assignment expression has the value of the left operand after
2249 // the assignment...'.
2250 if (LHS.isBitField())
2251 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
2254 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
2256 // If the result is clearly ignored, return now.
2260 // The result of an assignment in C is the assigned r-value.
2261 if (!CGF.getContext().getLangOptions().CPlusPlus)
2264 // Objective-C property assignment never reloads the value following a store.
2265 if (LHS.isPropertyRef())
2268 // If the lvalue is non-volatile, return the computed value of the assignment.
2269 if (!LHS.isVolatileQualified())
2272 // Otherwise, reload the value.
2273 return EmitLoadOfLValue(LHS, E->getType());
2276 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2277 const llvm::Type *ResTy = ConvertType(E->getType());
2279 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2280 // If we have 1 && X, just emit X without inserting the control flow.
2282 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2283 if (LHSCondVal) { // If we have 1 && X, just emit X.
2284 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2285 // ZExt result to int or bool.
2286 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
2289 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
2290 if (!CGF.ContainsLabel(E->getRHS()))
2291 return llvm::Constant::getNullValue(ResTy);
2294 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2295 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
2297 CodeGenFunction::ConditionalEvaluation eval(CGF);
2299 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2300 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2302 // Any edges into the ContBlock are now from an (indeterminate number of)
2303 // edges from this first condition. All of these values will be false. Start
2304 // setting up the PHI node in the Cont Block for this.
2305 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2307 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2309 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
2312 CGF.EmitBlock(RHSBlock);
2313 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2316 // Reaquire the RHS block, as there may be subblocks inserted.
2317 RHSBlock = Builder.GetInsertBlock();
2319 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2320 // into the phi node for the edge with the value of RHSCond.
2321 if (CGF.getDebugInfo())
2322 // There is no need to emit line number for unconditional branch.
2323 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
2324 CGF.EmitBlock(ContBlock);
2325 PN->addIncoming(RHSCond, RHSBlock);
2327 // ZExt result to int.
2328 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
2331 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
2332 const llvm::Type *ResTy = ConvertType(E->getType());
2334 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2335 // If we have 0 || X, just emit X without inserting the control flow.
2337 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2338 if (!LHSCondVal) { // If we have 0 || X, just emit X.
2339 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2340 // ZExt result to int or bool.
2341 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
2344 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
2345 if (!CGF.ContainsLabel(E->getRHS()))
2346 return llvm::ConstantInt::get(ResTy, 1);
2349 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2350 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
2352 CodeGenFunction::ConditionalEvaluation eval(CGF);
2354 // Branch on the LHS first. If it is true, go to the success (cont) block.
2355 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2357 // Any edges into the ContBlock are now from an (indeterminate number of)
2358 // edges from this first condition. All of these values will be true. Start
2359 // setting up the PHI node in the Cont Block for this.
2360 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2362 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2364 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
2368 // Emit the RHS condition as a bool value.
2369 CGF.EmitBlock(RHSBlock);
2370 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2374 // Reaquire the RHS block, as there may be subblocks inserted.
2375 RHSBlock = Builder.GetInsertBlock();
2377 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2378 // into the phi node for the edge with the value of RHSCond.
2379 CGF.EmitBlock(ContBlock);
2380 PN->addIncoming(RHSCond, RHSBlock);
2382 // ZExt result to int.
2383 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
2386 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2387 CGF.EmitIgnoredExpr(E->getLHS());
2388 CGF.EnsureInsertPoint();
2389 return Visit(E->getRHS());
2392 //===----------------------------------------------------------------------===//
2394 //===----------------------------------------------------------------------===//
2396 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2397 /// expression is cheap enough and side-effect-free enough to evaluate
2398 /// unconditionally instead of conditionally. This is used to convert control
2399 /// flow into selects in some cases.
2400 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2401 CodeGenFunction &CGF) {
2402 E = E->IgnoreParens();
2404 // Anything that is an integer or floating point constant is fine.
2405 if (E->isConstantInitializer(CGF.getContext(), false))
2408 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2409 // X and Y are local variables.
2410 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2411 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2412 if (VD->hasLocalStorage() && !(CGF.getContext()
2413 .getCanonicalType(VD->getType())
2414 .isVolatileQualified()))
2421 Value *ScalarExprEmitter::
2422 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
2423 TestAndClearIgnoreResultAssign();
2425 // Bind the common expression if necessary.
2426 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2428 Expr *condExpr = E->getCond();
2429 Expr *lhsExpr = E->getTrueExpr();
2430 Expr *rhsExpr = E->getFalseExpr();
2432 // If the condition constant folds and can be elided, try to avoid emitting
2433 // the condition and the dead arm.
2435 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2436 Expr *live = lhsExpr, *dead = rhsExpr;
2437 if (!CondExprBool) std::swap(live, dead);
2439 // If the dead side doesn't have labels we need, and if the Live side isn't
2440 // the gnu missing ?: extension (which we could handle, but don't bother
2441 // to), just emit the Live part.
2442 if (!CGF.ContainsLabel(dead))
2446 // OpenCL: If the condition is a vector, we can treat this condition like
2447 // the select function.
2448 if (CGF.getContext().getLangOptions().OpenCL
2449 && condExpr->getType()->isVectorType()) {
2450 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2451 llvm::Value *LHS = Visit(lhsExpr);
2452 llvm::Value *RHS = Visit(rhsExpr);
2454 const llvm::Type *condType = ConvertType(condExpr->getType());
2455 const llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2457 unsigned numElem = vecTy->getNumElements();
2458 const llvm::Type *elemType = vecTy->getElementType();
2460 std::vector<llvm::Constant*> Zvals;
2461 for (unsigned i = 0; i < numElem; ++i)
2462 Zvals.push_back(llvm::ConstantInt::get(elemType, 0));
2464 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2465 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2466 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2467 llvm::VectorType::get(elemType,
2470 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2472 // Cast float to int to perform ANDs if necessary.
2473 llvm::Value *RHSTmp = RHS;
2474 llvm::Value *LHSTmp = LHS;
2475 bool wasCast = false;
2476 const llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2477 if (rhsVTy->getElementType()->isFloatTy()) {
2478 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2479 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2483 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2484 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2485 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2487 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2492 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2493 // select instead of as control flow. We can only do this if it is cheap and
2494 // safe to evaluate the LHS and RHS unconditionally.
2495 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2496 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2497 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2498 llvm::Value *LHS = Visit(lhsExpr);
2499 llvm::Value *RHS = Visit(rhsExpr);
2500 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2503 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2504 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
2505 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
2507 CodeGenFunction::ConditionalEvaluation eval(CGF);
2508 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
2510 CGF.EmitBlock(LHSBlock);
2512 Value *LHS = Visit(lhsExpr);
2515 LHSBlock = Builder.GetInsertBlock();
2516 Builder.CreateBr(ContBlock);
2518 CGF.EmitBlock(RHSBlock);
2520 Value *RHS = Visit(rhsExpr);
2523 RHSBlock = Builder.GetInsertBlock();
2524 CGF.EmitBlock(ContBlock);
2526 // If the LHS or RHS is a throw expression, it will be legitimately null.
2532 // Create a PHI node for the real part.
2533 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
2534 PN->addIncoming(LHS, LHSBlock);
2535 PN->addIncoming(RHS, RHSBlock);
2539 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
2540 return Visit(E->getChosenSubExpr(CGF.getContext()));
2543 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
2544 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
2545 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2547 // If EmitVAArg fails, we fall back to the LLVM instruction.
2549 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2551 // FIXME Volatility.
2552 return Builder.CreateLoad(ArgPtr);
2555 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2556 return CGF.EmitBlockLiteral(block);
2559 //===----------------------------------------------------------------------===//
2560 // Entry Point into this File
2561 //===----------------------------------------------------------------------===//
2563 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
2564 /// type, ignoring the result.
2565 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
2566 assert(E && !hasAggregateLLVMType(E->getType()) &&
2567 "Invalid scalar expression to emit");
2569 if (isa<CXXDefaultArgExpr>(E))
2571 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
2572 .Visit(const_cast<Expr*>(E));
2573 if (isa<CXXDefaultArgExpr>(E))
2578 /// EmitScalarConversion - Emit a conversion from the specified type to the
2579 /// specified destination type, both of which are LLVM scalar types.
2580 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2582 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2583 "Invalid scalar expression to emit");
2584 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2587 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2588 /// type to the specified destination type, where the destination type is an
2589 /// LLVM scalar type.
2590 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2593 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
2594 "Invalid complex -> scalar conversion");
2595 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2600 llvm::Value *CodeGenFunction::
2601 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2602 bool isInc, bool isPre) {
2603 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2606 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2608 // object->isa or (*object).isa
2609 // Generate code as for: *(Class*)object
2610 // build Class* type
2611 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
2613 Expr *BaseExpr = E->getBase();
2614 if (BaseExpr->isRValue()) {
2615 V = CreateTempAlloca(ClassPtrTy, "resval");
2616 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2617 Builder.CreateStore(Src, V);
2618 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2619 MakeAddrLValue(V, E->getType()), E->getType());
2622 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2624 V = EmitLValue(BaseExpr).getAddress();
2627 // build Class* type
2628 ClassPtrTy = ClassPtrTy->getPointerTo();
2629 V = Builder.CreateBitCast(V, ClassPtrTy);
2630 return MakeAddrLValue(V, E->getType());
2634 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
2635 const CompoundAssignOperator *E) {
2636 ScalarExprEmitter Scalar(*this);
2638 switch (E->getOpcode()) {
2639 #define COMPOUND_OP(Op) \
2640 case BO_##Op##Assign: \
2641 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
2677 assert(false && "Not valid compound assignment operators");
2681 llvm_unreachable("Unhandled compound assignment operator");