blob: 5ded216f03abbf26908c631e2f63abbc17d21a47 [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 Anderson73e7f802009-07-14 23:10:40 +0000124 return VMContext.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 Anderson73e7f802009-07-14 23:10:40 +0000127 return VMContext.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 Andersonb17ec712009-07-24 23:12:58 +0000137 llvm::ConstantInt::get(llvm::Type::Int32Ty,
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 Anderson73e7f802009-07-14 23:10:40 +0000203 llvm::Value *V = VMContext.getUndef(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 Andersonb17ec712009-07-24 23:12:58 +0000209 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Devang Patel32c39832007-10-24 18:05:48 +0000210 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel01ab1302007-10-24 17:18:43 +0000211 }
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000212
213 // Emit remaining default initializers
214 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
Owen Andersonb17ec712009-07-24 23:12:58 +0000215 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Owen Anderson73e7f802009-07-14 23:10:40 +0000216 llvm::Value *NewV = VMContext.getNullValue(ElementType);
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000217 V = Builder.CreateInsertElement(V, NewV, Idx);
218 }
219
Devang Patel32c39832007-10-24 18:05:48 +0000220 return V;
Devang Patel01ab1302007-10-24 17:18:43 +0000221 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000222
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000223 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Owen Anderson73e7f802009-07-14 23:10:40 +0000224 return VMContext.getNullValue(ConvertType(E->getType()));
Douglas Gregorc9e012a2009-01-29 17:44:32 +0000225 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000226 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
Eli Friedmana7ef8e52009-04-20 03:54:15 +0000227 Value *VisitCastExpr(const CastExpr *E) {
228 // Make sure to evaluate VLA bounds now so that we have them for later.
229 if (E->getType()->isVariablyModifiedType())
230 CGF.EmitVLASize(E->getType());
231
Chris Lattner9fba49a2007-08-24 05:35:26 +0000232 return EmitCastExpr(E->getSubExpr(), E->getType());
233 }
234 Value *EmitCastExpr(const Expr *E, QualType T);
235
236 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssoncd295282009-05-27 03:37:57 +0000237 if (E->getCallReturnType()->isReferenceType())
238 return EmitLoadOfLValue(E);
239
Chris Lattnere24c4cf2007-08-31 22:49:20 +0000240 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000241 }
Daniel Dunbara04840b2008-08-23 03:46:30 +0000242
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000243 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpfca5da02009-02-21 20:00:35 +0000244
Mike Stump2b6933f2009-02-28 09:07:16 +0000245 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000246
Chris Lattner9fba49a2007-08-24 05:35:26 +0000247 // Unary Operators.
248 Value *VisitPrePostIncDec(const UnaryOperator *E, bool isInc, bool isPre);
249 Value *VisitUnaryPostDec(const UnaryOperator *E) {
250 return VisitPrePostIncDec(E, false, false);
251 }
252 Value *VisitUnaryPostInc(const UnaryOperator *E) {
253 return VisitPrePostIncDec(E, true, false);
254 }
255 Value *VisitUnaryPreDec(const UnaryOperator *E) {
256 return VisitPrePostIncDec(E, false, true);
257 }
258 Value *VisitUnaryPreInc(const UnaryOperator *E) {
259 return VisitPrePostIncDec(E, true, true);
260 }
261 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
262 return EmitLValue(E->getSubExpr()).getAddress();
263 }
264 Value *VisitUnaryDeref(const Expr *E) { return EmitLoadOfLValue(E); }
265 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000266 // This differs from gcc, though, most likely due to a bug in gcc.
267 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000268 return Visit(E->getSubExpr());
269 }
270 Value *VisitUnaryMinus (const UnaryOperator *E);
271 Value *VisitUnaryNot (const UnaryOperator *E);
272 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner01211af2007-08-24 21:20:17 +0000273 Value *VisitUnaryReal (const UnaryOperator *E);
274 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000275 Value *VisitUnaryExtension(const UnaryOperator *E) {
276 return Visit(E->getSubExpr());
277 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000278 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Anders Carlsson49d4a572009-04-14 16:58:56 +0000279
280 // C++
Chris Lattner3e254fb2008-04-08 04:40:51 +0000281 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
282 return Visit(DAE->getExpr());
283 }
Anders Carlsson49d4a572009-04-14 16:58:56 +0000284 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
285 return CGF.LoadCXXThis();
286 }
Anders Carlsson52774ad2008-01-29 15:56:48 +0000287
Anders Carlsson272b5f52009-05-19 04:48:36 +0000288 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlssond6775602009-05-31 00:09:15 +0000289 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlsson272b5f52009-05-19 04:48:36 +0000290 }
Anders Carlsson18e88bc2009-05-31 01:40:14 +0000291 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
292 return CGF.EmitCXXNewExpr(E);
293 }
Anders Carlsson272b5f52009-05-19 04:48:36 +0000294
Chris Lattner9fba49a2007-08-24 05:35:26 +0000295 // Binary Operators.
Chris Lattner9fba49a2007-08-24 05:35:26 +0000296 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stumpf71b7742009-04-02 18:15:54 +0000297 if (CGF.getContext().getLangOptions().OverflowChecking
298 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +0000299 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +0000300 if (Ops.LHS->getType()->isFPOrFPVector())
301 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000302 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
303 }
Mike Stumpdb789912009-04-01 20:28:16 +0000304 /// Create a binary op that checks for overflow.
305 /// Currently only supports +, - and *.
306 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000307 Value *EmitDiv(const BinOpInfo &Ops);
308 Value *EmitRem(const BinOpInfo &Ops);
309 Value *EmitAdd(const BinOpInfo &Ops);
310 Value *EmitSub(const BinOpInfo &Ops);
311 Value *EmitShl(const BinOpInfo &Ops);
312 Value *EmitShr(const BinOpInfo &Ops);
313 Value *EmitAnd(const BinOpInfo &Ops) {
314 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
315 }
316 Value *EmitXor(const BinOpInfo &Ops) {
317 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
318 }
319 Value *EmitOr (const BinOpInfo &Ops) {
320 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
321 }
322
Chris Lattner660e31d2007-08-24 21:00:35 +0000323 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattner0d965302007-08-26 21:41:21 +0000324 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000325 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
326
327 // Binary operators and binary compound assignment operators.
328#define HANDLEBINOP(OP) \
Chris Lattner0d965302007-08-26 21:41:21 +0000329 Value *VisitBin ## OP(const BinaryOperator *E) { \
330 return Emit ## OP(EmitBinOps(E)); \
331 } \
332 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
333 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner660e31d2007-08-24 21:00:35 +0000334 }
335 HANDLEBINOP(Mul);
336 HANDLEBINOP(Div);
337 HANDLEBINOP(Rem);
338 HANDLEBINOP(Add);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000339 HANDLEBINOP(Sub);
Chris Lattner660e31d2007-08-24 21:00:35 +0000340 HANDLEBINOP(Shl);
341 HANDLEBINOP(Shr);
342 HANDLEBINOP(And);
343 HANDLEBINOP(Xor);
344 HANDLEBINOP(Or);
345#undef HANDLEBINOP
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000346
Chris Lattner9fba49a2007-08-24 05:35:26 +0000347 // Comparisons.
348 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
349 unsigned SICmpOpc, unsigned FCmpOpc);
350#define VISITCOMP(CODE, UI, SI, FP) \
351 Value *VisitBin##CODE(const BinaryOperator *E) { \
352 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
353 llvm::FCmpInst::FP); }
354 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT);
355 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT);
356 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE);
357 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE);
358 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ);
359 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE);
360#undef VISITCOMP
361
362 Value *VisitBinAssign (const BinaryOperator *E);
363
364 Value *VisitBinLAnd (const BinaryOperator *E);
365 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000366 Value *VisitBinComma (const BinaryOperator *E);
367
368 // Other Operators.
Mike Stump4eb81dc2009-02-12 18:29:15 +0000369 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000370 Value *VisitConditionalOperator(const ConditionalOperator *CO);
371 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson36760332007-10-15 20:28:48 +0000372 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000373 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
374 return CGF.EmitObjCStringLiteral(E);
375 }
376};
377} // end anonymous namespace.
378
379//===----------------------------------------------------------------------===//
380// Utilities
381//===----------------------------------------------------------------------===//
382
Chris Lattnerd8d44222007-08-26 16:42:57 +0000383/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner05942062007-08-26 17:25:57 +0000384/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnerd8d44222007-08-26 16:42:57 +0000385Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
386 assert(SrcType->isCanonical() && "EmitScalarConversion strips typedefs");
387
388 if (SrcType->isRealFloatingType()) {
389 // Compare against 0.0 for fp scalars.
Owen Anderson73e7f802009-07-14 23:10:40 +0000390 llvm::Value *Zero = VMContext.getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000391 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
392 }
393
Daniel Dunbar5d54eed2008-08-25 10:38:11 +0000394 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnerd8d44222007-08-26 16:42:57 +0000395 "Unknown scalar type to convert");
396
397 // Because of the type rules of C, we often end up computing a logical value,
398 // then zero extending it to int, then wanting it as a logical value again.
399 // Optimize this common case.
400 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
401 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
402 Value *Result = ZI->getOperand(0);
Eli Friedman24f33972008-01-29 18:13:51 +0000403 // If there aren't any more uses, zap the instruction to save space.
404 // Note that there can be more uses, for example if this
405 // is the result of an assignment.
406 if (ZI->use_empty())
407 ZI->eraseFromParent();
Chris Lattnerd8d44222007-08-26 16:42:57 +0000408 return Result;
409 }
410 }
411
412 // Compare against an integer or pointer null.
Owen Anderson73e7f802009-07-14 23:10:40 +0000413 llvm::Value *Zero = VMContext.getNullValue(Src->getType());
Chris Lattnerd8d44222007-08-26 16:42:57 +0000414 return Builder.CreateICmpNE(Src, Zero, "tobool");
415}
416
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000417/// EmitScalarConversion - Emit a conversion from the specified type to the
418/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000419Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
420 QualType DstType) {
Chris Lattnerc154ac12008-07-26 22:37:01 +0000421 SrcType = CGF.getContext().getCanonicalType(SrcType);
422 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000423 if (SrcType == DstType) return Src;
Chris Lattnere133d7f2007-08-26 07:21:11 +0000424
425 if (DstType->isVoidType()) return 0;
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000426
427 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc39c3652007-08-26 16:52:28 +0000428 if (DstType->isBooleanType())
429 return EmitConversionToBool(Src, SrcType);
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000430
431 const llvm::Type *DstTy = ConvertType(DstType);
432
433 // Ignore conversions like int -> uint.
434 if (Src->getType() == DstTy)
435 return Src;
436
Daniel Dunbar238335f2008-08-25 09:51:32 +0000437 // Handle pointer conversions next: pointers can only be converted
438 // to/from other pointers and integers. Check for pointer types in
439 // terms of LLVM, as some native types (like Obj-C id) may map to a
440 // pointer type.
441 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000442 // The source value may be an integer, or a pointer.
Fariborz Jahanianf7f6cf82009-07-28 22:00:58 +0000443 if (isa<llvm::PointerType>(Src->getType())) {
444 // Some heavy lifting for derived to base conversion.
445 if (const PointerType *PT = SrcType->getAsPointerType()) {
446 QualType SrcClassTy = PT->getPointeeType();
447 if (const RecordType *RT = SrcClassTy->getAsRecordType())
448 if (CXXRecordDecl *ClassDecl =
449 dyn_cast<CXXRecordDecl>(RT->getDecl())) {
450 QualType DstClassType = DstType->getPointeeType();
451 if (const RecordType *DRT = DstClassType->getAsRecordType())
452 if (CXXRecordDecl *BaseClassDecl =
453 dyn_cast<CXXRecordDecl>(DRT->getDecl()))
454 Src = CGF.AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl);
455 }
456 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000457 return Builder.CreateBitCast(Src, DstTy, "conv");
Fariborz Jahanianf7f6cf82009-07-28 22:00:58 +0000458 }
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000459 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman35bcec82009-03-04 04:02:35 +0000460 // First, convert to the correct width so that we control the kind of
461 // extension.
Owen Anderson73e7f802009-07-14 23:10:40 +0000462 const llvm::Type *MiddleTy = VMContext.getIntegerType(CGF.LLVMPointerWidth);
Eli Friedman35bcec82009-03-04 04:02:35 +0000463 bool InputSigned = SrcType->isSignedIntegerType();
464 llvm::Value* IntResult =
465 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
466 // Then, cast to pointer.
467 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000468 }
469
Daniel Dunbar238335f2008-08-25 09:51:32 +0000470 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000471 // Must be an ptr to int cast.
472 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson44db38f2007-10-31 23:18:02 +0000473 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000474 }
475
Nate Begemanaf6ed502008-04-18 23:10:10 +0000476 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman7903d052009-01-18 06:42:49 +0000477 if (DstType->isExtVectorType() && !isa<VectorType>(SrcType)) {
478 // Cast the scalar to element type
479 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
480 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
481
482 // Insert the element in element zero of an undef vector
Owen Anderson73e7f802009-07-14 23:10:40 +0000483 llvm::Value *UnV = VMContext.getUndef(DstTy);
Owen Andersonb17ec712009-07-24 23:12:58 +0000484 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Nate Begeman7903d052009-01-18 06:42:49 +0000485 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
486
487 // Splat the element across to all elements
488 llvm::SmallVector<llvm::Constant*, 16> Args;
489 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
490 for (unsigned i = 0; i < NumElements; i++)
Owen Andersonb17ec712009-07-24 23:12:58 +0000491 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Nate Begeman7903d052009-01-18 06:42:49 +0000492
Owen Anderson17971fa2009-07-28 21:22:35 +0000493 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Nate Begeman7903d052009-01-18 06:42:49 +0000494 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
495 return Yay;
496 }
Nate Begemanec2d1062007-12-30 02:59:45 +0000497
Chris Lattner4f025a42008-02-02 04:51:41 +0000498 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000499 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner4f025a42008-02-02 04:51:41 +0000500 isa<llvm::VectorType>(DstTy))
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000501 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson4513ecb2007-12-05 07:36:10 +0000502
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000503 // Finally, we have the arithmetic types: real int/float.
504 if (isa<llvm::IntegerType>(Src->getType())) {
505 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000506 if (isa<llvm::IntegerType>(DstTy))
507 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
508 else if (InputSigned)
509 return Builder.CreateSIToFP(Src, DstTy, "conv");
510 else
511 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000512 }
513
514 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
515 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000516 if (DstType->isSignedIntegerType())
517 return Builder.CreateFPToSI(Src, DstTy, "conv");
518 else
519 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000520 }
521
522 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlsson4dac3f42007-12-26 18:20:19 +0000523 if (DstTy->getTypeID() < Src->getType()->getTypeID())
524 return Builder.CreateFPTrunc(Src, DstTy, "conv");
525 else
526 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000527}
528
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000529/// EmitComplexToScalarConversion - Emit a conversion from the specified
530/// complex type to the specified destination type, where the destination
531/// type is an LLVM scalar type.
532Value *ScalarExprEmitter::
533EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
534 QualType SrcTy, QualType DstTy) {
Chris Lattnerc39c3652007-08-26 16:52:28 +0000535 // Get the source element type.
Chris Lattnerc154ac12008-07-26 22:37:01 +0000536 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc39c3652007-08-26 16:52:28 +0000537
538 // Handle conversions to bool first, they are special: comparisons against 0.
539 if (DstTy->isBooleanType()) {
540 // Complex != 0 -> (Real != 0) | (Imag != 0)
541 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
542 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
543 return Builder.CreateOr(Src.first, Src.second, "tobool");
544 }
545
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000546 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
547 // the imaginary part of the complex value is discarded and the value of the
548 // real part is converted according to the conversion rules for the
549 // corresponding real type.
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000550 return EmitScalarConversion(Src.first, SrcTy, DstTy);
551}
552
553
Chris Lattner9fba49a2007-08-24 05:35:26 +0000554//===----------------------------------------------------------------------===//
555// Visitor Methods
556//===----------------------------------------------------------------------===//
557
558Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar9503b782008-08-16 00:56:44 +0000559 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000560 if (E->getType()->isVoidType())
561 return 0;
Owen Anderson73e7f802009-07-14 23:10:40 +0000562 return VMContext.getUndef(CGF.ConvertType(E->getType()));
Chris Lattner9fba49a2007-08-24 05:35:26 +0000563}
564
Eli Friedmand0e9d092008-05-14 19:38:39 +0000565Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
566 llvm::SmallVector<llvm::Constant*, 32> indices;
567 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
568 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
569 }
570 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
571 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Owen Anderson17971fa2009-07-28 21:22:35 +0000572 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
Eli Friedmand0e9d092008-05-14 19:38:39 +0000573 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
574}
575
Chris Lattner9fba49a2007-08-24 05:35:26 +0000576Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000577 TestAndClearIgnoreResultAssign();
578
Chris Lattner9fba49a2007-08-24 05:35:26 +0000579 // Emit subscript expressions in rvalue context's. For most cases, this just
580 // loads the lvalue formed by the subscript expr. However, we have to be
581 // careful, because the base of a vector subscript is occasionally an rvalue,
582 // so we can't get it as an lvalue.
583 if (!E->getBase()->getType()->isVectorType())
584 return EmitLoadOfLValue(E);
585
586 // Handle the vector case. The base must be a vector, the index must be an
587 // integer value.
588 Value *Base = Visit(E->getBase());
589 Value *Idx = Visit(E->getIdx());
Eli Friedman4a0073b2009-03-28 02:45:41 +0000590 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Eli Friedmand4531942009-03-28 03:27:06 +0000591 Idx = Builder.CreateIntCast(Idx, llvm::Type::Int32Ty, IdxSigned,
592 "vecidxcast");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000593 return Builder.CreateExtractElement(Base, Idx, "vecext");
594}
595
596/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
597/// also handle things like function to pointer-to-function decay, and array to
598/// pointer decay.
599Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
600 const Expr *Op = E->getSubExpr();
601
602 // If this is due to array->pointer conversion, emit the array expression as
603 // an l-value.
604 if (Op->getType()->isArrayType()) {
Chris Lattnerfb182ee2007-08-26 16:34:22 +0000605 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000606
Eli Friedman4a0073b2009-03-28 02:45:41 +0000607 // Note that VLA pointers are always decayed, so we don't need to do
608 // anything here.
Eli Friedman8fef47e2008-12-20 23:11:59 +0000609 if (!Op->getType()->isVariableArrayType()) {
610 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
611 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
612 ->getElementType()) &&
613 "Expected pointer to array");
614 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbar952f4732008-08-29 17:28:43 +0000615 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000616
617 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattner3b8f5c62008-07-23 06:31:27 +0000618 // types as well (e.g. void*) and can be implicitly converted to integer.
619 const llvm::Type *DestTy = ConvertType(E->getType());
620 if (V->getType() != DestTy) {
621 if (isa<llvm::PointerType>(DestTy))
622 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
623 else {
624 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
625 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
626 }
627 }
Chris Lattnere54443b2007-12-12 04:13:20 +0000628 return V;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000629 }
Eli Friedman4a0073b2009-03-28 02:45:41 +0000630
Chris Lattner9fba49a2007-08-24 05:35:26 +0000631 return EmitCastExpr(Op, E->getType());
632}
633
634
635// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
636// have to handle a more broad range of conversions than explicit casts, as they
637// handle things like function to ptr-to-function decay etc.
638Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000639 if (!DestTy->isVoidType())
640 TestAndClearIgnoreResultAssign();
641
Chris Lattner82e10392007-08-26 07:26:12 +0000642 // Handle cases where the source is an non-complex type.
Chris Lattner77288792008-02-16 23:55:16 +0000643
644 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000645 Value *Src = Visit(const_cast<Expr*>(E));
646
Chris Lattner4e05d1e2007-08-26 06:48:56 +0000647 // Use EmitScalarConversion to perform the conversion.
648 return EmitScalarConversion(Src, E->getType(), DestTy);
649 }
Chris Lattner77288792008-02-16 23:55:16 +0000650
Chris Lattnerde0908b2008-04-04 16:54:41 +0000651 if (E->getType()->isAnyComplexType()) {
Chris Lattner77288792008-02-16 23:55:16 +0000652 // Handle cases where the source is a complex type.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000653 bool IgnoreImag = true;
654 bool IgnoreImagAssign = true;
655 bool IgnoreReal = IgnoreResultAssign;
656 bool IgnoreRealAssign = IgnoreResultAssign;
657 if (DestTy->isBooleanType())
658 IgnoreImagAssign = IgnoreImag = false;
659 else if (DestTy->isVoidType()) {
660 IgnoreReal = IgnoreImag = false;
661 IgnoreRealAssign = IgnoreImagAssign = true;
662 }
663 CodeGenFunction::ComplexPairTy V
664 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
665 IgnoreImagAssign);
666 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattner77288792008-02-16 23:55:16 +0000667 }
Chris Lattnerd579f7f2007-08-26 07:16:41 +0000668
Chris Lattner77288792008-02-16 23:55:16 +0000669 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
670 // evaluate the result and return.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000671 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattner77288792008-02-16 23:55:16 +0000672 return 0;
Chris Lattner9fba49a2007-08-24 05:35:26 +0000673}
674
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000675Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner09cee852008-07-26 20:23:23 +0000676 return CGF.EmitCompoundStmt(*E->getSubStmt(),
677 !E->getType()->isVoidType()).getScalarVal();
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000678}
679
Mike Stump2b6933f2009-02-28 09:07:16 +0000680Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
681 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stumpfca5da02009-02-21 20:00:35 +0000682}
Chris Lattnerea6cdd72007-08-31 22:09:40 +0000683
Chris Lattner9fba49a2007-08-24 05:35:26 +0000684//===----------------------------------------------------------------------===//
685// Unary Operators
686//===----------------------------------------------------------------------===//
687
688Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner855e3d72007-08-24 16:24:49 +0000689 bool isInc, bool isPre) {
Chris Lattner9fba49a2007-08-24 05:35:26 +0000690 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedman6a259872009-03-23 03:00:06 +0000691 QualType ValTy = E->getSubExpr()->getType();
692 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000693
694 int AmountVal = isInc ? 1 : -1;
Eli Friedman4a0073b2009-03-28 02:45:41 +0000695
696 if (ValTy->isPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +0000697 ValTy->getAsPointerType()->isVariableArrayType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +0000698 // The amount of the addition/subtraction needs to account for the VLA size
699 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
700 }
701
Chris Lattner9fba49a2007-08-24 05:35:26 +0000702 Value *NextVal;
Chris Lattner8360c612009-03-18 04:25:13 +0000703 if (const llvm::PointerType *PT =
704 dyn_cast<llvm::PointerType>(InVal->getType())) {
Owen Anderson73e7f802009-07-14 23:10:40 +0000705 llvm::Constant *Inc =
Owen Andersonb17ec712009-07-24 23:12:58 +0000706 llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattner8360c612009-03-18 04:25:13 +0000707 if (!isa<llvm::FunctionType>(PT->getElementType())) {
Fariborz Jahanian69b91ca2009-07-16 22:04:59 +0000708 QualType PTEE = ValTy->getPointeeType();
709 if (const ObjCInterfaceType *OIT =
710 dyn_cast<ObjCInterfaceType>(PTEE)) {
711 // Handle interface types, which are not represented with a concrete type.
712 int size = CGF.getContext().getTypeSize(OIT) / 8;
713 if (!isInc)
714 size = -size;
Owen Andersonb17ec712009-07-24 23:12:58 +0000715 Inc = llvm::ConstantInt::get(Inc->getType(), size);
Fariborz Jahanian69b91ca2009-07-16 22:04:59 +0000716 const llvm::Type *i8Ty =
717 VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
718 InVal = Builder.CreateBitCast(InVal, i8Ty);
719 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
720 llvm::Value *lhs = LV.getAddress();
721 lhs = Builder.CreateBitCast(lhs, VMContext.getPointerTypeUnqual(i8Ty));
722 LV = LValue::MakeAddr(lhs, ValTy.getCVRQualifiers(),
723 CGF.getContext().getObjCGCAttrKind(ValTy));
724 }
725 else
726 NextVal = Builder.CreateGEP(InVal, Inc, "ptrincdec");
Chris Lattner8360c612009-03-18 04:25:13 +0000727 } else {
Owen Anderson73e7f802009-07-14 23:10:40 +0000728 const llvm::Type *i8Ty =
729 VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Chris Lattner8360c612009-03-18 04:25:13 +0000730 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
731 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
732 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
733 }
Chris Lattner49083172009-02-11 07:40:06 +0000734 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
735 // Bool++ is an interesting case, due to promotion rules, we get:
736 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
737 // Bool = ((int)Bool+1) != 0
738 // An interesting aspect of this is that increment is always true.
739 // Decrement does not have this property.
Owen Anderson0ce92b42009-07-21 18:06:41 +0000740 NextVal = VMContext.getTrue();
Chris Lattner291a2b32009-06-17 06:36:24 +0000741 } else if (isa<llvm::IntegerType>(InVal->getType())) {
Owen Andersonb17ec712009-07-24 23:12:58 +0000742 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattner291a2b32009-06-17 06:36:24 +0000743 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000744 } else {
745 // Add the inc/dec to the real part.
Chris Lattner291a2b32009-06-17 06:36:24 +0000746 if (InVal->getType() == llvm::Type::FloatTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000747 NextVal =
Owen Andersonb56fd0b2009-07-27 21:00:51 +0000748 llvm::ConstantFP::get(VMContext,
749 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000750 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patel0f2a8fb2007-10-30 20:59:40 +0000751 NextVal =
Owen Andersonb56fd0b2009-07-27 21:00:51 +0000752 llvm::ConstantFP::get(VMContext,
753 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerd54d1f22008-04-20 00:50:39 +0000754 else {
755 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesen2461f612008-10-09 23:02:32 +0000756 bool ignored;
757 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
758 &ignored);
Owen Andersonb56fd0b2009-07-27 21:00:51 +0000759 NextVal = llvm::ConstantFP::get(VMContext, F);
Chris Lattnerb2a7dab2007-09-13 06:19:18 +0000760 }
Chris Lattner291a2b32009-06-17 06:36:24 +0000761 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattner0dc11f62007-08-26 05:10:16 +0000762 }
Chris Lattner9fba49a2007-08-24 05:35:26 +0000763
764 // Store the updated result through the lvalue.
Eli Friedman6a259872009-03-23 03:00:06 +0000765 if (LV.isBitfield())
766 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
767 &NextVal);
768 else
769 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner9fba49a2007-08-24 05:35:26 +0000770
771 // If this is a postinc, return the value read from memory, otherwise use the
772 // updated value.
773 return isPre ? NextVal : InVal;
774}
775
776
777Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000778 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000779 Value *Op = Visit(E->getSubExpr());
Chris Lattner291a2b32009-06-17 06:36:24 +0000780 if (Op->getType()->isFPOrFPVector())
781 return Builder.CreateFNeg(Op, "neg");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000782 return Builder.CreateNeg(Op, "neg");
783}
784
785Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000786 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000787 Value *Op = Visit(E->getSubExpr());
788 return Builder.CreateNot(Op, "neg");
789}
790
791Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
792 // Compare operand to zero.
793 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
794
795 // Invert value.
796 // TODO: Could dynamically modify easy computations here. For example, if
797 // the operand is an icmp ne, turn into icmp eq.
798 BoolVal = Builder.CreateNot(BoolVal, "lnot");
799
Anders Carlsson62943f32009-05-19 18:44:53 +0000800 // ZExt result to the expr type.
801 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner9fba49a2007-08-24 05:35:26 +0000802}
803
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000804/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
805/// argument of the sizeof expression as an integer.
806Value *
807ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl0cb7c872008-11-11 17:56:53 +0000808 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000809 if (E->isSizeOf()) {
810 if (const VariableArrayType *VAT =
811 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
812 if (E->isArgumentType()) {
813 // sizeof(type) - make sure to emit the VLA size.
814 CGF.EmitVLASize(TypeToSize);
Eli Friedman04659bd2009-04-20 03:21:44 +0000815 } else {
816 // C99 6.5.3.4p2: If the argument is an expression of type
817 // VLA, it is evaluated.
818 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000819 }
Anders Carlssond309f572009-01-30 16:41:04 +0000820
Anders Carlsson8f30de92009-02-05 19:43:10 +0000821 return CGF.GetVLASize(VAT);
Anders Carlsson6cb99b72008-12-21 03:33:21 +0000822 }
Anders Carlsson9be6aaf2008-12-12 07:38:43 +0000823 }
Eli Friedman5a2c38f2009-01-24 22:19:05 +0000824
825 // If this isn't sizeof(vla), the result must be constant; use the
826 // constant folding logic so we don't have to duplicate it here.
827 Expr::EvalResult Result;
828 E->Evaluate(Result, CGF.getContext());
Owen Andersonb17ec712009-07-24 23:12:58 +0000829 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner9fba49a2007-08-24 05:35:26 +0000830}
831
Chris Lattner01211af2007-08-24 21:20:17 +0000832Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
833 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000834 if (Op->getType()->isAnyComplexType())
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000835 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner01211af2007-08-24 21:20:17 +0000836 return Visit(Op);
837}
838Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
839 Expr *Op = E->getSubExpr();
Chris Lattnerde0908b2008-04-04 16:54:41 +0000840 if (Op->getType()->isAnyComplexType())
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000841 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Chris Lattnerdb8a6c92007-08-26 05:29:21 +0000842
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000843 // __imag on a scalar returns zero. Emit the subexpr to ensure side
844 // effects are evaluated, but not the actual value.
845 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
846 CGF.EmitLValue(Op);
847 else
848 CGF.EmitScalarExpr(Op, true);
Owen Anderson73e7f802009-07-14 23:10:40 +0000849 return VMContext.getNullValue(ConvertType(E->getType()));
Chris Lattner01211af2007-08-24 21:20:17 +0000850}
851
Anders Carlsson52774ad2008-01-29 15:56:48 +0000852Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
853{
Eli Friedman342d9432009-02-27 06:44:11 +0000854 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedmanccffea92009-01-24 22:38:55 +0000855 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman342d9432009-02-27 06:44:11 +0000856 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlsson52774ad2008-01-29 15:56:48 +0000857}
Chris Lattner01211af2007-08-24 21:20:17 +0000858
Chris Lattner9fba49a2007-08-24 05:35:26 +0000859//===----------------------------------------------------------------------===//
860// Binary Operators
861//===----------------------------------------------------------------------===//
862
863BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000864 TestAndClearIgnoreResultAssign();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000865 BinOpInfo Result;
866 Result.LHS = Visit(E->getLHS());
867 Result.RHS = Visit(E->getRHS());
Chris Lattner660e31d2007-08-24 21:00:35 +0000868 Result.Ty = E->getType();
Chris Lattner9fba49a2007-08-24 05:35:26 +0000869 Result.E = E;
870 return Result;
871}
872
Chris Lattner0d965302007-08-26 21:41:21 +0000873Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner660e31d2007-08-24 21:00:35 +0000874 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000875 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner660e31d2007-08-24 21:00:35 +0000876 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
877
878 BinOpInfo OpInfo;
879
Eli Friedman3cd92882009-03-28 01:22:36 +0000880 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +0000881 // This needs to go through the complex expression emitter, but
Eli Friedman3cd92882009-03-28 01:22:36 +0000882 // it's a tad complicated to do that... I'm leaving it out for now.
883 // (Note that we do actually need the imaginary part of the RHS for
884 // multiplication and division.)
885 CGF.ErrorUnsupported(E, "complex compound assignment");
Owen Anderson73e7f802009-07-14 23:10:40 +0000886 return VMContext.getUndef(CGF.ConvertType(E->getType()));
Eli Friedman3cd92882009-03-28 01:22:36 +0000887 }
888
Mike Stump8d962262009-05-22 19:07:20 +0000889 // Emit the RHS first. __block variables need to have the rhs evaluated
890 // first, plus this should improve codegen a little.
891 OpInfo.RHS = Visit(E->getRHS());
892 OpInfo.Ty = E->getComputationResultType();
893 OpInfo.E = E;
Eli Friedman3cd92882009-03-28 01:22:36 +0000894 // Load/convert the LHS.
Chris Lattner660e31d2007-08-24 21:00:35 +0000895 LValue LHSLV = EmitLValue(E->getLHS());
896 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedman3cd92882009-03-28 01:22:36 +0000897 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
898 E->getComputationLHSType());
Chris Lattner660e31d2007-08-24 21:00:35 +0000899
900 // Expand the binary operator.
901 Value *Result = (this->*Func)(OpInfo);
902
Daniel Dunbar5d7d0382008-08-06 02:00:38 +0000903 // Convert the result back to the LHS type.
Eli Friedman3cd92882009-03-28 01:22:36 +0000904 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
905
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000906 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar2710fc92008-11-19 11:54:05 +0000907 // handled specially because the result is altered by the store,
908 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
909 // the left operand after the assignment...'.
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000910 if (LHSLV.isBitfield()) {
911 if (!LHSLV.isVolatileQualified()) {
912 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
913 &Result);
914 return Result;
915 } else
916 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
917 } else
Daniel Dunbar2668dd12008-11-19 09:36:46 +0000918 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stumpb8fc73e2009-05-29 15:46:01 +0000919 if (Ignore)
920 return 0;
921 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner660e31d2007-08-24 21:00:35 +0000922}
923
924
Chris Lattner9fba49a2007-08-24 05:35:26 +0000925Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begemanaade3bf2007-12-30 01:28:16 +0000926 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000927 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner660e31d2007-08-24 21:00:35 +0000928 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000929 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
930 else
931 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
932}
933
934Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
935 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner660e31d2007-08-24 21:00:35 +0000936 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +0000937 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
938 else
939 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
940}
941
Mike Stumpdb789912009-04-01 20:28:16 +0000942Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
943 unsigned IID;
944 unsigned OpID = 0;
Mike Stump0f595bb2009-04-02 01:03:55 +0000945
Mike Stumpf71b7742009-04-02 18:15:54 +0000946 switch (Ops.E->getOpcode()) {
947 case BinaryOperator::Add:
948 case BinaryOperator::AddAssign:
949 OpID = 1;
950 IID = llvm::Intrinsic::sadd_with_overflow;
951 break;
952 case BinaryOperator::Sub:
953 case BinaryOperator::SubAssign:
954 OpID = 2;
955 IID = llvm::Intrinsic::ssub_with_overflow;
956 break;
957 case BinaryOperator::Mul:
958 case BinaryOperator::MulAssign:
959 OpID = 3;
960 IID = llvm::Intrinsic::smul_with_overflow;
961 break;
962 default:
963 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbar96e909b2009-04-08 16:23:09 +0000964 IID = 0;
Mike Stumpdb789912009-04-01 20:28:16 +0000965 }
Mike Stumpf71b7742009-04-02 18:15:54 +0000966 OpID <<= 1;
967 OpID |= 1;
968
Mike Stumpdb789912009-04-01 20:28:16 +0000969 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
970
971 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
972
973 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
974 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
975 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
976
977 // Branch in case of overflow.
978 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
979 llvm::BasicBlock *overflowBB =
980 CGF.createBasicBlock("overflow", CGF.CurFn);
981 llvm::BasicBlock *continueBB =
982 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
983
984 Builder.CreateCondBr(overflow, overflowBB, continueBB);
985
986 // Handle overflow
987
988 Builder.SetInsertPoint(overflowBB);
989
990 // Handler is:
991 // long long *__overflow_handler)(long long a, long long b, char op,
992 // char width)
993 std::vector<const llvm::Type*> handerArgTypes;
994 handerArgTypes.push_back(llvm::Type::Int64Ty);
995 handerArgTypes.push_back(llvm::Type::Int64Ty);
996 handerArgTypes.push_back(llvm::Type::Int8Ty);
997 handerArgTypes.push_back(llvm::Type::Int8Ty);
Owen Anderson73e7f802009-07-14 23:10:40 +0000998 llvm::FunctionType *handlerTy = VMContext.getFunctionType(llvm::Type::Int64Ty,
Mike Stumpdb789912009-04-01 20:28:16 +0000999 handerArgTypes, false);
1000 llvm::Value *handlerFunction =
1001 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
Owen Anderson73e7f802009-07-14 23:10:40 +00001002 VMContext.getPointerTypeUnqual(handlerTy));
Mike Stumpdb789912009-04-01 20:28:16 +00001003 handlerFunction = Builder.CreateLoad(handlerFunction);
1004
1005 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
1006 Builder.CreateSExt(Ops.LHS, llvm::Type::Int64Ty),
1007 Builder.CreateSExt(Ops.RHS, llvm::Type::Int64Ty),
Owen Andersonb17ec712009-07-24 23:12:58 +00001008 llvm::ConstantInt::get(llvm::Type::Int8Ty, OpID),
1009 llvm::ConstantInt::get(llvm::Type::Int8Ty,
Mike Stumpdb789912009-04-01 20:28:16 +00001010 cast<llvm::IntegerType>(opTy)->getBitWidth()));
1011
1012 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1013
1014 Builder.CreateBr(continueBB);
1015
1016 // Set up the continuation
1017 Builder.SetInsertPoint(continueBB);
1018 // Get the correct result
1019 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1020 phi->reserveOperandSpace(2);
1021 phi->addIncoming(result, initialBB);
1022 phi->addIncoming(handlerResult, overflowBB);
1023
1024 return phi;
1025}
Chris Lattner9fba49a2007-08-24 05:35:26 +00001026
1027Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff79ae19a2009-07-14 18:25:06 +00001028 if (!Ops.Ty->isAnyPointerType()) {
Chris Lattner291a2b32009-06-17 06:36:24 +00001029 if (CGF.getContext().getLangOptions().OverflowChecking &&
1030 Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +00001031 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +00001032
1033 if (Ops.LHS->getType()->isFPOrFPVector())
1034 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1035
Chris Lattner9fba49a2007-08-24 05:35:26 +00001036 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stumpdb789912009-04-01 20:28:16 +00001037 }
Eli Friedman4a0073b2009-03-28 02:45:41 +00001038
Steve Naroff329ec222009-07-10 23:34:53 +00001039 if (Ops.Ty->isPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001040 Ops.Ty->getAsPointerType()->isVariableArrayType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +00001041 // The amount of the addition needs to account for the VLA size
1042 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1043 }
Chris Lattner17c0cb02008-01-03 06:36:51 +00001044 Value *Ptr, *Idx;
1045 Expr *IdxExp;
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001046 const PointerType *PT = Ops.E->getLHS()->getType()->getAsPointerType();
Steve Naroff329ec222009-07-10 23:34:53 +00001047 const ObjCObjectPointerType *OPT =
1048 Ops.E->getLHS()->getType()->getAsObjCObjectPointerType();
1049 if (PT || OPT) {
Chris Lattner17c0cb02008-01-03 06:36:51 +00001050 Ptr = Ops.LHS;
1051 Idx = Ops.RHS;
1052 IdxExp = Ops.E->getRHS();
Steve Naroff329ec222009-07-10 23:34:53 +00001053 } else { // int + pointer
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001054 PT = Ops.E->getRHS()->getType()->getAsPointerType();
Steve Naroff329ec222009-07-10 23:34:53 +00001055 OPT = Ops.E->getRHS()->getType()->getAsObjCObjectPointerType();
1056 assert((PT || OPT) && "Invalid add expr");
Chris Lattner17c0cb02008-01-03 06:36:51 +00001057 Ptr = Ops.RHS;
1058 Idx = Ops.LHS;
1059 IdxExp = Ops.E->getLHS();
1060 }
1061
1062 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001063 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner17c0cb02008-01-03 06:36:51 +00001064 // Zero or sign extend the pointer value based on whether the index is
1065 // signed or not.
Owen Anderson73e7f802009-07-14 23:10:40 +00001066 const llvm::Type *IdxType = VMContext.getIntegerType(CGF.LLVMPointerWidth);
Chris Lattnerc154ac12008-07-26 22:37:01 +00001067 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner17c0cb02008-01-03 06:36:51 +00001068 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1069 else
1070 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1071 }
Steve Naroff329ec222009-07-10 23:34:53 +00001072 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001073 // Handle interface types, which are not represented with a concrete
1074 // type.
1075 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1076 llvm::Value *InterfaceSize =
Owen Andersonb17ec712009-07-24 23:12:58 +00001077 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001078 CGF.getContext().getTypeSize(OIT) / 8);
1079 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Anderson73e7f802009-07-14 23:10:40 +00001080 const llvm::Type *i8Ty = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001081 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1082 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1083 return Builder.CreateBitCast(Res, Ptr->getType());
1084 }
1085
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001086 // Explicitly handle GNU void* and function pointer arithmetic
1087 // extensions. The GNU void* casts amount to no-ops since our void*
1088 // type is i8*, but this is future proof.
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001089 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Owen Anderson73e7f802009-07-14 23:10:40 +00001090 const llvm::Type *i8Ty = VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001091 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001092 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001093 return Builder.CreateBitCast(Res, Ptr->getType());
1094 }
Chris Lattner17c0cb02008-01-03 06:36:51 +00001095
1096 return Builder.CreateGEP(Ptr, Idx, "add.ptr");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001097}
1098
1099Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stumpdb789912009-04-01 20:28:16 +00001100 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stumpf71b7742009-04-02 18:15:54 +00001101 if (CGF.getContext().getLangOptions().OverflowChecking
1102 && Ops.Ty->isSignedIntegerType())
Mike Stumpdb789912009-04-01 20:28:16 +00001103 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner291a2b32009-06-17 06:36:24 +00001104
1105 if (Ops.LHS->getType()->isFPOrFPVector())
1106 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001107 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stumpdb789912009-04-01 20:28:16 +00001108 }
Chris Lattner660e31d2007-08-24 21:00:35 +00001109
Steve Naroff329ec222009-07-10 23:34:53 +00001110 if (Ops.E->getLHS()->getType()->isPointerType() &&
Ted Kremenekd9b39bf2009-07-17 17:50:17 +00001111 Ops.E->getLHS()->getType()->getAsPointerType()->isVariableArrayType()) {
Eli Friedman4a0073b2009-03-28 02:45:41 +00001112 // The amount of the addition needs to account for the VLA size for
1113 // ptr-int
1114 // The amount of the division needs to account for the VLA size for
1115 // ptr-ptr.
1116 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1117 }
1118
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001119 const QualType LHSType = Ops.E->getLHS()->getType();
Steve Naroff329ec222009-07-10 23:34:53 +00001120 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001121 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1122 // pointer - int
1123 Value *Idx = Ops.RHS;
1124 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Guptacee8fea2009-04-24 02:40:57 +00001125 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001126 // Zero or sign extend the pointer value based on whether the index is
1127 // signed or not.
Owen Anderson73e7f802009-07-14 23:10:40 +00001128 const llvm::Type *IdxType =
1129 VMContext.getIntegerType(CGF.LLVMPointerWidth);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001130 if (Ops.E->getRHS()->getType()->isSignedIntegerType())
1131 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1132 else
1133 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1134 }
1135 Idx = Builder.CreateNeg(Idx, "sub.ptr.neg");
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001136
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001137 // Handle interface types, which are not represented with a concrete
1138 // type.
1139 if (const ObjCInterfaceType *OIT =
1140 dyn_cast<ObjCInterfaceType>(LHSElementType)) {
1141 llvm::Value *InterfaceSize =
Owen Andersonb17ec712009-07-24 23:12:58 +00001142 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001143 CGF.getContext().getTypeSize(OIT) / 8);
1144 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Anderson73e7f802009-07-14 23:10:40 +00001145 const llvm::Type *i8Ty =
1146 VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbar6864c0d2009-04-25 05:08:32 +00001147 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1148 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "add.ptr");
1149 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1150 }
1151
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001152 // Explicitly handle GNU void* and function pointer arithmetic
1153 // extensions. The GNU void* casts amount to no-ops since our
1154 // void* type is i8*, but this is future proof.
1155 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Owen Anderson73e7f802009-07-14 23:10:40 +00001156 const llvm::Type *i8Ty =
1157 VMContext.getPointerTypeUnqual(llvm::Type::Int8Ty);
Daniel Dunbar4fd58ab2009-01-23 18:51:09 +00001158 Value *LHSCasted = Builder.CreateBitCast(Ops.LHS, i8Ty);
1159 Value *Res = Builder.CreateGEP(LHSCasted, Idx, "sub.ptr");
1160 return Builder.CreateBitCast(Res, Ops.LHS->getType());
1161 }
1162
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001163 return Builder.CreateGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001164 } else {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001165 // pointer - pointer
1166 Value *LHS = Ops.LHS;
1167 Value *RHS = Ops.RHS;
Chris Lattner660e31d2007-08-24 21:00:35 +00001168
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001169 uint64_t ElementSize;
Daniel Dunbar0aac9f62008-08-05 00:47:03 +00001170
Chris Lattner6d2e3492009-02-11 07:21:43 +00001171 // Handle GCC extension for pointer arithmetic on void* and function pointer
1172 // types.
1173 if (LHSElementType->isVoidType() || LHSElementType->isFunctionType()) {
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001174 ElementSize = 1;
1175 } else {
1176 ElementSize = CGF.getContext().getTypeSize(LHSElementType) / 8;
1177 }
1178
1179 const llvm::Type *ResultType = ConvertType(Ops.Ty);
1180 LHS = Builder.CreatePtrToInt(LHS, ResultType, "sub.ptr.lhs.cast");
1181 RHS = Builder.CreatePtrToInt(RHS, ResultType, "sub.ptr.rhs.cast");
1182 Value *BytesBetween = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
1183
Chris Lattner6d2e3492009-02-11 07:21:43 +00001184 // Optimize out the shift for element size of 1.
1185 if (ElementSize == 1)
1186 return BytesBetween;
1187
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001188 // HACK: LLVM doesn't have an divide instruction that 'knows' there is no
1189 // remainder. As such, we handle common power-of-two cases here to generate
1190 // better code. See PR2247.
1191 if (llvm::isPowerOf2_64(ElementSize)) {
1192 Value *ShAmt =
Owen Andersonb17ec712009-07-24 23:12:58 +00001193 llvm::ConstantInt::get(ResultType, llvm::Log2_64(ElementSize));
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001194 return Builder.CreateAShr(BytesBetween, ShAmt, "sub.ptr.shr");
1195 }
1196
1197 // Otherwise, do a full sdiv.
Owen Andersonb17ec712009-07-24 23:12:58 +00001198 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
Daniel Dunbar5d7d0382008-08-06 02:00:38 +00001199 return Builder.CreateSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001200 }
Chris Lattner9fba49a2007-08-24 05:35:26 +00001201}
1202
1203Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1204 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1205 // RHS to the same size as the LHS.
1206 Value *RHS = Ops.RHS;
1207 if (Ops.LHS->getType() != RHS->getType())
1208 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1209
1210 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1211}
1212
1213Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1214 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1215 // RHS to the same size as the LHS.
1216 Value *RHS = Ops.RHS;
1217 if (Ops.LHS->getType() != RHS->getType())
1218 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1219
Chris Lattner660e31d2007-08-24 21:00:35 +00001220 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner9fba49a2007-08-24 05:35:26 +00001221 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1222 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1223}
1224
1225Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1226 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001227 TestAndClearIgnoreResultAssign();
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001228 Value *Result;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001229 QualType LHSTy = E->getLHS()->getType();
Chris Lattner08ac8522009-07-08 01:08:03 +00001230 if (!LHSTy->isAnyComplexType()) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001231 Value *LHS = Visit(E->getLHS());
1232 Value *RHS = Visit(E->getRHS());
1233
Eli Friedman04865bc2009-07-22 06:07:16 +00001234 if (LHS->getType()->isFPOrFPVector()) {
Nate Begeman1591bc52008-07-25 20:16:05 +00001235 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001236 LHS, RHS, "cmp");
Eli Friedman850ea372008-05-29 15:09:15 +00001237 } else if (LHSTy->isSignedIntegerType()) {
1238 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001239 LHS, RHS, "cmp");
1240 } else {
Eli Friedman850ea372008-05-29 15:09:15 +00001241 // Unsigned integers and pointers.
1242 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner9fba49a2007-08-24 05:35:26 +00001243 LHS, RHS, "cmp");
1244 }
Chris Lattner08ac8522009-07-08 01:08:03 +00001245
1246 // If this is a vector comparison, sign extend the result to the appropriate
1247 // vector integer type and return it (don't convert to bool).
1248 if (LHSTy->isVectorType())
1249 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Nate Begeman1591bc52008-07-25 20:16:05 +00001250
Chris Lattner9fba49a2007-08-24 05:35:26 +00001251 } else {
1252 // Complex Comparison: can only be an equality comparison.
1253 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1254 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1255
Chris Lattnerc154ac12008-07-26 22:37:01 +00001256 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001257
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001258 Value *ResultR, *ResultI;
Chris Lattner9fba49a2007-08-24 05:35:26 +00001259 if (CETy->isRealFloatingType()) {
1260 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1261 LHS.first, RHS.first, "cmp.r");
1262 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1263 LHS.second, RHS.second, "cmp.i");
1264 } else {
1265 // Complex comparisons can only be equality comparisons. As such, signed
1266 // and unsigned opcodes are the same.
1267 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1268 LHS.first, RHS.first, "cmp.r");
1269 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1270 LHS.second, RHS.second, "cmp.i");
1271 }
1272
1273 if (E->getOpcode() == BinaryOperator::EQ) {
1274 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1275 } else {
1276 assert(E->getOpcode() == BinaryOperator::NE &&
1277 "Complex comparison other than == or != ?");
1278 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1279 }
1280 }
Nuno Lopes92577002009-01-11 23:22:37 +00001281
1282 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001283}
1284
1285Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001286 bool Ignore = TestAndClearIgnoreResultAssign();
1287
1288 // __block variables need to have the rhs evaluated first, plus this should
1289 // improve codegen just a little.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001290 Value *RHS = Visit(E->getRHS());
Mike Stump68df15c2009-05-21 21:05:15 +00001291 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001292
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001293 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar2710fc92008-11-19 11:54:05 +00001294 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1295 // 'An assignment expression has the value of the left operand after
Eli Friedman4a0073b2009-03-28 02:45:41 +00001296 // the assignment...'.
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001297 if (LHS.isBitfield()) {
1298 if (!LHS.isVolatileQualified()) {
1299 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1300 &RHS);
1301 return RHS;
1302 } else
1303 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1304 } else
Daniel Dunbar2668dd12008-11-19 09:36:46 +00001305 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001306 if (Ignore)
1307 return 0;
1308 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner9fba49a2007-08-24 05:35:26 +00001309}
1310
1311Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001312 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1313 // If we have 1 && X, just emit X without inserting the control flow.
1314 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1315 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001316 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1317 // ZExt result to int.
1318 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1319 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001320
1321 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1322 if (!CGF.ContainsLabel(E->getRHS()))
Owen Anderson73e7f802009-07-14 23:10:40 +00001323 return VMContext.getNullValue(CGF.LLVMIntTy);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001324 }
1325
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001326 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1327 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner715c2a72008-11-12 08:26:50 +00001328
Chris Lattner7f80bb32008-11-12 08:38:24 +00001329 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1330 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1331
1332 // Any edges into the ContBlock are now from an (indeterminate number of)
1333 // edges from this first condition. All of these values will be false. Start
1334 // setting up the PHI node in the Cont Block for this.
1335 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1336 PN->reserveOperandSpace(2); // Normal case, two inputs.
1337 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1338 PI != PE; ++PI)
Owen Anderson0ce92b42009-07-21 18:06:41 +00001339 PN->addIncoming(VMContext.getFalse(), *PI);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001340
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001341 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001342 CGF.EmitBlock(RHSBlock);
1343 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001344 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001345
1346 // Reaquire the RHS block, as there may be subblocks inserted.
1347 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f80bb32008-11-12 08:38:24 +00001348
1349 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1350 // into the phi node for the edge with the value of RHSCond.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001351 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001352 PN->addIncoming(RHSCond, RHSBlock);
1353
1354 // ZExt result to int.
1355 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1356}
1357
1358Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner715c2a72008-11-12 08:26:50 +00001359 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1360 // If we have 0 || X, just emit X without inserting the control flow.
1361 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1362 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001363 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1364 // ZExt result to int.
1365 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1366 }
Chris Lattner715c2a72008-11-12 08:26:50 +00001367
Eli Friedmanea137cd2008-12-02 16:02:46 +00001368 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner715c2a72008-11-12 08:26:50 +00001369 if (!CGF.ContainsLabel(E->getRHS()))
Owen Andersonb17ec712009-07-24 23:12:58 +00001370 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner3f73d0d2008-11-11 07:41:27 +00001371 }
1372
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001373 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1374 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner9fba49a2007-08-24 05:35:26 +00001375
Chris Lattner7f80bb32008-11-12 08:38:24 +00001376 // Branch on the LHS first. If it is true, go to the success (cont) block.
1377 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1378
1379 // Any edges into the ContBlock are now from an (indeterminate number of)
1380 // edges from this first condition. All of these values will be true. Start
1381 // setting up the PHI node in the Cont Block for this.
1382 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1383 PN->reserveOperandSpace(2); // Normal case, two inputs.
1384 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1385 PI != PE; ++PI)
Owen Anderson0ce92b42009-07-21 18:06:41 +00001386 PN->addIncoming(VMContext.getTrue(), *PI);
Chris Lattner7f80bb32008-11-12 08:38:24 +00001387
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001388 CGF.PushConditionalTempDestruction();
1389
Chris Lattner7f80bb32008-11-12 08:38:24 +00001390 // Emit the RHS condition as a bool value.
Chris Lattner9fba49a2007-08-24 05:35:26 +00001391 CGF.EmitBlock(RHSBlock);
1392 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1393
Anders Carlssonac36c0e2009-06-04 02:53:13 +00001394 CGF.PopConditionalTempDestruction();
1395
Chris Lattner9fba49a2007-08-24 05:35:26 +00001396 // Reaquire the RHS block, as there may be subblocks inserted.
1397 RHSBlock = Builder.GetInsertBlock();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001398
Chris Lattner7f80bb32008-11-12 08:38:24 +00001399 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1400 // into the phi node for the edge with the value of RHSCond.
1401 CGF.EmitBlock(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001402 PN->addIncoming(RHSCond, RHSBlock);
1403
1404 // ZExt result to int.
1405 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1406}
1407
1408Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1409 CGF.EmitStmt(E->getLHS());
Daniel Dunbar5aa22bc2008-11-11 23:11:34 +00001410 CGF.EnsureInsertPoint();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001411 return Visit(E->getRHS());
1412}
1413
1414//===----------------------------------------------------------------------===//
1415// Other Operators
1416//===----------------------------------------------------------------------===//
1417
Chris Lattner504a5282008-11-12 08:55:54 +00001418/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1419/// expression is cheap enough and side-effect-free enough to evaluate
1420/// unconditionally instead of conditionally. This is used to convert control
1421/// flow into selects in some cases.
1422static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1423 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1424 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1425
1426 // TODO: Allow anything we can constant fold to an integer or fp constant.
1427 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1428 isa<FloatingLiteral>(E))
1429 return true;
1430
1431 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1432 // X and Y are local variables.
1433 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1434 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1435 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1436 return true;
1437
1438 return false;
1439}
1440
1441
Chris Lattner9fba49a2007-08-24 05:35:26 +00001442Value *ScalarExprEmitter::
1443VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001444 TestAndClearIgnoreResultAssign();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001445 // If the condition constant folds and can be elided, try to avoid emitting
1446 // the condition and the dead arm.
1447 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattner044bffc2008-11-11 18:56:45 +00001448 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattner3d6606b2008-11-12 08:04:58 +00001449 if (Cond == -1)
Chris Lattner044bffc2008-11-11 18:56:45 +00001450 std::swap(Live, Dead);
Chris Lattner3d6606b2008-11-12 08:04:58 +00001451
1452 // If the dead side doesn't have labels we need, and if the Live side isn't
1453 // the gnu missing ?: extension (which we could handle, but don't bother
1454 // to), just emit the Live part.
1455 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1456 Live) // Live part isn't missing.
1457 return Visit(Live);
Chris Lattner044bffc2008-11-11 18:56:45 +00001458 }
1459
Chris Lattner504a5282008-11-12 08:55:54 +00001460
1461 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1462 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner1f11af22008-11-16 06:16:27 +00001463 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner504a5282008-11-12 08:55:54 +00001464 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1465 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1466 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1467 llvm::Value *LHS = Visit(E->getLHS());
1468 llvm::Value *RHS = Visit(E->getRHS());
1469 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1470 }
1471
1472
Daniel Dunbarb23e9922008-11-12 10:13:37 +00001473 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1474 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar6e3a10c2008-11-13 01:38:36 +00001475 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner67e22462008-11-12 08:08:13 +00001476 Value *CondVal = 0;
Chris Lattner3d6606b2008-11-12 08:04:58 +00001477
Chris Lattner86031712009-02-13 23:35:32 +00001478 // If we don't have the GNU missing condition extension, emit a branch on
1479 // bool the normal way.
1480 if (E->getLHS()) {
1481 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1482 // the branch on bool.
1483 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1484 } else {
1485 // Otherwise, for the ?: extension, evaluate the conditional and then
1486 // convert it to bool the hard way. We do this explicitly because we need
1487 // the unconverted value for the missing middle value of the ?:.
Chris Lattner67e22462008-11-12 08:08:13 +00001488 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattner86031712009-02-13 23:35:32 +00001489
1490 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1491 // if there are no extra uses (an optimization). Inhibit this by making an
1492 // extra dead use, because we're going to add a use of CondVal later. We
1493 // don't use the builder for this, because we don't want it to get optimized
1494 // away. This leaves dead code, but the ?: extension isn't common.
1495 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1496 Builder.GetInsertBlock());
1497
Chris Lattner67e22462008-11-12 08:08:13 +00001498 Value *CondBoolVal =
1499 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1500 CGF.getContext().BoolTy);
1501 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner67e22462008-11-12 08:08:13 +00001502 }
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001503
1504 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001505 CGF.EmitBlock(LHSBlock);
1506
1507 // Handle the GNU extension for missing LHS.
Chris Lattner98a425c2007-11-26 01:40:58 +00001508 Value *LHS;
1509 if (E->getLHS())
Eli Friedmance8d7032008-05-16 20:38:39 +00001510 LHS = Visit(E->getLHS());
Chris Lattner98a425c2007-11-26 01:40:58 +00001511 else // Perform promotions, to handle cases like "short ?: int"
1512 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1513
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001514 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001515 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001516 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001517
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001518 CGF.PushConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001519 CGF.EmitBlock(RHSBlock);
1520
Eli Friedmance8d7032008-05-16 20:38:39 +00001521 Value *RHS = Visit(E->getRHS());
Anders Carlssonbf3b93a2009-06-04 03:00:32 +00001522 CGF.PopConditionalTempDestruction();
Chris Lattner9fba49a2007-08-24 05:35:26 +00001523 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbar5276caa2008-11-11 09:41:28 +00001524 CGF.EmitBranch(ContBlock);
Chris Lattner9fba49a2007-08-24 05:35:26 +00001525
1526 CGF.EmitBlock(ContBlock);
1527
Nuno Lopesb62ff242008-06-04 19:15:45 +00001528 if (!LHS || !RHS) {
Chris Lattner307da022007-11-30 17:56:23 +00001529 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1530 return 0;
1531 }
1532
Chris Lattner9fba49a2007-08-24 05:35:26 +00001533 // Create a PHI node for the real part.
1534 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1535 PN->reserveOperandSpace(2);
1536 PN->addIncoming(LHS, LHSBlock);
1537 PN->addIncoming(RHS, RHSBlock);
1538 return PN;
1539}
1540
1541Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmand540c112009-03-04 05:52:32 +00001542 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001543}
1544
Chris Lattner307da022007-11-30 17:56:23 +00001545Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman8f5e8782009-01-20 17:46:04 +00001546 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson285611e2008-11-04 05:30:00 +00001547 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1548
1549 // If EmitVAArg fails, we fall back to the LLVM instruction.
1550 if (!ArgPtr)
1551 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1552
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001553 // FIXME Volatility.
Anders Carlsson285611e2008-11-04 05:30:00 +00001554 return Builder.CreateLoad(ArgPtr);
Anders Carlsson36760332007-10-15 20:28:48 +00001555}
1556
Mike Stump4eb81dc2009-02-12 18:29:15 +00001557Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stump1fa52fe2009-03-07 02:35:30 +00001558 return CGF.BuildBlockLiteralTmp(BE);
Mike Stump4eb81dc2009-02-12 18:29:15 +00001559}
1560
Chris Lattner9fba49a2007-08-24 05:35:26 +00001561//===----------------------------------------------------------------------===//
1562// Entry Point into this File
1563//===----------------------------------------------------------------------===//
1564
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001565/// EmitScalarExpr - Emit the computation of the specified expression of
1566/// scalar type, ignoring the result.
1567Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner9fba49a2007-08-24 05:35:26 +00001568 assert(E && !hasAggregateLLVMType(E->getType()) &&
1569 "Invalid scalar expression to emit");
1570
Mike Stumpb8fc73e2009-05-29 15:46:01 +00001571 return ScalarExprEmitter(*this, IgnoreResultAssign)
1572 .Visit(const_cast<Expr*>(E));
Chris Lattner9fba49a2007-08-24 05:35:26 +00001573}
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001574
1575/// EmitScalarConversion - Emit a conversion from the specified type to the
1576/// specified destination type, both of which are LLVM scalar types.
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001577Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1578 QualType DstTy) {
Chris Lattner4e05d1e2007-08-26 06:48:56 +00001579 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1580 "Invalid scalar expression to emit");
1581 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1582}
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001583
1584/// EmitComplexToScalarConversion - Emit a conversion from the specified
1585/// complex type to the specified destination type, where the destination
1586/// type is an LLVM scalar type.
1587Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1588 QualType SrcTy,
1589 QualType DstTy) {
Chris Lattnerde0908b2008-04-04 16:54:41 +00001590 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattnerfb182ee2007-08-26 16:34:22 +00001591 "Invalid complex -> scalar conversion");
1592 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1593 DstTy);
1594}
Anders Carlssona9234fe2007-12-10 19:35:18 +00001595
1596Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1597 assert(V1->getType() == V2->getType() &&
1598 "Vector operands must be of the same type");
Anders Carlssona9234fe2007-12-10 19:35:18 +00001599 unsigned NumElements =
1600 cast<llvm::VectorType>(V1->getType())->getNumElements();
1601
1602 va_list va;
1603 va_start(va, V2);
1604
1605 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssona9234fe2007-12-10 19:35:18 +00001606 for (unsigned i = 0; i < NumElements; i++) {
1607 int n = va_arg(va, int);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001608 assert(n >= 0 && n < (int)NumElements * 2 &&
1609 "Vector shuffle index out of bounds!");
Owen Andersonb17ec712009-07-24 23:12:58 +00001610 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
Anders Carlssona9234fe2007-12-10 19:35:18 +00001611 }
1612
1613 const char *Name = va_arg(va, const char *);
1614 va_end(va);
1615
Owen Anderson17971fa2009-07-28 21:22:35 +00001616 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Anders Carlssona9234fe2007-12-10 19:35:18 +00001617
1618 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1619}
1620
Anders Carlsson68b8be92007-12-15 21:23:30 +00001621llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001622 unsigned NumVals, bool isSplat) {
Anders Carlsson68b8be92007-12-15 21:23:30 +00001623 llvm::Value *Vec
Owen Anderson73e7f802009-07-14 23:10:40 +00001624 = VMContext.getUndef(VMContext.getVectorType(Vals[0]->getType(), NumVals));
Anders Carlsson68b8be92007-12-15 21:23:30 +00001625
Chris Lattnera23eb7b2008-07-26 20:15:14 +00001626 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begemanec2d1062007-12-30 02:59:45 +00001627 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Owen Andersonb17ec712009-07-24 23:12:58 +00001628 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begemanec2d1062007-12-30 02:59:45 +00001629 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlsson68b8be92007-12-15 21:23:30 +00001630 }
1631
1632 return Vec;
1633}