blob: ed927e2fb4afa92e12621998b1cffc7d374394eb [file] [log] [blame]
Chris Lattner7f02f722007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner7f02f722007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall4c40d982010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "CGDebugInfo.h"
Fariborz Jahanianf7bcc7e2009-10-10 20:07:56 +000017#include "CGObjCRuntime.h"
Chris Lattner7f02f722007-08-24 05:35:26 +000018#include "CodeGenModule.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar98c5ead2008-08-12 05:08:18 +000020#include "clang/AST/DeclObjC.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000021#include "clang/AST/RecordLayout.h"
Daniel Dunbarde7fb842008-08-11 05:00:27 +000022#include "clang/AST/StmtVisitor.h"
Chris Lattner25ddea72008-04-20 00:50:39 +000023#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000025#include "llvm/IR/Constants.h"
26#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/Function.h"
28#include "llvm/IR/GlobalVariable.h"
29#include "llvm/IR/Intrinsics.h"
30#include "llvm/IR/Module.h"
Chris Lattnerf7b5ea92008-11-12 08:38:24 +000031#include "llvm/Support/CFG.h"
Chris Lattnerc89bf692008-01-03 07:05:49 +000032#include <cstdarg>
Ted Kremenek6aad91a2007-12-10 23:44:32 +000033
Chris Lattner7f02f722007-08-24 05:35:26 +000034using namespace clang;
35using namespace CodeGen;
36using llvm::Value;
37
38//===----------------------------------------------------------------------===//
39// Scalar Expression Emitter
40//===----------------------------------------------------------------------===//
41
Benjamin Kramer79ba2a62010-10-22 16:48:22 +000042namespace {
Chris Lattner7f02f722007-08-24 05:35:26 +000043struct BinOpInfo {
44 Value *LHS;
45 Value *RHS;
Chris Lattner1f1ded92007-08-24 21:00:35 +000046 QualType Ty; // Computation Type.
Chris Lattner9a207232010-06-26 21:48:21 +000047 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
Lang Hamesbe9af122012-10-02 04:45:10 +000048 bool FPContractable;
Chris Lattner9a207232010-06-26 21:48:21 +000049 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner7f02f722007-08-24 05:35:26 +000050};
51
John McCall404cd162010-11-13 01:35:44 +000052static bool MustVisitNullValue(const Expr *E) {
53 // If a null pointer expression's type is the C++0x nullptr_t, then
54 // it's not necessarily a simple constant and it must be evaluated
55 // for its potential side effects.
56 return E->getType()->isNullPtrType();
57}
58
Benjamin Kramer85b45212009-11-28 19:45:26 +000059class ScalarExprEmitter
Chris Lattner7f02f722007-08-24 05:35:26 +000060 : public StmtVisitor<ScalarExprEmitter, Value*> {
61 CodeGenFunction &CGF;
Daniel Dunbar45d196b2008-11-01 01:53:16 +000062 CGBuilderTy &Builder;
Mike Stump7f79f9b2009-05-29 15:46:01 +000063 bool IgnoreResultAssign;
Owen Andersona1cf15f2009-07-14 23:10:40 +000064 llvm::LLVMContext &VMContext;
Chris Lattner7f02f722007-08-24 05:35:26 +000065public:
66
Mike Stump7f79f9b2009-05-29 15:46:01 +000067 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stumpdb52dcd2009-09-09 13:00:44 +000068 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Andersona1cf15f2009-07-14 23:10:40 +000069 VMContext(cgf.getLLVMContext()) {
Chris Lattner7f02f722007-08-24 05:35:26 +000070 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000071
Chris Lattner7f02f722007-08-24 05:35:26 +000072 //===--------------------------------------------------------------------===//
73 // Utilities
74 //===--------------------------------------------------------------------===//
75
Mike Stump7f79f9b2009-05-29 15:46:01 +000076 bool TestAndClearIgnoreResultAssign() {
Chris Lattner9c10fcf2009-07-08 01:08:03 +000077 bool I = IgnoreResultAssign;
78 IgnoreResultAssign = false;
79 return I;
80 }
Mike Stump7f79f9b2009-05-29 15:46:01 +000081
Chris Lattner2acc6e32011-07-18 04:24:23 +000082 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner7f02f722007-08-24 05:35:26 +000083 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith7ac9ef12012-09-08 02:08:36 +000084 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
85 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith2c9f87c2012-08-24 00:54:33 +000086 }
Chris Lattner7f02f722007-08-24 05:35:26 +000087
Richard Smith4def70d2012-10-09 19:52:38 +000088 void EmitBinOpCheck(Value *Check, const BinOpInfo &Info);
89
John McCall545d9962011-06-25 02:11:03 +000090 Value *EmitLoadOfLValue(LValue LV) {
91 return CGF.EmitLoadOfLValue(LV).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000092 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000093
Chris Lattner7f02f722007-08-24 05:35:26 +000094 /// EmitLoadOfLValue - Given an expression with complex type that represents a
95 /// value l-value, this method emits the address of the l-value, then loads
96 /// and returns the result.
97 Value *EmitLoadOfLValue(const Expr *E) {
Richard Smith7ac9ef12012-09-08 02:08:36 +000098 return EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load));
Chris Lattner7f02f722007-08-24 05:35:26 +000099 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000100
Chris Lattner9abc84e2007-08-26 16:42:57 +0000101 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000102 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000103 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000104
Richard Smithb2aa66c2012-10-12 22:57:06 +0000105 /// \brief Emit a check that a conversion to or from a floating-point type
106 /// does not overflow.
107 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
108 Value *Src, QualType SrcType,
109 QualType DstType, llvm::Type *DstTy);
110
Chris Lattner3707b252007-08-26 06:48:56 +0000111 /// EmitScalarConversion - Emit a conversion from the specified type to the
112 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000113 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
114
115 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000116 /// complex type to the specified destination type, where the destination type
117 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000118 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
119 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000120
Anders Carlssona40a9f32010-05-22 17:45:10 +0000121 /// EmitNullValue - Emit a value that corresponds to null for the given type.
122 Value *EmitNullValue(QualType Ty);
123
John McCalldaa8e4e2010-11-15 09:13:47 +0000124 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
125 Value *EmitFloatToBoolConversion(Value *V) {
126 // Compare against 0.0 for fp scalars.
127 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
128 return Builder.CreateFCmpUNE(V, Zero, "tobool");
129 }
130
131 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
132 Value *EmitPointerToBoolConversion(Value *V) {
133 Value *Zero = llvm::ConstantPointerNull::get(
134 cast<llvm::PointerType>(V->getType()));
135 return Builder.CreateICmpNE(V, Zero, "tobool");
136 }
137
138 Value *EmitIntToBoolConversion(Value *V) {
139 // Because of the type rules of C, we often end up computing a
140 // logical value, then zero extending it to int, then wanting it
141 // as a logical value again. Optimize this common case.
142 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
143 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
144 Value *Result = ZI->getOperand(0);
145 // If there aren't any more uses, zap the instruction to save space.
146 // Note that there can be more uses, for example if this
147 // is the result of an assignment.
148 if (ZI->use_empty())
149 ZI->eraseFromParent();
150 return Result;
151 }
152 }
153
Chris Lattner48431f92011-04-19 22:55:03 +0000154 return Builder.CreateIsNotNull(V, "tobool");
John McCalldaa8e4e2010-11-15 09:13:47 +0000155 }
156
Chris Lattner7f02f722007-08-24 05:35:26 +0000157 //===--------------------------------------------------------------------===//
158 // Visitor Methods
159 //===--------------------------------------------------------------------===//
160
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000161 Value *Visit(Expr *E) {
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000162 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
163 }
164
Chris Lattner7f02f722007-08-24 05:35:26 +0000165 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000166 S->dump(CGF.getContext().getSourceManager());
David Blaikieb219cfc2011-09-23 05:06:16 +0000167 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner7f02f722007-08-24 05:35:26 +0000168 }
169 Value *VisitExpr(Expr *S);
Fariborz Jahanianf51dc642009-10-21 23:45:42 +0000170
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000171 Value *VisitParenExpr(ParenExpr *PE) {
172 return Visit(PE->getSubExpr());
173 }
John McCall91a57552011-07-15 05:09:51 +0000174 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
175 return Visit(E->getReplacement());
176 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000177 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
178 return Visit(GE->getResultExpr());
179 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000180
181 // Leaves.
182 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000183 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000184 }
185 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000186 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000187 }
188 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000189 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000190 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000191 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
192 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
193 }
Nate Begemane7579b52007-11-15 05:40:03 +0000194 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000195 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000196 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000197 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000198 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000199 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000200 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000201 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000202 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000203 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000204 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000205 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000206 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
207 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000208 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000209
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000210 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000211 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000212 }
John McCalle996ffd2011-02-16 08:02:54 +0000213
John McCall4b9c2d22011-11-06 09:01:30 +0000214 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
215 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
216 }
217
John McCalle996ffd2011-02-16 08:02:54 +0000218 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000219 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +0000220 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E));
John McCalle996ffd2011-02-16 08:02:54 +0000221
222 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000223 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000224 }
John McCalldd2ecee2012-03-10 03:05:10 +0000225
Chris Lattner7f02f722007-08-24 05:35:26 +0000226 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000227 Value *VisitDeclRefExpr(DeclRefExpr *E) {
228 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCalldd2ecee2012-03-10 03:05:10 +0000229 if (result.isReference())
John McCallf4b88a42012-03-10 09:33:50 +0000230 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E));
John McCalldd2ecee2012-03-10 03:05:10 +0000231 return result.getValue();
Richard Smitha3ca41f2012-03-02 23:27:11 +0000232 }
John McCallf4b88a42012-03-10 09:33:50 +0000233 return EmitLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000234 }
235
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000236 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
237 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000238 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000239 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
240 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000241 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000242 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000243 return EmitLoadOfLValue(E);
244 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000245 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000246 if (E->getMethodDecl() &&
247 E->getMethodDecl()->getResultType()->isReferenceType())
248 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000249 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000250 }
251
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000252 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000253 LValue LV = CGF.EmitObjCIsaExpr(E);
John McCall545d9962011-06-25 02:11:03 +0000254 Value *V = CGF.EmitLoadOfLValue(LV).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000255 return V;
256 }
257
Chris Lattner7f02f722007-08-24 05:35:26 +0000258 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000259 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000260 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000261 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000262 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
263 return EmitLoadOfLValue(E);
264 }
Devang Patel35634f52007-10-24 17:18:43 +0000265
Nate Begeman0533b302009-10-18 20:10:40 +0000266 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000267
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000268 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith0dbe2fb2012-12-21 03:17:28 +0000269 return EmitNullValue(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000270 }
John McCallbc8d40d2011-06-24 21:55:10 +0000271 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000272 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000273 CGF.EmitVariablyModifiedType(E->getType());
274 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000275 }
John McCallbc8d40d2011-06-24 21:55:10 +0000276 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000277
278 Value *VisitCallExpr(const CallExpr *E) {
Anders Carlssone9f2f452009-05-27 03:37:57 +0000279 if (E->getCallReturnType()->isReferenceType())
280 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000281
Chris Lattner9b655512007-08-31 22:49:20 +0000282 return CGF.EmitCallExpr(E).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +0000283 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000284
Chris Lattner33793202007-08-31 22:09:40 +0000285 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000286
Chris Lattner7f02f722007-08-24 05:35:26 +0000287 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000288 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000289 LValue LV = EmitLValue(E->getSubExpr());
290 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000291 }
292 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000293 LValue LV = EmitLValue(E->getSubExpr());
294 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000295 }
296 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000297 LValue LV = EmitLValue(E->getSubExpr());
298 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000299 }
300 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000301 LValue LV = EmitLValue(E->getSubExpr());
302 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000303 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000304
Anton Yartsev683564a2011-02-07 02:17:30 +0000305 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
306 llvm::Value *InVal,
307 llvm::Value *NextVal,
308 bool IsInc);
309
Chris Lattner8c11a652010-06-26 22:09:34 +0000310 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
311 bool isInc, bool isPre);
312
313
Chris Lattner7f02f722007-08-24 05:35:26 +0000314 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000315 if (isa<MemberPointerType>(E->getType())) // never sugared
316 return CGF.CGM.getMemberPointerConstant(E);
317
Chris Lattner7f02f722007-08-24 05:35:26 +0000318 return EmitLValue(E->getSubExpr()).getAddress();
319 }
John McCallfd569002010-12-04 12:43:24 +0000320 Value *VisitUnaryDeref(const UnaryOperator *E) {
321 if (E->getType()->isVoidType())
322 return Visit(E->getSubExpr()); // the actual value should be unused
323 return EmitLoadOfLValue(E);
324 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000325 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000326 // This differs from gcc, though, most likely due to a bug in gcc.
327 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000328 return Visit(E->getSubExpr());
329 }
330 Value *VisitUnaryMinus (const UnaryOperator *E);
331 Value *VisitUnaryNot (const UnaryOperator *E);
332 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000333 Value *VisitUnaryReal (const UnaryOperator *E);
334 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000335 Value *VisitUnaryExtension(const UnaryOperator *E) {
336 return Visit(E->getSubExpr());
337 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +0000338
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000339 // C++
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000340 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedmanec24b0e2011-08-14 04:50:34 +0000341 return EmitLoadOfLValue(E);
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000342 }
343
Chris Lattner04421082008-04-08 04:40:51 +0000344 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
345 return Visit(DAE->getExpr());
346 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000347 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
348 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000349 }
350
John McCall4765fa02010-12-06 08:20:24 +0000351 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000352 CGF.enterFullExpression(E);
353 CodeGenFunction::RunCleanupsScope Scope(CGF);
354 return Visit(E->getSubExpr());
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000355 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000356 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
357 return CGF.EmitCXXNewExpr(E);
358 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000359 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
360 CGF.EmitCXXDeleteExpr(E);
361 return 0;
362 }
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000363 Value *VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000364 return Builder.getInt1(E->getValue());
Eli Friedman9dfebdc2009-12-10 22:40:32 +0000365 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000366
Francois Pichet6ad6f282010-12-07 00:08:36 +0000367 Value *VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000368 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000369 }
370
John Wiegley21ff2e52011-04-28 00:16:57 +0000371 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
372 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
373 }
374
John Wiegley55262202011-04-25 06:54:41 +0000375 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
376 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
377 }
378
Douglas Gregora71d8192009-09-04 17:36:40 +0000379 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
380 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000381 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000382 // operator (), and the result of such a call has type void. The only
383 // effect is the evaluation of the postfix-expression before the dot or
384 // arrow.
385 CGF.EmitScalarExpr(E->getBase());
386 return 0;
387 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000388
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000389 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000390 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000391 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000392
393 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
394 CGF.EmitCXXThrowExpr(E);
395 return 0;
396 }
397
Sebastian Redl98294de2010-09-10 21:04:00 +0000398 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000399 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000400 }
401
Chris Lattner7f02f722007-08-24 05:35:26 +0000402 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000403 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000404 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000405 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000406 case LangOptions::SOB_Defined:
407 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith9d3e2262012-08-25 00:32:28 +0000408 case LangOptions::SOB_Undefined:
Will Dietz4f45bc02013-01-18 11:30:38 +0000409 if (!CGF.SanOpts->SignedIntegerOverflow)
Richard Smith9d3e2262012-08-25 00:32:28 +0000410 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
411 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +0000412 case LangOptions::SOB_Trapping:
413 return EmitOverflowCheckedBinOp(Ops);
414 }
415 }
Richard Smithd6396a62012-11-05 22:21:05 +0000416
Will Dietz4f45bc02013-01-18 11:30:38 +0000417 if (Ops.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
Will Dietzb8540362012-11-27 15:01:55 +0000418 return EmitOverflowCheckedBinOp(Ops);
419
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000420 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000421 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000422 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
423 }
Mike Stump2add4732009-04-01 20:28:16 +0000424 /// Create a binary op that checks for overflow.
425 /// Currently only supports +, - and *.
426 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith7ac9ef12012-09-08 02:08:36 +0000427
Chris Lattner80230302010-09-11 21:47:09 +0000428 // Check for undefined division and modulus behaviors.
429 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
430 llvm::Value *Zero,bool isDiv);
David Tweed7a834212013-01-07 16:43:27 +0000431 // Common helper for getting how wide LHS of shift is.
432 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
Chris Lattner7f02f722007-08-24 05:35:26 +0000433 Value *EmitDiv(const BinOpInfo &Ops);
434 Value *EmitRem(const BinOpInfo &Ops);
435 Value *EmitAdd(const BinOpInfo &Ops);
436 Value *EmitSub(const BinOpInfo &Ops);
437 Value *EmitShl(const BinOpInfo &Ops);
438 Value *EmitShr(const BinOpInfo &Ops);
439 Value *EmitAnd(const BinOpInfo &Ops) {
440 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
441 }
442 Value *EmitXor(const BinOpInfo &Ops) {
443 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
444 }
445 Value *EmitOr (const BinOpInfo &Ops) {
446 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
447 }
448
Chris Lattner1f1ded92007-08-24 21:00:35 +0000449 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000450 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
451 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000452 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000453
Chris Lattner3ccf7742007-08-26 21:41:21 +0000454 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000455 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
456
457 // Binary operators and binary compound assignment operators.
458#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000459 Value *VisitBin ## OP(const BinaryOperator *E) { \
460 return Emit ## OP(EmitBinOps(E)); \
461 } \
462 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
463 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000464 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000465 HANDLEBINOP(Mul)
466 HANDLEBINOP(Div)
467 HANDLEBINOP(Rem)
468 HANDLEBINOP(Add)
469 HANDLEBINOP(Sub)
470 HANDLEBINOP(Shl)
471 HANDLEBINOP(Shr)
472 HANDLEBINOP(And)
473 HANDLEBINOP(Xor)
474 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000475#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000476
Chris Lattner7f02f722007-08-24 05:35:26 +0000477 // Comparisons.
478 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
479 unsigned SICmpOpc, unsigned FCmpOpc);
480#define VISITCOMP(CODE, UI, SI, FP) \
481 Value *VisitBin##CODE(const BinaryOperator *E) { \
482 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
483 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000484 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
485 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
486 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
487 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
488 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
489 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000490#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000491
Chris Lattner7f02f722007-08-24 05:35:26 +0000492 Value *VisitBinAssign (const BinaryOperator *E);
493
494 Value *VisitBinLAnd (const BinaryOperator *E);
495 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000496 Value *VisitBinComma (const BinaryOperator *E);
497
Eli Friedman25b825d2009-11-18 09:41:26 +0000498 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
499 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
500
Chris Lattner7f02f722007-08-24 05:35:26 +0000501 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000502 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000503 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000504 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000505 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000506 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
507 return CGF.EmitObjCStringLiteral(E);
508 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000509 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
510 return CGF.EmitObjCBoxedExpr(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000511 }
512 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
513 return CGF.EmitObjCArrayLiteral(E);
514 }
515 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
516 return CGF.EmitObjCDictionaryLiteral(E);
517 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000518 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedman276b0612011-10-11 02:20:01 +0000519 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000520};
521} // end anonymous namespace.
522
523//===----------------------------------------------------------------------===//
524// Utilities
525//===----------------------------------------------------------------------===//
526
Chris Lattner9abc84e2007-08-26 16:42:57 +0000527/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000528/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000529Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000530 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000531
John McCalldaa8e4e2010-11-15 09:13:47 +0000532 if (SrcType->isRealFloatingType())
533 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000534
John McCall0bab0cd2010-08-23 01:21:21 +0000535 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
536 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000537
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000538 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000539 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000540
John McCalldaa8e4e2010-11-15 09:13:47 +0000541 if (isa<llvm::IntegerType>(Src->getType()))
542 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000543
John McCalldaa8e4e2010-11-15 09:13:47 +0000544 assert(isa<llvm::PointerType>(Src->getType()));
545 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000546}
547
Richard Smithb2aa66c2012-10-12 22:57:06 +0000548void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
549 QualType OrigSrcType,
550 Value *Src, QualType SrcType,
551 QualType DstType,
552 llvm::Type *DstTy) {
553 using llvm::APFloat;
554 using llvm::APSInt;
555
556 llvm::Type *SrcTy = Src->getType();
557
558 llvm::Value *Check = 0;
559 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
560 // Integer to floating-point. This can fail for unsigned short -> __half
561 // or unsigned __int128 -> float.
562 assert(DstType->isFloatingType());
563 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
564
565 APFloat LargestFloat =
566 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
567 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
568
569 bool IsExact;
570 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
571 &IsExact) != APFloat::opOK)
572 // The range of representable values of this floating point type includes
573 // all values of this integer type. Don't need an overflow check.
574 return;
575
576 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
577 if (SrcIsUnsigned)
578 Check = Builder.CreateICmpULE(Src, Max);
579 else {
580 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
581 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
582 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
583 Check = Builder.CreateAnd(GE, LE);
584 }
585 } else {
586 // Floating-point to integer or floating-point to floating-point. This has
587 // undefined behavior if the source is +-Inf, NaN, or doesn't fit into the
588 // destination type.
589 const llvm::fltSemantics &SrcSema =
590 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
591 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
592 APFloat MinSrc(SrcSema, APFloat::uninitialized);
593
594 if (isa<llvm::IntegerType>(DstTy)) {
595 unsigned Width = CGF.getContext().getIntWidth(DstType);
596 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
597
598 APSInt Min = APSInt::getMinValue(Width, Unsigned);
599 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
600 APFloat::opOverflow)
601 // Don't need an overflow check for lower bound. Just check for
602 // -Inf/NaN.
603 MinSrc = APFloat::getLargest(SrcSema, true);
604
605 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
606 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
607 APFloat::opOverflow)
608 // Don't need an overflow check for upper bound. Just check for
609 // +Inf/NaN.
610 MaxSrc = APFloat::getLargest(SrcSema, false);
611 } else {
612 const llvm::fltSemantics &DstSema =
613 CGF.getContext().getFloatTypeSemantics(DstType);
614 bool IsInexact;
615
616 MinSrc = APFloat::getLargest(DstSema, true);
617 if (MinSrc.convert(SrcSema, APFloat::rmTowardZero, &IsInexact) &
618 APFloat::opOverflow)
619 MinSrc = APFloat::getLargest(SrcSema, true);
620
621 MaxSrc = APFloat::getLargest(DstSema, false);
622 if (MaxSrc.convert(SrcSema, APFloat::rmTowardZero, &IsInexact) &
623 APFloat::opOverflow)
624 MaxSrc = APFloat::getLargest(SrcSema, false);
625 }
626
627 // If we're converting from __half, convert the range to float to match
628 // the type of src.
629 if (OrigSrcType->isHalfType()) {
630 const llvm::fltSemantics &Sema =
631 CGF.getContext().getFloatTypeSemantics(SrcType);
632 bool IsInexact;
633 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
634 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
635 }
636
637 llvm::Value *GE =
638 Builder.CreateFCmpOGE(Src, llvm::ConstantFP::get(VMContext, MinSrc));
639 llvm::Value *LE =
640 Builder.CreateFCmpOLE(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
641 Check = Builder.CreateAnd(GE, LE);
642 }
643
644 // FIXME: Provide a SourceLocation.
645 llvm::Constant *StaticArgs[] = {
646 CGF.EmitCheckTypeDescriptor(OrigSrcType),
647 CGF.EmitCheckTypeDescriptor(DstType)
648 };
Will Dietzad954812012-12-02 19:50:33 +0000649 CGF.EmitCheck(Check, "float_cast_overflow", StaticArgs, OrigSrc,
650 CodeGenFunction::CRK_Recoverable);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000651}
652
Chris Lattner3707b252007-08-26 06:48:56 +0000653/// EmitScalarConversion - Emit a conversion from the specified type to the
654/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000655Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
656 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000657 SrcType = CGF.getContext().getCanonicalType(SrcType);
658 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000659 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000660
Chris Lattnercf289082007-08-26 07:21:11 +0000661 if (DstType->isVoidType()) return 0;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000662
Richard Smithb2aa66c2012-10-12 22:57:06 +0000663 llvm::Value *OrigSrc = Src;
664 QualType OrigSrcType = SrcType;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000665 llvm::Type *SrcTy = Src->getType();
666
667 // Floating casts might be a bit special: if we're doing casts to / from half
668 // FP, we should go via special intrinsics.
669 if (SrcType->isHalfType()) {
670 Src = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16), Src);
671 SrcType = CGF.getContext().FloatTy;
Chris Lattner8b418682012-02-07 00:39:47 +0000672 SrcTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000673 }
674
Chris Lattner3707b252007-08-26 06:48:56 +0000675 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000676 if (DstType->isBooleanType())
677 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000678
Chris Lattner2acc6e32011-07-18 04:24:23 +0000679 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000680
681 // Ignore conversions like int -> uint.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000682 if (SrcTy == DstTy)
Chris Lattner3707b252007-08-26 06:48:56 +0000683 return Src;
684
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000685 // Handle pointer conversions next: pointers can only be converted to/from
686 // other pointers and integers. Check for pointer types in terms of LLVM, as
687 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000688 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000689 // The source value may be an integer, or a pointer.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000690 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3707b252007-08-26 06:48:56 +0000691 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000692
Chris Lattner3707b252007-08-26 06:48:56 +0000693 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000694 // First, convert to the correct width so that we control the kind of
695 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000696 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000697 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000698 llvm::Value* IntResult =
699 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
700 // Then, cast to pointer.
701 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000702 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000703
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000704 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000705 // Must be an ptr to int cast.
706 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000707 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000708 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000709
Nate Begeman213541a2008-04-18 23:10:10 +0000710 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000711 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000712 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000713 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000714 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
715
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000716 // Splat the element across to all elements
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000717 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Benjamin Kramer0b227082013-01-01 20:08:10 +0000718 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000719 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000720
Chris Lattner3b1ae002008-02-02 04:51:41 +0000721 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000722 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000723 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000724 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000725
Chris Lattner3707b252007-08-26 06:48:56 +0000726 // Finally, we have the arithmetic types: real int/float.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000727 Value *Res = NULL;
728 llvm::Type *ResTy = DstTy;
729
Richard Smithb2aa66c2012-10-12 22:57:06 +0000730 // An overflowing conversion has undefined behavior if either the source type
731 // or the destination type is a floating-point type.
Will Dietz4f45bc02013-01-18 11:30:38 +0000732 if (CGF.SanOpts->FloatCastOverflow &&
Richard Smithb2aa66c2012-10-12 22:57:06 +0000733 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
Will Dietz4f45bc02013-01-18 11:30:38 +0000734 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType,
735 DstTy);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000736
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000737 // Cast to half via float
738 if (DstType->isHalfType())
Chris Lattner8b418682012-02-07 00:39:47 +0000739 DstTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000740
741 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000742 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000743 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000744 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000745 else if (InputSigned)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000746 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000747 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000748 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
749 } else if (isa<llvm::IntegerType>(DstTy)) {
750 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor575a1c92011-05-20 16:38:50 +0000751 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000752 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000753 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000754 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
755 } else {
756 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
757 "Unknown real conversion");
758 if (DstTy->getTypeID() < SrcTy->getTypeID())
759 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
760 else
761 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000762 }
763
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000764 if (DstTy != ResTy) {
765 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
766 Res = Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16), Res);
767 }
768
769 return Res;
Chris Lattner3707b252007-08-26 06:48:56 +0000770}
771
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000772/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
773/// type to the specified destination type, where the destination type is an
774/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000775Value *ScalarExprEmitter::
776EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
777 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000778 // Get the source element type.
John McCall183700f2009-09-21 23:43:11 +0000779 SrcTy = SrcTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000780
Chris Lattnered70f0a2007-08-26 16:52:28 +0000781 // Handle conversions to bool first, they are special: comparisons against 0.
782 if (DstTy->isBooleanType()) {
783 // Complex != 0 -> (Real != 0) | (Imag != 0)
784 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
785 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
786 return Builder.CreateOr(Src.first, Src.second, "tobool");
787 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000788
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000789 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
790 // the imaginary part of the complex value is discarded and the value of the
791 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000792 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000793 return EmitScalarConversion(Src.first, SrcTy, DstTy);
794}
795
Anders Carlssona40a9f32010-05-22 17:45:10 +0000796Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
Richard Smith0dbe2fb2012-12-21 03:17:28 +0000797 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
Anders Carlssona40a9f32010-05-22 17:45:10 +0000798}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000799
Richard Smith4def70d2012-10-09 19:52:38 +0000800/// \brief Emit a sanitization check for the given "binary" operation (which
801/// might actually be a unary increment which has been lowered to a binary
802/// operation). The check passes if \p Check, which is an \c i1, is \c true.
803void ScalarExprEmitter::EmitBinOpCheck(Value *Check, const BinOpInfo &Info) {
804 StringRef CheckName;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000805 SmallVector<llvm::Constant *, 4> StaticData;
806 SmallVector<llvm::Value *, 2> DynamicData;
Richard Smith4def70d2012-10-09 19:52:38 +0000807
808 BinaryOperatorKind Opcode = Info.Opcode;
809 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
810 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
811
812 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
813 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
814 if (UO && UO->getOpcode() == UO_Minus) {
815 CheckName = "negate_overflow";
816 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
817 DynamicData.push_back(Info.RHS);
818 } else {
819 if (BinaryOperator::isShiftOp(Opcode)) {
820 // Shift LHS negative or too large, or RHS out of bounds.
821 CheckName = "shift_out_of_bounds";
822 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
823 StaticData.push_back(
824 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
825 StaticData.push_back(
826 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
827 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
828 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
829 CheckName = "divrem_overflow";
Will Dietz822023a2013-01-07 22:25:52 +0000830 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smith4def70d2012-10-09 19:52:38 +0000831 } else {
832 // Signed arithmetic overflow (+, -, *).
833 switch (Opcode) {
834 case BO_Add: CheckName = "add_overflow"; break;
835 case BO_Sub: CheckName = "sub_overflow"; break;
836 case BO_Mul: CheckName = "mul_overflow"; break;
837 default: llvm_unreachable("unexpected opcode for bin op check");
838 }
Will Dietz822023a2013-01-07 22:25:52 +0000839 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smith4def70d2012-10-09 19:52:38 +0000840 }
841 DynamicData.push_back(Info.LHS);
842 DynamicData.push_back(Info.RHS);
843 }
844
Will Dietzad954812012-12-02 19:50:33 +0000845 CGF.EmitCheck(Check, CheckName, StaticData, DynamicData,
846 CodeGenFunction::CRK_Recoverable);
Richard Smith4def70d2012-10-09 19:52:38 +0000847}
848
Chris Lattner7f02f722007-08-24 05:35:26 +0000849//===----------------------------------------------------------------------===//
850// Visitor Methods
851//===----------------------------------------------------------------------===//
852
853Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000854 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000855 if (E->getType()->isVoidType())
856 return 0;
Owen Anderson03e20502009-07-30 23:11:26 +0000857 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000858}
859
Eli Friedmand38617c2008-05-14 19:38:39 +0000860Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000861 // Vector Mask Case
862 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000863 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000864 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
865 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
866 Value *Mask;
Nate Begeman37b6a572010-06-08 00:16:34 +0000867
Chris Lattner2acc6e32011-07-18 04:24:23 +0000868 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000869 unsigned LHSElts = LTy->getNumElements();
870
871 if (E->getNumSubExprs() == 3) {
872 Mask = CGF.EmitScalarExpr(E->getExpr(2));
873
874 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000875 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000876 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000877 concat.push_back(Builder.getInt32(2*i));
878 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000879 }
880
Chris Lattnerfb018d12011-02-15 00:14:06 +0000881 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000882 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
883 LHSElts *= 2;
884 } else {
885 Mask = RHS;
886 }
887
Chris Lattner2acc6e32011-07-18 04:24:23 +0000888 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000889 llvm::Constant* EltMask;
890
891 // Treat vec3 like vec4.
892 if ((LHSElts == 6) && (E->getNumSubExprs() == 3))
893 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
894 (1 << llvm::Log2_32(LHSElts+2))-1);
895 else if ((LHSElts == 3) && (E->getNumSubExprs() == 2))
896 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
897 (1 << llvm::Log2_32(LHSElts+1))-1);
898 else
899 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
900 (1 << llvm::Log2_32(LHSElts))-1);
901
902 // Mask off the high bits of each shuffle index.
Chris Lattner2ce88422012-01-25 05:34:41 +0000903 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
904 EltMask);
Nate Begeman37b6a572010-06-08 00:16:34 +0000905 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
906
907 // newv = undef
908 // mask = mask & maskbits
909 // for each elt
910 // n = extract mask i
911 // x = extract val n
912 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000913 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Nate Begeman37b6a572010-06-08 00:16:34 +0000914 MTy->getNumElements());
915 Value* NewV = llvm::UndefValue::get(RTy);
916 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Eli Friedman87b9c032012-04-05 21:48:40 +0000917 Value *IIndx = Builder.getInt32(i);
918 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Chris Lattner77b89b82010-06-27 07:15:29 +0000919 Indx = Builder.CreateZExt(Indx, CGF.Int32Ty, "idx_zext");
Nate Begeman37b6a572010-06-08 00:16:34 +0000920
921 // Handle vec3 special since the index will be off by one for the RHS.
922 if ((LHSElts == 6) && (E->getNumSubExprs() == 3)) {
923 Value *cmpIndx, *newIndx;
Chris Lattner48431f92011-04-19 22:55:03 +0000924 cmpIndx = Builder.CreateICmpUGT(Indx, Builder.getInt32(3),
Nate Begeman37b6a572010-06-08 00:16:34 +0000925 "cmp_shuf_idx");
Chris Lattner48431f92011-04-19 22:55:03 +0000926 newIndx = Builder.CreateSub(Indx, Builder.getInt32(1), "shuf_idx_adj");
Nate Begeman37b6a572010-06-08 00:16:34 +0000927 Indx = Builder.CreateSelect(cmpIndx, newIndx, Indx, "sel_shuf_idx");
928 }
929 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman87b9c032012-04-05 21:48:40 +0000930 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begeman37b6a572010-06-08 00:16:34 +0000931 }
932 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +0000933 }
Nate Begeman37b6a572010-06-08 00:16:34 +0000934
Eli Friedmand38617c2008-05-14 19:38:39 +0000935 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
936 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000937
938 // Handle vec3 special since the index will be off by one for the RHS.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000939 llvm::VectorType *VTy = cast<llvm::VectorType>(V1->getType());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000940 SmallVector<llvm::Constant*, 32> indices;
Nate Begeman37b6a572010-06-08 00:16:34 +0000941 for (unsigned i = 2; i < E->getNumSubExprs(); i++) {
Eli Friedman0eb47fc2011-05-19 00:37:32 +0000942 unsigned Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
943 if (VTy->getNumElements() == 3 && Idx > 3)
944 Idx -= 1;
945 indices.push_back(Builder.getInt32(Idx));
Nate Begeman37b6a572010-06-08 00:16:34 +0000946 }
947
Chris Lattnerfb018d12011-02-15 00:14:06 +0000948 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +0000949 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
950}
Eli Friedman28665272009-11-26 03:22:21 +0000951Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith80d4b552011-12-28 19:48:30 +0000952 llvm::APSInt Value;
953 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedman28665272009-11-26 03:22:21 +0000954 if (E->isArrow())
955 CGF.EmitScalarExpr(E->getBase());
956 else
957 EmitLValue(E->getBase());
Richard Smith80d4b552011-12-28 19:48:30 +0000958 return Builder.getInt(Value);
Eli Friedman28665272009-11-26 03:22:21 +0000959 }
Devang Patel78ba3d42010-10-04 21:46:04 +0000960
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000961 // Emit debug info for aggregate now, if it was delayed to reduce
Devang Patel78ba3d42010-10-04 21:46:04 +0000962 // debug info size.
963 CGDebugInfo *DI = CGF.getDebugInfo();
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000964 if (DI &&
Douglas Gregor4cdad312012-10-23 20:05:01 +0000965 CGF.CGM.getCodeGenOpts().getDebugInfo()
966 == CodeGenOptions::LimitedDebugInfo) {
Devang Patel78ba3d42010-10-04 21:46:04 +0000967 QualType PQTy = E->getBase()->IgnoreParenImpCasts()->getType();
968 if (const PointerType * PTy = dyn_cast<PointerType>(PQTy))
Devang Patel49c84652010-10-04 22:28:23 +0000969 if (FieldDecl *M = dyn_cast<FieldDecl>(E->getMemberDecl()))
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000970 DI->getOrCreateRecordType(PTy->getPointeeType(),
Devang Patel78ba3d42010-10-04 21:46:04 +0000971 M->getParent()->getLocation());
Devang Patel7fa8ab22010-10-04 22:13:18 +0000972 }
Eli Friedman28665272009-11-26 03:22:21 +0000973 return EmitLoadOfLValue(E);
974}
Eli Friedmand38617c2008-05-14 19:38:39 +0000975
Chris Lattner7f02f722007-08-24 05:35:26 +0000976Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000977 TestAndClearIgnoreResultAssign();
978
Chris Lattner7f02f722007-08-24 05:35:26 +0000979 // Emit subscript expressions in rvalue context's. For most cases, this just
980 // loads the lvalue formed by the subscript expr. However, we have to be
981 // careful, because the base of a vector subscript is occasionally an rvalue,
982 // so we can't get it as an lvalue.
983 if (!E->getBase()->getType()->isVectorType())
984 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000985
Chris Lattner7f02f722007-08-24 05:35:26 +0000986 // Handle the vector case. The base must be a vector, the index must be an
987 // integer value.
988 Value *Base = Visit(E->getBase());
989 Value *Idx = Visit(E->getIdx());
Douglas Gregor575a1c92011-05-20 16:38:50 +0000990 bool IdxSigned = E->getIdx()->getType()->isSignedIntegerOrEnumerationType();
Chris Lattner77b89b82010-06-27 07:15:29 +0000991 Idx = Builder.CreateIntCast(Idx, CGF.Int32Ty, IdxSigned, "vecidxcast");
Chris Lattner7f02f722007-08-24 05:35:26 +0000992 return Builder.CreateExtractElement(Base, Idx, "vecext");
993}
994
Nate Begeman0533b302009-10-18 20:10:40 +0000995static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +0000996 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +0000997 int MV = SVI->getMaskValue(Idx);
998 if (MV == -1)
999 return llvm::UndefValue::get(I32Ty);
1000 return llvm::ConstantInt::get(I32Ty, Off+MV);
1001}
1002
1003Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1004 bool Ignore = TestAndClearIgnoreResultAssign();
1005 (void)Ignore;
1006 assert (Ignore == false && "init list ignored");
1007 unsigned NumInitElements = E->getNumInits();
1008
1009 if (E->hadArrayRangeDesignator())
1010 CGF.ErrorUnsupported(E, "GNU array range designator extension");
1011
Chris Lattner2acc6e32011-07-18 04:24:23 +00001012 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +00001013 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
1014
Sebastian Redlcea8d962011-09-24 17:48:14 +00001015 if (!VType) {
1016 if (NumInitElements == 0) {
1017 // C++11 value-initialization for the scalar.
1018 return EmitNullValue(E->getType());
1019 }
1020 // We have a scalar in braces. Just use the first element.
Nate Begeman0533b302009-10-18 20:10:40 +00001021 return Visit(E->getInit(0));
Sebastian Redlcea8d962011-09-24 17:48:14 +00001022 }
Nate Begeman0533b302009-10-18 20:10:40 +00001023
1024 unsigned ResElts = VType->getNumElements();
Nate Begeman0533b302009-10-18 20:10:40 +00001025
1026 // Loop over initializers collecting the Value for each, and remembering
1027 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1028 // us to fold the shuffle for the swizzle into the shuffle for the vector
1029 // initializer, since LLVM optimizers generally do not want to touch
1030 // shuffles.
1031 unsigned CurIdx = 0;
1032 bool VIsUndefShuffle = false;
1033 llvm::Value *V = llvm::UndefValue::get(VType);
1034 for (unsigned i = 0; i != NumInitElements; ++i) {
1035 Expr *IE = E->getInit(i);
1036 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001037 SmallVector<llvm::Constant*, 16> Args;
Nate Begeman0533b302009-10-18 20:10:40 +00001038
Chris Lattner2acc6e32011-07-18 04:24:23 +00001039 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Nate Begeman0533b302009-10-18 20:10:40 +00001040
1041 // Handle scalar elements. If the scalar initializer is actually one
1042 // element of a different vector of the same width, use shuffle instead of
1043 // extract+insert.
1044 if (!VVT) {
1045 if (isa<ExtVectorElementExpr>(IE)) {
1046 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1047
1048 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1049 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
1050 Value *LHS = 0, *RHS = 0;
1051 if (CurIdx == 0) {
1052 // insert into undef -> shuffle (src, undef)
1053 Args.push_back(C);
Benjamin Kramer14c59822012-02-14 12:06:21 +00001054 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001055
1056 LHS = EI->getVectorOperand();
1057 RHS = V;
1058 VIsUndefShuffle = true;
1059 } else if (VIsUndefShuffle) {
1060 // insert into undefshuffle && size match -> shuffle (v, src)
1061 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1062 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +00001063 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +00001064 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001065 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1066
Nate Begeman0533b302009-10-18 20:10:40 +00001067 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1068 RHS = EI->getVectorOperand();
1069 VIsUndefShuffle = false;
1070 }
1071 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +00001072 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001073 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1074 ++CurIdx;
1075 continue;
1076 }
1077 }
1078 }
Chris Lattner48431f92011-04-19 22:55:03 +00001079 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1080 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +00001081 VIsUndefShuffle = false;
1082 ++CurIdx;
1083 continue;
1084 }
1085
1086 unsigned InitElts = VVT->getNumElements();
1087
1088 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
1089 // input is the same width as the vector being constructed, generate an
1090 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +00001091 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +00001092 if (isa<ExtVectorElementExpr>(IE)) {
1093 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1094 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001095 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Nate Begeman0533b302009-10-18 20:10:40 +00001096
1097 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +00001098 for (unsigned j = 0; j != CurIdx; ++j) {
1099 // If the current vector initializer is a shuffle with undef, merge
1100 // this shuffle directly into it.
1101 if (VIsUndefShuffle) {
1102 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +00001103 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001104 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001105 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +00001106 }
1107 }
1108 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +00001109 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001110 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001111
1112 if (VIsUndefShuffle)
1113 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1114
1115 Init = SVOp;
1116 }
1117 }
1118
1119 // Extend init to result vector length, and then shuffle its contribution
1120 // to the vector initializer into V.
1121 if (Args.empty()) {
1122 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001123 Args.push_back(Builder.getInt32(j));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001124 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +00001125 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001126 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +00001127 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +00001128
1129 Args.clear();
1130 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001131 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +00001132 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001133 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001134 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001135 }
1136
1137 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1138 // merging subsequent shuffles into this one.
1139 if (CurIdx == 0)
1140 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +00001141 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001142 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1143 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1144 CurIdx += InitElts;
1145 }
1146
1147 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1148 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001149 llvm::Type *EltTy = VType->getElementType();
Nate Begeman0533b302009-10-18 20:10:40 +00001150
1151 // Emit remaining default initializers
1152 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +00001153 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +00001154 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1155 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1156 }
1157 return V;
1158}
1159
Anders Carlssona3697c92009-11-23 17:57:54 +00001160static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1161 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +00001162
John McCall2de56d12010-08-25 11:45:40 +00001163 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +00001164 return false;
Anders Carlssona3697c92009-11-23 17:57:54 +00001165
1166 if (isa<CXXThisExpr>(E)) {
1167 // We always assume that 'this' is never null.
1168 return false;
1169 }
1170
1171 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00001172 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +00001173 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +00001174 return false;
1175 }
1176
1177 return true;
1178}
1179
Chris Lattner7f02f722007-08-24 05:35:26 +00001180// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1181// have to handle a more broad range of conversions than explicit casts, as they
1182// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001183Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001184 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001185 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001186 CastKind Kind = CE->getCastKind();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001187
Mike Stump7f79f9b2009-05-29 15:46:01 +00001188 if (!DestTy->isVoidType())
1189 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001190
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001191 // Since almost all cast kinds apply to scalars, this switch doesn't have
1192 // a default case, so the compiler will warn on a missing case. The cases
1193 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001194 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001195 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001196 case CK_BuiltinFnToFnPtr:
1197 llvm_unreachable("builtin functions are handled elsewhere");
1198
John McCall2de56d12010-08-25 11:45:40 +00001199 case CK_LValueBitCast:
1200 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001201 Value *V = EmitLValue(E).getAddress();
1202 V = Builder.CreateBitCast(V,
1203 ConvertType(CGF.getContext().getPointerType(DestTy)));
Eli Friedmand71f4422011-12-19 23:03:09 +00001204 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy));
Douglas Gregore39a3892010-07-13 23:17:26 +00001205 }
John McCalldc05b112011-09-10 01:16:55 +00001206
John McCall1d9b3b22011-09-09 05:25:32 +00001207 case CK_CPointerToObjCPointerCast:
1208 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001209 case CK_AnyPointerToBlockPointerCast:
1210 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001211 Value *Src = Visit(const_cast<Expr*>(E));
1212 return Builder.CreateBitCast(Src, ConvertType(DestTy));
1213 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001214 case CK_AtomicToNonAtomic:
1215 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +00001216 case CK_NoOp:
1217 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001218 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001219
John McCall2de56d12010-08-25 11:45:40 +00001220 case CK_BaseToDerived: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001221 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1222 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1223
1224 return CGF.GetAddressOfDerivedClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001225 CE->path_begin(), CE->path_end(),
Anders Carlssona04efdf2010-04-24 21:23:59 +00001226 ShouldNullCheckClassCastValue(CE));
Anders Carlssona3697c92009-11-23 17:57:54 +00001227 }
John McCall2de56d12010-08-25 11:45:40 +00001228 case CK_UncheckedDerivedToBase:
1229 case CK_DerivedToBase: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001230 const CXXRecordDecl *DerivedClassDecl =
1231 E->getType()->getPointeeCXXRecordDecl();
1232 assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
Anders Carlsson191dfe92009-09-12 04:57:16 +00001233
Anders Carlsson34a2d382010-04-24 21:06:20 +00001234 return CGF.GetAddressOfBaseClass(Visit(E), DerivedClassDecl,
John McCallf871d0c2010-08-07 06:22:56 +00001235 CE->path_begin(), CE->path_end(),
Anders Carlsson34a2d382010-04-24 21:06:20 +00001236 ShouldNullCheckClassCastValue(CE));
Anders Carlsson191dfe92009-09-12 04:57:16 +00001237 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001238 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001239 Value *V = Visit(const_cast<Expr*>(E));
1240 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1241 return CGF.EmitDynamicCast(V, DCE);
1242 }
Eli Friedmand8889622009-11-27 04:41:50 +00001243
John McCall2de56d12010-08-25 11:45:40 +00001244 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001245 assert(E->getType()->isArrayType() &&
1246 "Array to pointer decay must have array source type!");
1247
1248 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1249
1250 // Note that VLA pointers are always decayed, so we don't need to do
1251 // anything here.
1252 if (!E->getType()->isVariableArrayType()) {
1253 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
1254 assert(isa<llvm::ArrayType>(cast<llvm::PointerType>(V->getType())
1255 ->getElementType()) &&
1256 "Expected pointer to array");
1257 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1258 }
1259
Chris Lattner410b12e2011-07-20 04:31:01 +00001260 // Make sure the array decay ends up being the right type. This matters if
1261 // the array type was of an incomplete type.
Chris Lattnercb8095f2011-07-20 04:59:57 +00001262 return CGF.Builder.CreateBitCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001263 }
John McCall2de56d12010-08-25 11:45:40 +00001264 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001265 return EmitLValue(E).getAddress();
1266
John McCall404cd162010-11-13 01:35:44 +00001267 case CK_NullToPointer:
1268 if (MustVisitNullValue(E))
1269 (void) Visit(E);
1270
1271 return llvm::ConstantPointerNull::get(
1272 cast<llvm::PointerType>(ConvertType(DestTy)));
1273
John McCall2de56d12010-08-25 11:45:40 +00001274 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001275 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001276 (void) Visit(E);
1277
John McCall0bab0cd2010-08-23 01:21:21 +00001278 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1279 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1280 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001281
John McCall4d4e5c12012-02-15 01:22:51 +00001282 case CK_ReinterpretMemberPointer:
John McCall2de56d12010-08-25 11:45:40 +00001283 case CK_BaseToDerivedMemberPointer:
1284 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001285 Value *Src = Visit(E);
John McCalld608cdb2010-08-22 10:59:02 +00001286
1287 // Note that the AST doesn't distinguish between checked and
1288 // unchecked member pointer conversions, so we always have to
1289 // implement checked conversions here. This is inefficient when
1290 // actual control flow may be required in order to perform the
1291 // check, which it is for data member pointers (but not member
1292 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001293 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001294 }
John McCallf85e1932011-06-15 23:02:42 +00001295
John McCall33e56f32011-09-10 06:18:15 +00001296 case CK_ARCProduceObject:
John McCallf85e1932011-06-15 23:02:42 +00001297 return CGF.EmitARCRetainScalarExpr(E);
John McCall33e56f32011-09-10 06:18:15 +00001298 case CK_ARCConsumeObject:
John McCallf85e1932011-06-15 23:02:42 +00001299 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall33e56f32011-09-10 06:18:15 +00001300 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00001301 llvm::Value *value = Visit(E);
1302 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1303 return CGF.EmitObjCConsumeObject(E->getType(), value);
1304 }
John McCall348f16f2011-10-04 06:23:45 +00001305 case CK_ARCExtendBlockObject:
1306 return CGF.EmitARCExtendBlockObject(E);
John McCallf85e1932011-06-15 23:02:42 +00001307
Douglas Gregorac1303e2012-02-22 05:02:47 +00001308 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmancae40c42012-02-28 01:08:45 +00001309 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Douglas Gregorac1303e2012-02-22 05:02:47 +00001310
John McCall2bb5d002010-11-13 09:02:35 +00001311 case CK_FloatingRealToComplex:
1312 case CK_FloatingComplexCast:
1313 case CK_IntegralRealToComplex:
1314 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001315 case CK_IntegralComplexToFloatingComplex:
1316 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001317 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001318 case CK_ToUnion:
1319 llvm_unreachable("scalar cast to non-scalar value");
John McCallf6a16482010-12-04 03:47:34 +00001320
John McCall0ae287a2010-12-01 04:43:34 +00001321 case CK_LValueToRValue:
1322 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001323 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001324 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001325
John McCall2de56d12010-08-25 11:45:40 +00001326 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001327 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001328
Anders Carlsson82debc72009-10-18 18:12:03 +00001329 // First, convert to the correct width so that we control the kind of
1330 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001331 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001332 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001333 llvm::Value* IntResult =
1334 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001335
Anders Carlsson82debc72009-10-18 18:12:03 +00001336 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001337 }
Eli Friedman65949422011-06-25 02:58:47 +00001338 case CK_PointerToIntegral:
1339 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1340 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001341
John McCall2de56d12010-08-25 11:45:40 +00001342 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001343 CGF.EmitIgnoredExpr(E);
Eli Friedmanad35a832009-11-16 21:33:53 +00001344 return 0;
1345 }
John McCall2de56d12010-08-25 11:45:40 +00001346 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001347 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001348 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5fa56082012-02-06 05:05:50 +00001349 Elt = EmitScalarConversion(Elt, E->getType(),
1350 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanad35a832009-11-16 21:33:53 +00001351
Eli Friedmanad35a832009-11-16 21:33:53 +00001352 // Splat the element across to all elements
Eli Friedmanad35a832009-11-16 21:33:53 +00001353 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Benjamin Kramer0b227082013-01-01 20:08:10 +00001354 return Builder.CreateVectorSplat(NumElements, Elt, "splat");;
Eli Friedmanad35a832009-11-16 21:33:53 +00001355 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001356
John McCall2de56d12010-08-25 11:45:40 +00001357 case CK_IntegralCast:
1358 case CK_IntegralToFloating:
1359 case CK_FloatingToIntegral:
1360 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001361 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCalldaa8e4e2010-11-15 09:13:47 +00001362 case CK_IntegralToBoolean:
1363 return EmitIntToBoolConversion(Visit(E));
1364 case CK_PointerToBoolean:
1365 return EmitPointerToBoolConversion(Visit(E));
1366 case CK_FloatingToBoolean:
1367 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001368 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001369 llvm::Value *MemPtr = Visit(E);
1370 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1371 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001372 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001373
1374 case CK_FloatingComplexToReal:
1375 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001376 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001377
1378 case CK_FloatingComplexToBoolean:
1379 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001380 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001381
1382 // TODO: kill this function off, inline appropriate case here
1383 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1384 }
1385
Guy Benyeie6b9d802013-01-20 12:31:11 +00001386 case CK_ZeroToOCLEvent: {
1387 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non event type");
1388 return llvm::Constant::getNullValue(ConvertType(DestTy));
1389 }
1390
John McCall0bab0cd2010-08-23 01:21:21 +00001391 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001392
John McCall61ad0e62010-11-16 06:21:14 +00001393 llvm_unreachable("unknown scalar cast");
Chris Lattner7f02f722007-08-24 05:35:26 +00001394}
1395
Chris Lattner33793202007-08-31 22:09:40 +00001396Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001397 CodeGenFunction::StmtExprEvaluation eval(CGF);
1398 return CGF.EmitCompoundStmt(*E->getSubStmt(), !E->getType()->isVoidType())
1399 .getScalarVal();
Chris Lattner33793202007-08-31 22:09:40 +00001400}
1401
Chris Lattner7f02f722007-08-24 05:35:26 +00001402//===----------------------------------------------------------------------===//
1403// Unary Operators
1404//===----------------------------------------------------------------------===//
1405
Chris Lattner8c11a652010-06-26 22:09:34 +00001406llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001407EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1408 llvm::Value *InVal,
1409 llvm::Value *NextVal, bool IsInc) {
Richard Smith7edf9e32012-11-01 22:30:59 +00001410 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00001411 case LangOptions::SOB_Defined:
1412 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Richard Smith9d3e2262012-08-25 00:32:28 +00001413 case LangOptions::SOB_Undefined:
Will Dietz4f45bc02013-01-18 11:30:38 +00001414 if (!CGF.SanOpts->SignedIntegerOverflow)
Richard Smith9d3e2262012-08-25 00:32:28 +00001415 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1416 // Fall through.
Anton Yartsev683564a2011-02-07 02:17:30 +00001417 case LangOptions::SOB_Trapping:
1418 BinOpInfo BinOp;
1419 BinOp.LHS = InVal;
1420 BinOp.RHS = NextVal;
1421 BinOp.Ty = E->getType();
1422 BinOp.Opcode = BO_Add;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001423 BinOp.FPContractable = false;
Anton Yartsev683564a2011-02-07 02:17:30 +00001424 BinOp.E = E;
1425 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev683564a2011-02-07 02:17:30 +00001426 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001427 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev683564a2011-02-07 02:17:30 +00001428}
1429
John McCall5936e332011-02-15 09:22:45 +00001430llvm::Value *
1431ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1432 bool isInc, bool isPre) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001433
John McCall5936e332011-02-15 09:22:45 +00001434 QualType type = E->getSubExpr()->getType();
John McCall545d9962011-06-25 02:11:03 +00001435 llvm::Value *value = EmitLoadOfLValue(LV);
John McCall5936e332011-02-15 09:22:45 +00001436 llvm::Value *input = value;
David Chisnall7a7ee302012-01-16 17:27:18 +00001437 llvm::PHINode *atomicPHI = 0;
Anton Yartsev683564a2011-02-07 02:17:30 +00001438
John McCall5936e332011-02-15 09:22:45 +00001439 int amount = (isInc ? 1 : -1);
1440
David Chisnall7a7ee302012-01-16 17:27:18 +00001441 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
1442 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1443 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1444 Builder.CreateBr(opBB);
1445 Builder.SetInsertPoint(opBB);
1446 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1447 atomicPHI->addIncoming(value, startBB);
1448 type = atomicTy->getValueType();
1449 value = atomicPHI;
1450 }
1451
John McCall5936e332011-02-15 09:22:45 +00001452 // Special case of integer increment that we have to check first: bool++.
1453 // Due to promotion rules, we get:
1454 // bool++ -> bool = bool + 1
1455 // -> bool = (int)bool + 1
1456 // -> bool = ((int)bool + 1 != 0)
1457 // An interesting aspect of this is that increment is always true.
1458 // Decrement does not have this property.
1459 if (isInc && type->isBooleanType()) {
1460 value = Builder.getTrue();
1461
1462 // Most common case by far: integer increment.
1463 } else if (type->isIntegerType()) {
1464
Michael Liao36d5cea2012-08-28 16:55:13 +00001465 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCall5936e332011-02-15 09:22:45 +00001466
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001467 // Note that signed integer inc/dec with width less than int can't
1468 // overflow because of promotion rules; we're just eliding a few steps here.
Will Dietzb8540362012-11-27 15:01:55 +00001469 if (value->getType()->getPrimitiveSizeInBits() >=
1470 CGF.IntTy->getBitWidth() &&
1471 type->isSignedIntegerOrEnumerationType()) {
John McCall5936e332011-02-15 09:22:45 +00001472 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
Will Dietzb8540362012-11-27 15:01:55 +00001473 } else if (value->getType()->getPrimitiveSizeInBits() >=
Will Dietz4f45bc02013-01-18 11:30:38 +00001474 CGF.IntTy->getBitWidth() && type->isUnsignedIntegerType() &&
1475 CGF.SanOpts->UnsignedIntegerOverflow) {
Will Dietzb8540362012-11-27 15:01:55 +00001476 BinOpInfo BinOp;
1477 BinOp.LHS = value;
1478 BinOp.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
1479 BinOp.Ty = E->getType();
1480 BinOp.Opcode = isInc ? BO_Add : BO_Sub;
1481 BinOp.FPContractable = false;
1482 BinOp.E = E;
1483 value = EmitOverflowCheckedBinOp(BinOp);
1484 } else
John McCall5936e332011-02-15 09:22:45 +00001485 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
1486
1487 // Next most common: pointer increment.
1488 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1489 QualType type = ptr->getPointeeType();
1490
1491 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001492 if (const VariableArrayType *vla
1493 = CGF.getContext().getAsVariableArrayType(type)) {
1494 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001495 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Richard Smith7edf9e32012-11-01 22:30:59 +00001496 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001497 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001498 else
John McCallbc8d40d2011-06-24 21:55:10 +00001499 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
John McCall5936e332011-02-15 09:22:45 +00001500
1501 // Arithmetic on function pointers (!) is just +-1.
1502 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001503 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001504
1505 value = CGF.EmitCastToVoidPtr(value);
Richard Smith7edf9e32012-11-01 22:30:59 +00001506 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001507 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1508 else
1509 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001510 value = Builder.CreateBitCast(value, input->getType());
1511
1512 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001513 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001514 llvm::Value *amt = Builder.getInt32(amount);
Richard Smith7edf9e32012-11-01 22:30:59 +00001515 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001516 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1517 else
1518 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001519 }
1520
1521 // Vector increment/decrement.
1522 } else if (type->isVectorType()) {
1523 if (type->hasIntegerRepresentation()) {
1524 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1525
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001526 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001527 } else {
1528 value = Builder.CreateFAdd(
1529 value,
1530 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001531 isInc ? "inc" : "dec");
1532 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001533
John McCall5936e332011-02-15 09:22:45 +00001534 // Floating point.
1535 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001536 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001537 llvm::Value *amt;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001538
1539 if (type->isHalfType()) {
1540 // Another special case: half FP increment should be done via float
1541 value =
1542 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16),
1543 input);
1544 }
1545
John McCall5936e332011-02-15 09:22:45 +00001546 if (value->getType()->isFloatTy())
1547 amt = llvm::ConstantFP::get(VMContext,
1548 llvm::APFloat(static_cast<float>(amount)));
1549 else if (value->getType()->isDoubleTy())
1550 amt = llvm::ConstantFP::get(VMContext,
1551 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001552 else {
John McCall5936e332011-02-15 09:22:45 +00001553 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001554 bool ignored;
1555 F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
1556 &ignored);
John McCall5936e332011-02-15 09:22:45 +00001557 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001558 }
John McCall5936e332011-02-15 09:22:45 +00001559 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1560
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001561 if (type->isHalfType())
1562 value =
1563 Builder.CreateCall(CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16),
1564 value);
1565
John McCall5936e332011-02-15 09:22:45 +00001566 // Objective-C pointer types.
1567 } else {
1568 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1569 value = CGF.EmitCastToVoidPtr(value);
1570
1571 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1572 if (!isInc) size = -size;
1573 llvm::Value *sizeValue =
1574 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1575
Richard Smith7edf9e32012-11-01 22:30:59 +00001576 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001577 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1578 else
1579 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001580 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001581 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001582
1583 if (atomicPHI) {
1584 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1585 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1586 llvm::Value *old = Builder.CreateAtomicCmpXchg(LV.getAddress(), atomicPHI,
1587 value, llvm::SequentiallyConsistent);
1588 atomicPHI->addIncoming(old, opBB);
1589 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1590 Builder.CreateCondBr(success, contBB, opBB);
1591 Builder.SetInsertPoint(contBB);
1592 return isPre ? value : input;
1593 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001594
Chris Lattner8c11a652010-06-26 22:09:34 +00001595 // Store the updated result through the lvalue.
1596 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001597 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001598 else
John McCall545d9962011-06-25 02:11:03 +00001599 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001600
Chris Lattner8c11a652010-06-26 22:09:34 +00001601 // If this is a postinc, return the value read from memory, otherwise use the
1602 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001603 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001604}
1605
1606
1607
Chris Lattner7f02f722007-08-24 05:35:26 +00001608Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001609 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001610 // Emit unary minus with EmitSub so we handle overflow cases etc.
1611 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001612 BinOp.RHS = Visit(E->getSubExpr());
1613
1614 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1615 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
1616 else
1617 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001618 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001619 BinOp.Opcode = BO_Sub;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001620 BinOp.FPContractable = false;
Chris Lattner9a207232010-06-26 21:48:21 +00001621 BinOp.E = E;
1622 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001623}
1624
1625Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001626 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001627 Value *Op = Visit(E->getSubExpr());
1628 return Builder.CreateNot(Op, "neg");
1629}
1630
1631Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00001632
1633 // Perform vector logical not on comparison with zero vector.
1634 if (E->getType()->isExtVectorType()) {
1635 Value *Oper = Visit(E->getSubExpr());
1636 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
1637 Value *Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
1638 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1639 }
1640
Chris Lattner7f02f722007-08-24 05:35:26 +00001641 // Compare operand to zero.
1642 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001643
Chris Lattner7f02f722007-08-24 05:35:26 +00001644 // Invert value.
1645 // TODO: Could dynamically modify easy computations here. For example, if
1646 // the operand is an icmp ne, turn into icmp eq.
1647 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001648
Anders Carlsson9f84d882009-05-19 18:44:53 +00001649 // ZExt result to the expr type.
1650 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001651}
1652
Eli Friedman0027d2b2010-08-05 09:58:49 +00001653Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1654 // Try folding the offsetof to a constant.
Richard Smith80d4b552011-12-28 19:48:30 +00001655 llvm::APSInt Value;
1656 if (E->EvaluateAsInt(Value, CGF.getContext()))
1657 return Builder.getInt(Value);
Eli Friedman0027d2b2010-08-05 09:58:49 +00001658
1659 // Loop over the components of the offsetof to compute the value.
1660 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001661 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001662 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1663 QualType CurrentType = E->getTypeSourceInfo()->getType();
1664 for (unsigned i = 0; i != n; ++i) {
1665 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Eli Friedman16fd39f2010-08-06 16:37:05 +00001666 llvm::Value *Offset = 0;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001667 switch (ON.getKind()) {
1668 case OffsetOfExpr::OffsetOfNode::Array: {
1669 // Compute the index
1670 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1671 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001672 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001673 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1674
1675 // Save the element type
1676 CurrentType =
1677 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1678
1679 // Compute the element size
1680 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1681 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1682
1683 // Multiply out to compute the result
1684 Offset = Builder.CreateMul(Idx, ElemSize);
1685 break;
1686 }
1687
1688 case OffsetOfExpr::OffsetOfNode::Field: {
1689 FieldDecl *MemberDecl = ON.getField();
1690 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1691 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1692
1693 // Compute the index of the field in its parent.
1694 unsigned i = 0;
1695 // FIXME: It would be nice if we didn't have to loop here!
1696 for (RecordDecl::field_iterator Field = RD->field_begin(),
1697 FieldEnd = RD->field_end();
David Blaikie262bc182012-04-30 02:36:29 +00001698 Field != FieldEnd; ++Field, ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00001699 if (*Field == MemberDecl)
Eli Friedman0027d2b2010-08-05 09:58:49 +00001700 break;
1701 }
1702 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1703
1704 // Compute the offset to the field
1705 int64_t OffsetInt = RL.getFieldOffset(i) /
1706 CGF.getContext().getCharWidth();
1707 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1708
1709 // Save the element type.
1710 CurrentType = MemberDecl->getType();
1711 break;
1712 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001713
Eli Friedman0027d2b2010-08-05 09:58:49 +00001714 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001715 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001716
Eli Friedman0027d2b2010-08-05 09:58:49 +00001717 case OffsetOfExpr::OffsetOfNode::Base: {
1718 if (ON.getBase()->isVirtual()) {
1719 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1720 continue;
1721 }
1722
1723 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1724 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1725
1726 // Save the element type.
1727 CurrentType = ON.getBase()->getType();
1728
1729 // Compute the offset to the base.
1730 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1731 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001732 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1733 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001734 break;
1735 }
1736 }
1737 Result = Builder.CreateAdd(Result, Offset);
1738 }
1739 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001740}
1741
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001742/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001743/// argument of the sizeof expression as an integer.
1744Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001745ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1746 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001747 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001748 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001749 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001750 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1751 if (E->isArgumentType()) {
1752 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001753 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001754 } else {
1755 // C99 6.5.3.4p2: If the argument is an expression of type
1756 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001757 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001758 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001759
John McCallbc8d40d2011-06-24 21:55:10 +00001760 QualType eltType;
1761 llvm::Value *numElts;
1762 llvm::tie(numElts, eltType) = CGF.getVLASize(VAT);
1763
1764 llvm::Value *size = numElts;
1765
1766 // Scale the number of non-VLA elements by the non-VLA element size.
1767 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1768 if (!eltSize.isOne())
1769 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1770
1771 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001772 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001773 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001774
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001775 // If this isn't sizeof(vla), the result must be constant; use the constant
1776 // folding logic so we don't have to duplicate it here.
Richard Smith80d4b552011-12-28 19:48:30 +00001777 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001778}
1779
Chris Lattner46f93d02007-08-24 21:20:17 +00001780Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1781 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001782 if (Op->getType()->isAnyComplexType()) {
1783 // If it's an l-value, load through the appropriate subobject l-value.
1784 // Note that we have to ask E because Op might be an l-value that
1785 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001786 if (E->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001787 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001788
1789 // Otherwise, calculate and project.
1790 return CGF.EmitComplexExpr(Op, false, true).first;
1791 }
1792
Chris Lattner46f93d02007-08-24 21:20:17 +00001793 return Visit(Op);
1794}
John McCallb418d742010-11-16 10:08:07 +00001795
Chris Lattner46f93d02007-08-24 21:20:17 +00001796Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
1797 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001798 if (Op->getType()->isAnyComplexType()) {
1799 // If it's an l-value, load through the appropriate subobject l-value.
1800 // Note that we have to ask E because Op might be an l-value that
1801 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00001802 if (Op->isGLValue())
John McCall545d9962011-06-25 02:11:03 +00001803 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E)).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00001804
1805 // Otherwise, calculate and project.
1806 return CGF.EmitComplexExpr(Op, true, false).second;
1807 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001808
Mike Stump7f79f9b2009-05-29 15:46:01 +00001809 // __imag on a scalar returns zero. Emit the subexpr to ensure side
1810 // effects are evaluated, but not the actual value.
Richard Smithdfb80de2012-02-18 20:53:32 +00001811 if (Op->isGLValue())
1812 CGF.EmitLValue(Op);
1813 else
1814 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00001815 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00001816}
1817
Chris Lattner7f02f722007-08-24 05:35:26 +00001818//===----------------------------------------------------------------------===//
1819// Binary Operators
1820//===----------------------------------------------------------------------===//
1821
1822BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001823 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001824 BinOpInfo Result;
1825 Result.LHS = Visit(E->getLHS());
1826 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00001827 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00001828 Result.Opcode = E->getOpcode();
Lang Hamesbe9af122012-10-02 04:45:10 +00001829 Result.FPContractable = E->isFPContractable();
Chris Lattner7f02f722007-08-24 05:35:26 +00001830 Result.E = E;
1831 return Result;
1832}
1833
Douglas Gregor6a03e342010-04-23 04:16:32 +00001834LValue ScalarExprEmitter::EmitCompoundAssignLValue(
1835 const CompoundAssignOperator *E,
1836 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001837 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00001838 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00001839 BinOpInfo OpInfo;
Douglas Gregor6a03e342010-04-23 04:16:32 +00001840
Eli Friedmanab3a8522009-03-28 01:22:36 +00001841 if (E->getComputationResultType()->isAnyComplexType()) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001842 // This needs to go through the complex expression emitter, but it's a tad
1843 // complicated to do that... I'm leaving it out for now. (Note that we do
1844 // actually need the imaginary part of the RHS for multiplication and
1845 // division.)
Eli Friedmanab3a8522009-03-28 01:22:36 +00001846 CGF.ErrorUnsupported(E, "complex compound assignment");
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001847 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Douglas Gregor6a03e342010-04-23 04:16:32 +00001848 return LValue();
Eli Friedmanab3a8522009-03-28 01:22:36 +00001849 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001850
Mike Stumpcc0442f2009-05-22 19:07:20 +00001851 // Emit the RHS first. __block variables need to have the rhs evaluated
1852 // first, plus this should improve codegen a little.
1853 OpInfo.RHS = Visit(E->getRHS());
1854 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00001855 OpInfo.Opcode = E->getOpcode();
Benjamin Kramerddc57332012-10-03 20:58:04 +00001856 OpInfo.FPContractable = false;
Mike Stumpcc0442f2009-05-22 19:07:20 +00001857 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00001858 // Load/convert the LHS.
Richard Smith7ac9ef12012-09-08 02:08:36 +00001859 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall545d9962011-06-25 02:11:03 +00001860 OpInfo.LHS = EmitLoadOfLValue(LHSLV);
David Chisnall7a7ee302012-01-16 17:27:18 +00001861
1862 llvm::PHINode *atomicPHI = 0;
Eli Friedman860a3192012-06-16 02:19:17 +00001863 if (LHSTy->isAtomicType()) {
David Chisnall7a7ee302012-01-16 17:27:18 +00001864 // FIXME: For floating point types, we should be saving and restoring the
1865 // floating point environment in the loop.
1866 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1867 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
1868 Builder.CreateBr(opBB);
1869 Builder.SetInsertPoint(opBB);
1870 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
1871 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00001872 OpInfo.LHS = atomicPHI;
1873 }
Eli Friedman860a3192012-06-16 02:19:17 +00001874
1875 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
1876 E->getComputationLHSType());
1877
Chris Lattner1f1ded92007-08-24 21:00:35 +00001878 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001879 Result = (this->*Func)(OpInfo);
Douglas Gregor6a03e342010-04-23 04:16:32 +00001880
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00001881 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00001882 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnall7a7ee302012-01-16 17:27:18 +00001883
1884 if (atomicPHI) {
1885 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1886 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
1887 llvm::Value *old = Builder.CreateAtomicCmpXchg(LHSLV.getAddress(), atomicPHI,
1888 Result, llvm::SequentiallyConsistent);
1889 atomicPHI->addIncoming(old, opBB);
1890 llvm::Value *success = Builder.CreateICmpEQ(old, atomicPHI);
1891 Builder.CreateCondBr(success, contBB, opBB);
1892 Builder.SetInsertPoint(contBB);
1893 return LHSLV;
1894 }
Douglas Gregor6a03e342010-04-23 04:16:32 +00001895
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001896 // Store the result value into the LHS lvalue. Bit-fields are handled
1897 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
1898 // 'An assignment expression has the value of the left operand after the
1899 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001900 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001901 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001902 else
John McCall545d9962011-06-25 02:11:03 +00001903 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001904
Douglas Gregor6a03e342010-04-23 04:16:32 +00001905 return LHSLV;
1906}
1907
1908Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
1909 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
1910 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001911 Value *RHS;
1912 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
1913
1914 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00001915 if (Ignore)
1916 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001917
John McCallb418d742010-11-16 10:08:07 +00001918 // The result of an assignment in C is the assigned r-value.
Richard Smith7edf9e32012-11-01 22:30:59 +00001919 if (!CGF.getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00001920 return RHS;
1921
Daniel Dunbard7f7d082010-06-29 22:00:45 +00001922 // If the lvalue is non-volatile, return the computed value of the assignment.
1923 if (!LHS.isVolatileQualified())
1924 return RHS;
1925
1926 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00001927 return EmitLoadOfLValue(LHS);
Chris Lattner1f1ded92007-08-24 21:00:35 +00001928}
1929
Chris Lattner80230302010-09-11 21:47:09 +00001930void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith7ac9ef12012-09-08 02:08:36 +00001931 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Richard Smithc54e25f2012-11-06 02:30:30 +00001932 llvm::Value *Cond = 0;
Chris Lattner80230302010-09-11 21:47:09 +00001933
Will Dietz4f45bc02013-01-18 11:30:38 +00001934 if (CGF.SanOpts->IntegerDivideByZero)
Richard Smithc54e25f2012-11-06 02:30:30 +00001935 Cond = Builder.CreateICmpNE(Ops.RHS, Zero);
1936
Will Dietz4f45bc02013-01-18 11:30:38 +00001937 if (CGF.SanOpts->SignedIntegerOverflow &&
Richard Smithc54e25f2012-11-06 02:30:30 +00001938 Ops.Ty->hasSignedIntegerRepresentation()) {
1939 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
1940
Chris Lattner80230302010-09-11 21:47:09 +00001941 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00001942 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00001943 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
1944
Richard Smith7ac9ef12012-09-08 02:08:36 +00001945 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
1946 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
Richard Smithc54e25f2012-11-06 02:30:30 +00001947 llvm::Value *Overflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
1948 Cond = Cond ? Builder.CreateAnd(Cond, Overflow, "and") : Overflow;
Chris Lattner80230302010-09-11 21:47:09 +00001949 }
Richard Smithc54e25f2012-11-06 02:30:30 +00001950
1951 if (Cond)
1952 EmitBinOpCheck(Cond, Ops);
Chris Lattner80230302010-09-11 21:47:09 +00001953}
Chris Lattner1f1ded92007-08-24 21:00:35 +00001954
Chris Lattner7f02f722007-08-24 05:35:26 +00001955Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Will Dietz4f45bc02013-01-18 11:30:38 +00001956 if ((CGF.SanOpts->IntegerDivideByZero ||
1957 CGF.SanOpts->SignedIntegerOverflow) &&
Will Dietzb8540362012-11-27 15:01:55 +00001958 Ops.Ty->isIntegerType()) {
Chris Lattner80230302010-09-11 21:47:09 +00001959 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Will Dietzb8540362012-11-27 15:01:55 +00001960 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Will Dietz4f45bc02013-01-18 11:30:38 +00001961 } else if (CGF.SanOpts->FloatDivideByZero &&
Will Dietzb8540362012-11-27 15:01:55 +00001962 Ops.Ty->isRealFloatingType()) {
1963 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1964 EmitBinOpCheck(Builder.CreateFCmpUNE(Ops.RHS, Zero), Ops);
Chris Lattner80230302010-09-11 21:47:09 +00001965 }
Will Dietzb8540362012-11-27 15:01:55 +00001966
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001967 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
1968 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Richard Smith7edf9e32012-11-01 22:30:59 +00001969 if (CGF.getLangOpts().OpenCL) {
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001970 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
1971 llvm::Type *ValTy = Val->getType();
1972 if (ValTy->isFloatTy() ||
1973 (isa<llvm::VectorType>(ValTy) &&
1974 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sands82500162012-04-10 08:23:07 +00001975 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbournec5096cb2011-10-27 19:19:51 +00001976 }
1977 return Val;
1978 }
Douglas Gregorf6094622010-07-23 15:58:24 +00001979 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001980 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
1981 else
1982 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
1983}
1984
1985Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
1986 // Rem in C can't be a floating point type: C99 6.5.5p2.
Will Dietz4f45bc02013-01-18 11:30:38 +00001987 if (CGF.SanOpts->IntegerDivideByZero) {
Chris Lattner80230302010-09-11 21:47:09 +00001988 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
1989
Will Dietzb8540362012-11-27 15:01:55 +00001990 if (Ops.Ty->isIntegerType())
Chris Lattner80230302010-09-11 21:47:09 +00001991 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
1992 }
1993
Eli Friedman52d68742011-04-10 04:44:11 +00001994 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00001995 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
1996 else
1997 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
1998}
1999
Mike Stump2add4732009-04-01 20:28:16 +00002000Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2001 unsigned IID;
2002 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00002003
Will Dietzb8540362012-11-27 15:01:55 +00002004 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
Chris Lattner9a207232010-06-26 21:48:21 +00002005 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00002006 case BO_Add:
2007 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002008 OpID = 1;
Will Dietzb8540362012-11-27 15:01:55 +00002009 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2010 llvm::Intrinsic::uadd_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002011 break;
John McCall2de56d12010-08-25 11:45:40 +00002012 case BO_Sub:
2013 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002014 OpID = 2;
Will Dietzb8540362012-11-27 15:01:55 +00002015 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2016 llvm::Intrinsic::usub_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002017 break;
John McCall2de56d12010-08-25 11:45:40 +00002018 case BO_Mul:
2019 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002020 OpID = 3;
Will Dietzb8540362012-11-27 15:01:55 +00002021 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2022 llvm::Intrinsic::umul_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002023 break;
2024 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002025 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump2add4732009-04-01 20:28:16 +00002026 }
Mike Stump035cf892009-04-02 18:15:54 +00002027 OpID <<= 1;
Will Dietzb8540362012-11-27 15:01:55 +00002028 if (isSigned)
2029 OpID |= 1;
Mike Stump035cf892009-04-02 18:15:54 +00002030
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002031 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00002032
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002033 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00002034
2035 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2036 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2037 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2038
Richard Smith7ac9ef12012-09-08 02:08:36 +00002039 // Handle overflow with llvm.trap if no custom handler has been specified.
2040 const std::string *handlerName =
Richard Smith7edf9e32012-11-01 22:30:59 +00002041 &CGF.getLangOpts().OverflowHandler;
Richard Smith7ac9ef12012-09-08 02:08:36 +00002042 if (handlerName->empty()) {
Richard Smithd6396a62012-11-05 22:21:05 +00002043 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
Richard Smithcc305612012-11-01 22:15:34 +00002044 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
Will Dietz4f45bc02013-01-18 11:30:38 +00002045 if (!isSigned || CGF.SanOpts->SignedIntegerOverflow)
Richard Smithcc305612012-11-01 22:15:34 +00002046 EmitBinOpCheck(Builder.CreateNot(overflow), Ops);
2047 else
2048 CGF.EmitTrapvCheck(Builder.CreateNot(overflow));
Richard Smith7ac9ef12012-09-08 02:08:36 +00002049 return result;
2050 }
2051
Mike Stump2add4732009-04-01 20:28:16 +00002052 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00002053 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00002054 llvm::Function::iterator insertPt = initialBB;
2055 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
2056 llvm::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00002057 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00002058
2059 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2060
David Chisnall7f18e672010-09-17 18:29:54 +00002061 // If an overflow handler is set, then we want to call it and then use its
2062 // result, if it returns.
2063 Builder.SetInsertPoint(overflowBB);
2064
2065 // Get the overflow handler.
Chris Lattner8b418682012-02-07 00:39:47 +00002066 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002067 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00002068 llvm::FunctionType *handlerTy =
2069 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2070 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2071
2072 // Sign extend the args to 64-bit, so that we can use the same handler for
2073 // all types of overflow.
2074 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2075 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2076
2077 // Call the handler with the two arguments, the operation, and the size of
2078 // the result.
2079 llvm::Value *handlerResult = Builder.CreateCall4(handler, lhs, rhs,
2080 Builder.getInt8(OpID),
2081 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth()));
2082
2083 // Truncate the result back to the desired size.
2084 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2085 Builder.CreateBr(continueBB);
2086
Mike Stump2add4732009-04-01 20:28:16 +00002087 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002088 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00002089 phi->addIncoming(result, initialBB);
2090 phi->addIncoming(handlerResult, overflowBB);
2091
2092 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00002093}
Chris Lattner7f02f722007-08-24 05:35:26 +00002094
John McCall913dab22011-06-25 01:32:37 +00002095/// Emit pointer + index arithmetic.
2096static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2097 const BinOpInfo &op,
2098 bool isSubtraction) {
2099 // Must have binary (not unary) expr here. Unary pointer
2100 // increment/decrement doesn't use this path.
2101 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2102
2103 Value *pointer = op.LHS;
2104 Expr *pointerOperand = expr->getLHS();
2105 Value *index = op.RHS;
2106 Expr *indexOperand = expr->getRHS();
2107
2108 // In a subtraction, the LHS is always the pointer.
2109 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2110 std::swap(pointer, index);
2111 std::swap(pointerOperand, indexOperand);
2112 }
2113
2114 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2115 if (width != CGF.PointerWidthInBits) {
2116 // Zero-extend or sign-extend the pointer value according to
2117 // whether the index is signed or not.
2118 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2119 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2120 "idx.ext");
2121 }
2122
2123 // If this is subtraction, negate the index.
2124 if (isSubtraction)
2125 index = CGF.Builder.CreateNeg(index, "idx.neg");
2126
2127 const PointerType *pointerType
2128 = pointerOperand->getType()->getAs<PointerType>();
2129 if (!pointerType) {
2130 QualType objectType = pointerOperand->getType()
2131 ->castAs<ObjCObjectPointerType>()
2132 ->getPointeeType();
2133 llvm::Value *objectSize
2134 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2135
2136 index = CGF.Builder.CreateMul(index, objectSize);
2137
2138 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2139 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2140 return CGF.Builder.CreateBitCast(result, pointer->getType());
2141 }
2142
2143 QualType elementType = pointerType->getPointeeType();
2144 if (const VariableArrayType *vla
2145 = CGF.getContext().getAsVariableArrayType(elementType)) {
2146 // The element count here is the total number of non-VLA elements.
2147 llvm::Value *numElements = CGF.getVLASize(vla).first;
2148
2149 // Effectively, the multiply by the VLA size is part of the GEP.
2150 // GEP indexes are signed, and scaling an index isn't permitted to
2151 // signed-overflow, so we use the same semantics for our explicit
2152 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +00002153 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall913dab22011-06-25 01:32:37 +00002154 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2155 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2156 } else {
2157 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2158 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00002159 }
John McCall913dab22011-06-25 01:32:37 +00002160 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002161 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00002162
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002163 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2164 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2165 // future proof.
John McCall913dab22011-06-25 01:32:37 +00002166 if (elementType->isVoidType() || elementType->isFunctionType()) {
2167 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2168 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2169 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002170 }
2171
David Blaikie4e4d0842012-03-11 07:00:24 +00002172 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall913dab22011-06-25 01:32:37 +00002173 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2174
2175 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00002176}
2177
Lang Hamesbe9af122012-10-02 04:45:10 +00002178// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2179// Addend. Use negMul and negAdd to negate the first operand of the Mul or
2180// the add operand respectively. This allows fmuladd to represent a*b-c, or
2181// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2182// efficient operations.
2183static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2184 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2185 bool negMul, bool negAdd) {
2186 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
2187
2188 Value *MulOp0 = MulOp->getOperand(0);
2189 Value *MulOp1 = MulOp->getOperand(1);
2190 if (negMul) {
2191 MulOp0 =
2192 Builder.CreateFSub(
2193 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2194 "neg");
2195 } else if (negAdd) {
2196 Addend =
2197 Builder.CreateFSub(
2198 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2199 "neg");
2200 }
2201
2202 Value *FMulAdd =
2203 Builder.CreateCall3(
2204 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2205 MulOp0, MulOp1, Addend);
2206 MulOp->eraseFromParent();
2207
2208 return FMulAdd;
2209}
2210
2211// Check whether it would be legal to emit an fmuladd intrinsic call to
2212// represent op and if so, build the fmuladd.
2213//
2214// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2215// Does NOT check the type of the operation - it's assumed that this function
2216// will be called from contexts where it's known that the type is contractable.
2217static Value* tryEmitFMulAdd(const BinOpInfo &op,
2218 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2219 bool isSub=false) {
2220
2221 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2222 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2223 "Only fadd/fsub can be the root of an fmuladd.");
2224
2225 // Check whether this op is marked as fusable.
2226 if (!op.FPContractable)
2227 return 0;
2228
2229 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2230 // either disabled, or handled entirely by the LLVM backend).
Lang Hames931c0832012-11-15 07:51:26 +00002231 if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
Lang Hamesbe9af122012-10-02 04:45:10 +00002232 return 0;
2233
2234 // We have a potentially fusable op. Look for a mul on one of the operands.
2235 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2236 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002237 assert(LHSBinOp->getNumUses() == 0 &&
2238 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002239 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2240 }
2241 } else if (llvm::BinaryOperator* RHSBinOp =
2242 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2243 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002244 assert(RHSBinOp->getNumUses() == 0 &&
2245 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002246 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2247 }
2248 }
2249
2250 return 0;
2251}
2252
John McCall913dab22011-06-25 01:32:37 +00002253Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2254 if (op.LHS->getType()->isPointerTy() ||
2255 op.RHS->getType()->isPointerTy())
2256 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2257
2258 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002259 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
John McCall913dab22011-06-25 01:32:37 +00002260 case LangOptions::SOB_Defined:
2261 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith9d3e2262012-08-25 00:32:28 +00002262 case LangOptions::SOB_Undefined:
Will Dietz4f45bc02013-01-18 11:30:38 +00002263 if (!CGF.SanOpts->SignedIntegerOverflow)
Richard Smith9d3e2262012-08-25 00:32:28 +00002264 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2265 // Fall through.
John McCall913dab22011-06-25 01:32:37 +00002266 case LangOptions::SOB_Trapping:
2267 return EmitOverflowCheckedBinOp(op);
2268 }
2269 }
Will Dietzb8540362012-11-27 15:01:55 +00002270
Will Dietz4f45bc02013-01-18 11:30:38 +00002271 if (op.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
Will Dietzb8540362012-11-27 15:01:55 +00002272 return EmitOverflowCheckedBinOp(op);
2273
Lang Hamesbe9af122012-10-02 04:45:10 +00002274 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2275 // Try to form an fmuladd.
2276 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2277 return FMulAdd;
2278
John McCall913dab22011-06-25 01:32:37 +00002279 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
Lang Hamesbe9af122012-10-02 04:45:10 +00002280 }
John McCall913dab22011-06-25 01:32:37 +00002281
2282 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2283}
2284
2285Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2286 // The LHS is always a pointer if either side is.
2287 if (!op.LHS->getType()->isPointerTy()) {
2288 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002289 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00002290 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00002291 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith9d3e2262012-08-25 00:32:28 +00002292 case LangOptions::SOB_Undefined:
Will Dietz4f45bc02013-01-18 11:30:38 +00002293 if (!CGF.SanOpts->SignedIntegerOverflow)
Richard Smith9d3e2262012-08-25 00:32:28 +00002294 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2295 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +00002296 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00002297 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00002298 }
2299 }
Will Dietzb8540362012-11-27 15:01:55 +00002300
Will Dietz4f45bc02013-01-18 11:30:38 +00002301 if (op.Ty->isUnsignedIntegerType() && CGF.SanOpts->UnsignedIntegerOverflow)
Will Dietzb8540362012-11-27 15:01:55 +00002302 return EmitOverflowCheckedBinOp(op);
2303
Lang Hamesbe9af122012-10-02 04:45:10 +00002304 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2305 // Try to form an fmuladd.
2306 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2307 return FMulAdd;
John McCall913dab22011-06-25 01:32:37 +00002308 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Lang Hamesbe9af122012-10-02 04:45:10 +00002309 }
Chris Lattner2eb91e42010-03-29 17:28:16 +00002310
John McCall913dab22011-06-25 01:32:37 +00002311 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00002312 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00002313
John McCall913dab22011-06-25 01:32:37 +00002314 // If the RHS is not a pointer, then we have normal pointer
2315 // arithmetic.
2316 if (!op.RHS->getType()->isPointerTy())
2317 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00002318
John McCall913dab22011-06-25 01:32:37 +00002319 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00002320
John McCall913dab22011-06-25 01:32:37 +00002321 // Do the raw subtraction part.
2322 llvm::Value *LHS
2323 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2324 llvm::Value *RHS
2325 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2326 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002327
John McCall913dab22011-06-25 01:32:37 +00002328 // Okay, figure out the element size.
2329 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2330 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002331
John McCall913dab22011-06-25 01:32:37 +00002332 llvm::Value *divisor = 0;
2333
2334 // For a variable-length array, this is going to be non-constant.
2335 if (const VariableArrayType *vla
2336 = CGF.getContext().getAsVariableArrayType(elementType)) {
2337 llvm::Value *numElements;
2338 llvm::tie(numElements, elementType) = CGF.getVLASize(vla);
2339
2340 divisor = numElements;
2341
2342 // Scale the number of non-VLA elements by the non-VLA element size.
2343 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2344 if (!eltSize.isOne())
2345 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2346
2347 // For everything elese, we can just compute it, safe in the
2348 // assumption that Sema won't let anything through that we can't
2349 // safely compute the size of.
2350 } else {
2351 CharUnits elementSize;
2352 // Handle GCC extension for pointer arithmetic on void* and
2353 // function pointer types.
2354 if (elementType->isVoidType() || elementType->isFunctionType())
2355 elementSize = CharUnits::One();
2356 else
2357 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2358
2359 // Don't even emit the divide for element size of 1.
2360 if (elementSize.isOne())
2361 return diffInChars;
2362
2363 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002364 }
Chris Lattner2cb42222011-03-01 00:03:48 +00002365
Chris Lattner2cb42222011-03-01 00:03:48 +00002366 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2367 // pointer difference in C is only defined in the case where both operands
2368 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002369 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002370}
2371
David Tweed7a834212013-01-07 16:43:27 +00002372Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
David Tweedf20318f2013-01-10 09:11:33 +00002373 llvm::IntegerType *Ty;
2374 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2375 Ty = cast<llvm::IntegerType>(VT->getElementType());
2376 else
2377 Ty = cast<llvm::IntegerType>(LHS->getType());
2378 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
David Tweed7a834212013-01-07 16:43:27 +00002379}
2380
Chris Lattner7f02f722007-08-24 05:35:26 +00002381Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2382 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2383 // RHS to the same size as the LHS.
2384 Value *RHS = Ops.RHS;
2385 if (Ops.LHS->getType() != RHS->getType())
2386 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002387
Will Dietz4f45bc02013-01-18 11:30:38 +00002388 if (CGF.SanOpts->Shift && !CGF.getLangOpts().OpenCL &&
2389 isa<llvm::IntegerType>(Ops.LHS->getType())) {
David Tweed7a834212013-01-07 16:43:27 +00002390 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, RHS);
Richard Smith4def70d2012-10-09 19:52:38 +00002391 // FIXME: Emit the branching explicitly rather than emitting the check
2392 // twice.
2393 EmitBinOpCheck(Builder.CreateICmpULE(RHS, WidthMinusOne), Ops);
Richard Smith9d3e2262012-08-25 00:32:28 +00002394
2395 if (Ops.Ty->hasSignedIntegerRepresentation()) {
2396 // Check whether we are shifting any non-zero bits off the top of the
2397 // integer.
Richard Smith9d3e2262012-08-25 00:32:28 +00002398 llvm::Value *BitsShiftedOff =
2399 Builder.CreateLShr(Ops.LHS,
2400 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2401 /*NUW*/true, /*NSW*/true),
2402 "shl.check");
2403 if (CGF.getLangOpts().CPlusPlus) {
2404 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2405 // Under C++11's rules, shifting a 1 bit into the sign bit is
2406 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2407 // define signed left shifts, so we use the C99 and C++11 rules there).
2408 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2409 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2410 }
2411 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Richard Smith4def70d2012-10-09 19:52:38 +00002412 EmitBinOpCheck(Builder.CreateICmpEQ(BitsShiftedOff, Zero), Ops);
Richard Smith9d3e2262012-08-25 00:32:28 +00002413 }
Mike Stumpbe07f602009-12-14 21:58:14 +00002414 }
David Tweed7a834212013-01-07 16:43:27 +00002415 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2416 if (CGF.getLangOpts().OpenCL)
2417 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
Mike Stumpbe07f602009-12-14 21:58:14 +00002418
Chris Lattner7f02f722007-08-24 05:35:26 +00002419 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2420}
2421
2422Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2423 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2424 // RHS to the same size as the LHS.
2425 Value *RHS = Ops.RHS;
2426 if (Ops.LHS->getType() != RHS->getType())
2427 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002428
Will Dietz4f45bc02013-01-18 11:30:38 +00002429 if (CGF.SanOpts->Shift && !CGF.getLangOpts().OpenCL &&
2430 isa<llvm::IntegerType>(Ops.LHS->getType()))
David Tweed7a834212013-01-07 16:43:27 +00002431 EmitBinOpCheck(Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS)), Ops);
2432
2433 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2434 if (CGF.getLangOpts().OpenCL)
2435 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
Mike Stumpbe07f602009-12-14 21:58:14 +00002436
Douglas Gregorf6094622010-07-23 15:58:24 +00002437 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002438 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2439 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2440}
2441
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002442enum IntrinsicType { VCMPEQ, VCMPGT };
2443// return corresponding comparison intrinsic for given vector type
2444static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2445 BuiltinType::Kind ElemKind) {
2446 switch (ElemKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002447 default: llvm_unreachable("unexpected element type");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002448 case BuiltinType::Char_U:
2449 case BuiltinType::UChar:
2450 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2451 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002452 case BuiltinType::Char_S:
2453 case BuiltinType::SChar:
2454 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2455 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002456 case BuiltinType::UShort:
2457 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2458 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002459 case BuiltinType::Short:
2460 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2461 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002462 case BuiltinType::UInt:
2463 case BuiltinType::ULong:
2464 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2465 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002466 case BuiltinType::Int:
2467 case BuiltinType::Long:
2468 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2469 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002470 case BuiltinType::Float:
2471 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2472 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002473 }
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002474}
2475
Chris Lattner7f02f722007-08-24 05:35:26 +00002476Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2477 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002478 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002479 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002480 QualType LHSTy = E->getLHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002481 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002482 assert(E->getOpcode() == BO_EQ ||
2483 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002484 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2485 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002486 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002487 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Eli Friedmanb81c7862009-12-11 07:36:43 +00002488 } else if (!LHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002489 Value *LHS = Visit(E->getLHS());
2490 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002491
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002492 // If AltiVec, the comparison results in a numeric type, so we use
2493 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002494 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002495 // constants for mapping CR6 register bits to predicate result
2496 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2497
2498 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2499
2500 // in several cases vector arguments order will be reversed
2501 Value *FirstVecArg = LHS,
2502 *SecondVecArg = RHS;
2503
2504 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002505 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002506 BuiltinType::Kind ElementKind = BTy->getKind();
2507
2508 switch(E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002509 default: llvm_unreachable("is not a comparison operation");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002510 case BO_EQ:
2511 CR6 = CR6_LT;
2512 ID = GetIntrinsic(VCMPEQ, ElementKind);
2513 break;
2514 case BO_NE:
2515 CR6 = CR6_EQ;
2516 ID = GetIntrinsic(VCMPEQ, ElementKind);
2517 break;
2518 case BO_LT:
2519 CR6 = CR6_LT;
2520 ID = GetIntrinsic(VCMPGT, ElementKind);
2521 std::swap(FirstVecArg, SecondVecArg);
2522 break;
2523 case BO_GT:
2524 CR6 = CR6_LT;
2525 ID = GetIntrinsic(VCMPGT, ElementKind);
2526 break;
2527 case BO_LE:
2528 if (ElementKind == BuiltinType::Float) {
2529 CR6 = CR6_LT;
2530 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2531 std::swap(FirstVecArg, SecondVecArg);
2532 }
2533 else {
2534 CR6 = CR6_EQ;
2535 ID = GetIntrinsic(VCMPGT, ElementKind);
2536 }
2537 break;
2538 case BO_GE:
2539 if (ElementKind == BuiltinType::Float) {
2540 CR6 = CR6_LT;
2541 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2542 }
2543 else {
2544 CR6 = CR6_EQ;
2545 ID = GetIntrinsic(VCMPGT, ElementKind);
2546 std::swap(FirstVecArg, SecondVecArg);
2547 }
2548 break;
2549 }
2550
Chris Lattner48431f92011-04-19 22:55:03 +00002551 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002552 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2553 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2554 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2555 }
2556
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002557 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002558 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002559 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002560 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002561 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002562 LHS, RHS, "cmp");
2563 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002564 // Unsigned integers and pointers.
2565 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002566 LHS, RHS, "cmp");
2567 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002568
2569 // If this is a vector comparison, sign extend the result to the appropriate
2570 // vector integer type and return it (don't convert to bool).
2571 if (LHSTy->isVectorType())
2572 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002573
Chris Lattner7f02f722007-08-24 05:35:26 +00002574 } else {
2575 // Complex Comparison: can only be an equality comparison.
2576 CodeGenFunction::ComplexPairTy LHS = CGF.EmitComplexExpr(E->getLHS());
2577 CodeGenFunction::ComplexPairTy RHS = CGF.EmitComplexExpr(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002578
John McCall183700f2009-09-21 23:43:11 +00002579 QualType CETy = LHSTy->getAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002580
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002581 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002582 if (CETy->isRealFloatingType()) {
2583 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2584 LHS.first, RHS.first, "cmp.r");
2585 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2586 LHS.second, RHS.second, "cmp.i");
2587 } else {
2588 // Complex comparisons can only be equality comparisons. As such, signed
2589 // and unsigned opcodes are the same.
2590 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2591 LHS.first, RHS.first, "cmp.r");
2592 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2593 LHS.second, RHS.second, "cmp.i");
2594 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002595
John McCall2de56d12010-08-25 11:45:40 +00002596 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002597 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2598 } else {
John McCall2de56d12010-08-25 11:45:40 +00002599 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002600 "Complex comparison other than == or != ?");
2601 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2602 }
2603 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002604
2605 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002606}
2607
2608Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002609 bool Ignore = TestAndClearIgnoreResultAssign();
2610
John McCallf85e1932011-06-15 23:02:42 +00002611 Value *RHS;
2612 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002613
John McCallf85e1932011-06-15 23:02:42 +00002614 switch (E->getLHS()->getType().getObjCLifetime()) {
2615 case Qualifiers::OCL_Strong:
2616 llvm::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
2617 break;
2618
2619 case Qualifiers::OCL_Autoreleasing:
2620 llvm::tie(LHS,RHS) = CGF.EmitARCStoreAutoreleasing(E);
2621 break;
2622
2623 case Qualifiers::OCL_Weak:
2624 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002625 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002626 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2627 break;
2628
2629 // No reason to do any of these differently.
2630 case Qualifiers::OCL_None:
2631 case Qualifiers::OCL_ExplicitNone:
2632 // __block variables need to have the rhs evaluated first, plus
2633 // this should improve codegen just a little.
2634 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002635 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002636
2637 // Store the value into the LHS. Bit-fields are handled specially
2638 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2639 // 'An assignment expression has the value of the left operand after
2640 // the assignment...'.
2641 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002642 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002643 else
John McCall545d9962011-06-25 02:11:03 +00002644 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002645 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002646
2647 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002648 if (Ignore)
2649 return 0;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002650
John McCallb418d742010-11-16 10:08:07 +00002651 // The result of an assignment in C is the assigned r-value.
Richard Smith7edf9e32012-11-01 22:30:59 +00002652 if (!CGF.getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00002653 return RHS;
2654
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002655 // If the lvalue is non-volatile, return the computed value of the assignment.
2656 if (!LHS.isVolatileQualified())
2657 return RHS;
2658
2659 // Otherwise, reload the value.
John McCall545d9962011-06-25 02:11:03 +00002660 return EmitLoadOfLValue(LHS);
Chris Lattner7f02f722007-08-24 05:35:26 +00002661}
2662
2663Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002664
2665 // Perform vector logical and on comparisons with zero vectors.
2666 if (E->getType()->isVectorType()) {
2667 Value *LHS = Visit(E->getLHS());
2668 Value *RHS = Visit(E->getRHS());
2669 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2670 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2671 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2672 Value *And = Builder.CreateAnd(LHS, RHS);
2673 return Builder.CreateSExt(And, Zero->getType(), "sext");
2674 }
2675
Chris Lattner2acc6e32011-07-18 04:24:23 +00002676 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002677
Chris Lattner20eb09d2008-11-12 08:26:50 +00002678 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
2679 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002680 bool LHSCondVal;
2681 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2682 if (LHSCondVal) { // If we have 1 && X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002683 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002684 // ZExt result to int or bool.
2685 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002686 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002687
Chris Lattner7804bcb2009-10-17 04:24:20 +00002688 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002689 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002690 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002691 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002692
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002693 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
2694 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00002695
John McCall150b4622011-01-26 04:00:11 +00002696 CodeGenFunction::ConditionalEvaluation eval(CGF);
2697
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002698 // Branch on the LHS first. If it is false, go to the failure (cont) block.
2699 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock);
2700
2701 // Any edges into the ContBlock are now from an (indeterminate number of)
2702 // edges from this first condition. All of these values will be false. Start
2703 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002704 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002705 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002706 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2707 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002708 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002709
John McCall150b4622011-01-26 04:00:11 +00002710 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00002711 CGF.EmitBlock(RHSBlock);
2712 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00002713 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002714
Chris Lattner7f02f722007-08-24 05:35:26 +00002715 // Reaquire the RHS block, as there may be subblocks inserted.
2716 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002717
2718 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2719 // into the phi node for the edge with the value of RHSCond.
Devang Patelacd72362011-03-30 00:08:31 +00002720 if (CGF.getDebugInfo())
2721 // There is no need to emit line number for unconditional branch.
2722 Builder.SetCurrentDebugLocation(llvm::DebugLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002723 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002724 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002725
Chris Lattner7f02f722007-08-24 05:35:26 +00002726 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002727 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002728}
2729
2730Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00002731
2732 // Perform vector logical or on comparisons with zero vectors.
2733 if (E->getType()->isVectorType()) {
2734 Value *LHS = Visit(E->getLHS());
2735 Value *RHS = Visit(E->getRHS());
2736 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
2737 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2738 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2739 Value *Or = Builder.CreateOr(LHS, RHS);
2740 return Builder.CreateSExt(Or, Zero->getType(), "sext");
2741 }
2742
Chris Lattner2acc6e32011-07-18 04:24:23 +00002743 llvm::Type *ResTy = ConvertType(E->getType());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002744
Chris Lattner20eb09d2008-11-12 08:26:50 +00002745 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
2746 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002747 bool LHSCondVal;
2748 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
2749 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Chris Lattner0946ccd2008-11-11 07:41:27 +00002750 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00002751 // ZExt result to int or bool.
2752 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00002753 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002754
Chris Lattner7804bcb2009-10-17 04:24:20 +00002755 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00002756 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00002757 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00002758 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002759
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002760 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
2761 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002762
John McCall150b4622011-01-26 04:00:11 +00002763 CodeGenFunction::ConditionalEvaluation eval(CGF);
2764
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002765 // Branch on the LHS first. If it is true, go to the success (cont) block.
2766 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock);
2767
2768 // Any edges into the ContBlock are now from an (indeterminate number of)
2769 // edges from this first condition. All of these values will be true. Start
2770 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002771 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00002772 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002773 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
2774 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00002775 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002776
John McCall150b4622011-01-26 04:00:11 +00002777 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00002778
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002779 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00002780 CGF.EmitBlock(RHSBlock);
2781 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002782
John McCall150b4622011-01-26 04:00:11 +00002783 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002784
Chris Lattner7f02f722007-08-24 05:35:26 +00002785 // Reaquire the RHS block, as there may be subblocks inserted.
2786 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002787
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00002788 // Emit an unconditional branch from this block to ContBlock. Insert an entry
2789 // into the phi node for the edge with the value of RHSCond.
2790 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00002791 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002792
Chris Lattner7f02f722007-08-24 05:35:26 +00002793 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00002794 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00002795}
2796
2797Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00002798 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00002799 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00002800 return Visit(E->getRHS());
2801}
2802
2803//===----------------------------------------------------------------------===//
2804// Other Operators
2805//===----------------------------------------------------------------------===//
2806
Chris Lattner9802a512008-11-12 08:55:54 +00002807/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
2808/// expression is cheap enough and side-effect-free enough to evaluate
2809/// unconditionally instead of conditionally. This is used to convert control
2810/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00002811static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
2812 CodeGenFunction &CGF) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002813 E = E->IgnoreParens();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002814
Chris Lattnerc6bea672011-04-16 23:15:35 +00002815 // Anything that is an integer or floating point constant is fine.
2816 if (E->isConstantInitializer(CGF.getContext(), false))
Chris Lattner9802a512008-11-12 08:55:54 +00002817 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002818
Chris Lattner9802a512008-11-12 08:55:54 +00002819 // Non-volatile automatic variables too, to get "cond ? X : Y" where
2820 // X and Y are local variables.
2821 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
2822 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Mike Stumpdf317bf2009-11-03 23:25:48 +00002823 if (VD->hasLocalStorage() && !(CGF.getContext()
2824 .getCanonicalType(VD->getType())
2825 .isVolatileQualified()))
Chris Lattner9802a512008-11-12 08:55:54 +00002826 return true;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002827
Chris Lattner9802a512008-11-12 08:55:54 +00002828 return false;
2829}
2830
2831
Chris Lattner7f02f722007-08-24 05:35:26 +00002832Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00002833VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002834 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00002835
2836 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +00002837 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCall56ca35d2011-02-17 10:25:35 +00002838
2839 Expr *condExpr = E->getCond();
2840 Expr *lhsExpr = E->getTrueExpr();
2841 Expr *rhsExpr = E->getFalseExpr();
2842
Chris Lattner31a09842008-11-12 08:04:58 +00002843 // If the condition constant folds and can be elided, try to avoid emitting
2844 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00002845 bool CondExprBool;
2846 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00002847 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00002848 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002849
Eli Friedmanc8645e32011-10-15 02:10:40 +00002850 // If the dead side doesn't have labels we need, just emit the Live part.
2851 if (!CGF.ContainsLabel(dead)) {
2852 Value *Result = Visit(live);
2853
2854 // If the live part is a throw expression, it acts like it has a void
2855 // type, so evaluating it returns a null Value*. However, a conditional
2856 // with non-void type must return a non-null Value*.
2857 if (!Result && !E->getType()->isVoidType())
2858 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
2859
2860 return Result;
2861 }
Chris Lattnerc657e922008-11-11 18:56:45 +00002862 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002863
Nate Begeman6155d732010-09-20 22:41:17 +00002864 // OpenCL: If the condition is a vector, we can treat this condition like
2865 // the select function.
Richard Smith7edf9e32012-11-01 22:30:59 +00002866 if (CGF.getLangOpts().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00002867 && condExpr->getType()->isVectorType()) {
2868 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
2869 llvm::Value *LHS = Visit(lhsExpr);
2870 llvm::Value *RHS = Visit(rhsExpr);
Nate Begeman6155d732010-09-20 22:41:17 +00002871
Chris Lattner2acc6e32011-07-18 04:24:23 +00002872 llvm::Type *condType = ConvertType(condExpr->getType());
2873 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Nate Begeman6155d732010-09-20 22:41:17 +00002874
2875 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002876 llvm::Type *elemType = vecTy->getElementType();
Nate Begeman6155d732010-09-20 22:41:17 +00002877
Chris Lattner2ce88422012-01-25 05:34:41 +00002878 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begeman6155d732010-09-20 22:41:17 +00002879 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
2880 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
2881 llvm::VectorType::get(elemType,
2882 numElem),
2883 "sext");
2884 llvm::Value *tmp2 = Builder.CreateNot(tmp);
2885
2886 // Cast float to int to perform ANDs if necessary.
2887 llvm::Value *RHSTmp = RHS;
2888 llvm::Value *LHSTmp = LHS;
2889 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00002890 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourne565204d2012-05-29 00:35:18 +00002891 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begeman6155d732010-09-20 22:41:17 +00002892 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
2893 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
2894 wasCast = true;
2895 }
2896
2897 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
2898 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
2899 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
2900 if (wasCast)
2901 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
2902
2903 return tmp5;
2904 }
2905
Chris Lattner9802a512008-11-12 08:55:54 +00002906 // If this is a really simple expression (like x ? 4 : 5), emit this as a
2907 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00002908 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00002909 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
2910 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
2911 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
2912 llvm::Value *LHS = Visit(lhsExpr);
2913 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman1e4f68c2011-12-08 22:01:56 +00002914 if (!LHS) {
2915 // If the conditional has void type, make sure we return a null Value*.
2916 assert(!RHS && "LHS and RHS types must match");
2917 return 0;
2918 }
Chris Lattner9802a512008-11-12 08:55:54 +00002919 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
2920 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002921
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00002922 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
2923 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00002924 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00002925
2926 CodeGenFunction::ConditionalEvaluation eval(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002927 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock);
Anders Carlssonfb6fa302009-06-04 03:00:32 +00002928
Chris Lattner7f02f722007-08-24 05:35:26 +00002929 CGF.EmitBlock(LHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002930 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002931 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002932 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002933
Chris Lattner7f02f722007-08-24 05:35:26 +00002934 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00002935 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002936
Chris Lattner7f02f722007-08-24 05:35:26 +00002937 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00002938 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00002939 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00002940 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002941
John McCall150b4622011-01-26 04:00:11 +00002942 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00002943 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002944
Eli Friedman48daf592009-12-07 20:25:53 +00002945 // If the LHS or RHS is a throw expression, it will be legitimately null.
2946 if (!LHS)
2947 return RHS;
2948 if (!RHS)
2949 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002950
Chris Lattner7f02f722007-08-24 05:35:26 +00002951 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00002952 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00002953 PN->addIncoming(LHS, LHSBlock);
2954 PN->addIncoming(RHS, RHSBlock);
2955 return PN;
2956}
2957
2958Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman79769322009-03-04 05:52:32 +00002959 return Visit(E->getChosenSubExpr(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00002960}
2961
Chris Lattner2202bce2007-11-30 17:56:23 +00002962Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Eli Friedman4fd0aa52009-01-20 17:46:04 +00002963 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002964 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
2965
2966 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002967 if (!ArgPtr)
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002968 return Builder.CreateVAArg(ArgValue, ConvertType(VE->getType()));
2969
Mike Stump7f79f9b2009-05-29 15:46:01 +00002970 // FIXME Volatility.
Anders Carlssonddf7cac2008-11-04 05:30:00 +00002971 return Builder.CreateLoad(ArgPtr);
Anders Carlsson7c50aca2007-10-15 20:28:48 +00002972}
2973
John McCall6b5a61b2011-02-07 10:33:21 +00002974Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
2975 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00002976}
2977
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002978Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
2979 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00002980 llvm::Type *DstTy = ConvertType(E->getType());
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002981
2982 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
2983 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002984 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002985 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
2986 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
2987 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
2988 if ((numElementsDst == 3 && numElementsSrc == 4)
2989 || (numElementsDst == 4 && numElementsSrc == 3)) {
2990
2991
2992 // In the case of going from int4->float3, a bitcast is needed before
2993 // doing a shuffle.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002994 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002995 cast<llvm::VectorType>(SrcTy)->getElementType();
Chris Lattner2acc6e32011-07-18 04:24:23 +00002996 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00002997 cast<llvm::VectorType>(DstTy)->getElementType();
2998
2999 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
3000 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
3001 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003002 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003003 numElementsSrc);
3004
3005 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
3006 }
3007
3008 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
3009
Chris Lattner5f9e2722011-07-23 10:55:15 +00003010 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003011 Args.push_back(Builder.getInt32(0));
3012 Args.push_back(Builder.getInt32(1));
3013 Args.push_back(Builder.getInt32(2));
3014
3015 if (numElementsDst == 4)
Chris Lattner8b418682012-02-07 00:39:47 +00003016 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003017
3018 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
3019
3020 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3021 }
3022 }
3023
3024 return Builder.CreateBitCast(Src, DstTy, "astype");
3025}
3026
Eli Friedman276b0612011-10-11 02:20:01 +00003027Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3028 return CGF.EmitAtomicExpr(E).getScalarVal();
3029}
3030
Chris Lattner7f02f722007-08-24 05:35:26 +00003031//===----------------------------------------------------------------------===//
3032// Entry Point into this File
3033//===----------------------------------------------------------------------===//
3034
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003035/// EmitScalarExpr - Emit the computation of the specified expression of scalar
3036/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00003037Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
Chris Lattner7f02f722007-08-24 05:35:26 +00003038 assert(E && !hasAggregateLLVMType(E->getType()) &&
3039 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003040
Devang Patel5de7a0e2011-03-07 18:29:53 +00003041 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00003042 disableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00003043 Value *V = ScalarExprEmitter(*this, IgnoreResultAssign)
Mike Stump7f79f9b2009-05-29 15:46:01 +00003044 .Visit(const_cast<Expr*>(E));
Devang Patel5de7a0e2011-03-07 18:29:53 +00003045 if (isa<CXXDefaultArgExpr>(E))
Devang Patelaa112892011-03-07 18:45:56 +00003046 enableDebugInfo();
Devang Patel5de7a0e2011-03-07 18:29:53 +00003047 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +00003048}
Chris Lattner3707b252007-08-26 06:48:56 +00003049
3050/// EmitScalarConversion - Emit a conversion from the specified type to the
3051/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003052Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3053 QualType DstTy) {
Chris Lattner3707b252007-08-26 06:48:56 +00003054 assert(!hasAggregateLLVMType(SrcTy) && !hasAggregateLLVMType(DstTy) &&
3055 "Invalid scalar expression to emit");
3056 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3057}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003058
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003059/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
3060/// type to the specified destination type, where the destination type is an
3061/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003062Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3063 QualType SrcTy,
3064 QualType DstTy) {
Chris Lattner9b2dc282008-04-04 16:54:41 +00003065 assert(SrcTy->isAnyComplexType() && !hasAggregateLLVMType(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003066 "Invalid complex -> scalar conversion");
3067 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3068 DstTy);
3069}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00003070
Chris Lattner8c11a652010-06-26 22:09:34 +00003071
3072llvm::Value *CodeGenFunction::
3073EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3074 bool isInc, bool isPre) {
3075 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3076}
3077
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003078LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3079 llvm::Value *V;
3080 // object->isa or (*object).isa
3081 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003082 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00003083 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003084
3085 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00003086 if (BaseExpr->isRValue()) {
Eli Friedmand71f4422011-12-19 23:03:09 +00003087 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003088 llvm::Value *Src = EmitScalarExpr(BaseExpr);
3089 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003090 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Eli Friedmand71f4422011-12-19 23:03:09 +00003091 MakeNaturalAlignAddrLValue(V, E->getType()));
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003092 } else {
3093 if (E->isArrow())
3094 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3095 else
3096 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003097 }
3098
3099 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003100 ClassPtrTy = ClassPtrTy->getPointerTo();
3101 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedmand71f4422011-12-19 23:03:09 +00003102 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003103}
3104
Douglas Gregor6a03e342010-04-23 04:16:32 +00003105
John McCall2a416372010-12-05 02:00:02 +00003106LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00003107 const CompoundAssignOperator *E) {
3108 ScalarExprEmitter Scalar(*this);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00003109 Value *Result = 0;
Douglas Gregor6a03e342010-04-23 04:16:32 +00003110 switch (E->getOpcode()) {
3111#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00003112 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00003113 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00003114 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00003115 COMPOUND_OP(Mul);
3116 COMPOUND_OP(Div);
3117 COMPOUND_OP(Rem);
3118 COMPOUND_OP(Add);
3119 COMPOUND_OP(Sub);
3120 COMPOUND_OP(Shl);
3121 COMPOUND_OP(Shr);
3122 COMPOUND_OP(And);
3123 COMPOUND_OP(Xor);
3124 COMPOUND_OP(Or);
3125#undef COMPOUND_OP
3126
John McCall2de56d12010-08-25 11:45:40 +00003127 case BO_PtrMemD:
3128 case BO_PtrMemI:
3129 case BO_Mul:
3130 case BO_Div:
3131 case BO_Rem:
3132 case BO_Add:
3133 case BO_Sub:
3134 case BO_Shl:
3135 case BO_Shr:
3136 case BO_LT:
3137 case BO_GT:
3138 case BO_LE:
3139 case BO_GE:
3140 case BO_EQ:
3141 case BO_NE:
3142 case BO_And:
3143 case BO_Xor:
3144 case BO_Or:
3145 case BO_LAnd:
3146 case BO_LOr:
3147 case BO_Assign:
3148 case BO_Comma:
David Blaikieb219cfc2011-09-23 05:06:16 +00003149 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor6a03e342010-04-23 04:16:32 +00003150 }
3151
3152 llvm_unreachable("Unhandled compound assignment operator");
3153}