blob: 3e1debd820b4a8add79b7335770ca3a32f43a3de [file] [log] [blame]
Chris Lattner7f02f722007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner7f02f722007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patel78ba3d42010-10-04 21:46:04 +000014#include "clang/Frontend/CodeGenOptions.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000015#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000017#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000018#include "CodeGenModule.h"
Devang Patel78ba3d42010-10-04 21:46:04 +000019#include "CGDebugInfo.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000023#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000024#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000025#include "llvm/Constants.h"
26#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000027#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000028#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000029#include "llvm/Module.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000030#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000031#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000032#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000033
Chris Lattner7f02f722007-08-24 05:35:26 +000034using namespace clang;
35using namespace CodeGen;
36using llvm::Value;
37
38//===----------------------------------------------------------------------===//
39// Scalar Expression Emitter
40//===----------------------------------------------------------------------===//
41
Benjamin Kramer79ba2a62010-10-22 16:48:22 +000042namespace {
Chris Lattner7f02f722007-08-24 05:35:26 +000043struct BinOpInfo {
44 Value *LHS;
45 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000046 QualType Ty; // Computation Type.
Chris Lattner9a207232010-06-26 21:48:21 +000047 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
48 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000049};
50
John McCall404cd162010-11-13 01:35:44 +000051static bool MustVisitNullValue(const Expr *E) {
52 // If a null pointer expression's type is the C++0x nullptr_t, then
53 // it's not necessarily a simple constant and it must be evaluated
54 // for its potential side effects.
55 return E->getType()->isNullPtrType();
56}
57
Benjamin Kramer85b45212009-11-28 19:45:26 +000058class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000059 : public StmtVisitor<ScalarExprEmitter, Value*> {
60 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000061 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000062 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000063 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000064public:
65
Mike Stump7f79f9b2009-05-29 15:46:01 +000066 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000067 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000068 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000069 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000070
Chris Lattner7f02f722007-08-24 05:35:26 +000071 //===--------------------------------------------------------------------===//
72 // Utilities
73 //===--------------------------------------------------------------------===//
74
Mike Stump7f79f9b2009-05-29 15:46:01 +000075 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000076 bool I = IgnoreResultAssign;
77 IgnoreResultAssign = false;
78 return I;
79 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000080
Chris Lattner7f02f722007-08-24 05:35:26 +000081 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
82 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Mike Stumpb14e62d2009-12-16 02:57:00 +000083 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
Chris Lattner7f02f722007-08-24 05:35:26 +000084
85 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000086 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000087 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000088
Chris Lattner7f02f722007-08-24 05:35:26 +000089 /// EmitLoadOfLValue - Given an expression with complex type that represents a
90 /// value l-value, this method emits the address of the l-value, then loads
91 /// and returns the result.
92 Value *EmitLoadOfLValue(const Expr *E) {
Mike Stumpb14e62d2009-12-16 02:57:00 +000093 return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +000094 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000095
Chris Lattner9abc84e2007-08-26 16:42:57 +000096 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000097 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000098 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +000099
Chris Lattner3707b252007-08-26 06:48:56 +0000100 /// EmitScalarConversion - Emit a conversion from the specified type to the
101 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000102 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
103
104 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000105 /// complex type to the specified destination type, where the destination type
106 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000107 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
108 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000109
Anders Carlssona40a9f32010-05-22 17:45:10 +0000110 /// EmitNullValue - Emit a value that corresponds to null for the given type.
111 Value *EmitNullValue(QualType Ty);
112
John McCalldaa8e4e2010-11-15 09:13:47 +0000113 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
114 Value *EmitFloatToBoolConversion(Value *V) {
115 // Compare against 0.0 for fp scalars.
116 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
117 return Builder.CreateFCmpUNE(V, Zero, "tobool");
118 }
119
120 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
121 Value *EmitPointerToBoolConversion(Value *V) {
122 Value *Zero = llvm::ConstantPointerNull::get(
123 cast<llvm::PointerType>(V->getType()));
124 return Builder.CreateICmpNE(V, Zero, "tobool");
125 }
126
127 Value *EmitIntToBoolConversion(Value *V) {
128 // Because of the type rules of C, we often end up computing a
129 // logical value, then zero extending it to int, then wanting it
130 // as a logical value again. Optimize this common case.
131 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
132 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
133 Value *Result = ZI->getOperand(0);
134 // If there aren't any more uses, zap the instruction to save space.
135 // Note that there can be more uses, for example if this
136 // is the result of an assignment.
137 if (ZI->use_empty())
138 ZI->eraseFromParent();
139 return Result;
140 }
141 }
142
143 const llvm::IntegerType *Ty = cast<llvm::IntegerType>(V->getType());
144 Value *Zero = llvm::ConstantInt::get(Ty, 0);
145 return Builder.CreateICmpNE(V, Zero, "tobool");
146 }
147
Chris Lattner7f02f722007-08-24 05:35:26 +0000148 //===--------------------------------------------------------------------===//
149 // Visitor Methods
150 //===--------------------------------------------------------------------===//
151
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000152 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000153 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
154 }
155
Chris Lattner7f02f722007-08-24 05:35:26 +0000156 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000157 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000158 assert(0 && "Stmt can't have complex result type!");
159 return 0;
160 }
161 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000162
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000163 Value *VisitParenExpr(ParenExpr *PE) {
164 return Visit(PE->getSubExpr());
165 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000166
167 // Leaves.
168 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000169 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000170 }
171 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000172 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000173 }
174 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000175 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000176 }
Nate Begemane7579b52007-11-15 05:40:03 +0000177 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000178 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000179 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000180 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000181 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000182 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000183 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000184 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000185 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000186 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +0000187 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000188 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000189 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
190 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000191 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000192
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000193 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
194 return llvm::ConstantInt::get(ConvertType(E->getType()),
195 E->getPackLength());
196 }
John McCalle996ffd2011-02-16 08:02:54 +0000197
198 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000199 if (E->isGLValue())
200 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getType());
John McCalle996ffd2011-02-16 08:02:54 +0000201
202 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000203 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000204 }
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000205
Chris Lattner7f02f722007-08-24 05:35:26 +0000206 // l-values.
207 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000208 Expr::EvalResult Result;
John McCall189d6ef2010-10-09 01:34:31 +0000209 if (!E->Evaluate(Result, CGF.getContext()))
210 return EmitLoadOfLValue(E);
211
212 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
213
214 llvm::Constant *C;
215 if (Result.Val.isInt()) {
216 C = llvm::ConstantInt::get(VMContext, Result.Val.getInt());
217 } else if (Result.Val.isFloat()) {
218 C = llvm::ConstantFP::get(VMContext, Result.Val.getFloat());
219 } else {
220 return EmitLoadOfLValue(E);
Eli Friedman28665272009-11-26 03:22:21 +0000221 }
John McCall189d6ef2010-10-09 01:34:31 +0000222
223 // Make sure we emit a debug reference to the global variable.
224 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
225 if (!CGF.getContext().DeclMustBeEmitted(VD))
226 CGF.EmitDeclRefExprDbgValue(E, C);
227 } else if (isa<EnumConstantDecl>(E->getDecl())) {
228 CGF.EmitDeclRefExprDbgValue(E, C);
229 }
230
231 return C;
Chris Lattner7f02f722007-08-24 05:35:26 +0000232 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000233 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
234 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000235 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000236 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
237 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000238 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000239 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000240 return EmitLoadOfLValue(E);
241 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000242 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
John McCallf6a16482010-12-04 03:47:34 +0000243 assert(E->getObjectKind() == OK_Ordinary &&
244 "reached property reference without lvalue-to-rvalue");
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000245 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000246 }
247 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
248 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000249 }
250
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000251 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000252 LValue LV = CGF.EmitObjCIsaExpr(E);
253 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000254 return V;
255 }
256
Chris Lattner7f02f722007-08-24 05:35:26 +0000257 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000258 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000259 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000260 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000261 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
262 return EmitLoadOfLValue(E);
263 }
Devang Patel35634f52007-10-24 17:18:43 +0000264
Nate Begeman0533b302009-10-18 20:10:40 +0000265 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000266
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000267 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000268 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000269 }
Eli Friedmand8889622009-11-27 04:41:50 +0000270 Value *VisitCastExpr(CastExpr *E) {
Eli Friedmanc62aad82009-04-20 03:54:15 +0000271 // Make sure to evaluate VLA bounds now so that we have them for later.
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000272 if (E->getType()->isVariablyModifiedType())
273 CGF.EmitVLASize(E->getType());
Eli Friedmanc62aad82009-04-20 03:54:15 +0000274
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000275 return EmitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000276 }
Eli Friedmand8889622009-11-27 04:41:50 +0000277 Value *EmitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000278
279 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000280 if (E->getCallReturnType()->isReferenceType())
281 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000282
Chris Lattner9b655512007-08-31 22:49:20 +0000283 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000284 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000285
Chris Lattner33793202007-08-31 22:09:40 +0000286 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000287
Mike Stumpa99038c2009-02-28 09:07:16 +0000288 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000289
Chris Lattner7f02f722007-08-24 05:35:26 +0000290 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000291 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000292 LValue LV = EmitLValue(E->getSubExpr());
293 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000294 }
295 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000296 LValue LV = EmitLValue(E->getSubExpr());
297 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000298 }
299 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000300 LValue LV = EmitLValue(E->getSubExpr());
301 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000302 }
303 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000304 LValue LV = EmitLValue(E->getSubExpr());
305 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000306 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000307
Anton Yartsev683564a2011-02-07 02:17:30 +0000308 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
309 llvm::Value *InVal,
310 llvm::Value *NextVal,
311 bool IsInc);
312
Chris Lattner8c11a652010-06-26 22:09:34 +0000313 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
314 bool isInc, bool isPre);
315
316
Chris Lattner7f02f722007-08-24 05:35:26 +0000317 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000318 if (isa<MemberPointerType>(E->getType())) // never sugared
319 return CGF.CGM.getMemberPointerConstant(E);
320
Chris Lattner7f02f722007-08-24 05:35:26 +0000321 return EmitLValue(E->getSubExpr()).getAddress();
322 }
John McCallfd569002010-12-04 12:43:24 +0000323 Value *VisitUnaryDeref(const UnaryOperator *E) {
324 if (E->getType()->isVoidType())
325 return Visit(E->getSubExpr()); // the actual value should be unused
326 return EmitLoadOfLValue(E);
327 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000328 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000329 // This differs from gcc, though, most likely due to a bug in gcc.
330 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000331 return Visit(E->getSubExpr());
332 }
333 Value *VisitUnaryMinus (const UnaryOperator *E);
334 Value *VisitUnaryNot (const UnaryOperator *E);
335 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000336 Value *VisitUnaryReal (const UnaryOperator *E);
337 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000338 Value *VisitUnaryExtension(const UnaryOperator *E) {
339 return Visit(E->getSubExpr());
340 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000341
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000342 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000343 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
344 return Visit(DAE->getExpr());
345 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000346 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
347 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000348 }
349
John McCall4765fa02010-12-06 08:20:24 +0000350 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
351 return CGF.EmitExprWithCleanups(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000352 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000353 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
354 return CGF.EmitCXXNewExpr(E);
355 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000356 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
357 CGF.EmitCXXDeleteExpr(E);
358 return 0;
359 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000360 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +0000361 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000362 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000363
Francois Pichet6ad6f282010-12-07 00:08:36 +0000364 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000365 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000366 }
367
Douglas Gregora71d8192009-09-04 17:36:40 +0000368 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
369 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000370 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000371 // operator (), and the result of such a call has type void. The only
372 // effect is the evaluation of the postfix-expression before the dot or
373 // arrow.
374 CGF.EmitScalarExpr(E->getBase());
375 return 0;
376 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000377
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000378 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000379 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000380 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000381
382 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
383 CGF.EmitCXXThrowExpr(E);
384 return 0;
385 }
386
Sebastian Redl98294de2010-09-10 21:04:00 +0000387 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
388 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
389 }
390
Chris Lattner7f02f722007-08-24 05:35:26 +0000391 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000392 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000393 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000394 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
395 case LangOptions::SOB_Undefined:
396 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
397 case LangOptions::SOB_Defined:
398 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
399 case LangOptions::SOB_Trapping:
400 return EmitOverflowCheckedBinOp(Ops);
401 }
402 }
403
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000404 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000405 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000406 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
407 }
Chris Lattner80230302010-09-11 21:47:09 +0000408 bool isTrapvOverflowBehavior() {
409 return CGF.getContext().getLangOptions().getSignedOverflowBehavior()
410 == LangOptions::SOB_Trapping;
411 }
Mike Stump2add4732009-04-01 20:28:16 +0000412 /// Create a binary op that checks for overflow.
413 /// Currently only supports +, - and *.
414 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner80230302010-09-11 21:47:09 +0000415 // Emit the overflow BB when -ftrapv option is activated.
416 void EmitOverflowBB(llvm::BasicBlock *overflowBB) {
417 Builder.SetInsertPoint(overflowBB);
418 llvm::Function *Trap = CGF.CGM.getIntrinsic(llvm::Intrinsic::trap);
419 Builder.CreateCall(Trap);
420 Builder.CreateUnreachable();
421 }
422 // Check for undefined division and modulus behaviors.
423 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
424 llvm::Value *Zero,bool isDiv);
Chris Lattner7f02f722007-08-24 05:35:26 +0000425 Value *EmitDiv(const BinOpInfo &Ops);
426 Value *EmitRem(const BinOpInfo &Ops);
427 Value *EmitAdd(const BinOpInfo &Ops);
428 Value *EmitSub(const BinOpInfo &Ops);
429 Value *EmitShl(const BinOpInfo &Ops);
430 Value *EmitShr(const BinOpInfo &Ops);
431 Value *EmitAnd(const BinOpInfo &Ops) {
432 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
433 }
434 Value *EmitXor(const BinOpInfo &Ops) {
435 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
436 }
437 Value *EmitOr (const BinOpInfo &Ops) {
438 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
439 }
440
Chris Lattner1f1ded92007-08-24 21:00:35 +0000441 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000442 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
443 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000444 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000445
Chris Lattner3ccf7742007-08-26 21:41:21 +0000446 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000447 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
448
449 // Binary operators and binary compound assignment operators.
450#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000451 Value *VisitBin ## OP(const BinaryOperator *E) { \
452 return Emit ## OP(EmitBinOps(E)); \
453 } \
454 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
455 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000456 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000457 HANDLEBINOP(Mul)
458 HANDLEBINOP(Div)
459 HANDLEBINOP(Rem)
460 HANDLEBINOP(Add)
461 HANDLEBINOP(Sub)
462 HANDLEBINOP(Shl)
463 HANDLEBINOP(Shr)
464 HANDLEBINOP(And)
465 HANDLEBINOP(Xor)
466 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000467#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000468
Chris Lattner7f02f722007-08-24 05:35:26 +0000469 // Comparisons.
470 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
471 unsigned SICmpOpc, unsigned FCmpOpc);
472#define VISITCOMP(CODE, UI, SI, FP) \
473 Value *VisitBin##CODE(const BinaryOperator *E) { \
474 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
475 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000476 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
477 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
478 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
479 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
480 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
481 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000482#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000483
Chris Lattner7f02f722007-08-24 05:35:26 +0000484 Value *VisitBinAssign (const BinaryOperator *E);
485
486 Value *VisitBinLAnd (const BinaryOperator *E);
487 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000488 Value *VisitBinComma (const BinaryOperator *E);
489
Eli Friedman25b825d2009-11-18 09:41:26 +0000490 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
491 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
492
Chris Lattner7f02f722007-08-24 05:35:26 +0000493 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000494 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000495 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000496 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000497 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000498 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
499 return CGF.EmitObjCStringLiteral(E);
500 }
501};
502} // end anonymous namespace.
503
504//===----------------------------------------------------------------------===//
505// Utilities
506//===----------------------------------------------------------------------===//
507
Chris Lattner9abc84e2007-08-26 16:42:57 +0000508/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000509/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000510Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000511 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000512
John McCalldaa8e4e2010-11-15 09:13:47 +0000513 if (SrcType->isRealFloatingType())
514 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000515
John McCall0bab0cd2010-08-23 01:21:21 +0000516 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
517 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000518
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000519 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000520 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000521
John McCalldaa8e4e2010-11-15 09:13:47 +0000522 if (isa<llvm::IntegerType>(Src->getType()))
523 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000524
John McCalldaa8e4e2010-11-15 09:13:47 +0000525 assert(isa<llvm::PointerType>(Src->getType()));
526 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000527}
528
Chris Lattner3707b252007-08-26 06:48:56 +0000529/// EmitScalarConversion - Emit a conversion from the specified type to the
530/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000531Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
532 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000533 SrcType = CGF.getContext().getCanonicalType(SrcType);
534 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000535 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000536
Chris Lattnercf289082007-08-26 07:21:11 +0000537 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000538
Chris Lattner3707b252007-08-26 06:48:56 +0000539 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000540 if (DstType->isBooleanType())
541 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000542
Chris Lattner3707b252007-08-26 06:48:56 +0000543 const llvm::Type *DstTy = ConvertType(DstType);
544
545 // Ignore conversions like int -> uint.
546 if (Src->getType() == DstTy)
547 return Src;
548
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000549 // Handle pointer conversions next: pointers can only be converted to/from
550 // other pointers and integers. Check for pointer types in terms of LLVM, as
551 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000552 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000553 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000554 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000555 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000556
Chris Lattner3707b252007-08-26 06:48:56 +0000557 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000558 // First, convert to the correct width so that we control the kind of
559 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +0000560 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Eli Friedman25615422009-03-04 04:02:35 +0000561 bool InputSigned = SrcType->isSignedIntegerType();
562 llvm::Value* IntResult =
563 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
564 // Then, cast to pointer.
565 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000566 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000567
Daniel Dunbar270cc662008-08-25 09:51:32 +0000568 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000569 // Must be an ptr to int cast.
570 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000571 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000572 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000573
Nate Begeman213541a2008-04-18 23:10:10 +0000574 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000575 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000576 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000577 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000578 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
579
580 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000581 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +0000582 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000583 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
584
585 // Splat the element across to all elements
586 llvm::SmallVector<llvm::Constant*, 16> Args;
587 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Chris Lattnerfb018d12011-02-15 00:14:06 +0000588 for (unsigned i = 0; i != NumElements; ++i)
Chris Lattner77b89b82010-06-27 07:15:29 +0000589 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000590
Chris Lattnerfb018d12011-02-15 00:14:06 +0000591 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000592 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
593 return Yay;
594 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000595
Chris Lattner3b1ae002008-02-02 04:51:41 +0000596 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000597 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000598 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000599 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000600
Chris Lattner3707b252007-08-26 06:48:56 +0000601 // Finally, we have the arithmetic types: real int/float.
602 if (isa<llvm::IntegerType>(Src->getType())) {
603 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000604 if (isa<llvm::IntegerType>(DstTy))
605 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
606 else if (InputSigned)
607 return Builder.CreateSIToFP(Src, DstTy, "conv");
608 else
609 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000610 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000611
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000612 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
Chris Lattner3707b252007-08-26 06:48:56 +0000613 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000614 if (DstType->isSignedIntegerType())
615 return Builder.CreateFPToSI(Src, DstTy, "conv");
616 else
617 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000618 }
619
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000620 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000621 if (DstTy->getTypeID() < Src->getType()->getTypeID())
622 return Builder.CreateFPTrunc(Src, DstTy, "conv");
623 else
624 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000625}
626
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000627/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
628/// type to the specified destination type, where the destination type is an
629/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000630Value *ScalarExprEmitter::
631EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
632 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000633 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000634 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000635
Chris Lattnered70f0a2007-08-26 16:52:28 +0000636 // Handle conversions to bool first, they are special: comparisons against 0.
637 if (DstTy->isBooleanType()) {
638 // Complex != 0 -> (Real != 0) | (Imag != 0)
639 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
640 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
641 return Builder.CreateOr(Src.first, Src.second, "tobool");
642 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000643
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000644 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
645 // the imaginary part of the complex value is discarded and the value of the
646 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000647 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000648 return EmitScalarConversion(Src.first, SrcTy, DstTy);
649}
650
Anders Carlssona40a9f32010-05-22 17:45:10 +0000651Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
John McCall0bab0cd2010-08-23 01:21:21 +0000652 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>())
653 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
654
655 return llvm::Constant::getNullValue(ConvertType(Ty));
Anders Carlssona40a9f32010-05-22 17:45:10 +0000656}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000657
Chris Lattner7f02f722007-08-24 05:35:26 +0000658//===----------------------------------------------------------------------===//
659// Visitor Methods
660//===----------------------------------------------------------------------===//
661
662Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000663 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000664 if (E->getType()->isVoidType())
665 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000666 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000667}
668
Eli Friedmand38617c2008-05-14 19:38:39 +0000669Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000670 // Vector Mask Case
671 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000672 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000673 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
674 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
675 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000676
Nate Begeman37b6a572010-06-08 00:16:34 +0000677 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
678 unsigned LHSElts = LTy->getNumElements();
679
680 if (E->getNumSubExprs() == 3) {
681 Mask = CGF.EmitScalarExpr(E->getExpr(2));
682
683 // Shuffle LHS & RHS into one input vector.
684 llvm::SmallVector<llvm::Constant*, 32> concat;
685 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000686 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i));
687 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000688 }
689
Chris Lattnerfb018d12011-02-15 00:14:06 +0000690 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000691 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
692 LHSElts *= 2;
693 } else {
694 Mask = RHS;
695 }
696
697 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
698 llvm::Constant* EltMask;
699
700 // Treat vec3 like vec4.
701 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
702 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
703 (1 << llvm::Log2_32(LHSElts+2))-1);
704 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
705 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
706 (1 << llvm::Log2_32(LHSElts+1))-1);
707 else
708 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
709 (1 << llvm::Log2_32(LHSElts))-1);
710
711 // Mask off the high bits of each shuffle index.
712 llvm::SmallVector<llvm::Constant *, 32> MaskV;
713 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
714 MaskV.push_back(EltMask);
715
Chris Lattnerfb018d12011-02-15 00:14:06 +0000716 Value* MaskBits = llvm::ConstantVector::get(MaskV);
Nate Begeman37b6a572010-06-08 00:16:34 +0000717 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
718
719 // newv = undef
720 // mask = mask & maskbits
721 // for each elt
722 // n = extract mask i
723 // x = extract val n
724 // newv = insert newv, x, i
725 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
726 MTy->getNumElements());
727 Value* NewV = llvm::UndefValue::get(RTy);
728 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000729 Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000730 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000731 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000732
733 // Handle vec3 special since the index will be off by one for the RHS.
734 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
735 Value *cmpIndx, *newIndx;
Chris Lattner77b89b82010-06-27 07:15:29 +0000736 cmpIndx = Builder.CreateICmpUGT(Indx,
737 llvm::ConstantInt::get(CGF.Int32Ty, 3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000738 "cmp_shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000739 newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1),
Nate Begeman37b6a572010-06-08 00:16:34 +0000740 "shuf_idx_adj");
741 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
742 }
743 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
744 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
745 }
746 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000747 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000748
Eli Friedmand38617c2008-05-14 19:38:39 +0000749 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
750 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000751
752 // Handle vec3 special since the index will be off by one for the RHS.
753 llvm::SmallVector<llvm::Constant*, 32> indices;
754 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
755 llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
756 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
757 if (VTy->getNumElements() == 3) {
758 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
759 uint64_t cVal = CI->getZExtValue();
760 if (cVal > 3) {
761 C = llvm::ConstantInt::get(C->getType(), cVal-1);
762 }
763 }
764 }
765 indices.push_back(C);
766 }
767
Chris Lattnerfb018d12011-02-15 00:14:06 +0000768 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000769 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
770}
Eli Friedman28665272009-11-26 03:22:21 +0000771Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
772 Expr::EvalResult Result;
773 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
774 if (E->isArrow())
775 CGF.EmitScalarExpr(E->getBase());
776 else
777 EmitLValue(E->getBase());
778 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
779 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000780
781 // Emit debug info for aggregate now, if it was delayed to reduce
782 // debug info size.
783 CGDebugInfo *DI = CGF.getDebugInfo();
784 if (DI && CGF.CGM.getCodeGenOpts().LimitDebugInfo) {
785 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
786 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000787 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Devang Patel78ba3d42010-10-04 21:46:04 +0000788 DI->getOrCreateRecordType(PTy->getPointeeType(),
789 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000790 }
Eli Friedman28665272009-11-26 03:22:21 +0000791 return EmitLoadOfLValue(E);
792}
Eli Friedmand38617c2008-05-14 19:38:39 +0000793
Chris Lattner7f02f722007-08-24 05:35:26 +0000794Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000795 TestAndClearIgnoreResultAssign();
796
Chris Lattner7f02f722007-08-24 05:35:26 +0000797 // Emit subscript expressions in rvalue context's. For most cases, this just
798 // loads the lvalue formed by the subscript expr. However, we have to be
799 // careful, because the base of a vector subscript is occasionally an rvalue,
800 // so we can't get it as an lvalue.
801 if (!E->getBase()->getType()->isVectorType())
802 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000803
Chris Lattner7f02f722007-08-24 05:35:26 +0000804 // Handle the vector case. The base must be a vector, the index must be an
805 // integer value.
806 Value *Base = Visit(E->getBase());
807 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000808 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000809 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000810 return Builder.CreateExtractElement(Base, Idx, "vecext");
811}
812
Nate Begeman0533b302009-10-18 20:10:40 +0000813static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
814 unsigned Off, const llvm::Type *I32Ty) {
815 int MV = SVI->getMaskValue(Idx);
816 if (MV == -1)
817 return llvm::UndefValue::get(I32Ty);
818 return llvm::ConstantInt::get(I32Ty, Off+MV);
819}
820
821Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
822 bool Ignore = TestAndClearIgnoreResultAssign();
823 (void)Ignore;
824 assert (Ignore == false && "init list ignored");
825 unsigned NumInitElements = E->getNumInits();
826
827 if (E->hadArrayRangeDesignator())
828 CGF.ErrorUnsupported(E, "GNU array range designator extension");
829
830 const llvm::VectorType *VType =
831 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
832
833 // We have a scalar in braces. Just use the first element.
834 if (!VType)
835 return Visit(E->getInit(0));
836
837 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000838
839 // Loop over initializers collecting the Value for each, and remembering
840 // whether the source was swizzle (ExtVectorElementExpr). This will allow
841 // us to fold the shuffle for the swizzle into the shuffle for the vector
842 // initializer, since LLVM optimizers generally do not want to touch
843 // shuffles.
844 unsigned CurIdx = 0;
845 bool VIsUndefShuffle = false;
846 llvm::Value *V = llvm::UndefValue::get(VType);
847 for (unsigned i = 0; i != NumInitElements; ++i) {
848 Expr *IE = E->getInit(i);
849 Value *Init = Visit(IE);
850 llvm::SmallVector<llvm::Constant*, 16> Args;
851
852 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
853
854 // Handle scalar elements. If the scalar initializer is actually one
855 // element of a different vector of the same width, use shuffle instead of
856 // extract+insert.
857 if (!VVT) {
858 if (isa<ExtVectorElementExpr>(IE)) {
859 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
860
861 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
862 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
863 Value *LHS = 0, *RHS = 0;
864 if (CurIdx == 0) {
865 // insert into undef -> shuffle (src, undef)
866 Args.push_back(C);
867 for (unsigned j = 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000868 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000869
870 LHS = EI->getVectorOperand();
871 RHS = V;
872 VIsUndefShuffle = true;
873 } else if (VIsUndefShuffle) {
874 // insert into undefshuffle && size match -> shuffle (v, src)
875 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
876 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000877 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
878 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
Nate Begeman0533b302009-10-18 20:10:40 +0000879 ResElts + C->getZExtValue()));
880 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000881 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000882
883 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
884 RHS = EI->getVectorOperand();
885 VIsUndefShuffle = false;
886 }
887 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +0000888 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000889 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
890 ++CurIdx;
891 continue;
892 }
893 }
894 }
Chris Lattner77b89b82010-06-27 07:15:29 +0000895 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000896 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
897 VIsUndefShuffle = false;
898 ++CurIdx;
899 continue;
900 }
901
902 unsigned InitElts = VVT->getNumElements();
903
904 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
905 // input is the same width as the vector being constructed, generate an
906 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000907 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000908 if (isa<ExtVectorElementExpr>(IE)) {
909 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
910 Value *SVOp = SVI->getOperand(0);
911 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
912
913 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000914 for (unsigned j = 0; j != CurIdx; ++j) {
915 // If the current vector initializer is a shuffle with undef, merge
916 // this shuffle directly into it.
917 if (VIsUndefShuffle) {
918 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000919 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000920 } else {
Chris Lattner77b89b82010-06-27 07:15:29 +0000921 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000922 }
923 }
924 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000925 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000926 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000927 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000928
929 if (VIsUndefShuffle)
930 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
931
932 Init = SVOp;
933 }
934 }
935
936 // Extend init to result vector length, and then shuffle its contribution
937 // to the vector initializer into V.
938 if (Args.empty()) {
939 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000940 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000941 for (unsigned j = InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000942 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +0000943 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000944 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000945 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000946
947 Args.clear();
948 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000949 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000950 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000951 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000952 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000953 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000954 }
955
956 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
957 // merging subsequent shuffles into this one.
958 if (CurIdx == 0)
959 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +0000960 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +0000961 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
962 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
963 CurIdx += InitElts;
964 }
965
966 // FIXME: evaluate codegen vs. shuffling against constant null vector.
967 // Emit remaining default initializers.
968 const llvm::Type *EltTy = VType->getElementType();
969
970 // Emit remaining default initializers
971 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000972 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000973 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
974 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
975 }
976 return V;
977}
978
Anders Carlssona3697c92009-11-23 17:57:54 +0000979static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
980 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +0000981
John McCall2de56d12010-08-25 11:45:40 +0000982 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +0000983 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +0000984
985 if (isa<CXXThisExpr>(E)) {
986 // We always assume that 'this' is never null.
987 return false;
988 }
989
990 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000991 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +0000992 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +0000993 return false;
994 }
995
996 return true;
997}
998
Chris Lattner7f02f722007-08-24 05:35:26 +0000999// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1000// have to handle a more broad range of conversions than explicit casts, as they
1001// handle things like function to ptr-to-function decay etc.
Eli Friedmand8889622009-11-27 04:41:50 +00001002Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
1003 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001004 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001005 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001006
Mike Stump7f79f9b2009-05-29 15:46:01 +00001007 if (!DestTy->isVoidType())
1008 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001009
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001010 // Since almost all cast kinds apply to scalars, this switch doesn't have
1011 // a default case, so the compiler will warn on a missing case. The cases
1012 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001013 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001014 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
1015
John McCall2de56d12010-08-25 11:45:40 +00001016 case CK_LValueBitCast:
1017 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001018 Value *V = EmitLValue(E).getAddress();
1019 V = Builder.CreateBitCast(V,
1020 ConvertType(CGF.getContext().getPointerType(DestTy)));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00001021 return EmitLoadOfLValue(CGF.MakeAddrLValue(V, DestTy), DestTy);
Douglas Gregore39a3892010-07-13 23:17:26 +00001022 }
1023
John McCall2de56d12010-08-25 11:45:40 +00001024 case CK_AnyPointerToObjCPointerCast:
1025 case CK_AnyPointerToBlockPointerCast:
1026 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001027 Value *Src = Visit(const_cast<Expr*>(E));
1028 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1029 }
John McCall2de56d12010-08-25 11:45:40 +00001030 case CK_NoOp:
1031 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001032 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001033
John McCall2de56d12010-08-25 11:45:40 +00001034 case CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +00001035 const CXXRecordDecl *DerivedClassDecl =
1036 DestTy->getCXXRecordDeclForPointerType();
1037
Anders Carlssona04efdf2010-04-24 21:23:59 +00001038 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001039 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001040 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001041 }
John McCall2de56d12010-08-25 11:45:40 +00001042 case CK_UncheckedDerivedToBase:
1043 case CK_DerivedToBase: {
Anders Carlsson191dfe92009-09-12 04:57:16 +00001044 const RecordType *DerivedClassTy =
1045 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
1046 CXXRecordDecl *DerivedClassDecl =
1047 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
1048
Anders Carlsson34a2d382010-04-24 21:06:20 +00001049 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001050 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001051 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001052 }
John McCall2de56d12010-08-25 11:45:40 +00001053 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001054 Value *V = Visit(const_cast<Expr*>(E));
1055 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1056 return CGF.EmitDynamicCast(V, DCE);
1057 }
Eli Friedmand8889622009-11-27 04:41:50 +00001058
John McCall2de56d12010-08-25 11:45:40 +00001059 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001060 assert(E->getType()->isArrayType() &&
1061 "Array to pointer decay must have array source type!");
1062
1063 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1064
1065 // Note that VLA pointers are always decayed, so we don't need to do
1066 // anything here.
1067 if (!E->getType()->isVariableArrayType()) {
1068 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1069 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1070 ->getElementType()) &&
1071 "Expected pointer to array");
1072 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1073 }
1074
1075 return V;
1076 }
John McCall2de56d12010-08-25 11:45:40 +00001077 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001078 return EmitLValue(E).getAddress();
1079
John McCall404cd162010-11-13 01:35:44 +00001080 case CK_NullToPointer:
1081 if (MustVisitNullValue(E))
1082 (void) Visit(E);
1083
1084 return llvm::ConstantPointerNull::get(
1085 cast<llvm::PointerType>(ConvertType(DestTy)));
1086
John McCall2de56d12010-08-25 11:45:40 +00001087 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001088 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001089 (void) Visit(E);
1090
John McCall0bab0cd2010-08-23 01:21:21 +00001091 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1092 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1093 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001094
John McCall2de56d12010-08-25 11:45:40 +00001095 case CK_BaseToDerivedMemberPointer:
1096 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001097 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001098
1099 // Note that the AST doesn't distinguish between checked and
1100 // unchecked member pointer conversions, so we always have to
1101 // implement checked conversions here. This is inefficient when
1102 // actual control flow may be required in order to perform the
1103 // check, which it is for data member pointers (but not member
1104 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001105 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001106 }
John McCall0bab0cd2010-08-23 01:21:21 +00001107
John McCall2bb5d002010-11-13 09:02:35 +00001108 case CK_FloatingRealToComplex:
1109 case CK_FloatingComplexCast:
1110 case CK_IntegralRealToComplex:
1111 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001112 case CK_IntegralComplexToFloatingComplex:
1113 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001114 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001115 case CK_ToUnion:
1116 llvm_unreachable("scalar cast to non-scalar value");
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001117 break;
John McCallf6a16482010-12-04 03:47:34 +00001118
1119 case CK_GetObjCProperty: {
1120 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
Douglas Gregorda29e092011-01-22 02:44:21 +00001121 assert(E->isGLValue() && E->getObjectKind() == OK_ObjCProperty &&
John McCallf6a16482010-12-04 03:47:34 +00001122 "CK_GetObjCProperty for non-lvalue or non-ObjCProperty");
1123 RValue RV = CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType());
1124 return RV.getScalarVal();
1125 }
John McCall0ae287a2010-12-01 04:43:34 +00001126
1127 case CK_LValueToRValue:
1128 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001129 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001130 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001131
John McCall2de56d12010-08-25 11:45:40 +00001132 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001133 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001134
Anders Carlsson82debc72009-10-18 18:12:03 +00001135 // First, convert to the correct width so that we control the kind of
1136 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +00001137 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Anders Carlsson82debc72009-10-18 18:12:03 +00001138 bool InputSigned = E->getType()->isSignedIntegerType();
1139 llvm::Value* IntResult =
1140 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001141
Anders Carlsson82debc72009-10-18 18:12:03 +00001142 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001143 }
John McCall2de56d12010-08-25 11:45:40 +00001144 case CK_PointerToIntegral: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001145 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001146
1147 // Handle conversion to bool correctly.
1148 if (DestTy->isBooleanType())
Daniel Dunbardb505472010-09-03 02:07:00 +00001149 return EmitScalarConversion(Src, E->getType(), DestTy);
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001150
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001151 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1152 }
John McCall2de56d12010-08-25 11:45:40 +00001153 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001154 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001155 return 0;
1156 }
John McCall2de56d12010-08-25 11:45:40 +00001157 case CK_VectorSplat: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001158 const llvm::Type *DstTy = ConvertType(DestTy);
1159 Value *Elt = Visit(const_cast<Expr*>(E));
1160
1161 // Insert the element in element zero of an undef vector
1162 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +00001163 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001164 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1165
1166 // Splat the element across to all elements
1167 llvm::SmallVector<llvm::Constant*, 16> Args;
1168 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
John McCalldaa8e4e2010-11-15 09:13:47 +00001169 llvm::Constant *Zero = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001170 for (unsigned i = 0; i < NumElements; i++)
John McCalldaa8e4e2010-11-15 09:13:47 +00001171 Args.push_back(Zero);
Eli Friedmanad35a832009-11-16 21:33:53 +00001172
Chris Lattnerfb018d12011-02-15 00:14:06 +00001173 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Eli Friedmanad35a832009-11-16 21:33:53 +00001174 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1175 return Yay;
1176 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001177
John McCall2de56d12010-08-25 11:45:40 +00001178 case CK_IntegralCast:
1179 case CK_IntegralToFloating:
1180 case CK_FloatingToIntegral:
1181 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001182 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001183
John McCalldaa8e4e2010-11-15 09:13:47 +00001184 case CK_IntegralToBoolean:
1185 return EmitIntToBoolConversion(Visit(E));
1186 case CK_PointerToBoolean:
1187 return EmitPointerToBoolConversion(Visit(E));
1188 case CK_FloatingToBoolean:
1189 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001190 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001191 llvm::Value *MemPtr = Visit(E);
1192 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1193 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001194 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001195
1196 case CK_FloatingComplexToReal:
1197 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001198 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001199
1200 case CK_FloatingComplexToBoolean:
1201 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001202 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001203
1204 // TODO: kill this function off, inline appropriate case here
1205 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1206 }
1207
John McCall0bab0cd2010-08-23 01:21:21 +00001208 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001209
John McCall61ad0e62010-11-16 06:21:14 +00001210 llvm_unreachable("unknown scalar cast");
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001211 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +00001212}
1213
Chris Lattner33793202007-08-31 22:09:40 +00001214Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001215 CodeGenFunction::StmtExprEvaluation eval(CGF);
1216 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1217 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001218}
1219
Mike Stumpa99038c2009-02-28 09:07:16 +00001220Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +00001221 llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
1222 if (E->getType().isObjCGCWeak())
1223 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
Fariborz Jahanian469a20d2010-09-03 23:07:53 +00001224 return CGF.EmitLoadOfScalar(V, false, 0, E->getType());
Mike Stump4e7a1f72009-02-21 20:00:35 +00001225}
Chris Lattner33793202007-08-31 22:09:40 +00001226
Chris Lattner7f02f722007-08-24 05:35:26 +00001227//===----------------------------------------------------------------------===//
1228// Unary Operators
1229//===----------------------------------------------------------------------===//
1230
Chris Lattner8c11a652010-06-26 22:09:34 +00001231llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001232EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1233 llvm::Value *InVal,
1234 llvm::Value *NextVal, bool IsInc) {
1235 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1236 case LangOptions::SOB_Undefined:
1237 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1238 break;
1239 case LangOptions::SOB_Defined:
1240 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1241 break;
1242 case LangOptions::SOB_Trapping:
1243 BinOpInfo BinOp;
1244 BinOp.LHS = InVal;
1245 BinOp.RHS = NextVal;
1246 BinOp.Ty = E->getType();
1247 BinOp.Opcode = BO_Add;
1248 BinOp.E = E;
1249 return EmitOverflowCheckedBinOp(BinOp);
1250 break;
1251 }
1252 assert(false && "Unknown SignedOverflowBehaviorTy");
1253 return 0;
1254}
1255
John McCall5936e332011-02-15 09:22:45 +00001256llvm::Value *
1257ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1258 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001259
John McCall5936e332011-02-15 09:22:45 +00001260 QualType type = E->getSubExpr()->getType();
1261 llvm::Value *value = EmitLoadOfLValue(LV, type);
1262 llvm::Value *input = value;
Anton Yartsev683564a2011-02-07 02:17:30 +00001263
John McCall5936e332011-02-15 09:22:45 +00001264 int amount = (isInc ? 1 : -1);
1265
1266 // Special case of integer increment that we have to check first: bool++.
1267 // Due to promotion rules, we get:
1268 // bool++ -> bool = bool + 1
1269 // -> bool = (int)bool + 1
1270 // -> bool = ((int)bool + 1 != 0)
1271 // An interesting aspect of this is that increment is always true.
1272 // Decrement does not have this property.
1273 if (isInc && type->isBooleanType()) {
1274 value = Builder.getTrue();
1275
1276 // Most common case by far: integer increment.
1277 } else if (type->isIntegerType()) {
1278
1279 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1280
1281 if (type->isSignedIntegerType())
1282 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1283
1284 // Unsigned integer inc is always two's complement.
1285 else
1286 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1287
1288 // Next most common: pointer increment.
1289 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1290 QualType type = ptr->getPointeeType();
1291
1292 // VLA types don't have constant size.
1293 if (type->isVariableArrayType()) {
1294 llvm::Value *vlaSize =
1295 CGF.GetVLASize(CGF.getContext().getAsVariableArrayType(type));
1296 value = CGF.EmitCastToVoidPtr(value);
1297 if (!isInc) vlaSize = Builder.CreateNSWNeg(vlaSize, "vla.negsize");
1298 value = Builder.CreateInBoundsGEP(value, vlaSize, "vla.inc");
1299 value = Builder.CreateBitCast(value, input->getType());
1300
1301 // Arithmetic on function pointers (!) is just +-1.
1302 } else if (type->isFunctionType()) {
1303 llvm::Value *amt = llvm::ConstantInt::get(CGF.Int32Ty, amount);
1304
1305 value = CGF.EmitCastToVoidPtr(value);
1306 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
1307 value = Builder.CreateBitCast(value, input->getType());
1308
1309 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001310 } else {
John McCall5936e332011-02-15 09:22:45 +00001311 llvm::Value *amt = llvm::ConstantInt::get(CGF.Int32Ty, amount);
1312 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
1313 }
1314
1315 // Vector increment/decrement.
1316 } else if (type->isVectorType()) {
1317 if (type->hasIntegerRepresentation()) {
1318 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1319
1320 if (type->hasSignedIntegerRepresentation())
1321 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
1322 else
1323 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1324 } else {
1325 value = Builder.CreateFAdd(
1326 value,
1327 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001328 isInc ? "inc" : "dec");
1329 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001330
John McCall5936e332011-02-15 09:22:45 +00001331 // Floating point.
1332 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001333 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001334 llvm::Value *amt;
1335 if (value->getType()->isFloatTy())
1336 amt = llvm::ConstantFP::get(VMContext,
1337 llvm::APFloat(static_cast<float>(amount)));
1338 else if (value->getType()->isDoubleTy())
1339 amt = llvm::ConstantFP::get(VMContext,
1340 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001341 else {
John McCall5936e332011-02-15 09:22:45 +00001342 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001343 bool ignored;
1344 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1345 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001346 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001347 }
John McCall5936e332011-02-15 09:22:45 +00001348 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1349
1350 // Objective-C pointer types.
1351 } else {
1352 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1353 value = CGF.EmitCastToVoidPtr(value);
1354
1355 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1356 if (!isInc) size = -size;
1357 llvm::Value *sizeValue =
1358 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1359
1360 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
1361 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001362 }
1363
1364 // Store the updated result through the lvalue.
1365 if (LV.isBitField())
John McCall5936e332011-02-15 09:22:45 +00001366 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, type, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001367 else
John McCall5936e332011-02-15 09:22:45 +00001368 CGF.EmitStoreThroughLValue(RValue::get(value), LV, type);
Chris Lattner8c11a652010-06-26 22:09:34 +00001369
1370 // If this is a postinc, return the value read from memory, otherwise use the
1371 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001372 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001373}
1374
1375
1376
Chris Lattner7f02f722007-08-24 05:35:26 +00001377Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001378 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001379 // Emit unary minus with EmitSub so we handle overflow cases etc.
1380 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001381 BinOp.RHS = Visit(E->getSubExpr());
1382
1383 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1384 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1385 else
1386 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001387 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001388 BinOp.Opcode = BO_Sub;
Chris Lattner9a207232010-06-26 21:48:21 +00001389 BinOp.E = E;
1390 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001391}
1392
1393Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001394 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001395 Value *Op = Visit(E->getSubExpr());
1396 return Builder.CreateNot(Op, "neg");
1397}
1398
1399Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1400 // Compare operand to zero.
1401 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001402
Chris Lattner7f02f722007-08-24 05:35:26 +00001403 // Invert value.
1404 // TODO: Could dynamically modify easy computations here. For example, if
1405 // the operand is an icmp ne, turn into icmp eq.
1406 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001407
Anders Carlsson9f84d882009-05-19 18:44:53 +00001408 // ZExt result to the expr type.
1409 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001410}
1411
Eli Friedman0027d2b2010-08-05 09:58:49 +00001412Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1413 // Try folding the offsetof to a constant.
1414 Expr::EvalResult EvalResult;
1415 if (E->Evaluate(EvalResult, CGF.getContext()))
1416 return llvm::ConstantInt::get(VMContext, EvalResult.Val.getInt());
1417
1418 // Loop over the components of the offsetof to compute the value.
1419 unsigned n = E->getNumComponents();
1420 const llvm::Type* ResultType = ConvertType(E->getType());
1421 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1422 QualType CurrentType = E->getTypeSourceInfo()->getType();
1423 for (unsigned i = 0; i != n; ++i) {
1424 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001425 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001426 switch (ON.getKind()) {
1427 case OffsetOfExpr::OffsetOfNode::Array: {
1428 // Compute the index
1429 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1430 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
1431 bool IdxSigned = IdxExpr->getType()->isSignedIntegerType();
1432 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1433
1434 // Save the element type
1435 CurrentType =
1436 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1437
1438 // Compute the element size
1439 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1440 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1441
1442 // Multiply out to compute the result
1443 Offset = Builder.CreateMul(Idx, ElemSize);
1444 break;
1445 }
1446
1447 case OffsetOfExpr::OffsetOfNode::Field: {
1448 FieldDecl *MemberDecl = ON.getField();
1449 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1450 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1451
1452 // Compute the index of the field in its parent.
1453 unsigned i = 0;
1454 // FIXME: It would be nice if we didn't have to loop here!
1455 for (RecordDecl::field_iterator Field = RD->field_begin(),
1456 FieldEnd = RD->field_end();
1457 Field != FieldEnd; (void)++Field, ++i) {
1458 if (*Field == MemberDecl)
1459 break;
1460 }
1461 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1462
1463 // Compute the offset to the field
1464 int64_t OffsetInt = RL.getFieldOffset(i) /
1465 CGF.getContext().getCharWidth();
1466 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1467
1468 // Save the element type.
1469 CurrentType = MemberDecl->getType();
1470 break;
1471 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001472
Eli Friedman0027d2b2010-08-05 09:58:49 +00001473 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001474 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001475
Eli Friedman0027d2b2010-08-05 09:58:49 +00001476 case OffsetOfExpr::OffsetOfNode::Base: {
1477 if (ON.getBase()->isVirtual()) {
1478 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1479 continue;
1480 }
1481
1482 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1483 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1484
1485 // Save the element type.
1486 CurrentType = ON.getBase()->getType();
1487
1488 // Compute the offset to the base.
1489 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1490 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Anders Carlssona14f5972010-10-31 23:22:37 +00001491 int64_t OffsetInt = RL.getBaseClassOffsetInBits(BaseRD) /
Eli Friedman0027d2b2010-08-05 09:58:49 +00001492 CGF.getContext().getCharWidth();
1493 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1494 break;
1495 }
1496 }
1497 Result = Builder.CreateAdd(Result, Offset);
1498 }
1499 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001500}
1501
Sebastian Redl05189992008-11-11 17:56:53 +00001502/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1503/// argument of the sizeof expression as an integer.
1504Value *
1505ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001506 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001507 if (E->isSizeOf()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001508 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001509 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1510 if (E->isArgumentType()) {
1511 // sizeof(type) - make sure to emit the VLA size.
1512 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001513 } else {
1514 // C99 6.5.3.4p2: If the argument is an expression of type
1515 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001516 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001517 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001518
Anders Carlsson96f21472009-02-05 19:43:10 +00001519 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +00001520 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001521 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001522
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001523 // If this isn't sizeof(vla), the result must be constant; use the constant
1524 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001525 Expr::EvalResult Result;
1526 E->Evaluate(Result, CGF.getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001527 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001528}
1529
Chris Lattner46f93d02007-08-24 21:20:17 +00001530Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1531 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001532 if (Op->getType()->isAnyComplexType()) {
1533 // If it's an l-value, load through the appropriate subobject l-value.
1534 // Note that we have to ask E because Op might be an l-value that
1535 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001536 if (E->isGLValue())
John McCallb418d742010-11-16 10:08:07 +00001537 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1538 .getScalarVal();
1539
1540 // Otherwise, calculate and project.
1541 return CGF.EmitComplexExpr(Op, false, true).first;
1542 }
1543
Chris Lattner46f93d02007-08-24 21:20:17 +00001544 return Visit(Op);
1545}
John McCallb418d742010-11-16 10:08:07 +00001546
Chris Lattner46f93d02007-08-24 21:20:17 +00001547Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1548 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001549 if (Op->getType()->isAnyComplexType()) {
1550 // If it's an l-value, load through the appropriate subobject l-value.
1551 // Note that we have to ask E because Op might be an l-value that
1552 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001553 if (Op->isGLValue())
John McCallb418d742010-11-16 10:08:07 +00001554 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E), E->getType())
1555 .getScalarVal();
1556
1557 // Otherwise, calculate and project.
1558 return CGF.EmitComplexExpr(Op, true, false).second;
1559 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001560
Mike Stump7f79f9b2009-05-29 15:46:01 +00001561 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1562 // effects are evaluated, but not the actual value.
John McCallb418d742010-11-16 10:08:07 +00001563 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001564 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001565}
1566
Chris Lattner7f02f722007-08-24 05:35:26 +00001567//===----------------------------------------------------------------------===//
1568// Binary Operators
1569//===----------------------------------------------------------------------===//
1570
1571BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001572 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001573 BinOpInfo Result;
1574 Result.LHS = Visit(E->getLHS());
1575 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001576 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001577 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001578 Result.E = E;
1579 return Result;
1580}
1581
Douglas Gregor6a03e342010-04-23 04:16:32 +00001582LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1583 const CompoundAssignOperator *E,
1584 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001585 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001586 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001587 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001588
Eli Friedmanab3a8522009-03-28 01:22:36 +00001589 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001590 // This needs to go through the complex expression emitter, but it's a tad
1591 // complicated to do that... I'm leaving it out for now. (Note that we do
1592 // actually need the imaginary part of the RHS for multiplication and
1593 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001594 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001595 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001596 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001597 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001598
Mike Stumpcc0442f2009-05-22 19:07:20 +00001599 // Emit the RHS first. __block variables need to have the rhs evaluated
1600 // first, plus this should improve codegen a little.
1601 OpInfo.RHS = Visit(E->getRHS());
1602 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001603 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001604 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001605 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001606 LValue LHSLV = EmitCheckedLValue(E->getLHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001607 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001608 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1609 E->getComputationLHSType());
Douglas Gregor6a03e342010-04-23 04:16:32 +00001610
Chris Lattner1f1ded92007-08-24 21:00:35 +00001611 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001612 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001613
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001614 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001615 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001616
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001617 // Store the result value into the LHS lvalue. Bit-fields are handled
1618 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1619 // 'An assignment expression has the value of the left operand after the
1620 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001621 if (LHSLV.isBitField())
1622 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1623 &Result);
1624 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001625 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001626
Douglas Gregor6a03e342010-04-23 04:16:32 +00001627 return LHSLV;
1628}
1629
1630Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1631 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1632 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001633 Value *RHS;
1634 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1635
1636 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001637 if (Ignore)
1638 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001639
John McCallb418d742010-11-16 10:08:07 +00001640 // The result of an assignment in C is the assigned r-value.
1641 if (!CGF.getContext().getLangOptions().CPlusPlus)
1642 return RHS;
1643
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001644 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00001645 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001646 return RHS;
1647
1648 // If the lvalue is non-volatile, return the computed value of the assignment.
1649 if (!LHS.isVolatileQualified())
1650 return RHS;
1651
1652 // Otherwise, reload the value.
1653 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001654}
1655
Chris Lattner80230302010-09-11 21:47:09 +00001656void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
1657 const BinOpInfo &Ops,
1658 llvm::Value *Zero, bool isDiv) {
1659 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1660 llvm::BasicBlock *contBB =
1661 CGF.createBasicBlock(isDiv ? "div.cont" : "rem.cont", CGF.CurFn);
1662
1663 const llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1664
1665 if (Ops.Ty->hasSignedIntegerRepresentation()) {
1666 llvm::Value *IntMin =
1667 llvm::ConstantInt::get(VMContext,
1668 llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
1669 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1670
1671 llvm::Value *Cond1 = Builder.CreateICmpEQ(Ops.RHS, Zero);
1672 llvm::Value *LHSCmp = Builder.CreateICmpEQ(Ops.LHS, IntMin);
1673 llvm::Value *RHSCmp = Builder.CreateICmpEQ(Ops.RHS, NegOne);
1674 llvm::Value *Cond2 = Builder.CreateAnd(LHSCmp, RHSCmp, "and");
1675 Builder.CreateCondBr(Builder.CreateOr(Cond1, Cond2, "or"),
1676 overflowBB, contBB);
1677 } else {
1678 CGF.Builder.CreateCondBr(Builder.CreateICmpEQ(Ops.RHS, Zero),
1679 overflowBB, contBB);
1680 }
1681 EmitOverflowBB(overflowBB);
1682 Builder.SetInsertPoint(contBB);
1683}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001684
Chris Lattner7f02f722007-08-24 05:35:26 +00001685Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Chris Lattner80230302010-09-11 21:47:09 +00001686 if (isTrapvOverflowBehavior()) {
1687 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1688
1689 if (Ops.Ty->isIntegerType())
1690 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
1691 else if (Ops.Ty->isRealFloatingType()) {
1692 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow",
1693 CGF.CurFn);
1694 llvm::BasicBlock *DivCont = CGF.createBasicBlock("div.cont", CGF.CurFn);
1695 CGF.Builder.CreateCondBr(Builder.CreateFCmpOEQ(Ops.RHS, Zero),
1696 overflowBB, DivCont);
1697 EmitOverflowBB(overflowBB);
1698 Builder.SetInsertPoint(DivCont);
1699 }
1700 }
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001701 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner7f02f722007-08-24 05:35:26 +00001702 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Douglas Gregorf6094622010-07-23 15:58:24 +00001703 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001704 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1705 else
1706 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1707}
1708
1709Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1710 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner80230302010-09-11 21:47:09 +00001711 if (isTrapvOverflowBehavior()) {
1712 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1713
1714 if (Ops.Ty->isIntegerType())
1715 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1716 }
1717
Chris Lattner1f1ded92007-08-24 21:00:35 +00001718 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001719 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1720 else
1721 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1722}
1723
Mike Stump2add4732009-04-01 20:28:16 +00001724Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1725 unsigned IID;
1726 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001727
Chris Lattner9a207232010-06-26 21:48:21 +00001728 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00001729 case BO_Add:
1730 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001731 OpID = 1;
1732 IID = llvm::Intrinsic::sadd_with_overflow;
1733 break;
John McCall2de56d12010-08-25 11:45:40 +00001734 case BO_Sub:
1735 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001736 OpID = 2;
1737 IID = llvm::Intrinsic::ssub_with_overflow;
1738 break;
John McCall2de56d12010-08-25 11:45:40 +00001739 case BO_Mul:
1740 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00001741 OpID = 3;
1742 IID = llvm::Intrinsic::smul_with_overflow;
1743 break;
1744 default:
1745 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001746 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001747 }
Mike Stump035cf892009-04-02 18:15:54 +00001748 OpID <<= 1;
1749 OpID |= 1;
1750
Mike Stump2add4732009-04-01 20:28:16 +00001751 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1752
1753 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1754
1755 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1756 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1757 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1758
1759 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00001760 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Chris Lattner93a00352010-08-07 00:20:46 +00001761 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
1762 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00001763
1764 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1765
Chris Lattner93a00352010-08-07 00:20:46 +00001766 // Handle overflow with llvm.trap.
David Chisnall7f18e672010-09-17 18:29:54 +00001767 const std::string *handlerName =
1768 &CGF.getContext().getLangOptions().OverflowHandler;
1769 if (handlerName->empty()) {
1770 EmitOverflowBB(overflowBB);
1771 Builder.SetInsertPoint(continueBB);
1772 return result;
1773 }
1774
1775 // If an overflow handler is set, then we want to call it and then use its
1776 // result, if it returns.
1777 Builder.SetInsertPoint(overflowBB);
1778
1779 // Get the overflow handler.
1780 const llvm::Type *Int8Ty = llvm::Type::getInt8Ty(VMContext);
1781 std::vector<const llvm::Type*> argTypes;
1782 argTypes.push_back(CGF.Int64Ty); argTypes.push_back(CGF.Int64Ty);
1783 argTypes.push_back(Int8Ty); argTypes.push_back(Int8Ty);
1784 llvm::FunctionType *handlerTy =
1785 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
1786 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
1787
1788 // Sign extend the args to 64-bit, so that we can use the same handler for
1789 // all types of overflow.
1790 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
1791 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
1792
1793 // Call the handler with the two arguments, the operation, and the size of
1794 // the result.
1795 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
1796 Builder.getInt8(OpID),
1797 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
1798
1799 // Truncate the result back to the desired size.
1800 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1801 Builder.CreateBr(continueBB);
1802
Mike Stump2add4732009-04-01 20:28:16 +00001803 Builder.SetInsertPoint(continueBB);
David Chisnall7f18e672010-09-17 18:29:54 +00001804 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1805 phi->reserveOperandSpace(2);
1806 phi->addIncoming(result, initialBB);
1807 phi->addIncoming(handlerResult, overflowBB);
1808
1809 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00001810}
Chris Lattner7f02f722007-08-24 05:35:26 +00001811
1812Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001813 if (!Ops.Ty->isAnyPointerType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001814 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001815 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1816 case LangOptions::SOB_Undefined:
1817 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1818 case LangOptions::SOB_Defined:
1819 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1820 case LangOptions::SOB_Trapping:
1821 return EmitOverflowCheckedBinOp(Ops);
1822 }
1823 }
1824
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001825 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001826 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanbf933a02009-08-12 01:16:29 +00001827
Chris Lattner7f02f722007-08-24 05:35:26 +00001828 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001829 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001830
Chris Lattner7f215c12010-06-26 21:52:32 +00001831 // Must have binary (not unary) expr here. Unary pointer decrement doesn't
Chris Lattner9a207232010-06-26 21:48:21 +00001832 // use this path.
1833 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1834
Steve Naroff14108da2009-07-10 23:34:53 +00001835 if (Ops.Ty->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001836 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001837 // The amount of the addition needs to account for the VLA size
Chris Lattner9a207232010-06-26 21:48:21 +00001838 CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001839 }
Chris Lattner9a207232010-06-26 21:48:21 +00001840
Chris Lattner8f925282008-01-03 06:36:51 +00001841 Value *Ptr, *Idx;
1842 Expr *IdxExp;
Chris Lattner9a207232010-06-26 21:48:21 +00001843 const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001844 const ObjCObjectPointerType *OPT =
Chris Lattner9a207232010-06-26 21:48:21 +00001845 BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001846 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001847 Ptr = Ops.LHS;
1848 Idx = Ops.RHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001849 IdxExp = BinOp->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001850 } else { // int + pointer
Chris Lattner9a207232010-06-26 21:48:21 +00001851 PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1852 OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001853 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001854 Ptr = Ops.RHS;
1855 Idx = Ops.LHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001856 IdxExp = BinOp->getLHS();
Chris Lattner8f925282008-01-03 06:36:51 +00001857 }
1858
1859 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
John McCall5936e332011-02-15 09:22:45 +00001860 if (Width < CGF.PointerWidthInBits) {
Chris Lattner8f925282008-01-03 06:36:51 +00001861 // Zero or sign extend the pointer value based on whether the index is
1862 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001863 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner96196622008-07-26 22:37:01 +00001864 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001865 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1866 else
1867 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1868 }
Steve Naroff14108da2009-07-10 23:34:53 +00001869 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001870 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001871 if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001872 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001873 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001874 CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001875 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001876 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001877 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1878 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1879 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001880 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001881
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001882 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1883 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1884 // future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001885 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001886 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001887 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001888 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001889 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001890 }
1891
Dan Gohman664f8932009-08-12 00:33:55 +00001892 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001893}
1894
1895Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001896 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001897 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001898 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1899 case LangOptions::SOB_Undefined:
1900 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1901 case LangOptions::SOB_Defined:
1902 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1903 case LangOptions::SOB_Trapping:
1904 return EmitOverflowCheckedBinOp(Ops);
1905 }
1906 }
1907
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001908 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001909 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00001910
Chris Lattner7f02f722007-08-24 05:35:26 +00001911 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001912 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001913
Chris Lattner9a207232010-06-26 21:48:21 +00001914 // Must have binary (not unary) expr here. Unary pointer increment doesn't
1915 // use this path.
1916 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1917
1918 if (BinOp->getLHS()->getType()->isPointerType() &&
1919 BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001920 // The amount of the addition needs to account for the VLA size for
1921 // ptr-int
1922 // The amount of the division needs to account for the VLA size for
1923 // ptr-ptr.
Chris Lattner9a207232010-06-26 21:48:21 +00001924 CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001925 }
1926
Chris Lattner9a207232010-06-26 21:48:21 +00001927 const QualType LHSType = BinOp->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001928 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001929 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1930 // pointer - int
1931 Value *Idx = Ops.RHS;
1932 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
John McCall5936e332011-02-15 09:22:45 +00001933 if (Width < CGF.PointerWidthInBits) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001934 // Zero or sign extend the pointer value based on whether the index is
1935 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001936 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner9a207232010-06-26 21:48:21 +00001937 if (BinOp->getRHS()->getType()->isSignedIntegerType())
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001938 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1939 else
1940 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1941 }
1942 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001943
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001944 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001945 if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001946 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001947 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001948 CGF.getContext().
1949 getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001950 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001951 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001952 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1953 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1954 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001955 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001956
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001957 // Explicitly handle GNU void* and function pointer arithmetic
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001958 // extensions. The GNU void* casts amount to no-ops since our void* type is
1959 // i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001960 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001961 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001962 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1963 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1964 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001965 }
1966
Dan Gohman664f8932009-08-12 00:33:55 +00001967 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001968 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001969 // pointer - pointer
1970 Value *LHS = Ops.LHS;
1971 Value *RHS = Ops.RHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001972
Ken Dyck199c3d62010-01-11 17:06:35 +00001973 CharUnits ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001974
Chris Lattnere5ed1512009-02-11 07:21:43 +00001975 // Handle GCC extension for pointer arithmetic on void* and function pointer
1976 // types.
1977 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Ken Dyck199c3d62010-01-11 17:06:35 +00001978 ElementSize = CharUnits::One();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001979 } else {
Ken Dyck199c3d62010-01-11 17:06:35 +00001980 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001981 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001982
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001983 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1984 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1985 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1986 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001987
Chris Lattnere5ed1512009-02-11 07:21:43 +00001988 // Optimize out the shift for element size of 1.
Ken Dyck199c3d62010-01-11 17:06:35 +00001989 if (ElementSize.isOne())
Chris Lattnere5ed1512009-02-11 07:21:43 +00001990 return BytesBetween;
Dan Gohmandf110942009-08-11 22:40:09 +00001991
1992 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001993 // pointer difference in C is only defined in the case where both operands
1994 // are pointing to elements of an array.
Ken Dyck199c3d62010-01-11 17:06:35 +00001995 Value *BytesPerElt =
1996 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
Dan Gohmandf110942009-08-11 22:40:09 +00001997 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00001998 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001999}
2000
2001Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2002 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2003 // RHS to the same size as the LHS.
2004 Value *RHS = Ops.RHS;
2005 if (Ops.LHS->getType() != RHS->getType())
2006 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002007
Mike Stumpbe07f602009-12-14 21:58:14 +00002008 if (CGF.CatchUndefined
2009 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2010 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2011 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2012 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2013 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002014 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002015 CGF.EmitBlock(Cont);
2016 }
2017
Chris Lattner7f02f722007-08-24 05:35:26 +00002018 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2019}
2020
2021Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2022 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2023 // RHS to the same size as the LHS.
2024 Value *RHS = Ops.RHS;
2025 if (Ops.LHS->getType() != RHS->getType())
2026 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002027
Mike Stumpbe07f602009-12-14 21:58:14 +00002028 if (CGF.CatchUndefined
2029 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
2030 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
2031 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2032 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
2033 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00002034 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00002035 CGF.EmitBlock(Cont);
2036 }
2037
Douglas Gregorf6094622010-07-23 15:58:24 +00002038 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002039 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2040 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2041}
2042
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002043enum IntrinsicType { VCMPEQ, VCMPGT };
2044// return corresponding comparison intrinsic for given vector type
2045static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2046 BuiltinType::Kind ElemKind) {
2047 switch (ElemKind) {
2048 default: assert(0 && "unexpected element type");
2049 case BuiltinType::Char_U:
2050 case BuiltinType::UChar:
2051 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2052 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
2053 break;
2054 case BuiltinType::Char_S:
2055 case BuiltinType::SChar:
2056 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2057 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
2058 break;
2059 case BuiltinType::UShort:
2060 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2061 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
2062 break;
2063 case BuiltinType::Short:
2064 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2065 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
2066 break;
2067 case BuiltinType::UInt:
2068 case BuiltinType::ULong:
2069 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2070 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
2071 break;
2072 case BuiltinType::Int:
2073 case BuiltinType::Long:
2074 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2075 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
2076 break;
2077 case BuiltinType::Float:
2078 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2079 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
2080 break;
2081 }
2082 return llvm::Intrinsic::not_intrinsic;
2083}
2084
Chris Lattner7f02f722007-08-24 05:35:26 +00002085Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2086 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002087 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002088 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002089 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002090 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002091 assert(E->getOpcode() == BO_EQ ||
2092 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002093 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2094 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002095 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002096 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002097 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002098 Value *LHS = Visit(E->getLHS());
2099 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002100
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002101 // If AltiVec, the comparison results in a numeric type, so we use
2102 // intrinsics comparing vectors and giving 0 or 1 as a result
2103 if (LHSTy->isVectorType() && CGF.getContext().getLangOptions().AltiVec) {
2104 // constants for mapping CR6 register bits to predicate result
2105 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2106
2107 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2108
2109 // in several cases vector arguments order will be reversed
2110 Value *FirstVecArg = LHS,
2111 *SecondVecArg = RHS;
2112
2113 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002114 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002115 BuiltinType::Kind ElementKind = BTy->getKind();
2116
2117 switch(E->getOpcode()) {
2118 default: assert(0 && "is not a comparison operation");
2119 case BO_EQ:
2120 CR6 = CR6_LT;
2121 ID = GetIntrinsic(VCMPEQ, ElementKind);
2122 break;
2123 case BO_NE:
2124 CR6 = CR6_EQ;
2125 ID = GetIntrinsic(VCMPEQ, ElementKind);
2126 break;
2127 case BO_LT:
2128 CR6 = CR6_LT;
2129 ID = GetIntrinsic(VCMPGT, ElementKind);
2130 std::swap(FirstVecArg, SecondVecArg);
2131 break;
2132 case BO_GT:
2133 CR6 = CR6_LT;
2134 ID = GetIntrinsic(VCMPGT, ElementKind);
2135 break;
2136 case BO_LE:
2137 if (ElementKind == BuiltinType::Float) {
2138 CR6 = CR6_LT;
2139 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2140 std::swap(FirstVecArg, SecondVecArg);
2141 }
2142 else {
2143 CR6 = CR6_EQ;
2144 ID = GetIntrinsic(VCMPGT, ElementKind);
2145 }
2146 break;
2147 case BO_GE:
2148 if (ElementKind == BuiltinType::Float) {
2149 CR6 = CR6_LT;
2150 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2151 }
2152 else {
2153 CR6 = CR6_EQ;
2154 ID = GetIntrinsic(VCMPGT, ElementKind);
2155 std::swap(FirstVecArg, SecondVecArg);
2156 }
2157 break;
2158 }
2159
2160 Value *CR6Param = llvm::ConstantInt::get(CGF.Int32Ty, CR6);
2161 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2162 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2163 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2164 }
2165
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002166 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002167 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002168 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002169 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002170 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002171 LHS, RHS, "cmp");
2172 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002173 // Unsigned integers and pointers.
2174 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002175 LHS, RHS, "cmp");
2176 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002177
2178 // If this is a vector comparison, sign extend the result to the appropriate
2179 // vector integer type and return it (don't convert to bool).
2180 if (LHSTy->isVectorType())
2181 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002182
Chris Lattner7f02f722007-08-24 05:35:26 +00002183 } else {
2184 // Complex Comparison: can only be an equality comparison.
2185 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2186 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002187
John McCall183700f2009-09-21 23:43:11 +00002188 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002189
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002190 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002191 if (CETy->isRealFloatingType()) {
2192 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2193 LHS.first, RHS.first, "cmp.r");
2194 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2195 LHS.second, RHS.second, "cmp.i");
2196 } else {
2197 // Complex comparisons can only be equality comparisons. As such, signed
2198 // and unsigned opcodes are the same.
2199 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2200 LHS.first, RHS.first, "cmp.r");
2201 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2202 LHS.second, RHS.second, "cmp.i");
2203 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002204
John McCall2de56d12010-08-25 11:45:40 +00002205 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002206 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2207 } else {
John McCall2de56d12010-08-25 11:45:40 +00002208 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002209 "Complex comparison other than == or != ?");
2210 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2211 }
2212 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002213
2214 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002215}
2216
2217Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002218 bool Ignore = TestAndClearIgnoreResultAssign();
2219
2220 // __block variables need to have the rhs evaluated first, plus this should
2221 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00002222 Value *RHS = Visit(E->getRHS());
Mike Stumpb14e62d2009-12-16 02:57:00 +00002223 LValue LHS = EmitCheckedLValue(E->getLHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002224
Daniel Dunbared3849b2008-11-19 09:36:46 +00002225 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00002226 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2227 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00002228 // the assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002229 if (LHS.isBitField())
2230 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
2231 &RHS);
2232 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00002233 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002234
2235 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002236 if (Ignore)
2237 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002238
John McCallb418d742010-11-16 10:08:07 +00002239 // The result of an assignment in C is the assigned r-value.
2240 if (!CGF.getContext().getLangOptions().CPlusPlus)
2241 return RHS;
2242
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002243 // Objective-C property assignment never reloads the value following a store.
John McCall119a1c62010-12-04 02:32:38 +00002244 if (LHS.isPropertyRef())
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002245 return RHS;
2246
2247 // If the lvalue is non-volatile, return the computed value of the assignment.
2248 if (!LHS.isVolatileQualified())
2249 return RHS;
2250
2251 // Otherwise, reload the value.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002252 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002253}
2254
2255Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00002256 const llvm::Type *ResTy = ConvertType(E->getType());
2257
Chris Lattner20eb09d2008-11-12 08:26:50 +00002258 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2259 // If we have 1 && X, just emit X without inserting the control flow.
2260 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
2261 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002262 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002263 // ZExt result to int or bool.
2264 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002265 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002266
Chris Lattner7804bcb2009-10-17 04:24:20 +00002267 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002268 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002269 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002270 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002271
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002272 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2273 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002274
John McCall150b4622011-01-26 04:00:11 +00002275 CodeGenFunction::ConditionalEvaluation eval(CGF);
2276
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002277 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2278 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2279
2280 // Any edges into the ContBlock are now from an (indeterminate number of)
2281 // edges from this first condition. All of these values will be false. Start
2282 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00002283 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
2284 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002285 PN->reserveOperandSpace(2); // Normal case, two inputs.
2286 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2287 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002288 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002289
John McCall150b4622011-01-26 04:00:11 +00002290 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002291 CGF.EmitBlock(RHSBlock);
2292 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002293 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002294
Chris Lattner7f02f722007-08-24 05:35:26 +00002295 // Reaquire the RHS block, as there may be subblocks inserted.
2296 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002297
2298 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2299 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00002300 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002301 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002302
Chris Lattner7f02f722007-08-24 05:35:26 +00002303 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002304 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002305}
2306
2307Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00002308 const llvm::Type *ResTy = ConvertType(E->getType());
2309
Chris Lattner20eb09d2008-11-12 08:26:50 +00002310 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2311 // If we have 0 || X, just emit X without inserting the control flow.
2312 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
2313 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002314 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002315 // ZExt result to int or bool.
2316 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002317 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002318
Chris Lattner7804bcb2009-10-17 04:24:20 +00002319 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002320 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002321 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002322 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002323
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002324 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2325 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002326
John McCall150b4622011-01-26 04:00:11 +00002327 CodeGenFunction::ConditionalEvaluation eval(CGF);
2328
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002329 // Branch on the LHS first. If it is true, go to the success (cont) block.
2330 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2331
2332 // Any edges into the ContBlock are now from an (indeterminate number of)
2333 // edges from this first condition. All of these values will be true. Start
2334 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00002335 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
2336 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002337 PN->reserveOperandSpace(2); // Normal case, two inputs.
2338 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2339 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002340 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002341
John McCall150b4622011-01-26 04:00:11 +00002342 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002343
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002344 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002345 CGF.EmitBlock(RHSBlock);
2346 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002347
John McCall150b4622011-01-26 04:00:11 +00002348 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002349
Chris Lattner7f02f722007-08-24 05:35:26 +00002350 // Reaquire the RHS block, as there may be subblocks inserted.
2351 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002352
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002353 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2354 // into the phi node for the edge with the value of RHSCond.
2355 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002356 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002357
Chris Lattner7f02f722007-08-24 05:35:26 +00002358 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002359 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002360}
2361
2362Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002363 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002364 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002365 return Visit(E->getRHS());
2366}
2367
2368//===----------------------------------------------------------------------===//
2369// Other Operators
2370//===----------------------------------------------------------------------===//
2371
Chris Lattner9802a512008-11-12 08:55:54 +00002372/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2373/// expression is cheap enough and side-effect-free enough to evaluate
2374/// unconditionally instead of conditionally. This is used to convert control
2375/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002376static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2377 CodeGenFunction &CGF) {
Chris Lattner9802a512008-11-12 08:55:54 +00002378 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002379 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002380
Chris Lattner9802a512008-11-12 08:55:54 +00002381 // TODO: Allow anything we can constant fold to an integer or fp constant.
2382 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
2383 isa<FloatingLiteral>(E))
2384 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002385
Chris Lattner9802a512008-11-12 08:55:54 +00002386 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2387 // X and Y are local variables.
2388 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2389 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002390 if (VD->hasLocalStorage() && !(CGF.getContext()
2391 .getCanonicalType(VD->getType())
2392 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002393 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002394
Chris Lattner9802a512008-11-12 08:55:54 +00002395 return false;
2396}
2397
2398
Chris Lattner7f02f722007-08-24 05:35:26 +00002399Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002400VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002401 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002402
2403 // Bind the common expression if necessary.
2404 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
2405
2406 Expr *condExpr = E->getCond();
2407 Expr *lhsExpr = E->getTrueExpr();
2408 Expr *rhsExpr = E->getFalseExpr();
2409
Chris Lattner31a09842008-11-12 08:04:58 +00002410 // If the condition constant folds and can be elided, try to avoid emitting
2411 // the condition and the dead arm.
John McCall56ca35d2011-02-17 10:25:35 +00002412 if (int Cond = CGF.ConstantFoldsToSimpleInteger(condExpr)){
2413 Expr *live = lhsExpr, *dead = rhsExpr;
2414 if (Cond == -1) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002415
Chris Lattner31a09842008-11-12 08:04:58 +00002416 // If the dead side doesn't have labels we need, and if the Live side isn't
2417 // the gnu missing ?: extension (which we could handle, but don't bother
2418 // to), just emit the Live part.
John McCall56ca35d2011-02-17 10:25:35 +00002419 if (!CGF.ContainsLabel(dead))
2420 return Visit(live);
Chris Lattnerc657e922008-11-11 18:56:45 +00002421 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002422
Nate Begeman6155d732010-09-20 22:41:17 +00002423 // OpenCL: If the condition is a vector, we can treat this condition like
2424 // the select function.
2425 if (CGF.getContext().getLangOptions().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002426 && condExpr->getType()->isVectorType()) {
2427 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2428 llvm::Value *LHS = Visit(lhsExpr);
2429 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002430
John McCall56ca35d2011-02-17 10:25:35 +00002431 const llvm::Type *condType = ConvertType(condExpr->getType());
Nate Begeman6155d732010-09-20 22:41:17 +00002432 const llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
2433
2434 unsigned numElem = vecTy->getNumElements();
2435 const llvm::Type *elemType = vecTy->getElementType();
2436
2437 std::vector<llvm::Constant*> Zvals;
2438 for (unsigned i = 0; i < numElem; ++i)
2439 Zvals.push_back(llvm::ConstantInt::get(elemType,0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002440
Nate Begeman6155d732010-09-20 22:41:17 +00002441 llvm::Value *zeroVec = llvm::ConstantVector::get(Zvals);
2442 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2443 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2444 llvm::VectorType::get(elemType,
2445 numElem),
2446 "sext");
2447 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2448
2449 // Cast float to int to perform ANDs if necessary.
2450 llvm::Value *RHSTmp = RHS;
2451 llvm::Value *LHSTmp = LHS;
2452 bool wasCast = false;
2453 const llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
2454 if (rhsVTy->getElementType()->isFloatTy()) {
2455 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2456 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2457 wasCast = true;
2458 }
2459
2460 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2461 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2462 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2463 if (wasCast)
2464 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2465
2466 return tmp5;
2467 }
2468
Chris Lattner9802a512008-11-12 08:55:54 +00002469 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2470 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002471 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002472 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2473 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2474 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2475 llvm::Value *LHS = Visit(lhsExpr);
2476 llvm::Value *RHS = Visit(rhsExpr);
Chris Lattner9802a512008-11-12 08:55:54 +00002477 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2478 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002479
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002480 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2481 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002482 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002483
2484 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002485 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002486
Chris Lattner7f02f722007-08-24 05:35:26 +00002487 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002488 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002489 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002490 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002491
Chris Lattner7f02f722007-08-24 05:35:26 +00002492 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002493 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002494
Chris Lattner7f02f722007-08-24 05:35:26 +00002495 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002496 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002497 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002498 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002499
John McCall150b4622011-01-26 04:00:11 +00002500 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002501 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002502
Eli Friedman48daf592009-12-07 20:25:53 +00002503 // If the LHS or RHS is a throw expression, it will be legitimately null.
2504 if (!LHS)
2505 return RHS;
2506 if (!RHS)
2507 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002508
Chris Lattner7f02f722007-08-24 05:35:26 +00002509 // Create a PHI node for the real part.
2510 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
2511 PN->reserveOperandSpace(2);
2512 PN->addIncoming(LHS, LHSBlock);
2513 PN->addIncoming(RHS, RHSBlock);
2514 return PN;
2515}
2516
2517Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002518 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002519}
2520
Chris Lattner2202bce2007-11-30 17:56:23 +00002521Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002522 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002523 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2524
2525 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002526 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002527 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2528
Mike Stump7f79f9b2009-05-29 15:46:01 +00002529 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002530 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002531}
2532
John McCall6b5a61b2011-02-07 10:33:21 +00002533Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2534 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002535}
2536
Chris Lattner7f02f722007-08-24 05:35:26 +00002537//===----------------------------------------------------------------------===//
2538// Entry Point into this File
2539//===----------------------------------------------------------------------===//
2540
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002541/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2542/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002543Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002544 assert(E && !hasAggregateLLVMType(E->getType()) &&
2545 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002546
Mike Stump7f79f9b2009-05-29 15:46:01 +00002547 return ScalarExprEmitter(*this, IgnoreResultAssign)
2548 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00002549}
Chris Lattner3707b252007-08-26 06:48:56 +00002550
2551/// EmitScalarConversion - Emit a conversion from the specified type to the
2552/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002553Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2554 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002555 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2556 "Invalid scalar expression to emit");
2557 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2558}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002559
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002560/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2561/// type to the specified destination type, where the destination type is an
2562/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002563Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2564 QualType SrcTy,
2565 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002566 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002567 "Invalid complex -> scalar conversion");
2568 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2569 DstTy);
2570}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002571
Chris Lattner8c11a652010-06-26 22:09:34 +00002572
2573llvm::Value *CodeGenFunction::
2574EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2575 bool isInc, bool isPre) {
2576 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2577}
2578
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002579LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2580 llvm::Value *V;
2581 // object->isa or (*object).isa
2582 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002583 // build Class* type
2584 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002585
2586 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00002587 if (BaseExpr->isRValue()) {
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002588 V = CreateTempAlloca(ClassPtrTy, "resval");
2589 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2590 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002591 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
2592 MakeAddrLValue(V, E->getType()), E->getType());
2593 } else {
2594 if (E->isArrow())
2595 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2596 else
2597 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002598 }
2599
2600 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002601 ClassPtrTy = ClassPtrTy->getPointerTo();
2602 V = Builder.CreateBitCast(V, ClassPtrTy);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00002603 return MakeAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002604}
2605
Douglas Gregor6a03e342010-04-23 04:16:32 +00002606
John McCall2a416372010-12-05 02:00:02 +00002607LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00002608 const CompoundAssignOperator *E) {
2609 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002610 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002611 switch (E->getOpcode()) {
2612#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00002613 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00002614 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002615 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002616 COMPOUND_OP(Mul);
2617 COMPOUND_OP(Div);
2618 COMPOUND_OP(Rem);
2619 COMPOUND_OP(Add);
2620 COMPOUND_OP(Sub);
2621 COMPOUND_OP(Shl);
2622 COMPOUND_OP(Shr);
2623 COMPOUND_OP(And);
2624 COMPOUND_OP(Xor);
2625 COMPOUND_OP(Or);
2626#undef COMPOUND_OP
2627
John McCall2de56d12010-08-25 11:45:40 +00002628 case BO_PtrMemD:
2629 case BO_PtrMemI:
2630 case BO_Mul:
2631 case BO_Div:
2632 case BO_Rem:
2633 case BO_Add:
2634 case BO_Sub:
2635 case BO_Shl:
2636 case BO_Shr:
2637 case BO_LT:
2638 case BO_GT:
2639 case BO_LE:
2640 case BO_GE:
2641 case BO_EQ:
2642 case BO_NE:
2643 case BO_And:
2644 case BO_Xor:
2645 case BO_Or:
2646 case BO_LAnd:
2647 case BO_LOr:
2648 case BO_Assign:
2649 case BO_Comma:
Douglas Gregor6a03e342010-04-23 04:16:32 +00002650 assert(false && "Not valid compound assignment operators");
2651 break;
2652 }
2653
2654 llvm_unreachable("Unhandled compound assignment operator");
2655}