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"
16 #include "CGDebugInfo.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/StmtVisitor.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Frontend/CodeGenOptions.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Support/CFG.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
49 const Expr *E; // Entire expr, for error unsupported. May not be binop.
52 static bool MustVisitNullValue(const Expr *E) {
53 // If a null pointer expression's type is the C++0x nullptr_t, then
54 // it's not necessarily a simple constant and it must be evaluated
55 // for its potential side effects.
56 return E->getType()->isNullPtrType();
59 class ScalarExprEmitter
60 : public StmtVisitor<ScalarExprEmitter, Value*> {
63 bool IgnoreResultAssign;
64 llvm::LLVMContext &VMContext;
67 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
68 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
69 VMContext(cgf.getLLVMContext()) {
72 //===--------------------------------------------------------------------===//
74 //===--------------------------------------------------------------------===//
76 bool TestAndClearIgnoreResultAssign() {
77 bool I = IgnoreResultAssign;
78 IgnoreResultAssign = false;
82 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
83 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
84 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85 return CGF.EmitCheckedLValue(E, TCK);
88 void EmitBinOpCheck(Value *Check, const BinOpInfo &Info);
90 Value *EmitLoadOfLValue(LValue LV) {
91 return CGF.EmitLoadOfLValue(LV).getScalarVal();
94 /// EmitLoadOfLValue - Given an expression with complex type that represents a
95 /// value l-value, this method emits the address of the l-value, then loads
96 /// and returns the result.
97 Value *EmitLoadOfLValue(const Expr *E) {
98 return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load));
101 /// EmitConversionToBool - Convert the specified expression value to a
102 /// boolean (i1) truth value. This is equivalent to "Val != 0".
103 Value *EmitConversionToBool(Value *Src, QualType DstTy);
105 /// \brief Emit a check that a conversion to or from a floating-point type
106 /// does not overflow.
107 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
108 Value *Src, QualType SrcType,
109 QualType DstType, llvm::Type *DstTy);
111 /// EmitScalarConversion - Emit a conversion from the specified type to the
112 /// specified destination type, both of which are LLVM scalar types.
113 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
115 /// EmitComplexToScalarConversion - Emit a conversion from the specified
116 /// complex type to the specified destination type, where the destination type
117 /// is an LLVM scalar type.
118 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
119 QualType SrcTy, QualType DstTy);
121 /// EmitNullValue - Emit a value that corresponds to null for the given type.
122 Value *EmitNullValue(QualType Ty);
124 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
125 Value *EmitFloatToBoolConversion(Value *V) {
126 // Compare against 0.0 for fp scalars.
127 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
128 return Builder.CreateFCmpUNE(V, Zero, "tobool");
131 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
132 Value *EmitPointerToBoolConversion(Value *V) {
133 Value *Zero = llvm::ConstantPointerNull::get(
134 cast<llvm::PointerType>(V->getType()));
135 return Builder.CreateICmpNE(V, Zero, "tobool");
138 Value *EmitIntToBoolConversion(Value *V) {
139 // Because of the type rules of C, we often end up computing a
140 // logical value, then zero extending it to int, then wanting it
141 // as a logical value again. Optimize this common case.
142 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
143 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
144 Value *Result = ZI->getOperand(0);
145 // If there aren't any more uses, zap the instruction to save space.
146 // Note that there can be more uses, for example if this
147 // is the result of an assignment.
149 ZI->eraseFromParent();
154 return Builder.CreateIsNotNull(V, "tobool");
157 //===--------------------------------------------------------------------===//
159 //===--------------------------------------------------------------------===//
161 Value *Visit(Expr *E) {
162 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
165 Value *VisitStmt(Stmt *S) {
166 S->dump(CGF.getContext().getSourceManager());
167 llvm_unreachable("Stmt can't have complex result type!");
169 Value *VisitExpr(Expr *S);
171 Value *VisitParenExpr(ParenExpr *PE) {
172 return Visit(PE->getSubExpr());
174 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
175 return Visit(E->getReplacement());
177 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
178 return Visit(GE->getResultExpr());
182 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
183 return Builder.getInt(E->getValue());
185 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
186 return llvm::ConstantFP::get(VMContext, E->getValue());
188 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
189 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
191 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
192 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
194 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
195 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
197 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
198 return EmitNullValue(E->getType());
200 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
201 return EmitNullValue(E->getType());
203 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
204 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
205 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
206 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
207 return Builder.CreateBitCast(V, ConvertType(E->getType()));
210 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
211 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
214 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
215 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
218 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
220 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
222 // Otherwise, assume the mapping is the scalar directly.
223 return CGF.getOpaqueRValueMapping(E).getScalarVal();
227 Value *VisitDeclRefExpr(DeclRefExpr *E) {
228 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
229 if (result.isReference())
230 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
231 return result.getValue();
233 return EmitLoadOfLValue(E);
236 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
237 return CGF.EmitObjCSelectorExpr(E);
239 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
240 return CGF.EmitObjCProtocolExpr(E);
242 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
243 return EmitLoadOfLValue(E);
245 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
246 if (E->getMethodDecl() &&
247 E->getMethodDecl()->getResultType()->isReferenceType())
248 return EmitLoadOfLValue(E);
249 return CGF.EmitObjCMessageExpr(E).getScalarVal();
252 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
253 LValue LV = CGF.EmitObjCIsaExpr(E);
254 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
258 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
259 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
260 Value *VisitMemberExpr(MemberExpr *E);
261 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
262 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
263 return EmitLoadOfLValue(E);
266 Value *VisitInitListExpr(InitListExpr *E);
268 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
269 return EmitNullValue(E->getType());
271 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
272 if (E->getType()->isVariablyModifiedType())
273 CGF.EmitVariablyModifiedType(E->getType());
274 return VisitCastExpr(E);
276 Value *VisitCastExpr(CastExpr *E);
278 Value *VisitCallExpr(const CallExpr *E) {
279 if (E->getCallReturnType()->isReferenceType())
280 return EmitLoadOfLValue(E);
282 return CGF.EmitCallExpr(E).getScalarVal();
285 Value *VisitStmtExpr(const StmtExpr *E);
288 Value *VisitUnaryPostDec(const UnaryOperator *E) {
289 LValue LV = EmitLValue(E->getSubExpr());
290 return EmitScalarPrePostIncDec(E, LV, false, false);
292 Value *VisitUnaryPostInc(const UnaryOperator *E) {
293 LValue LV = EmitLValue(E->getSubExpr());
294 return EmitScalarPrePostIncDec(E, LV, true, false);
296 Value *VisitUnaryPreDec(const UnaryOperator *E) {
297 LValue LV = EmitLValue(E->getSubExpr());
298 return EmitScalarPrePostIncDec(E, LV, false, true);
300 Value *VisitUnaryPreInc(const UnaryOperator *E) {
301 LValue LV = EmitLValue(E->getSubExpr());
302 return EmitScalarPrePostIncDec(E, LV, true, true);
305 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
307 llvm::Value *NextVal,
310 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
311 bool isInc, bool isPre);
314 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
315 if (isa<MemberPointerType>(E->getType())) // never sugared
316 return CGF.CGM.getMemberPointerConstant(E);
318 return EmitLValue(E->getSubExpr()).getAddress();
320 Value *VisitUnaryDeref(const UnaryOperator *E) {
321 if (E->getType()->isVoidType())
322 return Visit(E->getSubExpr()); // the actual value should be unused
323 return EmitLoadOfLValue(E);
325 Value *VisitUnaryPlus(const UnaryOperator *E) {
326 // This differs from gcc, though, most likely due to a bug in gcc.
327 TestAndClearIgnoreResultAssign();
328 return Visit(E->getSubExpr());
330 Value *VisitUnaryMinus (const UnaryOperator *E);
331 Value *VisitUnaryNot (const UnaryOperator *E);
332 Value *VisitUnaryLNot (const UnaryOperator *E);
333 Value *VisitUnaryReal (const UnaryOperator *E);
334 Value *VisitUnaryImag (const UnaryOperator *E);
335 Value *VisitUnaryExtension(const UnaryOperator *E) {
336 return Visit(E->getSubExpr());
340 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
341 return EmitLoadOfLValue(E);
344 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
345 return Visit(DAE->getExpr());
347 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
348 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
349 return Visit(DIE->getExpr());
351 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
352 return CGF.LoadCXXThis();
355 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
356 CGF.enterFullExpression(E);
357 CodeGenFunction::RunCleanupsScope Scope(CGF);
358 return Visit(E->getSubExpr());
360 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
361 return CGF.EmitCXXNewExpr(E);
363 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
364 CGF.EmitCXXDeleteExpr(E);
367 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
368 return Builder.getInt1(E->getValue());
371 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
372 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
375 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
376 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
379 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
380 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
383 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
384 // C++ [expr.pseudo]p1:
385 // The result shall only be used as the operand for the function call
386 // operator (), and the result of such a call has type void. The only
387 // effect is the evaluation of the postfix-expression before the dot or
389 CGF.EmitScalarExpr(E->getBase());
393 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
394 return EmitNullValue(E->getType());
397 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
398 CGF.EmitCXXThrowExpr(E);
402 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
403 return Builder.getInt1(E->getValue());
407 Value *EmitMul(const BinOpInfo &Ops) {
408 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
409 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
410 case LangOptions::SOB_Defined:
411 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
412 case LangOptions::SOB_Undefined:
413 if (!CGF.SanOpts->SignedIntegerOverflow)
414 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
416 case LangOptions::SOB_Trapping:
417 return EmitOverflowCheckedBinOp(Ops);
421 if (Ops.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
422 return EmitOverflowCheckedBinOp(Ops);
424 if (Ops.LHS->getType()->isFPOrFPVectorTy())
425 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
426 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
428 /// Create a binary op that checks for overflow.
429 /// Currently only supports +, - and *.
430 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
432 // Check for undefined division and modulus behaviors.
433 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
434 llvm::Value *Zero,bool isDiv);
435 // Common helper for getting how wide LHS of shift is.
436 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
437 Value *EmitDiv(const BinOpInfo &Ops);
438 Value *EmitRem(const BinOpInfo &Ops);
439 Value *EmitAdd(const BinOpInfo &Ops);
440 Value *EmitSub(const BinOpInfo &Ops);
441 Value *EmitShl(const BinOpInfo &Ops);
442 Value *EmitShr(const BinOpInfo &Ops);
443 Value *EmitAnd(const BinOpInfo &Ops) {
444 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
446 Value *EmitXor(const BinOpInfo &Ops) {
447 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
449 Value *EmitOr (const BinOpInfo &Ops) {
450 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
453 BinOpInfo EmitBinOps(const BinaryOperator *E);
454 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
455 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
458 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
459 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
461 // Binary operators and binary compound assignment operators.
462 #define HANDLEBINOP(OP) \
463 Value *VisitBin ## OP(const BinaryOperator *E) { \
464 return Emit ## OP(EmitBinOps(E)); \
466 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
467 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
482 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
483 unsigned SICmpOpc, unsigned FCmpOpc);
484 #define VISITCOMP(CODE, UI, SI, FP) \
485 Value *VisitBin##CODE(const BinaryOperator *E) { \
486 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
487 llvm::FCmpInst::FP); }
488 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
489 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
490 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
491 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
492 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
493 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
496 Value *VisitBinAssign (const BinaryOperator *E);
498 Value *VisitBinLAnd (const BinaryOperator *E);
499 Value *VisitBinLOr (const BinaryOperator *E);
500 Value *VisitBinComma (const BinaryOperator *E);
502 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
503 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
506 Value *VisitBlockExpr(const BlockExpr *BE);
507 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
508 Value *VisitChooseExpr(ChooseExpr *CE);
509 Value *VisitVAArgExpr(VAArgExpr *VE);
510 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
511 return CGF.EmitObjCStringLiteral(E);
513 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
514 return CGF.EmitObjCBoxedExpr(E);
516 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
517 return CGF.EmitObjCArrayLiteral(E);
519 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
520 return CGF.EmitObjCDictionaryLiteral(E);
522 Value *VisitAsTypeExpr(AsTypeExpr *CE);
523 Value *VisitAtomicExpr(AtomicExpr *AE);
525 } // end anonymous namespace.
527 //===----------------------------------------------------------------------===//
529 //===----------------------------------------------------------------------===//
531 /// EmitConversionToBool - Convert the specified expression value to a
532 /// boolean (i1) truth value. This is equivalent to "Val != 0".
533 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
534 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
536 if (SrcType->isRealFloatingType())
537 return EmitFloatToBoolConversion(Src);
539 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
540 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
542 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
543 "Unknown scalar type to convert");
545 if (isa<llvm::IntegerType>(Src->getType()))
546 return EmitIntToBoolConversion(Src);
548 assert(isa<llvm::PointerType>(Src->getType()));
549 return EmitPointerToBoolConversion(Src);
552 void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
553 QualType OrigSrcType,
554 Value *Src, QualType SrcType,
560 llvm::Type *SrcTy = Src->getType();
562 llvm::Value *Check = 0;
563 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
564 // Integer to floating-point. This can fail for unsigned short -> __half
565 // or unsigned __int128 -> float.
566 assert(DstType->isFloatingType());
567 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
569 APFloat LargestFloat =
570 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
571 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
574 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
575 &IsExact) != APFloat::opOK)
576 // The range of representable values of this floating point type includes
577 // all values of this integer type. Don't need an overflow check.
580 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
582 Check = Builder.CreateICmpULE(Src, Max);
584 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
585 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
586 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
587 Check = Builder.CreateAnd(GE, LE);
590 const llvm::fltSemantics &SrcSema =
591 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
592 if (isa<llvm::IntegerType>(DstTy)) {
593 // Floating-point to integer. This has undefined behavior if the source is
594 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
596 unsigned Width = CGF.getContext().getIntWidth(DstType);
597 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
599 APSInt Min = APSInt::getMinValue(Width, Unsigned);
600 APFloat MinSrc(SrcSema, APFloat::uninitialized);
601 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
603 // Don't need an overflow check for lower bound. Just check for
605 MinSrc = APFloat::getInf(SrcSema, true);
607 // Find the largest value which is too small to represent (before
608 // truncation toward zero).
609 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
611 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
612 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
613 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
615 // Don't need an overflow check for upper bound. Just check for
617 MaxSrc = APFloat::getInf(SrcSema, false);
619 // Find the smallest value which is too large to represent (before
620 // truncation toward zero).
621 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
623 // If we're converting from __half, convert the range to float to match
625 if (OrigSrcType->isHalfType()) {
626 const llvm::fltSemantics &Sema =
627 CGF.getContext().getFloatTypeSemantics(SrcType);
629 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
630 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
634 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
636 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
637 Check = Builder.CreateAnd(GE, LE);
639 // FIXME: Maybe split this sanitizer out from float-cast-overflow.
641 // Floating-point to floating-point. This has undefined behavior if the
642 // source is not in the range of representable values of the destination
643 // type. The C and C++ standards are spectacularly unclear here. We
644 // diagnose finite out-of-range conversions, but allow infinities and NaNs
645 // to convert to the corresponding value in the smaller type.
647 // C11 Annex F gives all such conversions defined behavior for IEC 60559
648 // conforming implementations. Unfortunately, LLVM's fptrunc instruction
651 // Converting from a lower rank to a higher rank can never have
652 // undefined behavior, since higher-rank types must have a superset
653 // of values of lower-rank types.
654 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
657 assert(!OrigSrcType->isHalfType() &&
658 "should not check conversion from __half, it has the lowest rank");
660 const llvm::fltSemantics &DstSema =
661 CGF.getContext().getFloatTypeSemantics(DstType);
662 APFloat MinBad = APFloat::getLargest(DstSema, false);
663 APFloat MaxBad = APFloat::getInf(DstSema, false);
666 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
667 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
669 Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
670 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
672 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
674 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
675 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
679 // FIXME: Provide a SourceLocation.
680 llvm::Constant *StaticArgs[] = {
681 CGF.EmitCheckTypeDescriptor(OrigSrcType),
682 CGF.EmitCheckTypeDescriptor(DstType)
684 CGF.EmitCheck(Check, "float_cast_overflow", StaticArgs, OrigSrc,
685 CodeGenFunction::CRK_Recoverable);
688 /// EmitScalarConversion - Emit a conversion from the specified type to the
689 /// specified destination type, both of which are LLVM scalar types.
690 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
692 SrcType = CGF.getContext().getCanonicalType(SrcType);
693 DstType = CGF.getContext().getCanonicalType(DstType);
694 if (SrcType == DstType) return Src;
696 if (DstType->isVoidType()) return 0;
698 llvm::Value *OrigSrc = Src;
699 QualType OrigSrcType = SrcType;
700 llvm::Type *SrcTy = Src->getType();
702 // If casting to/from storage-only half FP, use special intrinsics.
703 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
704 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
705 SrcType = CGF.getContext().FloatTy;
709 // Handle conversions to bool first, they are special: comparisons against 0.
710 if (DstType->isBooleanType())
711 return EmitConversionToBool(Src, SrcType);
713 llvm::Type *DstTy = ConvertType(DstType);
715 // Ignore conversions like int -> uint.
719 // Handle pointer conversions next: pointers can only be converted to/from
720 // other pointers and integers. Check for pointer types in terms of LLVM, as
721 // some native types (like Obj-C id) may map to a pointer type.
722 if (isa<llvm::PointerType>(DstTy)) {
723 // The source value may be an integer, or a pointer.
724 if (isa<llvm::PointerType>(SrcTy))
725 return Builder.CreateBitCast(Src, DstTy, "conv");
727 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
728 // First, convert to the correct width so that we control the kind of
730 llvm::Type *MiddleTy = CGF.IntPtrTy;
731 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
732 llvm::Value* IntResult =
733 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
734 // Then, cast to pointer.
735 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
738 if (isa<llvm::PointerType>(SrcTy)) {
739 // Must be an ptr to int cast.
740 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
741 return Builder.CreatePtrToInt(Src, DstTy, "conv");
744 // A scalar can be splatted to an extended vector of the same element type
745 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
746 // Cast the scalar to element type
747 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
748 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
750 // Splat the element across to all elements
751 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
752 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
755 // Allow bitcast from vector to integer/fp of the same size.
756 if (isa<llvm::VectorType>(SrcTy) ||
757 isa<llvm::VectorType>(DstTy))
758 return Builder.CreateBitCast(Src, DstTy, "conv");
760 // Finally, we have the arithmetic types: real int/float.
762 llvm::Type *ResTy = DstTy;
764 // An overflowing conversion has undefined behavior if either the source type
765 // or the destination type is a floating-point type.
766 if (CGF.SanOpts->FloatCastOverflow &&
767 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
768 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType,
771 // Cast to half via float
772 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType)
775 if (isa<llvm::IntegerType>(SrcTy)) {
776 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
777 if (isa<llvm::IntegerType>(DstTy))
778 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
779 else if (InputSigned)
780 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
782 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
783 } else if (isa<llvm::IntegerType>(DstTy)) {
784 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
785 if (DstType->isSignedIntegerOrEnumerationType())
786 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
788 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
790 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
791 "Unknown real conversion");
792 if (DstTy->getTypeID() < SrcTy->getTypeID())
793 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
795 Res = Builder.CreateFPExt(Src, DstTy, "conv");
798 if (DstTy != ResTy) {
799 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
800 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
806 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
807 /// type to the specified destination type, where the destination type is an
808 /// LLVM scalar type.
809 Value *ScalarExprEmitter::
810 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
811 QualType SrcTy, QualType DstTy) {
812 // Get the source element type.
813 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
815 // Handle conversions to bool first, they are special: comparisons against 0.
816 if (DstTy->isBooleanType()) {
817 // Complex != 0 -> (Real != 0) | (Imag != 0)
818 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
819 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
820 return Builder.CreateOr(Src.first, Src.second, "tobool");
823 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
824 // the imaginary part of the complex value is discarded and the value of the
825 // real part is converted according to the conversion rules for the
826 // corresponding real type.
827 return EmitScalarConversion(Src.first, SrcTy, DstTy);
830 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
831 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
834 /// \brief Emit a sanitization check for the given "binary" operation (which
835 /// might actually be a unary increment which has been lowered to a binary
836 /// operation). The check passes if \p Check, which is an \c i1, is \c true.
837 void ScalarExprEmitter::EmitBinOpCheck(Value *Check, const BinOpInfo &Info) {
839 SmallVector<llvm::Constant *, 4> StaticData;
840 SmallVector<llvm::Value *, 2> DynamicData;
842 BinaryOperatorKind Opcode = Info.Opcode;
843 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
844 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
846 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
847 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
848 if (UO && UO->getOpcode() == UO_Minus) {
849 CheckName = "negate_overflow";
850 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
851 DynamicData.push_back(Info.RHS);
853 if (BinaryOperator::isShiftOp(Opcode)) {
854 // Shift LHS negative or too large, or RHS out of bounds.
855 CheckName = "shift_out_of_bounds";
856 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
857 StaticData.push_back(
858 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
859 StaticData.push_back(
860 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
861 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
862 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
863 CheckName = "divrem_overflow";
864 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
866 // Signed arithmetic overflow (+, -, *).
868 case BO_Add: CheckName = "add_overflow"; break;
869 case BO_Sub: CheckName = "sub_overflow"; break;
870 case BO_Mul: CheckName = "mul_overflow"; break;
871 default: llvm_unreachable("unexpected opcode for bin op check");
873 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
875 DynamicData.push_back(Info.LHS);
876 DynamicData.push_back(Info.RHS);
879 CGF.EmitCheck(Check, CheckName, StaticData, DynamicData,
880 CodeGenFunction::CRK_Recoverable);
883 //===----------------------------------------------------------------------===//
885 //===----------------------------------------------------------------------===//
887 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
888 CGF.ErrorUnsupported(E, "scalar expression");
889 if (E->getType()->isVoidType())
891 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
894 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
896 if (E->getNumSubExprs() == 2 ||
897 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
898 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
899 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
902 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
903 unsigned LHSElts = LTy->getNumElements();
905 if (E->getNumSubExprs() == 3) {
906 Mask = CGF.EmitScalarExpr(E->getExpr(2));
908 // Shuffle LHS & RHS into one input vector.
909 SmallVector<llvm::Constant*, 32> concat;
910 for (unsigned i = 0; i != LHSElts; ++i) {
911 concat.push_back(Builder.getInt32(2*i));
912 concat.push_back(Builder.getInt32(2*i+1));
915 Value* CV = llvm::ConstantVector::get(concat);
916 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
922 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
923 llvm::Constant* EltMask;
925 // Treat vec3 like vec4.
926 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
927 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
928 (1 << llvm::Log2_32(LHSElts+2))-1);
929 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
930 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
931 (1 << llvm::Log2_32(LHSElts+1))-1);
933 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
934 (1 << llvm::Log2_32(LHSElts))-1);
936 // Mask off the high bits of each shuffle index.
937 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
939 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
942 // mask = mask & maskbits
944 // n = extract mask i
946 // newv = insert newv, x, i
947 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
948 MTy->getNumElements());
949 Value* NewV = llvm::UndefValue::get(RTy);
950 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
951 Value *IIndx = Builder.getInt32(i);
952 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
953 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
955 // Handle vec3 special since the index will be off by one for the RHS.
956 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
957 Value *cmpIndx, *newIndx;
958 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
960 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
961 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
963 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
964 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
969 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
970 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
972 // Handle vec3 special since the index will be off by one for the RHS.
973 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
974 SmallVector<llvm::Constant*, 32> indices;
975 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
976 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
977 if (VTy->getNumElements() == 3 && Idx > 3)
979 indices.push_back(Builder.getInt32(Idx));
982 Value *SV = llvm::ConstantVector::get(indices);
983 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
985 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
987 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
989 CGF.EmitScalarExpr(E->getBase());
991 EmitLValue(E->getBase());
992 return Builder.getInt(Value);
995 // Emit debug info for aggregate now, if it was delayed to reduce
997 CGDebugInfo *DI = CGF.getDebugInfo();
999 CGF.CGM.getCodeGenOpts().getDebugInfo()
1000 == CodeGenOptions::LimitedDebugInfo) {
1001 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
1002 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
1003 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
1004 DI->getOrCreateRecordType(PTy->getPointeeType(),
1005 M->getParent()->getLocation());
1007 return EmitLoadOfLValue(E);
1010 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
1011 TestAndClearIgnoreResultAssign();
1013 // Emit subscript expressions in rvalue context's. For most cases, this just
1014 // loads the lvalue formed by the subscript expr. However, we have to be
1015 // careful, because the base of a vector subscript is occasionally an rvalue,
1016 // so we can't get it as an lvalue.
1017 if (!E->getBase()->getType()->isVectorType())
1018 return EmitLoadOfLValue(E);
1020 // Handle the vector case. The base must be a vector, the index must be an
1022 Value *Base = Visit(E->getBase());
1023 Value *Idx = Visit(E->getIdx());
1024 QualType IdxTy = E->getIdx()->getType();
1026 if (CGF.SanOpts->Bounds)
1027 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1029 bool IdxSigned = IdxTy->isSignedIntegerOrEnumerationType();
1030 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
1031 return Builder.CreateExtractElement(Base, Idx, "vecext");
1034 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
1035 unsigned Off, llvm::Type *I32Ty) {
1036 int MV = SVI->getMaskValue(Idx);
1038 return llvm::UndefValue::get(I32Ty);
1039 return llvm::ConstantInt::get(I32Ty, Off+MV);
1042 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1043 bool Ignore = TestAndClearIgnoreResultAssign();
1045 assert (Ignore == false && "init list ignored");
1046 unsigned NumInitElements = E->getNumInits();
1048 if (E->hadArrayRangeDesignator())
1049 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1051 llvm::VectorType *VType =
1052 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1055 if (NumInitElements == 0) {
1056 // C++11 value-initialization for the scalar.
1057 return EmitNullValue(E->getType());
1059 // We have a scalar in braces. Just use the first element.
1060 return Visit(E->getInit(0));
1063 unsigned ResElts = VType->getNumElements();
1065 // Loop over initializers collecting the Value for each, and remembering
1066 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1067 // us to fold the shuffle for the swizzle into the shuffle for the vector
1068 // initializer, since LLVM optimizers generally do not want to touch
1070 unsigned CurIdx = 0;
1071 bool VIsUndefShuffle = false;
1072 llvm::Value *V = llvm::UndefValue::get(VType);
1073 for (unsigned i = 0; i != NumInitElements; ++i) {
1074 Expr *IE = E->getInit(i);
1075 Value *Init = Visit(IE);
1076 SmallVector<llvm::Constant*, 16> Args;
1078 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
1080 // Handle scalar elements. If the scalar initializer is actually one
1081 // element of a different vector of the same width, use shuffle instead of
1084 if (isa<ExtVectorElementExpr>(IE)) {
1085 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1087 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1088 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1089 Value *LHS = 0, *RHS = 0;
1091 // insert into undef -> shuffle (src, undef)
1093 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1095 LHS = EI->getVectorOperand();
1097 VIsUndefShuffle = true;
1098 } else if (VIsUndefShuffle) {
1099 // insert into undefshuffle && size match -> shuffle (v, src)
1100 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1101 for (unsigned j = 0; j != CurIdx; ++j)
1102 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
1103 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
1104 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1106 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1107 RHS = EI->getVectorOperand();
1108 VIsUndefShuffle = false;
1110 if (!Args.empty()) {
1111 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1112 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1118 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1120 VIsUndefShuffle = false;
1125 unsigned InitElts = VVT->getNumElements();
1127 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1128 // input is the same width as the vector being constructed, generate an
1129 // optimized shuffle of the swizzle input into the result.
1130 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
1131 if (isa<ExtVectorElementExpr>(IE)) {
1132 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1133 Value *SVOp = SVI->getOperand(0);
1134 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
1136 if (OpTy->getNumElements() == ResElts) {
1137 for (unsigned j = 0; j != CurIdx; ++j) {
1138 // If the current vector initializer is a shuffle with undef, merge
1139 // this shuffle directly into it.
1140 if (VIsUndefShuffle) {
1141 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
1144 Args.push_back(Builder.getInt32(j));
1147 for (unsigned j = 0, je = InitElts; j != je; ++j)
1148 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
1149 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1151 if (VIsUndefShuffle)
1152 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1158 // Extend init to result vector length, and then shuffle its contribution
1159 // to the vector initializer into V.
1161 for (unsigned j = 0; j != InitElts; ++j)
1162 Args.push_back(Builder.getInt32(j));
1163 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1164 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1165 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
1169 for (unsigned j = 0; j != CurIdx; ++j)
1170 Args.push_back(Builder.getInt32(j));
1171 for (unsigned j = 0; j != InitElts; ++j)
1172 Args.push_back(Builder.getInt32(j+Offset));
1173 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1176 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1177 // merging subsequent shuffles into this one.
1180 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1181 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1182 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1186 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1187 // Emit remaining default initializers.
1188 llvm::Type *EltTy = VType->getElementType();
1190 // Emit remaining default initializers
1191 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
1192 Value *Idx = Builder.getInt32(CurIdx);
1193 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1194 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1199 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1200 const Expr *E = CE->getSubExpr();
1202 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
1205 if (isa<CXXThisExpr>(E)) {
1206 // We always assume that 'this' is never null.
1210 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
1211 // And that glvalue casts are never null.
1212 if (ICE->getValueKind() != VK_RValue)
1219 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1220 // have to handle a more broad range of conversions than explicit casts, as they
1221 // handle things like function to ptr-to-function decay etc.
1222 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1223 Expr *E = CE->getSubExpr();
1224 QualType DestTy = CE->getType();
1225 CastKind Kind = CE->getCastKind();
1227 if (!DestTy->isVoidType())
1228 TestAndClearIgnoreResultAssign();
1230 // Since almost all cast kinds apply to scalars, this switch doesn't have
1231 // a default case, so the compiler will warn on a missing case. The cases
1232 // are in the same order as in the CastKind enum.
1234 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1235 case CK_BuiltinFnToFnPtr:
1236 llvm_unreachable("builtin functions are handled elsewhere");
1238 case CK_LValueBitCast:
1239 case CK_ObjCObjectLValueCast: {
1240 Value *V = EmitLValue(E).getAddress();
1241 V = Builder.CreateBitCast(V,
1242 ConvertType(CGF.getContext().getPointerType(DestTy)));
1243 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
1246 case CK_CPointerToObjCPointerCast:
1247 case CK_BlockPointerToObjCPointerCast:
1248 case CK_AnyPointerToBlockPointerCast:
1250 Value *Src = Visit(const_cast<Expr*>(E));
1251 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1253 case CK_AtomicToNonAtomic:
1254 case CK_NonAtomicToAtomic:
1256 case CK_UserDefinedConversion:
1257 return Visit(const_cast<Expr*>(E));
1259 case CK_BaseToDerived: {
1260 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1261 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1263 llvm::Value *V = Visit(E);
1265 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
1266 // performed and the object is not of the derived type.
1267 if (CGF.SanitizePerformTypeCheck)
1268 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
1269 V, DestTy->getPointeeType());
1271 return CGF.GetAddressOfDerivedClass(V, DerivedClassDecl,
1272 CE->path_begin(), CE->path_end(),
1273 ShouldNullCheckClassCastValue(CE));
1275 case CK_UncheckedDerivedToBase:
1276 case CK_DerivedToBase: {
1277 const CXXRecordDecl *DerivedClassDecl =
1278 E->getType()->getPointeeCXXRecordDecl();
1279 assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
1281 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
1282 CE->path_begin(), CE->path_end(),
1283 ShouldNullCheckClassCastValue(CE));
1286 Value *V = Visit(const_cast<Expr*>(E));
1287 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1288 return CGF.EmitDynamicCast(V, DCE);
1291 case CK_ArrayToPointerDecay: {
1292 assert(E->getType()->isArrayType() &&
1293 "Array to pointer decay must have array source type!");
1295 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1297 // Note that VLA pointers are always decayed, so we don't need to do
1299 if (!E->getType()->isVariableArrayType()) {
1300 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1301 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1302 ->getElementType()) &&
1303 "Expected pointer to array");
1304 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1307 // Make sure the array decay ends up being the right type. This matters if
1308 // the array type was of an incomplete type.
1309 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
1311 case CK_FunctionToPointerDecay:
1312 return EmitLValue(E).getAddress();
1314 case CK_NullToPointer:
1315 if (MustVisitNullValue(E))
1318 return llvm::ConstantPointerNull::get(
1319 cast<llvm::PointerType>(ConvertType(DestTy)));
1321 case CK_NullToMemberPointer: {
1322 if (MustVisitNullValue(E))
1325 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1326 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1329 case CK_ReinterpretMemberPointer:
1330 case CK_BaseToDerivedMemberPointer:
1331 case CK_DerivedToBaseMemberPointer: {
1332 Value *Src = Visit(E);
1334 // Note that the AST doesn't distinguish between checked and
1335 // unchecked member pointer conversions, so we always have to
1336 // implement checked conversions here. This is inefficient when
1337 // actual control flow may be required in order to perform the
1338 // check, which it is for data member pointers (but not member
1339 // function pointers on Itanium and ARM).
1340 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1343 case CK_ARCProduceObject:
1344 return CGF.EmitARCRetainScalarExpr(E);
1345 case CK_ARCConsumeObject:
1346 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1347 case CK_ARCReclaimReturnedObject: {
1348 llvm::Value *value = Visit(E);
1349 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1350 return CGF.EmitObjCConsumeObject(E->getType(), value);
1352 case CK_ARCExtendBlockObject:
1353 return CGF.EmitARCExtendBlockObject(E);
1355 case CK_CopyAndAutoreleaseBlockObject:
1356 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
1358 case CK_FloatingRealToComplex:
1359 case CK_FloatingComplexCast:
1360 case CK_IntegralRealToComplex:
1361 case CK_IntegralComplexCast:
1362 case CK_IntegralComplexToFloatingComplex:
1363 case CK_FloatingComplexToIntegralComplex:
1364 case CK_ConstructorConversion:
1366 llvm_unreachable("scalar cast to non-scalar value");
1368 case CK_LValueToRValue:
1369 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1370 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1371 return Visit(const_cast<Expr*>(E));
1373 case CK_IntegralToPointer: {
1374 Value *Src = Visit(const_cast<Expr*>(E));
1376 // First, convert to the correct width so that we control the kind of
1378 llvm::Type *MiddleTy = CGF.IntPtrTy;
1379 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1380 llvm::Value* IntResult =
1381 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1383 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1385 case CK_PointerToIntegral:
1386 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1387 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1390 CGF.EmitIgnoredExpr(E);
1393 case CK_VectorSplat: {
1394 llvm::Type *DstTy = ConvertType(DestTy);
1395 Value *Elt = Visit(const_cast<Expr*>(E));
1396 Elt = EmitScalarConversion(Elt, E->getType(),
1397 DestTy->getAs<VectorType>()->getElementType());
1399 // Splat the element across to all elements
1400 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1401 return Builder.CreateVectorSplat(NumElements, Elt, "splat");;
1404 case CK_IntegralCast:
1405 case CK_IntegralToFloating:
1406 case CK_FloatingToIntegral:
1407 case CK_FloatingCast:
1408 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1409 case CK_IntegralToBoolean:
1410 return EmitIntToBoolConversion(Visit(E));
1411 case CK_PointerToBoolean:
1412 return EmitPointerToBoolConversion(Visit(E));
1413 case CK_FloatingToBoolean:
1414 return EmitFloatToBoolConversion(Visit(E));
1415 case CK_MemberPointerToBoolean: {
1416 llvm::Value *MemPtr = Visit(E);
1417 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1418 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1421 case CK_FloatingComplexToReal:
1422 case CK_IntegralComplexToReal:
1423 return CGF.EmitComplexExpr(E, false, true).first;
1425 case CK_FloatingComplexToBoolean:
1426 case CK_IntegralComplexToBoolean: {
1427 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1429 // TODO: kill this function off, inline appropriate case here
1430 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1433 case CK_ZeroToOCLEvent: {
1434 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non event type");
1435 return llvm::Constant::getNullValue(ConvertType(DestTy));
1440 llvm_unreachable("unknown scalar cast");
1443 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1444 CodeGenFunction::StmtExprEvaluation eval(CGF);
1445 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1449 //===----------------------------------------------------------------------===//
1451 //===----------------------------------------------------------------------===//
1453 llvm::Value *ScalarExprEmitter::
1454 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1456 llvm::Value *NextVal, bool IsInc) {
1457 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
1458 case LangOptions::SOB_Defined:
1459 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1460 case LangOptions::SOB_Undefined:
1461 if (!CGF.SanOpts->SignedIntegerOverflow)
1462 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1464 case LangOptions::SOB_Trapping:
1467 BinOp.RHS = NextVal;
1468 BinOp.Ty = E->getType();
1469 BinOp.Opcode = BO_Add;
1470 BinOp.FPContractable = false;
1472 return EmitOverflowCheckedBinOp(BinOp);
1474 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
1478 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1479 bool isInc, bool isPre) {
1481 QualType type = E->getSubExpr()->getType();
1482 llvm::PHINode *atomicPHI = 0;
1486 int amount = (isInc ? 1 : -1);
1488 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1489 type = atomicTy->getValueType();
1490 if (isInc && type->isBooleanType()) {
1491 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
1493 Builder.Insert(new llvm::StoreInst(True,
1494 LV.getAddress(), LV.isVolatileQualified(),
1495 LV.getAlignment().getQuantity(),
1496 llvm::SequentiallyConsistent));
1497 return Builder.getTrue();
1499 // For atomic bool increment, we just store true and return it for
1500 // preincrement, do an atomic swap with true for postincrement
1501 return Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
1502 LV.getAddress(), True, llvm::SequentiallyConsistent);
1504 // Special case for atomic increment / decrement on integers, emit
1505 // atomicrmw instructions. We skip this if we want to be doing overflow
1506 // checking, and fall into the slow path with the atomic cmpxchg loop.
1507 if (!type->isBooleanType() && type->isIntegerType() &&
1508 !(type->isUnsignedIntegerType() &&
1509 CGF.SanOpts->UnsignedIntegerOverflow) &&
1510 CGF.getLangOpts().getSignedOverflowBehavior() !=
1511 LangOptions::SOB_Trapping) {
1512 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
1513 llvm::AtomicRMWInst::Sub;
1514 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
1515 llvm::Instruction::Sub;
1516 llvm::Value *amt = CGF.EmitToMemory(
1517 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
1518 llvm::Value *old = Builder.CreateAtomicRMW(aop,
1519 LV.getAddress(), amt, llvm::SequentiallyConsistent);
1520 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
1522 value = EmitLoadOfLValue(LV);
1524 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
1525 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1526 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1527 value = CGF.EmitToMemory(value, type);
1528 Builder.CreateBr(opBB);
1529 Builder.SetInsertPoint(opBB);
1530 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1531 atomicPHI->addIncoming(value, startBB);
1534 value = EmitLoadOfLValue(LV);
1538 // Special case of integer increment that we have to check first: bool++.
1539 // Due to promotion rules, we get:
1540 // bool++ -> bool = bool + 1
1541 // -> bool = (int)bool + 1
1542 // -> bool = ((int)bool + 1 != 0)
1543 // An interesting aspect of this is that increment is always true.
1544 // Decrement does not have this property.
1545 if (isInc && type->isBooleanType()) {
1546 value = Builder.getTrue();
1548 // Most common case by far: integer increment.
1549 } else if (type->isIntegerType()) {
1551 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
1553 // Note that signed integer inc/dec with width less than int can't
1554 // overflow because of promotion rules; we're just eliding a few steps here.
1555 if (value->getType()->getPrimitiveSizeInBits() >=
1556 CGF.IntTy->getBitWidth() &&
1557 type->isSignedIntegerOrEnumerationType()) {
1558 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1559 } else if (value->getType()->getPrimitiveSizeInBits() >=
1560 CGF.IntTy->getBitWidth() && type->isUnsignedIntegerType() &&
1561 CGF.SanOpts->UnsignedIntegerOverflow) {
1564 BinOp.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
1565 BinOp.Ty = E->getType();
1566 BinOp.Opcode = isInc ? BO_Add : BO_Sub;
1567 BinOp.FPContractable = false;
1569 value = EmitOverflowCheckedBinOp(BinOp);
1571 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1573 // Next most common: pointer increment.
1574 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1575 QualType type = ptr->getPointeeType();
1577 // VLA types don't have constant size.
1578 if (const VariableArrayType *vla
1579 = CGF.getContext().getAsVariableArrayType(type)) {
1580 llvm::Value *numElts = CGF.getVLASize(vla).first;
1581 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
1582 if (CGF.getLangOpts().isSignedOverflowDefined())
1583 value = Builder.CreateGEP(value, numElts, "vla.inc");
1585 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1587 // Arithmetic on function pointers (!) is just +-1.
1588 } else if (type->isFunctionType()) {
1589 llvm::Value *amt = Builder.getInt32(amount);
1591 value = CGF.EmitCastToVoidPtr(value);
1592 if (CGF.getLangOpts().isSignedOverflowDefined())
1593 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1595 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1596 value = Builder.CreateBitCast(value, input->getType());
1598 // For everything else, we can just do a simple increment.
1600 llvm::Value *amt = Builder.getInt32(amount);
1601 if (CGF.getLangOpts().isSignedOverflowDefined())
1602 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1604 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1607 // Vector increment/decrement.
1608 } else if (type->isVectorType()) {
1609 if (type->hasIntegerRepresentation()) {
1610 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1612 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1614 value = Builder.CreateFAdd(
1616 llvm::ConstantFP::get(value->getType(), amount),
1617 isInc ? "inc" : "dec");
1621 } else if (type->isRealFloatingType()) {
1622 // Add the inc/dec to the real part.
1625 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1626 // Another special case: half FP increment should be done via float
1628 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1632 if (value->getType()->isFloatTy())
1633 amt = llvm::ConstantFP::get(VMContext,
1634 llvm::APFloat(static_cast<float>(amount)));
1635 else if (value->getType()->isDoubleTy())
1636 amt = llvm::ConstantFP::get(VMContext,
1637 llvm::APFloat(static_cast<double>(amount)));
1639 llvm::APFloat F(static_cast<float>(amount));
1641 F.convert(CGF.getTarget().getLongDoubleFormat(),
1642 llvm::APFloat::rmTowardZero, &ignored);
1643 amt = llvm::ConstantFP::get(VMContext, F);
1645 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1647 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType)
1649 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1652 // Objective-C pointer types.
1654 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1655 value = CGF.EmitCastToVoidPtr(value);
1657 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1658 if (!isInc) size = -size;
1659 llvm::Value *sizeValue =
1660 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1662 if (CGF.getLangOpts().isSignedOverflowDefined())
1663 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1665 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1666 value = Builder.CreateBitCast(value, input->getType());
1670 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1671 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1672 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1673 CGF.EmitToMemory(value, type), llvm::SequentiallyConsistent);
1674 atomicPHI->addIncoming(old, opBB);
1675 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1676 Builder.CreateCondBr(success, contBB, opBB);
1677 Builder.SetInsertPoint(contBB);
1678 return isPre ? value : input;
1681 // Store the updated result through the lvalue.
1682 if (LV.isBitField())
1683 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1685 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1687 // If this is a postinc, return the value read from memory, otherwise use the
1689 return isPre ? value : input;
1694 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1695 TestAndClearIgnoreResultAssign();
1696 // Emit unary minus with EmitSub so we handle overflow cases etc.
1698 BinOp.RHS = Visit(E->getSubExpr());
1700 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1701 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1703 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1704 BinOp.Ty = E->getType();
1705 BinOp.Opcode = BO_Sub;
1706 BinOp.FPContractable = false;
1708 return EmitSub(BinOp);
1711 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1712 TestAndClearIgnoreResultAssign();
1713 Value *Op = Visit(E->getSubExpr());
1714 return Builder.CreateNot(Op, "neg");
1717 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1718 // Perform vector logical not on comparison with zero vector.
1719 if (E->getType()->isExtVectorType()) {
1720 Value *Oper = Visit(E->getSubExpr());
1721 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1723 if (Oper->getType()->isFPOrFPVectorTy())
1724 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
1726 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1727 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1730 // Compare operand to zero.
1731 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1734 // TODO: Could dynamically modify easy computations here. For example, if
1735 // the operand is an icmp ne, turn into icmp eq.
1736 BoolVal = Builder.CreateNot(BoolVal, "lnot");
1738 // ZExt result to the expr type.
1739 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1742 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1743 // Try folding the offsetof to a constant.
1745 if (E->EvaluateAsInt(Value, CGF.getContext()))
1746 return Builder.getInt(Value);
1748 // Loop over the components of the offsetof to compute the value.
1749 unsigned n = E->getNumComponents();
1750 llvm::Type* ResultType = ConvertType(E->getType());
1751 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1752 QualType CurrentType = E->getTypeSourceInfo()->getType();
1753 for (unsigned i = 0; i != n; ++i) {
1754 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1755 llvm::Value *Offset = 0;
1756 switch (ON.getKind()) {
1757 case OffsetOfExpr::OffsetOfNode::Array: {
1758 // Compute the index
1759 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1760 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1761 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
1762 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1764 // Save the element type
1766 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1768 // Compute the element size
1769 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1770 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1772 // Multiply out to compute the result
1773 Offset = Builder.CreateMul(Idx, ElemSize);
1777 case OffsetOfExpr::OffsetOfNode::Field: {
1778 FieldDecl *MemberDecl = ON.getField();
1779 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1780 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1782 // Compute the index of the field in its parent.
1784 // FIXME: It would be nice if we didn't have to loop here!
1785 for (RecordDecl::field_iterator Field = RD->field_begin(),
1786 FieldEnd = RD->field_end();
1787 Field != FieldEnd; ++Field, ++i) {
1788 if (*Field == MemberDecl)
1791 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1793 // Compute the offset to the field
1794 int64_t OffsetInt = RL.getFieldOffset(i) /
1795 CGF.getContext().getCharWidth();
1796 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1798 // Save the element type.
1799 CurrentType = MemberDecl->getType();
1803 case OffsetOfExpr::OffsetOfNode::Identifier:
1804 llvm_unreachable("dependent __builtin_offsetof");
1806 case OffsetOfExpr::OffsetOfNode::Base: {
1807 if (ON.getBase()->isVirtual()) {
1808 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1812 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1813 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1815 // Save the element type.
1816 CurrentType = ON.getBase()->getType();
1818 // Compute the offset to the base.
1819 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1820 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1821 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1822 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
1826 Result = Builder.CreateAdd(Result, Offset);
1831 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1832 /// argument of the sizeof expression as an integer.
1834 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1835 const UnaryExprOrTypeTraitExpr *E) {
1836 QualType TypeToSize = E->getTypeOfArgument();
1837 if (E->getKind() == UETT_SizeOf) {
1838 if (const VariableArrayType *VAT =
1839 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1840 if (E->isArgumentType()) {
1841 // sizeof(type) - make sure to emit the VLA size.
1842 CGF.EmitVariablyModifiedType(TypeToSize);
1844 // C99 6.5.3.4p2: If the argument is an expression of type
1845 // VLA, it is evaluated.
1846 CGF.EmitIgnoredExpr(E->getArgumentExpr());
1850 llvm::Value *numElts;
1851 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1853 llvm::Value *size = numElts;
1855 // Scale the number of non-VLA elements by the non-VLA element size.
1856 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1857 if (!eltSize.isOne())
1858 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1864 // If this isn't sizeof(vla), the result must be constant; use the constant
1865 // folding logic so we don't have to duplicate it here.
1866 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
1869 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1870 Expr *Op = E->getSubExpr();
1871 if (Op->getType()->isAnyComplexType()) {
1872 // If it's an l-value, load through the appropriate subobject l-value.
1873 // Note that we have to ask E because Op might be an l-value that
1874 // this won't work for, e.g. an Obj-C property.
1876 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1878 // Otherwise, calculate and project.
1879 return CGF.EmitComplexExpr(Op, false, true).first;
1885 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1886 Expr *Op = E->getSubExpr();
1887 if (Op->getType()->isAnyComplexType()) {
1888 // If it's an l-value, load through the appropriate subobject l-value.
1889 // Note that we have to ask E because Op might be an l-value that
1890 // this won't work for, e.g. an Obj-C property.
1891 if (Op->isGLValue())
1892 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1894 // Otherwise, calculate and project.
1895 return CGF.EmitComplexExpr(Op, true, false).second;
1898 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1899 // effects are evaluated, but not the actual value.
1900 if (Op->isGLValue())
1903 CGF.EmitScalarExpr(Op, true);
1904 return llvm::Constant::getNullValue(ConvertType(E->getType()));
1907 //===----------------------------------------------------------------------===//
1909 //===----------------------------------------------------------------------===//
1911 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1912 TestAndClearIgnoreResultAssign();
1914 Result.LHS = Visit(E->getLHS());
1915 Result.RHS = Visit(E->getRHS());
1916 Result.Ty = E->getType();
1917 Result.Opcode = E->getOpcode();
1918 Result.FPContractable = E->isFPContractable();
1923 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1924 const CompoundAssignOperator *E,
1925 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1927 QualType LHSTy = E->getLHS()->getType();
1930 if (E->getComputationResultType()->isAnyComplexType()) {
1931 // This needs to go through the complex expression emitter, but it's a tad
1932 // complicated to do that... I'm leaving it out for now. (Note that we do
1933 // actually need the imaginary part of the RHS for multiplication and
1935 CGF.ErrorUnsupported(E, "complex compound assignment");
1936 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1940 // Emit the RHS first. __block variables need to have the rhs evaluated
1941 // first, plus this should improve codegen a little.
1942 OpInfo.RHS = Visit(E->getRHS());
1943 OpInfo.Ty = E->getComputationResultType();
1944 OpInfo.Opcode = E->getOpcode();
1945 OpInfo.FPContractable = false;
1947 // Load/convert the LHS.
1948 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
1950 llvm::PHINode *atomicPHI = 0;
1951 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
1952 QualType type = atomicTy->getValueType();
1953 if (!type->isBooleanType() && type->isIntegerType() &&
1954 !(type->isUnsignedIntegerType() &&
1955 CGF.SanOpts->UnsignedIntegerOverflow) &&
1956 CGF.getLangOpts().getSignedOverflowBehavior() !=
1957 LangOptions::SOB_Trapping) {
1958 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
1959 switch (OpInfo.Opcode) {
1960 // We don't have atomicrmw operands for *, %, /, <<, >>
1961 case BO_MulAssign: case BO_DivAssign:
1967 aop = llvm::AtomicRMWInst::Add;
1970 aop = llvm::AtomicRMWInst::Sub;
1973 aop = llvm::AtomicRMWInst::And;
1976 aop = llvm::AtomicRMWInst::Xor;
1979 aop = llvm::AtomicRMWInst::Or;
1982 llvm_unreachable("Invalid compound assignment type");
1984 if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
1985 llvm::Value *amt = CGF.EmitToMemory(EmitScalarConversion(OpInfo.RHS,
1986 E->getRHS()->getType(), LHSTy), LHSTy);
1987 Builder.CreateAtomicRMW(aop, LHSLV.getAddress(), amt,
1988 llvm::SequentiallyConsistent);
1992 // FIXME: For floating point types, we should be saving and restoring the
1993 // floating point environment in the loop.
1994 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1995 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1996 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
1997 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
1998 Builder.CreateBr(opBB);
1999 Builder.SetInsertPoint(opBB);
2000 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2001 atomicPHI->addIncoming(OpInfo.LHS, startBB);
2002 OpInfo.LHS = atomicPHI;
2005 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
2007 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
2008 E->getComputationLHSType());
2010 // Expand the binary operator.
2011 Result = (this->*Func)(OpInfo);
2013 // Convert the result back to the LHS type.
2014 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
2017 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2018 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
2019 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
2020 CGF.EmitToMemory(Result, LHSTy), llvm::SequentiallyConsistent);
2021 atomicPHI->addIncoming(old, opBB);
2022 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
2023 Builder.CreateCondBr(success, contBB, opBB);
2024 Builder.SetInsertPoint(contBB);
2028 // Store the result value into the LHS lvalue. Bit-fields are handled
2029 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2030 // 'An assignment expression has the value of the left operand after the
2032 if (LHSLV.isBitField())
2033 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
2035 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
2040 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2041 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2042 bool Ignore = TestAndClearIgnoreResultAssign();
2044 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2046 // If the result is clearly ignored, return now.
2050 // The result of an assignment in C is the assigned r-value.
2051 if (!CGF.getLangOpts().CPlusPlus)
2054 // If the lvalue is non-volatile, return the computed value of the assignment.
2055 if (!LHS.isVolatileQualified())
2058 // Otherwise, reload the value.
2059 return EmitLoadOfLValue(LHS);
2062 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
2063 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
2064 llvm::Value *Cond = 0;
2066 if (CGF.SanOpts->IntegerDivideByZero)
2067 Cond = Builder.CreateICmpNE(Ops.RHS, Zero);
2069 if (CGF.SanOpts->SignedIntegerOverflow &&
2070 Ops.Ty->hasSignedIntegerRepresentation()) {
2071 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2073 llvm::Value *IntMin =
2074 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
2075 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2077 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2078 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
2079 llvm::Value *Overflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2080 Cond = Cond ? Builder.CreateAnd(Cond, Overflow, "and") : Overflow;
2084 EmitBinOpCheck(Cond, Ops);
2087 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
2088 if ((CGF.SanOpts->IntegerDivideByZero ||
2089 CGF.SanOpts->SignedIntegerOverflow) &&
2090 Ops.Ty->isIntegerType()) {
2091 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2092 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
2093 } else if (CGF.SanOpts->FloatDivideByZero &&
2094 Ops.Ty->isRealFloatingType()) {
2095 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2096 EmitBinOpCheck(Builder.CreateFCmpUNE(Ops.RHS, Zero), Ops);
2099 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
2100 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
2101 if (CGF.getLangOpts().OpenCL) {
2102 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
2103 llvm::Type *ValTy = Val->getType();
2104 if (ValTy->isFloatTy() ||
2105 (isa<llvm::VectorType>(ValTy) &&
2106 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
2107 CGF.SetFPAccuracy(Val, 2.5);
2111 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
2112 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2114 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2117 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
2118 // Rem in C can't be a floating point type: C99 6.5.5p2.
2119 if (CGF.SanOpts->IntegerDivideByZero) {
2120 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2122 if (Ops.Ty->isIntegerType())
2123 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2126 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2127 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2129 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2132 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2136 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
2137 switch (Ops.Opcode) {
2141 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2142 llvm::Intrinsic::uadd_with_overflow;
2147 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2148 llvm::Intrinsic::usub_with_overflow;
2153 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2154 llvm::Intrinsic::umul_with_overflow;
2157 llvm_unreachable("Unsupported operation for overflow detection");
2163 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
2165 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
2167 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2168 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2169 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2171 // Handle overflow with llvm.trap if no custom handler has been specified.
2172 const std::string *handlerName =
2173 &CGF.getLangOpts().OverflowHandler;
2174 if (handlerName->empty()) {
2175 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
2176 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
2177 if (!isSigned || CGF.SanOpts->SignedIntegerOverflow)
2178 EmitBinOpCheck(Builder.CreateNot(overflow), Ops);
2180 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
2184 // Branch in case of overflow.
2185 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
2186 llvm::Function::iterator insertPt = initialBB;
2187 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
2188 llvm::next(insertPt));
2189 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
2191 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2193 // If an overflow handler is set, then we want to call it and then use its
2194 // result, if it returns.
2195 Builder.SetInsertPoint(overflowBB);
2197 // Get the overflow handler.
2198 llvm::Type *Int8Ty = CGF.Int8Ty;
2199 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
2200 llvm::FunctionType *handlerTy =
2201 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2202 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2204 // Sign extend the args to 64-bit, so that we can use the same handler for
2205 // all types of overflow.
2206 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2207 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2209 // Call the handler with the two arguments, the operation, and the size of
2211 llvm::Value *handlerArgs[] = {
2214 Builder.getInt8(OpID),
2215 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2217 llvm::Value *handlerResult =
2218 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
2220 // Truncate the result back to the desired size.
2221 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2222 Builder.CreateBr(continueBB);
2224 Builder.SetInsertPoint(continueBB);
2225 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
2226 phi->addIncoming(result, initialBB);
2227 phi->addIncoming(handlerResult, overflowBB);
2232 /// Emit pointer + index arithmetic.
2233 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2234 const BinOpInfo &op,
2235 bool isSubtraction) {
2236 // Must have binary (not unary) expr here. Unary pointer
2237 // increment/decrement doesn't use this path.
2238 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2240 Value *pointer = op.LHS;
2241 Expr *pointerOperand = expr->getLHS();
2242 Value *index = op.RHS;
2243 Expr *indexOperand = expr->getRHS();
2245 // In a subtraction, the LHS is always the pointer.
2246 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2247 std::swap(pointer, index);
2248 std::swap(pointerOperand, indexOperand);
2251 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2252 if (width != CGF.PointerWidthInBits) {
2253 // Zero-extend or sign-extend the pointer value according to
2254 // whether the index is signed or not.
2255 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2256 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2260 // If this is subtraction, negate the index.
2262 index = CGF.Builder.CreateNeg(index, "idx.neg");
2264 if (CGF.SanOpts->Bounds)
2265 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2266 /*Accessed*/ false);
2268 const PointerType *pointerType
2269 = pointerOperand->getType()->getAs<PointerType>();
2271 QualType objectType = pointerOperand->getType()
2272 ->castAs<ObjCObjectPointerType>()
2274 llvm::Value *objectSize
2275 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2277 index = CGF.Builder.CreateMul(index, objectSize);
2279 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2280 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2281 return CGF.Builder.CreateBitCast(result, pointer->getType());
2284 QualType elementType = pointerType->getPointeeType();
2285 if (const VariableArrayType *vla
2286 = CGF.getContext().getAsVariableArrayType(elementType)) {
2287 // The element count here is the total number of non-VLA elements.
2288 llvm::Value *numElements = CGF.getVLASize(vla).first;
2290 // Effectively, the multiply by the VLA size is part of the GEP.
2291 // GEP indexes are signed, and scaling an index isn't permitted to
2292 // signed-overflow, so we use the same semantics for our explicit
2293 // multiply. We suppress this if overflow is not undefined behavior.
2294 if (CGF.getLangOpts().isSignedOverflowDefined()) {
2295 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2296 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2298 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2299 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2304 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2305 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2307 if (elementType->isVoidType() || elementType->isFunctionType()) {
2308 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2309 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2310 return CGF.Builder.CreateBitCast(result, pointer->getType());
2313 if (CGF.getLangOpts().isSignedOverflowDefined())
2314 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2316 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
2319 // Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2320 // Addend. Use negMul and negAdd to negate the first operand of the Mul or
2321 // the add operand respectively. This allows fmuladd to represent a*b-c, or
2322 // c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2323 // efficient operations.
2324 static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2325 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2326 bool negMul, bool negAdd) {
2327 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
2329 Value *MulOp0 = MulOp->getOperand(0);
2330 Value *MulOp1 = MulOp->getOperand(1);
2334 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2336 } else if (negAdd) {
2339 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2344 Builder.CreateCall3(
2345 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2346 MulOp0, MulOp1, Addend);
2347 MulOp->eraseFromParent();
2352 // Check whether it would be legal to emit an fmuladd intrinsic call to
2353 // represent op and if so, build the fmuladd.
2355 // Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2356 // Does NOT check the type of the operation - it's assumed that this function
2357 // will be called from contexts where it's known that the type is contractable.
2358 static Value* tryEmitFMulAdd(const BinOpInfo &op,
2359 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2362 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2363 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2364 "Only fadd/fsub can be the root of an fmuladd.");
2366 // Check whether this op is marked as fusable.
2367 if (!op.FPContractable)
2370 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2371 // either disabled, or handled entirely by the LLVM backend).
2372 if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
2375 // We have a potentially fusable op. Look for a mul on one of the operands.
2376 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2377 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2378 assert(LHSBinOp->getNumUses() == 0 &&
2379 "Operations with multiple uses shouldn't be contracted.");
2380 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2382 } else if (llvm::BinaryOperator* RHSBinOp =
2383 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2384 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
2385 assert(RHSBinOp->getNumUses() == 0 &&
2386 "Operations with multiple uses shouldn't be contracted.");
2387 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2394 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2395 if (op.LHS->getType()->isPointerTy() ||
2396 op.RHS->getType()->isPointerTy())
2397 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2399 if (op.Ty->isSignedIntegerOrEnumerationType()) {
2400 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2401 case LangOptions::SOB_Defined:
2402 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2403 case LangOptions::SOB_Undefined:
2404 if (!CGF.SanOpts->SignedIntegerOverflow)
2405 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2407 case LangOptions::SOB_Trapping:
2408 return EmitOverflowCheckedBinOp(op);
2412 if (op.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
2413 return EmitOverflowCheckedBinOp(op);
2415 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2416 // Try to form an fmuladd.
2417 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2420 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
2423 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2426 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2427 // The LHS is always a pointer if either side is.
2428 if (!op.LHS->getType()->isPointerTy()) {
2429 if (op.Ty->isSignedIntegerOrEnumerationType()) {
2430 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
2431 case LangOptions::SOB_Defined:
2432 return Builder.CreateSub(op.LHS, op.RHS, "sub");
2433 case LangOptions::SOB_Undefined:
2434 if (!CGF.SanOpts->SignedIntegerOverflow)
2435 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2437 case LangOptions::SOB_Trapping:
2438 return EmitOverflowCheckedBinOp(op);
2442 if (op.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
2443 return EmitOverflowCheckedBinOp(op);
2445 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2446 // Try to form an fmuladd.
2447 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2449 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
2452 return Builder.CreateSub(op.LHS, op.RHS, "sub");
2455 // If the RHS is not a pointer, then we have normal pointer
2457 if (!op.RHS->getType()->isPointerTy())
2458 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
2460 // Otherwise, this is a pointer subtraction.
2462 // Do the raw subtraction part.
2464 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2466 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2467 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2469 // Okay, figure out the element size.
2470 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2471 QualType elementType = expr->getLHS()->getType()->getPointeeType();
2473 llvm::Value *divisor = 0;
2475 // For a variable-length array, this is going to be non-constant.
2476 if (const VariableArrayType *vla
2477 = CGF.getContext().getAsVariableArrayType(elementType)) {
2478 llvm::Value *numElements;
2479 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2481 divisor = numElements;
2483 // Scale the number of non-VLA elements by the non-VLA element size.
2484 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2485 if (!eltSize.isOne())
2486 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2488 // For everything elese, we can just compute it, safe in the
2489 // assumption that Sema won't let anything through that we can't
2490 // safely compute the size of.
2492 CharUnits elementSize;
2493 // Handle GCC extension for pointer arithmetic on void* and
2494 // function pointer types.
2495 if (elementType->isVoidType() || elementType->isFunctionType())
2496 elementSize = CharUnits::One();
2498 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2500 // Don't even emit the divide for element size of 1.
2501 if (elementSize.isOne())
2504 divisor = CGF.CGM.getSize(elementSize);
2507 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2508 // pointer difference in C is only defined in the case where both operands
2509 // are pointing to elements of an array.
2510 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
2513 Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
2514 llvm::IntegerType *Ty;
2515 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2516 Ty = cast<llvm::IntegerType>(VT->getElementType());
2518 Ty = cast<llvm::IntegerType>(LHS->getType());
2519 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
2522 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2523 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2524 // RHS to the same size as the LHS.
2525 Value *RHS = Ops.RHS;
2526 if (Ops.LHS->getType() != RHS->getType())
2527 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2529 if (CGF.SanOpts->Shift && !CGF.getLangOpts().OpenCL &&
2530 isa<llvm::IntegerType>(Ops.LHS->getType())) {
2531 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, RHS);
2532 llvm::Value *Valid = Builder.CreateICmpULE(RHS, WidthMinusOne);
2534 if (Ops.Ty->hasSignedIntegerRepresentation()) {
2535 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
2536 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2537 llvm::BasicBlock *CheckBitsShifted = CGF.createBasicBlock("check");
2538 Builder.CreateCondBr(Valid, CheckBitsShifted, Cont);
2540 // Check whether we are shifting any non-zero bits off the top of the
2542 CGF.EmitBlock(CheckBitsShifted);
2543 llvm::Value *BitsShiftedOff =
2544 Builder.CreateLShr(Ops.LHS,
2545 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2546 /*NUW*/true, /*NSW*/true),
2548 if (CGF.getLangOpts().CPlusPlus) {
2549 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2550 // Under C++11's rules, shifting a 1 bit into the sign bit is
2551 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2552 // define signed left shifts, so we use the C99 and C++11 rules there).
2553 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2554 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2556 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
2557 llvm::Value *SecondCheck = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
2558 CGF.EmitBlock(Cont);
2559 llvm::PHINode *P = Builder.CreatePHI(Valid->getType(), 2);
2560 P->addIncoming(Valid, Orig);
2561 P->addIncoming(SecondCheck, CheckBitsShifted);
2565 EmitBinOpCheck(Valid, Ops);
2567 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2568 if (CGF.getLangOpts().OpenCL)
2569 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
2571 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2574 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2575 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2576 // RHS to the same size as the LHS.
2577 Value *RHS = Ops.RHS;
2578 if (Ops.LHS->getType() != RHS->getType())
2579 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2581 if (CGF.SanOpts->Shift && !CGF.getLangOpts().OpenCL &&
2582 isa<llvm::IntegerType>(Ops.LHS->getType()))
2583 EmitBinOpCheck(Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS)), Ops);
2585 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2586 if (CGF.getLangOpts().OpenCL)
2587 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
2589 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2590 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2591 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2594 enum IntrinsicType { VCMPEQ, VCMPGT };
2595 // return corresponding comparison intrinsic for given vector type
2596 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2597 BuiltinType::Kind ElemKind) {
2599 default: llvm_unreachable("unexpected element type");
2600 case BuiltinType::Char_U:
2601 case BuiltinType::UChar:
2602 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2603 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2604 case BuiltinType::Char_S:
2605 case BuiltinType::SChar:
2606 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2607 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2608 case BuiltinType::UShort:
2609 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2610 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2611 case BuiltinType::Short:
2612 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2613 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2614 case BuiltinType::UInt:
2615 case BuiltinType::ULong:
2616 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2617 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2618 case BuiltinType::Int:
2619 case BuiltinType::Long:
2620 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2621 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2622 case BuiltinType::Float:
2623 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2624 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2628 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2629 unsigned SICmpOpc, unsigned FCmpOpc) {
2630 TestAndClearIgnoreResultAssign();
2632 QualType LHSTy = E->getLHS()->getType();
2633 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2634 assert(E->getOpcode() == BO_EQ ||
2635 E->getOpcode() == BO_NE);
2636 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2637 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2638 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2639 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2640 } else if (!LHSTy->isAnyComplexType()) {
2641 Value *LHS = Visit(E->getLHS());
2642 Value *RHS = Visit(E->getRHS());
2644 // If AltiVec, the comparison results in a numeric type, so we use
2645 // intrinsics comparing vectors and giving 0 or 1 as a result
2646 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2647 // constants for mapping CR6 register bits to predicate result
2648 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2650 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2652 // in several cases vector arguments order will be reversed
2653 Value *FirstVecArg = LHS,
2654 *SecondVecArg = RHS;
2656 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2657 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2658 BuiltinType::Kind ElementKind = BTy->getKind();
2660 switch(E->getOpcode()) {
2661 default: llvm_unreachable("is not a comparison operation");
2664 ID = GetIntrinsic(VCMPEQ, ElementKind);
2668 ID = GetIntrinsic(VCMPEQ, ElementKind);
2672 ID = GetIntrinsic(VCMPGT, ElementKind);
2673 std::swap(FirstVecArg, SecondVecArg);
2677 ID = GetIntrinsic(VCMPGT, ElementKind);
2680 if (ElementKind == BuiltinType::Float) {
2682 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2683 std::swap(FirstVecArg, SecondVecArg);
2687 ID = GetIntrinsic(VCMPGT, ElementKind);
2691 if (ElementKind == BuiltinType::Float) {
2693 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2697 ID = GetIntrinsic(VCMPGT, ElementKind);
2698 std::swap(FirstVecArg, SecondVecArg);
2703 Value *CR6Param = Builder.getInt32(CR6);
2704 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2705 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2706 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2709 if (LHS->getType()->isFPOrFPVectorTy()) {
2710 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2712 } else if (LHSTy->hasSignedIntegerRepresentation()) {
2713 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2716 // Unsigned integers and pointers.
2717 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2721 // If this is a vector comparison, sign extend the result to the appropriate
2722 // vector integer type and return it (don't convert to bool).
2723 if (LHSTy->isVectorType())
2724 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2727 // Complex Comparison: can only be an equality comparison.
2728 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2729 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
2731 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
2733 Value *ResultR, *ResultI;
2734 if (CETy->isRealFloatingType()) {
2735 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2736 LHS.first, RHS.first, "cmp.r");
2737 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2738 LHS.second, RHS.second, "cmp.i");
2740 // Complex comparisons can only be equality comparisons. As such, signed
2741 // and unsigned opcodes are the same.
2742 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2743 LHS.first, RHS.first, "cmp.r");
2744 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2745 LHS.second, RHS.second, "cmp.i");
2748 if (E->getOpcode() == BO_EQ) {
2749 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2751 assert(E->getOpcode() == BO_NE &&
2752 "Complex comparison other than == or != ?");
2753 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2757 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2760 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2761 bool Ignore = TestAndClearIgnoreResultAssign();
2766 switch (E->getLHS()->getType().getObjCLifetime()) {
2767 case Qualifiers::OCL_Strong:
2768 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2771 case Qualifiers::OCL_Autoreleasing:
2772 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2775 case Qualifiers::OCL_Weak:
2776 RHS = Visit(E->getRHS());
2777 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2778 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2781 // No reason to do any of these differently.
2782 case Qualifiers::OCL_None:
2783 case Qualifiers::OCL_ExplicitNone:
2784 // __block variables need to have the rhs evaluated first, plus
2785 // this should improve codegen just a little.
2786 RHS = Visit(E->getRHS());
2787 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
2789 // Store the value into the LHS. Bit-fields are handled specially
2790 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2791 // 'An assignment expression has the value of the left operand after
2792 // the assignment...'.
2793 if (LHS.isBitField())
2794 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
2796 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
2799 // If the result is clearly ignored, return now.
2803 // The result of an assignment in C is the assigned r-value.
2804 if (!CGF.getLangOpts().CPlusPlus)
2807 // If the lvalue is non-volatile, return the computed value of the assignment.
2808 if (!LHS.isVolatileQualified())
2811 // Otherwise, reload the value.
2812 return EmitLoadOfLValue(LHS);
2815 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2816 // Perform vector logical and on comparisons with zero vectors.
2817 if (E->getType()->isVectorType()) {
2818 Value *LHS = Visit(E->getLHS());
2819 Value *RHS = Visit(E->getRHS());
2820 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2821 if (LHS->getType()->isFPOrFPVectorTy()) {
2822 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
2823 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
2825 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2826 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2828 Value *And = Builder.CreateAnd(LHS, RHS);
2829 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
2832 llvm::Type *ResTy = ConvertType(E->getType());
2834 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2835 // If we have 1 && X, just emit X without inserting the control flow.
2837 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2838 if (LHSCondVal) { // If we have 1 && X, just emit X.
2839 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2840 // ZExt result to int or bool.
2841 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
2844 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
2845 if (!CGF.ContainsLabel(E->getRHS()))
2846 return llvm::Constant::getNullValue(ResTy);
2849 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2850 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
2852 CodeGenFunction::ConditionalEvaluation eval(CGF);
2854 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2855 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2857 // Any edges into the ContBlock are now from an (indeterminate number of)
2858 // edges from this first condition. All of these values will be false. Start
2859 // setting up the PHI node in the Cont Block for this.
2860 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2862 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2864 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
2867 CGF.EmitBlock(RHSBlock);
2868 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2871 // Reaquire the RHS block, as there may be subblocks inserted.
2872 RHSBlock = Builder.GetInsertBlock();
2874 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2875 // into the phi node for the edge with the value of RHSCond.
2876 if (CGF.getDebugInfo())
2877 // There is no need to emit line number for unconditional branch.
2878 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
2879 CGF.EmitBlock(ContBlock);
2880 PN->addIncoming(RHSCond, RHSBlock);
2882 // ZExt result to int.
2883 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
2886 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
2887 // Perform vector logical or on comparisons with zero vectors.
2888 if (E->getType()->isVectorType()) {
2889 Value *LHS = Visit(E->getLHS());
2890 Value *RHS = Visit(E->getRHS());
2891 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2892 if (LHS->getType()->isFPOrFPVectorTy()) {
2893 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
2894 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
2896 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2897 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2899 Value *Or = Builder.CreateOr(LHS, RHS);
2900 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
2903 llvm::Type *ResTy = ConvertType(E->getType());
2905 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2906 // If we have 0 || X, just emit X without inserting the control flow.
2908 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2909 if (!LHSCondVal) { // If we have 0 || X, just emit X.
2910 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2911 // ZExt result to int or bool.
2912 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
2915 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
2916 if (!CGF.ContainsLabel(E->getRHS()))
2917 return llvm::ConstantInt::get(ResTy, 1);
2920 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2921 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
2923 CodeGenFunction::ConditionalEvaluation eval(CGF);
2925 // Branch on the LHS first. If it is true, go to the success (cont) block.
2926 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2928 // Any edges into the ContBlock are now from an (indeterminate number of)
2929 // edges from this first condition. All of these values will be true. Start
2930 // setting up the PHI node in the Cont Block for this.
2931 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2933 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2935 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
2939 // Emit the RHS condition as a bool value.
2940 CGF.EmitBlock(RHSBlock);
2941 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2945 // Reaquire the RHS block, as there may be subblocks inserted.
2946 RHSBlock = Builder.GetInsertBlock();
2948 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2949 // into the phi node for the edge with the value of RHSCond.
2950 CGF.EmitBlock(ContBlock);
2951 PN->addIncoming(RHSCond, RHSBlock);
2953 // ZExt result to int.
2954 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
2957 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2958 CGF.EmitIgnoredExpr(E->getLHS());
2959 CGF.EnsureInsertPoint();
2960 return Visit(E->getRHS());
2963 //===----------------------------------------------------------------------===//
2965 //===----------------------------------------------------------------------===//
2967 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2968 /// expression is cheap enough and side-effect-free enough to evaluate
2969 /// unconditionally instead of conditionally. This is used to convert control
2970 /// flow into selects in some cases.
2971 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2972 CodeGenFunction &CGF) {
2973 E = E->IgnoreParens();
2975 // Anything that is an integer or floating point constant is fine.
2976 if (E->isConstantInitializer(CGF.getContext(), false))
2979 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2980 // X and Y are local variables.
2981 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2982 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2983 if (VD->hasLocalStorage() && !(CGF.getContext()
2984 .getCanonicalType(VD->getType())
2985 .isVolatileQualified()))
2992 Value *ScalarExprEmitter::
2993 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
2994 TestAndClearIgnoreResultAssign();
2996 // Bind the common expression if necessary.
2997 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2999 Expr *condExpr = E->getCond();
3000 Expr *lhsExpr = E->getTrueExpr();
3001 Expr *rhsExpr = E->getFalseExpr();
3003 // If the condition constant folds and can be elided, try to avoid emitting
3004 // the condition and the dead arm.
3006 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
3007 Expr *live = lhsExpr, *dead = rhsExpr;
3008 if (!CondExprBool) std::swap(live, dead);
3010 // If the dead side doesn't have labels we need, just emit the Live part.
3011 if (!CGF.ContainsLabel(dead)) {
3012 Value *Result = Visit(live);
3014 // If the live part is a throw expression, it acts like it has a void
3015 // type, so evaluating it returns a null Value*. However, a conditional
3016 // with non-void type must return a non-null Value*.
3017 if (!Result && !E->getType()->isVoidType())
3018 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
3024 // OpenCL: If the condition is a vector, we can treat this condition like
3025 // the select function.
3026 if (CGF.getLangOpts().OpenCL
3027 && condExpr->getType()->isVectorType()) {
3028 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3029 llvm::Value *LHS = Visit(lhsExpr);
3030 llvm::Value *RHS = Visit(rhsExpr);
3032 llvm::Type *condType = ConvertType(condExpr->getType());
3033 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
3035 unsigned numElem = vecTy->getNumElements();
3036 llvm::Type *elemType = vecTy->getElementType();
3038 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
3039 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
3040 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
3041 llvm::VectorType::get(elemType,
3044 llvm::Value *tmp2 = Builder.CreateNot(tmp);
3046 // Cast float to int to perform ANDs if necessary.
3047 llvm::Value *RHSTmp = RHS;
3048 llvm::Value *LHSTmp = LHS;
3049 bool wasCast = false;
3050 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
3051 if (rhsVTy->getElementType()->isFloatingPointTy()) {
3052 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
3053 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
3057 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
3058 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
3059 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
3061 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3066 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3067 // select instead of as control flow. We can only do this if it is cheap and
3068 // safe to evaluate the LHS and RHS unconditionally.
3069 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
3070 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
3071 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3072 llvm::Value *LHS = Visit(lhsExpr);
3073 llvm::Value *RHS = Visit(rhsExpr);
3075 // If the conditional has void type, make sure we return a null Value*.
3076 assert(!RHS && "LHS and RHS types must match");
3079 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3082 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3083 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
3084 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
3086 CodeGenFunction::ConditionalEvaluation eval(CGF);
3087 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
3089 CGF.EmitBlock(LHSBlock);
3091 Value *LHS = Visit(lhsExpr);
3094 LHSBlock = Builder.GetInsertBlock();
3095 Builder.CreateBr(ContBlock);
3097 CGF.EmitBlock(RHSBlock);
3099 Value *RHS = Visit(rhsExpr);
3102 RHSBlock = Builder.GetInsertBlock();
3103 CGF.EmitBlock(ContBlock);
3105 // If the LHS or RHS is a throw expression, it will be legitimately null.
3111 // Create a PHI node for the real part.
3112 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
3113 PN->addIncoming(LHS, LHSBlock);
3114 PN->addIncoming(RHS, RHSBlock);
3118 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
3119 return Visit(E->getChosenSubExpr(CGF.getContext()));
3122 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
3123 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
3124 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
3126 // If EmitVAArg fails, we fall back to the LLVM instruction.
3128 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
3130 // FIXME Volatility.
3131 return Builder.CreateLoad(ArgPtr);
3134 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3135 return CGF.EmitBlockLiteral(block);
3138 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3139 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
3140 llvm::Type *DstTy = ConvertType(E->getType());
3142 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
3143 // a shuffle vector instead of a bitcast.
3144 llvm::Type *SrcTy = Src->getType();
3145 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
3146 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
3147 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
3148 if ((numElementsDst == 3 && numElementsSrc == 4)
3149 || (numElementsDst == 4 && numElementsSrc == 3)) {
3152 // In the case of going from int4->float3, a bitcast is needed before
3154 llvm::Type *srcElemTy =
3155 cast<llvm::VectorType>(SrcTy)->getElementType();
3156 llvm::Type *dstElemTy =
3157 cast<llvm::VectorType>(DstTy)->getElementType();
3159 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
3160 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
3161 // Create a float type of the same size as the source or destination.
3162 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
3165 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
3168 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
3170 SmallVector<llvm::Constant*, 3> Args;
3171 Args.push_back(Builder.getInt32(0));
3172 Args.push_back(Builder.getInt32(1));
3173 Args.push_back(Builder.getInt32(2));
3175 if (numElementsDst == 4)
3176 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
3178 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
3180 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3184 return Builder.CreateBitCast(Src, DstTy, "astype");
3187 Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3188 return CGF.EmitAtomicExpr(E).getScalarVal();
3191 //===----------------------------------------------------------------------===//
3192 // Entry Point into this File
3193 //===----------------------------------------------------------------------===//
3195 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
3196 /// type, ignoring the result.
3197 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
3198 assert(E && hasScalarEvaluationKind(E->getType()) &&
3199 "Invalid scalar expression to emit");
3201 if (isa<CXXDefaultArgExpr>(E))
3203 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
3204 .Visit(const_cast<Expr*>(E));
3205 if (isa<CXXDefaultArgExpr>(E))
3210 /// EmitScalarConversion - Emit a conversion from the specified type to the
3211 /// specified destination type, both of which are LLVM scalar types.
3212 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3214 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
3215 "Invalid scalar expression to emit");
3216 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3219 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
3220 /// type to the specified destination type, where the destination type is an
3221 /// LLVM scalar type.
3222 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3225 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
3226 "Invalid complex -> scalar conversion");
3227 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3232 llvm::Value *CodeGenFunction::
3233 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3234 bool isInc, bool isPre) {
3235 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3238 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3240 // object->isa or (*object).isa
3241 // Generate code as for: *(Class*)object
3242 // build Class* type
3243 llvm::Type *ClassPtrTy = ConvertType(E->getType());
3245 Expr *BaseExpr = E->getBase();
3246 if (BaseExpr->isRValue()) {
3247 V = CreateMemTemp(E->getType(), "resval");
3248 llvm::Value *Src = EmitScalarExpr(BaseExpr);
3249 Builder.CreateStore(Src, V);
3250 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
3251 MakeNaturalAlignAddrLValue(V, E->getType()));
3254 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3256 V = EmitLValue(BaseExpr).getAddress();
3259 // build Class* type
3260 ClassPtrTy = ClassPtrTy->getPointerTo();
3261 V = Builder.CreateBitCast(V, ClassPtrTy);
3262 return MakeNaturalAlignAddrLValue(V, E->getType());
3266 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
3267 const CompoundAssignOperator *E) {
3268 ScalarExprEmitter Scalar(*this);
3270 switch (E->getOpcode()) {
3271 #define COMPOUND_OP(Op) \
3272 case BO_##Op##Assign: \
3273 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
3309 llvm_unreachable("Not valid compound assignment operators");
3312 llvm_unreachable("Unhandled compound assignment operator");