blob: a28de703e54b0ae4186c53c5746090cb7200e9e5 [file] [log] [blame]
Chris Lattner7f02f722007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner7f02f722007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel78ba3d42010-10-04 21:46:04 +000014#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000015#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000017#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000018#include "CodeGenModule.h"
Devang Patel78ba3d42010-10-04 21:46:04 +000019#include "CGDebugInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000023#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000024#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000025#include "llvm/Constants.h"
26#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000028#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000029#include "llvm/Module.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000030#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000031#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000032#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000033
Chris Lattner7f02f722007-08-24 05:35:26 +000034using namespace clang;
35using namespace CodeGen;
36using llvm::Value;
37
38//===----------------------------------------------------------------------===//
39// Scalar Expression Emitter
40//===----------------------------------------------------------------------===//
41
Benjamin Kramer79ba2a62010-10-22 16:48:22 +000042namespace {
Chris Lattner7f02f722007-08-24 05:35:26 +000043struct BinOpInfo {
44 Value *LHS;
45 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000046 QualType Ty; // Computation Type.
Chris Lattner9a207232010-06-26 21:48:21 +000047 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
48 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000049};
50
John McCall404cd162010-11-13 01:35:44 +000051static 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();
56}
57
Benjamin Kramer85b45212009-11-28 19:45:26 +000058class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000059 : public StmtVisitor<ScalarExprEmitter, Value*> {
60 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000061 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000062 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000063 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000064public:
65
Mike Stump7f79f9b2009-05-29 15:46:01 +000066 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000067 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000068 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000069 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000070
Chris Lattner7f02f722007-08-24 05:35:26 +000071 //===--------------------------------------------------------------------===//
72 // Utilities
73 //===--------------------------------------------------------------------===//
74
Mike Stump7f79f9b2009-05-29 15:46:01 +000075 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000076 bool I = IgnoreResultAssign;
77 IgnoreResultAssign = false;
78 return I;
79 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000080
Chris Lattner7f02f722007-08-24 05:35:26 +000081 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
82 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Mike Stumpb14e62d2009-12-16 02:57:00 +000083 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
Chris Lattner7f02f722007-08-24 05:35:26 +000084
85 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000086 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000087 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000088
Chris Lattner7f02f722007-08-24 05:35:26 +000089 /// 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) {
Mike Stumpb14e62d2009-12-16 02:57:00 +000093 return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +000094 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000095
Chris Lattner9abc84e2007-08-26 16:42:57 +000096 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000097 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000098 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +000099
Chris Lattner3707b252007-08-26 06:48:56 +0000100 /// EmitScalarConversion - Emit a conversion from the specified type to the
101 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
103
104 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000105 /// complex type to the specified destination type, where the destination type
106 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
108 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000109
Anders Carlssona40a9f32010-05-22 17:45:10 +0000110 /// EmitNullValue - Emit a value that corresponds to null for the given type.
111 Value *EmitNullValue(QualType Ty);
112
John McCalldaa8e4e2010-11-15 09:13:47 +0000113 /// 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");
118 }
119
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");
125 }
126
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.
137 if (ZI->use_empty())
138 ZI->eraseFromParent();
139 return Result;
140 }
141 }
142
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");
146 }
147
Chris Lattner7f02f722007-08-24 05:35:26 +0000148 //===--------------------------------------------------------------------===//
149 // Visitor Methods
150 //===--------------------------------------------------------------------===//
151
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000152 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000153 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
154 }
155
Chris Lattner7f02f722007-08-24 05:35:26 +0000156 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000157 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000158 assert(0 && "Stmt can't have complex result type!");
159 return 0;
160 }
161 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000162
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000163 Value *VisitParenExpr(ParenExpr *PE) {
164 return Visit(PE->getSubExpr());
165 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000166
167 // Leaves.
168 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000169 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000170 }
171 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000172 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000173 }
174 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000175 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000176 }
Nate Begemane7579b52007-11-15 05:40:03 +0000177 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000178 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000179 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000180 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000181 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000182 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000183 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000184 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000185 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000186 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000187 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000188 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000189 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
190 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000191 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000192
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000193 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
194 return llvm::ConstantInt::get(ConvertType(E->getType()),
195 E->getPackLength());
196 }
John McCalle996ffd2011-02-16 08:02:54 +0000197
198 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000199 if (E->isGLValue())
200 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getType());
John McCalle996ffd2011-02-16 08:02:54 +0000201
202 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000203 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000204 }
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000205
Chris Lattner7f02f722007-08-24 05:35:26 +0000206 // l-values.
207 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000208 Expr::EvalResult Result;
John McCall189d6ef2010-10-09 01:34:31 +0000209 if (!E->Evaluate(Result, CGF.getContext()))
210 return EmitLoadOfLValue(E);
211
212 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
213
214 llvm::Constant *C;
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());
219 } else {
220 return EmitLoadOfLValue(E);
Eli Friedman28665272009-11-26 03:22:21 +0000221 }
John McCall189d6ef2010-10-09 01:34:31 +0000222
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);
229 }
230
231 return C;
Chris Lattner7f02f722007-08-24 05:35:26 +0000232 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000233 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
234 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000235 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000236 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
237 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000238 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000239 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000240 return EmitLoadOfLValue(E);
241 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000242 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
John McCallf6a16482010-12-04 03:47:34 +0000243 assert(E->getObjectKind() == OK_Ordinary &&
244 "reached property reference without lvalue-to-rvalue");
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000245 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000246 }
247 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000248 if (E->getMethodDecl() &&
249 E->getMethodDecl()->getResultType()->isReferenceType())
250 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000251 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000252 }
253
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000254 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000255 LValue LV = CGF.EmitObjCIsaExpr(E);
256 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000257 return V;
258 }
259
Chris Lattner7f02f722007-08-24 05:35:26 +0000260 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000261 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000262 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000263 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000264 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
265 return EmitLoadOfLValue(E);
266 }
Devang Patel35634f52007-10-24 17:18:43 +0000267
Nate Begeman0533b302009-10-18 20:10:40 +0000268 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000269
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000270 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000271 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000272 }
Eli Friedmand8889622009-11-27 04:41:50 +0000273 Value *VisitCastExpr(CastExpr *E) {
Eli Friedmanc62aad82009-04-20 03:54:15 +0000274 // Make sure to evaluate VLA bounds now so that we have them for later.
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000275 if (E->getType()->isVariablyModifiedType())
276 CGF.EmitVLASize(E->getType());
Eli Friedmanc62aad82009-04-20 03:54:15 +0000277
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000278 return EmitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000279 }
Eli Friedmand8889622009-11-27 04:41:50 +0000280 Value *EmitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000281
282 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000283 if (E->getCallReturnType()->isReferenceType())
284 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000285
Chris Lattner9b655512007-08-31 22:49:20 +0000286 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000287 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000288
Chris Lattner33793202007-08-31 22:09:40 +0000289 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000290
Mike Stumpa99038c2009-02-28 09:07:16 +0000291 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000292
Chris Lattner7f02f722007-08-24 05:35:26 +0000293 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000294 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000295 LValue LV = EmitLValue(E->getSubExpr());
296 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000297 }
298 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000299 LValue LV = EmitLValue(E->getSubExpr());
300 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000301 }
302 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000303 LValue LV = EmitLValue(E->getSubExpr());
304 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000305 }
306 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000307 LValue LV = EmitLValue(E->getSubExpr());
308 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000309 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000310
Anton Yartsev683564a2011-02-07 02:17:30 +0000311 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
312 llvm::Value *InVal,
313 llvm::Value *NextVal,
314 bool IsInc);
315
Chris Lattner8c11a652010-06-26 22:09:34 +0000316 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
317 bool isInc, bool isPre);
318
319
Chris Lattner7f02f722007-08-24 05:35:26 +0000320 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000321 if (isa<MemberPointerType>(E->getType())) // never sugared
322 return CGF.CGM.getMemberPointerConstant(E);
323
Chris Lattner7f02f722007-08-24 05:35:26 +0000324 return EmitLValue(E->getSubExpr()).getAddress();
325 }
John McCallfd569002010-12-04 12:43:24 +0000326 Value *VisitUnaryDeref(const UnaryOperator *E) {
327 if (E->getType()->isVoidType())
328 return Visit(E->getSubExpr()); // the actual value should be unused
329 return EmitLoadOfLValue(E);
330 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000331 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000332 // This differs from gcc, though, most likely due to a bug in gcc.
333 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000334 return Visit(E->getSubExpr());
335 }
336 Value *VisitUnaryMinus (const UnaryOperator *E);
337 Value *VisitUnaryNot (const UnaryOperator *E);
338 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000339 Value *VisitUnaryReal (const UnaryOperator *E);
340 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000341 Value *VisitUnaryExtension(const UnaryOperator *E) {
342 return Visit(E->getSubExpr());
343 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000344
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000345 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000346 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
347 return Visit(DAE->getExpr());
348 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000349 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
350 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000351 }
352
John McCall4765fa02010-12-06 08:20:24 +0000353 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
354 return CGF.EmitExprWithCleanups(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000355 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000356 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
357 return CGF.EmitCXXNewExpr(E);
358 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000359 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
360 CGF.EmitCXXDeleteExpr(E);
361 return 0;
362 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000363 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +0000364 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000365 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000366
Francois Pichet6ad6f282010-12-07 00:08:36 +0000367 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000368 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000369 }
370
Douglas Gregora71d8192009-09-04 17:36:40 +0000371 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
372 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000373 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000374 // operator (), and the result of such a call has type void. The only
375 // effect is the evaluation of the postfix-expression before the dot or
376 // arrow.
377 CGF.EmitScalarExpr(E->getBase());
378 return 0;
379 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000380
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000381 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000382 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000383 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000384
385 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
386 CGF.EmitCXXThrowExpr(E);
387 return 0;
388 }
389
Sebastian Redl98294de2010-09-10 21:04:00 +0000390 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
391 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
392 }
393
Chris Lattner7f02f722007-08-24 05:35:26 +0000394 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000395 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000396 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000397 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
398 case LangOptions::SOB_Undefined:
399 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
400 case LangOptions::SOB_Defined:
401 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
402 case LangOptions::SOB_Trapping:
403 return EmitOverflowCheckedBinOp(Ops);
404 }
405 }
406
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000407 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000408 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000409 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
410 }
Chris Lattner80230302010-09-11 21:47:09 +0000411 bool isTrapvOverflowBehavior() {
412 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
413 == LangOptions::SOB_Trapping;
414 }
Mike Stump2add4732009-04-01 20:28:16 +0000415 /// Create a binary op that checks for overflow.
416 /// Currently only supports +, - and *.
417 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner80230302010-09-11 21:47:09 +0000418 // Emit the overflow BB when -ftrapv option is activated.
419 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
420 Builder.SetInsertPoint(overflowBB);
421 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
422 Builder.CreateCall(Trap);
423 Builder.CreateUnreachable();
424 }
425 // Check for undefined division and modulus behaviors.
426 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
427 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000428 Value *EmitDiv(const BinOpInfo &Ops);
429 Value *EmitRem(const BinOpInfo &Ops);
430 Value *EmitAdd(const BinOpInfo &Ops);
431 Value *EmitSub(const BinOpInfo &Ops);
432 Value *EmitShl(const BinOpInfo &Ops);
433 Value *EmitShr(const BinOpInfo &Ops);
434 Value *EmitAnd(const BinOpInfo &Ops) {
435 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
436 }
437 Value *EmitXor(const BinOpInfo &Ops) {
438 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
439 }
440 Value *EmitOr (const BinOpInfo &Ops) {
441 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
442 }
443
Chris Lattner1f1ded92007-08-24 21:00:35 +0000444 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000445 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
446 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000447 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000448
Chris Lattner3ccf7742007-08-26 21:41:21 +0000449 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000450 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
451
452 // Binary operators and binary compound assignment operators.
453#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000454 Value *VisitBin ## OP(const BinaryOperator *E) { \
455 return Emit ## OP(EmitBinOps(E)); \
456 } \
457 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
458 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000459 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000460 HANDLEBINOP(Mul)
461 HANDLEBINOP(Div)
462 HANDLEBINOP(Rem)
463 HANDLEBINOP(Add)
464 HANDLEBINOP(Sub)
465 HANDLEBINOP(Shl)
466 HANDLEBINOP(Shr)
467 HANDLEBINOP(And)
468 HANDLEBINOP(Xor)
469 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000470#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000471
Chris Lattner7f02f722007-08-24 05:35:26 +0000472 // Comparisons.
473 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
474 unsigned SICmpOpc, unsigned FCmpOpc);
475#define VISITCOMP(CODE, UI, SI, FP) \
476 Value *VisitBin##CODE(const BinaryOperator *E) { \
477 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
478 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000479 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
480 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
481 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
482 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
483 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
484 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000485#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000486
Chris Lattner7f02f722007-08-24 05:35:26 +0000487 Value *VisitBinAssign (const BinaryOperator *E);
488
489 Value *VisitBinLAnd (const BinaryOperator *E);
490 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000491 Value *VisitBinComma (const BinaryOperator *E);
492
Eli Friedman25b825d2009-11-18 09:41:26 +0000493 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
494 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
495
Chris Lattner7f02f722007-08-24 05:35:26 +0000496 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000497 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000498 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000499 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000500 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000501 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
502 return CGF.EmitObjCStringLiteral(E);
503 }
504};
505} // end anonymous namespace.
506
507//===----------------------------------------------------------------------===//
508// Utilities
509//===----------------------------------------------------------------------===//
510
Chris Lattner9abc84e2007-08-26 16:42:57 +0000511/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000512/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000513Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000514 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000515
John McCalldaa8e4e2010-11-15 09:13:47 +0000516 if (SrcType->isRealFloatingType())
517 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000518
John McCall0bab0cd2010-08-23 01:21:21 +0000519 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
520 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000521
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000522 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000523 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000524
John McCalldaa8e4e2010-11-15 09:13:47 +0000525 if (isa<llvm::IntegerType>(Src->getType()))
526 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000527
John McCalldaa8e4e2010-11-15 09:13:47 +0000528 assert(isa<llvm::PointerType>(Src->getType()));
529 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000530}
531
Chris Lattner3707b252007-08-26 06:48:56 +0000532/// EmitScalarConversion - Emit a conversion from the specified type to the
533/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000534Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
535 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000536 SrcType = CGF.getContext().getCanonicalType(SrcType);
537 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000538 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000539
Chris Lattnercf289082007-08-26 07:21:11 +0000540 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000541
Chris Lattner3707b252007-08-26 06:48:56 +0000542 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000543 if (DstType->isBooleanType())
544 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000545
Chris Lattner3707b252007-08-26 06:48:56 +0000546 const llvm::Type *DstTy = ConvertType(DstType);
547
548 // Ignore conversions like int -> uint.
549 if (Src->getType() == DstTy)
550 return Src;
551
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000552 // Handle pointer conversions next: pointers can only be converted to/from
553 // other pointers and integers. Check for pointer types in terms of LLVM, as
554 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000555 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000556 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000557 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000558 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000559
Chris Lattner3707b252007-08-26 06:48:56 +0000560 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000561 // First, convert to the correct width so that we control the kind of
562 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +0000563 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Eli Friedman25615422009-03-04 04:02:35 +0000564 bool InputSigned = SrcType->isSignedIntegerType();
565 llvm::Value* IntResult =
566 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
567 // Then, cast to pointer.
568 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000569 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000570
Daniel Dunbar270cc662008-08-25 09:51:32 +0000571 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000572 // Must be an ptr to int cast.
573 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000574 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000575 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000576
Nate Begeman213541a2008-04-18 23:10:10 +0000577 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000578 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000579 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000580 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000581 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
582
583 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000584 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +0000585 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000586 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
587
588 // Splat the element across to all elements
589 llvm::SmallVector<llvm::Constant*, 16> Args;
590 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattnerfb018d12011-02-15 00:14:06 +0000591 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner77b89b82010-06-27 07:15:29 +0000592 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000593
Chris Lattnerfb018d12011-02-15 00:14:06 +0000594 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000595 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
596 return Yay;
597 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000598
Chris Lattner3b1ae002008-02-02 04:51:41 +0000599 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000600 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000601 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000602 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000603
Chris Lattner3707b252007-08-26 06:48:56 +0000604 // Finally, we have the arithmetic types: real int/float.
605 if (isa<llvm::IntegerType>(Src->getType())) {
606 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000607 if (isa<llvm::IntegerType>(DstTy))
608 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
609 else if (InputSigned)
610 return Builder.CreateSIToFP(Src, DstTy, "conv");
611 else
612 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000613 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000614
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000615 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
Chris Lattner3707b252007-08-26 06:48:56 +0000616 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000617 if (DstType->isSignedIntegerType())
618 return Builder.CreateFPToSI(Src, DstTy, "conv");
619 else
620 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000621 }
622
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000623 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000624 if (DstTy->getTypeID() < Src->getType()->getTypeID())
625 return Builder.CreateFPTrunc(Src, DstTy, "conv");
626 else
627 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000628}
629
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000630/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
631/// type to the specified destination type, where the destination type is an
632/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000633Value *ScalarExprEmitter::
634EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
635 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000636 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000637 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000638
Chris Lattnered70f0a2007-08-26 16:52:28 +0000639 // Handle conversions to bool first, they are special: comparisons against 0.
640 if (DstTy->isBooleanType()) {
641 // Complex != 0 -> (Real != 0) | (Imag != 0)
642 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
643 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
644 return Builder.CreateOr(Src.first, Src.second, "tobool");
645 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000646
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000647 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
648 // the imaginary part of the complex value is discarded and the value of the
649 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000650 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000651 return EmitScalarConversion(Src.first, SrcTy, DstTy);
652}
653
Anders Carlssona40a9f32010-05-22 17:45:10 +0000654Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000655 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
656 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
657
658 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000659}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000660
Chris Lattner7f02f722007-08-24 05:35:26 +0000661//===----------------------------------------------------------------------===//
662// Visitor Methods
663//===----------------------------------------------------------------------===//
664
665Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000666 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000667 if (E->getType()->isVoidType())
668 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000669 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000670}
671
Eli Friedmand38617c2008-05-14 19:38:39 +0000672Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000673 // Vector Mask Case
674 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000675 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000676 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
677 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
678 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000679
Nate Begeman37b6a572010-06-08 00:16:34 +0000680 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
681 unsigned LHSElts = LTy->getNumElements();
682
683 if (E->getNumSubExprs() == 3) {
684 Mask = CGF.EmitScalarExpr(E->getExpr(2));
685
686 // Shuffle LHS & RHS into one input vector.
687 llvm::SmallVector<llvm::Constant*, 32> concat;
688 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000689 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i));
690 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000691 }
692
Chris Lattnerfb018d12011-02-15 00:14:06 +0000693 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000694 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
695 LHSElts *= 2;
696 } else {
697 Mask = RHS;
698 }
699
700 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
701 llvm::Constant* EltMask;
702
703 // Treat vec3 like vec4.
704 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
705 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
706 (1 << llvm::Log2_32(LHSElts+2))-1);
707 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
708 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
709 (1 << llvm::Log2_32(LHSElts+1))-1);
710 else
711 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
712 (1 << llvm::Log2_32(LHSElts))-1);
713
714 // Mask off the high bits of each shuffle index.
715 llvm::SmallVector<llvm::Constant *, 32> MaskV;
716 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
717 MaskV.push_back(EltMask);
718
Chris Lattnerfb018d12011-02-15 00:14:06 +0000719 Value* MaskBits = llvm::ConstantVector::get(MaskV);
Nate Begeman37b6a572010-06-08 00:16:34 +0000720 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
721
722 // newv = undef
723 // mask = mask & maskbits
724 // for each elt
725 // n = extract mask i
726 // x = extract val n
727 // newv = insert newv, x, i
728 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
729 MTy->getNumElements());
730 Value* NewV = llvm::UndefValue::get(RTy);
731 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000732 Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000733 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000734 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000735
736 // Handle vec3 special since the index will be off by one for the RHS.
737 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
738 Value *cmpIndx, *newIndx;
Chris Lattner77b89b82010-06-27 07:15:29 +0000739 cmpIndx = Builder.CreateICmpUGT(Indx,
740 llvm::ConstantInt::get(CGF.Int32Ty, 3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000741 "cmp_shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000742 newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1),
Nate Begeman37b6a572010-06-08 00:16:34 +0000743 "shuf_idx_adj");
744 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
745 }
746 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
747 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
748 }
749 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000750 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000751
Eli Friedmand38617c2008-05-14 19:38:39 +0000752 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
753 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000754
755 // Handle vec3 special since the index will be off by one for the RHS.
756 llvm::SmallVector<llvm::Constant*, 32> indices;
757 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
758 llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
759 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
760 if (VTy->getNumElements() == 3) {
761 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
762 uint64_t cVal = CI->getZExtValue();
763 if (cVal > 3) {
764 C = llvm::ConstantInt::get(C->getType(), cVal-1);
765 }
766 }
767 }
768 indices.push_back(C);
769 }
770
Chris Lattnerfb018d12011-02-15 00:14:06 +0000771 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000772 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
773}
Eli Friedman28665272009-11-26 03:22:21 +0000774Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
775 Expr::EvalResult Result;
776 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
777 if (E->isArrow())
778 CGF.EmitScalarExpr(E->getBase());
779 else
780 EmitLValue(E->getBase());
781 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
782 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000783
784 // Emit debug info for aggregate now, if it was delayed to reduce
785 // debug info size.
786 CGDebugInfo *DI = CGF.getDebugInfo();
787 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
788 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
789 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000790 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Devang Patel78ba3d42010-10-04 21:46:04 +0000791 DI->getOrCreateRecordType(PTy->getPointeeType(),
792 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000793 }
Eli Friedman28665272009-11-26 03:22:21 +0000794 return EmitLoadOfLValue(E);
795}
Eli Friedmand38617c2008-05-14 19:38:39 +0000796
Chris Lattner7f02f722007-08-24 05:35:26 +0000797Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000798 TestAndClearIgnoreResultAssign();
799
Chris Lattner7f02f722007-08-24 05:35:26 +0000800 // Emit subscript expressions in rvalue context's. For most cases, this just
801 // loads the lvalue formed by the subscript expr. However, we have to be
802 // careful, because the base of a vector subscript is occasionally an rvalue,
803 // so we can't get it as an lvalue.
804 if (!E->getBase()->getType()->isVectorType())
805 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000806
Chris Lattner7f02f722007-08-24 05:35:26 +0000807 // Handle the vector case. The base must be a vector, the index must be an
808 // integer value.
809 Value *Base = Visit(E->getBase());
810 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000811 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000812 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000813 return Builder.CreateExtractElement(Base, Idx, "vecext");
814}
815
Nate Begeman0533b302009-10-18 20:10:40 +0000816static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
817 unsigned Off, const llvm::Type *I32Ty) {
818 int MV = SVI->getMaskValue(Idx);
819 if (MV == -1)
820 return llvm::UndefValue::get(I32Ty);
821 return llvm::ConstantInt::get(I32Ty, Off+MV);
822}
823
824Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
825 bool Ignore = TestAndClearIgnoreResultAssign();
826 (void)Ignore;
827 assert (Ignore == false && "init list ignored");
828 unsigned NumInitElements = E->getNumInits();
829
830 if (E->hadArrayRangeDesignator())
831 CGF.ErrorUnsupported(E, "GNU array range designator extension");
832
833 const llvm::VectorType *VType =
834 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
835
836 // We have a scalar in braces. Just use the first element.
837 if (!VType)
838 return Visit(E->getInit(0));
839
840 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000841
842 // Loop over initializers collecting the Value for each, and remembering
843 // whether the source was swizzle (ExtVectorElementExpr). This will allow
844 // us to fold the shuffle for the swizzle into the shuffle for the vector
845 // initializer, since LLVM optimizers generally do not want to touch
846 // shuffles.
847 unsigned CurIdx = 0;
848 bool VIsUndefShuffle = false;
849 llvm::Value *V = llvm::UndefValue::get(VType);
850 for (unsigned i = 0; i != NumInitElements; ++i) {
851 Expr *IE = E->getInit(i);
852 Value *Init = Visit(IE);
853 llvm::SmallVector<llvm::Constant*, 16> Args;
854
855 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
856
857 // Handle scalar elements. If the scalar initializer is actually one
858 // element of a different vector of the same width, use shuffle instead of
859 // extract+insert.
860 if (!VVT) {
861 if (isa<ExtVectorElementExpr>(IE)) {
862 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
863
864 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
865 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
866 Value *LHS = 0, *RHS = 0;
867 if (CurIdx == 0) {
868 // insert into undef -> shuffle (src, undef)
869 Args.push_back(C);
870 for (unsigned j = 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000871 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000872
873 LHS = EI->getVectorOperand();
874 RHS = V;
875 VIsUndefShuffle = true;
876 } else if (VIsUndefShuffle) {
877 // insert into undefshuffle && size match -> shuffle (v, src)
878 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
879 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000880 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
881 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
Nate Begeman0533b302009-10-18 20:10:40 +0000882 ResElts + C->getZExtValue()));
883 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000884 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000885
886 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
887 RHS = EI->getVectorOperand();
888 VIsUndefShuffle = false;
889 }
890 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000891 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000892 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
893 ++CurIdx;
894 continue;
895 }
896 }
897 }
Chris Lattner77b89b82010-06-27 07:15:29 +0000898 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000899 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
900 VIsUndefShuffle = false;
901 ++CurIdx;
902 continue;
903 }
904
905 unsigned InitElts = VVT->getNumElements();
906
907 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
908 // input is the same width as the vector being constructed, generate an
909 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000910 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000911 if (isa<ExtVectorElementExpr>(IE)) {
912 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
913 Value *SVOp = SVI->getOperand(0);
914 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
915
916 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000917 for (unsigned j = 0; j != CurIdx; ++j) {
918 // If the current vector initializer is a shuffle with undef, merge
919 // this shuffle directly into it.
920 if (VIsUndefShuffle) {
921 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000922 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000923 } else {
Chris Lattner77b89b82010-06-27 07:15:29 +0000924 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000925 }
926 }
927 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000928 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000929 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000930 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000931
932 if (VIsUndefShuffle)
933 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
934
935 Init = SVOp;
936 }
937 }
938
939 // Extend init to result vector length, and then shuffle its contribution
940 // to the vector initializer into V.
941 if (Args.empty()) {
942 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000943 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000944 for (unsigned j = InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000945 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000946 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000947 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000948 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000949
950 Args.clear();
951 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000952 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000953 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000954 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000955 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000956 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000957 }
958
959 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
960 // merging subsequent shuffles into this one.
961 if (CurIdx == 0)
962 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000963 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000964 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
965 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
966 CurIdx += InitElts;
967 }
968
969 // FIXME: evaluate codegen vs. shuffling against constant null vector.
970 // Emit remaining default initializers.
971 const llvm::Type *EltTy = VType->getElementType();
972
973 // Emit remaining default initializers
974 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000975 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000976 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
977 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
978 }
979 return V;
980}
981
Anders Carlssona3697c92009-11-23 17:57:54 +0000982static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
983 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +0000984
John McCall2de56d12010-08-25 11:45:40 +0000985 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +0000986 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +0000987
988 if (isa<CXXThisExpr>(E)) {
989 // We always assume that 'this' is never null.
990 return false;
991 }
992
993 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000994 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +0000995 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +0000996 return false;
997 }
998
999 return true;
1000}
1001
Chris Lattner7f02f722007-08-24 05:35:26 +00001002// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1003// have to handle a more broad range of conversions than explicit casts, as they
1004// handle things like function to ptr-to-function decay etc.
Eli Friedmand8889622009-11-27 04:41:50 +00001005Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
1006 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001007 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001008 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001009
Mike Stump7f79f9b2009-05-29 15:46:01 +00001010 if (!DestTy->isVoidType())
1011 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001012
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001013 // Since almost all cast kinds apply to scalars, this switch doesn't have
1014 // a default case, so the compiler will warn on a missing case. The cases
1015 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001016 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001017 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1018
John McCall2de56d12010-08-25 11:45:40 +00001019 case CK_LValueBitCast:
1020 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001021 Value *V = EmitLValue(E).getAddress();
1022 V = Builder.CreateBitCast(V,
1023 ConvertType(CGF.getContext().getPointerType(DestTy)));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00001024 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy);
Douglas Gregore39a3892010-07-13 23:17:26 +00001025 }
1026
John McCall2de56d12010-08-25 11:45:40 +00001027 case CK_AnyPointerToObjCPointerCast:
1028 case CK_AnyPointerToBlockPointerCast:
1029 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001030 Value *Src = Visit(const_cast<Expr*>(E));
1031 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1032 }
John McCall2de56d12010-08-25 11:45:40 +00001033 case CK_NoOp:
1034 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001035 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001036
John McCall2de56d12010-08-25 11:45:40 +00001037 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00001038 const CXXRecordDecl *DerivedClassDecl =
1039 DestTy->getCXXRecordDeclForPointerType();
1040
Anders Carlssona04efdf2010-04-24 21:23:59 +00001041 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001042 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001043 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001044 }
John McCall2de56d12010-08-25 11:45:40 +00001045 case CK_UncheckedDerivedToBase:
1046 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +00001047 const RecordType *DerivedClassTy =
1048 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1049 CXXRecordDecl *DerivedClassDecl =
1050 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1051
Anders Carlsson34a2d382010-04-24 21:06:20 +00001052 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001053 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001054 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001055 }
John McCall2de56d12010-08-25 11:45:40 +00001056 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001057 Value *V = Visit(const_cast<Expr*>(E));
1058 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1059 return CGF.EmitDynamicCast(V, DCE);
1060 }
Eli Friedmand8889622009-11-27 04:41:50 +00001061
John McCall2de56d12010-08-25 11:45:40 +00001062 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001063 assert(E->getType()->isArrayType() &&
1064 "Array to pointer decay must have array source type!");
1065
1066 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1067
1068 // Note that VLA pointers are always decayed, so we don't need to do
1069 // anything here.
1070 if (!E->getType()->isVariableArrayType()) {
1071 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1072 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1073 ->getElementType()) &&
1074 "Expected pointer to array");
1075 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1076 }
1077
1078 return V;
1079 }
John McCall2de56d12010-08-25 11:45:40 +00001080 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001081 return EmitLValue(E).getAddress();
1082
John McCall404cd162010-11-13 01:35:44 +00001083 case CK_NullToPointer:
1084 if (MustVisitNullValue(E))
1085 (void) Visit(E);
1086
1087 return llvm::ConstantPointerNull::get(
1088 cast<llvm::PointerType>(ConvertType(DestTy)));
1089
John McCall2de56d12010-08-25 11:45:40 +00001090 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001091 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001092 (void) Visit(E);
1093
John McCall0bab0cd2010-08-23 01:21:21 +00001094 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1095 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1096 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001097
John McCall2de56d12010-08-25 11:45:40 +00001098 case CK_BaseToDerivedMemberPointer:
1099 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001100 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001101
1102 // Note that the AST doesn't distinguish between checked and
1103 // unchecked member pointer conversions, so we always have to
1104 // implement checked conversions here. This is inefficient when
1105 // actual control flow may be required in order to perform the
1106 // check, which it is for data member pointers (but not member
1107 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001108 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001109 }
John McCall0bab0cd2010-08-23 01:21:21 +00001110
John McCall2bb5d002010-11-13 09:02:35 +00001111 case CK_FloatingRealToComplex:
1112 case CK_FloatingComplexCast:
1113 case CK_IntegralRealToComplex:
1114 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001115 case CK_IntegralComplexToFloatingComplex:
1116 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001117 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001118 case CK_ToUnion:
1119 llvm_unreachable("scalar cast to non-scalar value");
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001120 break;
John McCallf6a16482010-12-04 03:47:34 +00001121
1122 case CK_GetObjCProperty: {
1123 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
Douglas Gregorda29e092011-01-22 02:44:21 +00001124 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty &&
John McCallf6a16482010-12-04 03:47:34 +00001125 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
1126 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType());
1127 return RV.getScalarVal();
1128 }
John McCall0ae287a2010-12-01 04:43:34 +00001129
1130 case CK_LValueToRValue:
1131 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001132 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001133 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001134
John McCall2de56d12010-08-25 11:45:40 +00001135 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001136 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001137
Anders Carlsson82debc72009-10-18 18:12:03 +00001138 // First, convert to the correct width so that we control the kind of
1139 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +00001140 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Anders Carlsson82debc72009-10-18 18:12:03 +00001141 bool InputSigned = E->getType()->isSignedIntegerType();
1142 llvm::Value* IntResult =
1143 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001144
Anders Carlsson82debc72009-10-18 18:12:03 +00001145 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001146 }
John McCall2de56d12010-08-25 11:45:40 +00001147 case CK_PointerToIntegral: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001148 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001149
1150 // Handle conversion to bool correctly.
1151 if (DestTy->isBooleanType())
Daniel Dunbardb505472010-09-03 02:07:00 +00001152 return EmitScalarConversion(Src, E->getType(), DestTy);
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001153
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001154 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1155 }
John McCall2de56d12010-08-25 11:45:40 +00001156 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001157 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001158 return 0;
1159 }
John McCall2de56d12010-08-25 11:45:40 +00001160 case CK_VectorSplat: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001161 const llvm::Type *DstTy = ConvertType(DestTy);
1162 Value *Elt = Visit(const_cast<Expr*>(E));
1163
1164 // Insert the element in element zero of an undef vector
1165 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +00001166 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001167 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1168
1169 // Splat the element across to all elements
1170 llvm::SmallVector<llvm::Constant*, 16> Args;
1171 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
John McCalldaa8e4e2010-11-15 09:13:47 +00001172 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001173 for (unsigned i = 0; i < NumElements; i++)
John McCalldaa8e4e2010-11-15 09:13:47 +00001174 Args.push_back(Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001175
Chris Lattnerfb018d12011-02-15 00:14:06 +00001176 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Eli Friedmanad35a832009-11-16 21:33:53 +00001177 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1178 return Yay;
1179 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001180
John McCall2de56d12010-08-25 11:45:40 +00001181 case CK_IntegralCast:
1182 case CK_IntegralToFloating:
1183 case CK_FloatingToIntegral:
1184 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001185 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001186
John McCalldaa8e4e2010-11-15 09:13:47 +00001187 case CK_IntegralToBoolean:
1188 return EmitIntToBoolConversion(Visit(E));
1189 case CK_PointerToBoolean:
1190 return EmitPointerToBoolConversion(Visit(E));
1191 case CK_FloatingToBoolean:
1192 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001193 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001194 llvm::Value *MemPtr = Visit(E);
1195 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1196 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001197 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001198
1199 case CK_FloatingComplexToReal:
1200 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001201 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001202
1203 case CK_FloatingComplexToBoolean:
1204 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001205 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001206
1207 // TODO: kill this function off, inline appropriate case here
1208 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1209 }
1210
John McCall0bab0cd2010-08-23 01:21:21 +00001211 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001212
John McCall61ad0e62010-11-16 06:21:14 +00001213 llvm_unreachable("unknown scalar cast");
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001214 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +00001215}
1216
Chris Lattner33793202007-08-31 22:09:40 +00001217Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001218 CodeGenFunction::StmtExprEvaluation eval(CGF);
1219 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1220 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001221}
1222
Mike Stumpa99038c2009-02-28 09:07:16 +00001223Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
John McCalla5bcb8f2011-03-16 02:53:38 +00001224 LValue LV = CGF.EmitBlockDeclRefLValue(E);
1225 return CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
Mike Stump4e7a1f72009-02-21 20:00:35 +00001226}
Chris Lattner33793202007-08-31 22:09:40 +00001227
Chris Lattner7f02f722007-08-24 05:35:26 +00001228//===----------------------------------------------------------------------===//
1229// Unary Operators
1230//===----------------------------------------------------------------------===//
1231
Chris Lattner8c11a652010-06-26 22:09:34 +00001232llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001233EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1234 llvm::Value *InVal,
1235 llvm::Value *NextVal, bool IsInc) {
1236 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1237 case LangOptions::SOB_Undefined:
1238 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1239 break;
1240 case LangOptions::SOB_Defined:
1241 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1242 break;
1243 case LangOptions::SOB_Trapping:
1244 BinOpInfo BinOp;
1245 BinOp.LHS = InVal;
1246 BinOp.RHS = NextVal;
1247 BinOp.Ty = E->getType();
1248 BinOp.Opcode = BO_Add;
1249 BinOp.E = E;
1250 return EmitOverflowCheckedBinOp(BinOp);
1251 break;
1252 }
1253 assert(false && "Unknown SignedOverflowBehaviorTy");
1254 return 0;
1255}
1256
John McCall5936e332011-02-15 09:22:45 +00001257llvm::Value *
1258ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1259 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001260
John McCall5936e332011-02-15 09:22:45 +00001261 QualType type = E->getSubExpr()->getType();
1262 llvm::Value *value = EmitLoadOfLValue(LV, type);
1263 llvm::Value *input = value;
Anton Yartsev683564a2011-02-07 02:17:30 +00001264
John McCall5936e332011-02-15 09:22:45 +00001265 int amount = (isInc ? 1 : -1);
1266
1267 // Special case of integer increment that we have to check first: bool++.
1268 // Due to promotion rules, we get:
1269 // bool++ -> bool = bool + 1
1270 // -> bool = (int)bool + 1
1271 // -> bool = ((int)bool + 1 != 0)
1272 // An interesting aspect of this is that increment is always true.
1273 // Decrement does not have this property.
1274 if (isInc && type->isBooleanType()) {
1275 value = Builder.getTrue();
1276
1277 // Most common case by far: integer increment.
1278 } else if (type->isIntegerType()) {
1279
1280 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1281
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001282 // Note that signed integer inc/dec with width less than int can't
1283 // overflow because of promotion rules; we're just eliding a few steps here.
1284 if (type->isSignedIntegerType() &&
1285 value->getType()->getPrimitiveSizeInBits() >=
1286 CGF.CGM.IntTy->getBitWidth())
John McCall5936e332011-02-15 09:22:45 +00001287 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
John McCall5936e332011-02-15 09:22:45 +00001288 else
1289 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1290
1291 // Next most common: pointer increment.
1292 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1293 QualType type = ptr->getPointeeType();
1294
1295 // VLA types don't have constant size.
1296 if (type->isVariableArrayType()) {
1297 llvm::Value *vlaSize =
1298 CGF.GetVLASize(CGF.getContext().getAsVariableArrayType(type));
1299 value = CGF.EmitCastToVoidPtr(value);
1300 if (!isInc) vlaSize = Builder.CreateNSWNeg(vlaSize, "vla.negsize");
Chris Lattner2cb42222011-03-01 00:03:48 +00001301 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1302 value = Builder.CreateGEP(value, vlaSize, "vla.inc");
1303 else
1304 value = Builder.CreateInBoundsGEP(value, vlaSize, "vla.inc");
John McCall5936e332011-02-15 09:22:45 +00001305 value = Builder.CreateBitCast(value, input->getType());
1306
1307 // Arithmetic on function pointers (!) is just +-1.
1308 } else if (type->isFunctionType()) {
1309 llvm::Value *amt = llvm::ConstantInt::get(CGF.Int32Ty, amount);
1310
1311 value = CGF.EmitCastToVoidPtr(value);
Chris Lattner2cb42222011-03-01 00:03:48 +00001312 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1313 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1314 else
1315 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001316 value = Builder.CreateBitCast(value, input->getType());
1317
1318 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001319 } else {
John McCall5936e332011-02-15 09:22:45 +00001320 llvm::Value *amt = llvm::ConstantInt::get(CGF.Int32Ty, amount);
Chris Lattner2cb42222011-03-01 00:03:48 +00001321 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1322 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1323 else
1324 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001325 }
1326
1327 // Vector increment/decrement.
1328 } else if (type->isVectorType()) {
1329 if (type->hasIntegerRepresentation()) {
1330 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1331
1332 if (type->hasSignedIntegerRepresentation())
1333 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1334 else
1335 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1336 } else {
1337 value = Builder.CreateFAdd(
1338 value,
1339 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001340 isInc ? "inc" : "dec");
1341 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001342
John McCall5936e332011-02-15 09:22:45 +00001343 // Floating point.
1344 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001345 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001346 llvm::Value *amt;
1347 if (value->getType()->isFloatTy())
1348 amt = llvm::ConstantFP::get(VMContext,
1349 llvm::APFloat(static_cast<float>(amount)));
1350 else if (value->getType()->isDoubleTy())
1351 amt = llvm::ConstantFP::get(VMContext,
1352 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001353 else {
John McCall5936e332011-02-15 09:22:45 +00001354 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001355 bool ignored;
1356 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1357 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001358 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001359 }
John McCall5936e332011-02-15 09:22:45 +00001360 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1361
1362 // Objective-C pointer types.
1363 } else {
1364 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1365 value = CGF.EmitCastToVoidPtr(value);
1366
1367 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1368 if (!isInc) size = -size;
1369 llvm::Value *sizeValue =
1370 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1371
Chris Lattner2cb42222011-03-01 00:03:48 +00001372 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1373 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1374 else
1375 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001376 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001377 }
1378
1379 // Store the updated result through the lvalue.
1380 if (LV.isBitField())
John McCall5936e332011-02-15 09:22:45 +00001381 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, type, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001382 else
John McCall5936e332011-02-15 09:22:45 +00001383 CGF.EmitStoreThroughLValue(RValue::get(value), LV, type);
Chris Lattner8c11a652010-06-26 22:09:34 +00001384
1385 // If this is a postinc, return the value read from memory, otherwise use the
1386 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001387 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001388}
1389
1390
1391
Chris Lattner7f02f722007-08-24 05:35:26 +00001392Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001393 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001394 // Emit unary minus with EmitSub so we handle overflow cases etc.
1395 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001396 BinOp.RHS = Visit(E->getSubExpr());
1397
1398 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1399 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1400 else
1401 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001402 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001403 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001404 BinOp.E = E;
1405 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001406}
1407
1408Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001409 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001410 Value *Op = Visit(E->getSubExpr());
1411 return Builder.CreateNot(Op, "neg");
1412}
1413
1414Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1415 // Compare operand to zero.
1416 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001417
Chris Lattner7f02f722007-08-24 05:35:26 +00001418 // Invert value.
1419 // TODO: Could dynamically modify easy computations here. For example, if
1420 // the operand is an icmp ne, turn into icmp eq.
1421 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001422
Anders Carlsson9f84d882009-05-19 18:44:53 +00001423 // ZExt result to the expr type.
1424 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001425}
1426
Eli Friedman0027d2b2010-08-05 09:58:49 +00001427Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1428 // Try folding the offsetof to a constant.
1429 Expr::EvalResult EvalResult;
1430 if (E->Evaluate(EvalResult, CGF.getContext()))
1431 return llvm::ConstantInt::get(VMContext, EvalResult.Val.getInt());
1432
1433 // Loop over the components of the offsetof to compute the value.
1434 unsigned n = E->getNumComponents();
1435 const llvm::Type* ResultType = ConvertType(E->getType());
1436 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1437 QualType CurrentType = E->getTypeSourceInfo()->getType();
1438 for (unsigned i = 0; i != n; ++i) {
1439 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001440 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001441 switch (ON.getKind()) {
1442 case OffsetOfExpr::OffsetOfNode::Array: {
1443 // Compute the index
1444 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1445 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1446 bool IdxSigned = IdxExpr->getType()->isSignedIntegerType();
1447 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1448
1449 // Save the element type
1450 CurrentType =
1451 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1452
1453 // Compute the element size
1454 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1455 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1456
1457 // Multiply out to compute the result
1458 Offset = Builder.CreateMul(Idx, ElemSize);
1459 break;
1460 }
1461
1462 case OffsetOfExpr::OffsetOfNode::Field: {
1463 FieldDecl *MemberDecl = ON.getField();
1464 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1465 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1466
1467 // Compute the index of the field in its parent.
1468 unsigned i = 0;
1469 // FIXME: It would be nice if we didn't have to loop here!
1470 for (RecordDecl::field_iterator Field = RD->field_begin(),
1471 FieldEnd = RD->field_end();
1472 Field != FieldEnd; (void)++Field, ++i) {
1473 if (*Field == MemberDecl)
1474 break;
1475 }
1476 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1477
1478 // Compute the offset to the field
1479 int64_t OffsetInt = RL.getFieldOffset(i) /
1480 CGF.getContext().getCharWidth();
1481 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1482
1483 // Save the element type.
1484 CurrentType = MemberDecl->getType();
1485 break;
1486 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001487
Eli Friedman0027d2b2010-08-05 09:58:49 +00001488 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001489 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001490
Eli Friedman0027d2b2010-08-05 09:58:49 +00001491 case OffsetOfExpr::OffsetOfNode::Base: {
1492 if (ON.getBase()->isVirtual()) {
1493 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1494 continue;
1495 }
1496
1497 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1498 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1499
1500 // Save the element type.
1501 CurrentType = ON.getBase()->getType();
1502
1503 // Compute the offset to the base.
1504 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1505 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Anders Carlssona14f5972010-10-31 23:22:37 +00001506 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
Eli Friedman0027d2b2010-08-05 09:58:49 +00001507 CGF.getContext().getCharWidth();
1508 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1509 break;
1510 }
1511 }
1512 Result = Builder.CreateAdd(Result, Offset);
1513 }
1514 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001515}
1516
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001517/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001518/// argument of the sizeof expression as an integer.
1519Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001520ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1521 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001522 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001523 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001524 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001525 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1526 if (E->isArgumentType()) {
1527 // sizeof(type) - make sure to emit the VLA size.
1528 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001529 } else {
1530 // C99 6.5.3.4p2: If the argument is an expression of type
1531 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001532 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001533 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001534
Anders Carlsson96f21472009-02-05 19:43:10 +00001535 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +00001536 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001537 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001538
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001539 // If this isn't sizeof(vla), the result must be constant; use the constant
1540 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001541 Expr::EvalResult Result;
1542 E->Evaluate(Result, CGF.getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001543 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001544}
1545
Chris Lattner46f93d02007-08-24 21:20:17 +00001546Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1547 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001548 if (Op->getType()->isAnyComplexType()) {
1549 // If it's an l-value, load through the appropriate subobject l-value.
1550 // Note that we have to ask E because Op might be an l-value that
1551 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001552 if (E->isGLValue())
John McCallb418d742010-11-16 10:08:07 +00001553 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1554 .getScalarVal();
1555
1556 // Otherwise, calculate and project.
1557 return CGF.EmitComplexExpr(Op, false, true).first;
1558 }
1559
Chris Lattner46f93d02007-08-24 21:20:17 +00001560 return Visit(Op);
1561}
John McCallb418d742010-11-16 10:08:07 +00001562
Chris Lattner46f93d02007-08-24 21:20:17 +00001563Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1564 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001565 if (Op->getType()->isAnyComplexType()) {
1566 // If it's an l-value, load through the appropriate subobject l-value.
1567 // Note that we have to ask E because Op might be an l-value that
1568 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001569 if (Op->isGLValue())
John McCallb418d742010-11-16 10:08:07 +00001570 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1571 .getScalarVal();
1572
1573 // Otherwise, calculate and project.
1574 return CGF.EmitComplexExpr(Op, true, false).second;
1575 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001576
Mike Stump7f79f9b2009-05-29 15:46:01 +00001577 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1578 // effects are evaluated, but not the actual value.
John McCallb418d742010-11-16 10:08:07 +00001579 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001580 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001581}
1582
Chris Lattner7f02f722007-08-24 05:35:26 +00001583//===----------------------------------------------------------------------===//
1584// Binary Operators
1585//===----------------------------------------------------------------------===//
1586
1587BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001588 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001589 BinOpInfo Result;
1590 Result.LHS = Visit(E->getLHS());
1591 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001592 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001593 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001594 Result.E = E;
1595 return Result;
1596}
1597
Douglas Gregor6a03e342010-04-23 04:16:32 +00001598LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1599 const CompoundAssignOperator *E,
1600 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001601 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001602 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001603 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001604
Eli Friedmanab3a8522009-03-28 01:22:36 +00001605 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001606 // This needs to go through the complex expression emitter, but it's a tad
1607 // complicated to do that... I'm leaving it out for now. (Note that we do
1608 // actually need the imaginary part of the RHS for multiplication and
1609 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001610 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001611 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001612 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001613 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001614
Mike Stumpcc0442f2009-05-22 19:07:20 +00001615 // Emit the RHS first. __block variables need to have the rhs evaluated
1616 // first, plus this should improve codegen a little.
1617 OpInfo.RHS = Visit(E->getRHS());
1618 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001619 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001620 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001621 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001622 LValue LHSLV = EmitCheckedLValue(E->getLHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001623 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001624 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1625 E->getComputationLHSType());
Douglas Gregor6a03e342010-04-23 04:16:32 +00001626
Chris Lattner1f1ded92007-08-24 21:00:35 +00001627 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001628 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001629
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001630 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001631 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001632
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001633 // Store the result value into the LHS lvalue. Bit-fields are handled
1634 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1635 // 'An assignment expression has the value of the left operand after the
1636 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001637 if (LHSLV.isBitField())
1638 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1639 &Result);
1640 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001641 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001642
Douglas Gregor6a03e342010-04-23 04:16:32 +00001643 return LHSLV;
1644}
1645
1646Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1647 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1648 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001649 Value *RHS;
1650 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1651
1652 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001653 if (Ignore)
1654 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001655
John McCallb418d742010-11-16 10:08:07 +00001656 // The result of an assignment in C is the assigned r-value.
1657 if (!CGF.getContext().getLangOptions().CPlusPlus)
1658 return RHS;
1659
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001660 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00001661 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001662 return RHS;
1663
1664 // If the lvalue is non-volatile, return the computed value of the assignment.
1665 if (!LHS.isVolatileQualified())
1666 return RHS;
1667
1668 // Otherwise, reload the value.
1669 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001670}
1671
Chris Lattner80230302010-09-11 21:47:09 +00001672void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1673 const BinOpInfo &Ops,
1674 llvm::Value *Zero, bool isDiv) {
1675 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1676 llvm::BasicBlock *contBB =
1677 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn);
1678
1679 const llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1680
1681 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1682 llvm::Value *IntMin =
1683 llvm::ConstantInt::get(VMContext,
1684 llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1685 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1686
1687 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1688 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1689 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1690 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1691 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1692 overflowBB, contBB);
1693 } else {
1694 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1695 overflowBB, contBB);
1696 }
1697 EmitOverflowBB(overflowBB);
1698 Builder.SetInsertPoint(contBB);
1699}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001700
Chris Lattner7f02f722007-08-24 05:35:26 +00001701Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Chris Lattner80230302010-09-11 21:47:09 +00001702 if (isTrapvOverflowBehavior()) {
1703 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1704
1705 if (Ops.Ty->isIntegerType())
1706 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1707 else if (Ops.Ty->isRealFloatingType()) {
1708 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1709 CGF.CurFn);
1710 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn);
1711 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1712 overflowBB, DivCont);
1713 EmitOverflowBB(overflowBB);
1714 Builder.SetInsertPoint(DivCont);
1715 }
1716 }
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001717 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner7f02f722007-08-24 05:35:26 +00001718 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Douglas Gregorf6094622010-07-23 15:58:24 +00001719 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001720 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1721 else
1722 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1723}
1724
1725Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1726 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001727 if (isTrapvOverflowBehavior()) {
1728 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1729
1730 if (Ops.Ty->isIntegerType())
1731 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1732 }
1733
Chris Lattner1f1ded92007-08-24 21:00:35 +00001734 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001735 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1736 else
1737 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1738}
1739
Mike Stump2add4732009-04-01 20:28:16 +00001740Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1741 unsigned IID;
1742 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001743
Chris Lattner9a207232010-06-26 21:48:21 +00001744 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001745 case BO_Add:
1746 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001747 OpID = 1;
1748 IID = llvm::Intrinsic::sadd_with_overflow;
1749 break;
John McCall2de56d12010-08-25 11:45:40 +00001750 case BO_Sub:
1751 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001752 OpID = 2;
1753 IID = llvm::Intrinsic::ssub_with_overflow;
1754 break;
John McCall2de56d12010-08-25 11:45:40 +00001755 case BO_Mul:
1756 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001757 OpID = 3;
1758 IID = llvm::Intrinsic::smul_with_overflow;
1759 break;
1760 default:
1761 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001762 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001763 }
Mike Stump035cf892009-04-02 18:15:54 +00001764 OpID <<= 1;
1765 OpID |= 1;
1766
Mike Stump2add4732009-04-01 20:28:16 +00001767 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1768
1769 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1770
1771 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1772 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1773 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1774
1775 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001776 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Chris Lattner93a00352010-08-07 00:20:46 +00001777 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1778 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001779
1780 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1781
Chris Lattner93a00352010-08-07 00:20:46 +00001782 // Handle overflow with llvm.trap.
David Chisnall7f18e672010-09-17 18:29:54 +00001783 const std::string *handlerName =
1784 &CGF.getContext().getLangOptions().OverflowHandler;
1785 if (handlerName->empty()) {
1786 EmitOverflowBB(overflowBB);
1787 Builder.SetInsertPoint(continueBB);
1788 return result;
1789 }
1790
1791 // If an overflow handler is set, then we want to call it and then use its
1792 // result, if it returns.
1793 Builder.SetInsertPoint(overflowBB);
1794
1795 // Get the overflow handler.
1796 const llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
1797 std::vector<const llvm::Type*> argTypes;
1798 argTypes.push_back(CGF.Int64Ty); argTypes.push_back(CGF.Int64Ty);
1799 argTypes.push_back(Int8Ty); argTypes.push_back(Int8Ty);
1800 llvm::FunctionType *handlerTy =
1801 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1802 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1803
1804 // Sign extend the args to 64-bit, so that we can use the same handler for
1805 // all types of overflow.
1806 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1807 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1808
1809 // Call the handler with the two arguments, the operation, and the size of
1810 // the result.
1811 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1812 Builder.getInt8(OpID),
1813 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1814
1815 // Truncate the result back to the desired size.
1816 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1817 Builder.CreateBr(continueBB);
1818
Mike Stump2add4732009-04-01 20:28:16 +00001819 Builder.SetInsertPoint(continueBB);
David Chisnall7f18e672010-09-17 18:29:54 +00001820 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1821 phi->reserveOperandSpace(2);
1822 phi->addIncoming(result, initialBB);
1823 phi->addIncoming(handlerResult, overflowBB);
1824
1825 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001826}
Chris Lattner7f02f722007-08-24 05:35:26 +00001827
1828Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001829 if (!Ops.Ty->isAnyPointerType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001830 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001831 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1832 case LangOptions::SOB_Undefined:
1833 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1834 case LangOptions::SOB_Defined:
1835 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1836 case LangOptions::SOB_Trapping:
1837 return EmitOverflowCheckedBinOp(Ops);
1838 }
1839 }
1840
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001841 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001842 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanbf933a02009-08-12 01:16:29 +00001843
Chris Lattner7f02f722007-08-24 05:35:26 +00001844 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001845 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001846
Chris Lattner7f215c12010-06-26 21:52:32 +00001847 // Must have binary (not unary) expr here. Unary pointer decrement doesn't
Chris Lattner9a207232010-06-26 21:48:21 +00001848 // use this path.
1849 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1850
Steve Naroff14108da2009-07-10 23:34:53 +00001851 if (Ops.Ty->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001852 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001853 // The amount of the addition needs to account for the VLA size
Chris Lattner9a207232010-06-26 21:48:21 +00001854 CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001855 }
Chris Lattner9a207232010-06-26 21:48:21 +00001856
Chris Lattner8f925282008-01-03 06:36:51 +00001857 Value *Ptr, *Idx;
1858 Expr *IdxExp;
Chris Lattner9a207232010-06-26 21:48:21 +00001859 const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001860 const ObjCObjectPointerType *OPT =
Chris Lattner9a207232010-06-26 21:48:21 +00001861 BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001862 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001863 Ptr = Ops.LHS;
1864 Idx = Ops.RHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001865 IdxExp = BinOp->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001866 } else { // int + pointer
Chris Lattner9a207232010-06-26 21:48:21 +00001867 PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1868 OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001869 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001870 Ptr = Ops.RHS;
1871 Idx = Ops.LHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001872 IdxExp = BinOp->getLHS();
Chris Lattner8f925282008-01-03 06:36:51 +00001873 }
1874
1875 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
John McCall5936e332011-02-15 09:22:45 +00001876 if (Width < CGF.PointerWidthInBits) {
Chris Lattner8f925282008-01-03 06:36:51 +00001877 // Zero or sign extend the pointer value based on whether the index is
1878 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001879 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner96196622008-07-26 22:37:01 +00001880 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001881 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1882 else
1883 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1884 }
Steve Naroff14108da2009-07-10 23:34:53 +00001885 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001886 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001887 if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001888 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001889 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001890 CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001891 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001892 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001893 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1894 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1895 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001896 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001897
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001898 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1899 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1900 // future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001901 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001902 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001903 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001904 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001905 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001906 }
1907
Chris Lattner2cb42222011-03-01 00:03:48 +00001908 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1909 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Dan Gohman664f8932009-08-12 00:33:55 +00001910 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001911}
1912
1913Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001914 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001915 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001916 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1917 case LangOptions::SOB_Undefined:
1918 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1919 case LangOptions::SOB_Defined:
1920 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1921 case LangOptions::SOB_Trapping:
1922 return EmitOverflowCheckedBinOp(Ops);
1923 }
1924 }
1925
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001926 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001927 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00001928
Chris Lattner7f02f722007-08-24 05:35:26 +00001929 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001930 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001931
Chris Lattner9a207232010-06-26 21:48:21 +00001932 // Must have binary (not unary) expr here. Unary pointer increment doesn't
1933 // use this path.
1934 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1935
1936 if (BinOp->getLHS()->getType()->isPointerType() &&
1937 BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001938 // The amount of the addition needs to account for the VLA size for
1939 // ptr-int
1940 // The amount of the division needs to account for the VLA size for
1941 // ptr-ptr.
Chris Lattner9a207232010-06-26 21:48:21 +00001942 CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001943 }
1944
Chris Lattner9a207232010-06-26 21:48:21 +00001945 const QualType LHSType = BinOp->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001946 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001947 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1948 // pointer - int
1949 Value *Idx = Ops.RHS;
1950 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
John McCall5936e332011-02-15 09:22:45 +00001951 if (Width < CGF.PointerWidthInBits) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001952 // Zero or sign extend the pointer value based on whether the index is
1953 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001954 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner9a207232010-06-26 21:48:21 +00001955 if (BinOp->getRHS()->getType()->isSignedIntegerType())
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001956 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1957 else
1958 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1959 }
1960 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001961
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001962 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001963 if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001964 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001965 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001966 CGF.getContext().
1967 getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001968 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001969 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001970 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1971 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1972 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001973 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001974
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001975 // Explicitly handle GNU void* and function pointer arithmetic
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001976 // extensions. The GNU void* casts amount to no-ops since our void* type is
1977 // i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001978 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001979 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001980 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1981 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1982 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001983 }
1984
Chris Lattner2cb42222011-03-01 00:03:48 +00001985 if (CGF.getContext().getLangOptions().isSignedOverflowDefined())
1986 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Dan Gohman664f8932009-08-12 00:33:55 +00001987 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001988 }
Chris Lattner2cb42222011-03-01 00:03:48 +00001989
1990 // pointer - pointer
1991 Value *LHS = Ops.LHS;
1992 Value *RHS = Ops.RHS;
1993
1994 CharUnits ElementSize;
1995
1996 // Handle GCC extension for pointer arithmetic on void* and function pointer
1997 // types.
1998 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType())
1999 ElementSize = CharUnits::One();
2000 else
2001 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
2002
2003 const llvm::Type *ResultType = ConvertType(Ops.Ty);
2004 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
2005 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
2006 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
2007
2008 // Optimize out the shift for element size of 1.
2009 if (ElementSize.isOne())
2010 return BytesBetween;
2011
2012 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2013 // pointer difference in C is only defined in the case where both operands
2014 // are pointing to elements of an array.
2015 Value *BytesPerElt =
2016 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
2017 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002018}
2019
2020Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2021 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2022 // RHS to the same size as the LHS.
2023 Value *RHS = Ops.RHS;
2024 if (Ops.LHS->getType() != RHS->getType())
2025 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002026
Mike Stumpbe07f602009-12-14 21:58:14 +00002027 if (CGF.CatchUndefined
2028 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2029 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2030 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2031 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2032 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002033 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002034 CGF.EmitBlock(Cont);
2035 }
2036
Chris Lattner7f02f722007-08-24 05:35:26 +00002037 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2038}
2039
2040Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2041 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2042 // RHS to the same size as the LHS.
2043 Value *RHS = Ops.RHS;
2044 if (Ops.LHS->getType() != RHS->getType())
2045 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002046
Mike Stumpbe07f602009-12-14 21:58:14 +00002047 if (CGF.CatchUndefined
2048 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2049 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2050 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2051 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2052 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002053 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002054 CGF.EmitBlock(Cont);
2055 }
2056
Douglas Gregorf6094622010-07-23 15:58:24 +00002057 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002058 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2059 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2060}
2061
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002062enum IntrinsicType { VCMPEQ, VCMPGT };
2063// return corresponding comparison intrinsic for given vector type
2064static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2065 BuiltinType::Kind ElemKind) {
2066 switch (ElemKind) {
2067 default: assert(0 && "unexpected element type");
2068 case BuiltinType::Char_U:
2069 case BuiltinType::UChar:
2070 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2071 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2072 break;
2073 case BuiltinType::Char_S:
2074 case BuiltinType::SChar:
2075 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2076 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2077 break;
2078 case BuiltinType::UShort:
2079 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2080 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2081 break;
2082 case BuiltinType::Short:
2083 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2084 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2085 break;
2086 case BuiltinType::UInt:
2087 case BuiltinType::ULong:
2088 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2089 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2090 break;
2091 case BuiltinType::Int:
2092 case BuiltinType::Long:
2093 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2094 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2095 break;
2096 case BuiltinType::Float:
2097 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2098 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2099 break;
2100 }
2101 return llvm::Intrinsic::not_intrinsic;
2102}
2103
Chris Lattner7f02f722007-08-24 05:35:26 +00002104Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2105 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002106 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002107 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002108 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002109 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002110 assert(E->getOpcode() == BO_EQ ||
2111 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002112 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2113 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002114 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002115 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002116 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002117 Value *LHS = Visit(E->getLHS());
2118 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002119
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002120 // If AltiVec, the comparison results in a numeric type, so we use
2121 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002122 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002123 // constants for mapping CR6 register bits to predicate result
2124 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2125
2126 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2127
2128 // in several cases vector arguments order will be reversed
2129 Value *FirstVecArg = LHS,
2130 *SecondVecArg = RHS;
2131
2132 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002133 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002134 BuiltinType::Kind ElementKind = BTy->getKind();
2135
2136 switch(E->getOpcode()) {
2137 default: assert(0 && "is not a comparison operation");
2138 case BO_EQ:
2139 CR6 = CR6_LT;
2140 ID = GetIntrinsic(VCMPEQ, ElementKind);
2141 break;
2142 case BO_NE:
2143 CR6 = CR6_EQ;
2144 ID = GetIntrinsic(VCMPEQ, ElementKind);
2145 break;
2146 case BO_LT:
2147 CR6 = CR6_LT;
2148 ID = GetIntrinsic(VCMPGT, ElementKind);
2149 std::swap(FirstVecArg, SecondVecArg);
2150 break;
2151 case BO_GT:
2152 CR6 = CR6_LT;
2153 ID = GetIntrinsic(VCMPGT, ElementKind);
2154 break;
2155 case BO_LE:
2156 if (ElementKind == BuiltinType::Float) {
2157 CR6 = CR6_LT;
2158 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2159 std::swap(FirstVecArg, SecondVecArg);
2160 }
2161 else {
2162 CR6 = CR6_EQ;
2163 ID = GetIntrinsic(VCMPGT, ElementKind);
2164 }
2165 break;
2166 case BO_GE:
2167 if (ElementKind == BuiltinType::Float) {
2168 CR6 = CR6_LT;
2169 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2170 }
2171 else {
2172 CR6 = CR6_EQ;
2173 ID = GetIntrinsic(VCMPGT, ElementKind);
2174 std::swap(FirstVecArg, SecondVecArg);
2175 }
2176 break;
2177 }
2178
2179 Value *CR6Param = llvm::ConstantInt::get(CGF.Int32Ty, CR6);
2180 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2181 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2182 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2183 }
2184
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002185 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002186 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002187 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002188 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002189 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002190 LHS, RHS, "cmp");
2191 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002192 // Unsigned integers and pointers.
2193 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002194 LHS, RHS, "cmp");
2195 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002196
2197 // If this is a vector comparison, sign extend the result to the appropriate
2198 // vector integer type and return it (don't convert to bool).
2199 if (LHSTy->isVectorType())
2200 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002201
Chris Lattner7f02f722007-08-24 05:35:26 +00002202 } else {
2203 // Complex Comparison: can only be an equality comparison.
2204 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2205 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002206
John McCall183700f2009-09-21 23:43:11 +00002207 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002208
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002209 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002210 if (CETy->isRealFloatingType()) {
2211 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2212 LHS.first, RHS.first, "cmp.r");
2213 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2214 LHS.second, RHS.second, "cmp.i");
2215 } else {
2216 // Complex comparisons can only be equality comparisons. As such, signed
2217 // and unsigned opcodes are the same.
2218 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2219 LHS.first, RHS.first, "cmp.r");
2220 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2221 LHS.second, RHS.second, "cmp.i");
2222 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002223
John McCall2de56d12010-08-25 11:45:40 +00002224 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002225 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2226 } else {
John McCall2de56d12010-08-25 11:45:40 +00002227 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002228 "Complex comparison other than == or != ?");
2229 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2230 }
2231 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002232
2233 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002234}
2235
2236Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002237 bool Ignore = TestAndClearIgnoreResultAssign();
2238
2239 // __block variables need to have the rhs evaluated first, plus this should
2240 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00002241 Value *RHS = Visit(E->getRHS());
Mike Stumpb14e62d2009-12-16 02:57:00 +00002242 LValue LHS = EmitCheckedLValue(E->getLHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002243
Daniel Dunbared3849b2008-11-19 09:36:46 +00002244 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00002245 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2246 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00002247 // the assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002248 if (LHS.isBitField())
2249 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
2250 &RHS);
2251 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00002252 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002253
2254 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002255 if (Ignore)
2256 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002257
John McCallb418d742010-11-16 10:08:07 +00002258 // The result of an assignment in C is the assigned r-value.
2259 if (!CGF.getContext().getLangOptions().CPlusPlus)
2260 return RHS;
2261
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002262 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00002263 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002264 return RHS;
2265
2266 // If the lvalue is non-volatile, return the computed value of the assignment.
2267 if (!LHS.isVolatileQualified())
2268 return RHS;
2269
2270 // Otherwise, reload the value.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002271 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002272}
2273
2274Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00002275 const llvm::Type *ResTy = ConvertType(E->getType());
2276
Chris Lattner20eb09d2008-11-12 08:26:50 +00002277 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2278 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002279 bool LHSCondVal;
2280 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2281 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002282 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002283 // ZExt result to int or bool.
2284 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002285 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002286
Chris Lattner7804bcb2009-10-17 04:24:20 +00002287 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002288 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002289 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002290 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002291
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002292 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2293 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002294
John McCall150b4622011-01-26 04:00:11 +00002295 CodeGenFunction::ConditionalEvaluation eval(CGF);
2296
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002297 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2298 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2299
2300 // Any edges into the ContBlock are now from an (indeterminate number of)
2301 // edges from this first condition. All of these values will be false. Start
2302 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00002303 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
2304 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002305 PN->reserveOperandSpace(2); // Normal case, two inputs.
2306 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2307 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002308 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002309
John McCall150b4622011-01-26 04:00:11 +00002310 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002311 CGF.EmitBlock(RHSBlock);
2312 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002313 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002314
Chris Lattner7f02f722007-08-24 05:35:26 +00002315 // Reaquire the RHS block, as there may be subblocks inserted.
2316 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002317
2318 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2319 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00002320 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002321 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002322
Chris Lattner7f02f722007-08-24 05:35:26 +00002323 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002324 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002325}
2326
2327Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00002328 const llvm::Type *ResTy = ConvertType(E->getType());
2329
Chris Lattner20eb09d2008-11-12 08:26:50 +00002330 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2331 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002332 bool LHSCondVal;
2333 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2334 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002335 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002336 // ZExt result to int or bool.
2337 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002338 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002339
Chris Lattner7804bcb2009-10-17 04:24:20 +00002340 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002341 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002342 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002343 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002344
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002345 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2346 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002347
John McCall150b4622011-01-26 04:00:11 +00002348 CodeGenFunction::ConditionalEvaluation eval(CGF);
2349
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002350 // Branch on the LHS first. If it is true, go to the success (cont) block.
2351 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2352
2353 // Any edges into the ContBlock are now from an (indeterminate number of)
2354 // edges from this first condition. All of these values will be true. Start
2355 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00002356 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
2357 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002358 PN->reserveOperandSpace(2); // Normal case, two inputs.
2359 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2360 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002361 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002362
John McCall150b4622011-01-26 04:00:11 +00002363 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002364
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002365 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002366 CGF.EmitBlock(RHSBlock);
2367 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002368
John McCall150b4622011-01-26 04:00:11 +00002369 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002370
Chris Lattner7f02f722007-08-24 05:35:26 +00002371 // Reaquire the RHS block, as there may be subblocks inserted.
2372 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002373
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002374 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2375 // into the phi node for the edge with the value of RHSCond.
2376 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002377 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002378
Chris Lattner7f02f722007-08-24 05:35:26 +00002379 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002380 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002381}
2382
2383Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002384 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002385 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002386 return Visit(E->getRHS());
2387}
2388
2389//===----------------------------------------------------------------------===//
2390// Other Operators
2391//===----------------------------------------------------------------------===//
2392
Chris Lattner9802a512008-11-12 08:55:54 +00002393/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2394/// expression is cheap enough and side-effect-free enough to evaluate
2395/// unconditionally instead of conditionally. This is used to convert control
2396/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002397static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2398 CodeGenFunction &CGF) {
Chris Lattner9802a512008-11-12 08:55:54 +00002399 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002400 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002401
Chris Lattner9802a512008-11-12 08:55:54 +00002402 // TODO: Allow anything we can constant fold to an integer or fp constant.
2403 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
2404 isa<FloatingLiteral>(E))
2405 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002406
Chris Lattner9802a512008-11-12 08:55:54 +00002407 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2408 // X and Y are local variables.
2409 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2410 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002411 if (VD->hasLocalStorage() && !(CGF.getContext()
2412 .getCanonicalType(VD->getType())
2413 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002414 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002415
Chris Lattner9802a512008-11-12 08:55:54 +00002416 return false;
2417}
2418
2419
Chris Lattner7f02f722007-08-24 05:35:26 +00002420Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002421VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002422 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002423
2424 // Bind the common expression if necessary.
2425 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2426
2427 Expr *condExpr = E->getCond();
2428 Expr *lhsExpr = E->getTrueExpr();
2429 Expr *rhsExpr = E->getFalseExpr();
2430
Chris Lattner31a09842008-11-12 08:04:58 +00002431 // If the condition constant folds and can be elided, try to avoid emitting
2432 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002433 bool CondExprBool;
2434 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002435 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002436 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002437
Chris Lattner31a09842008-11-12 08:04:58 +00002438 // If the dead side doesn't have labels we need, and if the Live side isn't
2439 // the gnu missing ?: extension (which we could handle, but don't bother
2440 // to), just emit the Live part.
John McCall56ca35d2011-02-17 10:25:35 +00002441 if (!CGF.ContainsLabel(dead))
2442 return Visit(live);
Chris Lattnerc657e922008-11-11 18:56:45 +00002443 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002444
Nate Begeman6155d732010-09-20 22:41:17 +00002445 // OpenCL: If the condition is a vector, we can treat this condition like
2446 // the select function.
2447 if (CGF.getContext().getLangOptions().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002448 && condExpr->getType()->isVectorType()) {
2449 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2450 llvm::Value *LHS = Visit(lhsExpr);
2451 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002452
John McCall56ca35d2011-02-17 10:25:35 +00002453 const llvm::Type *condType = ConvertType(condExpr->getType());
Nate Begeman6155d732010-09-20 22:41:17 +00002454 const llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2455
2456 unsigned numElem = vecTy->getNumElements();
2457 const llvm::Type *elemType = vecTy->getElementType();
2458
2459 std::vector<llvm::Constant*> Zvals;
2460 for (unsigned i = 0; i < numElem; ++i)
2461 Zvals.push_back(llvm::ConstantInt::get(elemType,0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002462
Nate Begeman6155d732010-09-20 22:41:17 +00002463 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2464 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2465 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2466 llvm::VectorType::get(elemType,
2467 numElem),
2468 "sext");
2469 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2470
2471 // Cast float to int to perform ANDs if necessary.
2472 llvm::Value *RHSTmp = RHS;
2473 llvm::Value *LHSTmp = LHS;
2474 bool wasCast = false;
2475 const llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2476 if (rhsVTy->getElementType()->isFloatTy()) {
2477 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2478 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2479 wasCast = true;
2480 }
2481
2482 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2483 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2484 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2485 if (wasCast)
2486 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2487
2488 return tmp5;
2489 }
2490
Chris Lattner9802a512008-11-12 08:55:54 +00002491 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2492 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002493 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002494 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2495 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2496 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2497 llvm::Value *LHS = Visit(lhsExpr);
2498 llvm::Value *RHS = Visit(rhsExpr);
Chris Lattner9802a512008-11-12 08:55:54 +00002499 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2500 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002501
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002502 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2503 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002504 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002505
2506 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002507 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002508
Chris Lattner7f02f722007-08-24 05:35:26 +00002509 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002510 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002511 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002512 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002513
Chris Lattner7f02f722007-08-24 05:35:26 +00002514 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002515 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002516
Chris Lattner7f02f722007-08-24 05:35:26 +00002517 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002518 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002519 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002520 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002521
John McCall150b4622011-01-26 04:00:11 +00002522 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002523 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002524
Eli Friedman48daf592009-12-07 20:25:53 +00002525 // If the LHS or RHS is a throw expression, it will be legitimately null.
2526 if (!LHS)
2527 return RHS;
2528 if (!RHS)
2529 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002530
Chris Lattner7f02f722007-08-24 05:35:26 +00002531 // Create a PHI node for the real part.
2532 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
2533 PN->reserveOperandSpace(2);
2534 PN->addIncoming(LHS, LHSBlock);
2535 PN->addIncoming(RHS, RHSBlock);
2536 return PN;
2537}
2538
2539Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002540 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002541}
2542
Chris Lattner2202bce2007-11-30 17:56:23 +00002543Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002544 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002545 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2546
2547 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002548 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002549 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2550
Mike Stump7f79f9b2009-05-29 15:46:01 +00002551 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002552 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002553}
2554
John McCall6b5a61b2011-02-07 10:33:21 +00002555Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2556 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002557}
2558
Chris Lattner7f02f722007-08-24 05:35:26 +00002559//===----------------------------------------------------------------------===//
2560// Entry Point into this File
2561//===----------------------------------------------------------------------===//
2562
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002563/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2564/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002565Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002566 assert(E && !hasAggregateLLVMType(E->getType()) &&
2567 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002568
Devang Patel5de7a0e2011-03-07 18:29:53 +00002569 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002570 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002571 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00002572 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00002573 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00002574 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00002575 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00002576}
Chris Lattner3707b252007-08-26 06:48:56 +00002577
2578/// EmitScalarConversion - Emit a conversion from the specified type to the
2579/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002580Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2581 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002582 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2583 "Invalid scalar expression to emit");
2584 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2585}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002586
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002587/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2588/// type to the specified destination type, where the destination type is an
2589/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002590Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2591 QualType SrcTy,
2592 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002593 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002594 "Invalid complex -> scalar conversion");
2595 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2596 DstTy);
2597}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002598
Chris Lattner8c11a652010-06-26 22:09:34 +00002599
2600llvm::Value *CodeGenFunction::
2601EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2602 bool isInc, bool isPre) {
2603 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2604}
2605
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002606LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2607 llvm::Value *V;
2608 // object->isa or (*object).isa
2609 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002610 // build Class* type
2611 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002612
2613 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002614 if (BaseExpr->isRValue()) {
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002615 V = CreateTempAlloca(ClassPtrTy, "resval");
2616 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2617 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002618 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2619 MakeAddrLValue(V, E->getType()), E->getType());
2620 } else {
2621 if (E->isArrow())
2622 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2623 else
2624 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002625 }
2626
2627 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002628 ClassPtrTy = ClassPtrTy->getPointerTo();
2629 V = Builder.CreateBitCast(V, ClassPtrTy);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002630 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002631}
2632
Douglas Gregor6a03e342010-04-23 04:16:32 +00002633
John McCall2a416372010-12-05 02:00:02 +00002634LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002635 const CompoundAssignOperator *E) {
2636 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002637 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002638 switch (E->getOpcode()) {
2639#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002640 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002641 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002642 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002643 COMPOUND_OP(Mul);
2644 COMPOUND_OP(Div);
2645 COMPOUND_OP(Rem);
2646 COMPOUND_OP(Add);
2647 COMPOUND_OP(Sub);
2648 COMPOUND_OP(Shl);
2649 COMPOUND_OP(Shr);
2650 COMPOUND_OP(And);
2651 COMPOUND_OP(Xor);
2652 COMPOUND_OP(Or);
2653#undef COMPOUND_OP
2654
John McCall2de56d12010-08-25 11:45:40 +00002655 case BO_PtrMemD:
2656 case BO_PtrMemI:
2657 case BO_Mul:
2658 case BO_Div:
2659 case BO_Rem:
2660 case BO_Add:
2661 case BO_Sub:
2662 case BO_Shl:
2663 case BO_Shr:
2664 case BO_LT:
2665 case BO_GT:
2666 case BO_LE:
2667 case BO_GE:
2668 case BO_EQ:
2669 case BO_NE:
2670 case BO_And:
2671 case BO_Xor:
2672 case BO_Or:
2673 case BO_LAnd:
2674 case BO_LOr:
2675 case BO_Assign:
2676 case BO_Comma:
Douglas Gregor6a03e342010-04-23 04:16:32 +00002677 assert(false && "Not valid compound assignment operators");
2678 break;
2679 }
2680
2681 llvm_unreachable("Unhandled compound assignment operator");
2682}