blob: c0f6335d8813e3b43308899a82571b37a2f6e4c5 [file] [log] [blame]
Chris Lattner2da04b32007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattner2da04b32007-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 Dunbarad319a72008-08-11 05:00:27 +000016#include "clang/AST/ASTContext.h"
Daniel Dunbar6630e102008-08-12 05:08:18 +000017#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000018#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000019#include "clang/AST/StmtVisitor.h"
Chris Lattnerff2367c2008-04-20 00:50:39 +000020#include "clang/Basic/TargetInfo.h"
Chris Lattner2da04b32007-08-24 05:35:26 +000021#include "llvm/Constants.h"
22#include "llvm/Function.h"
Anders Carlssond8499822007-10-29 05:01:08 +000023#include "llvm/GlobalVariable.h"
Anders Carlsson7e13ab82007-10-15 20:28:48 +000024#include "llvm/Intrinsics.h"
Mike Stump0c61b732009-04-01 20:28:16 +000025#include "llvm/Module.h"
Chris Lattner2da04b32007-08-24 05:35:26 +000026#include "llvm/Support/Compiler.h"
Chris Lattner35710d182008-11-12 08:38:24 +000027#include "llvm/Support/CFG.h"
Mike Stumpcb2fbcb2009-02-21 20:00:35 +000028#include "llvm/Target/TargetData.h"
Chris Lattner1800c182008-01-03 07:05:49 +000029#include <cstdarg>
Ted Kremenekf182e812007-12-10 23:44:32 +000030
Chris Lattner2da04b32007-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 Lattner3d966d62007-08-24 21:00:35 +000042 QualType Ty; // Computation Type.
Chris Lattner2da04b32007-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 Dunbarcb463852008-11-01 01:53:16 +000050 CGBuilderTy &Builder;
Mike Stumpdf0fe272009-05-29 15:46:01 +000051 bool IgnoreResultAssign;
Owen Anderson170229f2009-07-14 23:10:40 +000052 llvm::LLVMContext &VMContext;
Chris Lattner2da04b32007-08-24 05:35:26 +000053public:
54
Mike Stumpdf0fe272009-05-29 15:46:01 +000055 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Owen Anderson170229f2009-07-14 23:10:40 +000056 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
57 VMContext(cgf.getLLVMContext()) {
Chris Lattner2da04b32007-08-24 05:35:26 +000058 }
Chris Lattner2da04b32007-08-24 05:35:26 +000059
60 //===--------------------------------------------------------------------===//
61 // Utilities
62 //===--------------------------------------------------------------------===//
63
Mike Stumpdf0fe272009-05-29 15:46:01 +000064 bool TestAndClearIgnoreResultAssign() {
Chris Lattner2a7deb62009-07-08 01:08:03 +000065 bool I = IgnoreResultAssign;
66 IgnoreResultAssign = false;
67 return I;
68 }
Mike Stumpdf0fe272009-05-29 15:46:01 +000069
Chris Lattner2da04b32007-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 Lattner4647a212007-08-31 22:49:20 +000074 return CGF.EmitLoadOfLValue(LV, T).getScalarVal();
Chris Lattner2da04b32007-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 Lattner2da04b32007-08-24 05:35:26 +000081 return EmitLoadOfLValue(EmitLValue(E), E->getType());
82 }
83
Chris Lattnere0044382007-08-26 16:42:57 +000084 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +000085 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +000086 Value *EmitConversionToBool(Value *Src, QualType DstTy);
87
Chris Lattner3474c202007-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 Lattner42e6b812007-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 Stumpab3afd82009-02-12 18:29:15 +000097
Chris Lattner2da04b32007-08-24 05:35:26 +000098 //===--------------------------------------------------------------------===//
99 // Visitor Methods
100 //===--------------------------------------------------------------------===//
101
102 Value *VisitStmt(Stmt *S) {
Ted Kremenekd4e5fba2007-12-11 21:27:55 +0000103 S->dump(CGF.getContext().getSourceManager());
Chris Lattner2da04b32007-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 Andersonb7a2fe62009-07-24 23:12:58 +0000112 return llvm::ConstantInt::get(VMContext, E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000113 }
114 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersone05f2ed2009-07-27 21:00:51 +0000115 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000116 }
117 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000118 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000119 }
Nate Begeman4c18c232007-11-15 05:40:03 +0000120 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000121 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begeman4c18c232007-11-15 05:40:03 +0000122 }
Argyrios Kyrtzidisce4528f2008-08-23 19:35:47 +0000123 Value *VisitCXXZeroInitValueExpr(const CXXZeroInitValueExpr *E) {
Owen Anderson0b75f232009-07-31 20:28:54 +0000124 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Argyrios Kyrtzidisce4528f2008-08-23 19:35:47 +0000125 }
Anders Carlsson39def3a2008-12-21 22:39:40 +0000126 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Owen Anderson0b75f232009-07-31 20:28:54 +0000127 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Anders Carlsson39def3a2008-12-21 22:39:40 +0000128 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000129 Value *VisitTypesCompatibleExpr(const TypesCompatibleExpr *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000130 return llvm::ConstantInt::get(ConvertType(E->getType()),
Steve Naroff32e44c02007-10-15 20:41:53 +0000131 CGF.getContext().typesAreCompatible(
132 E->getArgType1(), E->getArgType2()));
Chris Lattner2da04b32007-08-24 05:35:26 +0000133 }
Sebastian Redl6f282892008-11-11 17:56:53 +0000134 Value *VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E);
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000135 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Daniel Dunbar8bc821a2008-08-16 01:41:47 +0000136 llvm::Value *V =
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000137 llvm::ConstantInt::get(llvm::Type::Int32Ty,
Daniel Dunbar8bc821a2008-08-16 01:41:47 +0000138 CGF.GetIDForAddrOfLabel(E->getLabel()));
139
140 return Builder.CreateIntToPtr(V, ConvertType(E->getType()));
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000141 }
Chris Lattner2da04b32007-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 Andersonb7a2fe62009-07-24 23:12:58 +0000146 return llvm::ConstantInt::get(VMContext, EC->getInitVal());
Chris Lattner2da04b32007-08-24 05:35:26 +0000147 return EmitLoadOfLValue(E);
148 }
Daniel Dunbar55310df2008-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 Dunbarc8317a42008-08-23 10:51:21 +0000158 Value *VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +0000159 return EmitLoadOfLValue(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000160 }
Fariborz Jahanian9ac53512008-11-22 22:30:21 +0000161 Value *VisitObjCKVCRefExpr(ObjCKVCRefExpr *E) {
162 return EmitLoadOfLValue(E);
163 }
Daniel Dunbar55310df2008-08-27 06:57:25 +0000164 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
165 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000166 }
167
Chris Lattner2da04b32007-08-24 05:35:26 +0000168 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000169 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000170 Value *VisitMemberExpr(Expr *E) { return EmitLoadOfLValue(E); }
Nate Begemance4d7fc2008-04-18 23:10:10 +0000171 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattner084bc322008-10-26 23:53:12 +0000172 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
173 return EmitLoadOfLValue(E);
174 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000175 Value *VisitStringLiteral(Expr *E) { return EmitLValue(E).getAddress(); }
Chris Lattnerd7e7b8e2009-02-24 22:18:39 +0000176 Value *VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
177 return EmitLValue(E).getAddress();
178 }
179
Chris Lattner6307f192008-08-10 01:53:14 +0000180 Value *VisitPredefinedExpr(Expr *E) { return EmitLValue(E).getAddress(); }
Devang Patel43fc86d2007-10-24 17:18:43 +0000181
182 Value *VisitInitListExpr(InitListExpr *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000183 bool Ignore = TestAndClearIgnoreResultAssign();
184 (void)Ignore;
185 assert (Ignore == false && "init list ignored");
Anders Carlssona297e7a2007-12-05 07:36:10 +0000186 unsigned NumInitElements = E->getNumInits();
187
Douglas Gregorbf7207a2009-01-29 19:42:23 +0000188 if (E->hadArrayRangeDesignator()) {
189 CGF.ErrorUnsupported(E, "GNU array range designator extension");
190 }
191
Anders Carlssona297e7a2007-12-05 07:36:10 +0000192 const llvm::VectorType *VType =
Anders Carlsson6f2a10e2008-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 Carlssona297e7a2007-12-05 07:36:10 +0000198
Anders Carlssona297e7a2007-12-05 07:36:10 +0000199 unsigned NumVectorElements = VType->getNumElements();
200 const llvm::Type *ElementType = VType->getElementType();
Anders Carlssona297e7a2007-12-05 07:36:10 +0000201
202 // Emit individual vector element stores.
Owen Anderson7ec07a52009-07-30 23:11:26 +0000203 llvm::Value *V = llvm::UndefValue::get(VType);
Anders Carlssona297e7a2007-12-05 07:36:10 +0000204
Anders Carlssonaa5c9192007-12-18 02:45:33 +0000205 // Emit initializers
206 unsigned i;
207 for (i = 0; i < NumInitElements; ++i) {
Devang Patelb67e5962007-10-24 18:05:48 +0000208 Value *NewV = Visit(E->getInit(i));
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000209 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Devang Patelb67e5962007-10-24 18:05:48 +0000210 V = Builder.CreateInsertElement(V, NewV, Idx);
Devang Patel43fc86d2007-10-24 17:18:43 +0000211 }
Anders Carlssona297e7a2007-12-05 07:36:10 +0000212
213 // Emit remaining default initializers
214 for (/* Do not initialize i*/; i < NumVectorElements; ++i) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000215 Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Owen Anderson0b75f232009-07-31 20:28:54 +0000216 llvm::Value *NewV = llvm::Constant::getNullValue(ElementType);
Anders Carlssona297e7a2007-12-05 07:36:10 +0000217 V = Builder.CreateInsertElement(V, NewV, Idx);
218 }
219
Devang Patelb67e5962007-10-24 18:05:48 +0000220 return V;
Devang Patel43fc86d2007-10-24 17:18:43 +0000221 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000222
Douglas Gregor0202cb42009-01-29 17:44:32 +0000223 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Owen Anderson0b75f232009-07-31 20:28:54 +0000224 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Douglas Gregor0202cb42009-01-29 17:44:32 +0000225 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000226 Value *VisitImplicitCastExpr(const ImplicitCastExpr *E);
Eli Friedmanbc633be2009-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 Lattner2da04b32007-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 Carlssond8b7ae22009-05-27 03:37:57 +0000237 if (E->getCallReturnType()->isReferenceType())
238 return EmitLoadOfLValue(E);
239
Chris Lattner4647a212007-08-31 22:49:20 +0000240 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner2da04b32007-08-24 05:35:26 +0000241 }
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000242
Chris Lattner04a913b2007-08-31 22:09:40 +0000243 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000244
Mike Stump1db7d042009-02-28 09:07:16 +0000245 Value *VisitBlockDeclRefExpr(const BlockDeclRefExpr *E);
Chris Lattner04a913b2007-08-31 22:09:40 +0000246
Chris Lattner2da04b32007-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 Stumpdf0fe272009-05-29 15:46:01 +0000266 // This differs from gcc, though, most likely due to a bug in gcc.
267 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-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 Lattner9f0ad962007-08-24 21:20:17 +0000273 Value *VisitUnaryReal (const UnaryOperator *E);
274 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000275 Value *VisitUnaryExtension(const UnaryOperator *E) {
276 return Visit(E->getSubExpr());
277 }
Anders Carlssona8dc3e62008-01-29 15:56:48 +0000278 Value *VisitUnaryOffsetOf(const UnaryOperator *E);
Anders Carlssona5d077d2009-04-14 16:58:56 +0000279
280 // C++
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000281 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
282 return Visit(DAE->getExpr());
283 }
Anders Carlssona5d077d2009-04-14 16:58:56 +0000284 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
285 return CGF.LoadCXXThis();
286 }
Anders Carlssona8dc3e62008-01-29 15:56:48 +0000287
Anders Carlssonc82b86d2009-05-19 04:48:36 +0000288 Value *VisitCXXExprWithTemporaries(CXXExprWithTemporaries *E) {
Anders Carlsson2262b302009-05-31 00:09:15 +0000289 return CGF.EmitCXXExprWithTemporaries(E).getScalarVal();
Anders Carlssonc82b86d2009-05-19 04:48:36 +0000290 }
Anders Carlsson4a7b49b2009-05-31 01:40:14 +0000291 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
292 return CGF.EmitCXXNewExpr(E);
293 }
Anders Carlssonc82b86d2009-05-19 04:48:36 +0000294
Chris Lattner2da04b32007-08-24 05:35:26 +0000295 // Binary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000296 Value *EmitMul(const BinOpInfo &Ops) {
Mike Stumpd3e38852009-04-02 18:15:54 +0000297 if (CGF.getContext().getLangOptions().OverflowChecking
298 && Ops.Ty->isSignedIntegerType())
Mike Stump0c61b732009-04-01 20:28:16 +0000299 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner94dfae22009-06-17 06:36:24 +0000300 if (Ops.LHS->getType()->isFPOrFPVector())
301 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner2da04b32007-08-24 05:35:26 +0000302 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
303 }
Mike Stump0c61b732009-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 Lattner2da04b32007-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 Lattner3d966d62007-08-24 21:00:35 +0000323 BinOpInfo EmitBinOps(const BinaryOperator *E);
Chris Lattnerb6334692007-08-26 21:41:21 +0000324 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner3d966d62007-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 Lattnerb6334692007-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 Lattner3d966d62007-08-24 21:00:35 +0000334 }
335 HANDLEBINOP(Mul);
336 HANDLEBINOP(Div);
337 HANDLEBINOP(Rem);
338 HANDLEBINOP(Add);
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +0000339 HANDLEBINOP(Sub);
Chris Lattner3d966d62007-08-24 21:00:35 +0000340 HANDLEBINOP(Shl);
341 HANDLEBINOP(Shr);
342 HANDLEBINOP(And);
343 HANDLEBINOP(Xor);
344 HANDLEBINOP(Or);
345#undef HANDLEBINOP
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +0000346
Chris Lattner2da04b32007-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 Lattner2da04b32007-08-24 05:35:26 +0000366 Value *VisitBinComma (const BinaryOperator *E);
367
368 // Other Operators.
Mike Stumpab3afd82009-02-12 18:29:15 +0000369 Value *VisitBlockExpr(const BlockExpr *BE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000370 Value *VisitConditionalOperator(const ConditionalOperator *CO);
371 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000372 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner2da04b32007-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 Lattnere0044382007-08-26 16:42:57 +0000383/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000384/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-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 Anderson0b75f232009-07-31 20:28:54 +0000390 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnere0044382007-08-26 16:42:57 +0000391 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
392 }
393
Anders Carlssonf48123b2009-08-09 18:26:27 +0000394 if (SrcType->isMemberPointerType()) {
395 // FIXME: This is ABI specific.
396
397 // Compare against -1.
398 llvm::Value *NegativeOne = llvm::Constant::getAllOnesValue(Src->getType());
399 return Builder.CreateICmpNE(Src, NegativeOne, "tobool");
400 }
401
Daniel Dunbaref957f32008-08-25 10:38:11 +0000402 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnere0044382007-08-26 16:42:57 +0000403 "Unknown scalar type to convert");
404
405 // Because of the type rules of C, we often end up computing a logical value,
406 // then zero extending it to int, then wanting it as a logical value again.
407 // Optimize this common case.
408 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Src)) {
409 if (ZI->getOperand(0)->getType() == llvm::Type::Int1Ty) {
410 Value *Result = ZI->getOperand(0);
Eli Friedman7031d732008-01-29 18:13:51 +0000411 // If there aren't any more uses, zap the instruction to save space.
412 // Note that there can be more uses, for example if this
413 // is the result of an assignment.
414 if (ZI->use_empty())
415 ZI->eraseFromParent();
Chris Lattnere0044382007-08-26 16:42:57 +0000416 return Result;
417 }
418 }
419
420 // Compare against an integer or pointer null.
Owen Anderson0b75f232009-07-31 20:28:54 +0000421 llvm::Value *Zero = llvm::Constant::getNullValue(Src->getType());
Chris Lattnere0044382007-08-26 16:42:57 +0000422 return Builder.CreateICmpNE(Src, Zero, "tobool");
423}
424
Chris Lattner3474c202007-08-26 06:48:56 +0000425/// EmitScalarConversion - Emit a conversion from the specified type to the
426/// specified destination type, both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +0000427Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
428 QualType DstType) {
Chris Lattner0f398c42008-07-26 22:37:01 +0000429 SrcType = CGF.getContext().getCanonicalType(SrcType);
430 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3474c202007-08-26 06:48:56 +0000431 if (SrcType == DstType) return Src;
Chris Lattner08c611e2007-08-26 07:21:11 +0000432
433 if (DstType->isVoidType()) return 0;
Chris Lattner3474c202007-08-26 06:48:56 +0000434
435 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000436 if (DstType->isBooleanType())
437 return EmitConversionToBool(Src, SrcType);
Chris Lattner3474c202007-08-26 06:48:56 +0000438
439 const llvm::Type *DstTy = ConvertType(DstType);
440
441 // Ignore conversions like int -> uint.
442 if (Src->getType() == DstTy)
443 return Src;
444
Daniel Dunbar427f8732008-08-25 09:51:32 +0000445 // Handle pointer conversions next: pointers can only be converted
446 // to/from other pointers and integers. Check for pointer types in
447 // terms of LLVM, as some native types (like Obj-C id) may map to a
448 // pointer type.
449 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +0000450 // The source value may be an integer, or a pointer.
Fariborz Jahanianf1707152009-07-28 22:00:58 +0000451 if (isa<llvm::PointerType>(Src->getType())) {
452 // Some heavy lifting for derived to base conversion.
Fariborz Jahanian82e28742009-07-29 00:44:13 +0000453 if (const CXXRecordDecl *ClassDecl =
454 SrcType->getCXXRecordDeclForPointerType())
455 if (const CXXRecordDecl *BaseClassDecl =
456 DstType->getCXXRecordDeclForPointerType())
457 Src = CGF.AddressCXXOfBaseClass(Src, ClassDecl, BaseClassDecl);
Chris Lattner3474c202007-08-26 06:48:56 +0000458 return Builder.CreateBitCast(Src, DstTy, "conv");
Fariborz Jahanianf1707152009-07-28 22:00:58 +0000459 }
Chris Lattner3474c202007-08-26 06:48:56 +0000460 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman42d2a3a2009-03-04 04:02:35 +0000461 // First, convert to the correct width so that we control the kind of
462 // extension.
Owen Anderson9793f0e2009-07-29 22:16:19 +0000463 const llvm::Type *MiddleTy = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Eli Friedman42d2a3a2009-03-04 04:02:35 +0000464 bool InputSigned = SrcType->isSignedIntegerType();
465 llvm::Value* IntResult =
466 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
467 // Then, cast to pointer.
468 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000469 }
470
Daniel Dunbar427f8732008-08-25 09:51:32 +0000471 if (isa<llvm::PointerType>(Src->getType())) {
Chris Lattner3474c202007-08-26 06:48:56 +0000472 // Must be an ptr to int cast.
473 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlssone89b84a2007-10-31 23:18:02 +0000474 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000475 }
476
Nate Begemance4d7fc2008-04-18 23:10:10 +0000477 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman5ec4b312009-08-10 23:49:36 +0000478 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begemanb699c9b2009-01-18 06:42:49 +0000479 // Cast the scalar to element type
480 QualType EltTy = DstType->getAsExtVectorType()->getElementType();
481 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
482
483 // Insert the element in element zero of an undef vector
Owen Anderson7ec07a52009-07-30 23:11:26 +0000484 llvm::Value *UnV = llvm::UndefValue::get(DstTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000485 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, 0);
Nate Begemanb699c9b2009-01-18 06:42:49 +0000486 UnV = Builder.CreateInsertElement(UnV, Elt, Idx, "tmp");
487
488 // Splat the element across to all elements
489 llvm::SmallVector<llvm::Constant*, 16> Args;
490 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
491 for (unsigned i = 0; i < NumElements; i++)
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000492 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, 0));
Nate Begemanb699c9b2009-01-18 06:42:49 +0000493
Owen Anderson3cc120a2009-07-28 21:22:35 +0000494 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Nate Begemanb699c9b2009-01-18 06:42:49 +0000495 llvm::Value *Yay = Builder.CreateShuffleVector(UnV, UnV, Mask, "splat");
496 return Yay;
497 }
Nate Begeman330aaa72007-12-30 02:59:45 +0000498
Chris Lattner6cba8e92008-02-02 04:51:41 +0000499 // Allow bitcast from vector to integer/fp of the same size.
Anders Carlssona297e7a2007-12-05 07:36:10 +0000500 if (isa<llvm::VectorType>(Src->getType()) ||
Chris Lattner6cba8e92008-02-02 04:51:41 +0000501 isa<llvm::VectorType>(DstTy))
Anders Carlssona297e7a2007-12-05 07:36:10 +0000502 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlssona297e7a2007-12-05 07:36:10 +0000503
Chris Lattner3474c202007-08-26 06:48:56 +0000504 // Finally, we have the arithmetic types: real int/float.
505 if (isa<llvm::IntegerType>(Src->getType())) {
506 bool InputSigned = SrcType->isSignedIntegerType();
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000507 if (isa<llvm::IntegerType>(DstTy))
508 return Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
509 else if (InputSigned)
510 return Builder.CreateSIToFP(Src, DstTy, "conv");
511 else
512 return Builder.CreateUIToFP(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000513 }
514
515 assert(Src->getType()->isFloatingPoint() && "Unknown real conversion");
516 if (isa<llvm::IntegerType>(DstTy)) {
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000517 if (DstType->isSignedIntegerType())
518 return Builder.CreateFPToSI(Src, DstTy, "conv");
519 else
520 return Builder.CreateFPToUI(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000521 }
522
523 assert(DstTy->isFloatingPoint() && "Unknown real conversion");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000524 if (DstTy->getTypeID() < Src->getType()->getTypeID())
525 return Builder.CreateFPTrunc(Src, DstTy, "conv");
526 else
527 return Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000528}
529
Chris Lattner42e6b812007-08-26 16:34:22 +0000530/// EmitComplexToScalarConversion - Emit a conversion from the specified
531/// complex type to the specified destination type, where the destination
532/// type is an LLVM scalar type.
533Value *ScalarExprEmitter::
534EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
535 QualType SrcTy, QualType DstTy) {
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000536 // Get the source element type.
Chris Lattner0f398c42008-07-26 22:37:01 +0000537 SrcTy = SrcTy->getAsComplexType()->getElementType();
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000538
539 // Handle conversions to bool first, they are special: comparisons against 0.
540 if (DstTy->isBooleanType()) {
541 // Complex != 0 -> (Real != 0) | (Imag != 0)
542 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
543 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
544 return Builder.CreateOr(Src.first, Src.second, "tobool");
545 }
546
Chris Lattner42e6b812007-08-26 16:34:22 +0000547 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
548 // the imaginary part of the complex value is discarded and the value of the
549 // real part is converted according to the conversion rules for the
550 // corresponding real type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000551 return EmitScalarConversion(Src.first, SrcTy, DstTy);
552}
553
554
Chris Lattner2da04b32007-08-24 05:35:26 +0000555//===----------------------------------------------------------------------===//
556// Visitor Methods
557//===----------------------------------------------------------------------===//
558
559Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000560 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner2da04b32007-08-24 05:35:26 +0000561 if (E->getType()->isVoidType())
562 return 0;
Owen Anderson7ec07a52009-07-30 23:11:26 +0000563 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner2da04b32007-08-24 05:35:26 +0000564}
565
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000566Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
567 llvm::SmallVector<llvm::Constant*, 32> indices;
568 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
569 indices.push_back(cast<llvm::Constant>(CGF.EmitScalarExpr(E->getExpr(i))));
570 }
571 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
572 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Owen Anderson3cc120a2009-07-28 21:22:35 +0000573 Value* SV = llvm::ConstantVector::get(indices.begin(), indices.size());
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000574 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
575}
576
Chris Lattner2da04b32007-08-24 05:35:26 +0000577Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000578 TestAndClearIgnoreResultAssign();
579
Chris Lattner2da04b32007-08-24 05:35:26 +0000580 // Emit subscript expressions in rvalue context's. For most cases, this just
581 // loads the lvalue formed by the subscript expr. However, we have to be
582 // careful, because the base of a vector subscript is occasionally an rvalue,
583 // so we can't get it as an lvalue.
584 if (!E->getBase()->getType()->isVectorType())
585 return EmitLoadOfLValue(E);
586
587 // Handle the vector case. The base must be a vector, the index must be an
588 // integer value.
589 Value *Base = Visit(E->getBase());
590 Value *Idx = Visit(E->getIdx());
Eli Friedmane381f7e2009-03-28 02:45:41 +0000591 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerType();
Eli Friedman754d5ac2009-03-28 03:27:06 +0000592 Idx = Builder.CreateIntCast(Idx, llvm::Type::Int32Ty, IdxSigned,
593 "vecidxcast");
Chris Lattner2da04b32007-08-24 05:35:26 +0000594 return Builder.CreateExtractElement(Base, Idx, "vecext");
595}
596
597/// VisitImplicitCastExpr - Implicit casts are the same as normal casts, but
598/// also handle things like function to pointer-to-function decay, and array to
599/// pointer decay.
600Value *ScalarExprEmitter::VisitImplicitCastExpr(const ImplicitCastExpr *E) {
601 const Expr *Op = E->getSubExpr();
602
603 // If this is due to array->pointer conversion, emit the array expression as
604 // an l-value.
605 if (Op->getType()->isArrayType()) {
Anders Carlsson8fc489d2009-08-07 23:48:20 +0000606 assert(E->getCastKind() == CastExpr::CK_ArrayToPointerDecay);
Chris Lattner42e6b812007-08-26 16:34:22 +0000607 Value *V = EmitLValue(Op).getAddress(); // Bitfields can't be arrays.
Eli Friedmanf4084702008-12-20 23:11:59 +0000608
Eli Friedmane381f7e2009-03-28 02:45:41 +0000609 // Note that VLA pointers are always decayed, so we don't need to do
610 // anything here.
Eli Friedmanf4084702008-12-20 23:11:59 +0000611 if (!Op->getType()->isVariableArrayType()) {
612 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
613 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
614 ->getElementType()) &&
615 "Expected pointer to array");
616 V = Builder.CreateStructGEP(V, 0, "arraydecay");
Daniel Dunbara7998072008-08-29 17:28:43 +0000617 }
Chris Lattnerc6208a72007-12-12 04:13:20 +0000618
619 // The resultant pointer type can be implicitly casted to other pointer
Chris Lattnerd2583252008-07-23 06:31:27 +0000620 // types as well (e.g. void*) and can be implicitly converted to integer.
621 const llvm::Type *DestTy = ConvertType(E->getType());
622 if (V->getType() != DestTy) {
623 if (isa<llvm::PointerType>(DestTy))
624 V = Builder.CreateBitCast(V, DestTy, "ptrconv");
625 else {
626 assert(isa<llvm::IntegerType>(DestTy) && "Unknown array decay");
627 V = Builder.CreatePtrToInt(V, DestTy, "ptrconv");
628 }
629 }
Chris Lattnerc6208a72007-12-12 04:13:20 +0000630 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000631 }
Eli Friedmane381f7e2009-03-28 02:45:41 +0000632
Chris Lattner2da04b32007-08-24 05:35:26 +0000633 return EmitCastExpr(Op, E->getType());
634}
635
636
637// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
638// have to handle a more broad range of conversions than explicit casts, as they
639// handle things like function to ptr-to-function decay etc.
640Value *ScalarExprEmitter::EmitCastExpr(const Expr *E, QualType DestTy) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000641 if (!DestTy->isVoidType())
642 TestAndClearIgnoreResultAssign();
643
Chris Lattner5de3b172007-08-26 07:26:12 +0000644 // Handle cases where the source is an non-complex type.
Chris Lattnerdf53e202008-02-16 23:55:16 +0000645
646 if (!CGF.hasAggregateLLVMType(E->getType())) {
Chris Lattner3474c202007-08-26 06:48:56 +0000647 Value *Src = Visit(const_cast<Expr*>(E));
648
Chris Lattner3474c202007-08-26 06:48:56 +0000649 // Use EmitScalarConversion to perform the conversion.
650 return EmitScalarConversion(Src, E->getType(), DestTy);
651 }
Chris Lattnerdf53e202008-02-16 23:55:16 +0000652
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000653 if (E->getType()->isAnyComplexType()) {
Chris Lattnerdf53e202008-02-16 23:55:16 +0000654 // Handle cases where the source is a complex type.
Mike Stumpdf0fe272009-05-29 15:46:01 +0000655 bool IgnoreImag = true;
656 bool IgnoreImagAssign = true;
657 bool IgnoreReal = IgnoreResultAssign;
658 bool IgnoreRealAssign = IgnoreResultAssign;
659 if (DestTy->isBooleanType())
660 IgnoreImagAssign = IgnoreImag = false;
661 else if (DestTy->isVoidType()) {
662 IgnoreReal = IgnoreImag = false;
663 IgnoreRealAssign = IgnoreImagAssign = true;
664 }
665 CodeGenFunction::ComplexPairTy V
666 = CGF.EmitComplexExpr(E, IgnoreReal, IgnoreImag, IgnoreRealAssign,
667 IgnoreImagAssign);
668 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
Chris Lattnerdf53e202008-02-16 23:55:16 +0000669 }
Chris Lattner46c71612007-08-26 07:16:41 +0000670
Chris Lattnerdf53e202008-02-16 23:55:16 +0000671 // Okay, this is a cast from an aggregate. It must be a cast to void. Just
672 // evaluate the result and return.
Mike Stumpdf0fe272009-05-29 15:46:01 +0000673 CGF.EmitAggExpr(E, 0, false, true);
Chris Lattnerdf53e202008-02-16 23:55:16 +0000674 return 0;
Chris Lattner2da04b32007-08-24 05:35:26 +0000675}
676
Chris Lattner04a913b2007-08-31 22:09:40 +0000677Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
Chris Lattner7e800972008-07-26 20:23:23 +0000678 return CGF.EmitCompoundStmt(*E->getSubStmt(),
679 !E->getType()->isVoidType()).getScalarVal();
Chris Lattner04a913b2007-08-31 22:09:40 +0000680}
681
Mike Stump1db7d042009-02-28 09:07:16 +0000682Value *ScalarExprEmitter::VisitBlockDeclRefExpr(const BlockDeclRefExpr *E) {
683 return Builder.CreateLoad(CGF.GetAddrOfBlockDecl(E), false, "tmp");
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000684}
Chris Lattner04a913b2007-08-31 22:09:40 +0000685
Chris Lattner2da04b32007-08-24 05:35:26 +0000686//===----------------------------------------------------------------------===//
687// Unary Operators
688//===----------------------------------------------------------------------===//
689
690Value *ScalarExprEmitter::VisitPrePostIncDec(const UnaryOperator *E,
Chris Lattner100198f2007-08-24 16:24:49 +0000691 bool isInc, bool isPre) {
Chris Lattner2da04b32007-08-24 05:35:26 +0000692 LValue LV = EmitLValue(E->getSubExpr());
Eli Friedman7b471672009-03-23 03:00:06 +0000693 QualType ValTy = E->getSubExpr()->getType();
694 Value *InVal = CGF.EmitLoadOfLValue(LV, ValTy).getScalarVal();
Chris Lattner2da04b32007-08-24 05:35:26 +0000695
696 int AmountVal = isInc ? 1 : -1;
Eli Friedmane381f7e2009-03-28 02:45:41 +0000697
698 if (ValTy->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000699 ValTy->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmane381f7e2009-03-28 02:45:41 +0000700 // The amount of the addition/subtraction needs to account for the VLA size
701 CGF.ErrorUnsupported(E, "VLA pointer inc/dec");
702 }
703
Chris Lattner2da04b32007-08-24 05:35:26 +0000704 Value *NextVal;
Chris Lattnerc2a0b972009-03-18 04:25:13 +0000705 if (const llvm::PointerType *PT =
706 dyn_cast<llvm::PointerType>(InVal->getType())) {
Owen Anderson170229f2009-07-14 23:10:40 +0000707 llvm::Constant *Inc =
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000708 llvm::ConstantInt::get(llvm::Type::Int32Ty, AmountVal);
Chris Lattnerc2a0b972009-03-18 04:25:13 +0000709 if (!isa<llvm::FunctionType>(PT->getElementType())) {
Fariborz Jahanianc3443a32009-07-16 22:04:59 +0000710 QualType PTEE = ValTy->getPointeeType();
711 if (const ObjCInterfaceType *OIT =
712 dyn_cast<ObjCInterfaceType>(PTEE)) {
713 // Handle interface types, which are not represented with a concrete type.
714 int size = CGF.getContext().getTypeSize(OIT) / 8;
715 if (!isInc)
716 size = -size;
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000717 Inc = llvm::ConstantInt::get(Inc->getType(), size);
Fariborz Jahanianc3443a32009-07-16 22:04:59 +0000718 const llvm::Type *i8Ty =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000719 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Fariborz Jahanianc3443a32009-07-16 22:04:59 +0000720 InVal = Builder.CreateBitCast(InVal, i8Ty);
721 NextVal = Builder.CreateGEP(InVal, Inc, "add.ptr");
722 llvm::Value *lhs = LV.getAddress();
Owen Anderson9793f0e2009-07-29 22:16:19 +0000723 lhs = Builder.CreateBitCast(lhs, llvm::PointerType::getUnqual(i8Ty));
Fariborz Jahanianc3443a32009-07-16 22:04:59 +0000724 LV = LValue::MakeAddr(lhs, ValTy.getCVRQualifiers(),
725 CGF.getContext().getObjCGCAttrKind(ValTy));
Mike Stump658fe022009-07-30 22:28:39 +0000726 } else
Dan Gohman43b44842009-08-12 00:33:55 +0000727 NextVal = Builder.CreateInBoundsGEP(InVal, Inc, "ptrincdec");
Chris Lattnerc2a0b972009-03-18 04:25:13 +0000728 } else {
Owen Anderson170229f2009-07-14 23:10:40 +0000729 const llvm::Type *i8Ty =
Owen Anderson9793f0e2009-07-29 22:16:19 +0000730 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Chris Lattnerc2a0b972009-03-18 04:25:13 +0000731 NextVal = Builder.CreateBitCast(InVal, i8Ty, "tmp");
732 NextVal = Builder.CreateGEP(NextVal, Inc, "ptrincdec");
733 NextVal = Builder.CreateBitCast(NextVal, InVal->getType());
734 }
Chris Lattner746b2132009-02-11 07:40:06 +0000735 } else if (InVal->getType() == llvm::Type::Int1Ty && isInc) {
736 // Bool++ is an interesting case, due to promotion rules, we get:
737 // Bool++ -> Bool = Bool+1 -> Bool = (int)Bool+1 ->
738 // Bool = ((int)Bool+1) != 0
739 // An interesting aspect of this is that increment is always true.
740 // Decrement does not have this property.
Owen Andersonfe4e3472009-07-31 17:39:36 +0000741 NextVal = llvm::ConstantInt::getTrue(VMContext);
Chris Lattner94dfae22009-06-17 06:36:24 +0000742 } else if (isa<llvm::IntegerType>(InVal->getType())) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000743 NextVal = llvm::ConstantInt::get(InVal->getType(), AmountVal);
Chris Lattner94dfae22009-06-17 06:36:24 +0000744 NextVal = Builder.CreateAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnera01d8982007-08-26 05:10:16 +0000745 } else {
746 // Add the inc/dec to the real part.
Chris Lattner94dfae22009-06-17 06:36:24 +0000747 if (InVal->getType() == llvm::Type::FloatTy)
Devang Patelffe1e212007-10-30 20:59:40 +0000748 NextVal =
Owen Andersone05f2ed2009-07-27 21:00:51 +0000749 llvm::ConstantFP::get(VMContext,
750 llvm::APFloat(static_cast<float>(AmountVal)));
Chris Lattnerff2367c2008-04-20 00:50:39 +0000751 else if (InVal->getType() == llvm::Type::DoubleTy)
Devang Patelffe1e212007-10-30 20:59:40 +0000752 NextVal =
Owen Andersone05f2ed2009-07-27 21:00:51 +0000753 llvm::ConstantFP::get(VMContext,
754 llvm::APFloat(static_cast<double>(AmountVal)));
Chris Lattnerff2367c2008-04-20 00:50:39 +0000755 else {
756 llvm::APFloat F(static_cast<float>(AmountVal));
Dale Johannesenc48814b2008-10-09 23:02:32 +0000757 bool ignored;
758 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
759 &ignored);
Owen Andersone05f2ed2009-07-27 21:00:51 +0000760 NextVal = llvm::ConstantFP::get(VMContext, F);
Chris Lattnerd3d8aca2007-09-13 06:19:18 +0000761 }
Chris Lattner94dfae22009-06-17 06:36:24 +0000762 NextVal = Builder.CreateFAdd(InVal, NextVal, isInc ? "inc" : "dec");
Chris Lattnera01d8982007-08-26 05:10:16 +0000763 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000764
765 // Store the updated result through the lvalue.
Eli Friedman7b471672009-03-23 03:00:06 +0000766 if (LV.isBitfield())
767 CGF.EmitStoreThroughBitfieldLValue(RValue::get(NextVal), LV, ValTy,
768 &NextVal);
769 else
770 CGF.EmitStoreThroughLValue(RValue::get(NextVal), LV, ValTy);
Chris Lattner2da04b32007-08-24 05:35:26 +0000771
772 // If this is a postinc, return the value read from memory, otherwise use the
773 // updated value.
774 return isPre ? NextVal : InVal;
775}
776
777
778Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000779 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +0000780 Value *Op = Visit(E->getSubExpr());
Chris Lattner94dfae22009-06-17 06:36:24 +0000781 if (Op->getType()->isFPOrFPVector())
782 return Builder.CreateFNeg(Op, "neg");
Chris Lattner2da04b32007-08-24 05:35:26 +0000783 return Builder.CreateNeg(Op, "neg");
784}
785
786Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000787 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +0000788 Value *Op = Visit(E->getSubExpr());
789 return Builder.CreateNot(Op, "neg");
790}
791
792Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
793 // Compare operand to zero.
794 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
795
796 // Invert value.
797 // TODO: Could dynamically modify easy computations here. For example, if
798 // the operand is an icmp ne, turn into icmp eq.
799 BoolVal = Builder.CreateNot(BoolVal, "lnot");
800
Anders Carlsson775640d2009-05-19 18:44:53 +0000801 // ZExt result to the expr type.
802 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +0000803}
804
Sebastian Redl6f282892008-11-11 17:56:53 +0000805/// VisitSizeOfAlignOfExpr - Return the size or alignment of the type of
806/// argument of the sizeof expression as an integer.
807Value *
808ScalarExprEmitter::VisitSizeOfAlignOfExpr(const SizeOfAlignOfExpr *E) {
Sebastian Redl6f282892008-11-11 17:56:53 +0000809 QualType TypeToSize = E->getTypeOfArgument();
Eli Friedman2aa38fe2009-01-24 22:19:05 +0000810 if (E->isSizeOf()) {
811 if (const VariableArrayType *VAT =
812 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
813 if (E->isArgumentType()) {
814 // sizeof(type) - make sure to emit the VLA size.
815 CGF.EmitVLASize(TypeToSize);
Eli Friedman3253e182009-04-20 03:21:44 +0000816 } else {
817 // C99 6.5.3.4p2: If the argument is an expression of type
818 // VLA, it is evaluated.
819 CGF.EmitAnyExpr(E->getArgumentExpr());
Eli Friedman2aa38fe2009-01-24 22:19:05 +0000820 }
Anders Carlsson221483d2009-01-30 16:41:04 +0000821
Anders Carlsson31f86492009-02-05 19:43:10 +0000822 return CGF.GetVLASize(VAT);
Anders Carlsson76dbc042008-12-21 03:33:21 +0000823 }
Anders Carlsson30032882008-12-12 07:38:43 +0000824 }
Eli Friedman2aa38fe2009-01-24 22:19:05 +0000825
826 // If this isn't sizeof(vla), the result must be constant; use the
827 // constant folding logic so we don't have to duplicate it here.
828 Expr::EvalResult Result;
829 E->Evaluate(Result, CGF.getContext());
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000830 return llvm::ConstantInt::get(VMContext, Result.Val.getInt());
Chris Lattner2da04b32007-08-24 05:35:26 +0000831}
832
Chris Lattner9f0ad962007-08-24 21:20:17 +0000833Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
834 Expr *Op = E->getSubExpr();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000835 if (Op->getType()->isAnyComplexType())
Mike Stumpdf0fe272009-05-29 15:46:01 +0000836 return CGF.EmitComplexExpr(Op, false, true, false, true).first;
Chris Lattner9f0ad962007-08-24 21:20:17 +0000837 return Visit(Op);
838}
839Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
840 Expr *Op = E->getSubExpr();
Chris Lattnerf3bc75a2008-04-04 16:54:41 +0000841 if (Op->getType()->isAnyComplexType())
Mike Stumpdf0fe272009-05-29 15:46:01 +0000842 return CGF.EmitComplexExpr(Op, true, false, true, false).second;
Chris Lattnerb5e12622007-08-26 05:29:21 +0000843
Mike Stumpdf0fe272009-05-29 15:46:01 +0000844 // __imag on a scalar returns zero. Emit the subexpr to ensure side
845 // effects are evaluated, but not the actual value.
846 if (E->isLvalue(CGF.getContext()) == Expr::LV_Valid)
847 CGF.EmitLValue(Op);
848 else
849 CGF.EmitScalarExpr(Op, true);
Owen Anderson0b75f232009-07-31 20:28:54 +0000850 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner9f0ad962007-08-24 21:20:17 +0000851}
852
Anders Carlssona8dc3e62008-01-29 15:56:48 +0000853Value *ScalarExprEmitter::VisitUnaryOffsetOf(const UnaryOperator *E)
854{
Eli Friedman988a16b2009-02-27 06:44:11 +0000855 Value* ResultAsPtr = EmitLValue(E->getSubExpr()).getAddress();
Eli Friedman8549e5d2009-01-24 22:38:55 +0000856 const llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman988a16b2009-02-27 06:44:11 +0000857 return Builder.CreatePtrToInt(ResultAsPtr, ResultType, "offsetof");
Anders Carlssona8dc3e62008-01-29 15:56:48 +0000858}
Chris Lattner9f0ad962007-08-24 21:20:17 +0000859
Chris Lattner2da04b32007-08-24 05:35:26 +0000860//===----------------------------------------------------------------------===//
861// Binary Operators
862//===----------------------------------------------------------------------===//
863
864BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000865 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +0000866 BinOpInfo Result;
867 Result.LHS = Visit(E->getLHS());
868 Result.RHS = Visit(E->getRHS());
Chris Lattner3d966d62007-08-24 21:00:35 +0000869 Result.Ty = E->getType();
Chris Lattner2da04b32007-08-24 05:35:26 +0000870 Result.E = E;
871 return Result;
872}
873
Chris Lattnerb6334692007-08-26 21:41:21 +0000874Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner3d966d62007-08-24 21:00:35 +0000875 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000876 bool Ignore = TestAndClearIgnoreResultAssign();
Chris Lattner3d966d62007-08-24 21:00:35 +0000877 QualType LHSTy = E->getLHS()->getType(), RHSTy = E->getRHS()->getType();
878
879 BinOpInfo OpInfo;
880
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000881 if (E->getComputationResultType()->isAnyComplexType()) {
Eli Friedmane381f7e2009-03-28 02:45:41 +0000882 // This needs to go through the complex expression emitter, but
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000883 // it's a tad complicated to do that... I'm leaving it out for now.
884 // (Note that we do actually need the imaginary part of the RHS for
885 // multiplication and division.)
886 CGF.ErrorUnsupported(E, "complex compound assignment");
Owen Anderson7ec07a52009-07-30 23:11:26 +0000887 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000888 }
889
Mike Stumpc63428b2009-05-22 19:07:20 +0000890 // Emit the RHS first. __block variables need to have the rhs evaluated
891 // first, plus this should improve codegen a little.
892 OpInfo.RHS = Visit(E->getRHS());
893 OpInfo.Ty = E->getComputationResultType();
894 OpInfo.E = E;
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000895 // Load/convert the LHS.
Chris Lattner3d966d62007-08-24 21:00:35 +0000896 LValue LHSLV = EmitLValue(E->getLHS());
897 OpInfo.LHS = EmitLoadOfLValue(LHSLV, LHSTy);
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000898 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
899 E->getComputationLHSType());
Chris Lattner3d966d62007-08-24 21:00:35 +0000900
901 // Expand the binary operator.
902 Value *Result = (this->*Func)(OpInfo);
903
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +0000904 // Convert the result back to the LHS type.
Eli Friedman8b7b1b12009-03-28 01:22:36 +0000905 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
906
Daniel Dunbar9b1335e2008-11-19 09:36:46 +0000907 // Store the result value into the LHS lvalue. Bit-fields are
Daniel Dunbar7689f6b2008-11-19 11:54:05 +0000908 // handled specially because the result is altered by the store,
909 // i.e., [C99 6.5.16p1] 'An assignment expression has the value of
910 // the left operand after the assignment...'.
Mike Stumpdf0fe272009-05-29 15:46:01 +0000911 if (LHSLV.isBitfield()) {
912 if (!LHSLV.isVolatileQualified()) {
913 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy,
914 &Result);
915 return Result;
916 } else
917 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, LHSTy);
918 } else
Daniel Dunbar9b1335e2008-11-19 09:36:46 +0000919 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV, LHSTy);
Mike Stumpdf0fe272009-05-29 15:46:01 +0000920 if (Ignore)
921 return 0;
922 return EmitLoadOfLValue(LHSLV, E->getType());
Chris Lattner3d966d62007-08-24 21:00:35 +0000923}
924
925
Chris Lattner2da04b32007-08-24 05:35:26 +0000926Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Nate Begeman628028b2007-12-30 01:28:16 +0000927 if (Ops.LHS->getType()->isFPOrFPVector())
Chris Lattner2da04b32007-08-24 05:35:26 +0000928 return Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Chris Lattner3d966d62007-08-24 21:00:35 +0000929 else if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner2da04b32007-08-24 05:35:26 +0000930 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
931 else
932 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
933}
934
935Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
936 // Rem in C can't be a floating point type: C99 6.5.5p2.
Chris Lattner3d966d62007-08-24 21:00:35 +0000937 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner2da04b32007-08-24 05:35:26 +0000938 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
939 else
940 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
941}
942
Mike Stump0c61b732009-04-01 20:28:16 +0000943Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
944 unsigned IID;
945 unsigned OpID = 0;
Mike Stump40968592009-04-02 01:03:55 +0000946
Mike Stumpd3e38852009-04-02 18:15:54 +0000947 switch (Ops.E->getOpcode()) {
948 case BinaryOperator::Add:
949 case BinaryOperator::AddAssign:
950 OpID = 1;
951 IID = llvm::Intrinsic::sadd_with_overflow;
952 break;
953 case BinaryOperator::Sub:
954 case BinaryOperator::SubAssign:
955 OpID = 2;
956 IID = llvm::Intrinsic::ssub_with_overflow;
957 break;
958 case BinaryOperator::Mul:
959 case BinaryOperator::MulAssign:
960 OpID = 3;
961 IID = llvm::Intrinsic::smul_with_overflow;
962 break;
963 default:
964 assert(false && "Unsupported operation for overflow detection");
Daniel Dunbard92123f2009-04-08 16:23:09 +0000965 IID = 0;
Mike Stump0c61b732009-04-01 20:28:16 +0000966 }
Mike Stumpd3e38852009-04-02 18:15:54 +0000967 OpID <<= 1;
968 OpID |= 1;
969
Mike Stump0c61b732009-04-01 20:28:16 +0000970 const llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
971
972 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, &opTy, 1);
973
974 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
975 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
976 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
977
978 // Branch in case of overflow.
979 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
980 llvm::BasicBlock *overflowBB =
981 CGF.createBasicBlock("overflow", CGF.CurFn);
982 llvm::BasicBlock *continueBB =
983 CGF.createBasicBlock("overflow.continue", CGF.CurFn);
984
985 Builder.CreateCondBr(overflow, overflowBB, continueBB);
986
987 // Handle overflow
988
989 Builder.SetInsertPoint(overflowBB);
990
991 // Handler is:
992 // long long *__overflow_handler)(long long a, long long b, char op,
993 // char width)
994 std::vector<const llvm::Type*> handerArgTypes;
995 handerArgTypes.push_back(llvm::Type::Int64Ty);
996 handerArgTypes.push_back(llvm::Type::Int64Ty);
997 handerArgTypes.push_back(llvm::Type::Int8Ty);
998 handerArgTypes.push_back(llvm::Type::Int8Ty);
Owen Anderson9793f0e2009-07-29 22:16:19 +0000999 llvm::FunctionType *handlerTy = llvm::FunctionType::get(llvm::Type::Int64Ty,
Mike Stump0c61b732009-04-01 20:28:16 +00001000 handerArgTypes, false);
1001 llvm::Value *handlerFunction =
1002 CGF.CGM.getModule().getOrInsertGlobal("__overflow_handler",
Owen Anderson9793f0e2009-07-29 22:16:19 +00001003 llvm::PointerType::getUnqual(handlerTy));
Mike Stump0c61b732009-04-01 20:28:16 +00001004 handlerFunction = Builder.CreateLoad(handlerFunction);
1005
1006 llvm::Value *handlerResult = Builder.CreateCall4(handlerFunction,
1007 Builder.CreateSExt(Ops.LHS, llvm::Type::Int64Ty),
1008 Builder.CreateSExt(Ops.RHS, llvm::Type::Int64Ty),
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001009 llvm::ConstantInt::get(llvm::Type::Int8Ty, OpID),
1010 llvm::ConstantInt::get(llvm::Type::Int8Ty,
Mike Stump0c61b732009-04-01 20:28:16 +00001011 cast<llvm::IntegerType>(opTy)->getBitWidth()));
1012
1013 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
1014
1015 Builder.CreateBr(continueBB);
1016
1017 // Set up the continuation
1018 Builder.SetInsertPoint(continueBB);
1019 // Get the correct result
1020 llvm::PHINode *phi = Builder.CreatePHI(opTy);
1021 phi->reserveOperandSpace(2);
1022 phi->addIncoming(result, initialBB);
1023 phi->addIncoming(handlerResult, overflowBB);
1024
1025 return phi;
1026}
Chris Lattner2da04b32007-08-24 05:35:26 +00001027
1028Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &Ops) {
Steve Naroff6b712a72009-07-14 18:25:06 +00001029 if (!Ops.Ty->isAnyPointerType()) {
Chris Lattner94dfae22009-06-17 06:36:24 +00001030 if (CGF.getContext().getLangOptions().OverflowChecking &&
1031 Ops.Ty->isSignedIntegerType())
Mike Stump0c61b732009-04-01 20:28:16 +00001032 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner94dfae22009-06-17 06:36:24 +00001033
1034 if (Ops.LHS->getType()->isFPOrFPVector())
1035 return Builder.CreateFAdd(Ops.LHS, Ops.RHS, "add");
1036
Chris Lattner2da04b32007-08-24 05:35:26 +00001037 return Builder.CreateAdd(Ops.LHS, Ops.RHS, "add");
Mike Stump0c61b732009-04-01 20:28:16 +00001038 }
Eli Friedmane381f7e2009-03-28 02:45:41 +00001039
Steve Naroff7cae42b2009-07-10 23:34:53 +00001040 if (Ops.Ty->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001041 Ops.Ty->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmane381f7e2009-03-28 02:45:41 +00001042 // The amount of the addition needs to account for the VLA size
1043 CGF.ErrorUnsupported(Ops.E, "VLA pointer addition");
1044 }
Chris Lattner20455f22008-01-03 06:36:51 +00001045 Value *Ptr, *Idx;
1046 Expr *IdxExp;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001047 const PointerType *PT = Ops.E->getLHS()->getType()->getAs<PointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001048 const ObjCObjectPointerType *OPT =
1049 Ops.E->getLHS()->getType()->getAsObjCObjectPointerType();
1050 if (PT || OPT) {
Chris Lattner20455f22008-01-03 06:36:51 +00001051 Ptr = Ops.LHS;
1052 Idx = Ops.RHS;
1053 IdxExp = Ops.E->getRHS();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001054 } else { // int + pointer
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001055 PT = Ops.E->getRHS()->getType()->getAs<PointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001056 OPT = Ops.E->getRHS()->getType()->getAsObjCObjectPointerType();
1057 assert((PT || OPT) && "Invalid add expr");
Chris Lattner20455f22008-01-03 06:36:51 +00001058 Ptr = Ops.RHS;
1059 Idx = Ops.LHS;
1060 IdxExp = Ops.E->getLHS();
1061 }
1062
1063 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta47425152009-04-24 02:40:57 +00001064 if (Width < CGF.LLVMPointerWidth) {
Chris Lattner20455f22008-01-03 06:36:51 +00001065 // Zero or sign extend the pointer value based on whether the index is
1066 // signed or not.
Owen Anderson9793f0e2009-07-29 22:16:19 +00001067 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Chris Lattner0f398c42008-07-26 22:37:01 +00001068 if (IdxExp->getType()->isSignedIntegerType())
Chris Lattner20455f22008-01-03 06:36:51 +00001069 Idx = Builder.CreateSExt(Idx, IdxType, "idx.ext");
1070 else
1071 Idx = Builder.CreateZExt(Idx, IdxType, "idx.ext");
1072 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001073 const QualType ElementType = PT ? PT->getPointeeType() : OPT->getPointeeType();
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001074 // Handle interface types, which are not represented with a concrete
1075 // type.
1076 if (const ObjCInterfaceType *OIT = dyn_cast<ObjCInterfaceType>(ElementType)) {
1077 llvm::Value *InterfaceSize =
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001078 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001079 CGF.getContext().getTypeSize(OIT) / 8);
1080 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Anderson9793f0e2009-07-29 22:16:19 +00001081 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001082 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
1083 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
1084 return Builder.CreateBitCast(Res, Ptr->getType());
1085 }
1086
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00001087 // Explicitly handle GNU void* and function pointer arithmetic
1088 // extensions. The GNU void* casts amount to no-ops since our void*
1089 // type is i8*, but this is future proof.
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00001090 if (ElementType->isVoidType() || ElementType->isFunctionType()) {
Owen Anderson9793f0e2009-07-29 22:16:19 +00001091 const llvm::Type *i8Ty = llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00001092 Value *Casted = Builder.CreateBitCast(Ptr, i8Ty);
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001093 Value *Res = Builder.CreateGEP(Casted, Idx, "add.ptr");
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00001094 return Builder.CreateBitCast(Res, Ptr->getType());
1095 }
Chris Lattner20455f22008-01-03 06:36:51 +00001096
Dan Gohman43b44842009-08-12 00:33:55 +00001097 return Builder.CreateInBoundsGEP(Ptr, Idx, "add.ptr");
Chris Lattner2da04b32007-08-24 05:35:26 +00001098}
1099
1100Value *ScalarExprEmitter::EmitSub(const BinOpInfo &Ops) {
Mike Stump0c61b732009-04-01 20:28:16 +00001101 if (!isa<llvm::PointerType>(Ops.LHS->getType())) {
Mike Stumpd3e38852009-04-02 18:15:54 +00001102 if (CGF.getContext().getLangOptions().OverflowChecking
1103 && Ops.Ty->isSignedIntegerType())
Mike Stump0c61b732009-04-01 20:28:16 +00001104 return EmitOverflowCheckedBinOp(Ops);
Chris Lattner94dfae22009-06-17 06:36:24 +00001105
1106 if (Ops.LHS->getType()->isFPOrFPVector())
1107 return Builder.CreateFSub(Ops.LHS, Ops.RHS, "sub");
Chris Lattner2da04b32007-08-24 05:35:26 +00001108 return Builder.CreateSub(Ops.LHS, Ops.RHS, "sub");
Mike Stump0c61b732009-04-01 20:28:16 +00001109 }
Chris Lattner3d966d62007-08-24 21:00:35 +00001110
Steve Naroff7cae42b2009-07-10 23:34:53 +00001111 if (Ops.E->getLHS()->getType()->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001112 Ops.E->getLHS()->getType()->getAs<PointerType>()->isVariableArrayType()) {
Eli Friedmane381f7e2009-03-28 02:45:41 +00001113 // The amount of the addition needs to account for the VLA size for
1114 // ptr-int
1115 // The amount of the division needs to account for the VLA size for
1116 // ptr-ptr.
1117 CGF.ErrorUnsupported(Ops.E, "VLA pointer subtraction");
1118 }
1119
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00001120 const QualType LHSType = Ops.E->getLHS()->getType();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001121 const QualType LHSElementType = LHSType->getPointeeType();
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +00001122 if (!isa<llvm::PointerType>(Ops.RHS->getType())) {
1123 // pointer - int
1124 Value *Idx = Ops.RHS;
1125 unsigned Width = cast<llvm::IntegerType>(Idx->getType())->getBitWidth();
Sanjiv Gupta47425152009-04-24 02:40:57 +00001126 if (Width < CGF.LLVMPointerWidth) {
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +00001127 // Zero or sign extend the pointer value based on whether the index is
1128 // signed or not.
Owen Anderson9793f0e2009-07-29 22:16:19 +00001129 const llvm::Type *IdxType = llvm::IntegerType::get(CGF.LLVMPointerWidth);
Daniel Dunbarbfb1cd72008-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 Dunbar42a8cd32009-01-23 18:51:09 +00001136
Daniel Dunbaref2ffbc2009-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 Andersonb7a2fe62009-07-24 23:12:58 +00001142 llvm::ConstantInt::get(Idx->getType(),
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00001143 CGF.getContext().getTypeSize(OIT) / 8);
1144 Idx = Builder.CreateMul(Idx, InterfaceSize);
Owen Anderson170229f2009-07-14 23:10:40 +00001145 const llvm::Type *i8Ty =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001146 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbaref2ffbc2009-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 Dunbar42a8cd32009-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 Anderson170229f2009-07-14 23:10:40 +00001156 const llvm::Type *i8Ty =
Owen Anderson9793f0e2009-07-29 22:16:19 +00001157 llvm::PointerType::getUnqual(llvm::Type::Int8Ty);
Daniel Dunbar42a8cd32009-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
Dan Gohman43b44842009-08-12 00:33:55 +00001163 return Builder.CreateInBoundsGEP(Ops.LHS, Idx, "sub.ptr");
Daniel Dunbar5aa55d52008-08-05 00:47:03 +00001164 } else {
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +00001165 // pointer - pointer
1166 Value *LHS = Ops.LHS;
1167 Value *RHS = Ops.RHS;
Chris Lattner3d966d62007-08-24 21:00:35 +00001168
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +00001169 uint64_t ElementSize;
Daniel Dunbar5aa55d52008-08-05 00:47:03 +00001170
Chris Lattner60dcdc72009-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 Dunbarbfb1cd72008-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 Lattner60dcdc72009-02-11 07:21:43 +00001184 // Optimize out the shift for element size of 1.
1185 if (ElementSize == 1)
1186 return BytesBetween;
Dan Gohman1cebe562009-08-11 22:40:09 +00001187
1188 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
1189 // pointer difference in C is only defined in the case where both
1190 // operands are pointing to elements of an array.
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001191 Value *BytesPerElt = llvm::ConstantInt::get(ResultType, ElementSize);
Dan Gohman1cebe562009-08-11 22:40:09 +00001192 return Builder.CreateExactSDiv(BytesBetween, BytesPerElt, "sub.ptr.div");
Chris Lattner2da04b32007-08-24 05:35:26 +00001193 }
Chris Lattner2da04b32007-08-24 05:35:26 +00001194}
1195
1196Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
1197 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1198 // RHS to the same size as the LHS.
1199 Value *RHS = Ops.RHS;
1200 if (Ops.LHS->getType() != RHS->getType())
1201 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1202
1203 return Builder.CreateShl(Ops.LHS, RHS, "shl");
1204}
1205
1206Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
1207 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
1208 // RHS to the same size as the LHS.
1209 Value *RHS = Ops.RHS;
1210 if (Ops.LHS->getType() != RHS->getType())
1211 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
1212
Chris Lattner3d966d62007-08-24 21:00:35 +00001213 if (Ops.Ty->isUnsignedIntegerType())
Chris Lattner2da04b32007-08-24 05:35:26 +00001214 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
1215 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
1216}
1217
1218Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
1219 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001220 TestAndClearIgnoreResultAssign();
Chris Lattner42e6b812007-08-26 16:34:22 +00001221 Value *Result;
Chris Lattner2da04b32007-08-24 05:35:26 +00001222 QualType LHSTy = E->getLHS()->getType();
Chris Lattner2a7deb62009-07-08 01:08:03 +00001223 if (!LHSTy->isAnyComplexType()) {
Chris Lattner2da04b32007-08-24 05:35:26 +00001224 Value *LHS = Visit(E->getLHS());
1225 Value *RHS = Visit(E->getRHS());
1226
Eli Friedman5ac69052009-07-22 06:07:16 +00001227 if (LHS->getType()->isFPOrFPVector()) {
Nate Begemanfe79ca22008-07-25 20:16:05 +00001228 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00001229 LHS, RHS, "cmp");
Eli Friedman3c285242008-05-29 15:09:15 +00001230 } else if (LHSTy->isSignedIntegerType()) {
1231 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00001232 LHS, RHS, "cmp");
1233 } else {
Eli Friedman3c285242008-05-29 15:09:15 +00001234 // Unsigned integers and pointers.
1235 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00001236 LHS, RHS, "cmp");
1237 }
Chris Lattner2a7deb62009-07-08 01:08:03 +00001238
1239 // If this is a vector comparison, sign extend the result to the appropriate
1240 // vector integer type and return it (don't convert to bool).
1241 if (LHSTy->isVectorType())
1242 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Nate Begemanfe79ca22008-07-25 20:16:05 +00001243
Chris Lattner2da04b32007-08-24 05:35:26 +00001244 } else {
1245 // Complex Comparison: can only be an equality comparison.
1246 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
1247 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
1248
Chris Lattner0f398c42008-07-26 22:37:01 +00001249 QualType CETy = LHSTy->getAsComplexType()->getElementType();
Chris Lattner2da04b32007-08-24 05:35:26 +00001250
Chris Lattner42e6b812007-08-26 16:34:22 +00001251 Value *ResultR, *ResultI;
Chris Lattner2da04b32007-08-24 05:35:26 +00001252 if (CETy->isRealFloatingType()) {
1253 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1254 LHS.first, RHS.first, "cmp.r");
1255 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
1256 LHS.second, RHS.second, "cmp.i");
1257 } else {
1258 // Complex comparisons can only be equality comparisons. As such, signed
1259 // and unsigned opcodes are the same.
1260 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1261 LHS.first, RHS.first, "cmp.r");
1262 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
1263 LHS.second, RHS.second, "cmp.i");
1264 }
1265
1266 if (E->getOpcode() == BinaryOperator::EQ) {
1267 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
1268 } else {
1269 assert(E->getOpcode() == BinaryOperator::NE &&
1270 "Complex comparison other than == or != ?");
1271 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
1272 }
1273 }
Nuno Lopesa0abe622009-01-11 23:22:37 +00001274
1275 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner2da04b32007-08-24 05:35:26 +00001276}
1277
1278Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001279 bool Ignore = TestAndClearIgnoreResultAssign();
1280
1281 // __block variables need to have the rhs evaluated first, plus this should
1282 // improve codegen just a little.
Chris Lattner2da04b32007-08-24 05:35:26 +00001283 Value *RHS = Visit(E->getRHS());
Mike Stumpaed08f92009-05-21 21:05:15 +00001284 LValue LHS = EmitLValue(E->getLHS());
Chris Lattner2da04b32007-08-24 05:35:26 +00001285
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001286 // Store the value into the LHS. Bit-fields are handled specially
Daniel Dunbar7689f6b2008-11-19 11:54:05 +00001287 // because the result is altered by the store, i.e., [C99 6.5.16p1]
1288 // 'An assignment expression has the value of the left operand after
Eli Friedmane381f7e2009-03-28 02:45:41 +00001289 // the assignment...'.
Mike Stumpdf0fe272009-05-29 15:46:01 +00001290 if (LHS.isBitfield()) {
1291 if (!LHS.isVolatileQualified()) {
1292 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType(),
1293 &RHS);
1294 return RHS;
1295 } else
1296 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, E->getType());
1297 } else
Daniel Dunbar9b1335e2008-11-19 09:36:46 +00001298 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS, E->getType());
Mike Stumpdf0fe272009-05-29 15:46:01 +00001299 if (Ignore)
1300 return 0;
1301 return EmitLoadOfLValue(LHS, E->getType());
Chris Lattner2da04b32007-08-24 05:35:26 +00001302}
1303
1304Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Chris Lattner8b084582008-11-12 08:26:50 +00001305 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
1306 // If we have 1 && X, just emit X without inserting the control flow.
1307 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1308 if (Cond == 1) { // If we have 1 && X, just emit X.
Chris Lattner5b1964b2008-11-11 07:41:27 +00001309 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1310 // ZExt result to int.
1311 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "land.ext");
1312 }
Chris Lattner8b084582008-11-12 08:26:50 +00001313
1314 // 0 && RHS: If it is safe, just elide the RHS, and return 0.
1315 if (!CGF.ContainsLabel(E->getRHS()))
Owen Anderson0b75f232009-07-31 20:28:54 +00001316 return llvm::Constant::getNullValue(CGF.LLVMIntTy);
Chris Lattner5b1964b2008-11-11 07:41:27 +00001317 }
1318
Daniel Dunbara612e792008-11-13 01:38:36 +00001319 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
1320 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner8b084582008-11-12 08:26:50 +00001321
Chris Lattner35710d182008-11-12 08:38:24 +00001322 // Branch on the LHS first. If it is false, go to the failure (cont) block.
1323 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
1324
1325 // Any edges into the ContBlock are now from an (indeterminate number of)
1326 // edges from this first condition. All of these values will be false. Start
1327 // setting up the PHI node in the Cont Block for this.
1328 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1329 PN->reserveOperandSpace(2); // Normal case, two inputs.
1330 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1331 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00001332 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Chris Lattner2da04b32007-08-24 05:35:26 +00001333
Anders Carlssonf47a3de2009-06-04 02:53:13 +00001334 CGF.PushConditionalTempDestruction();
Chris Lattner2da04b32007-08-24 05:35:26 +00001335 CGF.EmitBlock(RHSBlock);
1336 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Anders Carlssonf47a3de2009-06-04 02:53:13 +00001337 CGF.PopConditionalTempDestruction();
Chris Lattner2da04b32007-08-24 05:35:26 +00001338
1339 // Reaquire the RHS block, as there may be subblocks inserted.
1340 RHSBlock = Builder.GetInsertBlock();
Chris Lattner35710d182008-11-12 08:38:24 +00001341
1342 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1343 // into the phi node for the edge with the value of RHSCond.
Chris Lattner2da04b32007-08-24 05:35:26 +00001344 CGF.EmitBlock(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00001345 PN->addIncoming(RHSCond, RHSBlock);
1346
1347 // ZExt result to int.
1348 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "land.ext");
1349}
1350
1351Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Chris Lattner8b084582008-11-12 08:26:50 +00001352 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
1353 // If we have 0 || X, just emit X without inserting the control flow.
1354 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getLHS())) {
1355 if (Cond == -1) { // If we have 0 || X, just emit X.
Chris Lattner5b1964b2008-11-11 07:41:27 +00001356 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1357 // ZExt result to int.
1358 return Builder.CreateZExt(RHSCond, CGF.LLVMIntTy, "lor.ext");
1359 }
Chris Lattner8b084582008-11-12 08:26:50 +00001360
Eli Friedmane9184352008-12-02 16:02:46 +00001361 // 1 || RHS: If it is safe, just elide the RHS, and return 1.
Chris Lattner8b084582008-11-12 08:26:50 +00001362 if (!CGF.ContainsLabel(E->getRHS()))
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001363 return llvm::ConstantInt::get(CGF.LLVMIntTy, 1);
Chris Lattner5b1964b2008-11-11 07:41:27 +00001364 }
1365
Daniel Dunbara612e792008-11-13 01:38:36 +00001366 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
1367 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Chris Lattner2da04b32007-08-24 05:35:26 +00001368
Chris Lattner35710d182008-11-12 08:38:24 +00001369 // Branch on the LHS first. If it is true, go to the success (cont) block.
1370 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
1371
1372 // Any edges into the ContBlock are now from an (indeterminate number of)
1373 // edges from this first condition. All of these values will be true. Start
1374 // setting up the PHI node in the Cont Block for this.
1375 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::Int1Ty, "", ContBlock);
1376 PN->reserveOperandSpace(2); // Normal case, two inputs.
1377 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
1378 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00001379 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattner35710d182008-11-12 08:38:24 +00001380
Anders Carlssonf47a3de2009-06-04 02:53:13 +00001381 CGF.PushConditionalTempDestruction();
1382
Chris Lattner35710d182008-11-12 08:38:24 +00001383 // Emit the RHS condition as a bool value.
Chris Lattner2da04b32007-08-24 05:35:26 +00001384 CGF.EmitBlock(RHSBlock);
1385 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
1386
Anders Carlssonf47a3de2009-06-04 02:53:13 +00001387 CGF.PopConditionalTempDestruction();
1388
Chris Lattner2da04b32007-08-24 05:35:26 +00001389 // Reaquire the RHS block, as there may be subblocks inserted.
1390 RHSBlock = Builder.GetInsertBlock();
Chris Lattner2da04b32007-08-24 05:35:26 +00001391
Chris Lattner35710d182008-11-12 08:38:24 +00001392 // Emit an unconditional branch from this block to ContBlock. Insert an entry
1393 // into the phi node for the edge with the value of RHSCond.
1394 CGF.EmitBlock(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00001395 PN->addIncoming(RHSCond, RHSBlock);
1396
1397 // ZExt result to int.
1398 return Builder.CreateZExt(PN, CGF.LLVMIntTy, "lor.ext");
1399}
1400
1401Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
1402 CGF.EmitStmt(E->getLHS());
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00001403 CGF.EnsureInsertPoint();
Chris Lattner2da04b32007-08-24 05:35:26 +00001404 return Visit(E->getRHS());
1405}
1406
1407//===----------------------------------------------------------------------===//
1408// Other Operators
1409//===----------------------------------------------------------------------===//
1410
Chris Lattner3fd91f832008-11-12 08:55:54 +00001411/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
1412/// expression is cheap enough and side-effect-free enough to evaluate
1413/// unconditionally instead of conditionally. This is used to convert control
1414/// flow into selects in some cases.
1415static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E) {
1416 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
1417 return isCheapEnoughToEvaluateUnconditionally(PE->getSubExpr());
1418
1419 // TODO: Allow anything we can constant fold to an integer or fp constant.
1420 if (isa<IntegerLiteral>(E) || isa<CharacterLiteral>(E) ||
1421 isa<FloatingLiteral>(E))
1422 return true;
1423
1424 // Non-volatile automatic variables too, to get "cond ? X : Y" where
1425 // X and Y are local variables.
1426 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
1427 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
1428 if (VD->hasLocalStorage() && !VD->getType().isVolatileQualified())
1429 return true;
1430
1431 return false;
1432}
1433
1434
Chris Lattner2da04b32007-08-24 05:35:26 +00001435Value *ScalarExprEmitter::
1436VisitConditionalOperator(const ConditionalOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001437 TestAndClearIgnoreResultAssign();
Chris Lattnercd439292008-11-12 08:04:58 +00001438 // If the condition constant folds and can be elided, try to avoid emitting
1439 // the condition and the dead arm.
1440 if (int Cond = CGF.ConstantFoldsToSimpleInteger(E->getCond())){
Chris Lattnerd53e2332008-11-11 18:56:45 +00001441 Expr *Live = E->getLHS(), *Dead = E->getRHS();
Chris Lattnercd439292008-11-12 08:04:58 +00001442 if (Cond == -1)
Chris Lattnerd53e2332008-11-11 18:56:45 +00001443 std::swap(Live, Dead);
Chris Lattnercd439292008-11-12 08:04:58 +00001444
1445 // If the dead side doesn't have labels we need, and if the Live side isn't
1446 // the gnu missing ?: extension (which we could handle, but don't bother
1447 // to), just emit the Live part.
1448 if ((!Dead || !CGF.ContainsLabel(Dead)) && // No labels in dead part
1449 Live) // Live part isn't missing.
1450 return Visit(Live);
Chris Lattnerd53e2332008-11-11 18:56:45 +00001451 }
1452
Chris Lattner3fd91f832008-11-12 08:55:54 +00001453
1454 // If this is a really simple expression (like x ? 4 : 5), emit this as a
1455 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner9ce8a532008-11-16 06:16:27 +00001456 // safe to evaluate the LHS and RHS unconditionally.
Chris Lattner3fd91f832008-11-12 08:55:54 +00001457 if (E->getLHS() && isCheapEnoughToEvaluateUnconditionally(E->getLHS()) &&
1458 isCheapEnoughToEvaluateUnconditionally(E->getRHS())) {
1459 llvm::Value *CondV = CGF.EvaluateExprAsBool(E->getCond());
1460 llvm::Value *LHS = Visit(E->getLHS());
1461 llvm::Value *RHS = Visit(E->getRHS());
1462 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
1463 }
1464
1465
Daniel Dunbard2a53a72008-11-12 10:13:37 +00001466 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
1467 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbara612e792008-11-13 01:38:36 +00001468 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
Chris Lattner51e71182008-11-12 08:08:13 +00001469 Value *CondVal = 0;
Chris Lattnercd439292008-11-12 08:04:58 +00001470
Chris Lattnercd7bc142009-02-13 23:35:32 +00001471 // If we don't have the GNU missing condition extension, emit a branch on
1472 // bool the normal way.
1473 if (E->getLHS()) {
1474 // Otherwise, just use EmitBranchOnBoolExpr to get small and simple code for
1475 // the branch on bool.
1476 CGF.EmitBranchOnBoolExpr(E->getCond(), LHSBlock, RHSBlock);
1477 } else {
1478 // Otherwise, for the ?: extension, evaluate the conditional and then
1479 // convert it to bool the hard way. We do this explicitly because we need
1480 // the unconverted value for the missing middle value of the ?:.
Chris Lattner51e71182008-11-12 08:08:13 +00001481 CondVal = CGF.EmitScalarExpr(E->getCond());
Chris Lattnercd7bc142009-02-13 23:35:32 +00001482
1483 // In some cases, EmitScalarConversion will delete the "CondVal" expression
1484 // if there are no extra uses (an optimization). Inhibit this by making an
1485 // extra dead use, because we're going to add a use of CondVal later. We
1486 // don't use the builder for this, because we don't want it to get optimized
1487 // away. This leaves dead code, but the ?: extension isn't common.
1488 new llvm::BitCastInst(CondVal, CondVal->getType(), "dummy?:holder",
1489 Builder.GetInsertBlock());
1490
Chris Lattner51e71182008-11-12 08:08:13 +00001491 Value *CondBoolVal =
1492 CGF.EmitScalarConversion(CondVal, E->getCond()->getType(),
1493 CGF.getContext().BoolTy);
1494 Builder.CreateCondBr(CondBoolVal, LHSBlock, RHSBlock);
Chris Lattner51e71182008-11-12 08:08:13 +00001495 }
Anders Carlsson43c52cd2009-06-04 03:00:32 +00001496
1497 CGF.PushConditionalTempDestruction();
Chris Lattner2da04b32007-08-24 05:35:26 +00001498 CGF.EmitBlock(LHSBlock);
1499
1500 // Handle the GNU extension for missing LHS.
Chris Lattner2ab40a62007-11-26 01:40:58 +00001501 Value *LHS;
1502 if (E->getLHS())
Eli Friedmand5a48382008-05-16 20:38:39 +00001503 LHS = Visit(E->getLHS());
Chris Lattner2ab40a62007-11-26 01:40:58 +00001504 else // Perform promotions, to handle cases like "short ?: int"
1505 LHS = EmitScalarConversion(CondVal, E->getCond()->getType(), E->getType());
1506
Anders Carlsson43c52cd2009-06-04 03:00:32 +00001507 CGF.PopConditionalTempDestruction();
Chris Lattner2da04b32007-08-24 05:35:26 +00001508 LHSBlock = Builder.GetInsertBlock();
Daniel Dunbarc56e6762008-11-11 09:41:28 +00001509 CGF.EmitBranch(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00001510
Anders Carlsson43c52cd2009-06-04 03:00:32 +00001511 CGF.PushConditionalTempDestruction();
Chris Lattner2da04b32007-08-24 05:35:26 +00001512 CGF.EmitBlock(RHSBlock);
1513
Eli Friedmand5a48382008-05-16 20:38:39 +00001514 Value *RHS = Visit(E->getRHS());
Anders Carlsson43c52cd2009-06-04 03:00:32 +00001515 CGF.PopConditionalTempDestruction();
Chris Lattner2da04b32007-08-24 05:35:26 +00001516 RHSBlock = Builder.GetInsertBlock();
Daniel Dunbarc56e6762008-11-11 09:41:28 +00001517 CGF.EmitBranch(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00001518
1519 CGF.EmitBlock(ContBlock);
1520
Nuno Lopes7bd6e582008-06-04 19:15:45 +00001521 if (!LHS || !RHS) {
Chris Lattnerb6a7b582007-11-30 17:56:23 +00001522 assert(E->getType()->isVoidType() && "Non-void value should have a value");
1523 return 0;
1524 }
1525
Chris Lattner2da04b32007-08-24 05:35:26 +00001526 // Create a PHI node for the real part.
1527 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), "cond");
1528 PN->reserveOperandSpace(2);
1529 PN->addIncoming(LHS, LHSBlock);
1530 PN->addIncoming(RHS, RHSBlock);
1531 return PN;
1532}
1533
1534Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmane0a5b8b2009-03-04 05:52:32 +00001535 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner2da04b32007-08-24 05:35:26 +00001536}
1537
Chris Lattnerb6a7b582007-11-30 17:56:23 +00001538Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedmanddea0ad2009-01-20 17:46:04 +00001539 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson13abd7e2008-11-04 05:30:00 +00001540 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
1541
1542 // If EmitVAArg fails, we fall back to the LLVM instruction.
1543 if (!ArgPtr)
1544 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
1545
Mike Stumpdf0fe272009-05-29 15:46:01 +00001546 // FIXME Volatility.
Anders Carlsson13abd7e2008-11-04 05:30:00 +00001547 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7e13ab82007-10-15 20:28:48 +00001548}
1549
Mike Stumpab3afd82009-02-12 18:29:15 +00001550Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *BE) {
Mike Stumpaeb0ffd2009-03-07 02:35:30 +00001551 return CGF.BuildBlockLiteralTmp(BE);
Mike Stumpab3afd82009-02-12 18:29:15 +00001552}
1553
Chris Lattner2da04b32007-08-24 05:35:26 +00001554//===----------------------------------------------------------------------===//
1555// Entry Point into this File
1556//===----------------------------------------------------------------------===//
1557
Mike Stumpdf0fe272009-05-29 15:46:01 +00001558/// EmitScalarExpr - Emit the computation of the specified expression of
1559/// scalar type, ignoring the result.
1560Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner2da04b32007-08-24 05:35:26 +00001561 assert(E && !hasAggregateLLVMType(E->getType()) &&
1562 "Invalid scalar expression to emit");
1563
Mike Stumpdf0fe272009-05-29 15:46:01 +00001564 return ScalarExprEmitter(*this, IgnoreResultAssign)
1565 .Visit(const_cast<Expr*>(E));
Chris Lattner2da04b32007-08-24 05:35:26 +00001566}
Chris Lattner3474c202007-08-26 06:48:56 +00001567
1568/// EmitScalarConversion - Emit a conversion from the specified type to the
1569/// specified destination type, both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00001570Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
1571 QualType DstTy) {
Chris Lattner3474c202007-08-26 06:48:56 +00001572 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
1573 "Invalid scalar expression to emit");
1574 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
1575}
Chris Lattner42e6b812007-08-26 16:34:22 +00001576
1577/// EmitComplexToScalarConversion - Emit a conversion from the specified
1578/// complex type to the specified destination type, where the destination
1579/// type is an LLVM scalar type.
1580Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
1581 QualType SrcTy,
1582 QualType DstTy) {
Chris Lattnerf3bc75a2008-04-04 16:54:41 +00001583 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner42e6b812007-08-26 16:34:22 +00001584 "Invalid complex -> scalar conversion");
1585 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
1586 DstTy);
1587}
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00001588
1589Value *CodeGenFunction::EmitShuffleVector(Value* V1, Value *V2, ...) {
1590 assert(V1->getType() == V2->getType() &&
1591 "Vector operands must be of the same type");
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00001592 unsigned NumElements =
1593 cast<llvm::VectorType>(V1->getType())->getNumElements();
1594
1595 va_list va;
1596 va_start(va, V2);
1597
1598 llvm::SmallVector<llvm::Constant*, 16> Args;
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00001599 for (unsigned i = 0; i < NumElements; i++) {
1600 int n = va_arg(va, int);
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00001601 assert(n >= 0 && n < (int)NumElements * 2 &&
1602 "Vector shuffle index out of bounds!");
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001603 Args.push_back(llvm::ConstantInt::get(llvm::Type::Int32Ty, n));
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00001604 }
1605
1606 const char *Name = va_arg(va, const char *);
1607 va_end(va);
1608
Owen Anderson3cc120a2009-07-28 21:22:35 +00001609 llvm::Constant *Mask = llvm::ConstantVector::get(&Args[0], NumElements);
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00001610
1611 return Builder.CreateShuffleVector(V1, V2, Mask, Name);
1612}
1613
Anders Carlssonf5f65442007-12-15 21:23:30 +00001614llvm::Value *CodeGenFunction::EmitVector(llvm::Value * const *Vals,
Chris Lattner62843782008-07-26 20:15:14 +00001615 unsigned NumVals, bool isSplat) {
Anders Carlssonf5f65442007-12-15 21:23:30 +00001616 llvm::Value *Vec
Owen Anderson7ec07a52009-07-30 23:11:26 +00001617 = llvm::UndefValue::get(llvm::VectorType::get(Vals[0]->getType(), NumVals));
Anders Carlssonf5f65442007-12-15 21:23:30 +00001618
Chris Lattner62843782008-07-26 20:15:14 +00001619 for (unsigned i = 0, e = NumVals; i != e; ++i) {
Nate Begeman330aaa72007-12-30 02:59:45 +00001620 llvm::Value *Val = isSplat ? Vals[0] : Vals[i];
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001621 llvm::Value *Idx = llvm::ConstantInt::get(llvm::Type::Int32Ty, i);
Nate Begeman330aaa72007-12-30 02:59:45 +00001622 Vec = Builder.CreateInsertElement(Vec, Val, Idx, "tmp");
Anders Carlssonf5f65442007-12-15 21:23:30 +00001623 }
1624
1625 return Vec;
1626}