blob: 37d2995142aacca5363337031d89f1b36eefc097 [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"
15#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000017#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000018#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000019#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Anders Carlsson85f9bce2007-10-29 05:01:08 +000023#include "llvm/GlobalVariable.h"
Anders Carlsson7c50aca2007-10-15 20:28:48 +000024#include "llvm/Intrinsics.h"
Mike Stump2add4732009-04-01 20:28:16 +000025#include "llvm/Module.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000026#include "llvm/Support/Compiler.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 Lattner7f02f722007-08-24 05:35:26 +000043 const BinaryOperator *E;
44};
45
46namespace {
47class VISIBILITY_HIDDEN ScalarExprEmitter
48 : public StmtVisitor<ScalarExprEmitter, Value*> {
49 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000050 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000051 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000052 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000053public:
54
Mike Stump7f79f9b2009-05-29 15:46:01 +000055 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Owen Andersona1cf15f2009-07-14 23:10:40 +000056 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
57 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000058 }
Chris Lattner7f02f722007-08-24 05:35:26 +000059
60 //===--------------------------------------------------------------------===//
61 // Utilities
62 //===--------------------------------------------------------------------===//
63
Mike Stump7f79f9b2009-05-29 15:46:01 +000064 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000065 bool I = IgnoreResultAssign;
66 IgnoreResultAssign = false;
67 return I;
68 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000069
Chris Lattner7f02f722007-08-24 05:35:26 +000070 const llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
71 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
72
73 Value *EmitLoadOfLValue(LValue LV, QualType T) {
Chris Lattner9b655512007-08-31 22:49:20 +000074 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000075 }
76
77 /// EmitLoadOfLValue - Given an expression with complex type that represents a
78 /// value l-value, this method emits the address of the l-value, then loads
79 /// and returns the result.
80 Value *EmitLoadOfLValue(const Expr *E) {
Chris Lattner7f02f722007-08-24 05:35:26 +000081 return EmitLoadOfLValue(EmitLValue(E), E->getType());
82 }
83
Chris Lattner9abc84e2007-08-26 16:42:57 +000084 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +000085 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +000086 Value *EmitConversionToBool(Value *Src, QualType DstTy);
87
Chris Lattner3707b252007-08-26 06:48:56 +000088 /// EmitScalarConversion - Emit a conversion from the specified type to the
89 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +000090 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
91
92 /// EmitComplexToScalarConversion - Emit a conversion from the specified
93 /// complex type to the specified destination type, where the destination
94 /// type is an LLVM scalar type.
95 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
96 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +000097
Chris Lattner7f02f722007-08-24 05:35:26 +000098 //===--------------------------------------------------------------------===//
99 // Visitor Methods
100 //===--------------------------------------------------------------------===//
101
102 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000103 S->dump(CGF.getContext().getSourceManager());
Chris Lattner7f02f722007-08-24 05:35:26 +0000104 assert(0 && "Stmt can't have complex result type!");
105 return 0;
106 }
107 Value *VisitExpr(Expr *S);
108 Value *VisitParenExpr(ParenExpr *PE) { return Visit(PE->getSubExpr()); }
109
110 // Leaves.
111 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000112 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000113 }
114 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000115 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000116 }
117 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000118 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000119 }
Nate Begemane7579b52007-11-15 05:40:03 +0000120 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000121 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000122 }
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000123 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000124 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000125 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000126 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000127 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Anders Carlsson3f704562008-12-21 22:39:40 +0000128 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000129 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000130 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroffec0550f2007-10-15 20:41:53 +0000131 CGF.getContext().typesAreCompatible(
132 E->getArgType1(), E->getArgType2()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000133 }
Sebastian Redl05189992008-11-11 17:56:53 +0000134 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000135 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbar54d19092008-08-16 01:41:47 +0000136 llvm::Value *V =
Owen Anderson0032b272009-08-13 21:57:51 +0000137 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()),
Daniel Dunbar54d19092008-08-16 01:41:47 +0000138 CGF.GetIDForAddrOfLabel(E->getLabel()));
139
140 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000141 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000142
143 // l-values.
144 Value *VisitDeclRefExpr(DeclRefExpr *E) {
145 if (const EnumConstantDecl *EC = dyn_cast<EnumConstantDecl>(E->getDecl()))
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000146 return llvm::ConstantInt::get(VMContext, EC->getInitVal());
Chris Lattner7f02f722007-08-24 05:35:26 +0000147 return EmitLoadOfLValue(E);
148 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000149 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
150 return CGF.EmitObjCSelectorExpr(E);
151 }
152 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
153 return CGF.EmitObjCProtocolExpr(E);
154 }
155 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
156 return EmitLoadOfLValue(E);
157 }
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000158 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar85c59ed2008-08-29 08:11:39 +0000159 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000160 }
Fariborz Jahanian43f44702008-11-22 22:30:21 +0000161 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
162 return EmitLoadOfLValue(E);
163 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000164 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
165 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000166 }
167
Chris Lattner7f02f722007-08-24 05:35:26 +0000168 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000169 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000170 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begeman213541a2008-04-18 23:10:10 +0000171 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000172 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
173 return EmitLoadOfLValue(E);
174 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000175 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnereaf2bb82009-02-24 22:18:39 +0000176 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
177 return EmitLValue(E).getAddress();
178 }
179
Chris Lattnerd9f69102008-08-10 01:53:14 +0000180 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel35634f52007-10-24 17:18:43 +0000181
182 Value *VisitInitListExpr(InitListExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000183 bool Ignore = TestAndClearIgnoreResultAssign();
184 (void)Ignore;
185 assert (Ignore == false && "init list ignored");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000186 unsigned NumInitElements = E->getNumInits();
187
Douglas Gregora9c87802009-01-29 19:42:23 +0000188 if (E->hadArrayRangeDesignator()) {
189 CGF.ErrorUnsupported(E, "GNU array range designator extension");
190 }
191
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000192 const llvm::VectorType *VType =
Anders Carlssonf6884ac2008-01-29 01:15:48 +0000193 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
194
195 // We have a scalar in braces. Just use the first element.
196 if (!VType)
197 return Visit(E->getInit(0));
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000198
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000199 unsigned NumVectorElements = VType->getNumElements();
200 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000201
202 // Emit individual vector element stores.
Owen Anderson03e20502009-07-30 23:11:26 +0000203 llvm::Value *V = llvm::UndefValue::get(VType);
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000204
Anders Carlsson222d2c82007-12-18 02:45:33 +0000205 // Emit initializers
206 unsigned i;
207 for (i = 0; i < NumInitElements; ++i) {
Devang Patela83cc332007-10-24 18:05:48 +0000208 Value *NewV = Visit(E->getInit(i));
Owen Anderson0032b272009-08-13 21:57:51 +0000209 Value *Idx =
210 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
Devang Patela83cc332007-10-24 18:05:48 +0000211 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel35634f52007-10-24 17:18:43 +0000212 }
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000213
214 // Emit remaining default initializers
215 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
Owen Anderson0032b272009-08-13 21:57:51 +0000216 Value *Idx =
217 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000218 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000219 V = Builder.CreateInsertElement(V, NewV, Idx);
220 }
221
Devang Patela83cc332007-10-24 18:05:48 +0000222 return V;
Devang Patel35634f52007-10-24 17:18:43 +0000223 }
Chris Lattner04421082008-04-08 04:40:51 +0000224
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000225 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Owen Andersonc9c88b42009-07-31 20:28:54 +0000226 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000227 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000228 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
Eli Friedmanc62aad82009-04-20 03:54:15 +0000229 Value *VisitCastExpr(const CastExpr *E) {
230 // Make sure to evaluate VLA bounds now so that we have them for later.
231 if (E->getType()->isVariablyModifiedType())
232 CGF.EmitVLASize(E->getType());
233
Chris Lattner7f02f722007-08-24 05:35:26 +0000234 return EmitCastExpr(E->getSubExpr(), E->getType());
235 }
236 Value *EmitCastExpr(const Expr *E, QualType T);
237
238 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000239 if (E->getCallReturnType()->isReferenceType())
240 return EmitLoadOfLValue(E);
241
Chris Lattner9b655512007-08-31 22:49:20 +0000242 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000243 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000244
Chris Lattner33793202007-08-31 22:09:40 +0000245 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000246
Mike Stumpa99038c2009-02-28 09:07:16 +0000247 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattner33793202007-08-31 22:09:40 +0000248
Chris Lattner7f02f722007-08-24 05:35:26 +0000249 // Unary Operators.
250 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
251 Value *VisitUnaryPostDec(const UnaryOperator *E) {
252 return VisitPrePostIncDec(E, false, false);
253 }
254 Value *VisitUnaryPostInc(const UnaryOperator *E) {
255 return VisitPrePostIncDec(E, true, false);
256 }
257 Value *VisitUnaryPreDec(const UnaryOperator *E) {
258 return VisitPrePostIncDec(E, false, true);
259 }
260 Value *VisitUnaryPreInc(const UnaryOperator *E) {
261 return VisitPrePostIncDec(E, true, true);
262 }
263 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
264 return EmitLValue(E->getSubExpr()).getAddress();
265 }
266 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
267 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000268 // This differs from gcc, though, most likely due to a bug in gcc.
269 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000270 return Visit(E->getSubExpr());
271 }
272 Value *VisitUnaryMinus (const UnaryOperator *E);
273 Value *VisitUnaryNot (const UnaryOperator *E);
274 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000275 Value *VisitUnaryReal (const UnaryOperator *E);
276 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000277 Value *VisitUnaryExtension(const UnaryOperator *E) {
278 return Visit(E->getSubExpr());
279 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000280 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000281
282 // C++
Chris Lattner04421082008-04-08 04:40:51 +0000283 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
284 return Visit(DAE->getExpr());
285 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000286 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
287 return CGF.LoadCXXThis();
288 }
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000289
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000290 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlsson30824632009-05-31 00:09:15 +0000291 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000292 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000293 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
294 return CGF.EmitCXXNewExpr(E);
295 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000296 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
297 CGF.EmitCXXDeleteExpr(E);
298 return 0;
299 }
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000300
Chris Lattner7f02f722007-08-24 05:35:26 +0000301 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000302 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stump035cf892009-04-02 18:15:54 +0000303 if (CGF.getContext().getLangOptions().OverflowChecking
304 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +0000305 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +0000306 if (Ops.LHS->getType()->isFPOrFPVector())
307 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000308 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
309 }
Mike Stump2add4732009-04-01 20:28:16 +0000310 /// Create a binary op that checks for overflow.
311 /// Currently only supports +, - and *.
312 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner7f02f722007-08-24 05:35:26 +0000313 Value *EmitDiv(const BinOpInfo &Ops);
314 Value *EmitRem(const BinOpInfo &Ops);
315 Value *EmitAdd(const BinOpInfo &Ops);
316 Value *EmitSub(const BinOpInfo &Ops);
317 Value *EmitShl(const BinOpInfo &Ops);
318 Value *EmitShr(const BinOpInfo &Ops);
319 Value *EmitAnd(const BinOpInfo &Ops) {
320 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
321 }
322 Value *EmitXor(const BinOpInfo &Ops) {
323 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
324 }
325 Value *EmitOr (const BinOpInfo &Ops) {
326 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
327 }
328
Chris Lattner1f1ded92007-08-24 21:00:35 +0000329 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner3ccf7742007-08-26 21:41:21 +0000330 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000331 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
332
333 // Binary operators and binary compound assignment operators.
334#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000335 Value *VisitBin ## OP(const BinaryOperator *E) { \
336 return Emit ## OP(EmitBinOps(E)); \
337 } \
338 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
339 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000340 }
341 HANDLEBINOP(Mul);
342 HANDLEBINOP(Div);
343 HANDLEBINOP(Rem);
344 HANDLEBINOP(Add);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000345 HANDLEBINOP(Sub);
Chris Lattner1f1ded92007-08-24 21:00:35 +0000346 HANDLEBINOP(Shl);
347 HANDLEBINOP(Shr);
348 HANDLEBINOP(And);
349 HANDLEBINOP(Xor);
350 HANDLEBINOP(Or);
351#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000352
Chris Lattner7f02f722007-08-24 05:35:26 +0000353 // Comparisons.
354 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
355 unsigned SICmpOpc, unsigned FCmpOpc);
356#define VISITCOMP(CODE, UI, SI, FP) \
357 Value *VisitBin##CODE(const BinaryOperator *E) { \
358 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
359 llvm::FCmpInst::FP); }
360 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
361 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
362 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
363 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
364 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
365 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
366#undef VISITCOMP
367
368 Value *VisitBinAssign (const BinaryOperator *E);
369
370 Value *VisitBinLAnd (const BinaryOperator *E);
371 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000372 Value *VisitBinComma (const BinaryOperator *E);
373
374 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000375 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000376 Value *VisitConditionalOperator(const ConditionalOperator *CO);
377 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000378 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000379 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
380 return CGF.EmitObjCStringLiteral(E);
381 }
382};
383} // end anonymous namespace.
384
385//===----------------------------------------------------------------------===//
386// Utilities
387//===----------------------------------------------------------------------===//
388
Chris Lattner9abc84e2007-08-26 16:42:57 +0000389/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000390/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000391Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
392 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
393
394 if (SrcType->isRealFloatingType()) {
395 // Compare against 0.0 for fp scalars.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000396 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000397 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
398 }
399
Anders Carlsson237957c2009-08-09 18:26:27 +0000400 if (SrcType->isMemberPointerType()) {
401 // FIXME: This is ABI specific.
402
403 // Compare against -1.
404 llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType());
405 return Builder.CreateICmpNE(Src, NegativeOne, "tobool");
406 }
407
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000408 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000409 "Unknown scalar type to convert");
410
411 // Because of the type rules of C, we often end up computing a logical value,
412 // then zero extending it to int, then wanting it as a logical value again.
413 // Optimize this common case.
414 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
Owen Anderson0032b272009-08-13 21:57:51 +0000415 if (ZI->getOperand(0)->getType() ==
416 llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
Chris Lattner9abc84e2007-08-26 16:42:57 +0000417 Value *Result = ZI->getOperand(0);
Eli Friedman356916e2008-01-29 18:13:51 +0000418 // If there aren't any more uses, zap the instruction to save space.
419 // Note that there can be more uses, for example if this
420 // is the result of an assignment.
421 if (ZI->use_empty())
422 ZI->eraseFromParent();
Chris Lattner9abc84e2007-08-26 16:42:57 +0000423 return Result;
424 }
425 }
426
427 // Compare against an integer or pointer null.
Owen Andersonc9c88b42009-07-31 20:28:54 +0000428 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattner9abc84e2007-08-26 16:42:57 +0000429 return Builder.CreateICmpNE(Src, Zero, "tobool");
430}
431
Chris Lattner3707b252007-08-26 06:48:56 +0000432/// EmitScalarConversion - Emit a conversion from the specified type to the
433/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000434Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
435 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000436 SrcType = CGF.getContext().getCanonicalType(SrcType);
437 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000438 if (SrcType == DstType) return Src;
Chris Lattnercf289082007-08-26 07:21:11 +0000439
440 if (DstType->isVoidType()) return 0;
Owen Anderson0032b272009-08-13 21:57:51 +0000441
442 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
Chris Lattner3707b252007-08-26 06:48:56 +0000443
444 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000445 if (DstType->isBooleanType())
446 return EmitConversionToBool(Src, SrcType);
Chris Lattner3707b252007-08-26 06:48:56 +0000447
448 const llvm::Type *DstTy = ConvertType(DstType);
449
450 // Ignore conversions like int -> uint.
451 if (Src->getType() == DstTy)
452 return Src;
453
Daniel Dunbar270cc662008-08-25 09:51:32 +0000454 // Handle pointer conversions next: pointers can only be converted
455 // to/from other pointers and integers. Check for pointer types in
456 // terms of LLVM, as some native types (like Obj-C id) may map to a
457 // pointer type.
458 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000459 // The source value may be an integer, or a pointer.
Fariborz Jahanianfa9f8b42009-07-28 22:00:58 +0000460 if (isa<llvm::PointerType>(Src->getType())) {
461 // Some heavy lifting for derived to base conversion.
Fariborz Jahaniana91d6a62009-07-29 00:44:13 +0000462 if (const CXXRecordDecl *ClassDecl =
463 SrcType->getCXXRecordDeclForPointerType())
464 if (const CXXRecordDecl *BaseClassDecl =
465 DstType->getCXXRecordDeclForPointerType())
466 Src = CGF.AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl);
Chris Lattner3707b252007-08-26 06:48:56 +0000467 return Builder.CreateBitCast(Src, DstTy, "conv");
Fariborz Jahanianfa9f8b42009-07-28 22:00:58 +0000468 }
Chris Lattner3707b252007-08-26 06:48:56 +0000469 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000470 // First, convert to the correct width so that we control the kind of
471 // extension.
Owen Anderson0032b272009-08-13 21:57:51 +0000472 const llvm::Type *MiddleTy =
473 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
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 }
480
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 }
486
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
490 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
491 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);
Owen Anderson0032b272009-08-13 21:57:51 +0000495 llvm::Value *Idx =
496 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000497 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
498
499 // Splat the element across to all elements
500 llvm::SmallVector<llvm::Constant*, 16> Args;
501 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
502 for (unsigned i = 0; i < NumElements; i++)
Owen Anderson0032b272009-08-13 21:57:51 +0000503 Args.push_back(llvm::ConstantInt::get(
504 llvm::Type::getInt32Ty(VMContext), 0));
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000505
Owen Anderson4a289322009-07-28 21:22:35 +0000506 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000507 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
508 return Yay;
509 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000510
Chris Lattner3b1ae002008-02-02 04:51:41 +0000511 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000512 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000513 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000514 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000515
Chris Lattner3707b252007-08-26 06:48:56 +0000516 // Finally, we have the arithmetic types: real int/float.
517 if (isa<llvm::IntegerType>(Src->getType())) {
518 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000519 if (isa<llvm::IntegerType>(DstTy))
520 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
521 else if (InputSigned)
522 return Builder.CreateSIToFP(Src, DstTy, "conv");
523 else
524 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000525 }
526
527 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
528 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000529 if (DstType->isSignedIntegerType())
530 return Builder.CreateFPToSI(Src, DstTy, "conv");
531 else
532 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000533 }
534
535 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000536 if (DstTy->getTypeID() < Src->getType()->getTypeID())
537 return Builder.CreateFPTrunc(Src, DstTy, "conv");
538 else
539 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000540}
541
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000542/// EmitComplexToScalarConversion - Emit a conversion from the specified
543/// complex type to the specified destination type, where the destination
544/// type is an LLVM scalar type.
545Value *ScalarExprEmitter::
546EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
547 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000548 // Get the source element type.
Chris Lattner96196622008-07-26 22:37:01 +0000549 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnered70f0a2007-08-26 16:52:28 +0000550
551 // Handle conversions to bool first, they are special: comparisons against 0.
552 if (DstTy->isBooleanType()) {
553 // Complex != 0 -> (Real != 0) | (Imag != 0)
554 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
555 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
556 return Builder.CreateOr(Src.first, Src.second, "tobool");
557 }
558
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000559 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
560 // the imaginary part of the complex value is discarded and the value of the
561 // real part is converted according to the conversion rules for the
562 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000563 return EmitScalarConversion(Src.first, SrcTy, DstTy);
564}
565
566
Chris Lattner7f02f722007-08-24 05:35:26 +0000567//===----------------------------------------------------------------------===//
568// Visitor Methods
569//===----------------------------------------------------------------------===//
570
571Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000572 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000573 if (E->getType()->isVoidType())
574 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000575 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000576}
577
Eli Friedmand38617c2008-05-14 19:38:39 +0000578Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
579 llvm::SmallVector<llvm::Constant*, 32> indices;
580 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
581 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
582 }
583 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
584 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Owen Anderson4a289322009-07-28 21:22:35 +0000585 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
Eli Friedmand38617c2008-05-14 19:38:39 +0000586 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
587}
588
Chris Lattner7f02f722007-08-24 05:35:26 +0000589Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000590 TestAndClearIgnoreResultAssign();
591
Chris Lattner7f02f722007-08-24 05:35:26 +0000592 // Emit subscript expressions in rvalue context's. For most cases, this just
593 // loads the lvalue formed by the subscript expr. However, we have to be
594 // careful, because the base of a vector subscript is occasionally an rvalue,
595 // so we can't get it as an lvalue.
596 if (!E->getBase()->getType()->isVectorType())
597 return EmitLoadOfLValue(E);
598
599 // Handle the vector case. The base must be a vector, the index must be an
600 // integer value.
601 Value *Base = Visit(E->getBase());
602 Value *Idx = Visit(E->getIdx());
Eli Friedmandaa24a22009-03-28 02:45:41 +0000603 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Owen Anderson0032b272009-08-13 21:57:51 +0000604 Idx = Builder.CreateIntCast(Idx,
605 llvm::Type::getInt32Ty(CGF.getLLVMContext()),
606 IdxSigned,
Eli Friedman515ff5a2009-03-28 03:27:06 +0000607 "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000608 return Builder.CreateExtractElement(Base, Idx, "vecext");
609}
610
611/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
612/// also handle things like function to pointer-to-function decay, and array to
613/// pointer decay.
614Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
615 const Expr *Op = E->getSubExpr();
616
617 // If this is due to array->pointer conversion, emit the array expression as
618 // an l-value.
619 if (Op->getType()->isArrayType()) {
Anders Carlsson112a0a82009-08-07 23:48:20 +0000620 assert(E->getCastKind() == CastExpr::CK_ArrayToPointerDecay);
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000621 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000622
Eli Friedmandaa24a22009-03-28 02:45:41 +0000623 // Note that VLA pointers are always decayed, so we don't need to do
624 // anything here.
Eli Friedman8f39f5e2008-12-20 23:11:59 +0000625 if (!Op->getType()->isVariableArrayType()) {
626 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
627 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
628 ->getElementType()) &&
629 "Expected pointer to array");
630 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar662174c82008-08-29 17:28:43 +0000631 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000632
633 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattnerf31627f2008-07-23 06:31:27 +0000634 // types as well (e.g. void*) and can be implicitly converted to integer.
635 const llvm::Type *DestTy = ConvertType(E->getType());
636 if (V->getType() != DestTy) {
637 if (isa<llvm::PointerType>(DestTy))
638 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
639 else {
640 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
641 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
642 }
643 }
Chris Lattnera9e63722007-12-12 04:13:20 +0000644 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +0000645 }
Eli Friedmandaa24a22009-03-28 02:45:41 +0000646
Chris Lattner7f02f722007-08-24 05:35:26 +0000647 return EmitCastExpr(Op, E->getType());
648}
649
650
651// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
652// have to handle a more broad range of conversions than explicit casts, as they
653// handle things like function to ptr-to-function decay etc.
654Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000655 if (!DestTy->isVoidType())
656 TestAndClearIgnoreResultAssign();
657
Chris Lattner58a2e942007-08-26 07:26:12 +0000658 // Handle cases where the source is an non-complex type.
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000659
660 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3707b252007-08-26 06:48:56 +0000661 Value *Src = Visit(const_cast<Expr*>(E));
662
Chris Lattner3707b252007-08-26 06:48:56 +0000663 // Use EmitScalarConversion to perform the conversion.
664 return EmitScalarConversion(Src, E->getType(), DestTy);
665 }
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000666
Chris Lattner9b2dc282008-04-04 16:54:41 +0000667 if (E->getType()->isAnyComplexType()) {
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000668 // Handle cases where the source is a complex type.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000669 bool IgnoreImag = true;
670 bool IgnoreImagAssign = true;
671 bool IgnoreReal = IgnoreResultAssign;
672 bool IgnoreRealAssign = IgnoreResultAssign;
673 if (DestTy->isBooleanType())
674 IgnoreImagAssign = IgnoreImag = false;
675 else if (DestTy->isVoidType()) {
676 IgnoreReal = IgnoreImag = false;
677 IgnoreRealAssign = IgnoreImagAssign = true;
678 }
679 CodeGenFunction::ComplexPairTy V
680 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
681 IgnoreImagAssign);
682 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000683 }
Chris Lattner10b00cf2007-08-26 07:16:41 +0000684
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000685 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
686 // evaluate the result and return.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000687 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner19a1d7c2008-02-16 23:55:16 +0000688 return 0;
Chris Lattner7f02f722007-08-24 05:35:26 +0000689}
690
Chris Lattner33793202007-08-31 22:09:40 +0000691Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner91d723d2008-07-26 20:23:23 +0000692 return CGF.EmitCompoundStmt(*E->getSubStmt(),
693 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +0000694}
695
Mike Stumpa99038c2009-02-28 09:07:16 +0000696Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
697 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stump4e7a1f72009-02-21 20:00:35 +0000698}
Chris Lattner33793202007-08-31 22:09:40 +0000699
Chris Lattner7f02f722007-08-24 05:35:26 +0000700//===----------------------------------------------------------------------===//
701// Unary Operators
702//===----------------------------------------------------------------------===//
703
704Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattnerdfce2a52007-08-24 16:24:49 +0000705 bool isInc, bool isPre) {
Chris Lattner7f02f722007-08-24 05:35:26 +0000706 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedmanf52bbeb2009-03-23 03:00:06 +0000707 QualType ValTy = E->getSubExpr()->getType();
708 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Owen Anderson0032b272009-08-13 21:57:51 +0000709
710 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
Chris Lattner7f02f722007-08-24 05:35:26 +0000711
712 int AmountVal = isInc ? 1 : -1;
Eli Friedmandaa24a22009-03-28 02:45:41 +0000713
714 if (ValTy->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +0000715 ValTy->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +0000716 // The amount of the addition/subtraction needs to account for the VLA size
717 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
718 }
719
Chris Lattner7f02f722007-08-24 05:35:26 +0000720 Value *NextVal;
Chris Lattner8cc9d082009-03-18 04:25:13 +0000721 if (const llvm::PointerType *PT =
722 dyn_cast<llvm::PointerType>(InVal->getType())) {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000723 llvm::Constant *Inc =
Owen Anderson0032b272009-08-13 21:57:51 +0000724 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal);
Chris Lattner8cc9d082009-03-18 04:25:13 +0000725 if (!isa<llvm::FunctionType>(PT->getElementType())) {
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000726 QualType PTEE = ValTy->getPointeeType();
727 if (const ObjCInterfaceType *OIT =
728 dyn_cast<ObjCInterfaceType>(PTEE)) {
729 // Handle interface types, which are not represented with a concrete type.
730 int size = CGF.getContext().getTypeSize(OIT) / 8;
731 if (!isInc)
732 size = -size;
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000733 Inc = llvm::ConstantInt::get(Inc->getType(), size);
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000734 const llvm::Type *i8Ty =
Owen Anderson0032b272009-08-13 21:57:51 +0000735 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000736 InVal = Builder.CreateBitCast(InVal, i8Ty);
737 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
738 llvm::Value *lhs = LV.getAddress();
Owen Anderson96e0fc72009-07-29 22:16:19 +0000739 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
Fariborz Jahanian62a11a72009-07-16 22:04:59 +0000740 LV = LValue::MakeAddr(lhs, ValTy.getCVRQualifiers(),
741 CGF.getContext().getObjCGCAttrKind(ValTy));
Mike Stumpb3589f42009-07-30 22:28:39 +0000742 } else
Dan Gohman664f8932009-08-12 00:33:55 +0000743 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
Chris Lattner8cc9d082009-03-18 04:25:13 +0000744 } else {
Owen Andersona1cf15f2009-07-14 23:10:40 +0000745 const llvm::Type *i8Ty =
Owen Anderson0032b272009-08-13 21:57:51 +0000746 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Chris Lattner8cc9d082009-03-18 04:25:13 +0000747 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
748 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
749 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
750 }
Owen Anderson0032b272009-08-13 21:57:51 +0000751 } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) {
Chris Lattnerdb3bd4b2009-02-11 07:40:06 +0000752 // Bool++ is an interesting case, due to promotion rules, we get:
753 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
754 // Bool = ((int)Bool+1) != 0
755 // An interesting aspect of this is that increment is always true.
756 // Decrement does not have this property.
Owen Anderson3b144ba2009-07-31 17:39:36 +0000757 NextVal = llvm::ConstantInt::getTrue(VMContext);
Chris Lattner87415d22009-06-17 06:36:24 +0000758 } else if (isa<llvm::IntegerType>(InVal->getType())) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000759 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Dan Gohmanbf933a02009-08-12 01:16:29 +0000760
761 // Signed integer overflow is undefined behavior.
762 if (ValTy->isSignedIntegerType())
763 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
764 else
765 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000766 } else {
767 // Add the inc/dec to the real part.
Owen Anderson0032b272009-08-13 21:57:51 +0000768 if (InVal->getType() == llvm::Type::getFloatTy(VMContext))
Devang Patele9b8c0a2007-10-30 20:59:40 +0000769 NextVal =
Owen Andersonbc0a2222009-07-27 21:00:51 +0000770 llvm::ConstantFP::get(VMContext,
771 llvm::APFloat(static_cast<float>(AmountVal)));
Owen Anderson0032b272009-08-13 21:57:51 +0000772 else if (InVal->getType() == llvm::Type::getDoubleTy(VMContext))
Devang Patele9b8c0a2007-10-30 20:59:40 +0000773 NextVal =
Owen Andersonbc0a2222009-07-27 21:00:51 +0000774 llvm::ConstantFP::get(VMContext,
775 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattner25ddea72008-04-20 00:50:39 +0000776 else {
777 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesenee5a7002008-10-09 23:02:32 +0000778 bool ignored;
779 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
780 &ignored);
Owen Andersonbc0a2222009-07-27 21:00:51 +0000781 NextVal = llvm::ConstantFP::get(VMContext, F);
Chris Lattnerca2617c2007-09-13 06:19:18 +0000782 }
Chris Lattner87415d22009-06-17 06:36:24 +0000783 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnere936cc82007-08-26 05:10:16 +0000784 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000785
786 // Store the updated result through the lvalue.
Eli Friedmanf52bbeb2009-03-23 03:00:06 +0000787 if (LV.isBitfield())
788 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
789 &NextVal);
790 else
791 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner7f02f722007-08-24 05:35:26 +0000792
793 // If this is a postinc, return the value read from memory, otherwise use the
794 // updated value.
795 return isPre ? NextVal : InVal;
796}
797
798
799Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000800 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000801 Value *Op = Visit(E->getSubExpr());
Chris Lattner87415d22009-06-17 06:36:24 +0000802 if (Op->getType()->isFPOrFPVector())
803 return Builder.CreateFNeg(Op, "neg");
Chris Lattner7f02f722007-08-24 05:35:26 +0000804 return Builder.CreateNeg(Op, "neg");
805}
806
807Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000808 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000809 Value *Op = Visit(E->getSubExpr());
810 return Builder.CreateNot(Op, "neg");
811}
812
813Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
814 // Compare operand to zero.
815 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
816
817 // Invert value.
818 // TODO: Could dynamically modify easy computations here. For example, if
819 // the operand is an icmp ne, turn into icmp eq.
820 BoolVal = Builder.CreateNot(BoolVal, "lnot");
821
Anders Carlsson9f84d882009-05-19 18:44:53 +0000822 // ZExt result to the expr type.
823 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +0000824}
825
Sebastian Redl05189992008-11-11 17:56:53 +0000826/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
827/// argument of the sizeof expression as an integer.
828Value *
829ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +0000830 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000831 if (E->isSizeOf()) {
832 if (const VariableArrayType *VAT =
833 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
834 if (E->isArgumentType()) {
835 // sizeof(type) - make sure to emit the VLA size.
836 CGF.EmitVLASize(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +0000837 } else {
838 // C99 6.5.3.4p2: If the argument is an expression of type
839 // VLA, it is evaluated.
840 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000841 }
Anders Carlsson6cd586d2009-01-30 16:41:04 +0000842
Anders Carlsson96f21472009-02-05 19:43:10 +0000843 return CGF.GetVLASize(VAT);
Anders Carlssonb50525b2008-12-21 03:33:21 +0000844 }
Anders Carlsson5d463152008-12-12 07:38:43 +0000845 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +0000846
847 // If this isn't sizeof(vla), the result must be constant; use the
848 // constant folding logic so we don't have to duplicate it here.
849 Expr::EvalResult Result;
850 E->Evaluate(Result, CGF.getContext());
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000851 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner7f02f722007-08-24 05:35:26 +0000852}
853
Chris Lattner46f93d02007-08-24 21:20:17 +0000854Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
855 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000856 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +0000857 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner46f93d02007-08-24 21:20:17 +0000858 return Visit(Op);
859}
860Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
861 Expr *Op = E->getSubExpr();
Chris Lattner9b2dc282008-04-04 16:54:41 +0000862 if (Op->getType()->isAnyComplexType())
Mike Stump7f79f9b2009-05-29 15:46:01 +0000863 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Chris Lattner36f84062007-08-26 05:29:21 +0000864
Mike Stump7f79f9b2009-05-29 15:46:01 +0000865 // __imag on a scalar returns zero. Emit the subexpr to ensure side
866 // effects are evaluated, but not the actual value.
867 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
868 CGF.EmitLValue(Op);
869 else
870 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +0000871 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +0000872}
873
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000874Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
875{
Eli Friedman35183ac2009-02-27 06:44:11 +0000876 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedman769e4112009-01-24 22:38:55 +0000877 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman35183ac2009-02-27 06:44:11 +0000878 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson5a1deb82008-01-29 15:56:48 +0000879}
Chris Lattner46f93d02007-08-24 21:20:17 +0000880
Chris Lattner7f02f722007-08-24 05:35:26 +0000881//===----------------------------------------------------------------------===//
882// Binary Operators
883//===----------------------------------------------------------------------===//
884
885BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000886 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000887 BinOpInfo Result;
888 Result.LHS = Visit(E->getLHS());
889 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000890 Result.Ty = E->getType();
Chris Lattner7f02f722007-08-24 05:35:26 +0000891 Result.E = E;
892 return Result;
893}
894
Chris Lattner3ccf7742007-08-26 21:41:21 +0000895Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000896 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000897 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner1f1ded92007-08-24 21:00:35 +0000898 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
899
900 BinOpInfo OpInfo;
901
Eli Friedmanab3a8522009-03-28 01:22:36 +0000902 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +0000903 // This needs to go through the complex expression emitter, but
Eli Friedmanab3a8522009-03-28 01:22:36 +0000904 // it's a tad complicated to do that... I'm leaving it out for now.
905 // (Note that we do actually need the imaginary part of the RHS for
906 // multiplication and division.)
907 CGF.ErrorUnsupported(E, "complex compound assignment");
Owen Anderson03e20502009-07-30 23:11:26 +0000908 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Eli Friedmanab3a8522009-03-28 01:22:36 +0000909 }
910
Mike Stumpcc0442f2009-05-22 19:07:20 +0000911 // Emit the RHS first. __block variables need to have the rhs evaluated
912 // first, plus this should improve codegen a little.
913 OpInfo.RHS = Visit(E->getRHS());
914 OpInfo.Ty = E->getComputationResultType();
915 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +0000916 // Load/convert the LHS.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000917 LValue LHSLV = EmitLValue(E->getLHS());
918 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedmanab3a8522009-03-28 01:22:36 +0000919 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
920 E->getComputationLHSType());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000921
922 // Expand the binary operator.
923 Value *Result = (this->*Func)(OpInfo);
924
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000925 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +0000926 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
927
Daniel Dunbared3849b2008-11-19 09:36:46 +0000928 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar371d16f2008-11-19 11:54:05 +0000929 // handled specially because the result is altered by the store,
930 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
931 // the left operand after the assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +0000932 if (LHSLV.isBitfield()) {
933 if (!LHSLV.isVolatileQualified()) {
934 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
935 &Result);
936 return Result;
937 } else
938 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
939 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +0000940 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stump7f79f9b2009-05-29 15:46:01 +0000941 if (Ignore)
942 return 0;
943 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner1f1ded92007-08-24 21:00:35 +0000944}
945
946
Chris Lattner7f02f722007-08-24 05:35:26 +0000947Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanb3ab8dc2007-12-30 01:28:16 +0000948 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner7f02f722007-08-24 05:35:26 +0000949 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner1f1ded92007-08-24 21:00:35 +0000950 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000951 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
952 else
953 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
954}
955
956Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
957 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner1f1ded92007-08-24 21:00:35 +0000958 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +0000959 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
960 else
961 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
962}
963
Mike Stump2add4732009-04-01 20:28:16 +0000964Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
965 unsigned IID;
966 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +0000967
Mike Stump035cf892009-04-02 18:15:54 +0000968 switch (Ops.E->getOpcode()) {
969 case BinaryOperator::Add:
970 case BinaryOperator::AddAssign:
971 OpID = 1;
972 IID = llvm::Intrinsic::sadd_with_overflow;
973 break;
974 case BinaryOperator::Sub:
975 case BinaryOperator::SubAssign:
976 OpID = 2;
977 IID = llvm::Intrinsic::ssub_with_overflow;
978 break;
979 case BinaryOperator::Mul:
980 case BinaryOperator::MulAssign:
981 OpID = 3;
982 IID = llvm::Intrinsic::smul_with_overflow;
983 break;
984 default:
985 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbarab4eff62009-04-08 16:23:09 +0000986 IID = 0;
Mike Stump2add4732009-04-01 20:28:16 +0000987 }
Mike Stump035cf892009-04-02 18:15:54 +0000988 OpID <<= 1;
989 OpID |= 1;
990
Mike Stump2add4732009-04-01 20:28:16 +0000991 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
992
993 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
994
995 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
996 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
997 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
998
999 // Branch in case of overflow.
1000 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
1001 llvm::BasicBlock *overflowBB =
1002 CGF.createBasicBlock("overflow", CGF.CurFn);
1003 llvm::BasicBlock *continueBB =
1004 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
1005
1006 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1007
1008 // Handle overflow
1009
1010 Builder.SetInsertPoint(overflowBB);
1011
1012 // Handler is:
1013 // long long *__overflow_handler)(long long a, long long b, char op,
1014 // char width)
1015 std::vector<const llvm::Type*> handerArgTypes;
Owen Anderson0032b272009-08-13 21:57:51 +00001016 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1017 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1018 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1019 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1020 llvm::FunctionType *handlerTy = llvm::FunctionType::get(
1021 llvm::Type::getInt64Ty(VMContext), handerArgTypes, false);
Mike Stump2add4732009-04-01 20:28:16 +00001022 llvm::Value *handlerFunction =
1023 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
Owen Anderson96e0fc72009-07-29 22:16:19 +00001024 llvm::PointerType::getUnqual(handlerTy));
Mike Stump2add4732009-04-01 20:28:16 +00001025 handlerFunction = Builder.CreateLoad(handlerFunction);
1026
1027 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
Owen Anderson0032b272009-08-13 21:57:51 +00001028 Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)),
1029 Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)),
1030 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID),
1031 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
Mike Stump2add4732009-04-01 20:28:16 +00001032 cast<llvm::IntegerType>(opTy)->getBitWidth()));
1033
1034 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1035
1036 Builder.CreateBr(continueBB);
1037
1038 // Set up the continuation
1039 Builder.SetInsertPoint(continueBB);
1040 // Get the correct result
1041 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1042 phi->reserveOperandSpace(2);
1043 phi->addIncoming(result, initialBB);
1044 phi->addIncoming(handlerResult, overflowBB);
1045
1046 return phi;
1047}
Chris Lattner7f02f722007-08-24 05:35:26 +00001048
1049Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff58f9f2c2009-07-14 18:25:06 +00001050 if (!Ops.Ty->isAnyPointerType()) {
Chris Lattner87415d22009-06-17 06:36:24 +00001051 if (CGF.getContext().getLangOptions().OverflowChecking &&
1052 Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +00001053 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +00001054
1055 if (Ops.LHS->getType()->isFPOrFPVector())
1056 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanbf933a02009-08-12 01:16:29 +00001057
1058 // Signed integer overflow is undefined behavior.
1059 if (Ops.Ty->isSignedIntegerType())
1060 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1061
Chris Lattner7f02f722007-08-24 05:35:26 +00001062 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump2add4732009-04-01 20:28:16 +00001063 }
Eli Friedmandaa24a22009-03-28 02:45:41 +00001064
Steve Naroff14108da2009-07-10 23:34:53 +00001065 if (Ops.Ty->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001066 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001067 // The amount of the addition needs to account for the VLA size
1068 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1069 }
Chris Lattner8f925282008-01-03 06:36:51 +00001070 Value *Ptr, *Idx;
1071 Expr *IdxExp;
Ted Kremenek6217b802009-07-29 21:53:49 +00001072 const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001073 const ObjCObjectPointerType *OPT =
1074 Ops.E->getLHS()->getType()->getAsObjCObjectPointerType();
1075 if (PT || OPT) {
Chris Lattner8f925282008-01-03 06:36:51 +00001076 Ptr = Ops.LHS;
1077 Idx = Ops.RHS;
1078 IdxExp = Ops.E->getRHS();
Steve Naroff14108da2009-07-10 23:34:53 +00001079 } else { // int + pointer
Ted Kremenek6217b802009-07-29 21:53:49 +00001080 PT = Ops.E->getRHS()->getType()->getAs<PointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00001081 OPT = Ops.E->getRHS()->getType()->getAsObjCObjectPointerType();
1082 assert((PT || OPT) && "Invalid add expr");
Chris Lattner8f925282008-01-03 06:36:51 +00001083 Ptr = Ops.RHS;
1084 Idx = Ops.LHS;
1085 IdxExp = Ops.E->getLHS();
1086 }
1087
1088 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001089 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner8f925282008-01-03 06:36:51 +00001090 // Zero or sign extend the pointer value based on whether the index is
1091 // signed or not.
Owen Anderson0032b272009-08-13 21:57:51 +00001092 const llvm::Type *IdxType =
1093 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Chris Lattner96196622008-07-26 22:37:01 +00001094 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner8f925282008-01-03 06:36:51 +00001095 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1096 else
1097 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1098 }
Steve Naroff14108da2009-07-10 23:34:53 +00001099 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Daniel Dunbar2a866252009-04-25 05:08:32 +00001100 // Handle interface types, which are not represented with a concrete
1101 // type.
1102 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1103 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001104 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001105 CGF.getContext().getTypeSize(OIT) / 8);
1106 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Anderson0032b272009-08-13 21:57:51 +00001107 const llvm::Type *i8Ty =
1108 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbar2a866252009-04-25 05:08:32 +00001109 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1110 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1111 return Builder.CreateBitCast(Res, Ptr->getType());
1112 }
1113
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001114 // Explicitly handle GNU void* and function pointer arithmetic
1115 // extensions. The GNU void* casts amount to no-ops since our void*
1116 // type is i8*, but this is future proof.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001117 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Owen Anderson0032b272009-08-13 21:57:51 +00001118 const llvm::Type *i8Ty =
1119 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001120 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar2a866252009-04-25 05:08:32 +00001121 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001122 return Builder.CreateBitCast(Res, Ptr->getType());
1123 }
Chris Lattner8f925282008-01-03 06:36:51 +00001124
Dan Gohman664f8932009-08-12 00:33:55 +00001125 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00001126}
1127
1128Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump2add4732009-04-01 20:28:16 +00001129 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stump035cf892009-04-02 18:15:54 +00001130 if (CGF.getContext().getLangOptions().OverflowChecking
1131 && Ops.Ty->isSignedIntegerType())
Mike Stump2add4732009-04-01 20:28:16 +00001132 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner87415d22009-06-17 06:36:24 +00001133
1134 if (Ops.LHS->getType()->isFPOrFPVector())
1135 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner7f02f722007-08-24 05:35:26 +00001136 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00001137 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00001138
Steve Naroff14108da2009-07-10 23:34:53 +00001139 if (Ops.E->getLHS()->getType()->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001140 Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmandaa24a22009-03-28 02:45:41 +00001141 // The amount of the addition needs to account for the VLA size for
1142 // ptr-int
1143 // The amount of the division needs to account for the VLA size for
1144 // ptr-ptr.
1145 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1146 }
1147
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001148 const QualType LHSType = Ops.E->getLHS()->getType();
Steve Naroff14108da2009-07-10 23:34:53 +00001149 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001150 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1151 // pointer - int
1152 Value *Idx = Ops.RHS;
1153 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta7cabee52009-04-24 02:40:57 +00001154 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001155 // Zero or sign extend the pointer value based on whether the index is
1156 // signed or not.
Owen Anderson0032b272009-08-13 21:57:51 +00001157 const llvm::Type *IdxType =
1158 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001159 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1160 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1161 else
1162 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1163 }
1164 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001165
Daniel Dunbar2a866252009-04-25 05:08:32 +00001166 // Handle interface types, which are not represented with a concrete
1167 // type.
1168 if (const ObjCInterfaceType *OIT =
1169 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1170 llvm::Value *InterfaceSize =
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001171 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar2a866252009-04-25 05:08:32 +00001172 CGF.getContext().getTypeSize(OIT) / 8);
1173 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Andersona1cf15f2009-07-14 23:10:40 +00001174 const llvm::Type *i8Ty =
Owen Anderson0032b272009-08-13 21:57:51 +00001175 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbar2a866252009-04-25 05:08:32 +00001176 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1177 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1178 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1179 }
1180
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001181 // Explicitly handle GNU void* and function pointer arithmetic
1182 // extensions. The GNU void* casts amount to no-ops since our
1183 // void* type is i8*, but this is future proof.
1184 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Owen Andersona1cf15f2009-07-14 23:10:40 +00001185 const llvm::Type *i8Ty =
Owen Anderson0032b272009-08-13 21:57:51 +00001186 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbarb09fae72009-01-23 18:51:09 +00001187 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1188 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1189 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1190 }
1191
Dan Gohman664f8932009-08-12 00:33:55 +00001192 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar820b0332008-08-05 00:47:03 +00001193 } else {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001194 // pointer - pointer
1195 Value *LHS = Ops.LHS;
1196 Value *RHS = Ops.RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +00001197
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001198 uint64_t ElementSize;
Daniel Dunbar820b0332008-08-05 00:47:03 +00001199
Chris Lattnere5ed1512009-02-11 07:21:43 +00001200 // Handle GCC extension for pointer arithmetic on void* and function pointer
1201 // types.
1202 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001203 ElementSize = 1;
1204 } else {
1205 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1206 }
1207
1208 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1209 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1210 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1211 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1212
Chris Lattnere5ed1512009-02-11 07:21:43 +00001213 // Optimize out the shift for element size of 1.
1214 if (ElementSize == 1)
1215 return BytesBetween;
Dan Gohmandf110942009-08-11 22:40:09 +00001216
1217 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1218 // pointer difference in C is only defined in the case where both
1219 // operands are pointing to elements of an array.
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001220 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
Dan Gohmandf110942009-08-11 22:40:09 +00001221 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00001222 }
Chris Lattner7f02f722007-08-24 05:35:26 +00001223}
1224
1225Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1226 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1227 // RHS to the same size as the LHS.
1228 Value *RHS = Ops.RHS;
1229 if (Ops.LHS->getType() != RHS->getType())
1230 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1231
1232 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1233}
1234
1235Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1236 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1237 // RHS to the same size as the LHS.
1238 Value *RHS = Ops.RHS;
1239 if (Ops.LHS->getType() != RHS->getType())
1240 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1241
Chris Lattner1f1ded92007-08-24 21:00:35 +00001242 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner7f02f722007-08-24 05:35:26 +00001243 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1244 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1245}
1246
1247Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1248 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001249 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001250 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00001251 QualType LHSTy = E->getLHS()->getType();
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001252 if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001253 Value *LHS = Visit(E->getLHS());
1254 Value *RHS = Visit(E->getRHS());
1255
Eli Friedman1360d4a2009-07-22 06:07:16 +00001256 if (LHS->getType()->isFPOrFPVector()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001257 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001258 LHS, RHS, "cmp");
Eli Friedmanec2c1262008-05-29 15:09:15 +00001259 } else if (LHSTy->isSignedIntegerType()) {
1260 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001261 LHS, RHS, "cmp");
1262 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00001263 // Unsigned integers and pointers.
1264 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00001265 LHS, RHS, "cmp");
1266 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00001267
1268 // If this is a vector comparison, sign extend the result to the appropriate
1269 // vector integer type and return it (don't convert to bool).
1270 if (LHSTy->isVectorType())
1271 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Nate Begeman7a66d7b2008-07-25 20:16:05 +00001272
Chris Lattner7f02f722007-08-24 05:35:26 +00001273 } else {
1274 // Complex Comparison: can only be an equality comparison.
1275 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1276 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1277
Chris Lattner96196622008-07-26 22:37:01 +00001278 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner7f02f722007-08-24 05:35:26 +00001279
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001280 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00001281 if (CETy->isRealFloatingType()) {
1282 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1283 LHS.first, RHS.first, "cmp.r");
1284 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1285 LHS.second, RHS.second, "cmp.i");
1286 } else {
1287 // Complex comparisons can only be equality comparisons. As such, signed
1288 // and unsigned opcodes are the same.
1289 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1290 LHS.first, RHS.first, "cmp.r");
1291 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1292 LHS.second, RHS.second, "cmp.i");
1293 }
1294
1295 if (E->getOpcode() == BinaryOperator::EQ) {
1296 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1297 } else {
1298 assert(E->getOpcode() == BinaryOperator::NE &&
1299 "Complex comparison other than == or != ?");
1300 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1301 }
1302 }
Nuno Lopes32f62092009-01-11 23:22:37 +00001303
1304 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001305}
1306
1307Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001308 bool Ignore = TestAndClearIgnoreResultAssign();
1309
1310 // __block variables need to have the rhs evaluated first, plus this should
1311 // improve codegen just a little.
Chris Lattner7f02f722007-08-24 05:35:26 +00001312 Value *RHS = Visit(E->getRHS());
Mike Stump99459b62009-05-21 21:05:15 +00001313 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner7f02f722007-08-24 05:35:26 +00001314
Daniel Dunbared3849b2008-11-19 09:36:46 +00001315 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar371d16f2008-11-19 11:54:05 +00001316 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1317 // 'An assignment expression has the value of the left operand after
Eli Friedmandaa24a22009-03-28 02:45:41 +00001318 // the assignment...'.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001319 if (LHS.isBitfield()) {
1320 if (!LHS.isVolatileQualified()) {
1321 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1322 &RHS);
1323 return RHS;
1324 } else
1325 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1326 } else
Daniel Dunbared3849b2008-11-19 09:36:46 +00001327 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stump7f79f9b2009-05-29 15:46:01 +00001328 if (Ignore)
1329 return 0;
1330 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00001331}
1332
1333Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001334 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1335 // If we have 1 && X, just emit X without inserting the control flow.
1336 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1337 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001338 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1339 // ZExt result to int.
1340 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1341 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001342
1343 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1344 if (!CGF.ContainsLabel(E->getRHS()))
Owen Andersonc9c88b42009-07-31 20:28:54 +00001345 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001346 }
1347
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001348 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1349 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00001350
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001351 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1352 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1353
1354 // Any edges into the ContBlock are now from an (indeterminate number of)
1355 // edges from this first condition. All of these values will be false. Start
1356 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001357 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1358 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001359 PN->reserveOperandSpace(2); // Normal case, two inputs.
1360 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1361 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001362 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Chris Lattner7f02f722007-08-24 05:35:26 +00001363
Anders Carlsson33da07d2009-06-04 02:53:13 +00001364 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001365 CGF.EmitBlock(RHSBlock);
1366 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlsson33da07d2009-06-04 02:53:13 +00001367 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001368
1369 // Reaquire the RHS block, as there may be subblocks inserted.
1370 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001371
1372 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1373 // into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00001374 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001375 PN->addIncoming(RHSCond, RHSBlock);
1376
1377 // ZExt result to int.
1378 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1379}
1380
1381Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner20eb09d2008-11-12 08:26:50 +00001382 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1383 // If we have 0 || X, just emit X without inserting the control flow.
1384 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1385 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00001386 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1387 // ZExt result to int.
1388 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1389 }
Chris Lattner20eb09d2008-11-12 08:26:50 +00001390
Eli Friedman8de8d1d2008-12-02 16:02:46 +00001391 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner20eb09d2008-11-12 08:26:50 +00001392 if (!CGF.ContainsLabel(E->getRHS()))
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001393 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00001394 }
1395
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001396 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1397 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner7f02f722007-08-24 05:35:26 +00001398
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001399 // Branch on the LHS first. If it is true, go to the success (cont) block.
1400 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1401
1402 // Any edges into the ContBlock are now from an (indeterminate number of)
1403 // edges from this first condition. All of these values will be true. Start
1404 // setting up the PHI node in the Cont Block for this.
Owen Anderson0032b272009-08-13 21:57:51 +00001405 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1406 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001407 PN->reserveOperandSpace(2); // Normal case, two inputs.
1408 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1409 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00001410 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001411
Anders Carlsson33da07d2009-06-04 02:53:13 +00001412 CGF.PushConditionalTempDestruction();
1413
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001414 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00001415 CGF.EmitBlock(RHSBlock);
1416 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1417
Anders Carlsson33da07d2009-06-04 02:53:13 +00001418 CGF.PopConditionalTempDestruction();
1419
Chris Lattner7f02f722007-08-24 05:35:26 +00001420 // Reaquire the RHS block, as there may be subblocks inserted.
1421 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00001422
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00001423 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1424 // into the phi node for the edge with the value of RHSCond.
1425 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001426 PN->addIncoming(RHSCond, RHSBlock);
1427
1428 // ZExt result to int.
1429 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1430}
1431
1432Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1433 CGF.EmitStmt(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00001434 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00001435 return Visit(E->getRHS());
1436}
1437
1438//===----------------------------------------------------------------------===//
1439// Other Operators
1440//===----------------------------------------------------------------------===//
1441
Chris Lattner9802a512008-11-12 08:55:54 +00001442/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1443/// expression is cheap enough and side-effect-free enough to evaluate
1444/// unconditionally instead of conditionally. This is used to convert control
1445/// flow into selects in some cases.
1446static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1447 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1448 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1449
1450 // TODO: Allow anything we can constant fold to an integer or fp constant.
1451 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1452 isa<FloatingLiteral>(E))
1453 return true;
1454
1455 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1456 // X and Y are local variables.
1457 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1458 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1459 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1460 return true;
1461
1462 return false;
1463}
1464
1465
Chris Lattner7f02f722007-08-24 05:35:26 +00001466Value *ScalarExprEmitter::
1467VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001468 TestAndClearIgnoreResultAssign();
Chris Lattner31a09842008-11-12 08:04:58 +00001469 // If the condition constant folds and can be elided, try to avoid emitting
1470 // the condition and the dead arm.
1471 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerc657e922008-11-11 18:56:45 +00001472 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner31a09842008-11-12 08:04:58 +00001473 if (Cond == -1)
Chris Lattnerc657e922008-11-11 18:56:45 +00001474 std::swap(Live, Dead);
Chris Lattner31a09842008-11-12 08:04:58 +00001475
1476 // If the dead side doesn't have labels we need, and if the Live side isn't
1477 // the gnu missing ?: extension (which we could handle, but don't bother
1478 // to), just emit the Live part.
1479 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1480 Live) // Live part isn't missing.
1481 return Visit(Live);
Chris Lattnerc657e922008-11-11 18:56:45 +00001482 }
1483
Chris Lattner9802a512008-11-12 08:55:54 +00001484
1485 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1486 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00001487 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner9802a512008-11-12 08:55:54 +00001488 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1489 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1490 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1491 llvm::Value *LHS = Visit(E->getLHS());
1492 llvm::Value *RHS = Visit(E->getRHS());
1493 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1494 }
1495
1496
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00001497 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1498 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00001499 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner035cf422008-11-12 08:08:13 +00001500 Value *CondVal = 0;
Chris Lattner31a09842008-11-12 08:04:58 +00001501
Chris Lattner12d152f2009-02-13 23:35:32 +00001502 // If we don't have the GNU missing condition extension, emit a branch on
1503 // bool the normal way.
1504 if (E->getLHS()) {
1505 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1506 // the branch on bool.
1507 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1508 } else {
1509 // Otherwise, for the ?: extension, evaluate the conditional and then
1510 // convert it to bool the hard way. We do this explicitly because we need
1511 // the unconverted value for the missing middle value of the ?:.
Chris Lattner035cf422008-11-12 08:08:13 +00001512 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner12d152f2009-02-13 23:35:32 +00001513
1514 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1515 // if there are no extra uses (an optimization). Inhibit this by making an
1516 // extra dead use, because we're going to add a use of CondVal later. We
1517 // don't use the builder for this, because we don't want it to get optimized
1518 // away. This leaves dead code, but the ?: extension isn't common.
1519 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1520 Builder.GetInsertBlock());
1521
Chris Lattner035cf422008-11-12 08:08:13 +00001522 Value *CondBoolVal =
1523 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1524 CGF.getContext().BoolTy);
1525 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner035cf422008-11-12 08:08:13 +00001526 }
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001527
1528 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001529 CGF.EmitBlock(LHSBlock);
1530
1531 // Handle the GNU extension for missing LHS.
Chris Lattnera21ddb32007-11-26 01:40:58 +00001532 Value *LHS;
1533 if (E->getLHS())
Eli Friedman856226c2008-05-16 20:38:39 +00001534 LHS = Visit(E->getLHS());
Chris Lattnera21ddb32007-11-26 01:40:58 +00001535 else // Perform promotions, to handle cases like "short ?: int"
1536 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1537
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001538 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001539 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001540 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001541
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001542 CGF.PushConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001543 CGF.EmitBlock(RHSBlock);
1544
Eli Friedman856226c2008-05-16 20:38:39 +00001545 Value *RHS = Visit(E->getRHS());
Anders Carlssonfb6fa302009-06-04 03:00:32 +00001546 CGF.PopConditionalTempDestruction();
Chris Lattner7f02f722007-08-24 05:35:26 +00001547 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbard57a8712008-11-11 09:41:28 +00001548 CGF.EmitBranch(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00001549
1550 CGF.EmitBlock(ContBlock);
1551
Nuno Lopes108f55d2008-06-04 19:15:45 +00001552 if (!LHS || !RHS) {
Chris Lattner2202bce2007-11-30 17:56:23 +00001553 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1554 return 0;
1555 }
1556
Chris Lattner7f02f722007-08-24 05:35:26 +00001557 // Create a PHI node for the real part.
1558 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1559 PN->reserveOperandSpace(2);
1560 PN->addIncoming(LHS, LHSBlock);
1561 PN->addIncoming(RHS, RHSBlock);
1562 return PN;
1563}
1564
1565Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00001566 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001567}
1568
Chris Lattner2202bce2007-11-30 17:56:23 +00001569Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00001570 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001571 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1572
1573 // If EmitVAArg fails, we fall back to the LLVM instruction.
1574 if (!ArgPtr)
1575 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1576
Mike Stump7f79f9b2009-05-29 15:46:01 +00001577 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00001578 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00001579}
1580
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001581Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump08920992009-03-07 02:35:30 +00001582 return CGF.BuildBlockLiteralTmp(BE);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00001583}
1584
Chris Lattner7f02f722007-08-24 05:35:26 +00001585//===----------------------------------------------------------------------===//
1586// Entry Point into this File
1587//===----------------------------------------------------------------------===//
1588
Mike Stump7f79f9b2009-05-29 15:46:01 +00001589/// EmitScalarExpr - Emit the computation of the specified expression of
1590/// scalar type, ignoring the result.
1591Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00001592 assert(E && !hasAggregateLLVMType(E->getType()) &&
1593 "Invalid scalar expression to emit");
1594
Mike Stump7f79f9b2009-05-29 15:46:01 +00001595 return ScalarExprEmitter(*this, IgnoreResultAssign)
1596 .Visit(const_cast<Expr*>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00001597}
Chris Lattner3707b252007-08-26 06:48:56 +00001598
1599/// EmitScalarConversion - Emit a conversion from the specified type to the
1600/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001601Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1602 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00001603 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1604 "Invalid scalar expression to emit");
1605 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1606}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001607
1608/// EmitComplexToScalarConversion - Emit a conversion from the specified
1609/// complex type to the specified destination type, where the destination
1610/// type is an LLVM scalar type.
1611Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1612 QualType SrcTy,
1613 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00001614 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00001615 "Invalid complex -> scalar conversion");
1616 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1617 DstTy);
1618}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001619
1620Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1621 assert(V1->getType() == V2->getType() &&
1622 "Vector operands must be of the same type");
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001623 unsigned NumElements =
1624 cast<llvm::VectorType>(V1->getType())->getNumElements();
1625
1626 va_list va;
1627 va_start(va, V2);
1628
1629 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001630 for (unsigned i = 0; i < NumElements; i++) {
1631 int n = va_arg(va, int);
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001632 assert(n >= 0 && n < (int)NumElements * 2 &&
1633 "Vector shuffle index out of bounds!");
Owen Anderson0032b272009-08-13 21:57:51 +00001634 Args.push_back(llvm::ConstantInt::get(
1635 llvm::Type::getInt32Ty(VMContext), n));
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001636 }
1637
1638 const char *Name = va_arg(va, const char *);
1639 va_end(va);
1640
Owen Anderson4a289322009-07-28 21:22:35 +00001641 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Anders Carlssoncc23aca2007-12-10 19:35:18 +00001642
1643 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1644}
1645
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001646llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattner345f7202008-07-26 20:15:14 +00001647 unsigned NumVals, bool isSplat) {
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001648 llvm::Value *Vec
Owen Anderson03e20502009-07-30 23:11:26 +00001649 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001650
Chris Lattner345f7202008-07-26 20:15:14 +00001651 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begeman4119d1a2007-12-30 02:59:45 +00001652 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Owen Anderson0032b272009-08-13 21:57:51 +00001653 llvm::Value *Idx = llvm::ConstantInt::get(
1654 llvm::Type::getInt32Ty(VMContext), i);
Nate Begeman4119d1a2007-12-30 02:59:45 +00001655 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson6086bbd2007-12-15 21:23:30 +00001656 }
1657
1658 return Vec;
1659}