1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "CodeGenFunction.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenModule.h"
19 #include "CGDebugInfo.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/GlobalVariable.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Module.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Target/TargetData.h"
34 using namespace clang;
35 using namespace CodeGen;
38 //===----------------------------------------------------------------------===//
39 // Scalar Expression Emitter
40 //===----------------------------------------------------------------------===//
46 QualType Ty; // Computation Type.
47 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
48 const Expr *E; // Entire expr, for error unsupported. May not be binop.
51 static bool MustVisitNullValue(const Expr *E) {
52 // If a null pointer expression's type is the C++0x nullptr_t, then
53 // it's not necessarily a simple constant and it must be evaluated
54 // for its potential side effects.
55 return E->getType()->isNullPtrType();
58 class ScalarExprEmitter
59 : public StmtVisitor<ScalarExprEmitter, Value*> {
62 bool IgnoreResultAssign;
63 llvm::LLVMContext &VMContext;
66 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
67 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
68 VMContext(cgf.getLLVMContext()) {
71 //===--------------------------------------------------------------------===//
73 //===--------------------------------------------------------------------===//
75 bool TestAndClearIgnoreResultAssign() {
76 bool I = IgnoreResultAssign;
77 IgnoreResultAssign = false;
81 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
82 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
83 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
85 Value *EmitLoadOfLValue(LValue LV) {
86 return CGF.EmitLoadOfLValue(LV).getScalarVal();
89 /// EmitLoadOfLValue - Given an expression with complex type that represents a
90 /// value l-value, this method emits the address of the l-value, then loads
91 /// and returns the result.
92 Value *EmitLoadOfLValue(const Expr *E) {
93 return EmitLoadOfLValue(EmitCheckedLValue(E));
96 /// EmitConversionToBool - Convert the specified expression value to a
97 /// boolean (i1) truth value. This is equivalent to "Val != 0".
98 Value *EmitConversionToBool(Value *Src, QualType DstTy);
100 /// EmitScalarConversion - Emit a conversion from the specified type to the
101 /// specified destination type, both of which are LLVM scalar types.
102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
104 /// EmitComplexToScalarConversion - Emit a conversion from the specified
105 /// complex type to the specified destination type, where the destination type
106 /// is an LLVM scalar type.
107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
108 QualType SrcTy, QualType DstTy);
110 /// EmitNullValue - Emit a value that corresponds to null for the given type.
111 Value *EmitNullValue(QualType Ty);
113 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
114 Value *EmitFloatToBoolConversion(Value *V) {
115 // Compare against 0.0 for fp scalars.
116 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
117 return Builder.CreateFCmpUNE(V, Zero, "tobool");
120 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
121 Value *EmitPointerToBoolConversion(Value *V) {
122 Value *Zero = llvm::ConstantPointerNull::get(
123 cast<llvm::PointerType>(V->getType()));
124 return Builder.CreateICmpNE(V, Zero, "tobool");
127 Value *EmitIntToBoolConversion(Value *V) {
128 // Because of the type rules of C, we often end up computing a
129 // logical value, then zero extending it to int, then wanting it
130 // as a logical value again. Optimize this common case.
131 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
132 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
133 Value *Result = ZI->getOperand(0);
134 // If there aren't any more uses, zap the instruction to save space.
135 // Note that there can be more uses, for example if this
136 // is the result of an assignment.
138 ZI->eraseFromParent();
143 return Builder.CreateIsNotNull(V, "tobool");
146 //===--------------------------------------------------------------------===//
148 //===--------------------------------------------------------------------===//
150 Value *Visit(Expr *E) {
151 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
154 Value *VisitStmt(Stmt *S) {
155 S->dump(CGF.getContext().getSourceManager());
156 assert(0 && "Stmt can't have complex result type!");
159 Value *VisitExpr(Expr *S);
161 Value *VisitParenExpr(ParenExpr *PE) {
162 return Visit(PE->getSubExpr());
164 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
165 return Visit(E->getReplacement());
167 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
168 return Visit(GE->getResultExpr());
172 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
173 return Builder.getInt(E->getValue());
175 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
176 return llvm::ConstantFP::get(VMContext, E->getValue());
178 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
179 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
181 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
182 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
184 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
185 return EmitNullValue(E->getType());
187 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
188 return EmitNullValue(E->getType());
190 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
191 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
192 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
193 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
194 return Builder.CreateBitCast(V, ConvertType(E->getType()));
197 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
198 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
201 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
203 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
205 // Otherwise, assume the mapping is the scalar directly.
206 return CGF.getOpaqueRValueMapping(E).getScalarVal();
210 Value *VisitDeclRefExpr(DeclRefExpr *E) {
211 Expr::EvalResult Result;
212 if (!E->Evaluate(Result, CGF.getContext()))
213 return EmitLoadOfLValue(E);
215 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
218 if (Result.Val.isInt())
219 C = Builder.getInt(Result.Val.getInt());
220 else if (Result.Val.isFloat())
221 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
223 return EmitLoadOfLValue(E);
225 // Make sure we emit a debug reference to the global variable.
226 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
227 if (!CGF.getContext().DeclMustBeEmitted(VD))
228 CGF.EmitDeclRefExprDbgValue(E, C);
229 } else if (isa<EnumConstantDecl>(E->getDecl())) {
230 CGF.EmitDeclRefExprDbgValue(E, C);
235 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
236 return CGF.EmitObjCSelectorExpr(E);
238 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
239 return CGF.EmitObjCProtocolExpr(E);
241 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
242 return EmitLoadOfLValue(E);
244 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
245 assert(E->getObjectKind() == OK_Ordinary &&
246 "reached property reference without lvalue-to-rvalue");
247 return EmitLoadOfLValue(E);
249 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
250 if (E->getMethodDecl() &&
251 E->getMethodDecl()->getResultType()->isReferenceType())
252 return EmitLoadOfLValue(E);
253 return CGF.EmitObjCMessageExpr(E).getScalarVal();
256 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
257 LValue LV = CGF.EmitObjCIsaExpr(E);
258 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
262 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
263 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
264 Value *VisitMemberExpr(MemberExpr *E);
265 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
266 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
267 return EmitLoadOfLValue(E);
270 Value *VisitInitListExpr(InitListExpr *E);
272 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
273 return CGF.CGM.EmitNullConstant(E->getType());
275 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
276 if (E->getType()->isVariablyModifiedType())
277 CGF.EmitVariablyModifiedType(E->getType());
278 return VisitCastExpr(E);
280 Value *VisitCastExpr(CastExpr *E);
282 Value *VisitCallExpr(const CallExpr *E) {
283 if (E->getCallReturnType()->isReferenceType())
284 return EmitLoadOfLValue(E);
286 return CGF.EmitCallExpr(E).getScalarVal();
289 Value *VisitStmtExpr(const StmtExpr *E);
291 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
294 Value *VisitUnaryPostDec(const UnaryOperator *E) {
295 LValue LV = EmitLValue(E->getSubExpr());
296 return EmitScalarPrePostIncDec(E, LV, false, false);
298 Value *VisitUnaryPostInc(const UnaryOperator *E) {
299 LValue LV = EmitLValue(E->getSubExpr());
300 return EmitScalarPrePostIncDec(E, LV, true, false);
302 Value *VisitUnaryPreDec(const UnaryOperator *E) {
303 LValue LV = EmitLValue(E->getSubExpr());
304 return EmitScalarPrePostIncDec(E, LV, false, true);
306 Value *VisitUnaryPreInc(const UnaryOperator *E) {
307 LValue LV = EmitLValue(E->getSubExpr());
308 return EmitScalarPrePostIncDec(E, LV, true, true);
311 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
313 llvm::Value *NextVal,
316 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
317 bool isInc, bool isPre);
320 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
321 if (isa<MemberPointerType>(E->getType())) // never sugared
322 return CGF.CGM.getMemberPointerConstant(E);
324 return EmitLValue(E->getSubExpr()).getAddress();
326 Value *VisitUnaryDeref(const UnaryOperator *E) {
327 if (E->getType()->isVoidType())
328 return Visit(E->getSubExpr()); // the actual value should be unused
329 return EmitLoadOfLValue(E);
331 Value *VisitUnaryPlus(const UnaryOperator *E) {
332 // This differs from gcc, though, most likely due to a bug in gcc.
333 TestAndClearIgnoreResultAssign();
334 return Visit(E->getSubExpr());
336 Value *VisitUnaryMinus (const UnaryOperator *E);
337 Value *VisitUnaryNot (const UnaryOperator *E);
338 Value *VisitUnaryLNot (const UnaryOperator *E);
339 Value *VisitUnaryReal (const UnaryOperator *E);
340 Value *VisitUnaryImag (const UnaryOperator *E);
341 Value *VisitUnaryExtension(const UnaryOperator *E) {
342 return Visit(E->getSubExpr());
346 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
347 return Visit(DAE->getExpr());
349 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
350 return CGF.LoadCXXThis();
353 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
354 return CGF.EmitExprWithCleanups(E).getScalarVal();
356 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
357 return CGF.EmitCXXNewExpr(E);
359 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
360 CGF.EmitCXXDeleteExpr(E);
363 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
364 return Builder.getInt1(E->getValue());
367 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
368 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
371 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
372 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
375 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
376 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
379 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
380 // C++ [expr.pseudo]p1:
381 // The result shall only be used as the operand for the function call
382 // operator (), and the result of such a call has type void. The only
383 // effect is the evaluation of the postfix-expression before the dot or
385 CGF.EmitScalarExpr(E->getBase());
389 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
390 return EmitNullValue(E->getType());
393 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
394 CGF.EmitCXXThrowExpr(E);
398 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
399 return Builder.getInt1(E->getValue());
403 Value *EmitMul(const BinOpInfo &Ops) {
404 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
405 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
406 case LangOptions::SOB_Undefined:
407 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
408 case LangOptions::SOB_Defined:
409 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
410 case LangOptions::SOB_Trapping:
411 return EmitOverflowCheckedBinOp(Ops);
415 if (Ops.LHS->getType()->isFPOrFPVectorTy())
416 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
417 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
419 bool isTrapvOverflowBehavior() {
420 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
421 == LangOptions::SOB_Trapping;
423 /// Create a binary op that checks for overflow.
424 /// Currently only supports +, - and *.
425 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
426 // Emit the overflow BB when -ftrapv option is activated.
427 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
428 Builder.SetInsertPoint(overflowBB);
429 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
430 Builder.CreateCall(Trap);
431 Builder.CreateUnreachable();
433 // Check for undefined division and modulus behaviors.
434 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
435 llvm::Value *Zero,bool isDiv);
436 Value *EmitDiv(const BinOpInfo &Ops);
437 Value *EmitRem(const BinOpInfo &Ops);
438 Value *EmitAdd(const BinOpInfo &Ops);
439 Value *EmitSub(const BinOpInfo &Ops);
440 Value *EmitShl(const BinOpInfo &Ops);
441 Value *EmitShr(const BinOpInfo &Ops);
442 Value *EmitAnd(const BinOpInfo &Ops) {
443 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
445 Value *EmitXor(const BinOpInfo &Ops) {
446 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
448 Value *EmitOr (const BinOpInfo &Ops) {
449 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
452 BinOpInfo EmitBinOps(const BinaryOperator *E);
453 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
454 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
457 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
458 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
460 // Binary operators and binary compound assignment operators.
461 #define HANDLEBINOP(OP) \
462 Value *VisitBin ## OP(const BinaryOperator *E) { \
463 return Emit ## OP(EmitBinOps(E)); \
465 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
466 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
481 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
482 unsigned SICmpOpc, unsigned FCmpOpc);
483 #define VISITCOMP(CODE, UI, SI, FP) \
484 Value *VisitBin##CODE(const BinaryOperator *E) { \
485 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
486 llvm::FCmpInst::FP); }
487 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
488 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
489 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
490 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
491 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
492 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
495 Value *VisitBinAssign (const BinaryOperator *E);
497 Value *VisitBinLAnd (const BinaryOperator *E);
498 Value *VisitBinLOr (const BinaryOperator *E);
499 Value *VisitBinComma (const BinaryOperator *E);
501 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
502 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
505 Value *VisitBlockExpr(const BlockExpr *BE);
506 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
507 Value *VisitChooseExpr(ChooseExpr *CE);
508 Value *VisitVAArgExpr(VAArgExpr *VE);
509 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
510 return CGF.EmitObjCStringLiteral(E);
512 Value *VisitAsTypeExpr(AsTypeExpr *CE);
514 } // end anonymous namespace.
516 //===----------------------------------------------------------------------===//
518 //===----------------------------------------------------------------------===//
520 /// EmitConversionToBool - Convert the specified expression value to a
521 /// boolean (i1) truth value. This is equivalent to "Val != 0".
522 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
523 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
525 if (SrcType->isRealFloatingType())
526 return EmitFloatToBoolConversion(Src);
528 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
529 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
531 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
532 "Unknown scalar type to convert");
534 if (isa<llvm::IntegerType>(Src->getType()))
535 return EmitIntToBoolConversion(Src);
537 assert(isa<llvm::PointerType>(Src->getType()));
538 return EmitPointerToBoolConversion(Src);
541 /// EmitScalarConversion - Emit a conversion from the specified type to the
542 /// specified destination type, both of which are LLVM scalar types.
543 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
545 SrcType = CGF.getContext().getCanonicalType(SrcType);
546 DstType = CGF.getContext().getCanonicalType(DstType);
547 if (SrcType == DstType) return Src;
549 if (DstType->isVoidType()) return 0;
551 // Handle conversions to bool first, they are special: comparisons against 0.
552 if (DstType->isBooleanType())
553 return EmitConversionToBool(Src, SrcType);
555 const llvm::Type *DstTy = ConvertType(DstType);
557 // Ignore conversions like int -> uint.
558 if (Src->getType() == DstTy)
561 // Handle pointer conversions next: pointers can only be converted to/from
562 // other pointers and integers. Check for pointer types in terms of LLVM, as
563 // some native types (like Obj-C id) may map to a pointer type.
564 if (isa<llvm::PointerType>(DstTy)) {
565 // The source value may be an integer, or a pointer.
566 if (isa<llvm::PointerType>(Src->getType()))
567 return Builder.CreateBitCast(Src, DstTy, "conv");
569 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
570 // First, convert to the correct width so that we control the kind of
572 const llvm::Type *MiddleTy = CGF.IntPtrTy;
573 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
574 llvm::Value* IntResult =
575 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
576 // Then, cast to pointer.
577 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
580 if (isa<llvm::PointerType>(Src->getType())) {
581 // Must be an ptr to int cast.
582 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
583 return Builder.CreatePtrToInt(Src, DstTy, "conv");
586 // A scalar can be splatted to an extended vector of the same element type
587 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
588 // Cast the scalar to element type
589 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
590 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
592 // Insert the element in element zero of an undef vector
593 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
594 llvm::Value *Idx = Builder.getInt32(0);
595 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
597 // Splat the element across to all elements
598 llvm::SmallVector<llvm::Constant*, 16> Args;
599 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
600 for (unsigned i = 0; i != NumElements; ++i)
601 Args.push_back(Builder.getInt32(0));
603 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
604 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
608 // Allow bitcast from vector to integer/fp of the same size.
609 if (isa<llvm::VectorType>(Src->getType()) ||
610 isa<llvm::VectorType>(DstTy))
611 return Builder.CreateBitCast(Src, DstTy, "conv");
613 // Finally, we have the arithmetic types: real int/float.
614 if (isa<llvm::IntegerType>(Src->getType())) {
615 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
616 if (isa<llvm::IntegerType>(DstTy))
617 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
618 else if (InputSigned)
619 return Builder.CreateSIToFP(Src, DstTy, "conv");
621 return Builder.CreateUIToFP(Src, DstTy, "conv");
624 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
625 if (isa<llvm::IntegerType>(DstTy)) {
626 if (DstType->isSignedIntegerOrEnumerationType())
627 return Builder.CreateFPToSI(Src, DstTy, "conv");
629 return Builder.CreateFPToUI(Src, DstTy, "conv");
632 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
633 if (DstTy->getTypeID() < Src->getType()->getTypeID())
634 return Builder.CreateFPTrunc(Src, DstTy, "conv");
636 return Builder.CreateFPExt(Src, DstTy, "conv");
639 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
640 /// type to the specified destination type, where the destination type is an
641 /// LLVM scalar type.
642 Value *ScalarExprEmitter::
643 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
644 QualType SrcTy, QualType DstTy) {
645 // Get the source element type.
646 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
648 // Handle conversions to bool first, they are special: comparisons against 0.
649 if (DstTy->isBooleanType()) {
650 // Complex != 0 -> (Real != 0) | (Imag != 0)
651 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
652 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
653 return Builder.CreateOr(Src.first, Src.second, "tobool");
656 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
657 // the imaginary part of the complex value is discarded and the value of the
658 // real part is converted according to the conversion rules for the
659 // corresponding real type.
660 return EmitScalarConversion(Src.first, SrcTy, DstTy);
663 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
664 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
665 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
667 return llvm::Constant::getNullValue(ConvertType(Ty));
670 //===----------------------------------------------------------------------===//
672 //===----------------------------------------------------------------------===//
674 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
675 CGF.ErrorUnsupported(E, "scalar expression");
676 if (E->getType()->isVoidType())
678 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
681 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
683 if (E->getNumSubExprs() == 2 ||
684 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
685 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
686 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
689 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
690 unsigned LHSElts = LTy->getNumElements();
692 if (E->getNumSubExprs() == 3) {
693 Mask = CGF.EmitScalarExpr(E->getExpr(2));
695 // Shuffle LHS & RHS into one input vector.
696 llvm::SmallVector<llvm::Constant*, 32> concat;
697 for (unsigned i = 0; i != LHSElts; ++i) {
698 concat.push_back(Builder.getInt32(2*i));
699 concat.push_back(Builder.getInt32(2*i+1));
702 Value* CV = llvm::ConstantVector::get(concat);
703 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
709 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
710 llvm::Constant* EltMask;
712 // Treat vec3 like vec4.
713 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
714 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
715 (1 << llvm::Log2_32(LHSElts+2))-1);
716 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
717 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
718 (1 << llvm::Log2_32(LHSElts+1))-1);
720 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
721 (1 << llvm::Log2_32(LHSElts))-1);
723 // Mask off the high bits of each shuffle index.
724 llvm::SmallVector<llvm::Constant *, 32> MaskV;
725 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
726 MaskV.push_back(EltMask);
728 Value* MaskBits = llvm::ConstantVector::get(MaskV);
729 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
732 // mask = mask & maskbits
734 // n = extract mask i
736 // newv = insert newv, x, i
737 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
738 MTy->getNumElements());
739 Value* NewV = llvm::UndefValue::get(RTy);
740 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
741 Value *Indx = Builder.getInt32(i);
742 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
743 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
745 // Handle vec3 special since the index will be off by one for the RHS.
746 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
747 Value *cmpIndx, *newIndx;
748 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
750 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
751 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
753 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
754 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
759 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
760 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
762 // Handle vec3 special since the index will be off by one for the RHS.
763 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
764 llvm::SmallVector<llvm::Constant*, 32> indices;
765 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
766 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
767 if (VTy->getNumElements() == 3 && Idx > 3)
769 indices.push_back(Builder.getInt32(Idx));
772 Value *SV = llvm::ConstantVector::get(indices);
773 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
775 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
776 Expr::EvalResult Result;
777 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
779 CGF.EmitScalarExpr(E->getBase());
781 EmitLValue(E->getBase());
782 return Builder.getInt(Result.Val.getInt());
785 // Emit debug info for aggregate now, if it was delayed to reduce
787 CGDebugInfo *DI = CGF.getDebugInfo();
788 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
789 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
790 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
791 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
792 DI->getOrCreateRecordType(PTy->getPointeeType(),
793 M->getParent()->getLocation());
795 return EmitLoadOfLValue(E);
798 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
799 TestAndClearIgnoreResultAssign();
801 // Emit subscript expressions in rvalue context's. For most cases, this just
802 // loads the lvalue formed by the subscript expr. However, we have to be
803 // careful, because the base of a vector subscript is occasionally an rvalue,
804 // so we can't get it as an lvalue.
805 if (!E->getBase()->getType()->isVectorType())
806 return EmitLoadOfLValue(E);
808 // Handle the vector case. The base must be a vector, the index must be an
810 Value *Base = Visit(E->getBase());
811 Value *Idx = Visit(E->getIdx());
812 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
813 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
814 return Builder.CreateExtractElement(Base, Idx, "vecext");
817 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
818 unsigned Off, const llvm::Type *I32Ty) {
819 int MV = SVI->getMaskValue(Idx);
821 return llvm::UndefValue::get(I32Ty);
822 return llvm::ConstantInt::get(I32Ty, Off+MV);
825 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
826 bool Ignore = TestAndClearIgnoreResultAssign();
828 assert (Ignore == false && "init list ignored");
829 unsigned NumInitElements = E->getNumInits();
831 if (E->hadArrayRangeDesignator())
832 CGF.ErrorUnsupported(E, "GNU array range designator extension");
834 const llvm::VectorType *VType =
835 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
837 // We have a scalar in braces. Just use the first element.
839 return Visit(E->getInit(0));
841 unsigned ResElts = VType->getNumElements();
843 // Loop over initializers collecting the Value for each, and remembering
844 // whether the source was swizzle (ExtVectorElementExpr). This will allow
845 // us to fold the shuffle for the swizzle into the shuffle for the vector
846 // initializer, since LLVM optimizers generally do not want to touch
849 bool VIsUndefShuffle = false;
850 llvm::Value *V = llvm::UndefValue::get(VType);
851 for (unsigned i = 0; i != NumInitElements; ++i) {
852 Expr *IE = E->getInit(i);
853 Value *Init = Visit(IE);
854 llvm::SmallVector<llvm::Constant*, 16> Args;
856 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
858 // Handle scalar elements. If the scalar initializer is actually one
859 // element of a different vector of the same width, use shuffle instead of
862 if (isa<ExtVectorElementExpr>(IE)) {
863 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
865 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
866 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
867 Value *LHS = 0, *RHS = 0;
869 // insert into undef -> shuffle (src, undef)
871 for (unsigned j = 1; j != ResElts; ++j)
872 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
874 LHS = EI->getVectorOperand();
876 VIsUndefShuffle = true;
877 } else if (VIsUndefShuffle) {
878 // insert into undefshuffle && size match -> shuffle (v, src)
879 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
880 for (unsigned j = 0; j != CurIdx; ++j)
881 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
882 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
883 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
884 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
886 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
887 RHS = EI->getVectorOperand();
888 VIsUndefShuffle = false;
891 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
892 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
898 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
900 VIsUndefShuffle = false;
905 unsigned InitElts = VVT->getNumElements();
907 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
908 // input is the same width as the vector being constructed, generate an
909 // optimized shuffle of the swizzle input into the result.
910 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
911 if (isa<ExtVectorElementExpr>(IE)) {
912 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
913 Value *SVOp = SVI->getOperand(0);
914 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
916 if (OpTy->getNumElements() == ResElts) {
917 for (unsigned j = 0; j != CurIdx; ++j) {
918 // If the current vector initializer is a shuffle with undef, merge
919 // this shuffle directly into it.
920 if (VIsUndefShuffle) {
921 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
924 Args.push_back(Builder.getInt32(j));
927 for (unsigned j = 0, je = InitElts; j != je; ++j)
928 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
929 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
930 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
933 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
939 // Extend init to result vector length, and then shuffle its contribution
940 // to the vector initializer into V.
942 for (unsigned j = 0; j != InitElts; ++j)
943 Args.push_back(Builder.getInt32(j));
944 for (unsigned j = InitElts; j != ResElts; ++j)
945 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
946 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
947 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
951 for (unsigned j = 0; j != CurIdx; ++j)
952 Args.push_back(Builder.getInt32(j));
953 for (unsigned j = 0; j != InitElts; ++j)
954 Args.push_back(Builder.getInt32(j+Offset));
955 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
956 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
959 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
960 // merging subsequent shuffles into this one.
963 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
964 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
965 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
969 // FIXME: evaluate codegen vs. shuffling against constant null vector.
970 // Emit remaining default initializers.
971 const llvm::Type *EltTy = VType->getElementType();
973 // Emit remaining default initializers
974 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
975 Value *Idx = Builder.getInt32(CurIdx);
976 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
977 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
982 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
983 const Expr *E = CE->getSubExpr();
985 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
988 if (isa<CXXThisExpr>(E)) {
989 // We always assume that 'this' is never null.
993 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
994 // And that glvalue casts are never null.
995 if (ICE->getValueKind() != VK_RValue)
1002 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1003 // have to handle a more broad range of conversions than explicit casts, as they
1004 // handle things like function to ptr-to-function decay etc.
1005 Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
1006 Expr *E = CE->getSubExpr();
1007 QualType DestTy = CE->getType();
1008 CastKind Kind = CE->getCastKind();
1010 if (!DestTy->isVoidType())
1011 TestAndClearIgnoreResultAssign();
1013 // Since almost all cast kinds apply to scalars, this switch doesn't have
1014 // a default case, so the compiler will warn on a missing case. The cases
1015 // are in the same order as in the CastKind enum.
1017 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1019 case CK_LValueBitCast:
1020 case CK_ObjCObjectLValueCast: {
1021 Value *V = EmitLValue(E).getAddress();
1022 V = Builder.CreateBitCast(V,
1023 ConvertType(CGF.getContext().getPointerType(DestTy)));
1024 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy));
1027 case CK_AnyPointerToObjCPointerCast:
1028 case CK_AnyPointerToBlockPointerCast:
1030 Value *Src = Visit(const_cast<Expr*>(E));
1031 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1034 case CK_UserDefinedConversion:
1035 return Visit(const_cast<Expr*>(E));
1037 case CK_BaseToDerived: {
1038 const CXXRecordDecl *DerivedClassDecl =
1039 DestTy->getCXXRecordDeclForPointerType();
1041 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
1042 CE->path_begin(), CE->path_end(),
1043 ShouldNullCheckClassCastValue(CE));
1045 case CK_UncheckedDerivedToBase:
1046 case CK_DerivedToBase: {
1047 const RecordType *DerivedClassTy =
1048 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1049 CXXRecordDecl *DerivedClassDecl =
1050 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1052 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
1053 CE->path_begin(), CE->path_end(),
1054 ShouldNullCheckClassCastValue(CE));
1057 Value *V = Visit(const_cast<Expr*>(E));
1058 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1059 return CGF.EmitDynamicCast(V, DCE);
1062 case CK_ArrayToPointerDecay: {
1063 assert(E->getType()->isArrayType() &&
1064 "Array to pointer decay must have array source type!");
1066 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1068 // Note that VLA pointers are always decayed, so we don't need to do
1070 if (!E->getType()->isVariableArrayType()) {
1071 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1072 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1073 ->getElementType()) &&
1074 "Expected pointer to array");
1075 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1080 case CK_FunctionToPointerDecay:
1081 return EmitLValue(E).getAddress();
1083 case CK_NullToPointer:
1084 if (MustVisitNullValue(E))
1087 return llvm::ConstantPointerNull::get(
1088 cast<llvm::PointerType>(ConvertType(DestTy)));
1090 case CK_NullToMemberPointer: {
1091 if (MustVisitNullValue(E))
1094 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1095 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1098 case CK_BaseToDerivedMemberPointer:
1099 case CK_DerivedToBaseMemberPointer: {
1100 Value *Src = Visit(E);
1102 // Note that the AST doesn't distinguish between checked and
1103 // unchecked member pointer conversions, so we always have to
1104 // implement checked conversions here. This is inefficient when
1105 // actual control flow may be required in order to perform the
1106 // check, which it is for data member pointers (but not member
1107 // function pointers on Itanium and ARM).
1108 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1111 case CK_ObjCProduceObject:
1112 return CGF.EmitARCRetainScalarExpr(E);
1113 case CK_ObjCConsumeObject:
1114 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
1115 case CK_ObjCReclaimReturnedObject: {
1116 llvm::Value *value = Visit(E);
1117 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1118 return CGF.EmitObjCConsumeObject(E->getType(), value);
1121 case CK_FloatingRealToComplex:
1122 case CK_FloatingComplexCast:
1123 case CK_IntegralRealToComplex:
1124 case CK_IntegralComplexCast:
1125 case CK_IntegralComplexToFloatingComplex:
1126 case CK_FloatingComplexToIntegralComplex:
1127 case CK_ConstructorConversion:
1129 llvm_unreachable("scalar cast to non-scalar value");
1132 case CK_GetObjCProperty: {
1133 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1134 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty &&
1135 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
1136 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E));
1137 return RV.getScalarVal();
1140 case CK_LValueToRValue:
1141 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1142 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1143 return Visit(const_cast<Expr*>(E));
1145 case CK_IntegralToPointer: {
1146 Value *Src = Visit(const_cast<Expr*>(E));
1148 // First, convert to the correct width so that we control the kind of
1150 const llvm::Type *MiddleTy = CGF.IntPtrTy;
1151 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
1152 llvm::Value* IntResult =
1153 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1155 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1157 case CK_PointerToIntegral:
1158 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1159 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
1162 CGF.EmitIgnoredExpr(E);
1165 case CK_VectorSplat: {
1166 const llvm::Type *DstTy = ConvertType(DestTy);
1167 Value *Elt = Visit(const_cast<Expr*>(E));
1169 // Insert the element in element zero of an undef vector
1170 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
1171 llvm::Value *Idx = Builder.getInt32(0);
1172 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1174 // Splat the element across to all elements
1175 llvm::SmallVector<llvm::Constant*, 16> Args;
1176 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1177 llvm::Constant *Zero = Builder.getInt32(0);
1178 for (unsigned i = 0; i < NumElements; i++)
1179 Args.push_back(Zero);
1181 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1182 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1186 case CK_IntegralCast:
1187 case CK_IntegralToFloating:
1188 case CK_FloatingToIntegral:
1189 case CK_FloatingCast:
1190 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1192 case CK_IntegralToBoolean:
1193 return EmitIntToBoolConversion(Visit(E));
1194 case CK_PointerToBoolean:
1195 return EmitPointerToBoolConversion(Visit(E));
1196 case CK_FloatingToBoolean:
1197 return EmitFloatToBoolConversion(Visit(E));
1198 case CK_MemberPointerToBoolean: {
1199 llvm::Value *MemPtr = Visit(E);
1200 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1201 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1204 case CK_FloatingComplexToReal:
1205 case CK_IntegralComplexToReal:
1206 return CGF.EmitComplexExpr(E, false, true).first;
1208 case CK_FloatingComplexToBoolean:
1209 case CK_IntegralComplexToBoolean: {
1210 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1212 // TODO: kill this function off, inline appropriate case here
1213 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1218 llvm_unreachable("unknown scalar cast");
1222 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1223 CodeGenFunction::StmtExprEvaluation eval(CGF);
1224 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1228 Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
1229 LValue LV = CGF.EmitBlockDeclRefLValue(E);
1230 return CGF.EmitLoadOfLValue(LV).getScalarVal();
1233 //===----------------------------------------------------------------------===//
1235 //===----------------------------------------------------------------------===//
1237 llvm::Value *ScalarExprEmitter::
1238 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1240 llvm::Value *NextVal, bool IsInc) {
1241 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1242 case LangOptions::SOB_Undefined:
1243 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1245 case LangOptions::SOB_Defined:
1246 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1248 case LangOptions::SOB_Trapping:
1251 BinOp.RHS = NextVal;
1252 BinOp.Ty = E->getType();
1253 BinOp.Opcode = BO_Add;
1255 return EmitOverflowCheckedBinOp(BinOp);
1258 assert(false && "Unknown SignedOverflowBehaviorTy");
1263 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1264 bool isInc, bool isPre) {
1266 QualType type = E->getSubExpr()->getType();
1267 llvm::Value *value = EmitLoadOfLValue(LV);
1268 llvm::Value *input = value;
1270 int amount = (isInc ? 1 : -1);
1272 // Special case of integer increment that we have to check first: bool++.
1273 // Due to promotion rules, we get:
1274 // bool++ -> bool = bool + 1
1275 // -> bool = (int)bool + 1
1276 // -> bool = ((int)bool + 1 != 0)
1277 // An interesting aspect of this is that increment is always true.
1278 // Decrement does not have this property.
1279 if (isInc && type->isBooleanType()) {
1280 value = Builder.getTrue();
1282 // Most common case by far: integer increment.
1283 } else if (type->isIntegerType()) {
1285 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1287 // Note that signed integer inc/dec with width less than int can't
1288 // overflow because of promotion rules; we're just eliding a few steps here.
1289 if (type->isSignedIntegerOrEnumerationType() &&
1290 value->getType()->getPrimitiveSizeInBits() >=
1291 CGF.IntTy->getBitWidth())
1292 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1294 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1296 // Next most common: pointer increment.
1297 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1298 QualType type = ptr->getPointeeType();
1300 // VLA types don't have constant size.
1301 if (const VariableArrayType *vla
1302 = CGF.getContext().getAsVariableArrayType(type)) {
1303 llvm::Value *numElts = CGF.getVLASize(vla).first;
1304 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
1305 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1306 value = Builder.CreateGEP(value, numElts, "vla.inc");
1308 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
1310 // Arithmetic on function pointers (!) is just +-1.
1311 } else if (type->isFunctionType()) {
1312 llvm::Value *amt = Builder.getInt32(amount);
1314 value = CGF.EmitCastToVoidPtr(value);
1315 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1316 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1318 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1319 value = Builder.CreateBitCast(value, input->getType());
1321 // For everything else, we can just do a simple increment.
1323 llvm::Value *amt = Builder.getInt32(amount);
1324 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1325 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1327 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1330 // Vector increment/decrement.
1331 } else if (type->isVectorType()) {
1332 if (type->hasIntegerRepresentation()) {
1333 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1335 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1337 value = Builder.CreateFAdd(
1339 llvm::ConstantFP::get(value->getType(), amount),
1340 isInc ? "inc" : "dec");
1344 } else if (type->isRealFloatingType()) {
1345 // Add the inc/dec to the real part.
1347 if (value->getType()->isFloatTy())
1348 amt = llvm::ConstantFP::get(VMContext,
1349 llvm::APFloat(static_cast<float>(amount)));
1350 else if (value->getType()->isDoubleTy())
1351 amt = llvm::ConstantFP::get(VMContext,
1352 llvm::APFloat(static_cast<double>(amount)));
1354 llvm::APFloat F(static_cast<float>(amount));
1356 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1358 amt = llvm::ConstantFP::get(VMContext, F);
1360 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1362 // Objective-C pointer types.
1364 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1365 value = CGF.EmitCastToVoidPtr(value);
1367 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1368 if (!isInc) size = -size;
1369 llvm::Value *sizeValue =
1370 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1372 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1373 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1375 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1376 value = Builder.CreateBitCast(value, input->getType());
1379 // Store the updated result through the lvalue.
1380 if (LV.isBitField())
1381 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
1383 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
1385 // If this is a postinc, return the value read from memory, otherwise use the
1387 return isPre ? value : input;
1392 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1393 TestAndClearIgnoreResultAssign();
1394 // Emit unary minus with EmitSub so we handle overflow cases etc.
1396 BinOp.RHS = Visit(E->getSubExpr());
1398 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1399 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1401 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1402 BinOp.Ty = E->getType();
1403 BinOp.Opcode = BO_Sub;
1405 return EmitSub(BinOp);
1408 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1409 TestAndClearIgnoreResultAssign();
1410 Value *Op = Visit(E->getSubExpr());
1411 return Builder.CreateNot(Op, "neg");
1414 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1415 // Compare operand to zero.
1416 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1419 // TODO: Could dynamically modify easy computations here. For example, if
1420 // the operand is an icmp ne, turn into icmp eq.
1421 BoolVal = Builder.CreateNot(BoolVal, "lnot");
1423 // ZExt result to the expr type.
1424 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1427 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1428 // Try folding the offsetof to a constant.
1429 Expr::EvalResult EvalResult;
1430 if (E->Evaluate(EvalResult, CGF.getContext()))
1431 return Builder.getInt(EvalResult.Val.getInt());
1433 // Loop over the components of the offsetof to compute the value.
1434 unsigned n = E->getNumComponents();
1435 const llvm::Type* ResultType = ConvertType(E->getType());
1436 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1437 QualType CurrentType = E->getTypeSourceInfo()->getType();
1438 for (unsigned i = 0; i != n; ++i) {
1439 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1440 llvm::Value *Offset = 0;
1441 switch (ON.getKind()) {
1442 case OffsetOfExpr::OffsetOfNode::Array: {
1443 // Compute the index
1444 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1445 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1446 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
1447 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1449 // Save the element type
1451 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1453 // Compute the element size
1454 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1455 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1457 // Multiply out to compute the result
1458 Offset = Builder.CreateMul(Idx, ElemSize);
1462 case OffsetOfExpr::OffsetOfNode::Field: {
1463 FieldDecl *MemberDecl = ON.getField();
1464 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1465 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1467 // Compute the index of the field in its parent.
1469 // FIXME: It would be nice if we didn't have to loop here!
1470 for (RecordDecl::field_iterator Field = RD->field_begin(),
1471 FieldEnd = RD->field_end();
1472 Field != FieldEnd; (void)++Field, ++i) {
1473 if (*Field == MemberDecl)
1476 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1478 // Compute the offset to the field
1479 int64_t OffsetInt = RL.getFieldOffset(i) /
1480 CGF.getContext().getCharWidth();
1481 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1483 // Save the element type.
1484 CurrentType = MemberDecl->getType();
1488 case OffsetOfExpr::OffsetOfNode::Identifier:
1489 llvm_unreachable("dependent __builtin_offsetof");
1491 case OffsetOfExpr::OffsetOfNode::Base: {
1492 if (ON.getBase()->isVirtual()) {
1493 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1497 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1498 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1500 // Save the element type.
1501 CurrentType = ON.getBase()->getType();
1503 // Compute the offset to the base.
1504 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1505 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1506 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
1507 CGF.getContext().getCharWidth();
1508 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1512 Result = Builder.CreateAdd(Result, Offset);
1517 /// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
1518 /// argument of the sizeof expression as an integer.
1520 ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1521 const UnaryExprOrTypeTraitExpr *E) {
1522 QualType TypeToSize = E->getTypeOfArgument();
1523 if (E->getKind() == UETT_SizeOf) {
1524 if (const VariableArrayType *VAT =
1525 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1526 if (E->isArgumentType()) {
1527 // sizeof(type) - make sure to emit the VLA size.
1528 CGF.EmitVariablyModifiedType(TypeToSize);
1530 // C99 6.5.3.4p2: If the argument is an expression of type
1531 // VLA, it is evaluated.
1532 CGF.EmitIgnoredExpr(E->getArgumentExpr());
1536 llvm::Value *numElts;
1537 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1539 llvm::Value *size = numElts;
1541 // Scale the number of non-VLA elements by the non-VLA element size.
1542 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1543 if (!eltSize.isOne())
1544 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1550 // If this isn't sizeof(vla), the result must be constant; use the constant
1551 // folding logic so we don't have to duplicate it here.
1552 Expr::EvalResult Result;
1553 E->Evaluate(Result, CGF.getContext());
1554 return Builder.getInt(Result.Val.getInt());
1557 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1558 Expr *Op = E->getSubExpr();
1559 if (Op->getType()->isAnyComplexType()) {
1560 // If it's an l-value, load through the appropriate subobject l-value.
1561 // Note that we have to ask E because Op might be an l-value that
1562 // this won't work for, e.g. an Obj-C property.
1564 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1566 // Otherwise, calculate and project.
1567 return CGF.EmitComplexExpr(Op, false, true).first;
1573 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1574 Expr *Op = E->getSubExpr();
1575 if (Op->getType()->isAnyComplexType()) {
1576 // If it's an l-value, load through the appropriate subobject l-value.
1577 // Note that we have to ask E because Op might be an l-value that
1578 // this won't work for, e.g. an Obj-C property.
1579 if (Op->isGLValue())
1580 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
1582 // Otherwise, calculate and project.
1583 return CGF.EmitComplexExpr(Op, true, false).second;
1586 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1587 // effects are evaluated, but not the actual value.
1588 CGF.EmitScalarExpr(Op, true);
1589 return llvm::Constant::getNullValue(ConvertType(E->getType()));
1592 //===----------------------------------------------------------------------===//
1594 //===----------------------------------------------------------------------===//
1596 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1597 TestAndClearIgnoreResultAssign();
1599 Result.LHS = Visit(E->getLHS());
1600 Result.RHS = Visit(E->getRHS());
1601 Result.Ty = E->getType();
1602 Result.Opcode = E->getOpcode();
1607 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1608 const CompoundAssignOperator *E,
1609 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1611 QualType LHSTy = E->getLHS()->getType();
1614 if (E->getComputationResultType()->isAnyComplexType()) {
1615 // This needs to go through the complex expression emitter, but it's a tad
1616 // complicated to do that... I'm leaving it out for now. (Note that we do
1617 // actually need the imaginary part of the RHS for multiplication and
1619 CGF.ErrorUnsupported(E, "complex compound assignment");
1620 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1624 // Emit the RHS first. __block variables need to have the rhs evaluated
1625 // first, plus this should improve codegen a little.
1626 OpInfo.RHS = Visit(E->getRHS());
1627 OpInfo.Ty = E->getComputationResultType();
1628 OpInfo.Opcode = E->getOpcode();
1630 // Load/convert the LHS.
1631 LValue LHSLV = EmitCheckedLValue(E->getLHS());
1632 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
1633 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1634 E->getComputationLHSType());
1636 // Expand the binary operator.
1637 Result = (this->*Func)(OpInfo);
1639 // Convert the result back to the LHS type.
1640 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1642 // Store the result value into the LHS lvalue. Bit-fields are handled
1643 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1644 // 'An assignment expression has the value of the left operand after the
1646 if (LHSLV.isBitField())
1647 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
1649 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
1654 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1655 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1656 bool Ignore = TestAndClearIgnoreResultAssign();
1658 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1660 // If the result is clearly ignored, return now.
1664 // The result of an assignment in C is the assigned r-value.
1665 if (!CGF.getContext().getLangOptions().CPlusPlus)
1668 // Objective-C property assignment never reloads the value following a store.
1669 if (LHS.isPropertyRef())
1672 // If the lvalue is non-volatile, return the computed value of the assignment.
1673 if (!LHS.isVolatileQualified())
1676 // Otherwise, reload the value.
1677 return EmitLoadOfLValue(LHS);
1680 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1681 const BinOpInfo &Ops,
1682 llvm::Value *Zero, bool isDiv) {
1683 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1684 llvm::BasicBlock *contBB =
1685 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn,
1686 llvm::next(insertPt));
1687 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1689 const llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1691 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1692 llvm::Value *IntMin =
1693 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1694 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1696 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1697 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1698 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1699 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1700 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1701 overflowBB, contBB);
1703 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1704 overflowBB, contBB);
1706 EmitOverflowBB(overflowBB);
1707 Builder.SetInsertPoint(contBB);
1710 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1711 if (isTrapvOverflowBehavior()) {
1712 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1714 if (Ops.Ty->isIntegerType())
1715 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1716 else if (Ops.Ty->isRealFloatingType()) {
1717 llvm::Function::iterator insertPt = Builder.GetInsertBlock();
1718 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn,
1719 llvm::next(insertPt));
1720 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1722 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1723 overflowBB, DivCont);
1724 EmitOverflowBB(overflowBB);
1725 Builder.SetInsertPoint(DivCont);
1728 if (Ops.LHS->getType()->isFPOrFPVectorTy())
1729 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1730 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
1731 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1733 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1736 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1737 // Rem in C can't be a floating point type: C99 6.5.5p2.
1738 if (isTrapvOverflowBehavior()) {
1739 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1741 if (Ops.Ty->isIntegerType())
1742 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1745 if (Ops.Ty->hasUnsignedIntegerRepresentation())
1746 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1748 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1751 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1755 switch (Ops.Opcode) {
1759 IID = llvm::Intrinsic::sadd_with_overflow;
1764 IID = llvm::Intrinsic::ssub_with_overflow;
1769 IID = llvm::Intrinsic::smul_with_overflow;
1772 assert(false && "Unsupported operation for overflow detection");
1778 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1780 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
1782 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1783 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1784 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1786 // Branch in case of overflow.
1787 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1788 llvm::Function::iterator insertPt = initialBB;
1789 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
1790 llvm::next(insertPt));
1791 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1793 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1795 // Handle overflow with llvm.trap.
1796 const std::string *handlerName =
1797 &CGF.getContext().getLangOptions().OverflowHandler;
1798 if (handlerName->empty()) {
1799 EmitOverflowBB(overflowBB);
1800 Builder.SetInsertPoint(continueBB);
1804 // If an overflow handler is set, then we want to call it and then use its
1805 // result, if it returns.
1806 Builder.SetInsertPoint(overflowBB);
1808 // Get the overflow handler.
1809 llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
1810 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
1811 llvm::FunctionType *handlerTy =
1812 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1813 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1815 // Sign extend the args to 64-bit, so that we can use the same handler for
1816 // all types of overflow.
1817 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1818 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1820 // Call the handler with the two arguments, the operation, and the size of
1822 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1823 Builder.getInt8(OpID),
1824 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1826 // Truncate the result back to the desired size.
1827 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1828 Builder.CreateBr(continueBB);
1830 Builder.SetInsertPoint(continueBB);
1831 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
1832 phi->addIncoming(result, initialBB);
1833 phi->addIncoming(handlerResult, overflowBB);
1838 /// Emit pointer + index arithmetic.
1839 static Value *emitPointerArithmetic(CodeGenFunction &CGF,
1840 const BinOpInfo &op,
1841 bool isSubtraction) {
1842 // Must have binary (not unary) expr here. Unary pointer
1843 // increment/decrement doesn't use this path.
1844 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1846 Value *pointer = op.LHS;
1847 Expr *pointerOperand = expr->getLHS();
1848 Value *index = op.RHS;
1849 Expr *indexOperand = expr->getRHS();
1851 // In a subtraction, the LHS is always the pointer.
1852 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
1853 std::swap(pointer, index);
1854 std::swap(pointerOperand, indexOperand);
1857 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
1858 if (width != CGF.PointerWidthInBits) {
1859 // Zero-extend or sign-extend the pointer value according to
1860 // whether the index is signed or not.
1861 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
1862 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
1866 // If this is subtraction, negate the index.
1868 index = CGF.Builder.CreateNeg(index, "idx.neg");
1870 const PointerType *pointerType
1871 = pointerOperand->getType()->getAs<PointerType>();
1873 QualType objectType = pointerOperand->getType()
1874 ->castAs<ObjCObjectPointerType>()
1876 llvm::Value *objectSize
1877 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
1879 index = CGF.Builder.CreateMul(index, objectSize);
1881 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1882 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1883 return CGF.Builder.CreateBitCast(result, pointer->getType());
1886 QualType elementType = pointerType->getPointeeType();
1887 if (const VariableArrayType *vla
1888 = CGF.getContext().getAsVariableArrayType(elementType)) {
1889 // The element count here is the total number of non-VLA elements.
1890 llvm::Value *numElements = CGF.getVLASize(vla).first;
1892 // Effectively, the multiply by the VLA size is part of the GEP.
1893 // GEP indexes are signed, and scaling an index isn't permitted to
1894 // signed-overflow, so we use the same semantics for our explicit
1895 // multiply. We suppress this if overflow is not undefined behavior.
1896 if (CGF.getLangOptions().isSignedOverflowDefined()) {
1897 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
1898 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1900 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
1901 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
1906 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1907 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1909 if (elementType->isVoidType() || elementType->isFunctionType()) {
1910 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
1911 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
1912 return CGF.Builder.CreateBitCast(result, pointer->getType());
1915 if (CGF.getLangOptions().isSignedOverflowDefined())
1916 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
1918 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
1921 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
1922 if (op.LHS->getType()->isPointerTy() ||
1923 op.RHS->getType()->isPointerTy())
1924 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
1926 if (op.Ty->isSignedIntegerOrEnumerationType()) {
1927 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1928 case LangOptions::SOB_Undefined:
1929 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
1930 case LangOptions::SOB_Defined:
1931 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1932 case LangOptions::SOB_Trapping:
1933 return EmitOverflowCheckedBinOp(op);
1937 if (op.LHS->getType()->isFPOrFPVectorTy())
1938 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
1940 return Builder.CreateAdd(op.LHS, op.RHS, "add");
1943 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
1944 // The LHS is always a pointer if either side is.
1945 if (!op.LHS->getType()->isPointerTy()) {
1946 if (op.Ty->isSignedIntegerOrEnumerationType()) {
1947 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1948 case LangOptions::SOB_Undefined:
1949 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
1950 case LangOptions::SOB_Defined:
1951 return Builder.CreateSub(op.LHS, op.RHS, "sub");
1952 case LangOptions::SOB_Trapping:
1953 return EmitOverflowCheckedBinOp(op);
1957 if (op.LHS->getType()->isFPOrFPVectorTy())
1958 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
1960 return Builder.CreateSub(op.LHS, op.RHS, "sub");
1963 // If the RHS is not a pointer, then we have normal pointer
1965 if (!op.RHS->getType()->isPointerTy())
1966 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
1968 // Otherwise, this is a pointer subtraction.
1970 // Do the raw subtraction part.
1972 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
1974 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
1975 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1977 // Okay, figure out the element size.
1978 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
1979 QualType elementType = expr->getLHS()->getType()->getPointeeType();
1981 llvm::Value *divisor = 0;
1983 // For a variable-length array, this is going to be non-constant.
1984 if (const VariableArrayType *vla
1985 = CGF.getContext().getAsVariableArrayType(elementType)) {
1986 llvm::Value *numElements;
1987 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
1989 divisor = numElements;
1991 // Scale the number of non-VLA elements by the non-VLA element size.
1992 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
1993 if (!eltSize.isOne())
1994 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
1996 // For everything elese, we can just compute it, safe in the
1997 // assumption that Sema won't let anything through that we can't
1998 // safely compute the size of.
2000 CharUnits elementSize;
2001 // Handle GCC extension for pointer arithmetic on void* and
2002 // function pointer types.
2003 if (elementType->isVoidType() || elementType->isFunctionType())
2004 elementSize = CharUnits::One();
2006 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2008 // Don't even emit the divide for element size of 1.
2009 if (elementSize.isOne())
2012 divisor = CGF.CGM.getSize(elementSize);
2015 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2016 // pointer difference in C is only defined in the case where both operands
2017 // are pointing to elements of an array.
2018 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
2021 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2022 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2023 // RHS to the same size as the LHS.
2024 Value *RHS = Ops.RHS;
2025 if (Ops.LHS->getType() != RHS->getType())
2026 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2028 if (CGF.CatchUndefined
2029 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2030 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2031 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2032 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2033 llvm::ConstantInt::get(RHS->getType(), Width)),
2034 Cont, CGF.getTrapBB());
2035 CGF.EmitBlock(Cont);
2038 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2041 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2042 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2043 // RHS to the same size as the LHS.
2044 Value *RHS = Ops.RHS;
2045 if (Ops.LHS->getType() != RHS->getType())
2046 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2048 if (CGF.CatchUndefined
2049 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2050 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2051 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2052 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2053 llvm::ConstantInt::get(RHS->getType(), Width)),
2054 Cont, CGF.getTrapBB());
2055 CGF.EmitBlock(Cont);
2058 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2059 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2060 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2063 enum IntrinsicType { VCMPEQ, VCMPGT };
2064 // return corresponding comparison intrinsic for given vector type
2065 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2066 BuiltinType::Kind ElemKind) {
2068 default: assert(0 && "unexpected element type");
2069 case BuiltinType::Char_U:
2070 case BuiltinType::UChar:
2071 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2072 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2074 case BuiltinType::Char_S:
2075 case BuiltinType::SChar:
2076 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2077 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2079 case BuiltinType::UShort:
2080 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2081 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2083 case BuiltinType::Short:
2084 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2085 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2087 case BuiltinType::UInt:
2088 case BuiltinType::ULong:
2089 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2090 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2092 case BuiltinType::Int:
2093 case BuiltinType::Long:
2094 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2095 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2097 case BuiltinType::Float:
2098 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2099 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2102 return llvm::Intrinsic::not_intrinsic;
2105 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2106 unsigned SICmpOpc, unsigned FCmpOpc) {
2107 TestAndClearIgnoreResultAssign();
2109 QualType LHSTy = E->getLHS()->getType();
2110 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2111 assert(E->getOpcode() == BO_EQ ||
2112 E->getOpcode() == BO_NE);
2113 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2114 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2115 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2116 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2117 } else if (!LHSTy->isAnyComplexType()) {
2118 Value *LHS = Visit(E->getLHS());
2119 Value *RHS = Visit(E->getRHS());
2121 // If AltiVec, the comparison results in a numeric type, so we use
2122 // intrinsics comparing vectors and giving 0 or 1 as a result
2123 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
2124 // constants for mapping CR6 register bits to predicate result
2125 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2127 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2129 // in several cases vector arguments order will be reversed
2130 Value *FirstVecArg = LHS,
2131 *SecondVecArg = RHS;
2133 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2134 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2135 BuiltinType::Kind ElementKind = BTy->getKind();
2137 switch(E->getOpcode()) {
2138 default: assert(0 && "is not a comparison operation");
2141 ID = GetIntrinsic(VCMPEQ, ElementKind);
2145 ID = GetIntrinsic(VCMPEQ, ElementKind);
2149 ID = GetIntrinsic(VCMPGT, ElementKind);
2150 std::swap(FirstVecArg, SecondVecArg);
2154 ID = GetIntrinsic(VCMPGT, ElementKind);
2157 if (ElementKind == BuiltinType::Float) {
2159 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2160 std::swap(FirstVecArg, SecondVecArg);
2164 ID = GetIntrinsic(VCMPGT, ElementKind);
2168 if (ElementKind == BuiltinType::Float) {
2170 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2174 ID = GetIntrinsic(VCMPGT, ElementKind);
2175 std::swap(FirstVecArg, SecondVecArg);
2180 Value *CR6Param = Builder.getInt32(CR6);
2181 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2182 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2183 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2186 if (LHS->getType()->isFPOrFPVectorTy()) {
2187 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2189 } else if (LHSTy->hasSignedIntegerRepresentation()) {
2190 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2193 // Unsigned integers and pointers.
2194 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2198 // If this is a vector comparison, sign extend the result to the appropriate
2199 // vector integer type and return it (don't convert to bool).
2200 if (LHSTy->isVectorType())
2201 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2204 // Complex Comparison: can only be an equality comparison.
2205 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2206 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
2208 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
2210 Value *ResultR, *ResultI;
2211 if (CETy->isRealFloatingType()) {
2212 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2213 LHS.first, RHS.first, "cmp.r");
2214 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2215 LHS.second, RHS.second, "cmp.i");
2217 // Complex comparisons can only be equality comparisons. As such, signed
2218 // and unsigned opcodes are the same.
2219 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2220 LHS.first, RHS.first, "cmp.r");
2221 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2222 LHS.second, RHS.second, "cmp.i");
2225 if (E->getOpcode() == BO_EQ) {
2226 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2228 assert(E->getOpcode() == BO_NE &&
2229 "Complex comparison other than == or != ?");
2230 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2234 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2237 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2238 bool Ignore = TestAndClearIgnoreResultAssign();
2243 switch (E->getLHS()->getType().getObjCLifetime()) {
2244 case Qualifiers::OCL_Strong:
2245 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2248 case Qualifiers::OCL_Autoreleasing:
2249 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2252 case Qualifiers::OCL_Weak:
2253 RHS = Visit(E->getRHS());
2254 LHS = EmitCheckedLValue(E->getLHS());
2255 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2258 // No reason to do any of these differently.
2259 case Qualifiers::OCL_None:
2260 case Qualifiers::OCL_ExplicitNone:
2261 // __block variables need to have the rhs evaluated first, plus
2262 // this should improve codegen just a little.
2263 RHS = Visit(E->getRHS());
2264 LHS = EmitCheckedLValue(E->getLHS());
2266 // Store the value into the LHS. Bit-fields are handled specially
2267 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2268 // 'An assignment expression has the value of the left operand after
2269 // the assignment...'.
2270 if (LHS.isBitField())
2271 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
2273 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
2276 // If the result is clearly ignored, return now.
2280 // The result of an assignment in C is the assigned r-value.
2281 if (!CGF.getContext().getLangOptions().CPlusPlus)
2284 // Objective-C property assignment never reloads the value following a store.
2285 if (LHS.isPropertyRef())
2288 // If the lvalue is non-volatile, return the computed value of the assignment.
2289 if (!LHS.isVolatileQualified())
2292 // Otherwise, reload the value.
2293 return EmitLoadOfLValue(LHS);
2296 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2297 const llvm::Type *ResTy = ConvertType(E->getType());
2299 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2300 // If we have 1 && X, just emit X without inserting the control flow.
2302 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2303 if (LHSCondVal) { // If we have 1 && X, just emit X.
2304 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2305 // ZExt result to int or bool.
2306 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
2309 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
2310 if (!CGF.ContainsLabel(E->getRHS()))
2311 return llvm::Constant::getNullValue(ResTy);
2314 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2315 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
2317 CodeGenFunction::ConditionalEvaluation eval(CGF);
2319 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2320 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2322 // Any edges into the ContBlock are now from an (indeterminate number of)
2323 // edges from this first condition. All of these values will be false. Start
2324 // setting up the PHI node in the Cont Block for this.
2325 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2327 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2329 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
2332 CGF.EmitBlock(RHSBlock);
2333 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2336 // Reaquire the RHS block, as there may be subblocks inserted.
2337 RHSBlock = Builder.GetInsertBlock();
2339 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2340 // into the phi node for the edge with the value of RHSCond.
2341 if (CGF.getDebugInfo())
2342 // There is no need to emit line number for unconditional branch.
2343 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
2344 CGF.EmitBlock(ContBlock);
2345 PN->addIncoming(RHSCond, RHSBlock);
2347 // ZExt result to int.
2348 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
2351 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
2352 const llvm::Type *ResTy = ConvertType(E->getType());
2354 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2355 // If we have 0 || X, just emit X without inserting the control flow.
2357 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2358 if (!LHSCondVal) { // If we have 0 || X, just emit X.
2359 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2360 // ZExt result to int or bool.
2361 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
2364 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
2365 if (!CGF.ContainsLabel(E->getRHS()))
2366 return llvm::ConstantInt::get(ResTy, 1);
2369 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2370 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
2372 CodeGenFunction::ConditionalEvaluation eval(CGF);
2374 // Branch on the LHS first. If it is true, go to the success (cont) block.
2375 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2377 // Any edges into the ContBlock are now from an (indeterminate number of)
2378 // edges from this first condition. All of these values will be true. Start
2379 // setting up the PHI node in the Cont Block for this.
2380 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
2382 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2384 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
2388 // Emit the RHS condition as a bool value.
2389 CGF.EmitBlock(RHSBlock);
2390 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2394 // Reaquire the RHS block, as there may be subblocks inserted.
2395 RHSBlock = Builder.GetInsertBlock();
2397 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2398 // into the phi node for the edge with the value of RHSCond.
2399 CGF.EmitBlock(ContBlock);
2400 PN->addIncoming(RHSCond, RHSBlock);
2402 // ZExt result to int.
2403 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
2406 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2407 CGF.EmitIgnoredExpr(E->getLHS());
2408 CGF.EnsureInsertPoint();
2409 return Visit(E->getRHS());
2412 //===----------------------------------------------------------------------===//
2414 //===----------------------------------------------------------------------===//
2416 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2417 /// expression is cheap enough and side-effect-free enough to evaluate
2418 /// unconditionally instead of conditionally. This is used to convert control
2419 /// flow into selects in some cases.
2420 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2421 CodeGenFunction &CGF) {
2422 E = E->IgnoreParens();
2424 // Anything that is an integer or floating point constant is fine.
2425 if (E->isConstantInitializer(CGF.getContext(), false))
2428 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2429 // X and Y are local variables.
2430 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2431 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2432 if (VD->hasLocalStorage() && !(CGF.getContext()
2433 .getCanonicalType(VD->getType())
2434 .isVolatileQualified()))
2441 Value *ScalarExprEmitter::
2442 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
2443 TestAndClearIgnoreResultAssign();
2445 // Bind the common expression if necessary.
2446 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2448 Expr *condExpr = E->getCond();
2449 Expr *lhsExpr = E->getTrueExpr();
2450 Expr *rhsExpr = E->getFalseExpr();
2452 // If the condition constant folds and can be elided, try to avoid emitting
2453 // the condition and the dead arm.
2455 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
2456 Expr *live = lhsExpr, *dead = rhsExpr;
2457 if (!CondExprBool) std::swap(live, dead);
2459 // If the dead side doesn't have labels we need, and if the Live side isn't
2460 // the gnu missing ?: extension (which we could handle, but don't bother
2461 // to), just emit the Live part.
2462 if (!CGF.ContainsLabel(dead))
2466 // OpenCL: If the condition is a vector, we can treat this condition like
2467 // the select function.
2468 if (CGF.getContext().getLangOptions().OpenCL
2469 && condExpr->getType()->isVectorType()) {
2470 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2471 llvm::Value *LHS = Visit(lhsExpr);
2472 llvm::Value *RHS = Visit(rhsExpr);
2474 const llvm::Type *condType = ConvertType(condExpr->getType());
2475 const llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2477 unsigned numElem = vecTy->getNumElements();
2478 const llvm::Type *elemType = vecTy->getElementType();
2480 std::vector<llvm::Constant*> Zvals;
2481 for (unsigned i = 0; i < numElem; ++i)
2482 Zvals.push_back(llvm::ConstantInt::get(elemType, 0));
2484 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2485 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2486 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2487 llvm::VectorType::get(elemType,
2490 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2492 // Cast float to int to perform ANDs if necessary.
2493 llvm::Value *RHSTmp = RHS;
2494 llvm::Value *LHSTmp = LHS;
2495 bool wasCast = false;
2496 const llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2497 if (rhsVTy->getElementType()->isFloatTy()) {
2498 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2499 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2503 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2504 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2505 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2507 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2512 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2513 // select instead of as control flow. We can only do this if it is cheap and
2514 // safe to evaluate the LHS and RHS unconditionally.
2515 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2516 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2517 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2518 llvm::Value *LHS = Visit(lhsExpr);
2519 llvm::Value *RHS = Visit(rhsExpr);
2520 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2523 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2524 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
2525 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
2527 CodeGenFunction::ConditionalEvaluation eval(CGF);
2528 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
2530 CGF.EmitBlock(LHSBlock);
2532 Value *LHS = Visit(lhsExpr);
2535 LHSBlock = Builder.GetInsertBlock();
2536 Builder.CreateBr(ContBlock);
2538 CGF.EmitBlock(RHSBlock);
2540 Value *RHS = Visit(rhsExpr);
2543 RHSBlock = Builder.GetInsertBlock();
2544 CGF.EmitBlock(ContBlock);
2546 // If the LHS or RHS is a throw expression, it will be legitimately null.
2552 // Create a PHI node for the real part.
2553 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
2554 PN->addIncoming(LHS, LHSBlock);
2555 PN->addIncoming(RHS, RHSBlock);
2559 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
2560 return Visit(E->getChosenSubExpr(CGF.getContext()));
2563 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
2564 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
2565 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2567 // If EmitVAArg fails, we fall back to the LLVM instruction.
2569 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2571 // FIXME Volatility.
2572 return Builder.CreateLoad(ArgPtr);
2575 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2576 return CGF.EmitBlockLiteral(block);
2579 Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2580 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
2581 const llvm::Type *DstTy = ConvertType(E->getType());
2583 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2584 // a shuffle vector instead of a bitcast.
2585 const llvm::Type *SrcTy = Src->getType();
2586 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2587 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2588 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2589 if ((numElementsDst == 3 && numElementsSrc == 4)
2590 || (numElementsDst == 4 && numElementsSrc == 3)) {
2593 // In the case of going from int4->float3, a bitcast is needed before
2595 const llvm::Type *srcElemTy =
2596 cast<llvm::VectorType>(SrcTy)->getElementType();
2597 const llvm::Type *dstElemTy =
2598 cast<llvm::VectorType>(DstTy)->getElementType();
2600 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
2601 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
2602 // Create a float type of the same size as the source or destination.
2603 const llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
2606 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
2609 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
2611 llvm::SmallVector<llvm::Constant*, 3> Args;
2612 Args.push_back(Builder.getInt32(0));
2613 Args.push_back(Builder.getInt32(1));
2614 Args.push_back(Builder.getInt32(2));
2616 if (numElementsDst == 4)
2617 Args.push_back(llvm::UndefValue::get(
2618 llvm::Type::getInt32Ty(CGF.getLLVMContext())));
2620 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
2622 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
2626 return Builder.CreateBitCast(Src, DstTy, "astype");
2629 //===----------------------------------------------------------------------===//
2630 // Entry Point into this File
2631 //===----------------------------------------------------------------------===//
2633 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
2634 /// type, ignoring the result.
2635 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
2636 assert(E && !hasAggregateLLVMType(E->getType()) &&
2637 "Invalid scalar expression to emit");
2639 if (isa<CXXDefaultArgExpr>(E))
2641 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
2642 .Visit(const_cast<Expr*>(E));
2643 if (isa<CXXDefaultArgExpr>(E))
2648 /// EmitScalarConversion - Emit a conversion from the specified type to the
2649 /// specified destination type, both of which are LLVM scalar types.
2650 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2652 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2653 "Invalid scalar expression to emit");
2654 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2657 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2658 /// type to the specified destination type, where the destination type is an
2659 /// LLVM scalar type.
2660 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2663 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
2664 "Invalid complex -> scalar conversion");
2665 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2670 llvm::Value *CodeGenFunction::
2671 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2672 bool isInc, bool isPre) {
2673 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2676 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2678 // object->isa or (*object).isa
2679 // Generate code as for: *(Class*)object
2680 // build Class* type
2681 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
2683 Expr *BaseExpr = E->getBase();
2684 if (BaseExpr->isRValue()) {
2685 V = CreateTempAlloca(ClassPtrTy, "resval");
2686 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2687 Builder.CreateStore(Src, V);
2688 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2689 MakeAddrLValue(V, E->getType()));
2692 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2694 V = EmitLValue(BaseExpr).getAddress();
2697 // build Class* type
2698 ClassPtrTy = ClassPtrTy->getPointerTo();
2699 V = Builder.CreateBitCast(V, ClassPtrTy);
2700 return MakeAddrLValue(V, E->getType());
2704 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
2705 const CompoundAssignOperator *E) {
2706 ScalarExprEmitter Scalar(*this);
2708 switch (E->getOpcode()) {
2709 #define COMPOUND_OP(Op) \
2710 case BO_##Op##Assign: \
2711 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
2747 assert(false && "Not valid compound assignment operators");
2751 llvm_unreachable("Unhandled compound assignment operator");