1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Frontend/CodeGenOptions.h"
15 #include "CodeGenFunction.h"
17 #include "CGObjCRuntime.h"
18 #include "CodeGenModule.h"
19 #include "CGDebugInfo.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/RecordLayout.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/GlobalVariable.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Module.h"
30 #include "llvm/Support/CFG.h"
31 #include "llvm/Target/TargetData.h"
34 using namespace clang;
35 using namespace CodeGen;
38 //===----------------------------------------------------------------------===//
39 // Scalar Expression Emitter
40 //===----------------------------------------------------------------------===//
46 QualType Ty; // Computation Type.
47 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
48 const Expr *E; // Entire expr, for error unsupported. May not be binop.
51 static bool MustVisitNullValue(const Expr *E) {
52 // If a null pointer expression's type is the C++0x nullptr_t, then
53 // it's not necessarily a simple constant and it must be evaluated
54 // for its potential side effects.
55 return E->getType()->isNullPtrType();
58 class ScalarExprEmitter
59 : public StmtVisitor<ScalarExprEmitter, Value*> {
62 bool IgnoreResultAssign;
63 llvm::LLVMContext &VMContext;
66 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
67 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
68 VMContext(cgf.getLLVMContext()) {
71 //===--------------------------------------------------------------------===//
73 //===--------------------------------------------------------------------===//
75 bool TestAndClearIgnoreResultAssign() {
76 bool I = IgnoreResultAssign;
77 IgnoreResultAssign = false;
81 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
82 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
83 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
85 Value *EmitLoadOfLValue(LValue LV, QualType T) {
86 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
89 /// EmitLoadOfLValue - Given an expression with complex type that represents a
90 /// value l-value, this method emits the address of the l-value, then loads
91 /// and returns the result.
92 Value *EmitLoadOfLValue(const Expr *E) {
93 return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType());
96 /// EmitConversionToBool - Convert the specified expression value to a
97 /// boolean (i1) truth value. This is equivalent to "Val != 0".
98 Value *EmitConversionToBool(Value *Src, QualType DstTy);
100 /// EmitScalarConversion - Emit a conversion from the specified type to the
101 /// specified destination type, both of which are LLVM scalar types.
102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
104 /// EmitComplexToScalarConversion - Emit a conversion from the specified
105 /// complex type to the specified destination type, where the destination type
106 /// is an LLVM scalar type.
107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
108 QualType SrcTy, QualType DstTy);
110 /// EmitNullValue - Emit a value that corresponds to null for the given type.
111 Value *EmitNullValue(QualType Ty);
113 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
114 Value *EmitFloatToBoolConversion(Value *V) {
115 // Compare against 0.0 for fp scalars.
116 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
117 return Builder.CreateFCmpUNE(V, Zero, "tobool");
120 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
121 Value *EmitPointerToBoolConversion(Value *V) {
122 Value *Zero = llvm::ConstantPointerNull::get(
123 cast<llvm::PointerType>(V->getType()));
124 return Builder.CreateICmpNE(V, Zero, "tobool");
127 Value *EmitIntToBoolConversion(Value *V) {
128 // Because of the type rules of C, we often end up computing a
129 // logical value, then zero extending it to int, then wanting it
130 // as a logical value again. Optimize this common case.
131 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
132 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
133 Value *Result = ZI->getOperand(0);
134 // If there aren't any more uses, zap the instruction to save space.
135 // Note that there can be more uses, for example if this
136 // is the result of an assignment.
138 ZI->eraseFromParent();
143 const llvm::IntegerType *Ty = cast<llvm::IntegerType>(V->getType());
144 Value *Zero = llvm::ConstantInt::get(Ty, 0);
145 return Builder.CreateICmpNE(V, Zero, "tobool");
148 //===--------------------------------------------------------------------===//
150 //===--------------------------------------------------------------------===//
152 Value *Visit(Expr *E) {
153 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
156 Value *VisitStmt(Stmt *S) {
157 S->dump(CGF.getContext().getSourceManager());
158 assert(0 && "Stmt can't have complex result type!");
161 Value *VisitExpr(Expr *S);
163 Value *VisitParenExpr(ParenExpr *PE) {
164 return Visit(PE->getSubExpr());
168 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
169 return llvm::ConstantInt::get(VMContext, E->getValue());
171 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
172 return llvm::ConstantFP::get(VMContext, E->getValue());
174 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
175 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
177 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
178 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
180 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
181 return EmitNullValue(E->getType());
183 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
184 return EmitNullValue(E->getType());
186 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
187 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
188 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
189 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
190 return Builder.CreateBitCast(V, ConvertType(E->getType()));
193 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
194 return llvm::ConstantInt::get(ConvertType(E->getType()),
198 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
200 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getType());
202 // Otherwise, assume the mapping is the scalar directly.
203 return CGF.getOpaqueRValueMapping(E).getScalarVal();
207 Value *VisitDeclRefExpr(DeclRefExpr *E) {
208 Expr::EvalResult Result;
209 if (!E->Evaluate(Result, CGF.getContext()))
210 return EmitLoadOfLValue(E);
212 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
215 if (Result.Val.isInt()) {
216 C = llvm::ConstantInt::get(VMContext, Result.Val.getInt());
217 } else if (Result.Val.isFloat()) {
218 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
220 return EmitLoadOfLValue(E);
223 // Make sure we emit a debug reference to the global variable.
224 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
225 if (!CGF.getContext().DeclMustBeEmitted(VD))
226 CGF.EmitDeclRefExprDbgValue(E, C);
227 } else if (isa<EnumConstantDecl>(E->getDecl())) {
228 CGF.EmitDeclRefExprDbgValue(E, C);
233 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
234 return CGF.EmitObjCSelectorExpr(E);
236 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
237 return CGF.EmitObjCProtocolExpr(E);
239 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
240 return EmitLoadOfLValue(E);
242 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
243 assert(E->getObjectKind() == OK_Ordinary &&
244 "reached property reference without lvalue-to-rvalue");
245 return EmitLoadOfLValue(E);
247 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
248 return CGF.EmitObjCMessageExpr(E).getScalarVal();
251 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
252 LValue LV = CGF.EmitObjCIsaExpr(E);
253 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
257 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
258 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
259 Value *VisitMemberExpr(MemberExpr *E);
260 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
261 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
262 return EmitLoadOfLValue(E);
265 Value *VisitInitListExpr(InitListExpr *E);
267 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
268 return CGF.CGM.EmitNullConstant(E->getType());
270 Value *VisitCastExpr(CastExpr *E) {
271 // Make sure to evaluate VLA bounds now so that we have them for later.
272 if (E->getType()->isVariablyModifiedType())
273 CGF.EmitVLASize(E->getType());
275 return EmitCastExpr(E);
277 Value *EmitCastExpr(CastExpr *E);
279 Value *VisitCallExpr(const CallExpr *E) {
280 if (E->getCallReturnType()->isReferenceType())
281 return EmitLoadOfLValue(E);
283 return CGF.EmitCallExpr(E).getScalarVal();
286 Value *VisitStmtExpr(const StmtExpr *E);
288 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
291 Value *VisitUnaryPostDec(const UnaryOperator *E) {
292 LValue LV = EmitLValue(E->getSubExpr());
293 return EmitScalarPrePostIncDec(E, LV, false, false);
295 Value *VisitUnaryPostInc(const UnaryOperator *E) {
296 LValue LV = EmitLValue(E->getSubExpr());
297 return EmitScalarPrePostIncDec(E, LV, true, false);
299 Value *VisitUnaryPreDec(const UnaryOperator *E) {
300 LValue LV = EmitLValue(E->getSubExpr());
301 return EmitScalarPrePostIncDec(E, LV, false, true);
303 Value *VisitUnaryPreInc(const UnaryOperator *E) {
304 LValue LV = EmitLValue(E->getSubExpr());
305 return EmitScalarPrePostIncDec(E, LV, true, true);
308 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
310 llvm::Value *NextVal,
313 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
314 bool isInc, bool isPre);
317 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
318 if (isa<MemberPointerType>(E->getType())) // never sugared
319 return CGF.CGM.getMemberPointerConstant(E);
321 return EmitLValue(E->getSubExpr()).getAddress();
323 Value *VisitUnaryDeref(const UnaryOperator *E) {
324 if (E->getType()->isVoidType())
325 return Visit(E->getSubExpr()); // the actual value should be unused
326 return EmitLoadOfLValue(E);
328 Value *VisitUnaryPlus(const UnaryOperator *E) {
329 // This differs from gcc, though, most likely due to a bug in gcc.
330 TestAndClearIgnoreResultAssign();
331 return Visit(E->getSubExpr());
333 Value *VisitUnaryMinus (const UnaryOperator *E);
334 Value *VisitUnaryNot (const UnaryOperator *E);
335 Value *VisitUnaryLNot (const UnaryOperator *E);
336 Value *VisitUnaryReal (const UnaryOperator *E);
337 Value *VisitUnaryImag (const UnaryOperator *E);
338 Value *VisitUnaryExtension(const UnaryOperator *E) {
339 return Visit(E->getSubExpr());
343 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
344 return Visit(DAE->getExpr());
346 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
347 return CGF.LoadCXXThis();
350 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
351 return CGF.EmitExprWithCleanups(E).getScalarVal();
353 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
354 return CGF.EmitCXXNewExpr(E);
356 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
357 CGF.EmitCXXDeleteExpr(E);
360 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
361 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
364 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
365 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
368 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
369 // C++ [expr.pseudo]p1:
370 // The result shall only be used as the operand for the function call
371 // operator (), and the result of such a call has type void. The only
372 // effect is the evaluation of the postfix-expression before the dot or
374 CGF.EmitScalarExpr(E->getBase());
378 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
379 return EmitNullValue(E->getType());
382 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
383 CGF.EmitCXXThrowExpr(E);
387 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
388 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
392 Value *EmitMul(const BinOpInfo &Ops) {
393 if (Ops.Ty->hasSignedIntegerRepresentation()) {
394 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
395 case LangOptions::SOB_Undefined:
396 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
397 case LangOptions::SOB_Defined:
398 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
399 case LangOptions::SOB_Trapping:
400 return EmitOverflowCheckedBinOp(Ops);
404 if (Ops.LHS->getType()->isFPOrFPVectorTy())
405 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
406 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
408 bool isTrapvOverflowBehavior() {
409 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
410 == LangOptions::SOB_Trapping;
412 /// Create a binary op that checks for overflow.
413 /// Currently only supports +, - and *.
414 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
415 // Emit the overflow BB when -ftrapv option is activated.
416 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
417 Builder.SetInsertPoint(overflowBB);
418 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
419 Builder.CreateCall(Trap);
420 Builder.CreateUnreachable();
422 // Check for undefined division and modulus behaviors.
423 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
424 llvm::Value *Zero,bool isDiv);
425 Value *EmitDiv(const BinOpInfo &Ops);
426 Value *EmitRem(const BinOpInfo &Ops);
427 Value *EmitAdd(const BinOpInfo &Ops);
428 Value *EmitSub(const BinOpInfo &Ops);
429 Value *EmitShl(const BinOpInfo &Ops);
430 Value *EmitShr(const BinOpInfo &Ops);
431 Value *EmitAnd(const BinOpInfo &Ops) {
432 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
434 Value *EmitXor(const BinOpInfo &Ops) {
435 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
437 Value *EmitOr (const BinOpInfo &Ops) {
438 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
441 BinOpInfo EmitBinOps(const BinaryOperator *E);
442 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
443 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
446 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
447 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
449 // Binary operators and binary compound assignment operators.
450 #define HANDLEBINOP(OP) \
451 Value *VisitBin ## OP(const BinaryOperator *E) { \
452 return Emit ## OP(EmitBinOps(E)); \
454 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
455 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
470 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
471 unsigned SICmpOpc, unsigned FCmpOpc);
472 #define VISITCOMP(CODE, UI, SI, FP) \
473 Value *VisitBin##CODE(const BinaryOperator *E) { \
474 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
475 llvm::FCmpInst::FP); }
476 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
477 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
478 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
479 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
480 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
481 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
484 Value *VisitBinAssign (const BinaryOperator *E);
486 Value *VisitBinLAnd (const BinaryOperator *E);
487 Value *VisitBinLOr (const BinaryOperator *E);
488 Value *VisitBinComma (const BinaryOperator *E);
490 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
491 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
494 Value *VisitBlockExpr(const BlockExpr *BE);
495 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
496 Value *VisitChooseExpr(ChooseExpr *CE);
497 Value *VisitVAArgExpr(VAArgExpr *VE);
498 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
499 return CGF.EmitObjCStringLiteral(E);
502 } // end anonymous namespace.
504 //===----------------------------------------------------------------------===//
506 //===----------------------------------------------------------------------===//
508 /// EmitConversionToBool - Convert the specified expression value to a
509 /// boolean (i1) truth value. This is equivalent to "Val != 0".
510 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
511 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
513 if (SrcType->isRealFloatingType())
514 return EmitFloatToBoolConversion(Src);
516 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
517 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
519 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
520 "Unknown scalar type to convert");
522 if (isa<llvm::IntegerType>(Src->getType()))
523 return EmitIntToBoolConversion(Src);
525 assert(isa<llvm::PointerType>(Src->getType()));
526 return EmitPointerToBoolConversion(Src);
529 /// EmitScalarConversion - Emit a conversion from the specified type to the
530 /// specified destination type, both of which are LLVM scalar types.
531 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
533 SrcType = CGF.getContext().getCanonicalType(SrcType);
534 DstType = CGF.getContext().getCanonicalType(DstType);
535 if (SrcType == DstType) return Src;
537 if (DstType->isVoidType()) return 0;
539 // Handle conversions to bool first, they are special: comparisons against 0.
540 if (DstType->isBooleanType())
541 return EmitConversionToBool(Src, SrcType);
543 const llvm::Type *DstTy = ConvertType(DstType);
545 // Ignore conversions like int -> uint.
546 if (Src->getType() == DstTy)
549 // Handle pointer conversions next: pointers can only be converted to/from
550 // other pointers and integers. Check for pointer types in terms of LLVM, as
551 // some native types (like Obj-C id) may map to a pointer type.
552 if (isa<llvm::PointerType>(DstTy)) {
553 // The source value may be an integer, or a pointer.
554 if (isa<llvm::PointerType>(Src->getType()))
555 return Builder.CreateBitCast(Src, DstTy, "conv");
557 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
558 // First, convert to the correct width so that we control the kind of
560 const llvm::Type *MiddleTy = CGF.IntPtrTy;
561 bool InputSigned = SrcType->isSignedIntegerType();
562 llvm::Value* IntResult =
563 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
564 // Then, cast to pointer.
565 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
568 if (isa<llvm::PointerType>(Src->getType())) {
569 // Must be an ptr to int cast.
570 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
571 return Builder.CreatePtrToInt(Src, DstTy, "conv");
574 // A scalar can be splatted to an extended vector of the same element type
575 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
576 // Cast the scalar to element type
577 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
578 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
580 // Insert the element in element zero of an undef vector
581 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
582 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
583 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
585 // Splat the element across to all elements
586 llvm::SmallVector<llvm::Constant*, 16> Args;
587 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
588 for (unsigned i = 0; i != NumElements; ++i)
589 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
591 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
592 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
596 // Allow bitcast from vector to integer/fp of the same size.
597 if (isa<llvm::VectorType>(Src->getType()) ||
598 isa<llvm::VectorType>(DstTy))
599 return Builder.CreateBitCast(Src, DstTy, "conv");
601 // Finally, we have the arithmetic types: real int/float.
602 if (isa<llvm::IntegerType>(Src->getType())) {
603 bool InputSigned = SrcType->isSignedIntegerType();
604 if (isa<llvm::IntegerType>(DstTy))
605 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
606 else if (InputSigned)
607 return Builder.CreateSIToFP(Src, DstTy, "conv");
609 return Builder.CreateUIToFP(Src, DstTy, "conv");
612 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
613 if (isa<llvm::IntegerType>(DstTy)) {
614 if (DstType->isSignedIntegerType())
615 return Builder.CreateFPToSI(Src, DstTy, "conv");
617 return Builder.CreateFPToUI(Src, DstTy, "conv");
620 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
621 if (DstTy->getTypeID() < Src->getType()->getTypeID())
622 return Builder.CreateFPTrunc(Src, DstTy, "conv");
624 return Builder.CreateFPExt(Src, DstTy, "conv");
627 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
628 /// type to the specified destination type, where the destination type is an
629 /// LLVM scalar type.
630 Value *ScalarExprEmitter::
631 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
632 QualType SrcTy, QualType DstTy) {
633 // Get the source element type.
634 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
636 // Handle conversions to bool first, they are special: comparisons against 0.
637 if (DstTy->isBooleanType()) {
638 // Complex != 0 -> (Real != 0) | (Imag != 0)
639 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
640 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
641 return Builder.CreateOr(Src.first, Src.second, "tobool");
644 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
645 // the imaginary part of the complex value is discarded and the value of the
646 // real part is converted according to the conversion rules for the
647 // corresponding real type.
648 return EmitScalarConversion(Src.first, SrcTy, DstTy);
651 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
652 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
653 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
655 return llvm::Constant::getNullValue(ConvertType(Ty));
658 //===----------------------------------------------------------------------===//
660 //===----------------------------------------------------------------------===//
662 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
663 CGF.ErrorUnsupported(E, "scalar expression");
664 if (E->getType()->isVoidType())
666 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
669 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
671 if (E->getNumSubExprs() == 2 ||
672 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
673 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
674 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
677 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
678 unsigned LHSElts = LTy->getNumElements();
680 if (E->getNumSubExprs() == 3) {
681 Mask = CGF.EmitScalarExpr(E->getExpr(2));
683 // Shuffle LHS & RHS into one input vector.
684 llvm::SmallVector<llvm::Constant*, 32> concat;
685 for (unsigned i = 0; i != LHSElts; ++i) {
686 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i));
687 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1));
690 Value* CV = llvm::ConstantVector::get(concat);
691 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
697 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
698 llvm::Constant* EltMask;
700 // Treat vec3 like vec4.
701 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
702 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
703 (1 << llvm::Log2_32(LHSElts+2))-1);
704 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
705 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
706 (1 << llvm::Log2_32(LHSElts+1))-1);
708 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
709 (1 << llvm::Log2_32(LHSElts))-1);
711 // Mask off the high bits of each shuffle index.
712 llvm::SmallVector<llvm::Constant *, 32> MaskV;
713 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
714 MaskV.push_back(EltMask);
716 Value* MaskBits = llvm::ConstantVector::get(MaskV);
717 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
720 // mask = mask & maskbits
722 // n = extract mask i
724 // newv = insert newv, x, i
725 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
726 MTy->getNumElements());
727 Value* NewV = llvm::UndefValue::get(RTy);
728 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
729 Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i);
730 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
731 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
733 // Handle vec3 special since the index will be off by one for the RHS.
734 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
735 Value *cmpIndx, *newIndx;
736 cmpIndx = Builder.CreateICmpUGT(Indx,
737 llvm::ConstantInt::get(CGF.Int32Ty, 3),
739 newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1),
741 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
743 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
744 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
749 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
750 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
752 // Handle vec3 special since the index will be off by one for the RHS.
753 llvm::SmallVector<llvm::Constant*, 32> indices;
754 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
755 llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
756 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
757 if (VTy->getNumElements() == 3) {
758 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
759 uint64_t cVal = CI->getZExtValue();
761 C = llvm::ConstantInt::get(C->getType(), cVal-1);
765 indices.push_back(C);
768 Value *SV = llvm::ConstantVector::get(indices);
769 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
771 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
772 Expr::EvalResult Result;
773 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
775 CGF.EmitScalarExpr(E->getBase());
777 EmitLValue(E->getBase());
778 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
781 // Emit debug info for aggregate now, if it was delayed to reduce
783 CGDebugInfo *DI = CGF.getDebugInfo();
784 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
785 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
786 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
787 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
788 DI->getOrCreateRecordType(PTy->getPointeeType(),
789 M->getParent()->getLocation());
791 return EmitLoadOfLValue(E);
794 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
795 TestAndClearIgnoreResultAssign();
797 // Emit subscript expressions in rvalue context's. For most cases, this just
798 // loads the lvalue formed by the subscript expr. However, we have to be
799 // careful, because the base of a vector subscript is occasionally an rvalue,
800 // so we can't get it as an lvalue.
801 if (!E->getBase()->getType()->isVectorType())
802 return EmitLoadOfLValue(E);
804 // Handle the vector case. The base must be a vector, the index must be an
806 Value *Base = Visit(E->getBase());
807 Value *Idx = Visit(E->getIdx());
808 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
809 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
810 return Builder.CreateExtractElement(Base, Idx, "vecext");
813 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
814 unsigned Off, const llvm::Type *I32Ty) {
815 int MV = SVI->getMaskValue(Idx);
817 return llvm::UndefValue::get(I32Ty);
818 return llvm::ConstantInt::get(I32Ty, Off+MV);
821 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
822 bool Ignore = TestAndClearIgnoreResultAssign();
824 assert (Ignore == false && "init list ignored");
825 unsigned NumInitElements = E->getNumInits();
827 if (E->hadArrayRangeDesignator())
828 CGF.ErrorUnsupported(E, "GNU array range designator extension");
830 const llvm::VectorType *VType =
831 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
833 // We have a scalar in braces. Just use the first element.
835 return Visit(E->getInit(0));
837 unsigned ResElts = VType->getNumElements();
839 // Loop over initializers collecting the Value for each, and remembering
840 // whether the source was swizzle (ExtVectorElementExpr). This will allow
841 // us to fold the shuffle for the swizzle into the shuffle for the vector
842 // initializer, since LLVM optimizers generally do not want to touch
845 bool VIsUndefShuffle = false;
846 llvm::Value *V = llvm::UndefValue::get(VType);
847 for (unsigned i = 0; i != NumInitElements; ++i) {
848 Expr *IE = E->getInit(i);
849 Value *Init = Visit(IE);
850 llvm::SmallVector<llvm::Constant*, 16> Args;
852 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
854 // Handle scalar elements. If the scalar initializer is actually one
855 // element of a different vector of the same width, use shuffle instead of
858 if (isa<ExtVectorElementExpr>(IE)) {
859 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
861 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
862 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
863 Value *LHS = 0, *RHS = 0;
865 // insert into undef -> shuffle (src, undef)
867 for (unsigned j = 1; j != ResElts; ++j)
868 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
870 LHS = EI->getVectorOperand();
872 VIsUndefShuffle = true;
873 } else if (VIsUndefShuffle) {
874 // insert into undefshuffle && size match -> shuffle (v, src)
875 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
876 for (unsigned j = 0; j != CurIdx; ++j)
877 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
878 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
879 ResElts + C->getZExtValue()));
880 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
881 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
883 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
884 RHS = EI->getVectorOperand();
885 VIsUndefShuffle = false;
888 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
889 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
895 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
896 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
897 VIsUndefShuffle = false;
902 unsigned InitElts = VVT->getNumElements();
904 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
905 // input is the same width as the vector being constructed, generate an
906 // optimized shuffle of the swizzle input into the result.
907 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
908 if (isa<ExtVectorElementExpr>(IE)) {
909 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
910 Value *SVOp = SVI->getOperand(0);
911 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
913 if (OpTy->getNumElements() == ResElts) {
914 for (unsigned j = 0; j != CurIdx; ++j) {
915 // If the current vector initializer is a shuffle with undef, merge
916 // this shuffle directly into it.
917 if (VIsUndefShuffle) {
918 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
921 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
924 for (unsigned j = 0, je = InitElts; j != je; ++j)
925 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
926 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
927 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
930 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
936 // Extend init to result vector length, and then shuffle its contribution
937 // to the vector initializer into V.
939 for (unsigned j = 0; j != InitElts; ++j)
940 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
941 for (unsigned j = InitElts; j != ResElts; ++j)
942 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
943 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
944 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
948 for (unsigned j = 0; j != CurIdx; ++j)
949 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
950 for (unsigned j = 0; j != InitElts; ++j)
951 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset));
952 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
953 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
956 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
957 // merging subsequent shuffles into this one.
960 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
961 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
962 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
966 // FIXME: evaluate codegen vs. shuffling against constant null vector.
967 // Emit remaining default initializers.
968 const llvm::Type *EltTy = VType->getElementType();
970 // Emit remaining default initializers
971 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
972 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
973 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
974 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
979 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
980 const Expr *E = CE->getSubExpr();
982 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
985 if (isa<CXXThisExpr>(E)) {
986 // We always assume that 'this' is never null.
990 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
991 // And that glvalue casts are never null.
992 if (ICE->getValueKind() != VK_RValue)
999 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1000 // have to handle a more broad range of conversions than explicit casts, as they
1001 // handle things like function to ptr-to-function decay etc.
1002 Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
1003 Expr *E = CE->getSubExpr();
1004 QualType DestTy = CE->getType();
1005 CastKind Kind = CE->getCastKind();
1007 if (!DestTy->isVoidType())
1008 TestAndClearIgnoreResultAssign();
1010 // Since almost all cast kinds apply to scalars, this switch doesn't have
1011 // a default case, so the compiler will warn on a missing case. The cases
1012 // are in the same order as in the CastKind enum.
1014 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1016 case CK_LValueBitCast:
1017 case CK_ObjCObjectLValueCast: {
1018 Value *V = EmitLValue(E).getAddress();
1019 V = Builder.CreateBitCast(V,
1020 ConvertType(CGF.getContext().getPointerType(DestTy)));
1021 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy);
1024 case CK_AnyPointerToObjCPointerCast:
1025 case CK_AnyPointerToBlockPointerCast:
1027 Value *Src = Visit(const_cast<Expr*>(E));
1028 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1031 case CK_UserDefinedConversion:
1032 return Visit(const_cast<Expr*>(E));
1034 case CK_BaseToDerived: {
1035 const CXXRecordDecl *DerivedClassDecl =
1036 DestTy->getCXXRecordDeclForPointerType();
1038 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
1039 CE->path_begin(), CE->path_end(),
1040 ShouldNullCheckClassCastValue(CE));
1042 case CK_UncheckedDerivedToBase:
1043 case CK_DerivedToBase: {
1044 const RecordType *DerivedClassTy =
1045 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1046 CXXRecordDecl *DerivedClassDecl =
1047 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1049 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
1050 CE->path_begin(), CE->path_end(),
1051 ShouldNullCheckClassCastValue(CE));
1054 Value *V = Visit(const_cast<Expr*>(E));
1055 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1056 return CGF.EmitDynamicCast(V, DCE);
1059 case CK_ArrayToPointerDecay: {
1060 assert(E->getType()->isArrayType() &&
1061 "Array to pointer decay must have array source type!");
1063 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1065 // Note that VLA pointers are always decayed, so we don't need to do
1067 if (!E->getType()->isVariableArrayType()) {
1068 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1069 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1070 ->getElementType()) &&
1071 "Expected pointer to array");
1072 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1077 case CK_FunctionToPointerDecay:
1078 return EmitLValue(E).getAddress();
1080 case CK_NullToPointer:
1081 if (MustVisitNullValue(E))
1084 return llvm::ConstantPointerNull::get(
1085 cast<llvm::PointerType>(ConvertType(DestTy)));
1087 case CK_NullToMemberPointer: {
1088 if (MustVisitNullValue(E))
1091 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1092 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1095 case CK_BaseToDerivedMemberPointer:
1096 case CK_DerivedToBaseMemberPointer: {
1097 Value *Src = Visit(E);
1099 // Note that the AST doesn't distinguish between checked and
1100 // unchecked member pointer conversions, so we always have to
1101 // implement checked conversions here. This is inefficient when
1102 // actual control flow may be required in order to perform the
1103 // check, which it is for data member pointers (but not member
1104 // function pointers on Itanium and ARM).
1105 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1108 case CK_FloatingRealToComplex:
1109 case CK_FloatingComplexCast:
1110 case CK_IntegralRealToComplex:
1111 case CK_IntegralComplexCast:
1112 case CK_IntegralComplexToFloatingComplex:
1113 case CK_FloatingComplexToIntegralComplex:
1114 case CK_ConstructorConversion:
1116 llvm_unreachable("scalar cast to non-scalar value");
1119 case CK_GetObjCProperty: {
1120 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1121 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty &&
1122 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
1123 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType());
1124 return RV.getScalarVal();
1127 case CK_LValueToRValue:
1128 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
1129 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
1130 return Visit(const_cast<Expr*>(E));
1132 case CK_IntegralToPointer: {
1133 Value *Src = Visit(const_cast<Expr*>(E));
1135 // First, convert to the correct width so that we control the kind of
1137 const llvm::Type *MiddleTy = CGF.IntPtrTy;
1138 bool InputSigned = E->getType()->isSignedIntegerType();
1139 llvm::Value* IntResult =
1140 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1142 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1144 case CK_PointerToIntegral: {
1145 Value *Src = Visit(const_cast<Expr*>(E));
1147 // Handle conversion to bool correctly.
1148 if (DestTy->isBooleanType())
1149 return EmitScalarConversion(Src, E->getType(), DestTy);
1151 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1154 CGF.EmitIgnoredExpr(E);
1157 case CK_VectorSplat: {
1158 const llvm::Type *DstTy = ConvertType(DestTy);
1159 Value *Elt = Visit(const_cast<Expr*>(E));
1161 // Insert the element in element zero of an undef vector
1162 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
1163 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
1164 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1166 // Splat the element across to all elements
1167 llvm::SmallVector<llvm::Constant*, 16> Args;
1168 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1169 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Int32Ty, 0);
1170 for (unsigned i = 0; i < NumElements; i++)
1171 Args.push_back(Zero);
1173 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
1174 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1178 case CK_IntegralCast:
1179 case CK_IntegralToFloating:
1180 case CK_FloatingToIntegral:
1181 case CK_FloatingCast:
1182 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1184 case CK_IntegralToBoolean:
1185 return EmitIntToBoolConversion(Visit(E));
1186 case CK_PointerToBoolean:
1187 return EmitPointerToBoolConversion(Visit(E));
1188 case CK_FloatingToBoolean:
1189 return EmitFloatToBoolConversion(Visit(E));
1190 case CK_MemberPointerToBoolean: {
1191 llvm::Value *MemPtr = Visit(E);
1192 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1193 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1196 case CK_FloatingComplexToReal:
1197 case CK_IntegralComplexToReal:
1198 return CGF.EmitComplexExpr(E, false, true).first;
1200 case CK_FloatingComplexToBoolean:
1201 case CK_IntegralComplexToBoolean: {
1202 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
1204 // TODO: kill this function off, inline appropriate case here
1205 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1210 llvm_unreachable("unknown scalar cast");
1214 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1215 CodeGenFunction::StmtExprEvaluation eval(CGF);
1216 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1220 Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
1221 llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
1222 if (E->getType().isObjCGCWeak())
1223 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
1224 return CGF.EmitLoadOfScalar(V, false, 0, E->getType());
1227 //===----------------------------------------------------------------------===//
1229 //===----------------------------------------------------------------------===//
1231 llvm::Value *ScalarExprEmitter::
1232 EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1234 llvm::Value *NextVal, bool IsInc) {
1235 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1236 case LangOptions::SOB_Undefined:
1237 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1239 case LangOptions::SOB_Defined:
1240 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1242 case LangOptions::SOB_Trapping:
1245 BinOp.RHS = NextVal;
1246 BinOp.Ty = E->getType();
1247 BinOp.Opcode = BO_Add;
1249 return EmitOverflowCheckedBinOp(BinOp);
1252 assert(false && "Unknown SignedOverflowBehaviorTy");
1257 ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1258 bool isInc, bool isPre) {
1260 QualType type = E->getSubExpr()->getType();
1261 llvm::Value *value = EmitLoadOfLValue(LV, type);
1262 llvm::Value *input = value;
1264 int amount = (isInc ? 1 : -1);
1266 // Special case of integer increment that we have to check first: bool++.
1267 // Due to promotion rules, we get:
1268 // bool++ -> bool = bool + 1
1269 // -> bool = (int)bool + 1
1270 // -> bool = ((int)bool + 1 != 0)
1271 // An interesting aspect of this is that increment is always true.
1272 // Decrement does not have this property.
1273 if (isInc && type->isBooleanType()) {
1274 value = Builder.getTrue();
1276 // Most common case by far: integer increment.
1277 } else if (type->isIntegerType()) {
1279 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1281 if (type->isSignedIntegerType())
1282 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1284 // Unsigned integer inc is always two's complement.
1286 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1288 // Next most common: pointer increment.
1289 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1290 QualType type = ptr->getPointeeType();
1292 // VLA types don't have constant size.
1293 if (type->isVariableArrayType()) {
1294 llvm::Value *vlaSize =
1295 CGF.GetVLASize(CGF.getContext().getAsVariableArrayType(type));
1296 value = CGF.EmitCastToVoidPtr(value);
1297 if (!isInc) vlaSize = Builder.CreateNSWNeg(vlaSize, "vla.negsize");
1298 value = Builder.CreateInBoundsGEP(value, vlaSize, "vla.inc");
1299 value = Builder.CreateBitCast(value, input->getType());
1301 // Arithmetic on function pointers (!) is just +-1.
1302 } else if (type->isFunctionType()) {
1303 llvm::Value *amt = llvm::ConstantInt::get(CGF.Int32Ty, amount);
1305 value = CGF.EmitCastToVoidPtr(value);
1306 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1307 value = Builder.CreateBitCast(value, input->getType());
1309 // For everything else, we can just do a simple increment.
1311 llvm::Value *amt = llvm::ConstantInt::get(CGF.Int32Ty, amount);
1312 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1315 // Vector increment/decrement.
1316 } else if (type->isVectorType()) {
1317 if (type->hasIntegerRepresentation()) {
1318 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1320 if (type->hasSignedIntegerRepresentation())
1321 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1323 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1325 value = Builder.CreateFAdd(
1327 llvm::ConstantFP::get(value->getType(), amount),
1328 isInc ? "inc" : "dec");
1332 } else if (type->isRealFloatingType()) {
1333 // Add the inc/dec to the real part.
1335 if (value->getType()->isFloatTy())
1336 amt = llvm::ConstantFP::get(VMContext,
1337 llvm::APFloat(static_cast<float>(amount)));
1338 else if (value->getType()->isDoubleTy())
1339 amt = llvm::ConstantFP::get(VMContext,
1340 llvm::APFloat(static_cast<double>(amount)));
1342 llvm::APFloat F(static_cast<float>(amount));
1344 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1346 amt = llvm::ConstantFP::get(VMContext, F);
1348 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1350 // Objective-C pointer types.
1352 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1353 value = CGF.EmitCastToVoidPtr(value);
1355 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1356 if (!isInc) size = -size;
1357 llvm::Value *sizeValue =
1358 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1360 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1361 value = Builder.CreateBitCast(value, input->getType());
1364 // Store the updated result through the lvalue.
1365 if (LV.isBitField())
1366 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, type, &value);
1368 CGF.EmitStoreThroughLValue(RValue::get(value), LV, type);
1370 // If this is a postinc, return the value read from memory, otherwise use the
1372 return isPre ? value : input;
1377 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1378 TestAndClearIgnoreResultAssign();
1379 // Emit unary minus with EmitSub so we handle overflow cases etc.
1381 BinOp.RHS = Visit(E->getSubExpr());
1383 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1384 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1386 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1387 BinOp.Ty = E->getType();
1388 BinOp.Opcode = BO_Sub;
1390 return EmitSub(BinOp);
1393 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1394 TestAndClearIgnoreResultAssign();
1395 Value *Op = Visit(E->getSubExpr());
1396 return Builder.CreateNot(Op, "neg");
1399 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1400 // Compare operand to zero.
1401 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1404 // TODO: Could dynamically modify easy computations here. For example, if
1405 // the operand is an icmp ne, turn into icmp eq.
1406 BoolVal = Builder.CreateNot(BoolVal, "lnot");
1408 // ZExt result to the expr type.
1409 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1412 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1413 // Try folding the offsetof to a constant.
1414 Expr::EvalResult EvalResult;
1415 if (E->Evaluate(EvalResult, CGF.getContext()))
1416 return llvm::ConstantInt::get(VMContext, EvalResult.Val.getInt());
1418 // Loop over the components of the offsetof to compute the value.
1419 unsigned n = E->getNumComponents();
1420 const llvm::Type* ResultType = ConvertType(E->getType());
1421 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1422 QualType CurrentType = E->getTypeSourceInfo()->getType();
1423 for (unsigned i = 0; i != n; ++i) {
1424 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1425 llvm::Value *Offset = 0;
1426 switch (ON.getKind()) {
1427 case OffsetOfExpr::OffsetOfNode::Array: {
1428 // Compute the index
1429 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1430 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1431 bool IdxSigned = IdxExpr->getType()->isSignedIntegerType();
1432 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1434 // Save the element type
1436 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1438 // Compute the element size
1439 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1440 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1442 // Multiply out to compute the result
1443 Offset = Builder.CreateMul(Idx, ElemSize);
1447 case OffsetOfExpr::OffsetOfNode::Field: {
1448 FieldDecl *MemberDecl = ON.getField();
1449 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1450 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1452 // Compute the index of the field in its parent.
1454 // FIXME: It would be nice if we didn't have to loop here!
1455 for (RecordDecl::field_iterator Field = RD->field_begin(),
1456 FieldEnd = RD->field_end();
1457 Field != FieldEnd; (void)++Field, ++i) {
1458 if (*Field == MemberDecl)
1461 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1463 // Compute the offset to the field
1464 int64_t OffsetInt = RL.getFieldOffset(i) /
1465 CGF.getContext().getCharWidth();
1466 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1468 // Save the element type.
1469 CurrentType = MemberDecl->getType();
1473 case OffsetOfExpr::OffsetOfNode::Identifier:
1474 llvm_unreachable("dependent __builtin_offsetof");
1476 case OffsetOfExpr::OffsetOfNode::Base: {
1477 if (ON.getBase()->isVirtual()) {
1478 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1482 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1483 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1485 // Save the element type.
1486 CurrentType = ON.getBase()->getType();
1488 // Compute the offset to the base.
1489 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1490 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1491 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
1492 CGF.getContext().getCharWidth();
1493 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1497 Result = Builder.CreateAdd(Result, Offset);
1502 /// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1503 /// argument of the sizeof expression as an integer.
1505 ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1506 QualType TypeToSize = E->getTypeOfArgument();
1507 if (E->isSizeOf()) {
1508 if (const VariableArrayType *VAT =
1509 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1510 if (E->isArgumentType()) {
1511 // sizeof(type) - make sure to emit the VLA size.
1512 CGF.EmitVLASize(TypeToSize);
1514 // C99 6.5.3.4p2: If the argument is an expression of type
1515 // VLA, it is evaluated.
1516 CGF.EmitIgnoredExpr(E->getArgumentExpr());
1519 return CGF.GetVLASize(VAT);
1523 // If this isn't sizeof(vla), the result must be constant; use the constant
1524 // folding logic so we don't have to duplicate it here.
1525 Expr::EvalResult Result;
1526 E->Evaluate(Result, CGF.getContext());
1527 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
1530 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1531 Expr *Op = E->getSubExpr();
1532 if (Op->getType()->isAnyComplexType()) {
1533 // If it's an l-value, load through the appropriate subobject l-value.
1534 // Note that we have to ask E because Op might be an l-value that
1535 // this won't work for, e.g. an Obj-C property.
1537 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1540 // Otherwise, calculate and project.
1541 return CGF.EmitComplexExpr(Op, false, true).first;
1547 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1548 Expr *Op = E->getSubExpr();
1549 if (Op->getType()->isAnyComplexType()) {
1550 // If it's an l-value, load through the appropriate subobject l-value.
1551 // Note that we have to ask E because Op might be an l-value that
1552 // this won't work for, e.g. an Obj-C property.
1553 if (Op->isGLValue())
1554 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1557 // Otherwise, calculate and project.
1558 return CGF.EmitComplexExpr(Op, true, false).second;
1561 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1562 // effects are evaluated, but not the actual value.
1563 CGF.EmitScalarExpr(Op, true);
1564 return llvm::Constant::getNullValue(ConvertType(E->getType()));
1567 //===----------------------------------------------------------------------===//
1569 //===----------------------------------------------------------------------===//
1571 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1572 TestAndClearIgnoreResultAssign();
1574 Result.LHS = Visit(E->getLHS());
1575 Result.RHS = Visit(E->getRHS());
1576 Result.Ty = E->getType();
1577 Result.Opcode = E->getOpcode();
1582 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1583 const CompoundAssignOperator *E,
1584 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1586 QualType LHSTy = E->getLHS()->getType();
1589 if (E->getComputationResultType()->isAnyComplexType()) {
1590 // This needs to go through the complex expression emitter, but it's a tad
1591 // complicated to do that... I'm leaving it out for now. (Note that we do
1592 // actually need the imaginary part of the RHS for multiplication and
1594 CGF.ErrorUnsupported(E, "complex compound assignment");
1595 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1599 // Emit the RHS first. __block variables need to have the rhs evaluated
1600 // first, plus this should improve codegen a little.
1601 OpInfo.RHS = Visit(E->getRHS());
1602 OpInfo.Ty = E->getComputationResultType();
1603 OpInfo.Opcode = E->getOpcode();
1605 // Load/convert the LHS.
1606 LValue LHSLV = EmitCheckedLValue(E->getLHS());
1607 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
1608 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1609 E->getComputationLHSType());
1611 // Expand the binary operator.
1612 Result = (this->*Func)(OpInfo);
1614 // Convert the result back to the LHS type.
1615 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1617 // Store the result value into the LHS lvalue. Bit-fields are handled
1618 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1619 // 'An assignment expression has the value of the left operand after the
1621 if (LHSLV.isBitField())
1622 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1625 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
1630 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1631 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1632 bool Ignore = TestAndClearIgnoreResultAssign();
1634 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1636 // If the result is clearly ignored, return now.
1640 // The result of an assignment in C is the assigned r-value.
1641 if (!CGF.getContext().getLangOptions().CPlusPlus)
1644 // Objective-C property assignment never reloads the value following a store.
1645 if (LHS.isPropertyRef())
1648 // If the lvalue is non-volatile, return the computed value of the assignment.
1649 if (!LHS.isVolatileQualified())
1652 // Otherwise, reload the value.
1653 return EmitLoadOfLValue(LHS, E->getType());
1656 void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1657 const BinOpInfo &Ops,
1658 llvm::Value *Zero, bool isDiv) {
1659 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1660 llvm::BasicBlock *contBB =
1661 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn);
1663 const llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1665 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1666 llvm::Value *IntMin =
1667 llvm::ConstantInt::get(VMContext,
1668 llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1669 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1671 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1672 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1673 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1674 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1675 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1676 overflowBB, contBB);
1678 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1679 overflowBB, contBB);
1681 EmitOverflowBB(overflowBB);
1682 Builder.SetInsertPoint(contBB);
1685 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1686 if (isTrapvOverflowBehavior()) {
1687 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1689 if (Ops.Ty->isIntegerType())
1690 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1691 else if (Ops.Ty->isRealFloatingType()) {
1692 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1694 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn);
1695 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1696 overflowBB, DivCont);
1697 EmitOverflowBB(overflowBB);
1698 Builder.SetInsertPoint(DivCont);
1701 if (Ops.LHS->getType()->isFPOrFPVectorTy())
1702 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1703 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
1704 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1706 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1709 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1710 // Rem in C can't be a floating point type: C99 6.5.5p2.
1711 if (isTrapvOverflowBehavior()) {
1712 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1714 if (Ops.Ty->isIntegerType())
1715 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1718 if (Ops.Ty->isUnsignedIntegerType())
1719 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1721 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1724 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1728 switch (Ops.Opcode) {
1732 IID = llvm::Intrinsic::sadd_with_overflow;
1737 IID = llvm::Intrinsic::ssub_with_overflow;
1742 IID = llvm::Intrinsic::smul_with_overflow;
1745 assert(false && "Unsupported operation for overflow detection");
1751 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1753 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1755 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1756 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1757 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1759 // Branch in case of overflow.
1760 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1761 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1762 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
1764 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1766 // Handle overflow with llvm.trap.
1767 const std::string *handlerName =
1768 &CGF.getContext().getLangOptions().OverflowHandler;
1769 if (handlerName->empty()) {
1770 EmitOverflowBB(overflowBB);
1771 Builder.SetInsertPoint(continueBB);
1775 // If an overflow handler is set, then we want to call it and then use its
1776 // result, if it returns.
1777 Builder.SetInsertPoint(overflowBB);
1779 // Get the overflow handler.
1780 const llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
1781 std::vector<const llvm::Type*> argTypes;
1782 argTypes.push_back(CGF.Int64Ty); argTypes.push_back(CGF.Int64Ty);
1783 argTypes.push_back(Int8Ty); argTypes.push_back(Int8Ty);
1784 llvm::FunctionType *handlerTy =
1785 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1786 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1788 // Sign extend the args to 64-bit, so that we can use the same handler for
1789 // all types of overflow.
1790 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1791 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1793 // Call the handler with the two arguments, the operation, and the size of
1795 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1796 Builder.getInt8(OpID),
1797 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1799 // Truncate the result back to the desired size.
1800 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1801 Builder.CreateBr(continueBB);
1803 Builder.SetInsertPoint(continueBB);
1804 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1805 phi->reserveOperandSpace(2);
1806 phi->addIncoming(result, initialBB);
1807 phi->addIncoming(handlerResult, overflowBB);
1812 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
1813 if (!Ops.Ty->isAnyPointerType()) {
1814 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1815 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1816 case LangOptions::SOB_Undefined:
1817 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1818 case LangOptions::SOB_Defined:
1819 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1820 case LangOptions::SOB_Trapping:
1821 return EmitOverflowCheckedBinOp(Ops);
1825 if (Ops.LHS->getType()->isFPOrFPVectorTy())
1826 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1828 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1831 // Must have binary (not unary) expr here. Unary pointer decrement doesn't
1833 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1835 if (Ops.Ty->isPointerType() &&
1836 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
1837 // The amount of the addition needs to account for the VLA size
1838 CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
1843 const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
1844 const ObjCObjectPointerType *OPT =
1845 BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
1849 IdxExp = BinOp->getRHS();
1850 } else { // int + pointer
1851 PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1852 OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
1853 assert((PT || OPT) && "Invalid add expr");
1856 IdxExp = BinOp->getLHS();
1859 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1860 if (Width < CGF.PointerWidthInBits) {
1861 // Zero or sign extend the pointer value based on whether the index is
1863 const llvm::Type *IdxType = CGF.IntPtrTy;
1864 if (IdxExp->getType()->isSignedIntegerType())
1865 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1867 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1869 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
1870 // Handle interface types, which are not represented with a concrete type.
1871 if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
1872 llvm::Value *InterfaceSize =
1873 llvm::ConstantInt::get(Idx->getType(),
1874 CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
1875 Idx = Builder.CreateMul(Idx, InterfaceSize);
1876 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1877 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1878 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1879 return Builder.CreateBitCast(Res, Ptr->getType());
1882 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1883 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1885 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1886 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1887 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1888 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1889 return Builder.CreateBitCast(Res, Ptr->getType());
1892 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
1895 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
1896 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
1897 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1898 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1899 case LangOptions::SOB_Undefined:
1900 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1901 case LangOptions::SOB_Defined:
1902 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1903 case LangOptions::SOB_Trapping:
1904 return EmitOverflowCheckedBinOp(Ops);
1908 if (Ops.LHS->getType()->isFPOrFPVectorTy())
1909 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
1911 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1914 // Must have binary (not unary) expr here. Unary pointer increment doesn't
1916 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1918 if (BinOp->getLHS()->getType()->isPointerType() &&
1919 BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
1920 // The amount of the addition needs to account for the VLA size for
1922 // The amount of the division needs to account for the VLA size for
1924 CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
1927 const QualType LHSType = BinOp->getLHS()->getType();
1928 const QualType LHSElementType = LHSType->getPointeeType();
1929 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1931 Value *Idx = Ops.RHS;
1932 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1933 if (Width < CGF.PointerWidthInBits) {
1934 // Zero or sign extend the pointer value based on whether the index is
1936 const llvm::Type *IdxType = CGF.IntPtrTy;
1937 if (BinOp->getRHS()->getType()->isSignedIntegerType())
1938 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1940 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1942 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
1944 // Handle interface types, which are not represented with a concrete type.
1945 if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
1946 llvm::Value *InterfaceSize =
1947 llvm::ConstantInt::get(Idx->getType(),
1949 getTypeSizeInChars(OIT).getQuantity());
1950 Idx = Builder.CreateMul(Idx, InterfaceSize);
1951 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1952 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1953 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1954 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1957 // Explicitly handle GNU void* and function pointer arithmetic
1958 // extensions. The GNU void* casts amount to no-ops since our void* type is
1959 // i8*, but this is future proof.
1960 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1961 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1962 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1963 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1964 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1967 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
1969 // pointer - pointer
1970 Value *LHS = Ops.LHS;
1971 Value *RHS = Ops.RHS;
1973 CharUnits ElementSize;
1975 // Handle GCC extension for pointer arithmetic on void* and function pointer
1977 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1978 ElementSize = CharUnits::One();
1980 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
1983 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1984 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1985 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1986 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1988 // Optimize out the shift for element size of 1.
1989 if (ElementSize.isOne())
1990 return BytesBetween;
1992 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1993 // pointer difference in C is only defined in the case where both operands
1994 // are pointing to elements of an array.
1995 Value *BytesPerElt =
1996 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
1997 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
2001 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2002 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2003 // RHS to the same size as the LHS.
2004 Value *RHS = Ops.RHS;
2005 if (Ops.LHS->getType() != RHS->getType())
2006 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
2008 if (CGF.CatchUndefined
2009 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2010 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2011 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2012 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2013 llvm::ConstantInt::get(RHS->getType(), Width)),
2014 Cont, CGF.getTrapBB());
2015 CGF.EmitBlock(Cont);
2018 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2021 Value *ScalarExprEmitter::EmitShr(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 if (Ops.Ty->hasUnsignedIntegerRepresentation())
2039 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2040 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2043 enum IntrinsicType { VCMPEQ, VCMPGT };
2044 // return corresponding comparison intrinsic for given vector type
2045 static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2046 BuiltinType::Kind ElemKind) {
2048 default: assert(0 && "unexpected element type");
2049 case BuiltinType::Char_U:
2050 case BuiltinType::UChar:
2051 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2052 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2054 case BuiltinType::Char_S:
2055 case BuiltinType::SChar:
2056 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2057 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2059 case BuiltinType::UShort:
2060 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2061 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2063 case BuiltinType::Short:
2064 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2065 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2067 case BuiltinType::UInt:
2068 case BuiltinType::ULong:
2069 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2070 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2072 case BuiltinType::Int:
2073 case BuiltinType::Long:
2074 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2075 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2077 case BuiltinType::Float:
2078 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2079 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2082 return llvm::Intrinsic::not_intrinsic;
2085 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2086 unsigned SICmpOpc, unsigned FCmpOpc) {
2087 TestAndClearIgnoreResultAssign();
2089 QualType LHSTy = E->getLHS()->getType();
2090 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
2091 assert(E->getOpcode() == BO_EQ ||
2092 E->getOpcode() == BO_NE);
2093 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2094 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
2095 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
2096 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
2097 } else if (!LHSTy->isAnyComplexType()) {
2098 Value *LHS = Visit(E->getLHS());
2099 Value *RHS = Visit(E->getRHS());
2101 // If AltiVec, the comparison results in a numeric type, so we use
2102 // intrinsics comparing vectors and giving 0 or 1 as a result
2103 if (LHSTy->isVectorType() && CGF.getContext().getLangOptions().AltiVec) {
2104 // constants for mapping CR6 register bits to predicate result
2105 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2107 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2109 // in several cases vector arguments order will be reversed
2110 Value *FirstVecArg = LHS,
2111 *SecondVecArg = RHS;
2113 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
2114 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
2115 BuiltinType::Kind ElementKind = BTy->getKind();
2117 switch(E->getOpcode()) {
2118 default: assert(0 && "is not a comparison operation");
2121 ID = GetIntrinsic(VCMPEQ, ElementKind);
2125 ID = GetIntrinsic(VCMPEQ, ElementKind);
2129 ID = GetIntrinsic(VCMPGT, ElementKind);
2130 std::swap(FirstVecArg, SecondVecArg);
2134 ID = GetIntrinsic(VCMPGT, ElementKind);
2137 if (ElementKind == BuiltinType::Float) {
2139 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2140 std::swap(FirstVecArg, SecondVecArg);
2144 ID = GetIntrinsic(VCMPGT, ElementKind);
2148 if (ElementKind == BuiltinType::Float) {
2150 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2154 ID = GetIntrinsic(VCMPGT, ElementKind);
2155 std::swap(FirstVecArg, SecondVecArg);
2160 Value *CR6Param = llvm::ConstantInt::get(CGF.Int32Ty, CR6);
2161 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2162 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2163 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2166 if (LHS->getType()->isFPOrFPVectorTy()) {
2167 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
2169 } else if (LHSTy->hasSignedIntegerRepresentation()) {
2170 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
2173 // Unsigned integers and pointers.
2174 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2178 // If this is a vector comparison, sign extend the result to the appropriate
2179 // vector integer type and return it (don't convert to bool).
2180 if (LHSTy->isVectorType())
2181 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2184 // Complex Comparison: can only be an equality comparison.
2185 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2186 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
2188 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
2190 Value *ResultR, *ResultI;
2191 if (CETy->isRealFloatingType()) {
2192 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2193 LHS.first, RHS.first, "cmp.r");
2194 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2195 LHS.second, RHS.second, "cmp.i");
2197 // Complex comparisons can only be equality comparisons. As such, signed
2198 // and unsigned opcodes are the same.
2199 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2200 LHS.first, RHS.first, "cmp.r");
2201 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2202 LHS.second, RHS.second, "cmp.i");
2205 if (E->getOpcode() == BO_EQ) {
2206 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2208 assert(E->getOpcode() == BO_NE &&
2209 "Complex comparison other than == or != ?");
2210 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2214 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2217 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
2218 bool Ignore = TestAndClearIgnoreResultAssign();
2220 // __block variables need to have the rhs evaluated first, plus this should
2221 // improve codegen just a little.
2222 Value *RHS = Visit(E->getRHS());
2223 LValue LHS = EmitCheckedLValue(E->getLHS());
2225 // Store the value into the LHS. Bit-fields are handled specially
2226 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2227 // 'An assignment expression has the value of the left operand after
2228 // the assignment...'.
2229 if (LHS.isBitField())
2230 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
2233 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
2235 // If the result is clearly ignored, return now.
2239 // The result of an assignment in C is the assigned r-value.
2240 if (!CGF.getContext().getLangOptions().CPlusPlus)
2243 // Objective-C property assignment never reloads the value following a store.
2244 if (LHS.isPropertyRef())
2247 // If the lvalue is non-volatile, return the computed value of the assignment.
2248 if (!LHS.isVolatileQualified())
2251 // Otherwise, reload the value.
2252 return EmitLoadOfLValue(LHS, E->getType());
2255 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
2256 const llvm::Type *ResTy = ConvertType(E->getType());
2258 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2259 // If we have 1 && X, just emit X without inserting the control flow.
2260 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
2261 if (Cond == 1) { // If we have 1 && X, just emit X.
2262 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2263 // ZExt result to int or bool.
2264 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
2267 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
2268 if (!CGF.ContainsLabel(E->getRHS()))
2269 return llvm::Constant::getNullValue(ResTy);
2272 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2273 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
2275 CodeGenFunction::ConditionalEvaluation eval(CGF);
2277 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2278 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2280 // Any edges into the ContBlock are now from an (indeterminate number of)
2281 // edges from this first condition. All of these values will be false. Start
2282 // setting up the PHI node in the Cont Block for this.
2283 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
2285 PN->reserveOperandSpace(2); // Normal case, two inputs.
2286 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2288 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
2291 CGF.EmitBlock(RHSBlock);
2292 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2295 // Reaquire the RHS block, as there may be subblocks inserted.
2296 RHSBlock = Builder.GetInsertBlock();
2298 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2299 // into the phi node for the edge with the value of RHSCond.
2300 CGF.EmitBlock(ContBlock);
2301 PN->addIncoming(RHSCond, RHSBlock);
2303 // ZExt result to int.
2304 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
2307 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
2308 const llvm::Type *ResTy = ConvertType(E->getType());
2310 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2311 // If we have 0 || X, just emit X without inserting the control flow.
2312 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
2313 if (Cond == -1) { // If we have 0 || X, just emit X.
2314 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2315 // ZExt result to int or bool.
2316 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
2319 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
2320 if (!CGF.ContainsLabel(E->getRHS()))
2321 return llvm::ConstantInt::get(ResTy, 1);
2324 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2325 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
2327 CodeGenFunction::ConditionalEvaluation eval(CGF);
2329 // Branch on the LHS first. If it is true, go to the success (cont) block.
2330 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2332 // Any edges into the ContBlock are now from an (indeterminate number of)
2333 // edges from this first condition. All of these values will be true. Start
2334 // setting up the PHI node in the Cont Block for this.
2335 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
2337 PN->reserveOperandSpace(2); // Normal case, two inputs.
2338 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2340 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
2344 // Emit the RHS condition as a bool value.
2345 CGF.EmitBlock(RHSBlock);
2346 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
2350 // Reaquire the RHS block, as there may be subblocks inserted.
2351 RHSBlock = Builder.GetInsertBlock();
2353 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2354 // into the phi node for the edge with the value of RHSCond.
2355 CGF.EmitBlock(ContBlock);
2356 PN->addIncoming(RHSCond, RHSBlock);
2358 // ZExt result to int.
2359 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
2362 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2363 CGF.EmitIgnoredExpr(E->getLHS());
2364 CGF.EnsureInsertPoint();
2365 return Visit(E->getRHS());
2368 //===----------------------------------------------------------------------===//
2370 //===----------------------------------------------------------------------===//
2372 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2373 /// expression is cheap enough and side-effect-free enough to evaluate
2374 /// unconditionally instead of conditionally. This is used to convert control
2375 /// flow into selects in some cases.
2376 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2377 CodeGenFunction &CGF) {
2378 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
2379 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
2381 // TODO: Allow anything we can constant fold to an integer or fp constant.
2382 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
2383 isa<FloatingLiteral>(E))
2386 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2387 // X and Y are local variables.
2388 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2389 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2390 if (VD->hasLocalStorage() && !(CGF.getContext()
2391 .getCanonicalType(VD->getType())
2392 .isVolatileQualified()))
2399 Value *ScalarExprEmitter::
2400 VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
2401 TestAndClearIgnoreResultAssign();
2403 // Bind the common expression if necessary.
2404 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2406 Expr *condExpr = E->getCond();
2407 Expr *lhsExpr = E->getTrueExpr();
2408 Expr *rhsExpr = E->getFalseExpr();
2410 // If the condition constant folds and can be elided, try to avoid emitting
2411 // the condition and the dead arm.
2412 if (int Cond = CGF.ConstantFoldsToSimpleInteger(condExpr)){
2413 Expr *live = lhsExpr, *dead = rhsExpr;
2414 if (Cond == -1) std::swap(live, dead);
2416 // If the dead side doesn't have labels we need, and if the Live side isn't
2417 // the gnu missing ?: extension (which we could handle, but don't bother
2418 // to), just emit the Live part.
2419 if (!CGF.ContainsLabel(dead))
2423 // OpenCL: If the condition is a vector, we can treat this condition like
2424 // the select function.
2425 if (CGF.getContext().getLangOptions().OpenCL
2426 && condExpr->getType()->isVectorType()) {
2427 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2428 llvm::Value *LHS = Visit(lhsExpr);
2429 llvm::Value *RHS = Visit(rhsExpr);
2431 const llvm::Type *condType = ConvertType(condExpr->getType());
2432 const llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2434 unsigned numElem = vecTy->getNumElements();
2435 const llvm::Type *elemType = vecTy->getElementType();
2437 std::vector<llvm::Constant*> Zvals;
2438 for (unsigned i = 0; i < numElem; ++i)
2439 Zvals.push_back(llvm::ConstantInt::get(elemType,0));
2441 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2442 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2443 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2444 llvm::VectorType::get(elemType,
2447 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2449 // Cast float to int to perform ANDs if necessary.
2450 llvm::Value *RHSTmp = RHS;
2451 llvm::Value *LHSTmp = LHS;
2452 bool wasCast = false;
2453 const llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2454 if (rhsVTy->getElementType()->isFloatTy()) {
2455 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2456 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2460 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2461 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2462 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2464 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2469 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2470 // select instead of as control flow. We can only do this if it is cheap and
2471 // safe to evaluate the LHS and RHS unconditionally.
2472 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2473 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2474 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2475 llvm::Value *LHS = Visit(lhsExpr);
2476 llvm::Value *RHS = Visit(rhsExpr);
2477 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2480 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2481 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
2482 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
2484 CodeGenFunction::ConditionalEvaluation eval(CGF);
2485 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
2487 CGF.EmitBlock(LHSBlock);
2489 Value *LHS = Visit(lhsExpr);
2492 LHSBlock = Builder.GetInsertBlock();
2493 Builder.CreateBr(ContBlock);
2495 CGF.EmitBlock(RHSBlock);
2497 Value *RHS = Visit(rhsExpr);
2500 RHSBlock = Builder.GetInsertBlock();
2501 CGF.EmitBlock(ContBlock);
2503 // If the LHS or RHS is a throw expression, it will be legitimately null.
2509 // Create a PHI node for the real part.
2510 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
2511 PN->reserveOperandSpace(2);
2512 PN->addIncoming(LHS, LHSBlock);
2513 PN->addIncoming(RHS, RHSBlock);
2517 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
2518 return Visit(E->getChosenSubExpr(CGF.getContext()));
2521 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
2522 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
2523 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2525 // If EmitVAArg fails, we fall back to the LLVM instruction.
2527 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2529 // FIXME Volatility.
2530 return Builder.CreateLoad(ArgPtr);
2533 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2534 return CGF.EmitBlockLiteral(block);
2537 //===----------------------------------------------------------------------===//
2538 // Entry Point into this File
2539 //===----------------------------------------------------------------------===//
2541 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
2542 /// type, ignoring the result.
2543 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
2544 assert(E && !hasAggregateLLVMType(E->getType()) &&
2545 "Invalid scalar expression to emit");
2547 return ScalarExprEmitter(*this, IgnoreResultAssign)
2548 .Visit(const_cast<Expr*>(E));
2551 /// EmitScalarConversion - Emit a conversion from the specified type to the
2552 /// specified destination type, both of which are LLVM scalar types.
2553 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2555 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2556 "Invalid scalar expression to emit");
2557 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2560 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2561 /// type to the specified destination type, where the destination type is an
2562 /// LLVM scalar type.
2563 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2566 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
2567 "Invalid complex -> scalar conversion");
2568 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2573 llvm::Value *CodeGenFunction::
2574 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2575 bool isInc, bool isPre) {
2576 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2579 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2581 // object->isa or (*object).isa
2582 // Generate code as for: *(Class*)object
2583 // build Class* type
2584 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
2586 Expr *BaseExpr = E->getBase();
2587 if (BaseExpr->isRValue()) {
2588 V = CreateTempAlloca(ClassPtrTy, "resval");
2589 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2590 Builder.CreateStore(Src, V);
2591 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2592 MakeAddrLValue(V, E->getType()), E->getType());
2595 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2597 V = EmitLValue(BaseExpr).getAddress();
2600 // build Class* type
2601 ClassPtrTy = ClassPtrTy->getPointerTo();
2602 V = Builder.CreateBitCast(V, ClassPtrTy);
2603 return MakeAddrLValue(V, E->getType());
2607 LValue CodeGenFunction::EmitCompoundAssignmentLValue(
2608 const CompoundAssignOperator *E) {
2609 ScalarExprEmitter Scalar(*this);
2611 switch (E->getOpcode()) {
2612 #define COMPOUND_OP(Op) \
2613 case BO_##Op##Assign: \
2614 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
2650 assert(false && "Not valid compound assignment operators");
2654 llvm_unreachable("Unhandled compound assignment operator");