blob: 84e3b966c78d44db45408db893e36b411d3ee9bf [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
14#include "CodeGenFunction.h"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000015#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000016#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000018#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000019#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000020#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000021#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000022#include "llvm/Constants.h"
23#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000024#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000025#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000026#include "llvm/Module.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000027#include "llvm/Support/CFG.h"
Mike Stump4e7a1f72009-02-21 20:00:35 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000029#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000030
Chris Lattner7f02f722007-08-24 05:35:26 +000031using namespace clang;
32using namespace CodeGen;
33using llvm::Value;
34
35//===----------------------------------------------------------------------===//
36// Scalar Expression Emitter
37//===----------------------------------------------------------------------===//
38
39struct BinOpInfo {
40 Value *LHS;
41 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000042 QualType Ty; // Computation Type.
Chris Lattner9a207232010-06-26 21:48:21 +000043 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
44 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000045};
46
47namespace {
Benjamin Kramer85b45212009-11-28 19:45:26 +000048class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000049 : public StmtVisitor<ScalarExprEmitter, Value*> {
50 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000051 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000052 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000053 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000054public:
55
Mike Stump7f79f9b2009-05-29 15:46:01 +000056 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000057 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000058 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000059 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000060
Chris Lattner7f02f722007-08-24 05:35:26 +000061 //===--------------------------------------------------------------------===//
62 // Utilities
63 //===--------------------------------------------------------------------===//
64
Mike Stump7f79f9b2009-05-29 15:46:01 +000065 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000066 bool I = IgnoreResultAssign;
67 IgnoreResultAssign = false;
68 return I;
69 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000070
Chris Lattner7f02f722007-08-24 05:35:26 +000071 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
72 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Mike Stumpb14e62d2009-12-16 02:57:00 +000073 LValue EmitCheckedLValue(const Expr *E) { return CGF.EmitCheckedLValue(E); }
Chris Lattner7f02f722007-08-24 05:35:26 +000074
75 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000076 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000077 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000078
Chris Lattner7f02f722007-08-24 05:35:26 +000079 /// EmitLoadOfLValue - Given an expression with complex type that represents a
80 /// value l-value, this method emits the address of the l-value, then loads
81 /// and returns the result.
82 Value *EmitLoadOfLValue(const Expr *E) {
Mike Stumpb14e62d2009-12-16 02:57:00 +000083 return EmitLoadOfLValue(EmitCheckedLValue(E), E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +000084 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000085
Chris Lattner9abc84e2007-08-26 16:42:57 +000086 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000087 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000088 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +000089
Chris Lattner3707b252007-08-26 06:48:56 +000090 /// EmitScalarConversion - Emit a conversion from the specified type to the
91 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000092 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
93
94 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +000095 /// complex type to the specified destination type, where the destination type
96 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000097 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
98 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +000099
Anders Carlssona40a9f32010-05-22 17:45:10 +0000100 /// EmitNullValue - Emit a value that corresponds to null for the given type.
101 Value *EmitNullValue(QualType Ty);
102
Chris Lattner7f02f722007-08-24 05:35:26 +0000103 //===--------------------------------------------------------------------===//
104 // Visitor Methods
105 //===--------------------------------------------------------------------===//
106
107 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000108 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000109 assert(0 && "Stmt can't have complex result type!");
110 return 0;
111 }
112 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000113
Chris Lattner7f02f722007-08-24 05:35:26 +0000114 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
115
116 // Leaves.
117 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000118 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000119 }
120 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000121 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000122 }
123 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000124 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000125 }
Nate Begemane7579b52007-11-15 05:40:03 +0000126 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000127 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000128 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000129 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000130 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000131 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000132 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000133 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000134 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000135 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000136 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000137 CGF.getContext().typesAreCompatible(
138 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000139 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000140 Value *VisitOffsetOfExpr(const OffsetOfExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +0000141 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000142 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000143 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
144 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000145 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000146
Chris Lattner7f02f722007-08-24 05:35:26 +0000147 // l-values.
148 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Eli Friedman28665272009-11-26 03:22:21 +0000149 Expr::EvalResult Result;
150 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
151 assert(!Result.HasSideEffects && "Constant declref with side-effect?!");
152 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
153 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000154 return EmitLoadOfLValue(E);
155 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000156 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
157 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000158 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000159 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
160 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000161 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000162 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000163 return EmitLoadOfLValue(E);
164 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000165 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000166 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000167 }
Fariborz Jahanian09105f52009-08-20 17:02:02 +0000168 Value *VisitObjCImplicitSetterGetterRefExpr(
169 ObjCImplicitSetterGetterRefExpr *E) {
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000170 return EmitLoadOfLValue(E);
171 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000172 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
173 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000174 }
175
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000176 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000177 LValue LV = CGF.EmitObjCIsaExpr(E);
178 Value *V = CGF.EmitLoadOfLValue(LV, E->getType()).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000179 return V;
180 }
181
Chris Lattner7f02f722007-08-24 05:35:26 +0000182 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000183 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000184 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000185 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000186 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
187 return EmitLoadOfLValue(E);
188 }
Devang Patel35634f52007-10-24 17:18:43 +0000189
Nate Begeman0533b302009-10-18 20:10:40 +0000190 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000191
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000192 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Anders Carlsson3cb18bc2010-05-14 15:05:19 +0000193 return CGF.CGM.EmitNullConstant(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000194 }
Eli Friedmand8889622009-11-27 04:41:50 +0000195 Value *VisitCastExpr(CastExpr *E) {
Eli Friedmanc62aad82009-04-20 03:54:15 +0000196 // Make sure to evaluate VLA bounds now so that we have them for later.
197 if (E->getType()->isVariablyModifiedType())
198 CGF.EmitVLASize(E->getType());
199
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000200 return EmitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000201 }
Eli Friedmand8889622009-11-27 04:41:50 +0000202 Value *EmitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000203
204 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000205 if (E->getCallReturnType()->isReferenceType())
206 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000207
Chris Lattner9b655512007-08-31 22:49:20 +0000208 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000209 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000210
Chris Lattner33793202007-08-31 22:09:40 +0000211 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000212
Mike Stumpa99038c2009-02-28 09:07:16 +0000213 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000214
Chris Lattner7f02f722007-08-24 05:35:26 +0000215 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000216 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000217 LValue LV = EmitLValue(E->getSubExpr());
218 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000219 }
220 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000221 LValue LV = EmitLValue(E->getSubExpr());
222 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000223 }
224 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000225 LValue LV = EmitLValue(E->getSubExpr());
226 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000227 }
228 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000229 LValue LV = EmitLValue(E->getSubExpr());
230 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000231 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000232
233 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
234 bool isInc, bool isPre);
235
236
Chris Lattner7f02f722007-08-24 05:35:26 +0000237 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
238 return EmitLValue(E->getSubExpr()).getAddress();
239 }
240 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
241 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000242 // This differs from gcc, though, most likely due to a bug in gcc.
243 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000244 return Visit(E->getSubExpr());
245 }
246 Value *VisitUnaryMinus (const UnaryOperator *E);
247 Value *VisitUnaryNot (const UnaryOperator *E);
248 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000249 Value *VisitUnaryReal (const UnaryOperator *E);
250 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000251 Value *VisitUnaryExtension(const UnaryOperator *E) {
252 return Visit(E->getSubExpr());
253 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000254 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000255
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000256 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000257 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
258 return Visit(DAE->getExpr());
259 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000260 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
261 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000262 }
263
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000264 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlsson30824632009-05-31 00:09:15 +0000265 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000266 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000267 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
268 return CGF.EmitCXXNewExpr(E);
269 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000270 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
271 CGF.EmitCXXDeleteExpr(E);
272 return 0;
273 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000274 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
275 return llvm::ConstantInt::get(Builder.getInt1Ty(),
276 E->EvaluateTrait(CGF.getContext()));
277 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000278
Douglas Gregora71d8192009-09-04 17:36:40 +0000279 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
280 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000281 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000282 // operator (), and the result of such a call has type void. The only
283 // effect is the evaluation of the postfix-expression before the dot or
284 // arrow.
285 CGF.EmitScalarExpr(E->getBase());
286 return 0;
287 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000288
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000289 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000290 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000291 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000292
293 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
294 CGF.EmitCXXThrowExpr(E);
295 return 0;
296 }
297
Chris Lattner7f02f722007-08-24 05:35:26 +0000298 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000299 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregorf6094622010-07-23 15:58:24 +0000300 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000301 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
302 case LangOptions::SOB_Undefined:
303 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
304 case LangOptions::SOB_Defined:
305 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
306 case LangOptions::SOB_Trapping:
307 return EmitOverflowCheckedBinOp(Ops);
308 }
309 }
310
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000311 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000312 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000313 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
314 }
Mike Stump2add4732009-04-01 20:28:16 +0000315 /// Create a binary op that checks for overflow.
316 /// Currently only supports +, - and *.
317 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner7f02f722007-08-24 05:35:26 +0000318 Value *EmitDiv(const BinOpInfo &Ops);
319 Value *EmitRem(const BinOpInfo &Ops);
320 Value *EmitAdd(const BinOpInfo &Ops);
321 Value *EmitSub(const BinOpInfo &Ops);
322 Value *EmitShl(const BinOpInfo &Ops);
323 Value *EmitShr(const BinOpInfo &Ops);
324 Value *EmitAnd(const BinOpInfo &Ops) {
325 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
326 }
327 Value *EmitXor(const BinOpInfo &Ops) {
328 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
329 }
330 Value *EmitOr (const BinOpInfo &Ops) {
331 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
332 }
333
Chris Lattner1f1ded92007-08-24 21:00:35 +0000334 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000335 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
336 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000337 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000338
Chris Lattner3ccf7742007-08-26 21:41:21 +0000339 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000340 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
341
342 // Binary operators and binary compound assignment operators.
343#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000344 Value *VisitBin ## OP(const BinaryOperator *E) { \
345 return Emit ## OP(EmitBinOps(E)); \
346 } \
347 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
348 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000349 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000350 HANDLEBINOP(Mul)
351 HANDLEBINOP(Div)
352 HANDLEBINOP(Rem)
353 HANDLEBINOP(Add)
354 HANDLEBINOP(Sub)
355 HANDLEBINOP(Shl)
356 HANDLEBINOP(Shr)
357 HANDLEBINOP(And)
358 HANDLEBINOP(Xor)
359 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000360#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000361
Chris Lattner7f02f722007-08-24 05:35:26 +0000362 // Comparisons.
363 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
364 unsigned SICmpOpc, unsigned FCmpOpc);
365#define VISITCOMP(CODE, UI, SI, FP) \
366 Value *VisitBin##CODE(const BinaryOperator *E) { \
367 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
368 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000369 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
370 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
371 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
372 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
373 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
374 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000375#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000376
Chris Lattner7f02f722007-08-24 05:35:26 +0000377 Value *VisitBinAssign (const BinaryOperator *E);
378
379 Value *VisitBinLAnd (const BinaryOperator *E);
380 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000381 Value *VisitBinComma (const BinaryOperator *E);
382
Eli Friedman25b825d2009-11-18 09:41:26 +0000383 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
384 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
385
Chris Lattner7f02f722007-08-24 05:35:26 +0000386 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000387 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000388 Value *VisitConditionalOperator(const ConditionalOperator *CO);
389 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000390 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000391 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
392 return CGF.EmitObjCStringLiteral(E);
393 }
394};
395} // end anonymous namespace.
396
397//===----------------------------------------------------------------------===//
398// Utilities
399//===----------------------------------------------------------------------===//
400
Chris Lattner9abc84e2007-08-26 16:42:57 +0000401/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000402/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000403Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000404 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000405
Chris Lattner9abc84e2007-08-26 16:42:57 +0000406 if (SrcType->isRealFloatingType()) {
407 // Compare against 0.0 for fp scalars.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000408 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000409 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
410 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000411
Anders Carlsson237957c2009-08-09 18:26:27 +0000412 if (SrcType->isMemberPointerType()) {
Anders Carlsson237957c2009-08-09 18:26:27 +0000413 // Compare against -1.
414 llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType());
415 return Builder.CreateICmpNE(Src, NegativeOne, "tobool");
416 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000417
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000418 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000419 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000420
Chris Lattner9abc84e2007-08-26 16:42:57 +0000421 // Because of the type rules of C, we often end up computing a logical value,
422 // then zero extending it to int, then wanting it as a logical value again.
423 // Optimize this common case.
424 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000425 if (ZI->getOperand(0)->getType() ==
426 llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
Chris Lattner9abc84e2007-08-26 16:42:57 +0000427 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000428 // If there aren't any more uses, zap the instruction to save space.
429 // Note that there can be more uses, for example if this
430 // is the result of an assignment.
431 if (ZI->use_empty())
432 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000433 return Result;
434 }
435 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000436
Chris Lattner9abc84e2007-08-26 16:42:57 +0000437 // Compare against an integer or pointer null.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000438 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000439 return Builder.CreateICmpNE(Src, Zero, "tobool");
440}
441
Chris Lattner3707b252007-08-26 06:48:56 +0000442/// EmitScalarConversion - Emit a conversion from the specified type to the
443/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000444Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
445 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000446 SrcType = CGF.getContext().getCanonicalType(SrcType);
447 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000448 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000449
Chris Lattnercf289082007-08-26 07:21:11 +0000450 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000451
Chris Lattner3707b252007-08-26 06:48:56 +0000452 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000453 if (DstType->isBooleanType())
454 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000455
Chris Lattner3707b252007-08-26 06:48:56 +0000456 const llvm::Type *DstTy = ConvertType(DstType);
457
458 // Ignore conversions like int -> uint.
459 if (Src->getType() == DstTy)
460 return Src;
461
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000462 // Handle pointer conversions next: pointers can only be converted to/from
463 // other pointers and integers. Check for pointer types in terms of LLVM, as
464 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000465 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000466 // The source value may be an integer, or a pointer.
Anders Carlsson191dfe92009-09-12 04:57:16 +0000467 if (isa<llvm::PointerType>(Src->getType()))
Chris Lattner3707b252007-08-26 06:48:56 +0000468 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000469
Chris Lattner3707b252007-08-26 06:48:56 +0000470 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000471 // First, convert to the correct width so that we control the kind of
472 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +0000473 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Eli Friedman25615422009-03-04 04:02:35 +0000474 bool InputSigned = SrcType->isSignedIntegerType();
475 llvm::Value* IntResult =
476 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
477 // Then, cast to pointer.
478 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000479 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000480
Daniel Dunbar270cc662008-08-25 09:51:32 +0000481 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000482 // Must be an ptr to int cast.
483 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000484 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000485 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000486
Nate Begeman213541a2008-04-18 23:10:10 +0000487 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000488 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000489 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000490 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000491 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
492
493 // Insert the element in element zero of an undef vector
Owen Anderson03e20502009-07-30 23:11:26 +0000494 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +0000495 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000496 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
497
498 // Splat the element across to all elements
499 llvm::SmallVector<llvm::Constant*, 16> Args;
500 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
501 for (unsigned i = 0; i < NumElements; i++)
Chris Lattner77b89b82010-06-27 07:15:29 +0000502 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000503
Owen Anderson4a289322009-07-28 21:22:35 +0000504 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000505 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
506 return Yay;
507 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000508
Chris Lattner3b1ae002008-02-02 04:51:41 +0000509 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000510 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000511 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000512 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000513
Chris Lattner3707b252007-08-26 06:48:56 +0000514 // Finally, we have the arithmetic types: real int/float.
515 if (isa<llvm::IntegerType>(Src->getType())) {
516 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000517 if (isa<llvm::IntegerType>(DstTy))
518 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
519 else if (InputSigned)
520 return Builder.CreateSIToFP(Src, DstTy, "conv");
521 else
522 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000523 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000524
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000525 assert(Src->getType()->isFloatingPointTy() && "Unknown real conversion");
Chris Lattner3707b252007-08-26 06:48:56 +0000526 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000527 if (DstType->isSignedIntegerType())
528 return Builder.CreateFPToSI(Src, DstTy, "conv");
529 else
530 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000531 }
532
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000533 assert(DstTy->isFloatingPointTy() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000534 if (DstTy->getTypeID() < Src->getType()->getTypeID())
535 return Builder.CreateFPTrunc(Src, DstTy, "conv");
536 else
537 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000538}
539
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000540/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
541/// type to the specified destination type, where the destination type is an
542/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000543Value *ScalarExprEmitter::
544EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
545 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000546 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000547 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000548
Chris Lattnered70f0a2007-08-26 16:52:28 +0000549 // Handle conversions to bool first, they are special: comparisons against 0.
550 if (DstTy->isBooleanType()) {
551 // Complex != 0 -> (Real != 0) | (Imag != 0)
552 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
553 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
554 return Builder.CreateOr(Src.first, Src.second, "tobool");
555 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000556
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000557 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
558 // the imaginary part of the complex value is discarded and the value of the
559 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000560 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000561 return EmitScalarConversion(Src.first, SrcTy, DstTy);
562}
563
Anders Carlssona40a9f32010-05-22 17:45:10 +0000564Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
565 const llvm::Type *LTy = ConvertType(Ty);
566
567 if (!Ty->isMemberPointerType())
568 return llvm::Constant::getNullValue(LTy);
569
570 assert(!Ty->isMemberFunctionPointerType() &&
571 "member function pointers are not scalar!");
572
573 // Itanium C++ ABI 2.3:
574 // A NULL pointer is represented as -1.
575 return llvm::ConstantInt::get(LTy, -1ULL, /*isSigned=*/true);
576}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000577
Chris Lattner7f02f722007-08-24 05:35:26 +0000578//===----------------------------------------------------------------------===//
579// Visitor Methods
580//===----------------------------------------------------------------------===//
581
582Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000583 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000584 if (E->getType()->isVoidType())
585 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000586 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000587}
588
Eli Friedmand38617c2008-05-14 19:38:39 +0000589Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000590 // Vector Mask Case
591 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000592 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000593 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
594 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
595 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000596
Nate Begeman37b6a572010-06-08 00:16:34 +0000597 const llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
598 unsigned LHSElts = LTy->getNumElements();
599
600 if (E->getNumSubExprs() == 3) {
601 Mask = CGF.EmitScalarExpr(E->getExpr(2));
602
603 // Shuffle LHS & RHS into one input vector.
604 llvm::SmallVector<llvm::Constant*, 32> concat;
605 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000606 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i));
607 concat.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000608 }
609
610 Value* CV = llvm::ConstantVector::get(concat.begin(), concat.size());
611 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
612 LHSElts *= 2;
613 } else {
614 Mask = RHS;
615 }
616
617 const llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
618 llvm::Constant* EltMask;
619
620 // Treat vec3 like vec4.
621 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
622 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
623 (1 << llvm::Log2_32(LHSElts+2))-1);
624 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
625 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
626 (1 << llvm::Log2_32(LHSElts+1))-1);
627 else
628 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
629 (1 << llvm::Log2_32(LHSElts))-1);
630
631 // Mask off the high bits of each shuffle index.
632 llvm::SmallVector<llvm::Constant *, 32> MaskV;
633 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i)
634 MaskV.push_back(EltMask);
635
636 Value* MaskBits = llvm::ConstantVector::get(MaskV.begin(), MaskV.size());
637 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
638
639 // newv = undef
640 // mask = mask & maskbits
641 // for each elt
642 // n = extract mask i
643 // x = extract val n
644 // newv = insert newv, x, i
645 const llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
646 MTy->getNumElements());
647 Value* NewV = llvm::UndefValue::get(RTy);
648 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000649 Value *Indx = llvm::ConstantInt::get(CGF.Int32Ty, i);
Nate Begeman37b6a572010-06-08 00:16:34 +0000650 Indx = Builder.CreateExtractElement(Mask, Indx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000651 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000652
653 // Handle vec3 special since the index will be off by one for the RHS.
654 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
655 Value *cmpIndx, *newIndx;
Chris Lattner77b89b82010-06-27 07:15:29 +0000656 cmpIndx = Builder.CreateICmpUGT(Indx,
657 llvm::ConstantInt::get(CGF.Int32Ty, 3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000658 "cmp_shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000659 newIndx = Builder.CreateSub(Indx, llvm::ConstantInt::get(CGF.Int32Ty,1),
Nate Begeman37b6a572010-06-08 00:16:34 +0000660 "shuf_idx_adj");
661 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
662 }
663 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
664 NewV = Builder.CreateInsertElement(NewV, VExt, Indx, "shuf_ins");
665 }
666 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000667 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000668
Eli Friedmand38617c2008-05-14 19:38:39 +0000669 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
670 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000671
672 // Handle vec3 special since the index will be off by one for the RHS.
673 llvm::SmallVector<llvm::Constant*, 32> indices;
674 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
675 llvm::Constant *C = cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i)));
676 const llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
677 if (VTy->getNumElements() == 3) {
678 if (llvm::ConstantInt *CI = dyn_cast<llvm::ConstantInt>(C)) {
679 uint64_t cVal = CI->getZExtValue();
680 if (cVal > 3) {
681 C = llvm::ConstantInt::get(C->getType(), cVal-1);
682 }
683 }
684 }
685 indices.push_back(C);
686 }
687
Owen Anderson4a289322009-07-28 21:22:35 +0000688 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
Eli Friedmand38617c2008-05-14 19:38:39 +0000689 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
690}
Eli Friedman28665272009-11-26 03:22:21 +0000691Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
692 Expr::EvalResult Result;
693 if (E->Evaluate(Result, CGF.getContext()) && Result.Val.isInt()) {
694 if (E->isArrow())
695 CGF.EmitScalarExpr(E->getBase());
696 else
697 EmitLValue(E->getBase());
698 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
699 }
700 return EmitLoadOfLValue(E);
701}
Eli Friedmand38617c2008-05-14 19:38:39 +0000702
Chris Lattner7f02f722007-08-24 05:35:26 +0000703Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000704 TestAndClearIgnoreResultAssign();
705
Chris Lattner7f02f722007-08-24 05:35:26 +0000706 // Emit subscript expressions in rvalue context's. For most cases, this just
707 // loads the lvalue formed by the subscript expr. However, we have to be
708 // careful, because the base of a vector subscript is occasionally an rvalue,
709 // so we can't get it as an lvalue.
710 if (!E->getBase()->getType()->isVectorType())
711 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000712
Chris Lattner7f02f722007-08-24 05:35:26 +0000713 // Handle the vector case. The base must be a vector, the index must be an
714 // integer value.
715 Value *Base = Visit(E->getBase());
716 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000717 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000718 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000719 return Builder.CreateExtractElement(Base, Idx, "vecext");
720}
721
Nate Begeman0533b302009-10-18 20:10:40 +0000722static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
723 unsigned Off, const llvm::Type *I32Ty) {
724 int MV = SVI->getMaskValue(Idx);
725 if (MV == -1)
726 return llvm::UndefValue::get(I32Ty);
727 return llvm::ConstantInt::get(I32Ty, Off+MV);
728}
729
730Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
731 bool Ignore = TestAndClearIgnoreResultAssign();
732 (void)Ignore;
733 assert (Ignore == false && "init list ignored");
734 unsigned NumInitElements = E->getNumInits();
735
736 if (E->hadArrayRangeDesignator())
737 CGF.ErrorUnsupported(E, "GNU array range designator extension");
738
739 const llvm::VectorType *VType =
740 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
741
742 // We have a scalar in braces. Just use the first element.
743 if (!VType)
744 return Visit(E->getInit(0));
745
746 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +0000747
748 // Loop over initializers collecting the Value for each, and remembering
749 // whether the source was swizzle (ExtVectorElementExpr). This will allow
750 // us to fold the shuffle for the swizzle into the shuffle for the vector
751 // initializer, since LLVM optimizers generally do not want to touch
752 // shuffles.
753 unsigned CurIdx = 0;
754 bool VIsUndefShuffle = false;
755 llvm::Value *V = llvm::UndefValue::get(VType);
756 for (unsigned i = 0; i != NumInitElements; ++i) {
757 Expr *IE = E->getInit(i);
758 Value *Init = Visit(IE);
759 llvm::SmallVector<llvm::Constant*, 16> Args;
760
761 const llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
762
763 // Handle scalar elements. If the scalar initializer is actually one
764 // element of a different vector of the same width, use shuffle instead of
765 // extract+insert.
766 if (!VVT) {
767 if (isa<ExtVectorElementExpr>(IE)) {
768 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
769
770 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
771 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
772 Value *LHS = 0, *RHS = 0;
773 if (CurIdx == 0) {
774 // insert into undef -> shuffle (src, undef)
775 Args.push_back(C);
776 for (unsigned j = 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000777 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000778
779 LHS = EI->getVectorOperand();
780 RHS = V;
781 VIsUndefShuffle = true;
782 } else if (VIsUndefShuffle) {
783 // insert into undefshuffle && size match -> shuffle (v, src)
784 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
785 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000786 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
787 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
Nate Begeman0533b302009-10-18 20:10:40 +0000788 ResElts + C->getZExtValue()));
789 for (unsigned j = CurIdx + 1; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000790 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000791
792 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
793 RHS = EI->getVectorOperand();
794 VIsUndefShuffle = false;
795 }
796 if (!Args.empty()) {
797 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
798 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
799 ++CurIdx;
800 continue;
801 }
802 }
803 }
Chris Lattner77b89b82010-06-27 07:15:29 +0000804 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000805 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
806 VIsUndefShuffle = false;
807 ++CurIdx;
808 continue;
809 }
810
811 unsigned InitElts = VVT->getNumElements();
812
813 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
814 // input is the same width as the vector being constructed, generate an
815 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +0000816 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +0000817 if (isa<ExtVectorElementExpr>(IE)) {
818 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
819 Value *SVOp = SVI->getOperand(0);
820 const llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
821
822 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +0000823 for (unsigned j = 0; j != CurIdx; ++j) {
824 // If the current vector initializer is a shuffle with undef, merge
825 // this shuffle directly into it.
826 if (VIsUndefShuffle) {
827 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +0000828 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000829 } else {
Chris Lattner77b89b82010-06-27 07:15:29 +0000830 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000831 }
832 }
833 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000834 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000835 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000836 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000837
838 if (VIsUndefShuffle)
839 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
840
841 Init = SVOp;
842 }
843 }
844
845 // Extend init to result vector length, and then shuffle its contribution
846 // to the vector initializer into V.
847 if (Args.empty()) {
848 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000849 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000850 for (unsigned j = InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000851 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000852 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
853 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +0000854 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +0000855
856 Args.clear();
857 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000858 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j));
Nate Begeman0533b302009-10-18 20:10:40 +0000859 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000860 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, j+Offset));
Nate Begeman0533b302009-10-18 20:10:40 +0000861 for (unsigned j = CurIdx + InitElts; j != ResElts; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +0000862 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +0000863 }
864
865 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
866 // merging subsequent shuffles into this one.
867 if (CurIdx == 0)
868 std::swap(V, Init);
869 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], ResElts);
870 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
871 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
872 CurIdx += InitElts;
873 }
874
875 // FIXME: evaluate codegen vs. shuffling against constant null vector.
876 // Emit remaining default initializers.
877 const llvm::Type *EltTy = VType->getElementType();
878
879 // Emit remaining default initializers
880 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000881 Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +0000882 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
883 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
884 }
885 return V;
886}
887
Anders Carlssona3697c92009-11-23 17:57:54 +0000888static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
889 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +0000890
891 if (CE->getCastKind() == CastExpr::CK_UncheckedDerivedToBase)
892 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +0000893
894 if (isa<CXXThisExpr>(E)) {
895 // We always assume that 'this' is never null.
896 return false;
897 }
898
899 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +0000900 // And that glvalue casts are never null.
901 if (ICE->getCategory() != ImplicitCastExpr::RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +0000902 return false;
903 }
904
905 return true;
906}
907
Chris Lattner7f02f722007-08-24 05:35:26 +0000908// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
909// have to handle a more broad range of conversions than explicit casts, as they
910// handle things like function to ptr-to-function decay etc.
Eli Friedmand8889622009-11-27 04:41:50 +0000911Value *ScalarExprEmitter::EmitCastExpr(CastExpr *CE) {
912 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +0000913 QualType DestTy = CE->getType();
914 CastExpr::CastKind Kind = CE->getCastKind();
915
Mike Stump7f79f9b2009-05-29 15:46:01 +0000916 if (!DestTy->isVoidType())
917 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000918
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000919 // Since almost all cast kinds apply to scalars, this switch doesn't have
920 // a default case, so the compiler will warn on a missing case. The cases
921 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +0000922 switch (Kind) {
Anders Carlsson7f9e6462009-09-15 04:48:33 +0000923 case CastExpr::CK_Unknown:
Eli Friedmand8889622009-11-27 04:41:50 +0000924 // FIXME: All casts should have a known kind!
Eli Friedmanad35a832009-11-16 21:33:53 +0000925 //assert(0 && "Unknown cast kind!");
Anders Carlssone9776242009-08-24 18:26:39 +0000926 break;
Eli Friedmanad35a832009-11-16 21:33:53 +0000927
Douglas Gregore39a3892010-07-13 23:17:26 +0000928 case CastExpr::CK_LValueBitCast: {
929 Value *V = EmitLValue(E).getAddress();
930 V = Builder.CreateBitCast(V,
931 ConvertType(CGF.getContext().getPointerType(DestTy)));
932 // FIXME: Are the qualifiers correct here?
933 return EmitLoadOfLValue(LValue::MakeAddr(V, CGF.MakeQualifiers(DestTy)),
934 DestTy);
935 }
936
Fariborz Jahanian92ef5d72009-12-08 23:09:15 +0000937 case CastExpr::CK_AnyPointerToObjCPointerCast:
Fariborz Jahanian3b27f1a2009-12-11 22:40:48 +0000938 case CastExpr::CK_AnyPointerToBlockPointerCast:
Anders Carlssoncb3c3082009-09-01 20:52:42 +0000939 case CastExpr::CK_BitCast: {
940 Value *Src = Visit(const_cast<Expr*>(E));
941 return Builder.CreateBitCast(Src, ConvertType(DestTy));
942 }
Eli Friedmanad35a832009-11-16 21:33:53 +0000943 case CastExpr::CK_NoOp:
Anders Carlsson0ddb6f72009-12-18 14:42:03 +0000944 case CastExpr::CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +0000945 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000946
Anders Carlssona3697c92009-11-23 17:57:54 +0000947 case CastExpr::CK_BaseToDerived: {
Anders Carlssona3697c92009-11-23 17:57:54 +0000948 const CXXRecordDecl *DerivedClassDecl =
949 DestTy->getCXXRecordDeclForPointerType();
950
Anders Carlssona04efdf2010-04-24 21:23:59 +0000951 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
952 CE->getBasePath(),
953 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +0000954 }
John McCall23cba802010-03-30 23:58:03 +0000955 case CastExpr::CK_UncheckedDerivedToBase:
Anders Carlsson191dfe92009-09-12 04:57:16 +0000956 case CastExpr::CK_DerivedToBase: {
957 const RecordType *DerivedClassTy =
958 E->getType()->getAs<PointerType>()->getPointeeType()->getAs<RecordType>();
959 CXXRecordDecl *DerivedClassDecl =
960 cast<CXXRecordDecl>(DerivedClassTy->getDecl());
961
Anders Carlsson34a2d382010-04-24 21:06:20 +0000962 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
963 CE->getBasePath(),
964 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +0000965 }
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000966 case CastExpr::CK_Dynamic: {
967 Value *V = Visit(const_cast<Expr*>(E));
968 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
969 return CGF.EmitDynamicCast(V, DCE);
970 }
Eli Friedmand8889622009-11-27 04:41:50 +0000971 case CastExpr::CK_ToUnion:
Eli Friedmanad35a832009-11-16 21:33:53 +0000972 assert(0 && "Should be unreachable!");
973 break;
Eli Friedmand8889622009-11-27 04:41:50 +0000974
Eli Friedmanad35a832009-11-16 21:33:53 +0000975 case CastExpr::CK_ArrayToPointerDecay: {
976 assert(E->getType()->isArrayType() &&
977 "Array to pointer decay must have array source type!");
978
979 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
980
981 // Note that VLA pointers are always decayed, so we don't need to do
982 // anything here.
983 if (!E->getType()->isVariableArrayType()) {
984 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
985 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
986 ->getElementType()) &&
987 "Expected pointer to array");
988 V = Builder.CreateStructGEP(V, 0, "arraydecay");
989 }
990
991 return V;
992 }
993 case CastExpr::CK_FunctionToPointerDecay:
994 return EmitLValue(E).getAddress();
995
996 case CastExpr::CK_NullToMemberPointer:
997 return CGF.CGM.EmitNullConstant(DestTy);
Anders Carlsson191dfe92009-09-12 04:57:16 +0000998
Eli Friedman8c3e7e72009-11-27 02:07:44 +0000999 case CastExpr::CK_BaseToDerivedMemberPointer:
Eli Friedmand8889622009-11-27 04:41:50 +00001000 case CastExpr::CK_DerivedToBaseMemberPointer: {
1001 Value *Src = Visit(E);
1002
1003 // See if we need to adjust the pointer.
1004 const CXXRecordDecl *BaseDecl =
1005 cast<CXXRecordDecl>(E->getType()->getAs<MemberPointerType>()->
1006 getClass()->getAs<RecordType>()->getDecl());
1007 const CXXRecordDecl *DerivedDecl =
1008 cast<CXXRecordDecl>(CE->getType()->getAs<MemberPointerType>()->
1009 getClass()->getAs<RecordType>()->getDecl());
1010 if (CE->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
1011 std::swap(DerivedDecl, BaseDecl);
1012
Anders Carlssonbb7e17b2010-01-31 01:36:53 +00001013 if (llvm::Constant *Adj =
Chris Lattnere70ffd62010-06-26 20:27:24 +00001014 CGF.CGM.GetNonVirtualBaseClassOffset(DerivedDecl, CE->getBasePath())){
Eli Friedmand8889622009-11-27 04:41:50 +00001015 if (CE->getCastKind() == CastExpr::CK_DerivedToBaseMemberPointer)
Chris Lattnere70ffd62010-06-26 20:27:24 +00001016 Src = Builder.CreateNSWSub(Src, Adj, "adj");
Eli Friedmand8889622009-11-27 04:41:50 +00001017 else
Chris Lattnere70ffd62010-06-26 20:27:24 +00001018 Src = Builder.CreateNSWAdd(Src, Adj, "adj");
Eli Friedmand8889622009-11-27 04:41:50 +00001019 }
Chris Lattnere70ffd62010-06-26 20:27:24 +00001020
Eli Friedmand8889622009-11-27 04:41:50 +00001021 return Src;
1022 }
1023
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001024 case CastExpr::CK_ConstructorConversion:
Eli Friedmand8889622009-11-27 04:41:50 +00001025 assert(0 && "Should be unreachable!");
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001026 break;
1027
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001028 case CastExpr::CK_IntegralToPointer: {
1029 Value *Src = Visit(const_cast<Expr*>(E));
Anders Carlsson82debc72009-10-18 18:12:03 +00001030
1031 // First, convert to the correct width so that we control the kind of
1032 // extension.
Chris Lattner77b89b82010-06-27 07:15:29 +00001033 const llvm::Type *MiddleTy = CGF.IntPtrTy;
Anders Carlsson82debc72009-10-18 18:12:03 +00001034 bool InputSigned = E->getType()->isSignedIntegerType();
1035 llvm::Value* IntResult =
1036 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1037
1038 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001039 }
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001040 case CastExpr::CK_PointerToIntegral: {
1041 Value *Src = Visit(const_cast<Expr*>(E));
1042 return Builder.CreatePtrToInt(Src, ConvertType(DestTy));
1043 }
Eli Friedmanad35a832009-11-16 21:33:53 +00001044 case CastExpr::CK_ToVoid: {
1045 CGF.EmitAnyExpr(E, 0, false, true);
1046 return 0;
1047 }
Eli Friedmanad35a832009-11-16 21:33:53 +00001048 case CastExpr::CK_VectorSplat: {
1049 const llvm::Type *DstTy = ConvertType(DestTy);
1050 Value *Elt = Visit(const_cast<Expr*>(E));
1051
1052 // Insert the element in element zero of an undef vector
1053 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Chris Lattner77b89b82010-06-27 07:15:29 +00001054 llvm::Value *Idx = llvm::ConstantInt::get(CGF.Int32Ty, 0);
Eli Friedmanad35a832009-11-16 21:33:53 +00001055 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
1056
1057 // Splat the element across to all elements
1058 llvm::SmallVector<llvm::Constant*, 16> Args;
1059 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
1060 for (unsigned i = 0; i < NumElements; i++)
Chris Lattner77b89b82010-06-27 07:15:29 +00001061 Args.push_back(llvm::ConstantInt::get(CGF.Int32Ty, 0));
Eli Friedmanad35a832009-11-16 21:33:53 +00001062
1063 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
1064 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
1065 return Yay;
1066 }
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001067 case CastExpr::CK_IntegralCast:
1068 case CastExpr::CK_IntegralToFloating:
1069 case CastExpr::CK_FloatingToIntegral:
1070 case CastExpr::CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001071 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001072
Eli Friedman3a173702009-12-11 09:26:29 +00001073 case CastExpr::CK_MemberPointerToBoolean:
1074 return CGF.EvaluateExprAsBool(E);
Anders Carlssone9776242009-08-24 18:26:39 +00001075 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001076
Chris Lattner58a2e942007-08-26 07:26:12 +00001077 // Handle cases where the source is an non-complex type.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001078
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001079 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +00001080 Value *Src = Visit(const_cast<Expr*>(E));
1081
Chris Lattner3707b252007-08-26 06:48:56 +00001082 // Use EmitScalarConversion to perform the conversion.
1083 return EmitScalarConversion(Src, E->getType(), DestTy);
1084 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001085
Chris Lattner9b2dc282008-04-04 16:54:41 +00001086 if (E->getType()->isAnyComplexType()) {
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001087 // Handle cases where the source is a complex type.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001088 bool IgnoreImag = true;
1089 bool IgnoreImagAssign = true;
1090 bool IgnoreReal = IgnoreResultAssign;
1091 bool IgnoreRealAssign = IgnoreResultAssign;
1092 if (DestTy->isBooleanType())
1093 IgnoreImagAssign = IgnoreImag = false;
1094 else if (DestTy->isVoidType()) {
1095 IgnoreReal = IgnoreImag = false;
1096 IgnoreRealAssign = IgnoreImagAssign = true;
1097 }
1098 CodeGenFunction::ComplexPairTy V
1099 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
1100 IgnoreImagAssign);
1101 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001102 }
Chris Lattner10b00cf2007-08-26 07:16:41 +00001103
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001104 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
1105 // evaluate the result and return.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001106 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner19a1d7c2008-02-16 23:55:16 +00001107 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +00001108}
1109
Chris Lattner33793202007-08-31 22:09:40 +00001110Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner91d723d2008-07-26 20:23:23 +00001111 return CGF.EmitCompoundStmt(*E->getSubStmt(),
1112 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001113}
1114
Mike Stumpa99038c2009-02-28 09:07:16 +00001115Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +00001116 llvm::Value *V = CGF.GetAddrOfBlockDecl(E);
1117 if (E->getType().isObjCGCWeak())
1118 return CGF.CGM.getObjCRuntime().EmitObjCWeakRead(CGF, V);
Daniel Dunbar2da84ff2009-11-29 21:23:36 +00001119 return Builder.CreateLoad(V, "tmp");
Mike Stump4e7a1f72009-02-21 20:00:35 +00001120}
Chris Lattner33793202007-08-31 22:09:40 +00001121
Chris Lattner7f02f722007-08-24 05:35:26 +00001122//===----------------------------------------------------------------------===//
1123// Unary Operators
1124//===----------------------------------------------------------------------===//
1125
Chris Lattner8c11a652010-06-26 22:09:34 +00001126llvm::Value *ScalarExprEmitter::
1127EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1128 bool isInc, bool isPre) {
1129
1130 QualType ValTy = E->getSubExpr()->getType();
1131 llvm::Value *InVal = EmitLoadOfLValue(LV, ValTy);
1132
1133 int AmountVal = isInc ? 1 : -1;
1134
1135 if (ValTy->isPointerType() &&
1136 ValTy->getAs<PointerType>()->isVariableArrayType()) {
1137 // The amount of the addition/subtraction needs to account for the VLA size
1138 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
1139 }
1140
1141 llvm::Value *NextVal;
1142 if (const llvm::PointerType *PT =
1143 dyn_cast<llvm::PointerType>(InVal->getType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +00001144 llvm::Constant *Inc = llvm::ConstantInt::get(CGF.Int32Ty, AmountVal);
Chris Lattner8c11a652010-06-26 22:09:34 +00001145 if (!isa<llvm::FunctionType>(PT->getElementType())) {
1146 QualType PTEE = ValTy->getPointeeType();
1147 if (const ObjCObjectType *OIT = PTEE->getAs<ObjCObjectType>()) {
1148 // Handle interface types, which are not represented with a concrete
1149 // type.
1150 int size = CGF.getContext().getTypeSize(OIT) / 8;
1151 if (!isInc)
1152 size = -size;
1153 Inc = llvm::ConstantInt::get(Inc->getType(), size);
1154 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1155 InVal = Builder.CreateBitCast(InVal, i8Ty);
1156 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
1157 llvm::Value *lhs = LV.getAddress();
1158 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
1159 LV = LValue::MakeAddr(lhs, CGF.MakeQualifiers(ValTy));
1160 } else
1161 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
1162 } else {
1163 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
1164 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
1165 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
1166 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
1167 }
1168 } else if (InVal->getType()->isIntegerTy(1) && isInc) {
1169 // Bool++ is an interesting case, due to promotion rules, we get:
1170 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
1171 // Bool = ((int)Bool+1) != 0
1172 // An interesting aspect of this is that increment is always true.
1173 // Decrement does not have this property.
1174 NextVal = llvm::ConstantInt::getTrue(VMContext);
1175 } else if (isa<llvm::IntegerType>(InVal->getType())) {
1176 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
1177
Chris Lattner640d3262010-06-26 22:18:28 +00001178 if (!ValTy->isSignedIntegerType())
1179 // Unsigned integer inc is always two's complement.
Chris Lattner8c11a652010-06-26 22:09:34 +00001180 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattner640d3262010-06-26 22:18:28 +00001181 else {
1182 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1183 case LangOptions::SOB_Undefined:
1184 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
1185 break;
1186 case LangOptions::SOB_Defined:
1187 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
1188 break;
1189 case LangOptions::SOB_Trapping:
1190 BinOpInfo BinOp;
1191 BinOp.LHS = InVal;
1192 BinOp.RHS = NextVal;
1193 BinOp.Ty = E->getType();
1194 BinOp.Opcode = BinaryOperator::Add;
1195 BinOp.E = E;
1196 return EmitOverflowCheckedBinOp(BinOp);
1197 }
1198 }
Chris Lattner8c11a652010-06-26 22:09:34 +00001199 } else {
1200 // Add the inc/dec to the real part.
1201 if (InVal->getType()->isFloatTy())
1202 NextVal =
1203 llvm::ConstantFP::get(VMContext,
1204 llvm::APFloat(static_cast<float>(AmountVal)));
1205 else if (InVal->getType()->isDoubleTy())
1206 NextVal =
1207 llvm::ConstantFP::get(VMContext,
1208 llvm::APFloat(static_cast<double>(AmountVal)));
1209 else {
1210 llvm::APFloat F(static_cast<float>(AmountVal));
1211 bool ignored;
1212 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1213 &ignored);
1214 NextVal = llvm::ConstantFP::get(VMContext, F);
1215 }
1216 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
1217 }
1218
1219 // Store the updated result through the lvalue.
1220 if (LV.isBitField())
1221 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy, &NextVal);
1222 else
1223 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
1224
1225 // If this is a postinc, return the value read from memory, otherwise use the
1226 // updated value.
1227 return isPre ? NextVal : InVal;
1228}
1229
1230
1231
Chris Lattner7f02f722007-08-24 05:35:26 +00001232Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001233 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001234 // Emit unary minus with EmitSub so we handle overflow cases etc.
1235 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001236 BinOp.RHS = Visit(E->getSubExpr());
1237
1238 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1239 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1240 else
1241 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001242 BinOp.Ty = E->getType();
1243 BinOp.Opcode = BinaryOperator::Sub;
1244 BinOp.E = E;
1245 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001246}
1247
1248Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001249 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001250 Value *Op = Visit(E->getSubExpr());
1251 return Builder.CreateNot(Op, "neg");
1252}
1253
1254Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
1255 // Compare operand to zero.
1256 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001257
Chris Lattner7f02f722007-08-24 05:35:26 +00001258 // Invert value.
1259 // TODO: Could dynamically modify easy computations here. For example, if
1260 // the operand is an icmp ne, turn into icmp eq.
1261 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001262
Anders Carlsson9f84d882009-05-19 18:44:53 +00001263 // ZExt result to the expr type.
1264 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001265}
1266
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001267Value *ScalarExprEmitter::VisitOffsetOfExpr(const OffsetOfExpr *E) {
1268 Expr::EvalResult Result;
1269 if(E->Evaluate(Result, CGF.getContext()))
1270 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
1271
1272 // FIXME: Cannot support code generation for non-constant offsetof.
1273 unsigned DiagID = CGF.CGM.getDiags().getCustomDiagID(Diagnostic::Error,
1274 "cannot compile non-constant __builtin_offsetof");
1275 CGF.CGM.getDiags().Report(CGF.getContext().getFullLoc(E->getLocStart()),
1276 DiagID)
1277 << E->getSourceRange();
1278
1279 return llvm::Constant::getNullValue(ConvertType(E->getType()));
1280}
1281
Sebastian Redl05189992008-11-11 17:56:53 +00001282/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
1283/// argument of the sizeof expression as an integer.
1284Value *
1285ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001286 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001287 if (E->isSizeOf()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001288 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001289 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1290 if (E->isArgumentType()) {
1291 // sizeof(type) - make sure to emit the VLA size.
1292 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001293 } else {
1294 // C99 6.5.3.4p2: If the argument is an expression of type
1295 // VLA, it is evaluated.
1296 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001297 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001298
Anders Carlsson96f21472009-02-05 19:43:10 +00001299 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +00001300 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001301 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001302
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001303 // If this isn't sizeof(vla), the result must be constant; use the constant
1304 // folding logic so we don't have to duplicate it here.
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001305 Expr::EvalResult Result;
1306 E->Evaluate(Result, CGF.getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001307 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +00001308}
1309
Chris Lattner46f93d02007-08-24 21:20:17 +00001310Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1311 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +00001312 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +00001313 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner46f93d02007-08-24 21:20:17 +00001314 return Visit(Op);
1315}
1316Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1317 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +00001318 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +00001319 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001320
Mike Stump7f79f9b2009-05-29 15:46:01 +00001321 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1322 // effects are evaluated, but not the actual value.
1323 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
1324 CGF.EmitLValue(Op);
1325 else
1326 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001327 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001328}
1329
Mike Stump1eb44332009-09-09 15:08:12 +00001330Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E) {
Eli Friedman35183ac2009-02-27 06:44:11 +00001331 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedman769e4112009-01-24 22:38:55 +00001332 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman35183ac2009-02-27 06:44:11 +00001333 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson5a1deb82008-01-29 15:56:48 +00001334}
Chris Lattner46f93d02007-08-24 21:20:17 +00001335
Chris Lattner7f02f722007-08-24 05:35:26 +00001336//===----------------------------------------------------------------------===//
1337// Binary Operators
1338//===----------------------------------------------------------------------===//
1339
1340BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001341 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001342 BinOpInfo Result;
1343 Result.LHS = Visit(E->getLHS());
1344 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001345 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001346 Result.Opcode = E->getOpcode();
Chris Lattner7f02f722007-08-24 05:35:26 +00001347 Result.E = E;
1348 return Result;
1349}
1350
Douglas Gregor6a03e342010-04-23 04:16:32 +00001351LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1352 const CompoundAssignOperator *E,
1353 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001354 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001355 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001356 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001357
Eli Friedmanab3a8522009-03-28 01:22:36 +00001358 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001359 // This needs to go through the complex expression emitter, but it's a tad
1360 // complicated to do that... I'm leaving it out for now. (Note that we do
1361 // actually need the imaginary part of the RHS for multiplication and
1362 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001363 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001364 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001365 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001366 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001367
Mike Stumpcc0442f2009-05-22 19:07:20 +00001368 // Emit the RHS first. __block variables need to have the rhs evaluated
1369 // first, plus this should improve codegen a little.
1370 OpInfo.RHS = Visit(E->getRHS());
1371 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001372 OpInfo.Opcode = E->getOpcode();
Mike Stumpcc0442f2009-05-22 19:07:20 +00001373 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001374 // Load/convert the LHS.
Mike Stumpb14e62d2009-12-16 02:57:00 +00001375 LValue LHSLV = EmitCheckedLValue(E->getLHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001376 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +00001377 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1378 E->getComputationLHSType());
Douglas Gregor6a03e342010-04-23 04:16:32 +00001379
Chris Lattner1f1ded92007-08-24 21:00:35 +00001380 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001381 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001382
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001383 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001384 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001385
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001386 // Store the result value into the LHS lvalue. Bit-fields are handled
1387 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1388 // 'An assignment expression has the value of the left operand after the
1389 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001390 if (LHSLV.isBitField())
1391 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
1392 &Result);
1393 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001394 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001395
Douglas Gregor6a03e342010-04-23 04:16:32 +00001396 return LHSLV;
1397}
1398
1399Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1400 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1401 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001402 Value *RHS;
1403 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1404
1405 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001406 if (Ignore)
1407 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001408
1409 // Objective-C property assignment never reloads the value following a store.
1410 if (LHS.isPropertyRef() || LHS.isKVCRef())
1411 return RHS;
1412
1413 // If the lvalue is non-volatile, return the computed value of the assignment.
1414 if (!LHS.isVolatileQualified())
1415 return RHS;
1416
1417 // Otherwise, reload the value.
1418 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001419}
1420
1421
Chris Lattner7f02f722007-08-24 05:35:26 +00001422Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001423 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner7f02f722007-08-24 05:35:26 +00001424 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Douglas Gregorf6094622010-07-23 15:58:24 +00001425 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001426 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1427 else
1428 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1429}
1430
1431Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1432 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +00001433 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001434 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1435 else
1436 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1437}
1438
Mike Stump2add4732009-04-01 20:28:16 +00001439Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
1440 unsigned IID;
1441 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00001442
Chris Lattner9a207232010-06-26 21:48:21 +00001443 switch (Ops.Opcode) {
Mike Stump035cf892009-04-02 18:15:54 +00001444 case BinaryOperator::Add:
1445 case BinaryOperator::AddAssign:
1446 OpID = 1;
1447 IID = llvm::Intrinsic::sadd_with_overflow;
1448 break;
1449 case BinaryOperator::Sub:
1450 case BinaryOperator::SubAssign:
1451 OpID = 2;
1452 IID = llvm::Intrinsic::ssub_with_overflow;
1453 break;
1454 case BinaryOperator::Mul:
1455 case BinaryOperator::MulAssign:
1456 OpID = 3;
1457 IID = llvm::Intrinsic::smul_with_overflow;
1458 break;
1459 default:
1460 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +00001461 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +00001462 }
Mike Stump035cf892009-04-02 18:15:54 +00001463 OpID <<= 1;
1464 OpID |= 1;
1465
Mike Stump2add4732009-04-01 20:28:16 +00001466 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
1467
1468 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
1469
1470 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
1471 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
1472 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
1473
1474 // Branch in case of overflow.
1475 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1476 llvm::BasicBlock *overflowBB =
1477 CGF.createBasicBlock("overflow", CGF.CurFn);
1478 llvm::BasicBlock *continueBB =
1479 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
1480
1481 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1482
1483 // Handle overflow
1484
1485 Builder.SetInsertPoint(overflowBB);
1486
1487 // Handler is:
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001488 // long long *__overflow_handler)(long long a, long long b, char op,
Mike Stump2add4732009-04-01 20:28:16 +00001489 // char width)
1490 std::vector<const llvm::Type*> handerArgTypes;
Chris Lattner77b89b82010-06-27 07:15:29 +00001491 handerArgTypes.push_back(CGF.Int64Ty);
1492 handerArgTypes.push_back(CGF.Int64Ty);
Owen Anderson0032b272009-08-13 21:57:51 +00001493 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1494 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
Chris Lattner77b89b82010-06-27 07:15:29 +00001495 llvm::FunctionType *handlerTy =
1496 llvm::FunctionType::get(CGF.Int64Ty, handerArgTypes, false);
Mike Stump2add4732009-04-01 20:28:16 +00001497 llvm::Value *handlerFunction =
1498 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
Owen Anderson96e0fc72009-07-29 22:16:19 +00001499 llvm::PointerType::getUnqual(handlerTy));
Mike Stump2add4732009-04-01 20:28:16 +00001500 handlerFunction = Builder.CreateLoad(handlerFunction);
1501
1502 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
Chris Lattner77b89b82010-06-27 07:15:29 +00001503 Builder.CreateSExt(Ops.LHS, CGF.Int64Ty),
1504 Builder.CreateSExt(Ops.RHS, CGF.Int64Ty),
Owen Anderson0032b272009-08-13 21:57:51 +00001505 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID),
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001506 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
Mike Stump2add4732009-04-01 20:28:16 +00001507 cast<llvm::IntegerType>(opTy)->getBitWidth()));
1508
1509 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1510
1511 Builder.CreateBr(continueBB);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001512
Mike Stump2add4732009-04-01 20:28:16 +00001513 // Set up the continuation
1514 Builder.SetInsertPoint(continueBB);
1515 // Get the correct result
1516 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1517 phi->reserveOperandSpace(2);
1518 phi->addIncoming(result, initialBB);
1519 phi->addIncoming(handlerResult, overflowBB);
1520
1521 return phi;
1522}
Chris Lattner7f02f722007-08-24 05:35:26 +00001523
1524Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001525 if (!Ops.Ty->isAnyPointerType()) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001526 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001527 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1528 case LangOptions::SOB_Undefined:
1529 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1530 case LangOptions::SOB_Defined:
1531 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
1532 case LangOptions::SOB_Trapping:
1533 return EmitOverflowCheckedBinOp(Ops);
1534 }
1535 }
1536
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001537 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001538 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanbf933a02009-08-12 01:16:29 +00001539
Chris Lattner7f02f722007-08-24 05:35:26 +00001540 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001541 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001542
Chris Lattner7f215c12010-06-26 21:52:32 +00001543 // Must have binary (not unary) expr here. Unary pointer decrement doesn't
Chris Lattner9a207232010-06-26 21:48:21 +00001544 // use this path.
1545 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1546
Steve Naroff14108da2009-07-10 23:34:53 +00001547 if (Ops.Ty->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001548 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001549 // The amount of the addition needs to account for the VLA size
Chris Lattner9a207232010-06-26 21:48:21 +00001550 CGF.ErrorUnsupported(BinOp, "VLA pointer addition");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001551 }
Chris Lattner9a207232010-06-26 21:48:21 +00001552
Chris Lattner8f925282008-01-03 06:36:51 +00001553 Value *Ptr, *Idx;
1554 Expr *IdxExp;
Chris Lattner9a207232010-06-26 21:48:21 +00001555 const PointerType *PT = BinOp->getLHS()->getType()->getAs<PointerType>();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001556 const ObjCObjectPointerType *OPT =
Chris Lattner9a207232010-06-26 21:48:21 +00001557 BinOp->getLHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001558 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001559 Ptr = Ops.LHS;
1560 Idx = Ops.RHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001561 IdxExp = BinOp->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001562 } else { // int + pointer
Chris Lattner9a207232010-06-26 21:48:21 +00001563 PT = BinOp->getRHS()->getType()->getAs<PointerType>();
1564 OPT = BinOp->getRHS()->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001565 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001566 Ptr = Ops.RHS;
1567 Idx = Ops.LHS;
Chris Lattner9a207232010-06-26 21:48:21 +00001568 IdxExp = BinOp->getLHS();
Chris Lattner8f925282008-01-03 06:36:51 +00001569 }
1570
1571 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001572 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner8f925282008-01-03 06:36:51 +00001573 // Zero or sign extend the pointer value based on whether the index is
1574 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001575 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner96196622008-07-26 22:37:01 +00001576 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001577 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1578 else
1579 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1580 }
Steve Naroff14108da2009-07-10 23:34:53 +00001581 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001582 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001583 if (const ObjCObjectType *OIT = ElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001584 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001585 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001586 CGF.getContext().getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001587 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001588 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001589 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1590 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1591 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001592 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001593
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001594 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
1595 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
1596 // future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001597 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001598 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001599 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001600 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001601 return Builder.CreateBitCast(Res, Ptr->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001602 }
1603
Dan Gohman664f8932009-08-12 00:33:55 +00001604 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001605}
1606
1607Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001608 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Douglas Gregorf6094622010-07-23 15:58:24 +00001609 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00001610 switch (CGF.getContext().getLangOptions().getSignedOverflowBehavior()) {
1611 case LangOptions::SOB_Undefined:
1612 return Builder.CreateNSWSub(Ops.LHS, Ops.RHS, "sub");
1613 case LangOptions::SOB_Defined:
1614 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
1615 case LangOptions::SOB_Trapping:
1616 return EmitOverflowCheckedBinOp(Ops);
1617 }
1618 }
1619
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001620 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +00001621 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner2eb91e42010-03-29 17:28:16 +00001622
Chris Lattner7f02f722007-08-24 05:35:26 +00001623 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001624 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001625
Chris Lattner9a207232010-06-26 21:48:21 +00001626 // Must have binary (not unary) expr here. Unary pointer increment doesn't
1627 // use this path.
1628 const BinaryOperator *BinOp = cast<BinaryOperator>(Ops.E);
1629
1630 if (BinOp->getLHS()->getType()->isPointerType() &&
1631 BinOp->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001632 // The amount of the addition needs to account for the VLA size for
1633 // ptr-int
1634 // The amount of the division needs to account for the VLA size for
1635 // ptr-ptr.
Chris Lattner9a207232010-06-26 21:48:21 +00001636 CGF.ErrorUnsupported(BinOp, "VLA pointer subtraction");
Eli Friedmandaa24a22009-03-28 02:45:41 +00001637 }
1638
Chris Lattner9a207232010-06-26 21:48:21 +00001639 const QualType LHSType = BinOp->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001640 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001641 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1642 // pointer - int
1643 Value *Idx = Ops.RHS;
1644 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001645 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001646 // Zero or sign extend the pointer value based on whether the index is
1647 // signed or not.
Chris Lattner77b89b82010-06-27 07:15:29 +00001648 const llvm::Type *IdxType = CGF.IntPtrTy;
Chris Lattner9a207232010-06-26 21:48:21 +00001649 if (BinOp->getRHS()->getType()->isSignedIntegerType())
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001650 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1651 else
1652 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1653 }
1654 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001655
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001656 // Handle interface types, which are not represented with a concrete type.
John McCallc12c5bb2010-05-15 11:32:37 +00001657 if (const ObjCObjectType *OIT = LHSElementType->getAs<ObjCObjectType>()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001658 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001659 llvm::ConstantInt::get(Idx->getType(),
Ken Dyck199c3d62010-01-11 17:06:35 +00001660 CGF.getContext().
1661 getTypeSizeInChars(OIT).getQuantity());
Daniel Dunbar2a866252009-04-25 05:08:32 +00001662 Idx = Builder.CreateMul(Idx, InterfaceSize);
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001663 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001664 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1665 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1666 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001667 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00001668
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001669 // Explicitly handle GNU void* and function pointer arithmetic
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001670 // extensions. The GNU void* casts amount to no-ops since our void* type is
1671 // i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001672 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Benjamin Kramer3c0ef8c2009-10-13 10:07:13 +00001673 const llvm::Type *i8Ty = llvm::Type::getInt8PtrTy(VMContext);
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001674 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1675 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1676 return Builder.CreateBitCast(Res, Ops.LHS->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001677 }
1678
Dan Gohman664f8932009-08-12 00:33:55 +00001679 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001680 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001681 // pointer - pointer
1682 Value *LHS = Ops.LHS;
1683 Value *RHS = Ops.RHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001684
Ken Dyck199c3d62010-01-11 17:06:35 +00001685 CharUnits ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001686
Chris Lattnere5ed1512009-02-11 07:21:43 +00001687 // Handle GCC extension for pointer arithmetic on void* and function pointer
1688 // types.
1689 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Ken Dyck199c3d62010-01-11 17:06:35 +00001690 ElementSize = CharUnits::One();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001691 } else {
Ken Dyck199c3d62010-01-11 17:06:35 +00001692 ElementSize = CGF.getContext().getTypeSizeInChars(LHSElementType);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001693 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001694
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001695 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1696 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1697 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1698 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001699
Chris Lattnere5ed1512009-02-11 07:21:43 +00001700 // Optimize out the shift for element size of 1.
Ken Dyck199c3d62010-01-11 17:06:35 +00001701 if (ElementSize.isOne())
Chris Lattnere5ed1512009-02-11 07:21:43 +00001702 return BytesBetween;
Dan Gohmandf110942009-08-11 22:40:09 +00001703
1704 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001705 // pointer difference in C is only defined in the case where both operands
1706 // are pointing to elements of an array.
Ken Dyck199c3d62010-01-11 17:06:35 +00001707 Value *BytesPerElt =
1708 llvm::ConstantInt::get(ResultType, ElementSize.getQuantity());
Dan Gohmandf110942009-08-11 22:40:09 +00001709 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00001710 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001711}
1712
1713Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1714 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1715 // RHS to the same size as the LHS.
1716 Value *RHS = Ops.RHS;
1717 if (Ops.LHS->getType() != RHS->getType())
1718 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001719
Mike Stumpbe07f602009-12-14 21:58:14 +00001720 if (CGF.CatchUndefined
1721 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1722 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1723 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1724 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1725 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00001726 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00001727 CGF.EmitBlock(Cont);
1728 }
1729
Chris Lattner7f02f722007-08-24 05:35:26 +00001730 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1731}
1732
1733Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1734 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1735 // RHS to the same size as the LHS.
1736 Value *RHS = Ops.RHS;
1737 if (Ops.LHS->getType() != RHS->getType())
1738 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001739
Mike Stumpbe07f602009-12-14 21:58:14 +00001740 if (CGF.CatchUndefined
1741 && isa<llvm::IntegerType>(Ops.LHS->getType())) {
1742 unsigned Width = cast<llvm::IntegerType>(Ops.LHS->getType())->getBitWidth();
1743 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
1744 CGF.Builder.CreateCondBr(Builder.CreateICmpULT(RHS,
1745 llvm::ConstantInt::get(RHS->getType(), Width)),
Mike Stump15037ca2009-12-15 00:35:12 +00001746 Cont, CGF.getTrapBB());
Mike Stumpbe07f602009-12-14 21:58:14 +00001747 CGF.EmitBlock(Cont);
1748 }
1749
Douglas Gregorf6094622010-07-23 15:58:24 +00001750 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001751 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1752 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1753}
1754
1755Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1756 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001757 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001758 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00001759 QualType LHSTy = E->getLHS()->getType();
Eli Friedmanb81c7862009-12-11 07:36:43 +00001760 if (LHSTy->isMemberFunctionPointerType()) {
1761 Value *LHSPtr = CGF.EmitAnyExprToTemp(E->getLHS()).getAggregateAddr();
1762 Value *RHSPtr = CGF.EmitAnyExprToTemp(E->getRHS()).getAggregateAddr();
1763 llvm::Value *LHSFunc = Builder.CreateStructGEP(LHSPtr, 0);
1764 LHSFunc = Builder.CreateLoad(LHSFunc);
1765 llvm::Value *RHSFunc = Builder.CreateStructGEP(RHSPtr, 0);
1766 RHSFunc = Builder.CreateLoad(RHSFunc);
1767 Value *ResultF = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1768 LHSFunc, RHSFunc, "cmp.func");
1769 Value *NullPtr = llvm::Constant::getNullValue(LHSFunc->getType());
1770 Value *ResultNull = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1771 LHSFunc, NullPtr, "cmp.null");
1772 llvm::Value *LHSAdj = Builder.CreateStructGEP(LHSPtr, 1);
1773 LHSAdj = Builder.CreateLoad(LHSAdj);
1774 llvm::Value *RHSAdj = Builder.CreateStructGEP(RHSPtr, 1);
1775 RHSAdj = Builder.CreateLoad(RHSAdj);
1776 Value *ResultA = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1777 LHSAdj, RHSAdj, "cmp.adj");
1778 if (E->getOpcode() == BinaryOperator::EQ) {
1779 Result = Builder.CreateOr(ResultNull, ResultA, "or.na");
1780 Result = Builder.CreateAnd(Result, ResultF, "and.f");
1781 } else {
1782 assert(E->getOpcode() == BinaryOperator::NE &&
1783 "Member pointer comparison other than == or != ?");
1784 Result = Builder.CreateAnd(ResultNull, ResultA, "and.na");
1785 Result = Builder.CreateOr(Result, ResultF, "or.f");
1786 }
1787 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001788 Value *LHS = Visit(E->getLHS());
1789 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001790
Duncan Sandsf177d9d2010-02-15 16:14:01 +00001791 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001792 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001793 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00001794 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001795 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001796 LHS, RHS, "cmp");
1797 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001798 // Unsigned integers and pointers.
1799 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001800 LHS, RHS, "cmp");
1801 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001802
1803 // If this is a vector comparison, sign extend the result to the appropriate
1804 // vector integer type and return it (don't convert to bool).
1805 if (LHSTy->isVectorType())
1806 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001807
Chris Lattner7f02f722007-08-24 05:35:26 +00001808 } else {
1809 // Complex Comparison: can only be an equality comparison.
1810 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1811 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001812
John McCall183700f2009-09-21 23:43:11 +00001813 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001814
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001815 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00001816 if (CETy->isRealFloatingType()) {
1817 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1818 LHS.first, RHS.first, "cmp.r");
1819 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1820 LHS.second, RHS.second, "cmp.i");
1821 } else {
1822 // Complex comparisons can only be equality comparisons. As such, signed
1823 // and unsigned opcodes are the same.
1824 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1825 LHS.first, RHS.first, "cmp.r");
1826 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1827 LHS.second, RHS.second, "cmp.i");
1828 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001829
Chris Lattner7f02f722007-08-24 05:35:26 +00001830 if (E->getOpcode() == BinaryOperator::EQ) {
1831 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1832 } else {
1833 assert(E->getOpcode() == BinaryOperator::NE &&
1834 "Complex comparison other than == or != ?");
1835 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1836 }
1837 }
Nuno Lopes32f62092009-01-11 23:22:37 +00001838
1839 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001840}
1841
1842Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001843 bool Ignore = TestAndClearIgnoreResultAssign();
1844
1845 // __block variables need to have the rhs evaluated first, plus this should
1846 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00001847 Value *RHS = Visit(E->getRHS());
Mike Stumpb14e62d2009-12-16 02:57:00 +00001848 LValue LHS = EmitCheckedLValue(E->getLHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001849
Daniel Dunbared3849b2008-11-19 09:36:46 +00001850 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00001851 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1852 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00001853 // the assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001854 if (LHS.isBitField())
1855 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1856 &RHS);
1857 else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001858 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001859
1860 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001861 if (Ignore)
1862 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001863
1864 // Objective-C property assignment never reloads the value following a store.
1865 if (LHS.isPropertyRef() || LHS.isKVCRef())
1866 return RHS;
1867
1868 // If the lvalue is non-volatile, return the computed value of the assignment.
1869 if (!LHS.isVolatileQualified())
1870 return RHS;
1871
1872 // Otherwise, reload the value.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001873 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001874}
1875
1876Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00001877 const llvm::Type *ResTy = ConvertType(E->getType());
1878
Chris Lattner20eb09d2008-11-12 08:26:50 +00001879 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1880 // If we have 1 && X, just emit X without inserting the control flow.
1881 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1882 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001883 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00001884 // ZExt result to int or bool.
1885 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00001886 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001887
Chris Lattner7804bcb2009-10-17 04:24:20 +00001888 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001889 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00001890 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001891 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001892
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001893 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1894 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00001895
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001896 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1897 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1898
1899 // Any edges into the ContBlock are now from an (indeterminate number of)
1900 // edges from this first condition. All of these values will be false. Start
1901 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001902 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1903 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001904 PN->reserveOperandSpace(2); // Normal case, two inputs.
1905 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1906 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001907 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001908
Anders Carlsson72119a82010-02-04 17:18:07 +00001909 CGF.BeginConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00001910 CGF.EmitBlock(RHSBlock);
1911 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlsson72119a82010-02-04 17:18:07 +00001912 CGF.EndConditionalBranch();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001913
Chris Lattner7f02f722007-08-24 05:35:26 +00001914 // Reaquire the RHS block, as there may be subblocks inserted.
1915 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001916
1917 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1918 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00001919 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001920 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001921
Chris Lattner7f02f722007-08-24 05:35:26 +00001922 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00001923 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001924}
1925
1926Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner7804bcb2009-10-17 04:24:20 +00001927 const llvm::Type *ResTy = ConvertType(E->getType());
1928
Chris Lattner20eb09d2008-11-12 08:26:50 +00001929 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1930 // If we have 0 || X, just emit X without inserting the control flow.
1931 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1932 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001933 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00001934 // ZExt result to int or bool.
1935 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00001936 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001937
Chris Lattner7804bcb2009-10-17 04:24:20 +00001938 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001939 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00001940 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001941 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001942
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001943 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1944 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001945
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001946 // Branch on the LHS first. If it is true, go to the success (cont) block.
1947 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1948
1949 // Any edges into the ContBlock are now from an (indeterminate number of)
1950 // edges from this first condition. All of these values will be true. Start
1951 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001952 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1953 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001954 PN->reserveOperandSpace(2); // Normal case, two inputs.
1955 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1956 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001957 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001958
Anders Carlsson72119a82010-02-04 17:18:07 +00001959 CGF.BeginConditionalBranch();
Anders Carlsson33da07d2009-06-04 02:53:13 +00001960
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001961 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00001962 CGF.EmitBlock(RHSBlock);
1963 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001964
Anders Carlsson72119a82010-02-04 17:18:07 +00001965 CGF.EndConditionalBranch();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001966
Chris Lattner7f02f722007-08-24 05:35:26 +00001967 // Reaquire the RHS block, as there may be subblocks inserted.
1968 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001969
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001970 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1971 // into the phi node for the edge with the value of RHSCond.
1972 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001973 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001974
Chris Lattner7f02f722007-08-24 05:35:26 +00001975 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00001976 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001977}
1978
1979Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1980 CGF.EmitStmt(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00001981 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00001982 return Visit(E->getRHS());
1983}
1984
1985//===----------------------------------------------------------------------===//
1986// Other Operators
1987//===----------------------------------------------------------------------===//
1988
Chris Lattner9802a512008-11-12 08:55:54 +00001989/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1990/// expression is cheap enough and side-effect-free enough to evaluate
1991/// unconditionally instead of conditionally. This is used to convert control
1992/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00001993static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
1994 CodeGenFunction &CGF) {
Chris Lattner9802a512008-11-12 08:55:54 +00001995 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
Mike Stumpdf317bf2009-11-03 23:25:48 +00001996 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr(), CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001997
Chris Lattner9802a512008-11-12 08:55:54 +00001998 // TODO: Allow anything we can constant fold to an integer or fp constant.
1999 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
2000 isa<FloatingLiteral>(E))
2001 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002002
Chris Lattner9802a512008-11-12 08:55:54 +00002003 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2004 // X and Y are local variables.
2005 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2006 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002007 if (VD->hasLocalStorage() && !(CGF.getContext()
2008 .getCanonicalType(VD->getType())
2009 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002010 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002011
Chris Lattner9802a512008-11-12 08:55:54 +00002012 return false;
2013}
2014
2015
Chris Lattner7f02f722007-08-24 05:35:26 +00002016Value *ScalarExprEmitter::
2017VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002018 TestAndClearIgnoreResultAssign();
Chris Lattner31a09842008-11-12 08:04:58 +00002019 // If the condition constant folds and can be elided, try to avoid emitting
2020 // the condition and the dead arm.
2021 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00002022 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00002023 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00002024 std::swap(Live, Dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002025
Chris Lattner31a09842008-11-12 08:04:58 +00002026 // If the dead side doesn't have labels we need, and if the Live side isn't
2027 // the gnu missing ?: extension (which we could handle, but don't bother
2028 // to), just emit the Live part.
2029 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
2030 Live) // Live part isn't missing.
2031 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00002032 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002033
2034
Chris Lattner9802a512008-11-12 08:55:54 +00002035 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2036 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002037 // safe to evaluate the LHS and RHS unconditionally.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002038 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS(),
2039 CGF) &&
2040 isCheapEnoughToEvaluateUnconditionally(E->getRHS(), CGF)) {
Chris Lattner9802a512008-11-12 08:55:54 +00002041 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
2042 llvm::Value *LHS = Visit(E->getLHS());
2043 llvm::Value *RHS = Visit(E->getRHS());
2044 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2045 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002046
2047
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002048 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2049 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002050 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner035cf422008-11-12 08:08:13 +00002051 Value *CondVal = 0;
Chris Lattner31a09842008-11-12 08:04:58 +00002052
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002053 // If we don't have the GNU missing condition extension, emit a branch on bool
2054 // the normal way.
Chris Lattner12d152f2009-02-13 23:35:32 +00002055 if (E->getLHS()) {
2056 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
2057 // the branch on bool.
2058 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
2059 } else {
2060 // Otherwise, for the ?: extension, evaluate the conditional and then
2061 // convert it to bool the hard way. We do this explicitly because we need
2062 // the unconverted value for the missing middle value of the ?:.
Chris Lattner035cf422008-11-12 08:08:13 +00002063 CondVal = CGF.EmitScalarExpr(E->getCond());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002064
Chris Lattner12d152f2009-02-13 23:35:32 +00002065 // In some cases, EmitScalarConversion will delete the "CondVal" expression
2066 // if there are no extra uses (an optimization). Inhibit this by making an
2067 // extra dead use, because we're going to add a use of CondVal later. We
2068 // don't use the builder for this, because we don't want it to get optimized
2069 // away. This leaves dead code, but the ?: extension isn't common.
2070 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
2071 Builder.GetInsertBlock());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002072
Chris Lattner035cf422008-11-12 08:08:13 +00002073 Value *CondBoolVal =
2074 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
2075 CGF.getContext().BoolTy);
2076 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00002077 }
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002078
Anders Carlsson72119a82010-02-04 17:18:07 +00002079 CGF.BeginConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002080 CGF.EmitBlock(LHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002081
Chris Lattner7f02f722007-08-24 05:35:26 +00002082 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00002083 Value *LHS;
2084 if (E->getLHS())
Eli Friedman856226c2008-05-16 20:38:39 +00002085 LHS = Visit(E->getLHS());
Chris Lattnera21ddb32007-11-26 01:40:58 +00002086 else // Perform promotions, to handle cases like "short ?: int"
2087 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002088
Anders Carlsson72119a82010-02-04 17:18:07 +00002089 CGF.EndConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002090 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00002091 CGF.EmitBranch(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002092
Anders Carlsson72119a82010-02-04 17:18:07 +00002093 CGF.BeginConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002094 CGF.EmitBlock(RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002095
Eli Friedman856226c2008-05-16 20:38:39 +00002096 Value *RHS = Visit(E->getRHS());
Anders Carlsson72119a82010-02-04 17:18:07 +00002097 CGF.EndConditionalBranch();
Chris Lattner7f02f722007-08-24 05:35:26 +00002098 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00002099 CGF.EmitBranch(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002100
Chris Lattner7f02f722007-08-24 05:35:26 +00002101 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002102
Eli Friedman48daf592009-12-07 20:25:53 +00002103 // If the LHS or RHS is a throw expression, it will be legitimately null.
2104 if (!LHS)
2105 return RHS;
2106 if (!RHS)
2107 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002108
Chris Lattner7f02f722007-08-24 05:35:26 +00002109 // Create a PHI node for the real part.
2110 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
2111 PN->reserveOperandSpace(2);
2112 PN->addIncoming(LHS, LHSBlock);
2113 PN->addIncoming(RHS, RHSBlock);
2114 return PN;
2115}
2116
2117Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002118 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002119}
2120
Chris Lattner2202bce2007-11-30 17:56:23 +00002121Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002122 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002123 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2124
2125 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002126 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002127 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2128
Mike Stump7f79f9b2009-05-29 15:46:01 +00002129 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002130 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002131}
2132
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002133Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump08920992009-03-07 02:35:30 +00002134 return CGF.BuildBlockLiteralTmp(BE);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002135}
2136
Chris Lattner7f02f722007-08-24 05:35:26 +00002137//===----------------------------------------------------------------------===//
2138// Entry Point into this File
2139//===----------------------------------------------------------------------===//
2140
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002141/// EmitScalarExpr - Emit the computation of the specified expression of scalar
2142/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002143Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002144 assert(E && !hasAggregateLLVMType(E->getType()) &&
2145 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002146
Mike Stump7f79f9b2009-05-29 15:46:01 +00002147 return ScalarExprEmitter(*this, IgnoreResultAssign)
2148 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00002149}
Chris Lattner3707b252007-08-26 06:48:56 +00002150
2151/// EmitScalarConversion - Emit a conversion from the specified type to the
2152/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002153Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
2154 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00002155 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
2156 "Invalid scalar expression to emit");
2157 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
2158}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002159
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002160/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
2161/// type to the specified destination type, where the destination type is an
2162/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002163Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
2164 QualType SrcTy,
2165 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00002166 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002167 "Invalid complex -> scalar conversion");
2168 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
2169 DstTy);
2170}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00002171
Chris Lattner8c11a652010-06-26 22:09:34 +00002172
2173llvm::Value *CodeGenFunction::
2174EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2175 bool isInc, bool isPre) {
2176 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
2177}
2178
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002179LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
2180 llvm::Value *V;
2181 // object->isa or (*object).isa
2182 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002183 // build Class* type
2184 const llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002185
2186 Expr *BaseExpr = E->getBase();
2187 if (BaseExpr->isLvalue(getContext()) != Expr::LV_Valid) {
2188 V = CreateTempAlloca(ClassPtrTy, "resval");
2189 llvm::Value *Src = EmitScalarExpr(BaseExpr);
2190 Builder.CreateStore(Src, V);
Fariborz Jahanian9f9efe62010-03-03 22:09:47 +00002191 LValue LV = LValue::MakeAddr(V, MakeQualifiers(E->getType()));
2192 V = ScalarExprEmitter(*this).EmitLoadOfLValue(LV, E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00002193 }
2194 else {
2195 if (E->isArrow())
2196 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
2197 else
2198 V = EmitLValue(BaseExpr).getAddress();
2199 }
2200
2201 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00002202 ClassPtrTy = ClassPtrTy->getPointerTo();
2203 V = Builder.CreateBitCast(V, ClassPtrTy);
2204 LValue LV = LValue::MakeAddr(V, MakeQualifiers(E->getType()));
2205 return LV;
2206}
2207
Douglas Gregor6a03e342010-04-23 04:16:32 +00002208
2209LValue CodeGenFunction::EmitCompoundAssignOperatorLValue(
2210 const CompoundAssignOperator *E) {
2211 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002212 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00002213 switch (E->getOpcode()) {
2214#define COMPOUND_OP(Op) \
2215 case BinaryOperator::Op##Assign: \
2216 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002217 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00002218 COMPOUND_OP(Mul);
2219 COMPOUND_OP(Div);
2220 COMPOUND_OP(Rem);
2221 COMPOUND_OP(Add);
2222 COMPOUND_OP(Sub);
2223 COMPOUND_OP(Shl);
2224 COMPOUND_OP(Shr);
2225 COMPOUND_OP(And);
2226 COMPOUND_OP(Xor);
2227 COMPOUND_OP(Or);
2228#undef COMPOUND_OP
2229
2230 case BinaryOperator::PtrMemD:
2231 case BinaryOperator::PtrMemI:
2232 case BinaryOperator::Mul:
2233 case BinaryOperator::Div:
2234 case BinaryOperator::Rem:
2235 case BinaryOperator::Add:
2236 case BinaryOperator::Sub:
2237 case BinaryOperator::Shl:
2238 case BinaryOperator::Shr:
2239 case BinaryOperator::LT:
2240 case BinaryOperator::GT:
2241 case BinaryOperator::LE:
2242 case BinaryOperator::GE:
2243 case BinaryOperator::EQ:
2244 case BinaryOperator::NE:
2245 case BinaryOperator::And:
2246 case BinaryOperator::Xor:
2247 case BinaryOperator::Or:
2248 case BinaryOperator::LAnd:
2249 case BinaryOperator::LOr:
2250 case BinaryOperator::Assign:
2251 case BinaryOperator::Comma:
2252 assert(false && "Not valid compound assignment operators");
2253 break;
2254 }
2255
2256 llvm_unreachable("Unhandled compound assignment operator");
2257}