1 //===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
12 //===----------------------------------------------------------------------===//
14 #include "CodeGenFunction.h"
16 #include "CGObjCRuntime.h"
17 #include "CodeGenModule.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/AST/StmtVisitor.h"
22 #include "clang/Basic/TargetInfo.h"
23 #include "llvm/Constants.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/Module.h"
28 #include "llvm/Support/CFG.h"
29 #include "llvm/Target/TargetData.h"
32 using namespace clang;
33 using namespace CodeGen;
36 //===----------------------------------------------------------------------===//
37 // Scalar Expression Emitter
38 //===----------------------------------------------------------------------===//
43 QualType Ty; // Computation Type.
44 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
45 const Expr *E; // Entire expr, for error unsupported. May not be binop.
49 class ScalarExprEmitter
50 : public StmtVisitor<ScalarExprEmitter, Value*> {
53 bool IgnoreResultAssign;
54 llvm::LLVMContext &VMContext;
57 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
58 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
59 VMContext(cgf.getLLVMContext()) {
62 //===--------------------------------------------------------------------===//
64 //===--------------------------------------------------------------------===//
66 bool TestAndClearIgnoreResultAssign() {
67 bool I = IgnoreResultAssign;
68 IgnoreResultAssign = false;
72 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
73 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
74 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
76 Value *EmitLoadOfLValue(LValue LV, QualType T) {
77 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
80 /// EmitLoadOfLValue - Given an expression with complex type that represents a
81 /// value l-value, this method emits the address of the l-value, then loads
82 /// and returns the result.
83 Value *EmitLoadOfLValue(const Expr *E) {
84 return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType());
87 /// EmitConversionToBool - Convert the specified expression value to a
88 /// boolean (i1) truth value. This is equivalent to "Val != 0".
89 Value *EmitConversionToBool(Value *Src, QualType DstTy);
91 /// EmitScalarConversion - Emit a conversion from the specified type to the
92 /// specified destination type, both of which are LLVM scalar types.
93 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
95 /// EmitComplexToScalarConversion - Emit a conversion from the specified
96 /// complex type to the specified destination type, where the destination type
97 /// is an LLVM scalar type.
98 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
99 QualType SrcTy, QualType DstTy);
101 /// EmitNullValue - Emit a value that corresponds to null for the given type.
102 Value *EmitNullValue(QualType Ty);
104 //===--------------------------------------------------------------------===//
106 //===--------------------------------------------------------------------===//
108 Value *VisitStmt(Stmt *S) {
109 S->dump(CGF.getContext().getSourceManager());
110 assert(0 && "Stmt can't have complex result type!");
113 Value *VisitExpr(Expr *S);
115 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
118 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
119 return llvm::ConstantInt::get(VMContext, E->getValue());
121 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
122 return llvm::ConstantFP::get(VMContext, E->getValue());
124 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
125 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
127 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
128 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
130 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
131 return EmitNullValue(E->getType());
133 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
134 return EmitNullValue(E->getType());
136 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
137 return llvm::ConstantInt::get(ConvertType(E->getType()),
138 CGF.getContext().typesAreCompatible(
139 E->getArgType1(), E->getArgType2()));
141 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
142 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
143 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
144 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
145 return Builder.CreateBitCast(V, ConvertType(E->getType()));
149 Value *VisitDeclRefExpr(DeclRefExpr *E) {
150 Expr::EvalResult Result;
151 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
152 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
153 llvm::ConstantInt *CI
154 = llvm::ConstantInt::get(VMContext, Result.Val.getInt());
155 CGF.EmitDeclRefExprDbgValue(E, CI);
158 return EmitLoadOfLValue(E);
160 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
161 return CGF.EmitObjCSelectorExpr(E);
163 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
164 return CGF.EmitObjCProtocolExpr(E);
166 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
167 return EmitLoadOfLValue(E);
169 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
170 return EmitLoadOfLValue(E);
172 Value *VisitObjCImplicitSetterGetterRefExpr(
173 ObjCImplicitSetterGetterRefExpr *E) {
174 return EmitLoadOfLValue(E);
176 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
177 return CGF.EmitObjCMessageExpr(E).getScalarVal();
180 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
181 LValue LV = CGF.EmitObjCIsaExpr(E);
182 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
186 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
187 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
188 Value *VisitMemberExpr(MemberExpr *E);
189 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
190 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
191 return EmitLoadOfLValue(E);
194 Value *VisitInitListExpr(InitListExpr *E);
196 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
197 return CGF.CGM.EmitNullConstant(E->getType());
199 Value *VisitCastExpr(CastExpr *E) {
200 // Make sure to evaluate VLA bounds now so that we have them for later.
201 if (E->getType()->isVariablyModifiedType())
202 CGF.EmitVLASize(E->getType());
204 return EmitCastExpr(E);
206 Value *EmitCastExpr(CastExpr *E);
208 Value *VisitCallExpr(const CallExpr *E) {
209 if (E->getCallReturnType()->isReferenceType())
210 return EmitLoadOfLValue(E);
212 return CGF.EmitCallExpr(E).getScalarVal();
215 Value *VisitStmtExpr(const StmtExpr *E);
217 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
220 Value *VisitUnaryPostDec(const UnaryOperator *E) {
221 LValue LV = EmitLValue(E->getSubExpr());
222 return EmitScalarPrePostIncDec(E, LV, false, false);
224 Value *VisitUnaryPostInc(const UnaryOperator *E) {
225 LValue LV = EmitLValue(E->getSubExpr());
226 return EmitScalarPrePostIncDec(E, LV, true, false);
228 Value *VisitUnaryPreDec(const UnaryOperator *E) {
229 LValue LV = EmitLValue(E->getSubExpr());
230 return EmitScalarPrePostIncDec(E, LV, false, true);
232 Value *VisitUnaryPreInc(const UnaryOperator *E) {
233 LValue LV = EmitLValue(E->getSubExpr());
234 return EmitScalarPrePostIncDec(E, LV, true, true);
237 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
238 bool isInc, bool isPre);
241 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
242 // If the sub-expression is an instance member reference,
243 // EmitDeclRefLValue will magically emit it with the appropriate
244 // value as the "address".
245 return EmitLValue(E->getSubExpr()).getAddress();
247 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
248 Value *VisitUnaryPlus(const UnaryOperator *E) {
249 // This differs from gcc, though, most likely due to a bug in gcc.
250 TestAndClearIgnoreResultAssign();
251 return Visit(E->getSubExpr());
253 Value *VisitUnaryMinus (const UnaryOperator *E);
254 Value *VisitUnaryNot (const UnaryOperator *E);
255 Value *VisitUnaryLNot (const UnaryOperator *E);
256 Value *VisitUnaryReal (const UnaryOperator *E);
257 Value *VisitUnaryImag (const UnaryOperator *E);
258 Value *VisitUnaryExtension(const UnaryOperator *E) {
259 return Visit(E->getSubExpr());
263 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
264 return Visit(DAE->getExpr());
266 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
267 return CGF.LoadCXXThis();
270 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
271 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
273 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
274 return CGF.EmitCXXNewExpr(E);
276 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
277 CGF.EmitCXXDeleteExpr(E);
280 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
281 return llvm::ConstantInt::get(Builder.getInt1Ty(),
282 E->EvaluateTrait(CGF.getContext()));
285 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
286 // C++ [expr.pseudo]p1:
287 // The result shall only be used as the operand for the function call
288 // operator (), and the result of such a call has type void. The only
289 // effect is the evaluation of the postfix-expression before the dot or
291 CGF.EmitScalarExpr(E->getBase());
295 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
296 return EmitNullValue(E->getType());
299 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
300 CGF.EmitCXXThrowExpr(E);
305 Value *EmitMul(const BinOpInfo &Ops) {
306 if (Ops.Ty->hasSignedIntegerRepresentation()) {
307 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
308 case LangOptions::SOB_Undefined:
309 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
310 case LangOptions::SOB_Defined:
311 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
312 case LangOptions::SOB_Trapping:
313 return EmitOverflowCheckedBinOp(Ops);
317 if (Ops.LHS->getType()->isFPOrFPVectorTy())
318 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
319 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
321 /// Create a binary op that checks for overflow.
322 /// Currently only supports +, - and *.
323 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
324 Value *EmitDiv(const BinOpInfo &Ops);
325 Value *EmitRem(const BinOpInfo &Ops);
326 Value *EmitAdd(const BinOpInfo &Ops);
327 Value *EmitSub(const BinOpInfo &Ops);
328 Value *EmitShl(const BinOpInfo &Ops);
329 Value *EmitShr(const BinOpInfo &Ops);
330 Value *EmitAnd(const BinOpInfo &Ops) {
331 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
333 Value *EmitXor(const BinOpInfo &Ops) {
334 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
336 Value *EmitOr (const BinOpInfo &Ops) {
337 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
340 BinOpInfo EmitBinOps(const BinaryOperator *E);
341 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
342 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
345 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
346 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
348 // Binary operators and binary compound assignment operators.
349 #define HANDLEBINOP(OP) \
350 Value *VisitBin ## OP(const BinaryOperator *E) { \
351 return Emit ## OP(EmitBinOps(E)); \
353 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
354 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
369 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
370 unsigned SICmpOpc, unsigned FCmpOpc);
371 #define VISITCOMP(CODE, UI, SI, FP) \
372 Value *VisitBin##CODE(const BinaryOperator *E) { \
373 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
374 llvm::FCmpInst::FP); }
375 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
376 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
377 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
378 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
379 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
380 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
383 Value *VisitBinAssign (const BinaryOperator *E);
385 Value *VisitBinLAnd (const BinaryOperator *E);
386 Value *VisitBinLOr (const BinaryOperator *E);
387 Value *VisitBinComma (const BinaryOperator *E);
389 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
390 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
393 Value *VisitBlockExpr(const BlockExpr *BE);
394 Value *VisitConditionalOperator(const ConditionalOperator *CO);
395 Value *VisitChooseExpr(ChooseExpr *CE);
396 Value *VisitVAArgExpr(VAArgExpr *VE);
397 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
398 return CGF.EmitObjCStringLiteral(E);
401 } // end anonymous namespace.
403 //===----------------------------------------------------------------------===//
405 //===----------------------------------------------------------------------===//
407 /// EmitConversionToBool - Convert the specified expression value to a
408 /// boolean (i1) truth value. This is equivalent to "Val != 0".
409 Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
410 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
412 if (SrcType->isRealFloatingType()) {
413 // Compare against 0.0 for fp scalars.
414 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
415 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
418 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
419 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
421 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
422 "Unknown scalar type to convert");
424 // Because of the type rules of C, we often end up computing a logical value,
425 // then zero extending it to int, then wanting it as a logical value again.
426 // Optimize this common case.
427 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
428 if (ZI->getOperand(0)->getType() ==
429 llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
430 Value *Result = ZI->getOperand(0);
431 // If there aren't any more uses, zap the instruction to save space.
432 // Note that there can be more uses, for example if this
433 // is the result of an assignment.
435 ZI->eraseFromParent();
440 // Compare against an integer or pointer null.
441 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
442 return Builder.CreateICmpNE(Src, Zero, "tobool");
445 /// EmitScalarConversion - Emit a conversion from the specified type to the
446 /// specified destination type, both of which are LLVM scalar types.
447 Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
449 SrcType = CGF.getContext().getCanonicalType(SrcType);
450 DstType = CGF.getContext().getCanonicalType(DstType);
451 if (SrcType == DstType) return Src;
453 if (DstType->isVoidType()) return 0;
455 // Handle conversions to bool first, they are special: comparisons against 0.
456 if (DstType->isBooleanType())
457 return EmitConversionToBool(Src, SrcType);
459 const llvm::Type *DstTy = ConvertType(DstType);
461 // Ignore conversions like int -> uint.
462 if (Src->getType() == DstTy)
465 // Handle pointer conversions next: pointers can only be converted to/from
466 // other pointers and integers. Check for pointer types in terms of LLVM, as
467 // some native types (like Obj-C id) may map to a pointer type.
468 if (isa<llvm::PointerType>(DstTy)) {
469 // The source value may be an integer, or a pointer.
470 if (isa<llvm::PointerType>(Src->getType()))
471 return Builder.CreateBitCast(Src, DstTy, "conv");
473 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
474 // First, convert to the correct width so that we control the kind of
476 const llvm::Type *MiddleTy = CGF.IntPtrTy;
477 bool InputSigned = SrcType->isSignedIntegerType();
478 llvm::Value* IntResult =
479 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
480 // Then, cast to pointer.
481 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
484 if (isa<llvm::PointerType>(Src->getType())) {
485 // Must be an ptr to int cast.
486 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
487 return Builder.CreatePtrToInt(Src, DstTy, "conv");
490 // A scalar can be splatted to an extended vector of the same element type
491 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
492 // Cast the scalar to element type
493 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
494 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
496 // Insert the element in element zero of an undef vector
497 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
498 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
499 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
501 // Splat the element across to all elements
502 llvm::SmallVector<llvm::Constant*, 16> Args;
503 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
504 for (unsigned i = 0; i < NumElements; i++)
505 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
507 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
508 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
512 // Allow bitcast from vector to integer/fp of the same size.
513 if (isa<llvm::VectorType>(Src->getType()) ||
514 isa<llvm::VectorType>(DstTy))
515 return Builder.CreateBitCast(Src, DstTy, "conv");
517 // Finally, we have the arithmetic types: real int/float.
518 if (isa<llvm::IntegerType>(Src->getType())) {
519 bool InputSigned = SrcType->isSignedIntegerType();
520 if (isa<llvm::IntegerType>(DstTy))
521 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
522 else if (InputSigned)
523 return Builder.CreateSIToFP(Src, DstTy, "conv");
525 return Builder.CreateUIToFP(Src, DstTy, "conv");
528 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
529 if (isa<llvm::IntegerType>(DstTy)) {
530 if (DstType->isSignedIntegerType())
531 return Builder.CreateFPToSI(Src, DstTy, "conv");
533 return Builder.CreateFPToUI(Src, DstTy, "conv");
536 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
537 if (DstTy->getTypeID() < Src->getType()->getTypeID())
538 return Builder.CreateFPTrunc(Src, DstTy, "conv");
540 return Builder.CreateFPExt(Src, DstTy, "conv");
543 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
544 /// type to the specified destination type, where the destination type is an
545 /// LLVM scalar type.
546 Value *ScalarExprEmitter::
547 EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
548 QualType SrcTy, QualType DstTy) {
549 // Get the source element type.
550 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
552 // Handle conversions to bool first, they are special: comparisons against 0.
553 if (DstTy->isBooleanType()) {
554 // Complex != 0 -> (Real != 0) | (Imag != 0)
555 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
556 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
557 return Builder.CreateOr(Src.first, Src.second, "tobool");
560 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
561 // the imaginary part of the complex value is discarded and the value of the
562 // real part is converted according to the conversion rules for the
563 // corresponding real type.
564 return EmitScalarConversion(Src.first, SrcTy, DstTy);
567 Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
568 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
569 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
571 return llvm::Constant::getNullValue(ConvertType(Ty));
574 //===----------------------------------------------------------------------===//
576 //===----------------------------------------------------------------------===//
578 Value *ScalarExprEmitter::VisitExpr(Expr *E) {
579 CGF.ErrorUnsupported(E, "scalar expression");
580 if (E->getType()->isVoidType())
582 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
585 Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
587 if (E->getNumSubExprs() == 2 ||
588 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
589 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
590 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
593 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
594 unsigned LHSElts = LTy->getNumElements();
596 if (E->getNumSubExprs() == 3) {
597 Mask = CGF.EmitScalarExpr(E->getExpr(2));
599 // Shuffle LHS & RHS into one input vector.
600 llvm::SmallVector<llvm::Constant*, 32> concat;
601 for (unsigned i = 0; i != LHSElts; ++i) {
602 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i));
603 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1));
606 Value* CV = llvm::ConstantVector::get(concat.begin(), concat.size());
607 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
613 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
614 llvm::Constant* EltMask;
616 // Treat vec3 like vec4.
617 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
618 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
619 (1 << llvm::Log2_32(LHSElts+2))-1);
620 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
621 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
622 (1 << llvm::Log2_32(LHSElts+1))-1);
624 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
625 (1 << llvm::Log2_32(LHSElts))-1);
627 // Mask off the high bits of each shuffle index.
628 llvm::SmallVector<llvm::Constant *, 32> MaskV;
629 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
630 MaskV.push_back(EltMask);
632 Value* MaskBits = llvm::ConstantVector::get(MaskV.begin(), MaskV.size());
633 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
636 // mask = mask & maskbits
638 // n = extract mask i
640 // newv = insert newv, x, i
641 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
642 MTy->getNumElements());
643 Value* NewV = llvm::UndefValue::get(RTy);
644 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
645 Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i);
646 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
647 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
649 // Handle vec3 special since the index will be off by one for the RHS.
650 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
651 Value *cmpIndx, *newIndx;
652 cmpIndx = Builder.CreateICmpUGT(Indx,
653 llvm::ConstantInt::get(CGF.Int32Ty, 3),
655 newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1),
657 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
659 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
660 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
665 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
666 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
668 // Handle vec3 special since the index will be off by one for the RHS.
669 llvm::SmallVector<llvm::Constant*, 32> indices;
670 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
671 llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
672 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
673 if (VTy->getNumElements() == 3) {
674 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
675 uint64_t cVal = CI->getZExtValue();
677 C = llvm::ConstantInt::get(C->getType(), cVal-1);
681 indices.push_back(C);
684 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
685 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
687 Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
688 Expr::EvalResult Result;
689 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
691 CGF.EmitScalarExpr(E->getBase());
693 EmitLValue(E->getBase());
694 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
696 return EmitLoadOfLValue(E);
699 Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
700 TestAndClearIgnoreResultAssign();
702 // Emit subscript expressions in rvalue context's. For most cases, this just
703 // loads the lvalue formed by the subscript expr. However, we have to be
704 // careful, because the base of a vector subscript is occasionally an rvalue,
705 // so we can't get it as an lvalue.
706 if (!E->getBase()->getType()->isVectorType())
707 return EmitLoadOfLValue(E);
709 // Handle the vector case. The base must be a vector, the index must be an
711 Value *Base = Visit(E->getBase());
712 Value *Idx = Visit(E->getIdx());
713 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
714 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
715 return Builder.CreateExtractElement(Base, Idx, "vecext");
718 static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
719 unsigned Off, const llvm::Type *I32Ty) {
720 int MV = SVI->getMaskValue(Idx);
722 return llvm::UndefValue::get(I32Ty);
723 return llvm::ConstantInt::get(I32Ty, Off+MV);
726 Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
727 bool Ignore = TestAndClearIgnoreResultAssign();
729 assert (Ignore == false && "init list ignored");
730 unsigned NumInitElements = E->getNumInits();
732 if (E->hadArrayRangeDesignator())
733 CGF.ErrorUnsupported(E, "GNU array range designator extension");
735 const llvm::VectorType *VType =
736 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
738 // We have a scalar in braces. Just use the first element.
740 return Visit(E->getInit(0));
742 unsigned ResElts = VType->getNumElements();
744 // Loop over initializers collecting the Value for each, and remembering
745 // whether the source was swizzle (ExtVectorElementExpr). This will allow
746 // us to fold the shuffle for the swizzle into the shuffle for the vector
747 // initializer, since LLVM optimizers generally do not want to touch
750 bool VIsUndefShuffle = false;
751 llvm::Value *V = llvm::UndefValue::get(VType);
752 for (unsigned i = 0; i != NumInitElements; ++i) {
753 Expr *IE = E->getInit(i);
754 Value *Init = Visit(IE);
755 llvm::SmallVector<llvm::Constant*, 16> Args;
757 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
759 // Handle scalar elements. If the scalar initializer is actually one
760 // element of a different vector of the same width, use shuffle instead of
763 if (isa<ExtVectorElementExpr>(IE)) {
764 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
766 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
767 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
768 Value *LHS = 0, *RHS = 0;
770 // insert into undef -> shuffle (src, undef)
772 for (unsigned j = 1; j != ResElts; ++j)
773 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
775 LHS = EI->getVectorOperand();
777 VIsUndefShuffle = true;
778 } else if (VIsUndefShuffle) {
779 // insert into undefshuffle && size match -> shuffle (v, src)
780 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
781 for (unsigned j = 0; j != CurIdx; ++j)
782 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
783 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
784 ResElts + C->getZExtValue()));
785 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
786 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
788 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
789 RHS = EI->getVectorOperand();
790 VIsUndefShuffle = false;
793 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
794 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
800 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
801 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
802 VIsUndefShuffle = false;
807 unsigned InitElts = VVT->getNumElements();
809 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
810 // input is the same width as the vector being constructed, generate an
811 // optimized shuffle of the swizzle input into the result.
812 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
813 if (isa<ExtVectorElementExpr>(IE)) {
814 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
815 Value *SVOp = SVI->getOperand(0);
816 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
818 if (OpTy->getNumElements() == ResElts) {
819 for (unsigned j = 0; j != CurIdx; ++j) {
820 // If the current vector initializer is a shuffle with undef, merge
821 // this shuffle directly into it.
822 if (VIsUndefShuffle) {
823 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
826 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
829 for (unsigned j = 0, je = InitElts; j != je; ++j)
830 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
831 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
832 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
835 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
841 // Extend init to result vector length, and then shuffle its contribution
842 // to the vector initializer into V.
844 for (unsigned j = 0; j != InitElts; ++j)
845 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
846 for (unsigned j = InitElts; j != ResElts; ++j)
847 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
848 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
849 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
853 for (unsigned j = 0; j != CurIdx; ++j)
854 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
855 for (unsigned j = 0; j != InitElts; ++j)
856 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset));
857 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
858 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
861 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
862 // merging subsequent shuffles into this one.
865 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
866 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
867 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
871 // FIXME: evaluate codegen vs. shuffling against constant null vector.
872 // Emit remaining default initializers.
873 const llvm::Type *EltTy = VType->getElementType();
875 // Emit remaining default initializers
876 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
877 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
878 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
879 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
884 static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
885 const Expr *E = CE->getSubExpr();
887 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
890 if (isa<CXXThisExpr>(E)) {
891 // We always assume that 'this' is never null.
895 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
896 // And that glvalue casts are never null.
897 if (ICE->getValueKind() != VK_RValue)
904 // VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
905 // have to handle a more broad range of conversions than explicit casts, as they
906 // handle things like function to ptr-to-function decay etc.
907 Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
908 Expr *E = CE->getSubExpr();
909 QualType DestTy = CE->getType();
910 CastKind Kind = CE->getCastKind();
912 if (!DestTy->isVoidType())
913 TestAndClearIgnoreResultAssign();
915 // Since almost all cast kinds apply to scalars, this switch doesn't have
916 // a default case, so the compiler will warn on a missing case. The cases
917 // are in the same order as in the CastKind enum.
920 // FIXME: All casts should have a known kind!
921 //assert(0 && "Unknown cast kind!");
924 case CK_LValueBitCast:
925 case CK_ObjCObjectLValueCast: {
926 Value *V = EmitLValue(E).getAddress();
927 V = Builder.CreateBitCast(V,
928 ConvertType(CGF.getContext().getPointerType(DestTy)));
929 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy);
932 case CK_AnyPointerToObjCPointerCast:
933 case CK_AnyPointerToBlockPointerCast:
935 Value *Src = Visit(const_cast<Expr*>(E));
936 return Builder.CreateBitCast(Src, ConvertType(DestTy));
939 case CK_UserDefinedConversion:
940 return Visit(const_cast<Expr*>(E));
942 case CK_BaseToDerived: {
943 const CXXRecordDecl *DerivedClassDecl =
944 DestTy->getCXXRecordDeclForPointerType();
946 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
947 CE->path_begin(), CE->path_end(),
948 ShouldNullCheckClassCastValue(CE));
950 case CK_UncheckedDerivedToBase:
951 case CK_DerivedToBase: {
952 const RecordType *DerivedClassTy =
953 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
954 CXXRecordDecl *DerivedClassDecl =
955 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
957 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
958 CE->path_begin(), CE->path_end(),
959 ShouldNullCheckClassCastValue(CE));
962 Value *V = Visit(const_cast<Expr*>(E));
963 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
964 return CGF.EmitDynamicCast(V, DCE);
967 assert(0 && "Should be unreachable!");
970 case CK_ArrayToPointerDecay: {
971 assert(E->getType()->isArrayType() &&
972 "Array to pointer decay must have array source type!");
974 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
976 // Note that VLA pointers are always decayed, so we don't need to do
978 if (!E->getType()->isVariableArrayType()) {
979 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
980 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
981 ->getElementType()) &&
982 "Expected pointer to array");
983 V = Builder.CreateStructGEP(V, 0, "arraydecay");
988 case CK_FunctionToPointerDecay:
989 return EmitLValue(E).getAddress();
991 case CK_NullToMemberPointer: {
992 // If the subexpression's type is the C++0x nullptr_t, emit the
993 // subexpression, which may have side effects.
994 if (E->getType()->isNullPtrType())
997 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
998 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1001 case CK_BaseToDerivedMemberPointer:
1002 case CK_DerivedToBaseMemberPointer: {
1003 Value *Src = Visit(E);
1005 // Note that the AST doesn't distinguish between checked and
1006 // unchecked member pointer conversions, so we always have to
1007 // implement checked conversions here. This is inefficient when
1008 // actual control flow may be required in order to perform the
1009 // check, which it is for data member pointers (but not member
1010 // function pointers on Itanium and ARM).
1011 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
1015 case CK_ConstructorConversion:
1016 assert(0 && "Should be unreachable!");
1019 case CK_IntegralToPointer: {
1020 Value *Src = Visit(const_cast<Expr*>(E));
1022 // First, convert to the correct width so that we control the kind of
1024 const llvm::Type *MiddleTy = CGF.IntPtrTy;
1025 bool InputSigned = E->getType()->isSignedIntegerType();
1026 llvm::Value* IntResult =
1027 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1029 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
1031 case CK_PointerToIntegral: {
1032 Value *Src = Visit(const_cast<Expr*>(E));
1034 // Handle conversion to bool correctly.
1035 if (DestTy->isBooleanType())
1036 return EmitScalarConversion(Src, E->getType(), DestTy);
1038 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1041 if (E->Classify(CGF.getContext()).isGLValue())
1044 CGF.EmitAnyExpr(E, 0, false, true);
1047 case CK_VectorSplat: {
1048 const llvm::Type *DstTy = ConvertType(DestTy);
1049 Value *Elt = Visit(const_cast<Expr*>(E));
1051 // Insert the element in element zero of an undef vector
1052 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
1053 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
1054 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1056 // Splat the element across to all elements
1057 llvm::SmallVector<llvm::Constant*, 16> Args;
1058 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1059 for (unsigned i = 0; i < NumElements; i++)
1060 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
1062 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1063 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1066 case CK_IntegralCast:
1067 case CK_IntegralToFloating:
1068 case CK_FloatingToIntegral:
1069 case CK_FloatingCast:
1070 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
1072 case CK_MemberPointerToBoolean: {
1073 llvm::Value *MemPtr = Visit(E);
1074 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1075 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
1079 // Handle cases where the source is an non-complex type.
1081 if (!CGF.hasAggregateLLVMType(E->getType())) {
1082 Value *Src = Visit(const_cast<Expr*>(E));
1084 // Use EmitScalarConversion to perform the conversion.
1085 return EmitScalarConversion(Src, E->getType(), DestTy);
1088 if (E->getType()->isAnyComplexType()) {
1089 // Handle cases where the source is a complex type.
1090 bool IgnoreImag = true;
1091 bool IgnoreImagAssign = true;
1092 bool IgnoreReal = IgnoreResultAssign;
1093 bool IgnoreRealAssign = IgnoreResultAssign;
1094 if (DestTy->isBooleanType())
1095 IgnoreImagAssign = IgnoreImag = false;
1096 else if (DestTy->isVoidType()) {
1097 IgnoreReal = IgnoreImag = false;
1098 IgnoreRealAssign = IgnoreImagAssign = true;
1100 CodeGenFunction::ComplexPairTy V
1101 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
1103 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1106 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
1107 // evaluate the result and return.
1108 CGF.EmitAggExpr(E, 0, false, true);
1112 Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
1113 return CGF.EmitCompoundStmt(*E->getSubStmt(),
1114 !E->getType()->isVoidType()).getScalarVal();
1117 Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
1118 llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
1119 if (E->getType().isObjCGCWeak())
1120 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
1121 return CGF.EmitLoadOfScalar(V, false, 0, E->getType());
1124 //===----------------------------------------------------------------------===//
1126 //===----------------------------------------------------------------------===//
1128 llvm::Value *ScalarExprEmitter::
1129 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1130 bool isInc, bool isPre) {
1132 QualType ValTy = E->getSubExpr()->getType();
1133 llvm::Value *InVal = EmitLoadOfLValue(LV, ValTy);
1135 int AmountVal = isInc ? 1 : -1;
1137 if (ValTy->isPointerType() &&
1138 ValTy->getAs<PointerType>()->isVariableArrayType()) {
1139 // The amount of the addition/subtraction needs to account for the VLA size
1140 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
1143 llvm::Value *NextVal;
1144 if (const llvm::PointerType *PT =
1145 dyn_cast<llvm::PointerType>(InVal->getType())) {
1146 llvm::Constant *Inc = llvm::ConstantInt::get(CGF.Int32Ty, AmountVal);
1147 if (!isa<llvm::FunctionType>(PT->getElementType())) {
1148 QualType PTEE = ValTy->getPointeeType();
1149 if (const ObjCObjectType *OIT = PTEE->getAs<ObjCObjectType>()) {
1150 // Handle interface types, which are not represented with a concrete
1152 int size = CGF.getContext().getTypeSize(OIT) / 8;
1155 Inc = llvm::ConstantInt::get(Inc->getType(), size);
1156 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1157 InVal = Builder.CreateBitCast(InVal, i8Ty);
1158 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
1159 llvm::Value *lhs = LV.getAddress();
1160 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
1161 LV = CGF.MakeAddrLValue(lhs, ValTy);
1163 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
1165 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1166 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
1167 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
1168 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
1170 } else if (InVal->getType()->isIntegerTy(1) && isInc) {
1171 // Bool++ is an interesting case, due to promotion rules, we get:
1172 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
1173 // Bool = ((int)Bool+1) != 0
1174 // An interesting aspect of this is that increment is always true.
1175 // Decrement does not have this property.
1176 NextVal = llvm::ConstantInt::getTrue(VMContext);
1177 } else if (isa<llvm::IntegerType>(InVal->getType())) {
1178 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
1180 if (!ValTy->isSignedIntegerType())
1181 // Unsigned integer inc is always two's complement.
1182 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
1184 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1185 case LangOptions::SOB_Undefined:
1186 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
1188 case LangOptions::SOB_Defined:
1189 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
1191 case LangOptions::SOB_Trapping:
1194 BinOp.RHS = NextVal;
1195 BinOp.Ty = E->getType();
1196 BinOp.Opcode = BO_Add;
1198 NextVal = EmitOverflowCheckedBinOp(BinOp);
1203 // Add the inc/dec to the real part.
1204 if (InVal->getType()->isFloatTy())
1206 llvm::ConstantFP::get(VMContext,
1207 llvm::APFloat(static_cast<float>(AmountVal)));
1208 else if (InVal->getType()->isDoubleTy())
1210 llvm::ConstantFP::get(VMContext,
1211 llvm::APFloat(static_cast<double>(AmountVal)));
1213 llvm::APFloat F(static_cast<float>(AmountVal));
1215 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1217 NextVal = llvm::ConstantFP::get(VMContext, F);
1219 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
1222 // Store the updated result through the lvalue.
1223 if (LV.isBitField())
1224 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy, &NextVal);
1226 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
1228 // If this is a postinc, return the value read from memory, otherwise use the
1230 return isPre ? NextVal : InVal;
1235 Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
1236 TestAndClearIgnoreResultAssign();
1237 // Emit unary minus with EmitSub so we handle overflow cases etc.
1239 BinOp.RHS = Visit(E->getSubExpr());
1241 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1242 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1244 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
1245 BinOp.Ty = E->getType();
1246 BinOp.Opcode = BO_Sub;
1248 return EmitSub(BinOp);
1251 Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
1252 TestAndClearIgnoreResultAssign();
1253 Value *Op = Visit(E->getSubExpr());
1254 return Builder.CreateNot(Op, "neg");
1257 Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1258 // Compare operand to zero.
1259 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
1262 // TODO: Could dynamically modify easy computations here. For example, if
1263 // the operand is an icmp ne, turn into icmp eq.
1264 BoolVal = Builder.CreateNot(BoolVal, "lnot");
1266 // ZExt result to the expr type.
1267 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
1270 Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1271 // Try folding the offsetof to a constant.
1272 Expr::EvalResult EvalResult;
1273 if (E->Evaluate(EvalResult, CGF.getContext()))
1274 return llvm::ConstantInt::get(VMContext, EvalResult.Val.getInt());
1276 // Loop over the components of the offsetof to compute the value.
1277 unsigned n = E->getNumComponents();
1278 const llvm::Type* ResultType = ConvertType(E->getType());
1279 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1280 QualType CurrentType = E->getTypeSourceInfo()->getType();
1281 for (unsigned i = 0; i != n; ++i) {
1282 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
1283 llvm::Value *Offset = 0;
1284 switch (ON.getKind()) {
1285 case OffsetOfExpr::OffsetOfNode::Array: {
1286 // Compute the index
1287 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1288 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1289 bool IdxSigned = IdxExpr->getType()->isSignedIntegerType();
1290 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1292 // Save the element type
1294 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1296 // Compute the element size
1297 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1298 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1300 // Multiply out to compute the result
1301 Offset = Builder.CreateMul(Idx, ElemSize);
1305 case OffsetOfExpr::OffsetOfNode::Field: {
1306 FieldDecl *MemberDecl = ON.getField();
1307 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1308 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1310 // Compute the index of the field in its parent.
1312 // FIXME: It would be nice if we didn't have to loop here!
1313 for (RecordDecl::field_iterator Field = RD->field_begin(),
1314 FieldEnd = RD->field_end();
1315 Field != FieldEnd; (void)++Field, ++i) {
1316 if (*Field == MemberDecl)
1319 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1321 // Compute the offset to the field
1322 int64_t OffsetInt = RL.getFieldOffset(i) /
1323 CGF.getContext().getCharWidth();
1324 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1326 // Save the element type.
1327 CurrentType = MemberDecl->getType();
1331 case OffsetOfExpr::OffsetOfNode::Identifier:
1332 llvm_unreachable("dependent __builtin_offsetof");
1334 case OffsetOfExpr::OffsetOfNode::Base: {
1335 if (ON.getBase()->isVirtual()) {
1336 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1340 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1341 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1343 // Save the element type.
1344 CurrentType = ON.getBase()->getType();
1346 // Compute the offset to the base.
1347 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1348 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
1349 int64_t OffsetInt = RL.getBaseClassOffset(BaseRD) /
1350 CGF.getContext().getCharWidth();
1351 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1355 Result = Builder.CreateAdd(Result, Offset);
1360 /// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1361 /// argument of the sizeof expression as an integer.
1363 ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
1364 QualType TypeToSize = E->getTypeOfArgument();
1365 if (E->isSizeOf()) {
1366 if (const VariableArrayType *VAT =
1367 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1368 if (E->isArgumentType()) {
1369 // sizeof(type) - make sure to emit the VLA size.
1370 CGF.EmitVLASize(TypeToSize);
1372 // C99 6.5.3.4p2: If the argument is an expression of type
1373 // VLA, it is evaluated.
1374 CGF.EmitAnyExpr(E->getArgumentExpr());
1377 return CGF.GetVLASize(VAT);
1381 // If this isn't sizeof(vla), the result must be constant; use the constant
1382 // folding logic so we don't have to duplicate it here.
1383 Expr::EvalResult Result;
1384 E->Evaluate(Result, CGF.getContext());
1385 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
1388 Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1389 Expr *Op = E->getSubExpr();
1390 if (Op->getType()->isAnyComplexType())
1391 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
1394 Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1395 Expr *Op = E->getSubExpr();
1396 if (Op->getType()->isAnyComplexType())
1397 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
1399 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1400 // effects are evaluated, but not the actual value.
1401 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
1404 CGF.EmitScalarExpr(Op, true);
1405 return llvm::Constant::getNullValue(ConvertType(E->getType()));
1408 //===----------------------------------------------------------------------===//
1410 //===----------------------------------------------------------------------===//
1412 BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
1413 TestAndClearIgnoreResultAssign();
1415 Result.LHS = Visit(E->getLHS());
1416 Result.RHS = Visit(E->getRHS());
1417 Result.Ty = E->getType();
1418 Result.Opcode = E->getOpcode();
1423 LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1424 const CompoundAssignOperator *E,
1425 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
1427 QualType LHSTy = E->getLHS()->getType();
1430 if (E->getComputationResultType()->isAnyComplexType()) {
1431 // This needs to go through the complex expression emitter, but it's a tad
1432 // complicated to do that... I'm leaving it out for now. (Note that we do
1433 // actually need the imaginary part of the RHS for multiplication and
1435 CGF.ErrorUnsupported(E, "complex compound assignment");
1436 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
1440 // Emit the RHS first. __block variables need to have the rhs evaluated
1441 // first, plus this should improve codegen a little.
1442 OpInfo.RHS = Visit(E->getRHS());
1443 OpInfo.Ty = E->getComputationResultType();
1444 OpInfo.Opcode = E->getOpcode();
1446 // Load/convert the LHS.
1447 LValue LHSLV = EmitCheckedLValue(E->getLHS());
1448 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
1449 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1450 E->getComputationLHSType());
1452 // Expand the binary operator.
1453 Result = (this->*Func)(OpInfo);
1455 // Convert the result back to the LHS type.
1456 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
1458 // Store the result value into the LHS lvalue. Bit-fields are handled
1459 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1460 // 'An assignment expression has the value of the left operand after the
1462 if (LHSLV.isBitField())
1463 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1466 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
1471 Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1472 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1473 bool Ignore = TestAndClearIgnoreResultAssign();
1475 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1477 // If the result is clearly ignored, return now.
1481 // Objective-C property assignment never reloads the value following a store.
1482 if (LHS.isPropertyRef() || LHS.isKVCRef())
1485 // If the lvalue is non-volatile, return the computed value of the assignment.
1486 if (!LHS.isVolatileQualified())
1489 // Otherwise, reload the value.
1490 return EmitLoadOfLValue(LHS, E->getType());
1494 Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
1495 if (Ops.LHS->getType()->isFPOrFPVectorTy())
1496 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
1497 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
1498 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1500 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1503 Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1504 // Rem in C can't be a floating point type: C99 6.5.5p2.
1505 if (Ops.Ty->isUnsignedIntegerType())
1506 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1508 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1511 Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1515 switch (Ops.Opcode) {
1519 IID = llvm::Intrinsic::sadd_with_overflow;
1524 IID = llvm::Intrinsic::ssub_with_overflow;
1529 IID = llvm::Intrinsic::smul_with_overflow;
1532 assert(false && "Unsupported operation for overflow detection");
1538 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1540 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1542 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1543 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1544 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1546 // Branch in case of overflow.
1547 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1548 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
1550 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1552 // Handle overflow with llvm.trap.
1553 // TODO: it would be better to generate one of these blocks per function.
1554 Builder.SetInsertPoint(overflowBB);
1555 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
1556 Builder.CreateCall(Trap);
1557 Builder.CreateUnreachable();
1560 Builder.SetInsertPoint(continueBB);
1564 Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
1565 if (!Ops.Ty->isAnyPointerType()) {
1566 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1567 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1568 case LangOptions::SOB_Undefined:
1569 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1570 case LangOptions::SOB_Defined:
1571 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1572 case LangOptions::SOB_Trapping:
1573 return EmitOverflowCheckedBinOp(Ops);
1577 if (Ops.LHS->getType()->isFPOrFPVectorTy())
1578 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1580 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1583 // Must have binary (not unary) expr here. Unary pointer decrement doesn't
1585 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1587 if (Ops.Ty->isPointerType() &&
1588 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
1589 // The amount of the addition needs to account for the VLA size
1590 CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
1595 const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
1596 const ObjCObjectPointerType *OPT =
1597 BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
1601 IdxExp = BinOp->getRHS();
1602 } else { // int + pointer
1603 PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1604 OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
1605 assert((PT || OPT) && "Invalid add expr");
1608 IdxExp = BinOp->getLHS();
1611 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1612 if (Width < CGF.LLVMPointerWidth) {
1613 // Zero or sign extend the pointer value based on whether the index is
1615 const llvm::Type *IdxType = CGF.IntPtrTy;
1616 if (IdxExp->getType()->isSignedIntegerType())
1617 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1619 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1621 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
1622 // Handle interface types, which are not represented with a concrete type.
1623 if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
1624 llvm::Value *InterfaceSize =
1625 llvm::ConstantInt::get(Idx->getType(),
1626 CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
1627 Idx = Builder.CreateMul(Idx, InterfaceSize);
1628 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1629 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1630 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1631 return Builder.CreateBitCast(Res, Ptr->getType());
1634 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1635 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1637 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
1638 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1639 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1640 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1641 return Builder.CreateBitCast(Res, Ptr->getType());
1644 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
1647 Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
1648 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
1649 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1650 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1651 case LangOptions::SOB_Undefined:
1652 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1653 case LangOptions::SOB_Defined:
1654 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1655 case LangOptions::SOB_Trapping:
1656 return EmitOverflowCheckedBinOp(Ops);
1660 if (Ops.LHS->getType()->isFPOrFPVectorTy())
1661 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
1663 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1666 // Must have binary (not unary) expr here. Unary pointer increment doesn't
1668 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1670 if (BinOp->getLHS()->getType()->isPointerType() &&
1671 BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
1672 // The amount of the addition needs to account for the VLA size for
1674 // The amount of the division needs to account for the VLA size for
1676 CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
1679 const QualType LHSType = BinOp->getLHS()->getType();
1680 const QualType LHSElementType = LHSType->getPointeeType();
1681 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1683 Value *Idx = Ops.RHS;
1684 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
1685 if (Width < CGF.LLVMPointerWidth) {
1686 // Zero or sign extend the pointer value based on whether the index is
1688 const llvm::Type *IdxType = CGF.IntPtrTy;
1689 if (BinOp->getRHS()->getType()->isSignedIntegerType())
1690 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1692 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1694 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
1696 // Handle interface types, which are not represented with a concrete type.
1697 if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
1698 llvm::Value *InterfaceSize =
1699 llvm::ConstantInt::get(Idx->getType(),
1701 getTypeSizeInChars(OIT).getQuantity());
1702 Idx = Builder.CreateMul(Idx, InterfaceSize);
1703 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1704 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1705 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1706 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1709 // Explicitly handle GNU void* and function pointer arithmetic
1710 // extensions. The GNU void* casts amount to no-ops since our void* type is
1711 // i8*, but this is future proof.
1712 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1713 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1714 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1715 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1716 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1719 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
1721 // pointer - pointer
1722 Value *LHS = Ops.LHS;
1723 Value *RHS = Ops.RHS;
1725 CharUnits ElementSize;
1727 // Handle GCC extension for pointer arithmetic on void* and function pointer
1729 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
1730 ElementSize = CharUnits::One();
1732 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
1735 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1736 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1737 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1738 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1740 // Optimize out the shift for element size of 1.
1741 if (ElementSize.isOne())
1742 return BytesBetween;
1744 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1745 // pointer difference in C is only defined in the case where both operands
1746 // are pointing to elements of an array.
1747 Value *BytesPerElt =
1748 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
1749 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
1753 Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1754 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1755 // RHS to the same size as the LHS.
1756 Value *RHS = Ops.RHS;
1757 if (Ops.LHS->getType() != RHS->getType())
1758 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1760 if (CGF.CatchUndefined
1761 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1762 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1763 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1764 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1765 llvm::ConstantInt::get(RHS->getType(), Width)),
1766 Cont, CGF.getTrapBB());
1767 CGF.EmitBlock(Cont);
1770 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1773 Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1774 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1775 // RHS to the same size as the LHS.
1776 Value *RHS = Ops.RHS;
1777 if (Ops.LHS->getType() != RHS->getType())
1778 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1780 if (CGF.CatchUndefined
1781 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1782 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1783 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1784 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1785 llvm::ConstantInt::get(RHS->getType(), Width)),
1786 Cont, CGF.getTrapBB());
1787 CGF.EmitBlock(Cont);
1790 if (Ops.Ty->hasUnsignedIntegerRepresentation())
1791 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1792 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1795 Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1796 unsigned SICmpOpc, unsigned FCmpOpc) {
1797 TestAndClearIgnoreResultAssign();
1799 QualType LHSTy = E->getLHS()->getType();
1800 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
1801 assert(E->getOpcode() == BO_EQ ||
1802 E->getOpcode() == BO_NE);
1803 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
1804 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
1805 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
1806 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
1807 } else if (!LHSTy->isAnyComplexType()) {
1808 Value *LHS = Visit(E->getLHS());
1809 Value *RHS = Visit(E->getRHS());
1811 if (LHS->getType()->isFPOrFPVectorTy()) {
1812 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
1814 } else if (LHSTy->hasSignedIntegerRepresentation()) {
1815 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
1818 // Unsigned integers and pointers.
1819 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1823 // If this is a vector comparison, sign extend the result to the appropriate
1824 // vector integer type and return it (don't convert to bool).
1825 if (LHSTy->isVectorType())
1826 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1829 // Complex Comparison: can only be an equality comparison.
1830 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1831 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1833 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
1835 Value *ResultR, *ResultI;
1836 if (CETy->isRealFloatingType()) {
1837 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1838 LHS.first, RHS.first, "cmp.r");
1839 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1840 LHS.second, RHS.second, "cmp.i");
1842 // Complex comparisons can only be equality comparisons. As such, signed
1843 // and unsigned opcodes are the same.
1844 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1845 LHS.first, RHS.first, "cmp.r");
1846 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1847 LHS.second, RHS.second, "cmp.i");
1850 if (E->getOpcode() == BO_EQ) {
1851 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1853 assert(E->getOpcode() == BO_NE &&
1854 "Complex comparison other than == or != ?");
1855 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1859 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
1862 Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
1863 bool Ignore = TestAndClearIgnoreResultAssign();
1865 // __block variables need to have the rhs evaluated first, plus this should
1866 // improve codegen just a little.
1867 Value *RHS = Visit(E->getRHS());
1868 LValue LHS = EmitCheckedLValue(E->getLHS());
1870 // Store the value into the LHS. Bit-fields are handled specially
1871 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1872 // 'An assignment expression has the value of the left operand after
1873 // the assignment...'.
1874 if (LHS.isBitField())
1875 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1878 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
1880 // If the result is clearly ignored, return now.
1884 // Objective-C property assignment never reloads the value following a store.
1885 if (LHS.isPropertyRef() || LHS.isKVCRef())
1888 // If the lvalue is non-volatile, return the computed value of the assignment.
1889 if (!LHS.isVolatileQualified())
1892 // Otherwise, reload the value.
1893 return EmitLoadOfLValue(LHS, E->getType());
1896 Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
1897 const llvm::Type *ResTy = ConvertType(E->getType());
1899 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1900 // If we have 1 && X, just emit X without inserting the control flow.
1901 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1902 if (Cond == 1) { // If we have 1 && X, just emit X.
1903 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1904 // ZExt result to int or bool.
1905 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
1908 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
1909 if (!CGF.ContainsLabel(E->getRHS()))
1910 return llvm::Constant::getNullValue(ResTy);
1913 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1914 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
1916 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1917 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1919 // Any edges into the ContBlock are now from an (indeterminate number of)
1920 // edges from this first condition. All of these values will be false. Start
1921 // setting up the PHI node in the Cont Block for this.
1922 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1924 PN->reserveOperandSpace(2); // Normal case, two inputs.
1925 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1927 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
1929 CGF.BeginConditionalBranch();
1930 CGF.EmitBlock(RHSBlock);
1931 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1932 CGF.EndConditionalBranch();
1934 // Reaquire the RHS block, as there may be subblocks inserted.
1935 RHSBlock = Builder.GetInsertBlock();
1937 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1938 // into the phi node for the edge with the value of RHSCond.
1939 CGF.EmitBlock(ContBlock);
1940 PN->addIncoming(RHSCond, RHSBlock);
1942 // ZExt result to int.
1943 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
1946 Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
1947 const llvm::Type *ResTy = ConvertType(E->getType());
1949 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1950 // If we have 0 || X, just emit X without inserting the control flow.
1951 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1952 if (Cond == -1) { // If we have 0 || X, just emit X.
1953 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1954 // ZExt result to int or bool.
1955 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
1958 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
1959 if (!CGF.ContainsLabel(E->getRHS()))
1960 return llvm::ConstantInt::get(ResTy, 1);
1963 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1964 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
1966 // Branch on the LHS first. If it is true, go to the success (cont) block.
1967 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1969 // Any edges into the ContBlock are now from an (indeterminate number of)
1970 // edges from this first condition. All of these values will be true. Start
1971 // setting up the PHI node in the Cont Block for this.
1972 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1974 PN->reserveOperandSpace(2); // Normal case, two inputs.
1975 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1977 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
1979 CGF.BeginConditionalBranch();
1981 // Emit the RHS condition as a bool value.
1982 CGF.EmitBlock(RHSBlock);
1983 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1985 CGF.EndConditionalBranch();
1987 // Reaquire the RHS block, as there may be subblocks inserted.
1988 RHSBlock = Builder.GetInsertBlock();
1990 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1991 // into the phi node for the edge with the value of RHSCond.
1992 CGF.EmitBlock(ContBlock);
1993 PN->addIncoming(RHSCond, RHSBlock);
1995 // ZExt result to int.
1996 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
1999 Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
2000 CGF.EmitStmt(E->getLHS());
2001 CGF.EnsureInsertPoint();
2002 return Visit(E->getRHS());
2005 //===----------------------------------------------------------------------===//
2007 //===----------------------------------------------------------------------===//
2009 /// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2010 /// expression is cheap enough and side-effect-free enough to evaluate
2011 /// unconditionally instead of conditionally. This is used to convert control
2012 /// flow into selects in some cases.
2013 static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2014 CodeGenFunction &CGF) {
2015 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
2016 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
2018 // TODO: Allow anything we can constant fold to an integer or fp constant.
2019 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
2020 isa<FloatingLiteral>(E))
2023 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2024 // X and Y are local variables.
2025 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2026 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2027 if (VD->hasLocalStorage() && !(CGF.getContext()
2028 .getCanonicalType(VD->getType())
2029 .isVolatileQualified()))
2036 Value *ScalarExprEmitter::
2037 VisitConditionalOperator(const ConditionalOperator *E) {
2038 TestAndClearIgnoreResultAssign();
2039 // If the condition constant folds and can be elided, try to avoid emitting
2040 // the condition and the dead arm.
2041 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
2042 Expr *Live = E->getLHS(), *Dead = E->getRHS();
2044 std::swap(Live, Dead);
2046 // If the dead side doesn't have labels we need, and if the Live side isn't
2047 // the gnu missing ?: extension (which we could handle, but don't bother
2048 // to), just emit the Live part.
2049 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
2050 Live) // Live part isn't missing.
2055 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2056 // select instead of as control flow. We can only do this if it is cheap and
2057 // safe to evaluate the LHS and RHS unconditionally.
2058 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(),
2060 isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) {
2061 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
2062 llvm::Value *LHS = Visit(E->getLHS());
2063 llvm::Value *RHS = Visit(E->getRHS());
2064 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2067 if (!E->getLHS() && CGF.getContext().getLangOptions().CPlusPlus) {
2068 // Does not support GNU missing condition extension in C++ yet (see #7726)
2069 CGF.ErrorUnsupported(E, "conditional operator with missing LHS");
2070 return llvm::UndefValue::get(ConvertType(E->getType()));
2073 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2074 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
2075 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
2078 // If we don't have the GNU missing condition extension, emit a branch on bool
2081 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
2082 // the branch on bool.
2083 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
2085 // Otherwise, for the ?: extension, evaluate the conditional and then
2086 // convert it to bool the hard way. We do this explicitly because we need
2087 // the unconverted value for the missing middle value of the ?:.
2088 CondVal = CGF.EmitScalarExpr(E->getCond());
2090 // In some cases, EmitScalarConversion will delete the "CondVal" expression
2091 // if there are no extra uses (an optimization). Inhibit this by making an
2092 // extra dead use, because we're going to add a use of CondVal later. We
2093 // don't use the builder for this, because we don't want it to get optimized
2094 // away. This leaves dead code, but the ?: extension isn't common.
2095 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
2096 Builder.GetInsertBlock());
2098 Value *CondBoolVal =
2099 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
2100 CGF.getContext().BoolTy);
2101 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
2104 CGF.BeginConditionalBranch();
2105 CGF.EmitBlock(LHSBlock);
2107 // Handle the GNU extension for missing LHS.
2110 LHS = Visit(E->getLHS());
2111 else // Perform promotions, to handle cases like "short ?: int"
2112 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
2114 CGF.EndConditionalBranch();
2115 LHSBlock = Builder.GetInsertBlock();
2116 CGF.EmitBranch(ContBlock);
2118 CGF.BeginConditionalBranch();
2119 CGF.EmitBlock(RHSBlock);
2121 Value *RHS = Visit(E->getRHS());
2122 CGF.EndConditionalBranch();
2123 RHSBlock = Builder.GetInsertBlock();
2124 CGF.EmitBranch(ContBlock);
2126 CGF.EmitBlock(ContBlock);
2128 // If the LHS or RHS is a throw expression, it will be legitimately null.
2134 // Create a PHI node for the real part.
2135 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
2136 PN->reserveOperandSpace(2);
2137 PN->addIncoming(LHS, LHSBlock);
2138 PN->addIncoming(RHS, RHSBlock);
2142 Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
2143 return Visit(E->getChosenSubExpr(CGF.getContext()));
2146 Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
2147 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
2148 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2150 // If EmitVAArg fails, we fall back to the LLVM instruction.
2152 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2154 // FIXME Volatility.
2155 return Builder.CreateLoad(ArgPtr);
2158 Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
2159 return CGF.BuildBlockLiteralTmp(BE);
2162 //===----------------------------------------------------------------------===//
2163 // Entry Point into this File
2164 //===----------------------------------------------------------------------===//
2166 /// EmitScalarExpr - Emit the computation of the specified expression of scalar
2167 /// type, ignoring the result.
2168 Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
2169 assert(E && !hasAggregateLLVMType(E->getType()) &&
2170 "Invalid scalar expression to emit");
2172 return ScalarExprEmitter(*this, IgnoreResultAssign)
2173 .Visit(const_cast<Expr*>(E));
2176 /// EmitScalarConversion - Emit a conversion from the specified type to the
2177 /// specified destination type, both of which are LLVM scalar types.
2178 Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2180 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2181 "Invalid scalar expression to emit");
2182 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2185 /// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2186 /// type to the specified destination type, where the destination type is an
2187 /// LLVM scalar type.
2188 Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2191 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
2192 "Invalid complex -> scalar conversion");
2193 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2198 llvm::Value *CodeGenFunction::
2199 EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2200 bool isInc, bool isPre) {
2201 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2204 LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2206 // object->isa or (*object).isa
2207 // Generate code as for: *(Class*)object
2208 // build Class* type
2209 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
2211 Expr *BaseExpr = E->getBase();
2212 if (BaseExpr->isLvalue(getContext()) != Expr::LV_Valid) {
2213 V = CreateTempAlloca(ClassPtrTy, "resval");
2214 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2215 Builder.CreateStore(Src, V);
2216 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2217 MakeAddrLValue(V, E->getType()), E->getType());
2220 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2222 V = EmitLValue(BaseExpr).getAddress();
2225 // build Class* type
2226 ClassPtrTy = ClassPtrTy->getPointerTo();
2227 V = Builder.CreateBitCast(V, ClassPtrTy);
2228 return MakeAddrLValue(V, E->getType());
2232 LValue CodeGenFunction::EmitCompoundAssignOperatorLValue(
2233 const CompoundAssignOperator *E) {
2234 ScalarExprEmitter Scalar(*this);
2236 switch (E->getOpcode()) {
2237 #define COMPOUND_OP(Op) \
2238 case BO_##Op##Assign: \
2239 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
2275 assert(false && "Not valid compound assignment operators");
2279 llvm_unreachable("Unhandled compound assignment operator");