blob: 0b8cb8cb761f634e70e5c1274c160fcfca612d64 [file] [log] [blame]
Chris Lattner9fba49a2007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-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 Lattner9fba49a2007-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 Dunbareee5cd12008-08-11 05:00:27 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbarfa456242008-08-12 05:08:18 +000017#include "clang/AST/DeclObjC.h"
Anders Carlsson63f1ad92009-07-18 19:43:29 +000018#include "clang/AST/RecordLayout.h"
Daniel Dunbareee5cd12008-08-11 05:00:27 +000019#include "clang/AST/StmtVisitor.h"
Chris Lattnerd54d1f22008-04-20 00:50:39 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Anders Carlsson36f07d82007-10-29 05:01:08 +000023#include "llvm/GlobalVariable.h"
Anders Carlsson36760332007-10-15 20:28:48 +000024#include "llvm/Intrinsics.h"
Mike Stumpdb789912009-04-01 20:28:16 +000025#include "llvm/Module.h"
Chris Lattner9fba49a2007-08-24 05:35:26 +000026#include "llvm/Support/Compiler.h"
Chris Lattner7f80bb32008-11-12 08:38:24 +000027#include "llvm/Support/CFG.h"
Mike Stumpfca5da02009-02-21 20:00:35 +000028#include "llvm/Target/TargetData.h"
Chris Lattnerc2126682008-01-03 07:05:49 +000029#include <cstdarg>
Ted Kremenek03cf4df2007-12-10 23:44:32 +000030
Chris Lattner9fba49a2007-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 Lattner660e31d2007-08-24 21:00:35 +000042 QualType Ty; // Computation Type.
Chris Lattner9fba49a2007-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 Dunbard916e6e2008-11-01 01:53:16 +000050 CGBuilderTy &Builder;
Mike Stumpb8fc73e2009-05-29 15:46:01 +000051 bool IgnoreResultAssign;
Owen Anderson73e7f802009-07-14 23:10:40 +000052 llvm::LLVMContext &VMContext;
Chris Lattner9fba49a2007-08-24 05:35:26 +000053public:
54
Mike Stumpb8fc73e2009-05-29 15:46:01 +000055 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Owen Anderson73e7f802009-07-14 23:10:40 +000056 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
57 VMContext(cgf.getLLVMContext()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +000058 }
Chris Lattner9fba49a2007-08-24 05:35:26 +000059
60 //===--------------------------------------------------------------------===//
61 // Utilities
62 //===--------------------------------------------------------------------===//
63
Mike Stumpb8fc73e2009-05-29 15:46:01 +000064 bool TestAndClearIgnoreResultAssign() {
Chris Lattner08ac8522009-07-08 01:08:03 +000065 bool I = IgnoreResultAssign;
66 IgnoreResultAssign = false;
67 return I;
68 }
Mike Stumpb8fc73e2009-05-29 15:46:01 +000069
Chris Lattner9fba49a2007-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 Lattnere24c4cf2007-08-31 22:49:20 +000074 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner9fba49a2007-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 Lattner9fba49a2007-08-24 05:35:26 +000081 return EmitLoadOfLValue(EmitLValue(E), E->getType());
82 }
83
Chris Lattnerd8d44222007-08-26 16:42:57 +000084 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +000085 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +000086 Value *EmitConversionToBool(Value *Src, QualType DstTy);
87
Chris Lattner4e05d1e2007-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 Lattnerfb182ee2007-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 Stump4eb81dc2009-02-12 18:29:15 +000097
Chris Lattner9fba49a2007-08-24 05:35:26 +000098 //===--------------------------------------------------------------------===//
99 // Visitor Methods
100 //===--------------------------------------------------------------------===//
101
102 Value *VisitStmt(Stmt *S) {
Ted Kremenekb3ee1932007-12-11 21:27:55 +0000103 S->dump(CGF.getContext().getSourceManager());
Chris Lattner9fba49a2007-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 Andersonb17ec712009-07-24 23:12:58 +0000112 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000113 }
114 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonb56fd0b2009-07-27 21:00:51 +0000115 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000116 }
117 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Andersonb17ec712009-07-24 23:12:58 +0000118 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000119 }
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000120 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Andersonb17ec712009-07-24 23:12:58 +0000121 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane9bfe6d2007-11-15 05:40:03 +0000122 }
Argiris Kirtzidis750eb972008-08-23 19:35:47 +0000123 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Owen Andersonf37b84b2009-07-31 20:28:54 +0000124 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Argiris Kirtzidis750eb972008-08-23 19:35:47 +0000125 }
Anders Carlsson774f9c72008-12-21 22:39:40 +0000126 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Owen Andersonf37b84b2009-07-31 20:28:54 +0000127 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Anders Carlsson774f9c72008-12-21 22:39:40 +0000128 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000129 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Owen Andersonb17ec712009-07-24 23:12:58 +0000130 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff85f0dc52007-10-15 20:41:53 +0000131 CGF.getContext().typesAreCompatible(
132 E->getArgType1(), E->getArgType2()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000133 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000134 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar879788d2008-08-04 16:51:22 +0000135 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbarb5fda0c2008-08-16 01:41:47 +0000136 llvm::Value *V =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000137 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()),
Daniel Dunbarb5fda0c2008-08-16 01:41:47 +0000138 CGF.GetIDForAddrOfLabel(E->getLabel()));
139
140 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar879788d2008-08-04 16:51:22 +0000141 }
Chris Lattner9fba49a2007-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 Andersonb17ec712009-07-24 23:12:58 +0000146 return llvm::ConstantInt::get(VMContext, EC->getInitVal());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000147 return EmitLoadOfLValue(E);
148 }
Daniel Dunbar91cc4022008-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 Dunbar5e105892008-08-23 10:51:21 +0000158 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbare6c31752008-08-29 08:11:39 +0000159 return EmitLoadOfLValue(E);
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000160 }
Fariborz Jahanianb0973da2008-11-22 22:30:21 +0000161 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
162 return EmitLoadOfLValue(E);
163 }
Daniel Dunbar91cc4022008-08-27 06:57:25 +0000164 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
165 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar5e105892008-08-23 10:51:21 +0000166 }
167
Chris Lattner9fba49a2007-08-24 05:35:26 +0000168 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand0e9d092008-05-14 19:38:39 +0000169 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000170 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemanaf6ed502008-04-18 23:10:10 +0000171 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnera9177982008-10-26 23:53:12 +0000172 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
173 return EmitLoadOfLValue(E);
174 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000175 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnerc5d32632009-02-24 22:18:39 +0000176 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
177 return EmitLValue(E).getAddress();
178 }
179
Chris Lattner69909292008-08-10 01:53:14 +0000180 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel01ab1302007-10-24 17:18:43 +0000181
182 Value *VisitInitListExpr(InitListExpr *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000183 bool Ignore = TestAndClearIgnoreResultAssign();
184 (void)Ignore;
185 assert (Ignore == false && "init list ignored");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000186 unsigned NumInitElements = E->getNumInits();
187
Douglas Gregor9fddded2009-01-29 19:42:23 +0000188 if (E->hadArrayRangeDesignator()) {
189 CGF.ErrorUnsupported(E, "GNU array range designator extension");
190 }
191
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000192 const llvm::VectorType *VType =
Anders Carlsson35ab4f92008-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 Carlsson4513ecb2007-12-05 07:36:10 +0000198
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000199 unsigned NumVectorElements = VType->getNumElements();
200 const llvm::Type *ElementType = VType->getElementType();
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000201
202 // Emit individual vector element stores.
Owen Andersone0b5eff2009-07-30 23:11:26 +0000203 llvm::Value *V = llvm::UndefValue::get(VType);
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000204
Anders Carlsson323d5682007-12-18 02:45:33 +0000205 // Emit initializers
206 unsigned i;
207 for (i = 0; i < NumInitElements; ++i) {
Devang Patel32c39832007-10-24 18:05:48 +0000208 Value *NewV = Visit(E->getInit(i));
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000209 Value *Idx =
210 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
Devang Patel32c39832007-10-24 18:05:48 +0000211 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000212 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000213
214 // Emit remaining default initializers
215 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000216 Value *Idx =
217 llvm::ConstantInt::get(llvm::Type::getInt32Ty(CGF.getLLVMContext()), i);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000218 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000219 V = Builder.CreateInsertElement(V, NewV, Idx);
220 }
221
Devang Patel32c39832007-10-24 18:05:48 +0000222 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000223 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000224
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000225 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Owen Andersonf37b84b2009-07-31 20:28:54 +0000226 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000227 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000228 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
Eli Friedmana7ef8e52009-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 Lattner9fba49a2007-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 Carlssoncd295282009-05-27 03:37:57 +0000239 if (E->getCallReturnType()->isReferenceType())
240 return EmitLoadOfLValue(E);
241
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000242 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000243 }
Daniel Dunbara04840b2008-08-23 03:46:30 +0000244
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000245 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpfca5da02009-02-21 20:00:35 +0000246
Mike Stump2b6933f2009-02-28 09:07:16 +0000247 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000248
Chris Lattner9fba49a2007-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 Stumpb8fc73e2009-05-29 15:46:01 +0000268 // This differs from gcc, though, most likely due to a bug in gcc.
269 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-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 Lattner01211af2007-08-24 21:20:17 +0000275 Value *VisitUnaryReal (const UnaryOperator *E);
276 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000277 Value *VisitUnaryExtension(const UnaryOperator *E) {
278 return Visit(E->getSubExpr());
279 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000280 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Anders Carlsson49d4a572009-04-14 16:58:56 +0000281
282 // C++
Chris Lattner3e254fb2008-04-08 04:40:51 +0000283 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
284 return Visit(DAE->getExpr());
285 }
Anders Carlsson49d4a572009-04-14 16:58:56 +0000286 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
287 return CGF.LoadCXXThis();
288 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000289
Anders Carlsson272b5f52009-05-19 04:48:36 +0000290 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlssond6775602009-05-31 00:09:15 +0000291 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson272b5f52009-05-19 04:48:36 +0000292 }
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000293 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
294 return CGF.EmitCXXNewExpr(E);
295 }
Anders Carlsson272b5f52009-05-19 04:48:36 +0000296
Chris Lattner9fba49a2007-08-24 05:35:26 +0000297 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000298 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000299 if (CGF.getContext().getLangOptions().OverflowChecking
300 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000301 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +0000302 if (Ops.LHS->getType()->isFPOrFPVector())
303 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000304 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
305 }
Mike Stumpdb789912009-04-01 20:28:16 +0000306 /// Create a binary op that checks for overflow.
307 /// Currently only supports +, - and *.
308 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000309 Value *EmitDiv(const BinOpInfo &Ops);
310 Value *EmitRem(const BinOpInfo &Ops);
311 Value *EmitAdd(const BinOpInfo &Ops);
312 Value *EmitSub(const BinOpInfo &Ops);
313 Value *EmitShl(const BinOpInfo &Ops);
314 Value *EmitShr(const BinOpInfo &Ops);
315 Value *EmitAnd(const BinOpInfo &Ops) {
316 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
317 }
318 Value *EmitXor(const BinOpInfo &Ops) {
319 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
320 }
321 Value *EmitOr (const BinOpInfo &Ops) {
322 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
323 }
324
Chris Lattner660e31d2007-08-24 21:00:35 +0000325 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000326 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000327 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
328
329 // Binary operators and binary compound assignment operators.
330#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000331 Value *VisitBin ## OP(const BinaryOperator *E) { \
332 return Emit ## OP(EmitBinOps(E)); \
333 } \
334 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
335 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000336 }
337 HANDLEBINOP(Mul);
338 HANDLEBINOP(Div);
339 HANDLEBINOP(Rem);
340 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000341 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000342 HANDLEBINOP(Shl);
343 HANDLEBINOP(Shr);
344 HANDLEBINOP(And);
345 HANDLEBINOP(Xor);
346 HANDLEBINOP(Or);
347#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000348
Chris Lattner9fba49a2007-08-24 05:35:26 +0000349 // Comparisons.
350 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
351 unsigned SICmpOpc, unsigned FCmpOpc);
352#define VISITCOMP(CODE, UI, SI, FP) \
353 Value *VisitBin##CODE(const BinaryOperator *E) { \
354 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
355 llvm::FCmpInst::FP); }
356 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
357 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
358 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
359 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
360 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
361 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
362#undef VISITCOMP
363
364 Value *VisitBinAssign (const BinaryOperator *E);
365
366 Value *VisitBinLAnd (const BinaryOperator *E);
367 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000368 Value *VisitBinComma (const BinaryOperator *E);
369
370 // Other Operators.
Mike Stump4eb81dc2009-02-12 18:29:15 +0000371 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000372 Value *VisitConditionalOperator(const ConditionalOperator *CO);
373 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000374 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000375 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
376 return CGF.EmitObjCStringLiteral(E);
377 }
378};
379} // end anonymous namespace.
380
381//===----------------------------------------------------------------------===//
382// Utilities
383//===----------------------------------------------------------------------===//
384
Chris Lattnerd8d44222007-08-26 16:42:57 +0000385/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000386/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000387Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
388 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
389
390 if (SrcType->isRealFloatingType()) {
391 // Compare against 0.0 for fp scalars.
Owen Andersonf37b84b2009-07-31 20:28:54 +0000392 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000393 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
394 }
395
Anders Carlssone3ee66c2009-08-09 18:26:27 +0000396 if (SrcType->isMemberPointerType()) {
397 // FIXME: This is ABI specific.
398
399 // Compare against -1.
400 llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType());
401 return Builder.CreateICmpNE(Src, NegativeOne, "tobool");
402 }
403
Daniel Dunbar5d54eed2008-08-25 10:38:11 +0000404 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnerd8d44222007-08-26 16:42:57 +0000405 "Unknown scalar type to convert");
406
407 // Because of the type rules of C, we often end up computing a logical value,
408 // then zero extending it to int, then wanting it as a logical value again.
409 // Optimize this common case.
410 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000411 if (ZI->getOperand(0)->getType() ==
412 llvm::Type::getInt1Ty(CGF.getLLVMContext())) {
Chris Lattnerd8d44222007-08-26 16:42:57 +0000413 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000414 // If there aren't any more uses, zap the instruction to save space.
415 // Note that there can be more uses, for example if this
416 // is the result of an assignment.
417 if (ZI->use_empty())
418 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000419 return Result;
420 }
421 }
422
423 // Compare against an integer or pointer null.
Owen Andersonf37b84b2009-07-31 20:28:54 +0000424 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000425 return Builder.CreateICmpNE(Src, Zero, "tobool");
426}
427
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000428/// EmitScalarConversion - Emit a conversion from the specified type to the
429/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000430Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
431 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000432 SrcType = CGF.getContext().getCanonicalType(SrcType);
433 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000434 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000435
436 if (DstType->isVoidType()) return 0;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000437
438 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000439
440 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000441 if (DstType->isBooleanType())
442 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000443
444 const llvm::Type *DstTy = ConvertType(DstType);
445
446 // Ignore conversions like int -> uint.
447 if (Src->getType() == DstTy)
448 return Src;
449
Daniel Dunbar238335f2008-08-25 09:51:32 +0000450 // Handle pointer conversions next: pointers can only be converted
451 // to/from other pointers and integers. Check for pointer types in
452 // terms of LLVM, as some native types (like Obj-C id) may map to a
453 // pointer type.
454 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000455 // The source value may be an integer, or a pointer.
Fariborz Jahanianf7f6cf82009-07-28 22:00:58 +0000456 if (isa<llvm::PointerType>(Src->getType())) {
457 // Some heavy lifting for derived to base conversion.
Fariborz Jahanian90e18742009-07-29 00:44:13 +0000458 if (const CXXRecordDecl *ClassDecl =
459 SrcType->getCXXRecordDeclForPointerType())
460 if (const CXXRecordDecl *BaseClassDecl =
461 DstType->getCXXRecordDeclForPointerType())
462 Src = CGF.AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000463 return Builder.CreateBitCast(Src, DstTy, "conv");
Fariborz Jahanianf7f6cf82009-07-28 22:00:58 +0000464 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000465 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman35bcec82009-03-04 04:02:35 +0000466 // First, convert to the correct width so that we control the kind of
467 // extension.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000468 const llvm::Type *MiddleTy =
469 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Eli Friedman35bcec82009-03-04 04:02:35 +0000470 bool InputSigned = SrcType->isSignedIntegerType();
471 llvm::Value* IntResult =
472 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
473 // Then, cast to pointer.
474 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000475 }
476
Daniel Dunbar238335f2008-08-25 09:51:32 +0000477 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000478 // Must be an ptr to int cast.
479 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000480 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000481 }
482
Nate Begemanaf6ed502008-04-18 23:10:10 +0000483 // A scalar can be splatted to an extended vector of the same element type
Nate Begemane85f43d2009-08-10 23:49:36 +0000484 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman7903d052009-01-18 06:42:49 +0000485 // Cast the scalar to element type
486 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
487 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
488
489 // Insert the element in element zero of an undef vector
Owen Andersone0b5eff2009-07-30 23:11:26 +0000490 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000491 llvm::Value *Idx =
492 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), 0);
Nate Begeman7903d052009-01-18 06:42:49 +0000493 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
494
495 // Splat the element across to all elements
496 llvm::SmallVector<llvm::Constant*, 16> Args;
497 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
498 for (unsigned i = 0; i < NumElements; i++)
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000499 Args.push_back(llvm::ConstantInt::get(
500 llvm::Type::getInt32Ty(VMContext), 0));
Nate Begeman7903d052009-01-18 06:42:49 +0000501
Owen Anderson17971fa2009-07-28 21:22:35 +0000502 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Nate Begeman7903d052009-01-18 06:42:49 +0000503 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
504 return Yay;
505 }
Nate Begemanec2d1062007-12-30 02:59:45 +0000506
Chris Lattner4f025a42008-02-02 04:51:41 +0000507 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000508 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000509 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000510 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000511
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000512 // Finally, we have the arithmetic types: real int/float.
513 if (isa<llvm::IntegerType>(Src->getType())) {
514 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000515 if (isa<llvm::IntegerType>(DstTy))
516 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
517 else if (InputSigned)
518 return Builder.CreateSIToFP(Src, DstTy, "conv");
519 else
520 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000521 }
522
523 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
524 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000525 if (DstType->isSignedIntegerType())
526 return Builder.CreateFPToSI(Src, DstTy, "conv");
527 else
528 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000529 }
530
531 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000532 if (DstTy->getTypeID() < Src->getType()->getTypeID())
533 return Builder.CreateFPTrunc(Src, DstTy, "conv");
534 else
535 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000536}
537
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000538/// EmitComplexToScalarConversion - Emit a conversion from the specified
539/// complex type to the specified destination type, where the destination
540/// type is an LLVM scalar type.
541Value *ScalarExprEmitter::
542EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
543 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000544 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000545 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000546
547 // Handle conversions to bool first, they are special: comparisons against 0.
548 if (DstTy->isBooleanType()) {
549 // Complex != 0 -> (Real != 0) | (Imag != 0)
550 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
551 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
552 return Builder.CreateOr(Src.first, Src.second, "tobool");
553 }
554
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000555 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
556 // the imaginary part of the complex value is discarded and the value of the
557 // real part is converted according to the conversion rules for the
558 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000559 return EmitScalarConversion(Src.first, SrcTy, DstTy);
560}
561
562
Chris Lattner9fba49a2007-08-24 05:35:26 +0000563//===----------------------------------------------------------------------===//
564// Visitor Methods
565//===----------------------------------------------------------------------===//
566
567Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000568 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000569 if (E->getType()->isVoidType())
570 return 0;
Owen Andersone0b5eff2009-07-30 23:11:26 +0000571 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000572}
573
Eli Friedmand0e9d092008-05-14 19:38:39 +0000574Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
575 llvm::SmallVector<llvm::Constant*, 32> indices;
576 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
577 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
578 }
579 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
580 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Owen Anderson17971fa2009-07-28 21:22:35 +0000581 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000582 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
583}
584
Chris Lattner9fba49a2007-08-24 05:35:26 +0000585Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000586 TestAndClearIgnoreResultAssign();
587
Chris Lattner9fba49a2007-08-24 05:35:26 +0000588 // Emit subscript expressions in rvalue context's. For most cases, this just
589 // loads the lvalue formed by the subscript expr. However, we have to be
590 // careful, because the base of a vector subscript is occasionally an rvalue,
591 // so we can't get it as an lvalue.
592 if (!E->getBase()->getType()->isVectorType())
593 return EmitLoadOfLValue(E);
594
595 // Handle the vector case. The base must be a vector, the index must be an
596 // integer value.
597 Value *Base = Visit(E->getBase());
598 Value *Idx = Visit(E->getIdx());
Eli Friedman4a0073b2009-03-28 02:45:41 +0000599 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000600 Idx = Builder.CreateIntCast(Idx,
601 llvm::Type::getInt32Ty(CGF.getLLVMContext()),
602 IdxSigned,
Eli Friedmand4531942009-03-28 03:27:06 +0000603 "vecidxcast");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000604 return Builder.CreateExtractElement(Base, Idx, "vecext");
605}
606
607/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
608/// also handle things like function to pointer-to-function decay, and array to
609/// pointer decay.
610Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
611 const Expr *Op = E->getSubExpr();
612
613 // If this is due to array->pointer conversion, emit the array expression as
614 // an l-value.
615 if (Op->getType()->isArrayType()) {
Anders Carlsson5c09af02009-08-07 23:48:20 +0000616 assert(E->getCastKind() == CastExpr::CK_ArrayToPointerDecay);
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000617 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000618
Eli Friedman4a0073b2009-03-28 02:45:41 +0000619 // Note that VLA pointers are always decayed, so we don't need to do
620 // anything here.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000621 if (!Op->getType()->isVariableArrayType()) {
622 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
623 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
624 ->getElementType()) &&
625 "Expected pointer to array");
626 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar952f4732008-08-29 17:28:43 +0000627 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000628
629 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000630 // types as well (e.g. void*) and can be implicitly converted to integer.
631 const llvm::Type *DestTy = ConvertType(E->getType());
632 if (V->getType() != DestTy) {
633 if (isa<llvm::PointerType>(DestTy))
634 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
635 else {
636 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
637 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
638 }
639 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000640 return V;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000641 }
Eli Friedman4a0073b2009-03-28 02:45:41 +0000642
Chris Lattner9fba49a2007-08-24 05:35:26 +0000643 return EmitCastExpr(Op, E->getType());
644}
645
646
647// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
648// have to handle a more broad range of conversions than explicit casts, as they
649// handle things like function to ptr-to-function decay etc.
650Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000651 if (!DestTy->isVoidType())
652 TestAndClearIgnoreResultAssign();
653
Chris Lattner82e10392007-08-26 07:26:12 +0000654 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000655
656 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000657 Value *Src = Visit(const_cast<Expr*>(E));
658
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000659 // Use EmitScalarConversion to perform the conversion.
660 return EmitScalarConversion(Src, E->getType(), DestTy);
661 }
Chris Lattner77288792008-02-16 23:55:16 +0000662
Chris Lattnerde0908b2008-04-04 16:54:41 +0000663 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000664 // Handle cases where the source is a complex type.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000665 bool IgnoreImag = true;
666 bool IgnoreImagAssign = true;
667 bool IgnoreReal = IgnoreResultAssign;
668 bool IgnoreRealAssign = IgnoreResultAssign;
669 if (DestTy->isBooleanType())
670 IgnoreImagAssign = IgnoreImag = false;
671 else if (DestTy->isVoidType()) {
672 IgnoreReal = IgnoreImag = false;
673 IgnoreRealAssign = IgnoreImagAssign = true;
674 }
675 CodeGenFunction::ComplexPairTy V
676 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
677 IgnoreImagAssign);
678 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner77288792008-02-16 23:55:16 +0000679 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000680
Chris Lattner77288792008-02-16 23:55:16 +0000681 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
682 // evaluate the result and return.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000683 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner77288792008-02-16 23:55:16 +0000684 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000685}
686
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000687Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000688 return CGF.EmitCompoundStmt(*E->getSubStmt(),
689 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000690}
691
Mike Stump2b6933f2009-02-28 09:07:16 +0000692Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
693 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stumpfca5da02009-02-21 20:00:35 +0000694}
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000695
Chris Lattner9fba49a2007-08-24 05:35:26 +0000696//===----------------------------------------------------------------------===//
697// Unary Operators
698//===----------------------------------------------------------------------===//
699
700Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000701 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000702 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedman6a259872009-03-23 03:00:06 +0000703 QualType ValTy = E->getSubExpr()->getType();
704 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000705
706 llvm::LLVMContext &VMContext = CGF.getLLVMContext();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000707
708 int AmountVal = isInc ? 1 : -1;
Eli Friedman4a0073b2009-03-28 02:45:41 +0000709
710 if (ValTy->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +0000711 ValTy->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +0000712 // The amount of the addition/subtraction needs to account for the VLA size
713 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
714 }
715
Chris Lattner9fba49a2007-08-24 05:35:26 +0000716 Value *NextVal;
Chris Lattner8360c612009-03-18 04:25:13 +0000717 if (const llvm::PointerType *PT =
718 dyn_cast<llvm::PointerType>(InVal->getType())) {
Owen Anderson73e7f802009-07-14 23:10:40 +0000719 llvm::Constant *Inc =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000720 llvm::ConstantInt::get(llvm::Type::getInt32Ty(VMContext), AmountVal);
Chris Lattner8360c612009-03-18 04:25:13 +0000721 if (!isa<llvm::FunctionType>(PT->getElementType())) {
Fariborz Jahanian69b91ca2009-07-16 22:04:59 +0000722 QualType PTEE = ValTy->getPointeeType();
723 if (const ObjCInterfaceType *OIT =
724 dyn_cast<ObjCInterfaceType>(PTEE)) {
725 // Handle interface types, which are not represented with a concrete type.
726 int size = CGF.getContext().getTypeSize(OIT) / 8;
727 if (!isInc)
728 size = -size;
Owen Andersonb17ec712009-07-24 23:12:58 +0000729 Inc = llvm::ConstantInt::get(Inc->getType(), size);
Fariborz Jahanian69b91ca2009-07-16 22:04:59 +0000730 const llvm::Type *i8Ty =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000731 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Fariborz Jahanian69b91ca2009-07-16 22:04:59 +0000732 InVal = Builder.CreateBitCast(InVal, i8Ty);
733 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
734 llvm::Value *lhs = LV.getAddress();
Owen Anderson7ec2d8f2009-07-29 22:16:19 +0000735 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
Fariborz Jahanian69b91ca2009-07-16 22:04:59 +0000736 LV = LValue::MakeAddr(lhs, ValTy.getCVRQualifiers(),
737 CGF.getContext().getObjCGCAttrKind(ValTy));
Mike Stump487ce382009-07-30 22:28:39 +0000738 } else
Dan Gohman5a748242009-08-12 00:33:55 +0000739 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
Chris Lattner8360c612009-03-18 04:25:13 +0000740 } else {
Owen Anderson73e7f802009-07-14 23:10:40 +0000741 const llvm::Type *i8Ty =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000742 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Chris Lattner8360c612009-03-18 04:25:13 +0000743 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
744 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
745 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
746 }
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000747 } else if (InVal->getType() == llvm::Type::getInt1Ty(VMContext) && isInc) {
Chris Lattner49083172009-02-11 07:40:06 +0000748 // Bool++ is an interesting case, due to promotion rules, we get:
749 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
750 // Bool = ((int)Bool+1) != 0
751 // An interesting aspect of this is that increment is always true.
752 // Decrement does not have this property.
Owen Andersond3fd60e2009-07-31 17:39:36 +0000753 NextVal = llvm::ConstantInt::getTrue(VMContext);
Chris Lattner291a2b32009-06-17 06:36:24 +0000754 } else if (isa<llvm::IntegerType>(InVal->getType())) {
Owen Andersonb17ec712009-07-24 23:12:58 +0000755 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Dan Gohmanc87cf1d2009-08-12 01:16:29 +0000756
757 // Signed integer overflow is undefined behavior.
758 if (ValTy->isSignedIntegerType())
759 NextVal = Builder.CreateNSWAdd(InVal, NextVal, isInc ? "inc" : "dec");
760 else
761 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000762 } else {
763 // Add the inc/dec to the real part.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000764 if (InVal->getType() == llvm::Type::getFloatTy(VMContext))
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000765 NextVal =
Owen Andersonb56fd0b2009-07-27 21:00:51 +0000766 llvm::ConstantFP::get(VMContext,
767 llvm::APFloat(static_cast<float>(AmountVal)));
Owen Anderson3f5cc0a2009-08-13 21:57:51 +0000768 else if (InVal->getType() == llvm::Type::getDoubleTy(VMContext))
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000769 NextVal =
Owen Andersonb56fd0b2009-07-27 21:00:51 +0000770 llvm::ConstantFP::get(VMContext,
771 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000772 else {
773 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesen2461f612008-10-09 23:02:32 +0000774 bool ignored;
775 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
776 &ignored);
Owen Andersonb56fd0b2009-07-27 21:00:51 +0000777 NextVal = llvm::ConstantFP::get(VMContext, F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000778 }
Chris Lattner291a2b32009-06-17 06:36:24 +0000779 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000780 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000781
782 // Store the updated result through the lvalue.
Eli Friedman6a259872009-03-23 03:00:06 +0000783 if (LV.isBitfield())
784 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
785 &NextVal);
786 else
787 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000788
789 // If this is a postinc, return the value read from memory, otherwise use the
790 // updated value.
791 return isPre ? NextVal : InVal;
792}
793
794
795Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000796 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000797 Value *Op = Visit(E->getSubExpr());
Chris Lattner291a2b32009-06-17 06:36:24 +0000798 if (Op->getType()->isFPOrFPVector())
799 return Builder.CreateFNeg(Op, "neg");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000800 return Builder.CreateNeg(Op, "neg");
801}
802
803Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000804 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000805 Value *Op = Visit(E->getSubExpr());
806 return Builder.CreateNot(Op, "neg");
807}
808
809Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
810 // Compare operand to zero.
811 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
812
813 // Invert value.
814 // TODO: Could dynamically modify easy computations here. For example, if
815 // the operand is an icmp ne, turn into icmp eq.
816 BoolVal = Builder.CreateNot(BoolVal, "lnot");
817
Anders Carlsson62943f32009-05-19 18:44:53 +0000818 // ZExt result to the expr type.
819 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000820}
821
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000822/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
823/// argument of the sizeof expression as an integer.
824Value *
825ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000826 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000827 if (E->isSizeOf()) {
828 if (const VariableArrayType *VAT =
829 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
830 if (E->isArgumentType()) {
831 // sizeof(type) - make sure to emit the VLA size.
832 CGF.EmitVLASize(TypeToSize);
Eli Friedman04659bd2009-04-20 03:21:44 +0000833 } else {
834 // C99 6.5.3.4p2: If the argument is an expression of type
835 // VLA, it is evaluated.
836 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000837 }
Anders Carlssond309f572009-01-30 16:41:04 +0000838
Anders Carlsson8f30de92009-02-05 19:43:10 +0000839 return CGF.GetVLASize(VAT);
Anders Carlsson6cb99b72008-12-21 03:33:21 +0000840 }
Anders Carlsson9be6aaf2008-12-12 07:38:43 +0000841 }
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000842
843 // If this isn't sizeof(vla), the result must be constant; use the
844 // constant folding logic so we don't have to duplicate it here.
845 Expr::EvalResult Result;
846 E->Evaluate(Result, CGF.getContext());
Owen Andersonb17ec712009-07-24 23:12:58 +0000847 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000848}
849
Chris Lattner01211af2007-08-24 21:20:17 +0000850Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
851 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000852 if (Op->getType()->isAnyComplexType())
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000853 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner01211af2007-08-24 21:20:17 +0000854 return Visit(Op);
855}
856Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
857 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000858 if (Op->getType()->isAnyComplexType())
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000859 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000860
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000861 // __imag on a scalar returns zero. Emit the subexpr to ensure side
862 // effects are evaluated, but not the actual value.
863 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
864 CGF.EmitLValue(Op);
865 else
866 CGF.EmitScalarExpr(Op, true);
Owen Andersonf37b84b2009-07-31 20:28:54 +0000867 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000868}
869
Anders Carlsson52774ad2008-01-29 15:56:48 +0000870Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
871{
Eli Friedman342d9432009-02-27 06:44:11 +0000872 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedmanccffea92009-01-24 22:38:55 +0000873 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman342d9432009-02-27 06:44:11 +0000874 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson52774ad2008-01-29 15:56:48 +0000875}
Chris Lattner01211af2007-08-24 21:20:17 +0000876
Chris Lattner9fba49a2007-08-24 05:35:26 +0000877//===----------------------------------------------------------------------===//
878// Binary Operators
879//===----------------------------------------------------------------------===//
880
881BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000882 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000883 BinOpInfo Result;
884 Result.LHS = Visit(E->getLHS());
885 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000886 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000887 Result.E = E;
888 return Result;
889}
890
Chris Lattner0d965302007-08-26 21:41:21 +0000891Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000892 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000893 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner660e31d2007-08-24 21:00:35 +0000894 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
895
896 BinOpInfo OpInfo;
897
Eli Friedman3cd92882009-03-28 01:22:36 +0000898 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +0000899 // This needs to go through the complex expression emitter, but
Eli Friedman3cd92882009-03-28 01:22:36 +0000900 // it's a tad complicated to do that... I'm leaving it out for now.
901 // (Note that we do actually need the imaginary part of the RHS for
902 // multiplication and division.)
903 CGF.ErrorUnsupported(E, "complex compound assignment");
Owen Andersone0b5eff2009-07-30 23:11:26 +0000904 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Eli Friedman3cd92882009-03-28 01:22:36 +0000905 }
906
Mike Stump8d962262009-05-22 19:07:20 +0000907 // Emit the RHS first. __block variables need to have the rhs evaluated
908 // first, plus this should improve codegen a little.
909 OpInfo.RHS = Visit(E->getRHS());
910 OpInfo.Ty = E->getComputationResultType();
911 OpInfo.E = E;
Eli Friedman3cd92882009-03-28 01:22:36 +0000912 // Load/convert the LHS.
Chris Lattner660e31d2007-08-24 21:00:35 +0000913 LValue LHSLV = EmitLValue(E->getLHS());
914 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedman3cd92882009-03-28 01:22:36 +0000915 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
916 E->getComputationLHSType());
Chris Lattner660e31d2007-08-24 21:00:35 +0000917
918 // Expand the binary operator.
919 Value *Result = (this->*Func)(OpInfo);
920
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000921 // Convert the result back to the LHS type.
Eli Friedman3cd92882009-03-28 01:22:36 +0000922 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
923
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000924 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar2710fc92008-11-19 11:54:05 +0000925 // handled specially because the result is altered by the store,
926 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
927 // the left operand after the assignment...'.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000928 if (LHSLV.isBitfield()) {
929 if (!LHSLV.isVolatileQualified()) {
930 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
931 &Result);
932 return Result;
933 } else
934 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
935 } else
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000936 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000937 if (Ignore)
938 return 0;
939 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner660e31d2007-08-24 21:00:35 +0000940}
941
942
Chris Lattner9fba49a2007-08-24 05:35:26 +0000943Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000944 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000945 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000946 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000947 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
948 else
949 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
950}
951
952Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
953 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000954 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000955 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
956 else
957 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
958}
959
Mike Stumpdb789912009-04-01 20:28:16 +0000960Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
961 unsigned IID;
962 unsigned OpID = 0;
Mike Stump0f595bb2009-04-02 01:03:55 +0000963
Mike Stumpf71b7742009-04-02 18:15:54 +0000964 switch (Ops.E->getOpcode()) {
965 case BinaryOperator::Add:
966 case BinaryOperator::AddAssign:
967 OpID = 1;
968 IID = llvm::Intrinsic::sadd_with_overflow;
969 break;
970 case BinaryOperator::Sub:
971 case BinaryOperator::SubAssign:
972 OpID = 2;
973 IID = llvm::Intrinsic::ssub_with_overflow;
974 break;
975 case BinaryOperator::Mul:
976 case BinaryOperator::MulAssign:
977 OpID = 3;
978 IID = llvm::Intrinsic::smul_with_overflow;
979 break;
980 default:
981 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbar96e909b2009-04-08 16:23:09 +0000982 IID = 0;
Mike Stumpdb789912009-04-01 20:28:16 +0000983 }
Mike Stumpf71b7742009-04-02 18:15:54 +0000984 OpID <<= 1;
985 OpID |= 1;
986
Mike Stumpdb789912009-04-01 20:28:16 +0000987 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
988
989 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
990
991 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
992 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
993 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
994
995 // Branch in case of overflow.
996 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
997 llvm::BasicBlock *overflowBB =
998 CGF.createBasicBlock("overflow", CGF.CurFn);
999 llvm::BasicBlock *continueBB =
1000 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
1001
1002 Builder.CreateCondBr(overflow, overflowBB, continueBB);
1003
1004 // Handle overflow
1005
1006 Builder.SetInsertPoint(overflowBB);
1007
1008 // Handler is:
1009 // long long *__overflow_handler)(long long a, long long b, char op,
1010 // char width)
1011 std::vector<const llvm::Type*> handerArgTypes;
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001012 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1013 handerArgTypes.push_back(llvm::Type::getInt64Ty(VMContext));
1014 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1015 handerArgTypes.push_back(llvm::Type::getInt8Ty(VMContext));
1016 llvm::FunctionType *handlerTy = llvm::FunctionType::get(
1017 llvm::Type::getInt64Ty(VMContext), handerArgTypes, false);
Mike Stumpdb789912009-04-01 20:28:16 +00001018 llvm::Value *handlerFunction =
1019 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
Owen Anderson7ec2d8f2009-07-29 22:16:19 +00001020 llvm::PointerType::getUnqual(handlerTy));
Mike Stumpdb789912009-04-01 20:28:16 +00001021 handlerFunction = Builder.CreateLoad(handlerFunction);
1022
1023 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001024 Builder.CreateSExt(Ops.LHS, llvm::Type::getInt64Ty(VMContext)),
1025 Builder.CreateSExt(Ops.RHS, llvm::Type::getInt64Ty(VMContext)),
1026 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), OpID),
1027 llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext),
Mike Stumpdb789912009-04-01 20:28:16 +00001028 cast<llvm::IntegerType>(opTy)->getBitWidth()));
1029
1030 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1031
1032 Builder.CreateBr(continueBB);
1033
1034 // Set up the continuation
1035 Builder.SetInsertPoint(continueBB);
1036 // Get the correct result
1037 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1038 phi->reserveOperandSpace(2);
1039 phi->addIncoming(result, initialBB);
1040 phi->addIncoming(handlerResult, overflowBB);
1041
1042 return phi;
1043}
Chris Lattner9fba49a2007-08-24 05:35:26 +00001044
1045Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff79ae19a2009-07-14 18:25:06 +00001046 if (!Ops.Ty->isAnyPointerType()) {
Chris Lattner291a2b32009-06-17 06:36:24 +00001047 if (CGF.getContext().getLangOptions().OverflowChecking &&
1048 Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +00001049 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +00001050
1051 if (Ops.LHS->getType()->isFPOrFPVector())
1052 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
Dan Gohmanc87cf1d2009-08-12 01:16:29 +00001053
1054 // Signed integer overflow is undefined behavior.
1055 if (Ops.Ty->isSignedIntegerType())
1056 return Builder.CreateNSWAdd(Ops.LHS, Ops.RHS, "add");
1057
Chris Lattner9fba49a2007-08-24 05:35:26 +00001058 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stumpdb789912009-04-01 20:28:16 +00001059 }
Eli Friedman4a0073b2009-03-28 02:45:41 +00001060
Steve Naroff329ec222009-07-10 23:34:53 +00001061 if (Ops.Ty->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001062 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +00001063 // The amount of the addition needs to account for the VLA size
1064 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1065 }
Chris Lattner17c0cb02008-01-03 06:36:51 +00001066 Value *Ptr, *Idx;
1067 Expr *IdxExp;
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001068 const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>();
Steve Naroff329ec222009-07-10 23:34:53 +00001069 const ObjCObjectPointerType *OPT =
1070 Ops.E->getLHS()->getType()->getAsObjCObjectPointerType();
1071 if (PT || OPT) {
Chris Lattner17c0cb02008-01-03 06:36:51 +00001072 Ptr = Ops.LHS;
1073 Idx = Ops.RHS;
1074 IdxExp = Ops.E->getRHS();
Steve Naroff329ec222009-07-10 23:34:53 +00001075 } else { // int + pointer
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001076 PT = Ops.E->getRHS()->getType()->getAs<PointerType>();
Steve Naroff329ec222009-07-10 23:34:53 +00001077 OPT = Ops.E->getRHS()->getType()->getAsObjCObjectPointerType();
1078 assert((PT || OPT) && "Invalid add expr");
Chris Lattner17c0cb02008-01-03 06:36:51 +00001079 Ptr = Ops.RHS;
1080 Idx = Ops.LHS;
1081 IdxExp = Ops.E->getLHS();
1082 }
1083
1084 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001085 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner17c0cb02008-01-03 06:36:51 +00001086 // Zero or sign extend the pointer value based on whether the index is
1087 // signed or not.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001088 const llvm::Type *IdxType =
1089 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +00001090 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +00001091 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1092 else
1093 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1094 }
Steve Naroff329ec222009-07-10 23:34:53 +00001095 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001096 // Handle interface types, which are not represented with a concrete
1097 // type.
1098 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1099 llvm::Value *InterfaceSize =
Owen Andersonb17ec712009-07-24 23:12:58 +00001100 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001101 CGF.getContext().getTypeSize(OIT) / 8);
1102 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001103 const llvm::Type *i8Ty =
1104 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001105 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1106 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1107 return Builder.CreateBitCast(Res, Ptr->getType());
1108 }
1109
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001110 // Explicitly handle GNU void* and function pointer arithmetic
1111 // extensions. The GNU void* casts amount to no-ops since our void*
1112 // type is i8*, but this is future proof.
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001113 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001114 const llvm::Type *i8Ty =
1115 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001116 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001117 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001118 return Builder.CreateBitCast(Res, Ptr->getType());
1119 }
Chris Lattner17c0cb02008-01-03 06:36:51 +00001120
Dan Gohman5a748242009-08-12 00:33:55 +00001121 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001122}
1123
1124Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stumpdb789912009-04-01 20:28:16 +00001125 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stumpf71b7742009-04-02 18:15:54 +00001126 if (CGF.getContext().getLangOptions().OverflowChecking
1127 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +00001128 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +00001129
1130 if (Ops.LHS->getType()->isFPOrFPVector())
1131 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001132 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stumpdb789912009-04-01 20:28:16 +00001133 }
Chris Lattner660e31d2007-08-24 21:00:35 +00001134
Steve Naroff329ec222009-07-10 23:34:53 +00001135 if (Ops.E->getLHS()->getType()->isPointerType() &&
Ted Kremenekd00cd9e2009-07-29 21:53:49 +00001136 Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +00001137 // The amount of the addition needs to account for the VLA size for
1138 // ptr-int
1139 // The amount of the division needs to account for the VLA size for
1140 // ptr-ptr.
1141 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1142 }
1143
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001144 const QualType LHSType = Ops.E->getLHS()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00001145 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001146 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1147 // pointer - int
1148 Value *Idx = Ops.RHS;
1149 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001150 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001151 // Zero or sign extend the pointer value based on whether the index is
1152 // signed or not.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001153 const llvm::Type *IdxType =
1154 llvm::IntegerType::get(VMContext, CGF.LLVMPointerWidth);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001155 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1156 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1157 else
1158 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1159 }
1160 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001161
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001162 // Handle interface types, which are not represented with a concrete
1163 // type.
1164 if (const ObjCInterfaceType *OIT =
1165 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1166 llvm::Value *InterfaceSize =
Owen Andersonb17ec712009-07-24 23:12:58 +00001167 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001168 CGF.getContext().getTypeSize(OIT) / 8);
1169 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Anderson73e7f802009-07-14 23:10:40 +00001170 const llvm::Type *i8Ty =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001171 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001172 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1173 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1174 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1175 }
1176
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001177 // Explicitly handle GNU void* and function pointer arithmetic
1178 // extensions. The GNU void* casts amount to no-ops since our
1179 // void* type is i8*, but this is future proof.
1180 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Owen Anderson73e7f802009-07-14 23:10:40 +00001181 const llvm::Type *i8Ty =
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001182 llvm::PointerType::getUnqual(llvm::Type::getInt8Ty(VMContext));
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001183 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1184 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1185 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1186 }
1187
Dan Gohman5a748242009-08-12 00:33:55 +00001188 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001189 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001190 // pointer - pointer
1191 Value *LHS = Ops.LHS;
1192 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +00001193
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001194 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001195
Chris Lattner6d2e3492009-02-11 07:21:43 +00001196 // Handle GCC extension for pointer arithmetic on void* and function pointer
1197 // types.
1198 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001199 ElementSize = 1;
1200 } else {
1201 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1202 }
1203
1204 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1205 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1206 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1207 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1208
Chris Lattner6d2e3492009-02-11 07:21:43 +00001209 // Optimize out the shift for element size of 1.
1210 if (ElementSize == 1)
1211 return BytesBetween;
Dan Gohman8f61ba42009-08-11 22:40:09 +00001212
1213 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1214 // pointer difference in C is only defined in the case where both
1215 // operands are pointing to elements of an array.
Owen Andersonb17ec712009-07-24 23:12:58 +00001216 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
Dan Gohman8f61ba42009-08-11 22:40:09 +00001217 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001218 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001219}
1220
1221Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1222 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1223 // RHS to the same size as the LHS.
1224 Value *RHS = Ops.RHS;
1225 if (Ops.LHS->getType() != RHS->getType())
1226 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1227
1228 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1229}
1230
1231Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1232 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1233 // RHS to the same size as the LHS.
1234 Value *RHS = Ops.RHS;
1235 if (Ops.LHS->getType() != RHS->getType())
1236 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1237
Chris Lattner660e31d2007-08-24 21:00:35 +00001238 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +00001239 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1240 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1241}
1242
1243Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1244 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001245 TestAndClearIgnoreResultAssign();
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001246 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001247 QualType LHSTy = E->getLHS()->getType();
Chris Lattner08ac8522009-07-08 01:08:03 +00001248 if (!LHSTy->isAnyComplexType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001249 Value *LHS = Visit(E->getLHS());
1250 Value *RHS = Visit(E->getRHS());
1251
Eli Friedman04865bc2009-07-22 06:07:16 +00001252 if (LHS->getType()->isFPOrFPVector()) {
Nate Begeman1591bc52008-07-25 20:16:05 +00001253 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001254 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +00001255 } else if (LHSTy->isSignedIntegerType()) {
1256 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001257 LHS, RHS, "cmp");
1258 } else {
Eli Friedman850ea372008-05-29 15:09:15 +00001259 // Unsigned integers and pointers.
1260 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001261 LHS, RHS, "cmp");
1262 }
Chris Lattner08ac8522009-07-08 01:08:03 +00001263
1264 // If this is a vector comparison, sign extend the result to the appropriate
1265 // vector integer type and return it (don't convert to bool).
1266 if (LHSTy->isVectorType())
1267 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Nate Begeman1591bc52008-07-25 20:16:05 +00001268
Chris Lattner9fba49a2007-08-24 05:35:26 +00001269 } else {
1270 // Complex Comparison: can only be an equality comparison.
1271 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1272 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1273
Chris Lattnerc154ac12008-07-26 22:37:01 +00001274 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001275
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001276 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001277 if (CETy->isRealFloatingType()) {
1278 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1279 LHS.first, RHS.first, "cmp.r");
1280 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1281 LHS.second, RHS.second, "cmp.i");
1282 } else {
1283 // Complex comparisons can only be equality comparisons. As such, signed
1284 // and unsigned opcodes are the same.
1285 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1286 LHS.first, RHS.first, "cmp.r");
1287 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1288 LHS.second, RHS.second, "cmp.i");
1289 }
1290
1291 if (E->getOpcode() == BinaryOperator::EQ) {
1292 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1293 } else {
1294 assert(E->getOpcode() == BinaryOperator::NE &&
1295 "Complex comparison other than == or != ?");
1296 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1297 }
1298 }
Nuno Lopes92577002009-01-11 23:22:37 +00001299
1300 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001301}
1302
1303Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001304 bool Ignore = TestAndClearIgnoreResultAssign();
1305
1306 // __block variables need to have the rhs evaluated first, plus this should
1307 // improve codegen just a little.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001308 Value *RHS = Visit(E->getRHS());
Mike Stump68df15c2009-05-21 21:05:15 +00001309 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001310
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001311 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar2710fc92008-11-19 11:54:05 +00001312 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1313 // 'An assignment expression has the value of the left operand after
Eli Friedman4a0073b2009-03-28 02:45:41 +00001314 // the assignment...'.
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001315 if (LHS.isBitfield()) {
1316 if (!LHS.isVolatileQualified()) {
1317 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1318 &RHS);
1319 return RHS;
1320 } else
1321 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1322 } else
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001323 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001324 if (Ignore)
1325 return 0;
1326 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001327}
1328
1329Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001330 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1331 // If we have 1 && X, just emit X without inserting the control flow.
1332 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1333 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001334 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1335 // ZExt result to int.
1336 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1337 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001338
1339 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1340 if (!CGF.ContainsLabel(E->getRHS()))
Owen Andersonf37b84b2009-07-31 20:28:54 +00001341 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001342 }
1343
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001344 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1345 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner715c2a72008-11-12 08:26:50 +00001346
Chris Lattner7f80bb32008-11-12 08:38:24 +00001347 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1348 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1349
1350 // Any edges into the ContBlock are now from an (indeterminate number of)
1351 // edges from this first condition. All of these values will be false. Start
1352 // setting up the PHI node in the Cont Block for this.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001353 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1354 "", ContBlock);
Chris Lattner7f80bb32008-11-12 08:38:24 +00001355 PN->reserveOperandSpace(2); // Normal case, two inputs.
1356 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1357 PI != PE; ++PI)
Owen Andersond3fd60e2009-07-31 17:39:36 +00001358 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001359
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001360 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001361 CGF.EmitBlock(RHSBlock);
1362 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001363 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001364
1365 // Reaquire the RHS block, as there may be subblocks inserted.
1366 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f80bb32008-11-12 08:38:24 +00001367
1368 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1369 // into the phi node for the edge with the value of RHSCond.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001370 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001371 PN->addIncoming(RHSCond, RHSBlock);
1372
1373 // ZExt result to int.
1374 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1375}
1376
1377Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001378 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1379 // If we have 0 || X, just emit X without inserting the control flow.
1380 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1381 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001382 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1383 // ZExt result to int.
1384 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1385 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001386
Eli Friedmanea137cd2008-12-02 16:02:46 +00001387 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner715c2a72008-11-12 08:26:50 +00001388 if (!CGF.ContainsLabel(E->getRHS()))
Owen Andersonb17ec712009-07-24 23:12:58 +00001389 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001390 }
1391
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001392 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1393 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001394
Chris Lattner7f80bb32008-11-12 08:38:24 +00001395 // Branch on the LHS first. If it is true, go to the success (cont) block.
1396 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1397
1398 // Any edges into the ContBlock are now from an (indeterminate number of)
1399 // edges from this first condition. All of these values will be true. Start
1400 // setting up the PHI node in the Cont Block for this.
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001401 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext),
1402 "", ContBlock);
Chris Lattner7f80bb32008-11-12 08:38:24 +00001403 PN->reserveOperandSpace(2); // Normal case, two inputs.
1404 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1405 PI != PE; ++PI)
Owen Andersond3fd60e2009-07-31 17:39:36 +00001406 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattner7f80bb32008-11-12 08:38:24 +00001407
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001408 CGF.PushConditionalTempDestruction();
1409
Chris Lattner7f80bb32008-11-12 08:38:24 +00001410 // Emit the RHS condition as a bool value.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001411 CGF.EmitBlock(RHSBlock);
1412 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1413
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001414 CGF.PopConditionalTempDestruction();
1415
Chris Lattner9fba49a2007-08-24 05:35:26 +00001416 // Reaquire the RHS block, as there may be subblocks inserted.
1417 RHSBlock = Builder.GetInsertBlock();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001418
Chris Lattner7f80bb32008-11-12 08:38:24 +00001419 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1420 // into the phi node for the edge with the value of RHSCond.
1421 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001422 PN->addIncoming(RHSCond, RHSBlock);
1423
1424 // ZExt result to int.
1425 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1426}
1427
1428Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1429 CGF.EmitStmt(E->getLHS());
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001430 CGF.EnsureInsertPoint();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001431 return Visit(E->getRHS());
1432}
1433
1434//===----------------------------------------------------------------------===//
1435// Other Operators
1436//===----------------------------------------------------------------------===//
1437
Chris Lattner504a5282008-11-12 08:55:54 +00001438/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1439/// expression is cheap enough and side-effect-free enough to evaluate
1440/// unconditionally instead of conditionally. This is used to convert control
1441/// flow into selects in some cases.
1442static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1443 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1444 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1445
1446 // TODO: Allow anything we can constant fold to an integer or fp constant.
1447 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1448 isa<FloatingLiteral>(E))
1449 return true;
1450
1451 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1452 // X and Y are local variables.
1453 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1454 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1455 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1456 return true;
1457
1458 return false;
1459}
1460
1461
Chris Lattner9fba49a2007-08-24 05:35:26 +00001462Value *ScalarExprEmitter::
1463VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001464 TestAndClearIgnoreResultAssign();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001465 // If the condition constant folds and can be elided, try to avoid emitting
1466 // the condition and the dead arm.
1467 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattner044bffc2008-11-11 18:56:45 +00001468 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001469 if (Cond == -1)
Chris Lattner044bffc2008-11-11 18:56:45 +00001470 std::swap(Live, Dead);
Chris Lattner3d6606b2008-11-12 08:04:58 +00001471
1472 // If the dead side doesn't have labels we need, and if the Live side isn't
1473 // the gnu missing ?: extension (which we could handle, but don't bother
1474 // to), just emit the Live part.
1475 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1476 Live) // Live part isn't missing.
1477 return Visit(Live);
Chris Lattner044bffc2008-11-11 18:56:45 +00001478 }
1479
Chris Lattner504a5282008-11-12 08:55:54 +00001480
1481 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1482 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner1f11af22008-11-16 06:16:27 +00001483 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner504a5282008-11-12 08:55:54 +00001484 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1485 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1486 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1487 llvm::Value *LHS = Visit(E->getLHS());
1488 llvm::Value *RHS = Visit(E->getRHS());
1489 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1490 }
1491
1492
Daniel Dunbarb23e9922008-11-12 10:13:37 +00001493 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1494 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001495 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner67e22462008-11-12 08:08:13 +00001496 Value *CondVal = 0;
Chris Lattner3d6606b2008-11-12 08:04:58 +00001497
Chris Lattner86031712009-02-13 23:35:32 +00001498 // If we don't have the GNU missing condition extension, emit a branch on
1499 // bool the normal way.
1500 if (E->getLHS()) {
1501 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1502 // the branch on bool.
1503 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1504 } else {
1505 // Otherwise, for the ?: extension, evaluate the conditional and then
1506 // convert it to bool the hard way. We do this explicitly because we need
1507 // the unconverted value for the missing middle value of the ?:.
Chris Lattner67e22462008-11-12 08:08:13 +00001508 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner86031712009-02-13 23:35:32 +00001509
1510 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1511 // if there are no extra uses (an optimization). Inhibit this by making an
1512 // extra dead use, because we're going to add a use of CondVal later. We
1513 // don't use the builder for this, because we don't want it to get optimized
1514 // away. This leaves dead code, but the ?: extension isn't common.
1515 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1516 Builder.GetInsertBlock());
1517
Chris Lattner67e22462008-11-12 08:08:13 +00001518 Value *CondBoolVal =
1519 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1520 CGF.getContext().BoolTy);
1521 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner67e22462008-11-12 08:08:13 +00001522 }
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001523
1524 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001525 CGF.EmitBlock(LHSBlock);
1526
1527 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001528 Value *LHS;
1529 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001530 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001531 else // Perform promotions, to handle cases like "short ?: int"
1532 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1533
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001534 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001535 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001536 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001537
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001538 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001539 CGF.EmitBlock(RHSBlock);
1540
Eli Friedmance8d7032008-05-16 20:38:39 +00001541 Value *RHS = Visit(E->getRHS());
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001542 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001543 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001544 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001545
1546 CGF.EmitBlock(ContBlock);
1547
Nuno Lopesb62ff242008-06-04 19:15:45 +00001548 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001549 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1550 return 0;
1551 }
1552
Chris Lattner9fba49a2007-08-24 05:35:26 +00001553 // Create a PHI node for the real part.
1554 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1555 PN->reserveOperandSpace(2);
1556 PN->addIncoming(LHS, LHSBlock);
1557 PN->addIncoming(RHS, RHSBlock);
1558 return PN;
1559}
1560
1561Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmand540c112009-03-04 05:52:32 +00001562 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001563}
1564
Chris Lattner307da022007-11-30 17:56:23 +00001565Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman8f5e8782009-01-20 17:46:04 +00001566 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson285611e2008-11-04 05:30:00 +00001567 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1568
1569 // If EmitVAArg fails, we fall back to the LLVM instruction.
1570 if (!ArgPtr)
1571 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1572
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001573 // FIXME Volatility.
Anders Carlsson285611e2008-11-04 05:30:00 +00001574 return Builder.CreateLoad(ArgPtr);
Anders Carlsson36760332007-10-15 20:28:48 +00001575}
1576
Mike Stump4eb81dc2009-02-12 18:29:15 +00001577Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump1fa52fe2009-03-07 02:35:30 +00001578 return CGF.BuildBlockLiteralTmp(BE);
Mike Stump4eb81dc2009-02-12 18:29:15 +00001579}
1580
Chris Lattner9fba49a2007-08-24 05:35:26 +00001581//===----------------------------------------------------------------------===//
1582// Entry Point into this File
1583//===----------------------------------------------------------------------===//
1584
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001585/// EmitScalarExpr - Emit the computation of the specified expression of
1586/// scalar type, ignoring the result.
1587Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001588 assert(E && !hasAggregateLLVMType(E->getType()) &&
1589 "Invalid scalar expression to emit");
1590
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001591 return ScalarExprEmitter(*this, IgnoreResultAssign)
1592 .Visit(const_cast<Expr*>(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001593}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001594
1595/// EmitScalarConversion - Emit a conversion from the specified type to the
1596/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001597Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1598 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001599 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1600 "Invalid scalar expression to emit");
1601 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1602}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001603
1604/// EmitComplexToScalarConversion - Emit a conversion from the specified
1605/// complex type to the specified destination type, where the destination
1606/// type is an LLVM scalar type.
1607Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1608 QualType SrcTy,
1609 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001610 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001611 "Invalid complex -> scalar conversion");
1612 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1613 DstTy);
1614}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001615
1616Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1617 assert(V1->getType() == V2->getType() &&
1618 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001619 unsigned NumElements =
1620 cast<llvm::VectorType>(V1->getType())->getNumElements();
1621
1622 va_list va;
1623 va_start(va, V2);
1624
1625 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001626 for (unsigned i = 0; i < NumElements; i++) {
1627 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001628 assert(n >= 0 && n < (int)NumElements * 2 &&
1629 "Vector shuffle index out of bounds!");
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001630 Args.push_back(llvm::ConstantInt::get(
1631 llvm::Type::getInt32Ty(VMContext), n));
Anders Carlssona9234fe2007-12-10 19:35:18 +00001632 }
1633
1634 const char *Name = va_arg(va, const char *);
1635 va_end(va);
1636
Owen Anderson17971fa2009-07-28 21:22:35 +00001637 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001638
1639 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1640}
1641
Anders Carlsson68b8be92007-12-15 21:23:30 +00001642llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001643 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001644 llvm::Value *Vec
Owen Andersone0b5eff2009-07-30 23:11:26 +00001645 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001646
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001647 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001648 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Owen Anderson3f5cc0a2009-08-13 21:57:51 +00001649 llvm::Value *Idx = llvm::ConstantInt::get(
1650 llvm::Type::getInt32Ty(VMContext), i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001651 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001652 }
1653
1654 return Vec;
1655}