blob: e2e404f70fb526d583693211fc3b238b5f18c7f3 [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) {
153 llvm::DenseMap<const Expr *, llvm::Value *>::iterator I =
154 CGF.ConditionalSaveExprs.find(E);
155 if (I != CGF.ConditionalSaveExprs.end())
156 return I->second;
157
158 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
159 }
160
Chris Lattner7f02f722007-08-24 05:35:26 +0000161 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000162 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000163 assert(0 && "Stmt can't have complex result type!");
164 return 0;
165 }
166 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000167
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000168 Value *VisitParenExpr(ParenExpr *PE) {
169 return Visit(PE->getSubExpr());
170 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000171
172 // Leaves.
173 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000174 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000175 }
176 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000177 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000178 }
179 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000180 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000181 }
Nate Begemane7579b52007-11-15 05:40:03 +0000182 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000183 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000184 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000185 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000186 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000187 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000188 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000189 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000190 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000191 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +0000192 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000193 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000194 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
195 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000196 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000197
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000198 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
199 return llvm::ConstantInt::get(ConvertType(E->getType()),
200 E->getPackLength());
201 }
202
Chris Lattner7f02f722007-08-24 05:35:26 +0000203 // l-values.
204 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000205 Expr::EvalResult Result;
John McCall189d6ef2010-10-09 01:34:31 +0000206 if (!E->Evaluate(Result, CGF.getContext()))
207 return EmitLoadOfLValue(E);
208
209 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
210
211 llvm::Constant *C;
212 if (Result.Val.isInt()) {
213 C = llvm::ConstantInt::get(VMContext, Result.Val.getInt());
214 } else if (Result.Val.isFloat()) {
215 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
216 } else {
217 return EmitLoadOfLValue(E);
Eli Friedman28665272009-11-26 03:22:21 +0000218 }
John McCall189d6ef2010-10-09 01:34:31 +0000219
220 // Make sure we emit a debug reference to the global variable.
221 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
222 if (!CGF.getContext().DeclMustBeEmitted(VD))
223 CGF.EmitDeclRefExprDbgValue(E, C);
224 } else if (isa<EnumConstantDecl>(E->getDecl())) {
225 CGF.EmitDeclRefExprDbgValue(E, C);
226 }
227
228 return C;
Chris Lattner7f02f722007-08-24 05:35:26 +0000229 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000230 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
231 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000232 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000233 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
234 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000235 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000236 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000237 return EmitLoadOfLValue(E);
238 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000239 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
John McCallf6a16482010-12-04 03:47:34 +0000240 assert(E->getObjectKind() == OK_Ordinary &&
241 "reached property reference without lvalue-to-rvalue");
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000242 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000243 }
244 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
245 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000246 }
247
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000248 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000249 LValue LV = CGF.EmitObjCIsaExpr(E);
250 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000251 return V;
252 }
253
Chris Lattner7f02f722007-08-24 05:35:26 +0000254 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000255 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000256 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000257 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000258 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
259 return EmitLoadOfLValue(E);
260 }
Devang Patel35634f52007-10-24 17:18:43 +0000261
Nate Begeman0533b302009-10-18 20:10:40 +0000262 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000263
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000264 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000265 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000266 }
Eli Friedmand8889622009-11-27 04:41:50 +0000267 Value *VisitCastExpr(CastExpr *E) {
Eli Friedmanc62aad82009-04-20 03:54:15 +0000268 // Make sure to evaluate VLA bounds now so that we have them for later.
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000269 if (E->getType()->isVariablyModifiedType())
270 CGF.EmitVLASize(E->getType());
Eli Friedmanc62aad82009-04-20 03:54:15 +0000271
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000272 return EmitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000273 }
Eli Friedmand8889622009-11-27 04:41:50 +0000274 Value *EmitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000275
276 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000277 if (E->getCallReturnType()->isReferenceType())
278 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000279
Chris Lattner9b655512007-08-31 22:49:20 +0000280 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000281 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000282
Chris Lattner33793202007-08-31 22:09:40 +0000283 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000284
Mike Stumpa99038c2009-02-28 09:07:16 +0000285 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000286
Chris Lattner7f02f722007-08-24 05:35:26 +0000287 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000288 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000289 LValue LV = EmitLValue(E->getSubExpr());
290 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000291 }
292 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000293 LValue LV = EmitLValue(E->getSubExpr());
294 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000295 }
296 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000297 LValue LV = EmitLValue(E->getSubExpr());
298 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000299 }
300 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000301 LValue LV = EmitLValue(E->getSubExpr());
302 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000303 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000304
Anton Yartsev683564a2011-02-07 02:17:30 +0000305 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
306 llvm::Value *InVal,
307 llvm::Value *NextVal,
308 bool IsInc);
309
Chris Lattner8c11a652010-06-26 22:09:34 +0000310 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
311 bool isInc, bool isPre);
312
313
Chris Lattner7f02f722007-08-24 05:35:26 +0000314 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000315 if (isa<MemberPointerType>(E->getType())) // never sugared
316 return CGF.CGM.getMemberPointerConstant(E);
317
Chris Lattner7f02f722007-08-24 05:35:26 +0000318 return EmitLValue(E->getSubExpr()).getAddress();
319 }
John McCallfd569002010-12-04 12:43:24 +0000320 Value *VisitUnaryDeref(const UnaryOperator *E) {
321 if (E->getType()->isVoidType())
322 return Visit(E->getSubExpr()); // the actual value should be unused
323 return EmitLoadOfLValue(E);
324 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000325 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000326 // This differs from gcc, though, most likely due to a bug in gcc.
327 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000328 return Visit(E->getSubExpr());
329 }
330 Value *VisitUnaryMinus (const UnaryOperator *E);
331 Value *VisitUnaryNot (const UnaryOperator *E);
332 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000333 Value *VisitUnaryReal (const UnaryOperator *E);
334 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000335 Value *VisitUnaryExtension(const UnaryOperator *E) {
336 return Visit(E->getSubExpr());
337 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000338
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000339 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000340 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
341 return Visit(DAE->getExpr());
342 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000343 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
344 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000345 }
346
John McCall4765fa02010-12-06 08:20:24 +0000347 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
348 return CGF.EmitExprWithCleanups(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000349 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000350 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
351 return CGF.EmitCXXNewExpr(E);
352 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000353 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
354 CGF.EmitCXXDeleteExpr(E);
355 return 0;
356 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000357 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +0000358 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000359 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000360
Francois Pichet6ad6f282010-12-07 00:08:36 +0000361 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000362 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000363 }
364
Douglas Gregora71d8192009-09-04 17:36:40 +0000365 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
366 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000367 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000368 // operator (), and the result of such a call has type void. The only
369 // effect is the evaluation of the postfix-expression before the dot or
370 // arrow.
371 CGF.EmitScalarExpr(E->getBase());
372 return 0;
373 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000374
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000375 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000376 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000377 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000378
379 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
380 CGF.EmitCXXThrowExpr(E);
381 return 0;
382 }
383
Sebastian Redl98294de2010-09-10 21:04:00 +0000384 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
385 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
386 }
387
Chris Lattner7f02f722007-08-24 05:35:26 +0000388 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000389 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000390 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000391 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
392 case LangOptions::SOB_Undefined:
393 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
394 case LangOptions::SOB_Defined:
395 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
396 case LangOptions::SOB_Trapping:
397 return EmitOverflowCheckedBinOp(Ops);
398 }
399 }
400
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000401 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000402 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000403 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
404 }
Chris Lattner80230302010-09-11 21:47:09 +0000405 bool isTrapvOverflowBehavior() {
406 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
407 == LangOptions::SOB_Trapping;
408 }
Mike Stump2add4732009-04-01 20:28:16 +0000409 /// Create a binary op that checks for overflow.
410 /// Currently only supports +, - and *.
411 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner80230302010-09-11 21:47:09 +0000412 // Emit the overflow BB when -ftrapv option is activated.
413 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
414 Builder.SetInsertPoint(overflowBB);
415 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
416 Builder.CreateCall(Trap);
417 Builder.CreateUnreachable();
418 }
419 // Check for undefined division and modulus behaviors.
420 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
421 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000422 Value *EmitDiv(const BinOpInfo &Ops);
423 Value *EmitRem(const BinOpInfo &Ops);
424 Value *EmitAdd(const BinOpInfo &Ops);
425 Value *EmitSub(const BinOpInfo &Ops);
426 Value *EmitShl(const BinOpInfo &Ops);
427 Value *EmitShr(const BinOpInfo &Ops);
428 Value *EmitAnd(const BinOpInfo &Ops) {
429 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
430 }
431 Value *EmitXor(const BinOpInfo &Ops) {
432 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
433 }
434 Value *EmitOr (const BinOpInfo &Ops) {
435 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
436 }
437
Chris Lattner1f1ded92007-08-24 21:00:35 +0000438 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000439 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
440 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000441 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000442
Chris Lattner3ccf7742007-08-26 21:41:21 +0000443 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000444 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
445
446 // Binary operators and binary compound assignment operators.
447#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000448 Value *VisitBin ## OP(const BinaryOperator *E) { \
449 return Emit ## OP(EmitBinOps(E)); \
450 } \
451 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
452 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000453 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000454 HANDLEBINOP(Mul)
455 HANDLEBINOP(Div)
456 HANDLEBINOP(Rem)
457 HANDLEBINOP(Add)
458 HANDLEBINOP(Sub)
459 HANDLEBINOP(Shl)
460 HANDLEBINOP(Shr)
461 HANDLEBINOP(And)
462 HANDLEBINOP(Xor)
463 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000464#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000465
Chris Lattner7f02f722007-08-24 05:35:26 +0000466 // Comparisons.
467 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
468 unsigned SICmpOpc, unsigned FCmpOpc);
469#define VISITCOMP(CODE, UI, SI, FP) \
470 Value *VisitBin##CODE(const BinaryOperator *E) { \
471 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
472 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000473 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
474 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
475 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
476 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
477 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
478 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000479#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000480
Chris Lattner7f02f722007-08-24 05:35:26 +0000481 Value *VisitBinAssign (const BinaryOperator *E);
482
483 Value *VisitBinLAnd (const BinaryOperator *E);
484 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000485 Value *VisitBinComma (const BinaryOperator *E);
486
Eli Friedman25b825d2009-11-18 09:41:26 +0000487 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
488 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
489
Chris Lattner7f02f722007-08-24 05:35:26 +0000490 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000491 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000492 Value *VisitConditionalOperator(const ConditionalOperator *CO);
493 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000494 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000495 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
496 return CGF.EmitObjCStringLiteral(E);
497 }
498};
499} // end anonymous namespace.
500
501//===----------------------------------------------------------------------===//
502// Utilities
503//===----------------------------------------------------------------------===//
504
Chris Lattner9abc84e2007-08-26 16:42:57 +0000505/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000506/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000507Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000508 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000509
John McCalldaa8e4e2010-11-15 09:13:47 +0000510 if (SrcType->isRealFloatingType())
511 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000512
John McCall0bab0cd2010-08-23 01:21:21 +0000513 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
514 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000515
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000516 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000517 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000518
John McCalldaa8e4e2010-11-15 09:13:47 +0000519 if (isa<llvm::IntegerType>(Src->getType()))
520 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000521
John McCalldaa8e4e2010-11-15 09:13:47 +0000522 assert(isa<llvm::PointerType>(Src->getType()));
523 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000524}
525
Chris Lattner3707b252007-08-26 06:48:56 +0000526/// EmitScalarConversion - Emit a conversion from the specified type to the
527/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000528Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
529 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000530 SrcType = CGF.getContext().getCanonicalType(SrcType);
531 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000532 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000533
Chris Lattnercf289082007-08-26 07:21:11 +0000534 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000535
Chris Lattner3707b252007-08-26 06:48:56 +0000536 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000537 if (DstType->isBooleanType())
538 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000539
Chris Lattner3707b252007-08-26 06:48:56 +0000540 const llvm::Type *DstTy = ConvertType(DstType);
541
542 // Ignore conversions like int -> uint.
543 if (Src->getType() == DstTy)
544 return Src;
545
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000546 // Handle pointer conversions next: pointers can only be converted to/from
547 // other pointers and integers. Check for pointer types in terms of LLVM, as
548 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000549 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000550 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000551 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000552 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000553
Chris Lattner3707b252007-08-26 06:48:56 +0000554 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000555 // First, convert to the correct width so that we control the kind of
556 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +0000557 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Eli Friedman25615422009-03-04 04:02:35 +0000558 bool InputSigned = SrcType->isSignedIntegerType();
559 llvm::Value* IntResult =
560 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
561 // Then, cast to pointer.
562 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000563 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000564
Daniel Dunbar270cc662008-08-25 09:51:32 +0000565 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000566 // Must be an ptr to int cast.
567 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000568 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000569 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000570
Nate Begeman213541a2008-04-18 23:10:10 +0000571 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000572 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000573 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000574 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000575 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
576
577 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000578 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +0000579 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000580 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
581
582 // Splat the element across to all elements
583 llvm::SmallVector<llvm::Constant*, 16> Args;
584 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattnerfb018d12011-02-15 00:14:06 +0000585 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner77b89b82010-06-27 07:15:29 +0000586 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000587
Chris Lattnerfb018d12011-02-15 00:14:06 +0000588 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000589 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
590 return Yay;
591 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000592
Chris Lattner3b1ae002008-02-02 04:51:41 +0000593 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000594 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000595 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000596 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000597
Chris Lattner3707b252007-08-26 06:48:56 +0000598 // Finally, we have the arithmetic types: real int/float.
599 if (isa<llvm::IntegerType>(Src->getType())) {
600 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000601 if (isa<llvm::IntegerType>(DstTy))
602 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
603 else if (InputSigned)
604 return Builder.CreateSIToFP(Src, DstTy, "conv");
605 else
606 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000607 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000608
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000609 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
Chris Lattner3707b252007-08-26 06:48:56 +0000610 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000611 if (DstType->isSignedIntegerType())
612 return Builder.CreateFPToSI(Src, DstTy, "conv");
613 else
614 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000615 }
616
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000617 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000618 if (DstTy->getTypeID() < Src->getType()->getTypeID())
619 return Builder.CreateFPTrunc(Src, DstTy, "conv");
620 else
621 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000622}
623
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000624/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
625/// type to the specified destination type, where the destination type is an
626/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000627Value *ScalarExprEmitter::
628EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
629 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000630 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000631 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000632
Chris Lattnered70f0a2007-08-26 16:52:28 +0000633 // Handle conversions to bool first, they are special: comparisons against 0.
634 if (DstTy->isBooleanType()) {
635 // Complex != 0 -> (Real != 0) | (Imag != 0)
636 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
637 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
638 return Builder.CreateOr(Src.first, Src.second, "tobool");
639 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000640
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000641 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
642 // the imaginary part of the complex value is discarded and the value of the
643 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000644 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000645 return EmitScalarConversion(Src.first, SrcTy, DstTy);
646}
647
Anders Carlssona40a9f32010-05-22 17:45:10 +0000648Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000649 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
650 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
651
652 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000653}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000654
Chris Lattner7f02f722007-08-24 05:35:26 +0000655//===----------------------------------------------------------------------===//
656// Visitor Methods
657//===----------------------------------------------------------------------===//
658
659Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000660 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000661 if (E->getType()->isVoidType())
662 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000663 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000664}
665
Eli Friedmand38617c2008-05-14 19:38:39 +0000666Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000667 // Vector Mask Case
668 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000669 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000670 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
671 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
672 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000673
Nate Begeman37b6a572010-06-08 00:16:34 +0000674 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
675 unsigned LHSElts = LTy->getNumElements();
676
677 if (E->getNumSubExprs() == 3) {
678 Mask = CGF.EmitScalarExpr(E->getExpr(2));
679
680 // Shuffle LHS & RHS into one input vector.
681 llvm::SmallVector<llvm::Constant*, 32> concat;
682 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000683 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i));
684 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000685 }
686
Chris Lattnerfb018d12011-02-15 00:14:06 +0000687 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000688 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
689 LHSElts *= 2;
690 } else {
691 Mask = RHS;
692 }
693
694 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
695 llvm::Constant* EltMask;
696
697 // Treat vec3 like vec4.
698 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
699 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
700 (1 << llvm::Log2_32(LHSElts+2))-1);
701 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
702 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
703 (1 << llvm::Log2_32(LHSElts+1))-1);
704 else
705 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
706 (1 << llvm::Log2_32(LHSElts))-1);
707
708 // Mask off the high bits of each shuffle index.
709 llvm::SmallVector<llvm::Constant *, 32> MaskV;
710 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
711 MaskV.push_back(EltMask);
712
Chris Lattnerfb018d12011-02-15 00:14:06 +0000713 Value* MaskBits = llvm::ConstantVector::get(MaskV);
Nate Begeman37b6a572010-06-08 00:16:34 +0000714 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
715
716 // newv = undef
717 // mask = mask & maskbits
718 // for each elt
719 // n = extract mask i
720 // x = extract val n
721 // newv = insert newv, x, i
722 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
723 MTy->getNumElements());
724 Value* NewV = llvm::UndefValue::get(RTy);
725 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000726 Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000727 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000728 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000729
730 // Handle vec3 special since the index will be off by one for the RHS.
731 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
732 Value *cmpIndx, *newIndx;
Chris Lattner77b89b82010-06-27 07:15:29 +0000733 cmpIndx = Builder.CreateICmpUGT(Indx,
734 llvm::ConstantInt::get(CGF.Int32Ty, 3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000735 "cmp_shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000736 newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1),
Nate Begeman37b6a572010-06-08 00:16:34 +0000737 "shuf_idx_adj");
738 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
739 }
740 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
741 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
742 }
743 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000744 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000745
Eli Friedmand38617c2008-05-14 19:38:39 +0000746 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
747 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000748
749 // Handle vec3 special since the index will be off by one for the RHS.
750 llvm::SmallVector<llvm::Constant*, 32> indices;
751 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
752 llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
753 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
754 if (VTy->getNumElements() == 3) {
755 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
756 uint64_t cVal = CI->getZExtValue();
757 if (cVal > 3) {
758 C = llvm::ConstantInt::get(C->getType(), cVal-1);
759 }
760 }
761 }
762 indices.push_back(C);
763 }
764
Chris Lattnerfb018d12011-02-15 00:14:06 +0000765 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000766 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
767}
Eli Friedman28665272009-11-26 03:22:21 +0000768Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
769 Expr::EvalResult Result;
770 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
771 if (E->isArrow())
772 CGF.EmitScalarExpr(E->getBase());
773 else
774 EmitLValue(E->getBase());
775 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
776 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000777
778 // Emit debug info for aggregate now, if it was delayed to reduce
779 // debug info size.
780 CGDebugInfo *DI = CGF.getDebugInfo();
781 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
782 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
783 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000784 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Devang Patel78ba3d42010-10-04 21:46:04 +0000785 DI->getOrCreateRecordType(PTy->getPointeeType(),
786 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000787 }
Eli Friedman28665272009-11-26 03:22:21 +0000788 return EmitLoadOfLValue(E);
789}
Eli Friedmand38617c2008-05-14 19:38:39 +0000790
Chris Lattner7f02f722007-08-24 05:35:26 +0000791Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000792 TestAndClearIgnoreResultAssign();
793
Chris Lattner7f02f722007-08-24 05:35:26 +0000794 // Emit subscript expressions in rvalue context's. For most cases, this just
795 // loads the lvalue formed by the subscript expr. However, we have to be
796 // careful, because the base of a vector subscript is occasionally an rvalue,
797 // so we can't get it as an lvalue.
798 if (!E->getBase()->getType()->isVectorType())
799 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000800
Chris Lattner7f02f722007-08-24 05:35:26 +0000801 // Handle the vector case. The base must be a vector, the index must be an
802 // integer value.
803 Value *Base = Visit(E->getBase());
804 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000805 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000806 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000807 return Builder.CreateExtractElement(Base, Idx, "vecext");
808}
809
Nate Begeman0533b302009-10-18 20:10:40 +0000810static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
811 unsigned Off, const llvm::Type *I32Ty) {
812 int MV = SVI->getMaskValue(Idx);
813 if (MV == -1)
814 return llvm::UndefValue::get(I32Ty);
815 return llvm::ConstantInt::get(I32Ty, Off+MV);
816}
817
818Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
819 bool Ignore = TestAndClearIgnoreResultAssign();
820 (void)Ignore;
821 assert (Ignore == false && "init list ignored");
822 unsigned NumInitElements = E->getNumInits();
823
824 if (E->hadArrayRangeDesignator())
825 CGF.ErrorUnsupported(E, "GNU array range designator extension");
826
827 const llvm::VectorType *VType =
828 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
829
830 // We have a scalar in braces. Just use the first element.
831 if (!VType)
832 return Visit(E->getInit(0));
833
834 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000835
836 // Loop over initializers collecting the Value for each, and remembering
837 // whether the source was swizzle (ExtVectorElementExpr). This will allow
838 // us to fold the shuffle for the swizzle into the shuffle for the vector
839 // initializer, since LLVM optimizers generally do not want to touch
840 // shuffles.
841 unsigned CurIdx = 0;
842 bool VIsUndefShuffle = false;
843 llvm::Value *V = llvm::UndefValue::get(VType);
844 for (unsigned i = 0; i != NumInitElements; ++i) {
845 Expr *IE = E->getInit(i);
846 Value *Init = Visit(IE);
847 llvm::SmallVector<llvm::Constant*, 16> Args;
848
849 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
850
851 // Handle scalar elements. If the scalar initializer is actually one
852 // element of a different vector of the same width, use shuffle instead of
853 // extract+insert.
854 if (!VVT) {
855 if (isa<ExtVectorElementExpr>(IE)) {
856 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
857
858 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
859 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
860 Value *LHS = 0, *RHS = 0;
861 if (CurIdx == 0) {
862 // insert into undef -> shuffle (src, undef)
863 Args.push_back(C);
864 for (unsigned j = 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000865 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000866
867 LHS = EI->getVectorOperand();
868 RHS = V;
869 VIsUndefShuffle = true;
870 } else if (VIsUndefShuffle) {
871 // insert into undefshuffle && size match -> shuffle (v, src)
872 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
873 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000874 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
875 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
Nate Begeman0533b302009-10-18 20:10:40 +0000876 ResElts + C->getZExtValue()));
877 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000878 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000879
880 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
881 RHS = EI->getVectorOperand();
882 VIsUndefShuffle = false;
883 }
884 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000885 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000886 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
887 ++CurIdx;
888 continue;
889 }
890 }
891 }
Chris Lattner77b89b82010-06-27 07:15:29 +0000892 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000893 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
894 VIsUndefShuffle = false;
895 ++CurIdx;
896 continue;
897 }
898
899 unsigned InitElts = VVT->getNumElements();
900
901 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
902 // input is the same width as the vector being constructed, generate an
903 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000904 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000905 if (isa<ExtVectorElementExpr>(IE)) {
906 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
907 Value *SVOp = SVI->getOperand(0);
908 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
909
910 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000911 for (unsigned j = 0; j != CurIdx; ++j) {
912 // If the current vector initializer is a shuffle with undef, merge
913 // this shuffle directly into it.
914 if (VIsUndefShuffle) {
915 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000916 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000917 } else {
Chris Lattner77b89b82010-06-27 07:15:29 +0000918 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000919 }
920 }
921 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000922 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000923 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000924 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000925
926 if (VIsUndefShuffle)
927 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
928
929 Init = SVOp;
930 }
931 }
932
933 // Extend init to result vector length, and then shuffle its contribution
934 // to the vector initializer into V.
935 if (Args.empty()) {
936 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000937 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000938 for (unsigned j = InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000939 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000940 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000941 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000942 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000943
944 Args.clear();
945 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000946 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000947 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000948 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000949 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000950 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000951 }
952
953 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
954 // merging subsequent shuffles into this one.
955 if (CurIdx == 0)
956 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000957 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000958 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
959 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
960 CurIdx += InitElts;
961 }
962
963 // FIXME: evaluate codegen vs. shuffling against constant null vector.
964 // Emit remaining default initializers.
965 const llvm::Type *EltTy = VType->getElementType();
966
967 // Emit remaining default initializers
968 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000969 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000970 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
971 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
972 }
973 return V;
974}
975
Anders Carlssona3697c92009-11-23 17:57:54 +0000976static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
977 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +0000978
John McCall2de56d12010-08-25 11:45:40 +0000979 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +0000980 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +0000981
982 if (isa<CXXThisExpr>(E)) {
983 // We always assume that 'this' is never null.
984 return false;
985 }
986
987 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000988 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +0000989 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +0000990 return false;
991 }
992
993 return true;
994}
995
Chris Lattner7f02f722007-08-24 05:35:26 +0000996// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
997// have to handle a more broad range of conversions than explicit casts, as they
998// handle things like function to ptr-to-function decay etc.
Eli Friedmand8889622009-11-27 04:41:50 +0000999Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
1000 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001001 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001002 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001003
Mike Stump7f79f9b2009-05-29 15:46:01 +00001004 if (!DestTy->isVoidType())
1005 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001006
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001007 // Since almost all cast kinds apply to scalars, this switch doesn't have
1008 // a default case, so the compiler will warn on a missing case. The cases
1009 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001010 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001011 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1012
John McCall2de56d12010-08-25 11:45:40 +00001013 case CK_LValueBitCast:
1014 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001015 Value *V = EmitLValue(E).getAddress();
1016 V = Builder.CreateBitCast(V,
1017 ConvertType(CGF.getContext().getPointerType(DestTy)));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00001018 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy);
Douglas Gregore39a3892010-07-13 23:17:26 +00001019 }
1020
John McCall2de56d12010-08-25 11:45:40 +00001021 case CK_AnyPointerToObjCPointerCast:
1022 case CK_AnyPointerToBlockPointerCast:
1023 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001024 Value *Src = Visit(const_cast<Expr*>(E));
1025 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1026 }
John McCall2de56d12010-08-25 11:45:40 +00001027 case CK_NoOp:
1028 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001029 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001030
John McCall2de56d12010-08-25 11:45:40 +00001031 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00001032 const CXXRecordDecl *DerivedClassDecl =
1033 DestTy->getCXXRecordDeclForPointerType();
1034
Anders Carlssona04efdf2010-04-24 21:23:59 +00001035 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001036 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001037 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001038 }
John McCall2de56d12010-08-25 11:45:40 +00001039 case CK_UncheckedDerivedToBase:
1040 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +00001041 const RecordType *DerivedClassTy =
1042 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1043 CXXRecordDecl *DerivedClassDecl =
1044 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1045
Anders Carlsson34a2d382010-04-24 21:06:20 +00001046 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001047 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001048 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001049 }
John McCall2de56d12010-08-25 11:45:40 +00001050 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001051 Value *V = Visit(const_cast<Expr*>(E));
1052 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1053 return CGF.EmitDynamicCast(V, DCE);
1054 }
Eli Friedmand8889622009-11-27 04:41:50 +00001055
John McCall2de56d12010-08-25 11:45:40 +00001056 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001057 assert(E->getType()->isArrayType() &&
1058 "Array to pointer decay must have array source type!");
1059
1060 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1061
1062 // Note that VLA pointers are always decayed, so we don't need to do
1063 // anything here.
1064 if (!E->getType()->isVariableArrayType()) {
1065 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1066 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1067 ->getElementType()) &&
1068 "Expected pointer to array");
1069 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1070 }
1071
1072 return V;
1073 }
John McCall2de56d12010-08-25 11:45:40 +00001074 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001075 return EmitLValue(E).getAddress();
1076
John McCall404cd162010-11-13 01:35:44 +00001077 case CK_NullToPointer:
1078 if (MustVisitNullValue(E))
1079 (void) Visit(E);
1080
1081 return llvm::ConstantPointerNull::get(
1082 cast<llvm::PointerType>(ConvertType(DestTy)));
1083
John McCall2de56d12010-08-25 11:45:40 +00001084 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001085 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001086 (void) Visit(E);
1087
John McCall0bab0cd2010-08-23 01:21:21 +00001088 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1089 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1090 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001091
John McCall2de56d12010-08-25 11:45:40 +00001092 case CK_BaseToDerivedMemberPointer:
1093 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001094 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001095
1096 // Note that the AST doesn't distinguish between checked and
1097 // unchecked member pointer conversions, so we always have to
1098 // implement checked conversions here. This is inefficient when
1099 // actual control flow may be required in order to perform the
1100 // check, which it is for data member pointers (but not member
1101 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001102 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001103 }
John McCall0bab0cd2010-08-23 01:21:21 +00001104
John McCall2bb5d002010-11-13 09:02:35 +00001105 case CK_FloatingRealToComplex:
1106 case CK_FloatingComplexCast:
1107 case CK_IntegralRealToComplex:
1108 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001109 case CK_IntegralComplexToFloatingComplex:
1110 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001111 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001112 case CK_ToUnion:
1113 llvm_unreachable("scalar cast to non-scalar value");
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001114 break;
John McCallf6a16482010-12-04 03:47:34 +00001115
1116 case CK_GetObjCProperty: {
1117 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
Douglas Gregorda29e092011-01-22 02:44:21 +00001118 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty &&
John McCallf6a16482010-12-04 03:47:34 +00001119 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
1120 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType());
1121 return RV.getScalarVal();
1122 }
John McCall0ae287a2010-12-01 04:43:34 +00001123
1124 case CK_LValueToRValue:
1125 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001126 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001127 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001128
John McCall2de56d12010-08-25 11:45:40 +00001129 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001130 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001131
Anders Carlsson82debc72009-10-18 18:12:03 +00001132 // First, convert to the correct width so that we control the kind of
1133 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +00001134 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Anders Carlsson82debc72009-10-18 18:12:03 +00001135 bool InputSigned = E->getType()->isSignedIntegerType();
1136 llvm::Value* IntResult =
1137 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001138
Anders Carlsson82debc72009-10-18 18:12:03 +00001139 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001140 }
John McCall2de56d12010-08-25 11:45:40 +00001141 case CK_PointerToIntegral: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001142 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001143
1144 // Handle conversion to bool correctly.
1145 if (DestTy->isBooleanType())
Daniel Dunbardb505472010-09-03 02:07:00 +00001146 return EmitScalarConversion(Src, E->getType(), DestTy);
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001147
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001148 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1149 }
John McCall2de56d12010-08-25 11:45:40 +00001150 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001151 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001152 return 0;
1153 }
John McCall2de56d12010-08-25 11:45:40 +00001154 case CK_VectorSplat: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001155 const llvm::Type *DstTy = ConvertType(DestTy);
1156 Value *Elt = Visit(const_cast<Expr*>(E));
1157
1158 // Insert the element in element zero of an undef vector
1159 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +00001160 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001161 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1162
1163 // Splat the element across to all elements
1164 llvm::SmallVector<llvm::Constant*, 16> Args;
1165 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
John McCalldaa8e4e2010-11-15 09:13:47 +00001166 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001167 for (unsigned i = 0; i < NumElements; i++)
John McCalldaa8e4e2010-11-15 09:13:47 +00001168 Args.push_back(Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001169
Chris Lattnerfb018d12011-02-15 00:14:06 +00001170 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Eli Friedmanad35a832009-11-16 21:33:53 +00001171 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1172 return Yay;
1173 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001174
John McCall2de56d12010-08-25 11:45:40 +00001175 case CK_IntegralCast:
1176 case CK_IntegralToFloating:
1177 case CK_FloatingToIntegral:
1178 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001179 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001180
John McCalldaa8e4e2010-11-15 09:13:47 +00001181 case CK_IntegralToBoolean:
1182 return EmitIntToBoolConversion(Visit(E));
1183 case CK_PointerToBoolean:
1184 return EmitPointerToBoolConversion(Visit(E));
1185 case CK_FloatingToBoolean:
1186 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001187 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001188 llvm::Value *MemPtr = Visit(E);
1189 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1190 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001191 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001192
1193 case CK_FloatingComplexToReal:
1194 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001195 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001196
1197 case CK_FloatingComplexToBoolean:
1198 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001199 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001200
1201 // TODO: kill this function off, inline appropriate case here
1202 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1203 }
1204
John McCall0bab0cd2010-08-23 01:21:21 +00001205 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001206
John McCall61ad0e62010-11-16 06:21:14 +00001207 llvm_unreachable("unknown scalar cast");
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001208 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +00001209}
1210
Chris Lattner33793202007-08-31 22:09:40 +00001211Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001212 CodeGenFunction::StmtExprEvaluation eval(CGF);
1213 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1214 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001215}
1216
Mike Stumpa99038c2009-02-28 09:07:16 +00001217Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +00001218 llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
1219 if (E->getType().isObjCGCWeak())
1220 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
Fariborz Jahanian469a20d2010-09-03 23:07:53 +00001221 return CGF.EmitLoadOfScalar(V, false, 0, E->getType());
Mike Stump4e7a1f72009-02-21 20:00:35 +00001222}
Chris Lattner33793202007-08-31 22:09:40 +00001223
Chris Lattner7f02f722007-08-24 05:35:26 +00001224//===----------------------------------------------------------------------===//
1225// Unary Operators
1226//===----------------------------------------------------------------------===//
1227
Chris Lattner8c11a652010-06-26 22:09:34 +00001228llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001229EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1230 llvm::Value *InVal,
1231 llvm::Value *NextVal, bool IsInc) {
1232 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1233 case LangOptions::SOB_Undefined:
1234 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1235 break;
1236 case LangOptions::SOB_Defined:
1237 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1238 break;
1239 case LangOptions::SOB_Trapping:
1240 BinOpInfo BinOp;
1241 BinOp.LHS = InVal;
1242 BinOp.RHS = NextVal;
1243 BinOp.Ty = E->getType();
1244 BinOp.Opcode = BO_Add;
1245 BinOp.E = E;
1246 return EmitOverflowCheckedBinOp(BinOp);
1247 break;
1248 }
1249 assert(false && "Unknown SignedOverflowBehaviorTy");
1250 return 0;
1251}
1252
John McCall5936e332011-02-15 09:22:45 +00001253llvm::Value *
1254ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1255 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001256
John McCall5936e332011-02-15 09:22:45 +00001257 QualType type = E->getSubExpr()->getType();
1258 llvm::Value *value = EmitLoadOfLValue(LV, type);
1259 llvm::Value *input = value;
Anton Yartsev683564a2011-02-07 02:17:30 +00001260
John McCall5936e332011-02-15 09:22:45 +00001261 int amount = (isInc ? 1 : -1);
1262
1263 // Special case of integer increment that we have to check first: bool++.
1264 // Due to promotion rules, we get:
1265 // bool++ -> bool = bool + 1
1266 // -> bool = (int)bool + 1
1267 // -> bool = ((int)bool + 1 != 0)
1268 // An interesting aspect of this is that increment is always true.
1269 // Decrement does not have this property.
1270 if (isInc && type->isBooleanType()) {
1271 value = Builder.getTrue();
1272
1273 // Most common case by far: integer increment.
1274 } else if (type->isIntegerType()) {
1275
1276 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1277
1278 if (type->isSignedIntegerType())
1279 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1280
1281 // Unsigned integer inc is always two's complement.
1282 else
1283 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1284
1285 // Next most common: pointer increment.
1286 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1287 QualType type = ptr->getPointeeType();
1288
1289 // VLA types don't have constant size.
1290 if (type->isVariableArrayType()) {
1291 llvm::Value *vlaSize =
1292 CGF.GetVLASize(CGF.getContext().getAsVariableArrayType(type));
1293 value = CGF.EmitCastToVoidPtr(value);
1294 if (!isInc) vlaSize = Builder.CreateNSWNeg(vlaSize, "vla.negsize");
1295 value = Builder.CreateInBoundsGEP(value, vlaSize, "vla.inc");
1296 value = Builder.CreateBitCast(value, input->getType());
1297
1298 // Arithmetic on function pointers (!) is just +-1.
1299 } else if (type->isFunctionType()) {
1300 llvm::Value *amt = llvm::ConstantInt::get(CGF.Int32Ty, amount);
1301
1302 value = CGF.EmitCastToVoidPtr(value);
1303 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1304 value = Builder.CreateBitCast(value, input->getType());
1305
1306 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001307 } else {
John McCall5936e332011-02-15 09:22:45 +00001308 llvm::Value *amt = llvm::ConstantInt::get(CGF.Int32Ty, amount);
1309 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1310 }
1311
1312 // Vector increment/decrement.
1313 } else if (type->isVectorType()) {
1314 if (type->hasIntegerRepresentation()) {
1315 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1316
1317 if (type->hasSignedIntegerRepresentation())
1318 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1319 else
1320 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1321 } else {
1322 value = Builder.CreateFAdd(
1323 value,
1324 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001325 isInc ? "inc" : "dec");
1326 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001327
John McCall5936e332011-02-15 09:22:45 +00001328 // Floating point.
1329 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001330 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001331 llvm::Value *amt;
1332 if (value->getType()->isFloatTy())
1333 amt = llvm::ConstantFP::get(VMContext,
1334 llvm::APFloat(static_cast<float>(amount)));
1335 else if (value->getType()->isDoubleTy())
1336 amt = llvm::ConstantFP::get(VMContext,
1337 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001338 else {
John McCall5936e332011-02-15 09:22:45 +00001339 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001340 bool ignored;
1341 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1342 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001343 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001344 }
John McCall5936e332011-02-15 09:22:45 +00001345 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1346
1347 // Objective-C pointer types.
1348 } else {
1349 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1350 value = CGF.EmitCastToVoidPtr(value);
1351
1352 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1353 if (!isInc) size = -size;
1354 llvm::Value *sizeValue =
1355 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1356
1357 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1358 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001359 }
1360
1361 // Store the updated result through the lvalue.
1362 if (LV.isBitField())
John McCall5936e332011-02-15 09:22:45 +00001363 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, type, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001364 else
John McCall5936e332011-02-15 09:22:45 +00001365 CGF.EmitStoreThroughLValue(RValue::get(value), LV, type);
Chris Lattner8c11a652010-06-26 22:09:34 +00001366
1367 // If this is a postinc, return the value read from memory, otherwise use the
1368 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001369 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001370}
1371
1372
1373
Chris Lattner7f02f722007-08-24 05:35:26 +00001374Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001375 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001376 // Emit unary minus with EmitSub so we handle overflow cases etc.
1377 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001378 BinOp.RHS = Visit(E->getSubExpr());
1379
1380 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1381 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1382 else
1383 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001384 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001385 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001386 BinOp.E = E;
1387 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001388}
1389
1390Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001391 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001392 Value *Op = Visit(E->getSubExpr());
1393 return Builder.CreateNot(Op, "neg");
1394}
1395
1396Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1397 // Compare operand to zero.
1398 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001399
Chris Lattner7f02f722007-08-24 05:35:26 +00001400 // Invert value.
1401 // TODO: Could dynamically modify easy computations here. For example, if
1402 // the operand is an icmp ne, turn into icmp eq.
1403 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001404
Anders Carlsson9f84d882009-05-19 18:44:53 +00001405 // ZExt result to the expr type.
1406 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001407}
1408
Eli Friedman0027d2b2010-08-05 09:58:49 +00001409Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1410 // Try folding the offsetof to a constant.
1411 Expr::EvalResult EvalResult;
1412 if (E->Evaluate(EvalResult, CGF.getContext()))
1413 return llvm::ConstantInt::get(VMContext, EvalResult.Val.getInt());
1414
1415 // Loop over the components of the offsetof to compute the value.
1416 unsigned n = E->getNumComponents();
1417 const llvm::Type* ResultType = ConvertType(E->getType());
1418 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1419 QualType CurrentType = E->getTypeSourceInfo()->getType();
1420 for (unsigned i = 0; i != n; ++i) {
1421 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001422 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001423 switch (ON.getKind()) {
1424 case OffsetOfExpr::OffsetOfNode::Array: {
1425 // Compute the index
1426 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1427 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1428 bool IdxSigned = IdxExpr->getType()->isSignedIntegerType();
1429 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1430
1431 // Save the element type
1432 CurrentType =
1433 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1434
1435 // Compute the element size
1436 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1437 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1438
1439 // Multiply out to compute the result
1440 Offset = Builder.CreateMul(Idx, ElemSize);
1441 break;
1442 }
1443
1444 case OffsetOfExpr::OffsetOfNode::Field: {
1445 FieldDecl *MemberDecl = ON.getField();
1446 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1447 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1448
1449 // Compute the index of the field in its parent.
1450 unsigned i = 0;
1451 // FIXME: It would be nice if we didn't have to loop here!
1452 for (RecordDecl::field_iterator Field = RD->field_begin(),
1453 FieldEnd = RD->field_end();
1454 Field != FieldEnd; (void)++Field, ++i) {
1455 if (*Field == MemberDecl)
1456 break;
1457 }
1458 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1459
1460 // Compute the offset to the field
1461 int64_t OffsetInt = RL.getFieldOffset(i) /
1462 CGF.getContext().getCharWidth();
1463 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1464
1465 // Save the element type.
1466 CurrentType = MemberDecl->getType();
1467 break;
1468 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001469
Eli Friedman0027d2b2010-08-05 09:58:49 +00001470 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001471 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001472
Eli Friedman0027d2b2010-08-05 09:58:49 +00001473 case OffsetOfExpr::OffsetOfNode::Base: {
1474 if (ON.getBase()->isVirtual()) {
1475 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1476 continue;
1477 }
1478
1479 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1480 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1481
1482 // Save the element type.
1483 CurrentType = ON.getBase()->getType();
1484
1485 // Compute the offset to the base.
1486 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1487 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Anders Carlssona14f5972010-10-31 23:22:37 +00001488 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
Eli Friedman0027d2b2010-08-05 09:58:49 +00001489 CGF.getContext().getCharWidth();
1490 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1491 break;
1492 }
1493 }
1494 Result = Builder.CreateAdd(Result, Offset);
1495 }
1496 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001497}
1498
Sebastian Redl05189992008-11-11 17:56:53 +00001499/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1500/// argument of the sizeof expression as an integer.
1501Value *
1502ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001503 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001504 if (E->isSizeOf()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001505 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001506 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1507 if (E->isArgumentType()) {
1508 // sizeof(type) - make sure to emit the VLA size.
1509 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001510 } else {
1511 // C99 6.5.3.4p2: If the argument is an expression of type
1512 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001513 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001514 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001515
Anders Carlsson96f21472009-02-05 19:43:10 +00001516 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +00001517 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001518 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001519
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001520 // If this isn't sizeof(vla), the result must be constant; use the constant
1521 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001522 Expr::EvalResult Result;
1523 E->Evaluate(Result, CGF.getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001524 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001525}
1526
Chris Lattner46f93d02007-08-24 21:20:17 +00001527Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1528 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001529 if (Op->getType()->isAnyComplexType()) {
1530 // If it's an l-value, load through the appropriate subobject l-value.
1531 // Note that we have to ask E because Op might be an l-value that
1532 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001533 if (E->isGLValue())
John McCallb418d742010-11-16 10:08:07 +00001534 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1535 .getScalarVal();
1536
1537 // Otherwise, calculate and project.
1538 return CGF.EmitComplexExpr(Op, false, true).first;
1539 }
1540
Chris Lattner46f93d02007-08-24 21:20:17 +00001541 return Visit(Op);
1542}
John McCallb418d742010-11-16 10:08:07 +00001543
Chris Lattner46f93d02007-08-24 21:20:17 +00001544Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1545 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001546 if (Op->getType()->isAnyComplexType()) {
1547 // If it's an l-value, load through the appropriate subobject l-value.
1548 // Note that we have to ask E because Op might be an l-value that
1549 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001550 if (Op->isGLValue())
John McCallb418d742010-11-16 10:08:07 +00001551 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1552 .getScalarVal();
1553
1554 // Otherwise, calculate and project.
1555 return CGF.EmitComplexExpr(Op, true, false).second;
1556 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001557
Mike Stump7f79f9b2009-05-29 15:46:01 +00001558 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1559 // effects are evaluated, but not the actual value.
John McCallb418d742010-11-16 10:08:07 +00001560 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001561 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001562}
1563
Chris Lattner7f02f722007-08-24 05:35:26 +00001564//===----------------------------------------------------------------------===//
1565// Binary Operators
1566//===----------------------------------------------------------------------===//
1567
1568BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001569 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001570 BinOpInfo Result;
1571 Result.LHS = Visit(E->getLHS());
1572 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001573 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001574 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001575 Result.E = E;
1576 return Result;
1577}
1578
Douglas Gregor6a03e342010-04-23 04:16:32 +00001579LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1580 const CompoundAssignOperator *E,
1581 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001582 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001583 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001584 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001585
Eli Friedmanab3a8522009-03-28 01:22:36 +00001586 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001587 // This needs to go through the complex expression emitter, but it's a tad
1588 // complicated to do that... I'm leaving it out for now. (Note that we do
1589 // actually need the imaginary part of the RHS for multiplication and
1590 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001591 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001592 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001593 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001594 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001595
Mike Stumpcc0442f2009-05-22 19:07:20 +00001596 // Emit the RHS first. __block variables need to have the rhs evaluated
1597 // first, plus this should improve codegen a little.
1598 OpInfo.RHS = Visit(E->getRHS());
1599 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001600 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001601 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001602 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001603 LValue LHSLV = EmitCheckedLValue(E->getLHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001604 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001605 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1606 E->getComputationLHSType());
Douglas Gregor6a03e342010-04-23 04:16:32 +00001607
Chris Lattner1f1ded92007-08-24 21:00:35 +00001608 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001609 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001610
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001611 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001612 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001613
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001614 // Store the result value into the LHS lvalue. Bit-fields are handled
1615 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1616 // 'An assignment expression has the value of the left operand after the
1617 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001618 if (LHSLV.isBitField())
1619 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1620 &Result);
1621 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001622 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001623
Douglas Gregor6a03e342010-04-23 04:16:32 +00001624 return LHSLV;
1625}
1626
1627Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1628 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1629 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001630 Value *RHS;
1631 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1632
1633 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001634 if (Ignore)
1635 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001636
John McCallb418d742010-11-16 10:08:07 +00001637 // The result of an assignment in C is the assigned r-value.
1638 if (!CGF.getContext().getLangOptions().CPlusPlus)
1639 return RHS;
1640
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001641 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00001642 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001643 return RHS;
1644
1645 // If the lvalue is non-volatile, return the computed value of the assignment.
1646 if (!LHS.isVolatileQualified())
1647 return RHS;
1648
1649 // Otherwise, reload the value.
1650 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001651}
1652
Chris Lattner80230302010-09-11 21:47:09 +00001653void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1654 const BinOpInfo &Ops,
1655 llvm::Value *Zero, bool isDiv) {
1656 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1657 llvm::BasicBlock *contBB =
1658 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn);
1659
1660 const llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1661
1662 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1663 llvm::Value *IntMin =
1664 llvm::ConstantInt::get(VMContext,
1665 llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1666 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1667
1668 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1669 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1670 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1671 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1672 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1673 overflowBB, contBB);
1674 } else {
1675 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1676 overflowBB, contBB);
1677 }
1678 EmitOverflowBB(overflowBB);
1679 Builder.SetInsertPoint(contBB);
1680}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001681
Chris Lattner7f02f722007-08-24 05:35:26 +00001682Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Chris Lattner80230302010-09-11 21:47:09 +00001683 if (isTrapvOverflowBehavior()) {
1684 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1685
1686 if (Ops.Ty->isIntegerType())
1687 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1688 else if (Ops.Ty->isRealFloatingType()) {
1689 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1690 CGF.CurFn);
1691 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn);
1692 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1693 overflowBB, DivCont);
1694 EmitOverflowBB(overflowBB);
1695 Builder.SetInsertPoint(DivCont);
1696 }
1697 }
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001698 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner7f02f722007-08-24 05:35:26 +00001699 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Douglas Gregorf6094622010-07-23 15:58:24 +00001700 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001701 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1702 else
1703 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1704}
1705
1706Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1707 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001708 if (isTrapvOverflowBehavior()) {
1709 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1710
1711 if (Ops.Ty->isIntegerType())
1712 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1713 }
1714
Chris Lattner1f1ded92007-08-24 21:00:35 +00001715 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001716 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1717 else
1718 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1719}
1720
Mike Stump2add4732009-04-01 20:28:16 +00001721Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1722 unsigned IID;
1723 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001724
Chris Lattner9a207232010-06-26 21:48:21 +00001725 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001726 case BO_Add:
1727 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001728 OpID = 1;
1729 IID = llvm::Intrinsic::sadd_with_overflow;
1730 break;
John McCall2de56d12010-08-25 11:45:40 +00001731 case BO_Sub:
1732 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001733 OpID = 2;
1734 IID = llvm::Intrinsic::ssub_with_overflow;
1735 break;
John McCall2de56d12010-08-25 11:45:40 +00001736 case BO_Mul:
1737 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001738 OpID = 3;
1739 IID = llvm::Intrinsic::smul_with_overflow;
1740 break;
1741 default:
1742 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001743 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001744 }
Mike Stump035cf892009-04-02 18:15:54 +00001745 OpID <<= 1;
1746 OpID |= 1;
1747
Mike Stump2add4732009-04-01 20:28:16 +00001748 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1749
1750 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1751
1752 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1753 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1754 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1755
1756 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001757 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Chris Lattner93a00352010-08-07 00:20:46 +00001758 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1759 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001760
1761 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1762
Chris Lattner93a00352010-08-07 00:20:46 +00001763 // Handle overflow with llvm.trap.
David Chisnall7f18e672010-09-17 18:29:54 +00001764 const std::string *handlerName =
1765 &CGF.getContext().getLangOptions().OverflowHandler;
1766 if (handlerName->empty()) {
1767 EmitOverflowBB(overflowBB);
1768 Builder.SetInsertPoint(continueBB);
1769 return result;
1770 }
1771
1772 // If an overflow handler is set, then we want to call it and then use its
1773 // result, if it returns.
1774 Builder.SetInsertPoint(overflowBB);
1775
1776 // Get the overflow handler.
1777 const llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
1778 std::vector<const llvm::Type*> argTypes;
1779 argTypes.push_back(CGF.Int64Ty); argTypes.push_back(CGF.Int64Ty);
1780 argTypes.push_back(Int8Ty); argTypes.push_back(Int8Ty);
1781 llvm::FunctionType *handlerTy =
1782 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1783 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1784
1785 // Sign extend the args to 64-bit, so that we can use the same handler for
1786 // all types of overflow.
1787 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1788 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1789
1790 // Call the handler with the two arguments, the operation, and the size of
1791 // the result.
1792 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1793 Builder.getInt8(OpID),
1794 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1795
1796 // Truncate the result back to the desired size.
1797 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1798 Builder.CreateBr(continueBB);
1799
Mike Stump2add4732009-04-01 20:28:16 +00001800 Builder.SetInsertPoint(continueBB);
David Chisnall7f18e672010-09-17 18:29:54 +00001801 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1802 phi->reserveOperandSpace(2);
1803 phi->addIncoming(result, initialBB);
1804 phi->addIncoming(handlerResult, overflowBB);
1805
1806 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001807}
Chris Lattner7f02f722007-08-24 05:35:26 +00001808
1809Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001810 if (!Ops.Ty->isAnyPointerType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001811 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001812 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1813 case LangOptions::SOB_Undefined:
1814 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1815 case LangOptions::SOB_Defined:
1816 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1817 case LangOptions::SOB_Trapping:
1818 return EmitOverflowCheckedBinOp(Ops);
1819 }
1820 }
1821
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001822 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001823 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanbf933a02009-08-12 01:16:29 +00001824
Chris Lattner7f02f722007-08-24 05:35:26 +00001825 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001826 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001827
Chris Lattner7f215c12010-06-26 21:52:32 +00001828 // Must have binary (not unary) expr here. Unary pointer decrement doesn't
Chris Lattner9a207232010-06-26 21:48:21 +00001829 // use this path.
1830 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1831
Steve Naroff14108da2009-07-10 23:34:53 +00001832 if (Ops.Ty->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001833 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001834 // The amount of the addition needs to account for the VLA size
Chris Lattner9a207232010-06-26 21:48:21 +00001835 CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001836 }
Chris Lattner9a207232010-06-26 21:48:21 +00001837
Chris Lattner8f925282008-01-03 06:36:51 +00001838 Value *Ptr, *Idx;
1839 Expr *IdxExp;
Chris Lattner9a207232010-06-26 21:48:21 +00001840 const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001841 const ObjCObjectPointerType *OPT =
Chris Lattner9a207232010-06-26 21:48:21 +00001842 BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001843 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001844 Ptr = Ops.LHS;
1845 Idx = Ops.RHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001846 IdxExp = BinOp->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001847 } else { // int + pointer
Chris Lattner9a207232010-06-26 21:48:21 +00001848 PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1849 OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001850 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001851 Ptr = Ops.RHS;
1852 Idx = Ops.LHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001853 IdxExp = BinOp->getLHS();
Chris Lattner8f925282008-01-03 06:36:51 +00001854 }
1855
1856 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
John McCall5936e332011-02-15 09:22:45 +00001857 if (Width < CGF.PointerWidthInBits) {
Chris Lattner8f925282008-01-03 06:36:51 +00001858 // Zero or sign extend the pointer value based on whether the index is
1859 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001860 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner96196622008-07-26 22:37:01 +00001861 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001862 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1863 else
1864 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1865 }
Steve Naroff14108da2009-07-10 23:34:53 +00001866 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001867 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001868 if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001869 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001870 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001871 CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001872 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001873 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001874 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1875 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1876 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001877 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001878
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001879 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1880 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1881 // future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001882 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001883 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001884 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001885 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001886 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001887 }
1888
Dan Gohman664f8932009-08-12 00:33:55 +00001889 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001890}
1891
1892Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001893 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001894 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001895 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1896 case LangOptions::SOB_Undefined:
1897 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1898 case LangOptions::SOB_Defined:
1899 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1900 case LangOptions::SOB_Trapping:
1901 return EmitOverflowCheckedBinOp(Ops);
1902 }
1903 }
1904
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001905 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001906 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00001907
Chris Lattner7f02f722007-08-24 05:35:26 +00001908 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001909 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001910
Chris Lattner9a207232010-06-26 21:48:21 +00001911 // Must have binary (not unary) expr here. Unary pointer increment doesn't
1912 // use this path.
1913 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1914
1915 if (BinOp->getLHS()->getType()->isPointerType() &&
1916 BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001917 // The amount of the addition needs to account for the VLA size for
1918 // ptr-int
1919 // The amount of the division needs to account for the VLA size for
1920 // ptr-ptr.
Chris Lattner9a207232010-06-26 21:48:21 +00001921 CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001922 }
1923
Chris Lattner9a207232010-06-26 21:48:21 +00001924 const QualType LHSType = BinOp->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001925 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001926 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1927 // pointer - int
1928 Value *Idx = Ops.RHS;
1929 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
John McCall5936e332011-02-15 09:22:45 +00001930 if (Width < CGF.PointerWidthInBits) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001931 // Zero or sign extend the pointer value based on whether the index is
1932 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001933 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner9a207232010-06-26 21:48:21 +00001934 if (BinOp->getRHS()->getType()->isSignedIntegerType())
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001935 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1936 else
1937 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1938 }
1939 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001940
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001941 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001942 if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001943 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001944 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001945 CGF.getContext().
1946 getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001947 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001948 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001949 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1950 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1951 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001952 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001953
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001954 // Explicitly handle GNU void* and function pointer arithmetic
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001955 // extensions. The GNU void* casts amount to no-ops since our void* type is
1956 // i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001957 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001958 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001959 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1960 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1961 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001962 }
1963
Dan Gohman664f8932009-08-12 00:33:55 +00001964 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001965 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001966 // pointer - pointer
1967 Value *LHS = Ops.LHS;
1968 Value *RHS = Ops.RHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001969
Ken Dyck199c3d62010-01-11 17:06:35 +00001970 CharUnits ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001971
Chris Lattnere5ed1512009-02-11 07:21:43 +00001972 // Handle GCC extension for pointer arithmetic on void* and function pointer
1973 // types.
1974 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Ken Dyck199c3d62010-01-11 17:06:35 +00001975 ElementSize = CharUnits::One();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001976 } else {
Ken Dyck199c3d62010-01-11 17:06:35 +00001977 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001978 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001979
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001980 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1981 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1982 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1983 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001984
Chris Lattnere5ed1512009-02-11 07:21:43 +00001985 // Optimize out the shift for element size of 1.
Ken Dyck199c3d62010-01-11 17:06:35 +00001986 if (ElementSize.isOne())
Chris Lattnere5ed1512009-02-11 07:21:43 +00001987 return BytesBetween;
Dan Gohmandf110942009-08-11 22:40:09 +00001988
1989 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001990 // pointer difference in C is only defined in the case where both operands
1991 // are pointing to elements of an array.
Ken Dyck199c3d62010-01-11 17:06:35 +00001992 Value *BytesPerElt =
1993 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
Dan Gohmandf110942009-08-11 22:40:09 +00001994 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00001995 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001996}
1997
1998Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1999 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2000 // RHS to the same size as the LHS.
2001 Value *RHS = Ops.RHS;
2002 if (Ops.LHS->getType() != RHS->getType())
2003 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002004
Mike Stumpbe07f602009-12-14 21:58:14 +00002005 if (CGF.CatchUndefined
2006 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2007 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2008 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2009 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2010 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002011 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002012 CGF.EmitBlock(Cont);
2013 }
2014
Chris Lattner7f02f722007-08-24 05:35:26 +00002015 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2016}
2017
2018Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2019 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2020 // RHS to the same size as the LHS.
2021 Value *RHS = Ops.RHS;
2022 if (Ops.LHS->getType() != RHS->getType())
2023 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002024
Mike Stumpbe07f602009-12-14 21:58:14 +00002025 if (CGF.CatchUndefined
2026 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2027 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2028 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2029 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2030 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002031 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002032 CGF.EmitBlock(Cont);
2033 }
2034
Douglas Gregorf6094622010-07-23 15:58:24 +00002035 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002036 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2037 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2038}
2039
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002040enum IntrinsicType { VCMPEQ, VCMPGT };
2041// return corresponding comparison intrinsic for given vector type
2042static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2043 BuiltinType::Kind ElemKind) {
2044 switch (ElemKind) {
2045 default: assert(0 && "unexpected element type");
2046 case BuiltinType::Char_U:
2047 case BuiltinType::UChar:
2048 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2049 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2050 break;
2051 case BuiltinType::Char_S:
2052 case BuiltinType::SChar:
2053 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2054 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2055 break;
2056 case BuiltinType::UShort:
2057 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2058 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2059 break;
2060 case BuiltinType::Short:
2061 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2062 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2063 break;
2064 case BuiltinType::UInt:
2065 case BuiltinType::ULong:
2066 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2067 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2068 break;
2069 case BuiltinType::Int:
2070 case BuiltinType::Long:
2071 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2072 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2073 break;
2074 case BuiltinType::Float:
2075 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2076 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2077 break;
2078 }
2079 return llvm::Intrinsic::not_intrinsic;
2080}
2081
Chris Lattner7f02f722007-08-24 05:35:26 +00002082Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2083 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002084 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002085 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002086 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002087 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002088 assert(E->getOpcode() == BO_EQ ||
2089 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002090 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2091 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002092 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002093 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002094 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002095 Value *LHS = Visit(E->getLHS());
2096 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002097
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002098 // If AltiVec, the comparison results in a numeric type, so we use
2099 // intrinsics comparing vectors and giving 0 or 1 as a result
2100 if (LHSTy->isVectorType() && CGF.getContext().getLangOptions().AltiVec) {
2101 // constants for mapping CR6 register bits to predicate result
2102 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2103
2104 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2105
2106 // in several cases vector arguments order will be reversed
2107 Value *FirstVecArg = LHS,
2108 *SecondVecArg = RHS;
2109
2110 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002111 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002112 BuiltinType::Kind ElementKind = BTy->getKind();
2113
2114 switch(E->getOpcode()) {
2115 default: assert(0 && "is not a comparison operation");
2116 case BO_EQ:
2117 CR6 = CR6_LT;
2118 ID = GetIntrinsic(VCMPEQ, ElementKind);
2119 break;
2120 case BO_NE:
2121 CR6 = CR6_EQ;
2122 ID = GetIntrinsic(VCMPEQ, ElementKind);
2123 break;
2124 case BO_LT:
2125 CR6 = CR6_LT;
2126 ID = GetIntrinsic(VCMPGT, ElementKind);
2127 std::swap(FirstVecArg, SecondVecArg);
2128 break;
2129 case BO_GT:
2130 CR6 = CR6_LT;
2131 ID = GetIntrinsic(VCMPGT, ElementKind);
2132 break;
2133 case BO_LE:
2134 if (ElementKind == BuiltinType::Float) {
2135 CR6 = CR6_LT;
2136 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2137 std::swap(FirstVecArg, SecondVecArg);
2138 }
2139 else {
2140 CR6 = CR6_EQ;
2141 ID = GetIntrinsic(VCMPGT, ElementKind);
2142 }
2143 break;
2144 case BO_GE:
2145 if (ElementKind == BuiltinType::Float) {
2146 CR6 = CR6_LT;
2147 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2148 }
2149 else {
2150 CR6 = CR6_EQ;
2151 ID = GetIntrinsic(VCMPGT, ElementKind);
2152 std::swap(FirstVecArg, SecondVecArg);
2153 }
2154 break;
2155 }
2156
2157 Value *CR6Param = llvm::ConstantInt::get(CGF.Int32Ty, CR6);
2158 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2159 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2160 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2161 }
2162
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002163 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002164 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002165 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002166 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002167 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002168 LHS, RHS, "cmp");
2169 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002170 // Unsigned integers and pointers.
2171 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002172 LHS, RHS, "cmp");
2173 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002174
2175 // If this is a vector comparison, sign extend the result to the appropriate
2176 // vector integer type and return it (don't convert to bool).
2177 if (LHSTy->isVectorType())
2178 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002179
Chris Lattner7f02f722007-08-24 05:35:26 +00002180 } else {
2181 // Complex Comparison: can only be an equality comparison.
2182 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2183 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002184
John McCall183700f2009-09-21 23:43:11 +00002185 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002186
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002187 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002188 if (CETy->isRealFloatingType()) {
2189 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2190 LHS.first, RHS.first, "cmp.r");
2191 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2192 LHS.second, RHS.second, "cmp.i");
2193 } else {
2194 // Complex comparisons can only be equality comparisons. As such, signed
2195 // and unsigned opcodes are the same.
2196 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2197 LHS.first, RHS.first, "cmp.r");
2198 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2199 LHS.second, RHS.second, "cmp.i");
2200 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002201
John McCall2de56d12010-08-25 11:45:40 +00002202 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002203 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2204 } else {
John McCall2de56d12010-08-25 11:45:40 +00002205 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002206 "Complex comparison other than == or != ?");
2207 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2208 }
2209 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002210
2211 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002212}
2213
2214Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002215 bool Ignore = TestAndClearIgnoreResultAssign();
2216
2217 // __block variables need to have the rhs evaluated first, plus this should
2218 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00002219 Value *RHS = Visit(E->getRHS());
Mike Stumpb14e62d2009-12-16 02:57:00 +00002220 LValue LHS = EmitCheckedLValue(E->getLHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002221
Daniel Dunbared3849b2008-11-19 09:36:46 +00002222 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00002223 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2224 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00002225 // the assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002226 if (LHS.isBitField())
2227 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
2228 &RHS);
2229 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00002230 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002231
2232 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002233 if (Ignore)
2234 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002235
John McCallb418d742010-11-16 10:08:07 +00002236 // The result of an assignment in C is the assigned r-value.
2237 if (!CGF.getContext().getLangOptions().CPlusPlus)
2238 return RHS;
2239
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002240 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00002241 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002242 return RHS;
2243
2244 // If the lvalue is non-volatile, return the computed value of the assignment.
2245 if (!LHS.isVolatileQualified())
2246 return RHS;
2247
2248 // Otherwise, reload the value.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002249 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002250}
2251
2252Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00002253 const llvm::Type *ResTy = ConvertType(E->getType());
2254
Chris Lattner20eb09d2008-11-12 08:26:50 +00002255 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2256 // If we have 1 && X, just emit X without inserting the control flow.
2257 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
2258 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002259 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002260 // ZExt result to int or bool.
2261 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002262 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002263
Chris Lattner7804bcb2009-10-17 04:24:20 +00002264 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002265 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002266 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002267 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002268
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002269 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2270 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002271
John McCall150b4622011-01-26 04:00:11 +00002272 CodeGenFunction::ConditionalEvaluation eval(CGF);
2273
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002274 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2275 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2276
2277 // Any edges into the ContBlock are now from an (indeterminate number of)
2278 // edges from this first condition. All of these values will be false. Start
2279 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00002280 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
2281 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002282 PN->reserveOperandSpace(2); // Normal case, two inputs.
2283 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2284 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002285 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002286
John McCall150b4622011-01-26 04:00:11 +00002287 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002288 CGF.EmitBlock(RHSBlock);
2289 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002290 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002291
Chris Lattner7f02f722007-08-24 05:35:26 +00002292 // Reaquire the RHS block, as there may be subblocks inserted.
2293 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002294
2295 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2296 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00002297 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002298 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002299
Chris Lattner7f02f722007-08-24 05:35:26 +00002300 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002301 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002302}
2303
2304Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00002305 const llvm::Type *ResTy = ConvertType(E->getType());
2306
Chris Lattner20eb09d2008-11-12 08:26:50 +00002307 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2308 // If we have 0 || X, just emit X without inserting the control flow.
2309 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
2310 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002311 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002312 // ZExt result to int or bool.
2313 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002314 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002315
Chris Lattner7804bcb2009-10-17 04:24:20 +00002316 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002317 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002318 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002319 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002320
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002321 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2322 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002323
John McCall150b4622011-01-26 04:00:11 +00002324 CodeGenFunction::ConditionalEvaluation eval(CGF);
2325
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002326 // Branch on the LHS first. If it is true, go to the success (cont) block.
2327 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2328
2329 // Any edges into the ContBlock are now from an (indeterminate number of)
2330 // edges from this first condition. All of these values will be true. Start
2331 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00002332 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
2333 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002334 PN->reserveOperandSpace(2); // Normal case, two inputs.
2335 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2336 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002337 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002338
John McCall150b4622011-01-26 04:00:11 +00002339 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002340
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002341 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002342 CGF.EmitBlock(RHSBlock);
2343 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002344
John McCall150b4622011-01-26 04:00:11 +00002345 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002346
Chris Lattner7f02f722007-08-24 05:35:26 +00002347 // Reaquire the RHS block, as there may be subblocks inserted.
2348 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002349
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002350 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2351 // into the phi node for the edge with the value of RHSCond.
2352 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002353 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002354
Chris Lattner7f02f722007-08-24 05:35:26 +00002355 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002356 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002357}
2358
2359Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002360 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002361 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002362 return Visit(E->getRHS());
2363}
2364
2365//===----------------------------------------------------------------------===//
2366// Other Operators
2367//===----------------------------------------------------------------------===//
2368
Chris Lattner9802a512008-11-12 08:55:54 +00002369/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2370/// expression is cheap enough and side-effect-free enough to evaluate
2371/// unconditionally instead of conditionally. This is used to convert control
2372/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002373static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2374 CodeGenFunction &CGF) {
Chris Lattner9802a512008-11-12 08:55:54 +00002375 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002376 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002377
Chris Lattner9802a512008-11-12 08:55:54 +00002378 // TODO: Allow anything we can constant fold to an integer or fp constant.
2379 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
2380 isa<FloatingLiteral>(E))
2381 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002382
Chris Lattner9802a512008-11-12 08:55:54 +00002383 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2384 // X and Y are local variables.
2385 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2386 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002387 if (VD->hasLocalStorage() && !(CGF.getContext()
2388 .getCanonicalType(VD->getType())
2389 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002390 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002391
Chris Lattner9802a512008-11-12 08:55:54 +00002392 return false;
2393}
2394
2395
Chris Lattner7f02f722007-08-24 05:35:26 +00002396Value *ScalarExprEmitter::
2397VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002398 TestAndClearIgnoreResultAssign();
Chris Lattner31a09842008-11-12 08:04:58 +00002399 // If the condition constant folds and can be elided, try to avoid emitting
2400 // the condition and the dead arm.
2401 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00002402 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00002403 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00002404 std::swap(Live, Dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002405
Chris Lattner31a09842008-11-12 08:04:58 +00002406 // If the dead side doesn't have labels we need, and if the Live side isn't
2407 // the gnu missing ?: extension (which we could handle, but don't bother
2408 // to), just emit the Live part.
2409 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
2410 Live) // Live part isn't missing.
2411 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00002412 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002413
Nate Begeman6155d732010-09-20 22:41:17 +00002414 // OpenCL: If the condition is a vector, we can treat this condition like
2415 // the select function.
2416 if (CGF.getContext().getLangOptions().OpenCL
2417 && E->getCond()->getType()->isVectorType()) {
2418 llvm::Value *CondV = CGF.EmitScalarExpr(E->getCond());
2419 llvm::Value *LHS = Visit(E->getLHS());
2420 llvm::Value *RHS = Visit(E->getRHS());
2421
2422 const llvm::Type *condType = ConvertType(E->getCond()->getType());
2423 const llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2424
2425 unsigned numElem = vecTy->getNumElements();
2426 const llvm::Type *elemType = vecTy->getElementType();
2427
2428 std::vector<llvm::Constant*> Zvals;
2429 for (unsigned i = 0; i < numElem; ++i)
2430 Zvals.push_back(llvm::ConstantInt::get(elemType,0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002431
Nate Begeman6155d732010-09-20 22:41:17 +00002432 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2433 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2434 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2435 llvm::VectorType::get(elemType,
2436 numElem),
2437 "sext");
2438 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2439
2440 // Cast float to int to perform ANDs if necessary.
2441 llvm::Value *RHSTmp = RHS;
2442 llvm::Value *LHSTmp = LHS;
2443 bool wasCast = false;
2444 const llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2445 if (rhsVTy->getElementType()->isFloatTy()) {
2446 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2447 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2448 wasCast = true;
2449 }
2450
2451 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2452 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2453 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2454 if (wasCast)
2455 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2456
2457 return tmp5;
2458 }
2459
Chris Lattner9802a512008-11-12 08:55:54 +00002460 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2461 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002462 // safe to evaluate the LHS and RHS unconditionally.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002463 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(),
2464 CGF) &&
2465 isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) {
Chris Lattner9802a512008-11-12 08:55:54 +00002466 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
2467 llvm::Value *LHS = Visit(E->getLHS());
2468 llvm::Value *RHS = Visit(E->getRHS());
2469 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2470 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002471
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002472 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2473 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002474 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002475
2476 CodeGenFunction::ConditionalEvaluation eval(CGF);
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +00002477
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002478 // If we don't have the GNU missing condition extension, emit a branch on bool
2479 // the normal way.
Chris Lattner12d152f2009-02-13 23:35:32 +00002480 if (E->getLHS()) {
2481 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
2482 // the branch on bool.
2483 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
2484 } else {
2485 // Otherwise, for the ?: extension, evaluate the conditional and then
2486 // convert it to bool the hard way. We do this explicitly because we need
2487 // the unconverted value for the missing middle value of the ?:.
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +00002488 Expr *save = E->getSAVE();
2489 assert(save && "VisitConditionalOperator - save is null");
2490 // Intentianlly not doing direct assignment to ConditionalSaveExprs[save] !!
2491 Value *SaveVal = CGF.EmitScalarExpr(save);
2492 CGF.ConditionalSaveExprs[save] = SaveVal;
2493 Value *CondVal = Visit(E->getCond());
Chris Lattner12d152f2009-02-13 23:35:32 +00002494 // In some cases, EmitScalarConversion will delete the "CondVal" expression
2495 // if there are no extra uses (an optimization). Inhibit this by making an
2496 // extra dead use, because we're going to add a use of CondVal later. We
2497 // don't use the builder for this, because we don't want it to get optimized
2498 // away. This leaves dead code, but the ?: extension isn't common.
2499 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
2500 Builder.GetInsertBlock());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002501
Chris Lattner035cf422008-11-12 08:08:13 +00002502 Value *CondBoolVal =
2503 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
2504 CGF.getContext().BoolTy);
2505 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00002506 }
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002507
Chris Lattner7f02f722007-08-24 05:35:26 +00002508 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002509 eval.begin(CGF);
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +00002510 Value *LHS = Visit(E->getTrueExpr());
John McCall150b4622011-01-26 04:00:11 +00002511 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002512
Chris Lattner7f02f722007-08-24 05:35:26 +00002513 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002514 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002515
Chris Lattner7f02f722007-08-24 05:35:26 +00002516 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002517 eval.begin(CGF);
Eli Friedman856226c2008-05-16 20:38:39 +00002518 Value *RHS = Visit(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002519 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002520
John McCall150b4622011-01-26 04:00:11 +00002521 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002522 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002523
Eli Friedman48daf592009-12-07 20:25:53 +00002524 // If the LHS or RHS is a throw expression, it will be legitimately null.
2525 if (!LHS)
2526 return RHS;
2527 if (!RHS)
2528 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002529
Chris Lattner7f02f722007-08-24 05:35:26 +00002530 // Create a PHI node for the real part.
2531 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
2532 PN->reserveOperandSpace(2);
2533 PN->addIncoming(LHS, LHSBlock);
2534 PN->addIncoming(RHS, RHSBlock);
2535 return PN;
2536}
2537
2538Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002539 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002540}
2541
Chris Lattner2202bce2007-11-30 17:56:23 +00002542Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002543 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002544 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2545
2546 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002547 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002548 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2549
Mike Stump7f79f9b2009-05-29 15:46:01 +00002550 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002551 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002552}
2553
John McCall6b5a61b2011-02-07 10:33:21 +00002554Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2555 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002556}
2557
Chris Lattner7f02f722007-08-24 05:35:26 +00002558//===----------------------------------------------------------------------===//
2559// Entry Point into this File
2560//===----------------------------------------------------------------------===//
2561
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002562/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2563/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002564Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002565 assert(E && !hasAggregateLLVMType(E->getType()) &&
2566 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002567
Mike Stump7f79f9b2009-05-29 15:46:01 +00002568 return ScalarExprEmitter(*this, IgnoreResultAssign)
2569 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00002570}
Chris Lattner3707b252007-08-26 06:48:56 +00002571
2572/// EmitScalarConversion - Emit a conversion from the specified type to the
2573/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002574Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2575 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002576 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2577 "Invalid scalar expression to emit");
2578 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2579}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002580
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002581/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2582/// type to the specified destination type, where the destination type is an
2583/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002584Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2585 QualType SrcTy,
2586 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002587 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002588 "Invalid complex -> scalar conversion");
2589 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2590 DstTy);
2591}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002592
Chris Lattner8c11a652010-06-26 22:09:34 +00002593
2594llvm::Value *CodeGenFunction::
2595EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2596 bool isInc, bool isPre) {
2597 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2598}
2599
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002600LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2601 llvm::Value *V;
2602 // object->isa or (*object).isa
2603 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002604 // build Class* type
2605 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002606
2607 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002608 if (BaseExpr->isRValue()) {
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002609 V = CreateTempAlloca(ClassPtrTy, "resval");
2610 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2611 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002612 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2613 MakeAddrLValue(V, E->getType()), E->getType());
2614 } else {
2615 if (E->isArrow())
2616 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2617 else
2618 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002619 }
2620
2621 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002622 ClassPtrTy = ClassPtrTy->getPointerTo();
2623 V = Builder.CreateBitCast(V, ClassPtrTy);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002624 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002625}
2626
Douglas Gregor6a03e342010-04-23 04:16:32 +00002627
John McCall2a416372010-12-05 02:00:02 +00002628LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002629 const CompoundAssignOperator *E) {
2630 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002631 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002632 switch (E->getOpcode()) {
2633#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002634 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002635 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002636 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002637 COMPOUND_OP(Mul);
2638 COMPOUND_OP(Div);
2639 COMPOUND_OP(Rem);
2640 COMPOUND_OP(Add);
2641 COMPOUND_OP(Sub);
2642 COMPOUND_OP(Shl);
2643 COMPOUND_OP(Shr);
2644 COMPOUND_OP(And);
2645 COMPOUND_OP(Xor);
2646 COMPOUND_OP(Or);
2647#undef COMPOUND_OP
2648
John McCall2de56d12010-08-25 11:45:40 +00002649 case BO_PtrMemD:
2650 case BO_PtrMemI:
2651 case BO_Mul:
2652 case BO_Div:
2653 case BO_Rem:
2654 case BO_Add:
2655 case BO_Sub:
2656 case BO_Shl:
2657 case BO_Shr:
2658 case BO_LT:
2659 case BO_GT:
2660 case BO_LE:
2661 case BO_GE:
2662 case BO_EQ:
2663 case BO_NE:
2664 case BO_And:
2665 case BO_Xor:
2666 case BO_Or:
2667 case BO_LAnd:
2668 case BO_LOr:
2669 case BO_Assign:
2670 case BO_Comma:
Douglas Gregor6a03e342010-04-23 04:16:32 +00002671 assert(false && "Not valid compound assignment operators");
2672 break;
2673 }
2674
2675 llvm_unreachable("Unhandled compound assignment operator");
2676}