blob: dc12dd84249ba657b95c4a1dc7fbbf7c3c838793 [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"
Stephen Hines651f13c2014-04-23 16:59:28 -070025#include "llvm/IR/CFG.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000026#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/Function.h"
29#include "llvm/IR/GlobalVariable.h"
30#include "llvm/IR/Intrinsics.h"
31#include "llvm/IR/Module.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
Stephen Hines176edba2014-12-01 14:53:08 -080088 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerKind>> Checks,
89 const BinOpInfo &Info);
Richard Smith4def70d2012-10-09 19:52:38 +000090
Nick Lewycky4ee7dc22013-10-02 02:29:49 +000091 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
92 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
Chris Lattner7f02f722007-08-24 05:35:26 +000093 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +000094
Stephen Hines176edba2014-12-01 14:53:08 -080095 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
96 const AlignValueAttr *AVAttr = nullptr;
97 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
98 const ValueDecl *VD = DRE->getDecl();
99
100 if (VD->getType()->isReferenceType()) {
101 if (const auto *TTy =
102 dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
103 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
104 } else {
105 // Assumptions for function parameters are emitted at the start of the
106 // function, so there is no need to repeat that here.
107 if (isa<ParmVarDecl>(VD))
108 return;
109
110 AVAttr = VD->getAttr<AlignValueAttr>();
111 }
112 }
113
114 if (!AVAttr)
115 if (const auto *TTy =
116 dyn_cast<TypedefType>(E->getType()))
117 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
118
119 if (!AVAttr)
120 return;
121
122 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
123 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
124 CGF.EmitAlignmentAssumption(V, AlignmentCI->getZExtValue());
125 }
126
Chris Lattner7f02f722007-08-24 05:35:26 +0000127 /// EmitLoadOfLValue - Given an expression with complex type that represents a
128 /// value l-value, this method emits the address of the l-value, then loads
129 /// and returns the result.
130 Value *EmitLoadOfLValue(const Expr *E) {
Stephen Hines176edba2014-12-01 14:53:08 -0800131 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
132 E->getExprLoc());
133
134 EmitLValueAlignmentAssumption(E, V);
135 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +0000136 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000137
Chris Lattner9abc84e2007-08-26 16:42:57 +0000138 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000139 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000140 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000141
Richard Smithb2aa66c2012-10-12 22:57:06 +0000142 /// \brief Emit a check that a conversion to or from a floating-point type
143 /// does not overflow.
144 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
145 Value *Src, QualType SrcType,
146 QualType DstType, llvm::Type *DstTy);
147
Chris Lattner3707b252007-08-26 06:48:56 +0000148 /// EmitScalarConversion - Emit a conversion from the specified type to the
149 /// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000150 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
151
152 /// EmitComplexToScalarConversion - Emit a conversion from the specified
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000153 /// complex type to the specified destination type, where the destination type
154 /// is an LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000155 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
156 QualType SrcTy, QualType DstTy);
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000157
Anders Carlssona40a9f32010-05-22 17:45:10 +0000158 /// EmitNullValue - Emit a value that corresponds to null for the given type.
159 Value *EmitNullValue(QualType Ty);
160
John McCalldaa8e4e2010-11-15 09:13:47 +0000161 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
162 Value *EmitFloatToBoolConversion(Value *V) {
163 // Compare against 0.0 for fp scalars.
164 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
165 return Builder.CreateFCmpUNE(V, Zero, "tobool");
166 }
167
168 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
169 Value *EmitPointerToBoolConversion(Value *V) {
170 Value *Zero = llvm::ConstantPointerNull::get(
171 cast<llvm::PointerType>(V->getType()));
172 return Builder.CreateICmpNE(V, Zero, "tobool");
173 }
174
175 Value *EmitIntToBoolConversion(Value *V) {
176 // Because of the type rules of C, we often end up computing a
177 // logical value, then zero extending it to int, then wanting it
178 // as a logical value again. Optimize this common case.
179 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
180 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
181 Value *Result = ZI->getOperand(0);
182 // If there aren't any more uses, zap the instruction to save space.
183 // Note that there can be more uses, for example if this
184 // is the result of an assignment.
185 if (ZI->use_empty())
186 ZI->eraseFromParent();
187 return Result;
188 }
189 }
190
Chris Lattner48431f92011-04-19 22:55:03 +0000191 return Builder.CreateIsNotNull(V, "tobool");
John McCalldaa8e4e2010-11-15 09:13:47 +0000192 }
193
Chris Lattner7f02f722007-08-24 05:35:26 +0000194 //===--------------------------------------------------------------------===//
195 // Visitor Methods
196 //===--------------------------------------------------------------------===//
197
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000198 Value *Visit(Expr *E) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700199 ApplyDebugLocation DL(CGF, E);
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000200 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
201 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000202
Chris Lattner7f02f722007-08-24 05:35:26 +0000203 Value *VisitStmt(Stmt *S) {
Ted Kremenek7a9d49f2007-12-11 21:27:55 +0000204 S->dump(CGF.getContext().getSourceManager());
David Blaikieb219cfc2011-09-23 05:06:16 +0000205 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner7f02f722007-08-24 05:35:26 +0000206 }
207 Value *VisitExpr(Expr *S);
Craig Topperd10e5c22013-07-26 06:16:11 +0000208
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000209 Value *VisitParenExpr(ParenExpr *PE) {
Craig Topperd10e5c22013-07-26 06:16:11 +0000210 return Visit(PE->getSubExpr());
Fariborz Jahanianaf9b9682010-09-17 15:51:28 +0000211 }
John McCall91a57552011-07-15 05:09:51 +0000212 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
Craig Topperd10e5c22013-07-26 06:16:11 +0000213 return Visit(E->getReplacement());
John McCall91a57552011-07-15 05:09:51 +0000214 }
Peter Collingbournef111d932011-04-15 00:35:48 +0000215 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
216 return Visit(GE->getResultExpr());
217 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000218
219 // Leaves.
220 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000221 return Builder.getInt(E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000222 }
223 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersonbc0a2222009-07-27 21:00:51 +0000224 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000225 }
226 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000227 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner7f02f722007-08-24 05:35:26 +0000228 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000229 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
230 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
231 }
Nate Begemane7579b52007-11-15 05:40:03 +0000232 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Anderson4a28d5d2009-07-24 23:12:58 +0000233 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begemane7579b52007-11-15 05:40:03 +0000234 }
Douglas Gregored8abf12010-07-08 06:14:04 +0000235 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000236 return EmitNullValue(E->getType());
Argyrios Kyrtzidis7267f782008-08-23 19:35:47 +0000237 }
Anders Carlsson3f704562008-12-21 22:39:40 +0000238 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000239 return EmitNullValue(E->getType());
Anders Carlsson3f704562008-12-21 22:39:40 +0000240 }
Eli Friedman0027d2b2010-08-05 09:58:49 +0000241 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +0000242 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000243 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattnerd9becd12009-10-28 23:59:40 +0000244 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
245 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar0ffb1252008-08-04 16:51:22 +0000246 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000247
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000248 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000249 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregor9370c8f2011-01-12 22:11:34 +0000250 }
John McCalle996ffd2011-02-16 08:02:54 +0000251
John McCall4b9c2d22011-11-06 09:01:30 +0000252 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
253 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
254 }
255
John McCalle996ffd2011-02-16 08:02:54 +0000256 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCall56ca35d2011-02-17 10:25:35 +0000257 if (E->isGLValue())
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000258 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
John McCalle996ffd2011-02-16 08:02:54 +0000259
260 // Otherwise, assume the mapping is the scalar directly.
John McCall56ca35d2011-02-17 10:25:35 +0000261 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCalle996ffd2011-02-16 08:02:54 +0000262 }
John McCalldd2ecee2012-03-10 03:05:10 +0000263
Chris Lattner7f02f722007-08-24 05:35:26 +0000264 // l-values.
John McCallf4b88a42012-03-10 09:33:50 +0000265 Value *VisitDeclRefExpr(DeclRefExpr *E) {
266 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCalldd2ecee2012-03-10 03:05:10 +0000267 if (result.isReference())
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000268 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E),
269 E->getExprLoc());
John McCalldd2ecee2012-03-10 03:05:10 +0000270 return result.getValue();
Richard Smitha3ca41f2012-03-02 23:27:11 +0000271 }
John McCallf4b88a42012-03-10 09:33:50 +0000272 return EmitLoadOfLValue(E);
John McCalldd2ecee2012-03-10 03:05:10 +0000273 }
274
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000275 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
276 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000277 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000278 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
279 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000280 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000281 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000282 return EmitLoadOfLValue(E);
283 }
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000284 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Craig Topperd10e5c22013-07-26 06:16:11 +0000285 if (E->getMethodDecl() &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700286 E->getMethodDecl()->getReturnType()->isReferenceType())
Fariborz Jahanian180ff3a2011-03-02 20:09:49 +0000287 return EmitLoadOfLValue(E);
Daniel Dunbar9c3fc702008-08-27 06:57:25 +0000288 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbar0a04d772008-08-23 10:51:21 +0000289 }
290
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000291 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian820bca42009-12-09 23:35:29 +0000292 LValue LV = CGF.EmitObjCIsaExpr(E);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000293 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
Fariborz Jahanian83dc3252009-12-09 19:05:56 +0000294 return V;
295 }
296
Chris Lattner7f02f722007-08-24 05:35:26 +0000297 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmand38617c2008-05-14 19:38:39 +0000298 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Hal Finkel414a1bd2013-09-18 03:29:45 +0000299 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
Eli Friedman28665272009-11-26 03:22:21 +0000300 Value *VisitMemberExpr(MemberExpr *E);
Nate Begeman213541a2008-04-18 23:10:10 +0000301 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattnerbe20bb52008-10-26 23:53:12 +0000302 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
303 return EmitLoadOfLValue(E);
304 }
Devang Patel35634f52007-10-24 17:18:43 +0000305
Nate Begeman0533b302009-10-18 20:10:40 +0000306 Value *VisitInitListExpr(InitListExpr *E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000307
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000308 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith0dbe2fb2012-12-21 03:17:28 +0000309 return EmitNullValue(E->getType());
Douglas Gregor3498bdb2009-01-29 17:44:32 +0000310 }
John McCallbc8d40d2011-06-24 21:55:10 +0000311 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian745da3a2010-09-24 17:30:16 +0000312 if (E->getType()->isVariablyModifiedType())
John McCallbc8d40d2011-06-24 21:55:10 +0000313 CGF.EmitVariablyModifiedType(E->getType());
Stephen Hines176edba2014-12-01 14:53:08 -0800314
315 if (CGDebugInfo *DI = CGF.getDebugInfo())
316 DI->EmitExplicitCastType(E->getType());
317
John McCallbc8d40d2011-06-24 21:55:10 +0000318 return VisitCastExpr(E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000319 }
John McCallbc8d40d2011-06-24 21:55:10 +0000320 Value *VisitCastExpr(CastExpr *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000321
322 Value *VisitCallExpr(const CallExpr *E) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -0700323 if (E->getCallReturnType(CGF.getContext())->isReferenceType())
Anders Carlssone9f2f452009-05-27 03:37:57 +0000324 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000325
Stephen Hines176edba2014-12-01 14:53:08 -0800326 Value *V = CGF.EmitCallExpr(E).getScalarVal();
327
328 EmitLValueAlignmentAssumption(E, V);
329 return V;
Chris Lattner7f02f722007-08-24 05:35:26 +0000330 }
Daniel Dunbar8f2926b2008-08-23 03:46:30 +0000331
Chris Lattner33793202007-08-31 22:09:40 +0000332 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stump4e7a1f72009-02-21 20:00:35 +0000333
Chris Lattner7f02f722007-08-24 05:35:26 +0000334 // Unary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000335 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000336 LValue LV = EmitLValue(E->getSubExpr());
337 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000338 }
339 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000340 LValue LV = EmitLValue(E->getSubExpr());
341 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner7f02f722007-08-24 05:35:26 +0000342 }
343 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000344 LValue LV = EmitLValue(E->getSubExpr());
345 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000346 }
347 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner8c11a652010-06-26 22:09:34 +0000348 LValue LV = EmitLValue(E->getSubExpr());
349 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner7f02f722007-08-24 05:35:26 +0000350 }
Chris Lattner8c11a652010-06-26 22:09:34 +0000351
Anton Yartsev683564a2011-02-07 02:17:30 +0000352 llvm::Value *EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
353 llvm::Value *InVal,
354 llvm::Value *NextVal,
355 bool IsInc);
356
Chris Lattner8c11a652010-06-26 22:09:34 +0000357 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
358 bool isInc, bool isPre);
359
Craig Topperd10e5c22013-07-26 06:16:11 +0000360
Chris Lattner7f02f722007-08-24 05:35:26 +0000361 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCall5808ce42011-02-03 08:15:49 +0000362 if (isa<MemberPointerType>(E->getType())) // never sugared
363 return CGF.CGM.getMemberPointerConstant(E);
364
Chris Lattner7f02f722007-08-24 05:35:26 +0000365 return EmitLValue(E->getSubExpr()).getAddress();
366 }
John McCallfd569002010-12-04 12:43:24 +0000367 Value *VisitUnaryDeref(const UnaryOperator *E) {
368 if (E->getType()->isVoidType())
369 return Visit(E->getSubExpr()); // the actual value should be unused
370 return EmitLoadOfLValue(E);
371 }
Chris Lattner7f02f722007-08-24 05:35:26 +0000372 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +0000373 // This differs from gcc, though, most likely due to a bug in gcc.
374 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +0000375 return Visit(E->getSubExpr());
376 }
377 Value *VisitUnaryMinus (const UnaryOperator *E);
378 Value *VisitUnaryNot (const UnaryOperator *E);
379 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner46f93d02007-08-24 21:20:17 +0000380 Value *VisitUnaryReal (const UnaryOperator *E);
381 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000382 Value *VisitUnaryExtension(const UnaryOperator *E) {
383 return Visit(E->getSubExpr());
384 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000385
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000386 // C++
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000387 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedmanec24b0e2011-08-14 04:50:34 +0000388 return EmitLoadOfLValue(E);
Douglas Gregor3f86ce12011-08-09 00:37:14 +0000389 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000390
Chris Lattner04421082008-04-08 04:40:51 +0000391 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
392 return Visit(DAE->getExpr());
393 }
Richard Smithc3bf52c2013-04-20 22:23:05 +0000394 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
395 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
396 return Visit(DIE->getExpr());
397 }
Anders Carlsson5f4307b2009-04-14 16:58:56 +0000398 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
399 return CGF.LoadCXXThis();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000400 }
401
John McCall4765fa02010-12-06 08:20:24 +0000402 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall1a343eb2011-11-10 08:15:53 +0000403 CGF.enterFullExpression(E);
404 CodeGenFunction::RunCleanupsScope Scope(CGF);
Stephen Hines176edba2014-12-01 14:53:08 -0800405 return Visit(E->getSubExpr());
Anders Carlsson7f6ad152009-05-19 04:48:36 +0000406 }
Anders Carlssona00703d2009-05-31 01:40:14 +0000407 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
408 return CGF.EmitCXXNewExpr(E);
409 }
Anders Carlsson60e282c2009-08-16 21:13:42 +0000410 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
411 CGF.EmitCXXDeleteExpr(E);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700412 return nullptr;
Anders Carlsson60e282c2009-08-16 21:13:42 +0000413 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000414
Stephen Hines651f13c2014-04-23 16:59:28 -0700415 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
Francois Pichetf1872372010-12-08 22:35:30 +0000416 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet6ad6f282010-12-07 00:08:36 +0000417 }
418
John Wiegley21ff2e52011-04-28 00:16:57 +0000419 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
420 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
421 }
422
John Wiegley55262202011-04-25 06:54:41 +0000423 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
424 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
425 }
426
Douglas Gregora71d8192009-09-04 17:36:40 +0000427 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
428 // C++ [expr.pseudo]p1:
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000429 // The result shall only be used as the operand for the function call
Douglas Gregora71d8192009-09-04 17:36:40 +0000430 // operator (), and the result of such a call has type void. The only
431 // effect is the evaluation of the postfix-expression before the dot or
432 // arrow.
433 CGF.EmitScalarExpr(E->getBase());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700434 return nullptr;
Douglas Gregora71d8192009-09-04 17:36:40 +0000435 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000436
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000437 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlssona40a9f32010-05-22 17:45:10 +0000438 return EmitNullValue(E->getType());
Anders Carlssonc1eb14a2009-09-15 04:39:46 +0000439 }
Anders Carlsson756b5c42009-10-30 01:42:31 +0000440
441 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
442 CGF.EmitCXXThrowExpr(E);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700443 return nullptr;
Anders Carlsson756b5c42009-10-30 01:42:31 +0000444 }
445
Sebastian Redl98294de2010-09-10 21:04:00 +0000446 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner48431f92011-04-19 22:55:03 +0000447 return Builder.getInt1(E->getValue());
Sebastian Redl98294de2010-09-10 21:04:00 +0000448 }
449
Chris Lattner7f02f722007-08-24 05:35:26 +0000450 // Binary Operators.
Chris Lattner7f02f722007-08-24 05:35:26 +0000451 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000452 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +0000453 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +0000454 case LangOptions::SOB_Defined:
455 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith9d3e2262012-08-25 00:32:28 +0000456 case LangOptions::SOB_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -0800457 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith9d3e2262012-08-25 00:32:28 +0000458 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
459 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +0000460 case LangOptions::SOB_Trapping:
461 return EmitOverflowCheckedBinOp(Ops);
462 }
463 }
Richard Smithd6396a62012-11-05 22:21:05 +0000464
Stephen Hines176edba2014-12-01 14:53:08 -0800465 if (Ops.Ty->isUnsignedIntegerType() &&
466 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietzb8540362012-11-27 15:01:55 +0000467 return EmitOverflowCheckedBinOp(Ops);
468
Duncan Sandsf177d9d2010-02-15 16:14:01 +0000469 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner87415d22009-06-17 06:36:24 +0000470 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner7f02f722007-08-24 05:35:26 +0000471 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
472 }
Mike Stump2add4732009-04-01 20:28:16 +0000473 /// Create a binary op that checks for overflow.
474 /// Currently only supports +, - and *.
475 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith7ac9ef12012-09-08 02:08:36 +0000476
Chris Lattner80230302010-09-11 21:47:09 +0000477 // Check for undefined division and modulus behaviors.
Craig Topperd10e5c22013-07-26 06:16:11 +0000478 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
Chris Lattner80230302010-09-11 21:47:09 +0000479 llvm::Value *Zero,bool isDiv);
David Tweed7a834212013-01-07 16:43:27 +0000480 // Common helper for getting how wide LHS of shift is.
481 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
Chris Lattner7f02f722007-08-24 05:35:26 +0000482 Value *EmitDiv(const BinOpInfo &Ops);
483 Value *EmitRem(const BinOpInfo &Ops);
484 Value *EmitAdd(const BinOpInfo &Ops);
485 Value *EmitSub(const BinOpInfo &Ops);
486 Value *EmitShl(const BinOpInfo &Ops);
487 Value *EmitShr(const BinOpInfo &Ops);
488 Value *EmitAnd(const BinOpInfo &Ops) {
489 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
490 }
491 Value *EmitXor(const BinOpInfo &Ops) {
492 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
493 }
494 Value *EmitOr (const BinOpInfo &Ops) {
495 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
496 }
497
Chris Lattner1f1ded92007-08-24 21:00:35 +0000498 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000499 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
500 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +0000501 Value *&Result);
Douglas Gregor6a03e342010-04-23 04:16:32 +0000502
Chris Lattner3ccf7742007-08-26 21:41:21 +0000503 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner1f1ded92007-08-24 21:00:35 +0000504 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
505
506 // Binary operators and binary compound assignment operators.
507#define HANDLEBINOP(OP) \
Chris Lattner3ccf7742007-08-26 21:41:21 +0000508 Value *VisitBin ## OP(const BinaryOperator *E) { \
509 return Emit ## OP(EmitBinOps(E)); \
510 } \
511 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
512 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner1f1ded92007-08-24 21:00:35 +0000513 }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000514 HANDLEBINOP(Mul)
515 HANDLEBINOP(Div)
516 HANDLEBINOP(Rem)
517 HANDLEBINOP(Add)
518 HANDLEBINOP(Sub)
519 HANDLEBINOP(Shl)
520 HANDLEBINOP(Shr)
521 HANDLEBINOP(And)
522 HANDLEBINOP(Xor)
523 HANDLEBINOP(Or)
Chris Lattner1f1ded92007-08-24 21:00:35 +0000524#undef HANDLEBINOP
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +0000525
Chris Lattner7f02f722007-08-24 05:35:26 +0000526 // Comparisons.
527 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
528 unsigned SICmpOpc, unsigned FCmpOpc);
529#define VISITCOMP(CODE, UI, SI, FP) \
530 Value *VisitBin##CODE(const BinaryOperator *E) { \
531 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
532 llvm::FCmpInst::FP); }
Daniel Dunbar7177dee2009-12-19 17:50:07 +0000533 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
534 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
535 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
536 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
537 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
538 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner7f02f722007-08-24 05:35:26 +0000539#undef VISITCOMP
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000540
Chris Lattner7f02f722007-08-24 05:35:26 +0000541 Value *VisitBinAssign (const BinaryOperator *E);
542
543 Value *VisitBinLAnd (const BinaryOperator *E);
544 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner7f02f722007-08-24 05:35:26 +0000545 Value *VisitBinComma (const BinaryOperator *E);
546
Eli Friedman25b825d2009-11-18 09:41:26 +0000547 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
548 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
549
Chris Lattner7f02f722007-08-24 05:35:26 +0000550 // Other Operators.
Mike Stumpdf6b68c2009-02-12 18:29:15 +0000551 Value *VisitBlockExpr(const BlockExpr *BE);
John McCall56ca35d2011-02-17 10:25:35 +0000552 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner7f02f722007-08-24 05:35:26 +0000553 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000554 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000555 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
556 return CGF.EmitObjCStringLiteral(E);
557 }
Patrick Beardeb382ec2012-04-19 00:25:12 +0000558 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
559 return CGF.EmitObjCBoxedExpr(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000560 }
561 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
562 return CGF.EmitObjCArrayLiteral(E);
563 }
564 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
565 return CGF.EmitObjCDictionaryLiteral(E);
566 }
Tanya Lattner61eee0c2011-06-04 00:47:47 +0000567 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedman276b0612011-10-11 02:20:01 +0000568 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner7f02f722007-08-24 05:35:26 +0000569};
570} // end anonymous namespace.
571
572//===----------------------------------------------------------------------===//
573// Utilities
574//===----------------------------------------------------------------------===//
575
Chris Lattner9abc84e2007-08-26 16:42:57 +0000576/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner3420d0d2007-08-26 17:25:57 +0000577/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattner9abc84e2007-08-26 16:42:57 +0000578Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCall467b27b2009-10-22 20:10:53 +0000579 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000580
John McCalldaa8e4e2010-11-15 09:13:47 +0000581 if (SrcType->isRealFloatingType())
582 return EmitFloatToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000583
John McCall0bab0cd2010-08-23 01:21:21 +0000584 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
585 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000586
Daniel Dunbard1d66bc2008-08-25 10:38:11 +0000587 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattner9abc84e2007-08-26 16:42:57 +0000588 "Unknown scalar type to convert");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000589
John McCalldaa8e4e2010-11-15 09:13:47 +0000590 if (isa<llvm::IntegerType>(Src->getType()))
591 return EmitIntToBoolConversion(Src);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000592
John McCalldaa8e4e2010-11-15 09:13:47 +0000593 assert(isa<llvm::PointerType>(Src->getType()));
594 return EmitPointerToBoolConversion(Src);
Chris Lattner9abc84e2007-08-26 16:42:57 +0000595}
596
Richard Smithb2aa66c2012-10-12 22:57:06 +0000597void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
598 QualType OrigSrcType,
599 Value *Src, QualType SrcType,
600 QualType DstType,
601 llvm::Type *DstTy) {
Stephen Hines176edba2014-12-01 14:53:08 -0800602 CodeGenFunction::SanitizerScope SanScope(&CGF);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000603 using llvm::APFloat;
604 using llvm::APSInt;
605
606 llvm::Type *SrcTy = Src->getType();
607
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700608 llvm::Value *Check = nullptr;
Richard Smithb2aa66c2012-10-12 22:57:06 +0000609 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
610 // Integer to floating-point. This can fail for unsigned short -> __half
611 // or unsigned __int128 -> float.
612 assert(DstType->isFloatingType());
613 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
614
615 APFloat LargestFloat =
616 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
617 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
618
619 bool IsExact;
620 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
621 &IsExact) != APFloat::opOK)
622 // The range of representable values of this floating point type includes
623 // all values of this integer type. Don't need an overflow check.
624 return;
625
626 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
627 if (SrcIsUnsigned)
628 Check = Builder.CreateICmpULE(Src, Max);
629 else {
630 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
631 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
632 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
633 Check = Builder.CreateAnd(GE, LE);
634 }
635 } else {
Richard Smithb2aa66c2012-10-12 22:57:06 +0000636 const llvm::fltSemantics &SrcSema =
637 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000638 if (isa<llvm::IntegerType>(DstTy)) {
Richard Smith50876452013-03-27 23:20:25 +0000639 // Floating-point to integer. This has undefined behavior if the source is
640 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
641 // to an integer).
Richard Smithb2aa66c2012-10-12 22:57:06 +0000642 unsigned Width = CGF.getContext().getIntWidth(DstType);
643 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
644
645 APSInt Min = APSInt::getMinValue(Width, Unsigned);
Richard Smith50876452013-03-27 23:20:25 +0000646 APFloat MinSrc(SrcSema, APFloat::uninitialized);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000647 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
648 APFloat::opOverflow)
649 // Don't need an overflow check for lower bound. Just check for
650 // -Inf/NaN.
Richard Smithaa624952013-03-19 00:01:12 +0000651 MinSrc = APFloat::getInf(SrcSema, true);
652 else
653 // Find the largest value which is too small to represent (before
654 // truncation toward zero).
655 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000656
657 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
Richard Smith50876452013-03-27 23:20:25 +0000658 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000659 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
660 APFloat::opOverflow)
661 // Don't need an overflow check for upper bound. Just check for
662 // +Inf/NaN.
Richard Smithaa624952013-03-19 00:01:12 +0000663 MaxSrc = APFloat::getInf(SrcSema, false);
664 else
665 // Find the smallest value which is too large to represent (before
666 // truncation toward zero).
667 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000668
Richard Smith50876452013-03-27 23:20:25 +0000669 // If we're converting from __half, convert the range to float to match
670 // the type of src.
671 if (OrigSrcType->isHalfType()) {
672 const llvm::fltSemantics &Sema =
673 CGF.getContext().getFloatTypeSemantics(SrcType);
674 bool IsInexact;
675 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
676 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
677 }
Richard Smithb2aa66c2012-10-12 22:57:06 +0000678
Richard Smithaa624952013-03-19 00:01:12 +0000679 llvm::Value *GE =
680 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
681 llvm::Value *LE =
682 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
683 Check = Builder.CreateAnd(GE, LE);
684 } else {
Richard Smith50876452013-03-27 23:20:25 +0000685 // FIXME: Maybe split this sanitizer out from float-cast-overflow.
686 //
687 // Floating-point to floating-point. This has undefined behavior if the
688 // source is not in the range of representable values of the destination
689 // type. The C and C++ standards are spectacularly unclear here. We
690 // diagnose finite out-of-range conversions, but allow infinities and NaNs
691 // to convert to the corresponding value in the smaller type.
692 //
693 // C11 Annex F gives all such conversions defined behavior for IEC 60559
694 // conforming implementations. Unfortunately, LLVM's fptrunc instruction
695 // does not.
696
697 // Converting from a lower rank to a higher rank can never have
698 // undefined behavior, since higher-rank types must have a superset
699 // of values of lower-rank types.
700 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
701 return;
702
703 assert(!OrigSrcType->isHalfType() &&
704 "should not check conversion from __half, it has the lowest rank");
705
706 const llvm::fltSemantics &DstSema =
707 CGF.getContext().getFloatTypeSemantics(DstType);
708 APFloat MinBad = APFloat::getLargest(DstSema, false);
709 APFloat MaxBad = APFloat::getInf(DstSema, false);
710
711 bool IsInexact;
712 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
713 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
714
715 Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
716 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
Richard Smithaa624952013-03-19 00:01:12 +0000717 llvm::Value *GE =
Richard Smith50876452013-03-27 23:20:25 +0000718 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
Richard Smithaa624952013-03-19 00:01:12 +0000719 llvm::Value *LE =
Richard Smith50876452013-03-27 23:20:25 +0000720 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
721 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
Richard Smithaa624952013-03-19 00:01:12 +0000722 }
Richard Smithb2aa66c2012-10-12 22:57:06 +0000723 }
724
725 // FIXME: Provide a SourceLocation.
726 llvm::Constant *StaticArgs[] = {
727 CGF.EmitCheckTypeDescriptor(OrigSrcType),
728 CGF.EmitCheckTypeDescriptor(DstType)
729 };
Stephen Hines176edba2014-12-01 14:53:08 -0800730 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
731 "float_cast_overflow", StaticArgs, OrigSrc);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000732}
733
Chris Lattner3707b252007-08-26 06:48:56 +0000734/// EmitScalarConversion - Emit a conversion from the specified type to the
735/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000736Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
737 QualType DstType) {
Chris Lattner96196622008-07-26 22:37:01 +0000738 SrcType = CGF.getContext().getCanonicalType(SrcType);
739 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000740 if (SrcType == DstType) return Src;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000741
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700742 if (DstType->isVoidType()) return nullptr;
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000743
Richard Smithb2aa66c2012-10-12 22:57:06 +0000744 llvm::Value *OrigSrc = Src;
745 QualType OrigSrcType = SrcType;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000746 llvm::Type *SrcTy = Src->getType();
747
Joey Gouly19dbb202013-01-23 11:56:20 +0000748 // If casting to/from storage-only half FP, use special intrinsics.
Stephen Hines176edba2014-12-01 14:53:08 -0800749 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
750 !CGF.getContext().getLangOpts().HalfArgsAndReturns) {
751 Src = Builder.CreateCall(
752 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
753 CGF.CGM.FloatTy),
754 Src);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000755 SrcType = CGF.getContext().FloatTy;
Chris Lattner8b418682012-02-07 00:39:47 +0000756 SrcTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000757 }
758
Chris Lattner3707b252007-08-26 06:48:56 +0000759 // Handle conversions to bool first, they are special: comparisons against 0.
Chris Lattnered70f0a2007-08-26 16:52:28 +0000760 if (DstType->isBooleanType())
761 return EmitConversionToBool(Src, SrcType);
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000762
Chris Lattner2acc6e32011-07-18 04:24:23 +0000763 llvm::Type *DstTy = ConvertType(DstType);
Chris Lattner3707b252007-08-26 06:48:56 +0000764
765 // Ignore conversions like int -> uint.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000766 if (SrcTy == DstTy)
Chris Lattner3707b252007-08-26 06:48:56 +0000767 return Src;
768
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000769 // Handle pointer conversions next: pointers can only be converted to/from
770 // other pointers and integers. Check for pointer types in terms of LLVM, as
771 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar270cc662008-08-25 09:51:32 +0000772 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000773 // The source value may be an integer, or a pointer.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000774 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3707b252007-08-26 06:48:56 +0000775 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson191dfe92009-09-12 04:57:16 +0000776
Chris Lattner3707b252007-08-26 06:48:56 +0000777 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman25615422009-03-04 04:02:35 +0000778 // First, convert to the correct width so that we control the kind of
779 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000780 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +0000781 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman25615422009-03-04 04:02:35 +0000782 llvm::Value* IntResult =
783 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
784 // Then, cast to pointer.
785 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000786 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000787
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000788 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3707b252007-08-26 06:48:56 +0000789 // Must be an ptr to int cast.
790 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlsson50b5a302007-10-31 23:18:02 +0000791 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000792 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000793
Nate Begeman213541a2008-04-18 23:10:10 +0000794 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman2ef13e52009-08-10 23:49:36 +0000795 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000796 // Cast the scalar to element type
John McCall183700f2009-09-21 23:43:11 +0000797 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000798 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
799
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000800 // Splat the element across to all elements
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000801 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Benjamin Kramer0b227082013-01-01 20:08:10 +0000802 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Nate Begeman6fe7c8a2009-01-18 06:42:49 +0000803 }
Nate Begeman4119d1a2007-12-30 02:59:45 +0000804
Chris Lattner3b1ae002008-02-02 04:51:41 +0000805 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000806 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner3b1ae002008-02-02 04:51:41 +0000807 isa<llvm::VectorType>(DstTy))
Anders Carlsson7019a9e2007-12-05 07:36:10 +0000808 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000809
Chris Lattner3707b252007-08-26 06:48:56 +0000810 // Finally, we have the arithmetic types: real int/float.
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700811 Value *Res = nullptr;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000812 llvm::Type *ResTy = DstTy;
813
Richard Smithb2aa66c2012-10-12 22:57:06 +0000814 // An overflowing conversion has undefined behavior if either the source type
815 // or the destination type is a floating-point type.
Stephen Hines176edba2014-12-01 14:53:08 -0800816 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
Richard Smithb2aa66c2012-10-12 22:57:06 +0000817 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
Will Dietz4f45bc02013-01-18 11:30:38 +0000818 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType,
819 DstTy);
Richard Smithb2aa66c2012-10-12 22:57:06 +0000820
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000821 // Cast to half via float
Stephen Hines176edba2014-12-01 14:53:08 -0800822 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
823 !CGF.getContext().getLangOpts().HalfArgsAndReturns)
Chris Lattner8b418682012-02-07 00:39:47 +0000824 DstTy = CGF.FloatTy;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000825
826 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor575a1c92011-05-20 16:38:50 +0000827 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000828 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000829 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000830 else if (InputSigned)
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000831 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000832 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000833 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
834 } else if (isa<llvm::IntegerType>(DstTy)) {
835 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor575a1c92011-05-20 16:38:50 +0000836 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000837 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonb5ce0972007-12-26 18:20:19 +0000838 else
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000839 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
840 } else {
841 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
842 "Unknown real conversion");
843 if (DstTy->getTypeID() < SrcTy->getTypeID())
844 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
845 else
846 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3707b252007-08-26 06:48:56 +0000847 }
848
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000849 if (DstTy != ResTy) {
850 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
Stephen Hines176edba2014-12-01 14:53:08 -0800851 Res = Builder.CreateCall(
852 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
853 Res);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +0000854 }
855
856 return Res;
Chris Lattner3707b252007-08-26 06:48:56 +0000857}
858
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000859/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
860/// type to the specified destination type, where the destination type is an
861/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000862Value *ScalarExprEmitter::
863EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
864 QualType SrcTy, QualType DstTy) {
Chris Lattnered70f0a2007-08-26 16:52:28 +0000865 // Get the source element type.
John McCall9d232c82013-03-07 21:37:08 +0000866 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000867
Chris Lattnered70f0a2007-08-26 16:52:28 +0000868 // Handle conversions to bool first, they are special: comparisons against 0.
869 if (DstTy->isBooleanType()) {
870 // Complex != 0 -> (Real != 0) | (Imag != 0)
871 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
872 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
873 return Builder.CreateOr(Src.first, Src.second, "tobool");
874 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000875
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000876 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
877 // the imaginary part of the complex value is discarded and the value of the
878 // real part is converted according to the conversion rules for the
Mike Stumpdb52dcd2009-09-09 13:00:44 +0000879 // corresponding real type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000880 return EmitScalarConversion(Src.first, SrcTy, DstTy);
881}
882
Anders Carlssona40a9f32010-05-22 17:45:10 +0000883Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
Richard Smith0dbe2fb2012-12-21 03:17:28 +0000884 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
Anders Carlssona40a9f32010-05-22 17:45:10 +0000885}
Chris Lattner4f1a7b32007-08-26 16:34:22 +0000886
Richard Smith4def70d2012-10-09 19:52:38 +0000887/// \brief Emit a sanitization check for the given "binary" operation (which
888/// might actually be a unary increment which has been lowered to a binary
Stephen Hines176edba2014-12-01 14:53:08 -0800889/// operation). The check passes if all values in \p Checks (which are \c i1),
890/// are \c true.
891void ScalarExprEmitter::EmitBinOpCheck(
892 ArrayRef<std::pair<Value *, SanitizerKind>> Checks, const BinOpInfo &Info) {
893 assert(CGF.IsSanitizerScope);
Richard Smith4def70d2012-10-09 19:52:38 +0000894 StringRef CheckName;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000895 SmallVector<llvm::Constant *, 4> StaticData;
896 SmallVector<llvm::Value *, 2> DynamicData;
Richard Smith4def70d2012-10-09 19:52:38 +0000897
898 BinaryOperatorKind Opcode = Info.Opcode;
899 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
900 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
901
902 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
903 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
904 if (UO && UO->getOpcode() == UO_Minus) {
905 CheckName = "negate_overflow";
906 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
907 DynamicData.push_back(Info.RHS);
908 } else {
909 if (BinaryOperator::isShiftOp(Opcode)) {
910 // Shift LHS negative or too large, or RHS out of bounds.
911 CheckName = "shift_out_of_bounds";
912 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
913 StaticData.push_back(
914 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
915 StaticData.push_back(
916 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
917 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
918 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
919 CheckName = "divrem_overflow";
Will Dietz822023a2013-01-07 22:25:52 +0000920 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smith4def70d2012-10-09 19:52:38 +0000921 } else {
Stephen Hines176edba2014-12-01 14:53:08 -0800922 // Arithmetic overflow (+, -, *).
Richard Smith4def70d2012-10-09 19:52:38 +0000923 switch (Opcode) {
924 case BO_Add: CheckName = "add_overflow"; break;
925 case BO_Sub: CheckName = "sub_overflow"; break;
926 case BO_Mul: CheckName = "mul_overflow"; break;
927 default: llvm_unreachable("unexpected opcode for bin op check");
928 }
Will Dietz822023a2013-01-07 22:25:52 +0000929 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smith4def70d2012-10-09 19:52:38 +0000930 }
931 DynamicData.push_back(Info.LHS);
932 DynamicData.push_back(Info.RHS);
933 }
934
Stephen Hines176edba2014-12-01 14:53:08 -0800935 CGF.EmitCheck(Checks, CheckName, StaticData, DynamicData);
Richard Smith4def70d2012-10-09 19:52:38 +0000936}
937
Chris Lattner7f02f722007-08-24 05:35:26 +0000938//===----------------------------------------------------------------------===//
939// Visitor Methods
940//===----------------------------------------------------------------------===//
941
942Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbar488e9932008-08-16 00:56:44 +0000943 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner7f02f722007-08-24 05:35:26 +0000944 if (E->getType()->isVoidType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700945 return nullptr;
Owen Anderson03e20502009-07-30 23:11:26 +0000946 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner7f02f722007-08-24 05:35:26 +0000947}
948
Eli Friedmand38617c2008-05-14 19:38:39 +0000949Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begeman37b6a572010-06-08 00:16:34 +0000950 // Vector Mask Case
Craig Topperd10e5c22013-07-26 06:16:11 +0000951 if (E->getNumSubExprs() == 2 ||
Rafael Espindola3f4cb122010-06-09 02:17:08 +0000952 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner77b89b82010-06-27 07:15:29 +0000953 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
954 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
955 Value *Mask;
Craig Topperd10e5c22013-07-26 06:16:11 +0000956
Chris Lattner2acc6e32011-07-18 04:24:23 +0000957 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000958 unsigned LHSElts = LTy->getNumElements();
959
960 if (E->getNumSubExprs() == 3) {
961 Mask = CGF.EmitScalarExpr(E->getExpr(2));
Craig Topperd10e5c22013-07-26 06:16:11 +0000962
Nate Begeman37b6a572010-06-08 00:16:34 +0000963 // Shuffle LHS & RHS into one input vector.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000964 SmallVector<llvm::Constant*, 32> concat;
Nate Begeman37b6a572010-06-08 00:16:34 +0000965 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner48431f92011-04-19 22:55:03 +0000966 concat.push_back(Builder.getInt32(2*i));
967 concat.push_back(Builder.getInt32(2*i+1));
Nate Begeman37b6a572010-06-08 00:16:34 +0000968 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000969
Chris Lattnerfb018d12011-02-15 00:14:06 +0000970 Value* CV = llvm::ConstantVector::get(concat);
Nate Begeman37b6a572010-06-08 00:16:34 +0000971 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
972 LHSElts *= 2;
973 } else {
974 Mask = RHS;
975 }
Craig Topperd10e5c22013-07-26 06:16:11 +0000976
Chris Lattner2acc6e32011-07-18 04:24:23 +0000977 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Nate Begeman37b6a572010-06-08 00:16:34 +0000978 llvm::Constant* EltMask;
Craig Topperd10e5c22013-07-26 06:16:11 +0000979
Craig Topper2f665122013-08-01 06:42:40 +0000980 EltMask = llvm::ConstantInt::get(MTy->getElementType(),
981 llvm::NextPowerOf2(LHSElts-1)-1);
Craig Topperd10e5c22013-07-26 06:16:11 +0000982
Nate Begeman37b6a572010-06-08 00:16:34 +0000983 // Mask off the high bits of each shuffle index.
Chris Lattner2ce88422012-01-25 05:34:41 +0000984 Value *MaskBits = llvm::ConstantVector::getSplat(MTy->getNumElements(),
985 EltMask);
Nate Begeman37b6a572010-06-08 00:16:34 +0000986 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
Craig Topperd10e5c22013-07-26 06:16:11 +0000987
Nate Begeman37b6a572010-06-08 00:16:34 +0000988 // newv = undef
989 // mask = mask & maskbits
990 // for each elt
991 // n = extract mask i
992 // x = extract val n
993 // newv = insert newv, x, i
Chris Lattner2acc6e32011-07-18 04:24:23 +0000994 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Craig Topper34d55e12013-07-27 05:00:42 +0000995 MTy->getNumElements());
Nate Begeman37b6a572010-06-08 00:16:34 +0000996 Value* NewV = llvm::UndefValue::get(RTy);
997 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Stephen Hinesc568f1e2014-07-21 00:47:37 -0700998 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
Eli Friedman87b9c032012-04-05 21:48:40 +0000999 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Craig Topperd10e5c22013-07-26 06:16:11 +00001000
Nate Begeman37b6a572010-06-08 00:16:34 +00001001 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman87b9c032012-04-05 21:48:40 +00001002 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begeman37b6a572010-06-08 00:16:34 +00001003 }
1004 return NewV;
Eli Friedmand38617c2008-05-14 19:38:39 +00001005 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001006
Eli Friedmand38617c2008-05-14 19:38:39 +00001007 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1008 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Craig Topperd10e5c22013-07-26 06:16:11 +00001009
Chris Lattner5f9e2722011-07-23 10:55:15 +00001010 SmallVector<llvm::Constant*, 32> indices;
Craig Topper72c422c2013-08-01 04:51:48 +00001011 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
Craig Topper6f4f8082013-08-03 17:40:38 +00001012 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1013 // Check for -1 and output it as undef in the IR.
1014 if (Idx.isSigned() && Idx.isAllOnesValue())
1015 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1016 else
1017 indices.push_back(Builder.getInt32(Idx.getZExtValue()));
Nate Begeman37b6a572010-06-08 00:16:34 +00001018 }
1019
Chris Lattnerfb018d12011-02-15 00:14:06 +00001020 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmand38617c2008-05-14 19:38:39 +00001021 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1022}
Hal Finkel414a1bd2013-09-18 03:29:45 +00001023
1024Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1025 QualType SrcType = E->getSrcExpr()->getType(),
1026 DstType = E->getType();
1027
1028 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1029
1030 SrcType = CGF.getContext().getCanonicalType(SrcType);
1031 DstType = CGF.getContext().getCanonicalType(DstType);
1032 if (SrcType == DstType) return Src;
1033
1034 assert(SrcType->isVectorType() &&
1035 "ConvertVector source type must be a vector");
1036 assert(DstType->isVectorType() &&
1037 "ConvertVector destination type must be a vector");
1038
1039 llvm::Type *SrcTy = Src->getType();
1040 llvm::Type *DstTy = ConvertType(DstType);
1041
1042 // Ignore conversions like int -> uint.
1043 if (SrcTy == DstTy)
1044 return Src;
1045
1046 QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(),
1047 DstEltType = DstType->getAs<VectorType>()->getElementType();
1048
1049 assert(SrcTy->isVectorTy() &&
1050 "ConvertVector source IR type must be a vector");
1051 assert(DstTy->isVectorTy() &&
1052 "ConvertVector destination IR type must be a vector");
1053
1054 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1055 *DstEltTy = DstTy->getVectorElementType();
1056
1057 if (DstEltType->isBooleanType()) {
1058 assert((SrcEltTy->isFloatingPointTy() ||
1059 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1060
1061 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1062 if (SrcEltTy->isFloatingPointTy()) {
1063 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1064 } else {
1065 return Builder.CreateICmpNE(Src, Zero, "tobool");
1066 }
1067 }
1068
1069 // We have the arithmetic types: real int/float.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001070 Value *Res = nullptr;
Hal Finkel414a1bd2013-09-18 03:29:45 +00001071
1072 if (isa<llvm::IntegerType>(SrcEltTy)) {
1073 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1074 if (isa<llvm::IntegerType>(DstEltTy))
1075 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1076 else if (InputSigned)
1077 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1078 else
1079 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1080 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1081 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1082 if (DstEltType->isSignedIntegerOrEnumerationType())
1083 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1084 else
1085 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1086 } else {
1087 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1088 "Unknown real conversion");
1089 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1090 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1091 else
1092 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1093 }
1094
1095 return Res;
1096}
1097
Eli Friedman28665272009-11-26 03:22:21 +00001098Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith80d4b552011-12-28 19:48:30 +00001099 llvm::APSInt Value;
1100 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedman28665272009-11-26 03:22:21 +00001101 if (E->isArrow())
1102 CGF.EmitScalarExpr(E->getBase());
1103 else
1104 EmitLValue(E->getBase());
Richard Smith80d4b552011-12-28 19:48:30 +00001105 return Builder.getInt(Value);
Eli Friedman28665272009-11-26 03:22:21 +00001106 }
Devang Patel78ba3d42010-10-04 21:46:04 +00001107
Eli Friedman28665272009-11-26 03:22:21 +00001108 return EmitLoadOfLValue(E);
1109}
Eli Friedmand38617c2008-05-14 19:38:39 +00001110
Chris Lattner7f02f722007-08-24 05:35:26 +00001111Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001112 TestAndClearIgnoreResultAssign();
1113
Chris Lattner7f02f722007-08-24 05:35:26 +00001114 // Emit subscript expressions in rvalue context's. For most cases, this just
1115 // loads the lvalue formed by the subscript expr. However, we have to be
1116 // careful, because the base of a vector subscript is occasionally an rvalue,
1117 // so we can't get it as an lvalue.
1118 if (!E->getBase()->getType()->isVectorType())
1119 return EmitLoadOfLValue(E);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001120
Chris Lattner7f02f722007-08-24 05:35:26 +00001121 // Handle the vector case. The base must be a vector, the index must be an
1122 // integer value.
1123 Value *Base = Visit(E->getBase());
1124 Value *Idx = Visit(E->getIdx());
Richard Smitha0a628f2013-02-23 02:53:19 +00001125 QualType IdxTy = E->getIdx()->getType();
1126
Stephen Hines176edba2014-12-01 14:53:08 -08001127 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smitha0a628f2013-02-23 02:53:19 +00001128 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1129
Chris Lattner7f02f722007-08-24 05:35:26 +00001130 return Builder.CreateExtractElement(Base, Idx, "vecext");
1131}
1132
Nate Begeman0533b302009-10-18 20:10:40 +00001133static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001134 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman0533b302009-10-18 20:10:40 +00001135 int MV = SVI->getMaskValue(Idx);
Craig Topperd10e5c22013-07-26 06:16:11 +00001136 if (MV == -1)
Nate Begeman0533b302009-10-18 20:10:40 +00001137 return llvm::UndefValue::get(I32Ty);
1138 return llvm::ConstantInt::get(I32Ty, Off+MV);
1139}
1140
1141Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1142 bool Ignore = TestAndClearIgnoreResultAssign();
1143 (void)Ignore;
1144 assert (Ignore == false && "init list ignored");
1145 unsigned NumInitElements = E->getNumInits();
Craig Topperd10e5c22013-07-26 06:16:11 +00001146
Nate Begeman0533b302009-10-18 20:10:40 +00001147 if (E->hadArrayRangeDesignator())
1148 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Craig Topperd10e5c22013-07-26 06:16:11 +00001149
Chris Lattner2acc6e32011-07-18 04:24:23 +00001150 llvm::VectorType *VType =
Nate Begeman0533b302009-10-18 20:10:40 +00001151 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
Craig Topperd10e5c22013-07-26 06:16:11 +00001152
Sebastian Redlcea8d962011-09-24 17:48:14 +00001153 if (!VType) {
1154 if (NumInitElements == 0) {
1155 // C++11 value-initialization for the scalar.
1156 return EmitNullValue(E->getType());
1157 }
1158 // We have a scalar in braces. Just use the first element.
Nate Begeman0533b302009-10-18 20:10:40 +00001159 return Visit(E->getInit(0));
Sebastian Redlcea8d962011-09-24 17:48:14 +00001160 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001161
Nate Begeman0533b302009-10-18 20:10:40 +00001162 unsigned ResElts = VType->getNumElements();
Craig Topperd10e5c22013-07-26 06:16:11 +00001163
1164 // Loop over initializers collecting the Value for each, and remembering
Nate Begeman0533b302009-10-18 20:10:40 +00001165 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1166 // us to fold the shuffle for the swizzle into the shuffle for the vector
1167 // initializer, since LLVM optimizers generally do not want to touch
1168 // shuffles.
1169 unsigned CurIdx = 0;
1170 bool VIsUndefShuffle = false;
1171 llvm::Value *V = llvm::UndefValue::get(VType);
1172 for (unsigned i = 0; i != NumInitElements; ++i) {
1173 Expr *IE = E->getInit(i);
1174 Value *Init = Visit(IE);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001175 SmallVector<llvm::Constant*, 16> Args;
Craig Topperd10e5c22013-07-26 06:16:11 +00001176
Chris Lattner2acc6e32011-07-18 04:24:23 +00001177 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001178
Nate Begeman0533b302009-10-18 20:10:40 +00001179 // Handle scalar elements. If the scalar initializer is actually one
Craig Topperd10e5c22013-07-26 06:16:11 +00001180 // element of a different vector of the same width, use shuffle instead of
Nate Begeman0533b302009-10-18 20:10:40 +00001181 // extract+insert.
1182 if (!VVT) {
1183 if (isa<ExtVectorElementExpr>(IE)) {
1184 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1185
1186 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1187 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001188 Value *LHS = nullptr, *RHS = nullptr;
Nate Begeman0533b302009-10-18 20:10:40 +00001189 if (CurIdx == 0) {
1190 // insert into undef -> shuffle (src, undef)
1191 Args.push_back(C);
Benjamin Kramer14c59822012-02-14 12:06:21 +00001192 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001193
1194 LHS = EI->getVectorOperand();
1195 RHS = V;
1196 VIsUndefShuffle = true;
1197 } else if (VIsUndefShuffle) {
1198 // insert into undefshuffle && size match -> shuffle (v, src)
1199 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1200 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +00001201 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner48431f92011-04-19 22:55:03 +00001202 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001203 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1204
Nate Begeman0533b302009-10-18 20:10:40 +00001205 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1206 RHS = EI->getVectorOperand();
1207 VIsUndefShuffle = false;
1208 }
1209 if (!Args.empty()) {
Chris Lattnerfb018d12011-02-15 00:14:06 +00001210 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001211 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1212 ++CurIdx;
1213 continue;
1214 }
1215 }
1216 }
Chris Lattner48431f92011-04-19 22:55:03 +00001217 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1218 "vecinit");
Nate Begeman0533b302009-10-18 20:10:40 +00001219 VIsUndefShuffle = false;
1220 ++CurIdx;
1221 continue;
1222 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001223
Nate Begeman0533b302009-10-18 20:10:40 +00001224 unsigned InitElts = VVT->getNumElements();
1225
Craig Topperd10e5c22013-07-26 06:16:11 +00001226 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
Nate Begeman0533b302009-10-18 20:10:40 +00001227 // input is the same width as the vector being constructed, generate an
1228 // optimized shuffle of the swizzle input into the result.
Nate Begemana99f0832009-10-25 02:26:01 +00001229 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman0533b302009-10-18 20:10:40 +00001230 if (isa<ExtVectorElementExpr>(IE)) {
1231 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1232 Value *SVOp = SVI->getOperand(0);
Chris Lattner2acc6e32011-07-18 04:24:23 +00001233 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001234
Nate Begeman0533b302009-10-18 20:10:40 +00001235 if (OpTy->getNumElements() == ResElts) {
Nate Begeman0533b302009-10-18 20:10:40 +00001236 for (unsigned j = 0; j != CurIdx; ++j) {
1237 // If the current vector initializer is a shuffle with undef, merge
1238 // this shuffle directly into it.
1239 if (VIsUndefShuffle) {
1240 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner77b89b82010-06-27 07:15:29 +00001241 CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001242 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001243 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +00001244 }
1245 }
1246 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner77b89b82010-06-27 07:15:29 +00001247 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001248 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001249
1250 if (VIsUndefShuffle)
1251 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1252
1253 Init = SVOp;
1254 }
1255 }
1256
1257 // Extend init to result vector length, and then shuffle its contribution
1258 // to the vector initializer into V.
1259 if (Args.empty()) {
1260 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001261 Args.push_back(Builder.getInt32(j));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001262 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattnerfb018d12011-02-15 00:14:06 +00001263 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001264 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemana99f0832009-10-25 02:26:01 +00001265 Mask, "vext");
Nate Begeman0533b302009-10-18 20:10:40 +00001266
1267 Args.clear();
1268 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001269 Args.push_back(Builder.getInt32(j));
Nate Begeman0533b302009-10-18 20:10:40 +00001270 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner48431f92011-04-19 22:55:03 +00001271 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer14c59822012-02-14 12:06:21 +00001272 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman0533b302009-10-18 20:10:40 +00001273 }
1274
1275 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1276 // merging subsequent shuffles into this one.
1277 if (CurIdx == 0)
1278 std::swap(V, Init);
Chris Lattnerfb018d12011-02-15 00:14:06 +00001279 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman0533b302009-10-18 20:10:40 +00001280 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1281 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1282 CurIdx += InitElts;
1283 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001284
Nate Begeman0533b302009-10-18 20:10:40 +00001285 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1286 // Emit remaining default initializers.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001287 llvm::Type *EltTy = VType->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00001288
Nate Begeman0533b302009-10-18 20:10:40 +00001289 // Emit remaining default initializers
1290 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner48431f92011-04-19 22:55:03 +00001291 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman0533b302009-10-18 20:10:40 +00001292 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1293 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1294 }
1295 return V;
1296}
1297
Anders Carlssona3697c92009-11-23 17:57:54 +00001298static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1299 const Expr *E = CE->getSubExpr();
John McCall23cba802010-03-30 23:58:03 +00001300
John McCall2de56d12010-08-25 11:45:40 +00001301 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCall23cba802010-03-30 23:58:03 +00001302 return false;
Craig Topperd10e5c22013-07-26 06:16:11 +00001303
Anders Carlssona3697c92009-11-23 17:57:54 +00001304 if (isa<CXXThisExpr>(E)) {
1305 // We always assume that 'this' is never null.
1306 return false;
1307 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001308
Anders Carlssona3697c92009-11-23 17:57:54 +00001309 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00001310 // And that glvalue casts are never null.
John McCall5baba9d2010-08-25 10:28:54 +00001311 if (ICE->getValueKind() != VK_RValue)
Anders Carlssona3697c92009-11-23 17:57:54 +00001312 return false;
1313 }
1314
1315 return true;
1316}
1317
Chris Lattner7f02f722007-08-24 05:35:26 +00001318// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1319// have to handle a more broad range of conversions than explicit casts, as they
1320// handle things like function to ptr-to-function decay etc.
John McCallbc8d40d2011-06-24 21:55:10 +00001321Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmand8889622009-11-27 04:41:50 +00001322 Expr *E = CE->getSubExpr();
Anders Carlsson592a2bb2009-09-22 22:00:46 +00001323 QualType DestTy = CE->getType();
John McCall2de56d12010-08-25 11:45:40 +00001324 CastKind Kind = CE->getCastKind();
Craig Topperd10e5c22013-07-26 06:16:11 +00001325
Mike Stump7f79f9b2009-05-29 15:46:01 +00001326 if (!DestTy->isVoidType())
1327 TestAndClearIgnoreResultAssign();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001328
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001329 // Since almost all cast kinds apply to scalars, this switch doesn't have
1330 // a default case, so the compiler will warn on a missing case. The cases
1331 // are in the same order as in the CastKind enum.
Anders Carlssone9776242009-08-24 18:26:39 +00001332 switch (Kind) {
John McCalldaa8e4e2010-11-15 09:13:47 +00001333 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedmana6c66ce2012-08-31 00:14:07 +00001334 case CK_BuiltinFnToFnPtr:
1335 llvm_unreachable("builtin functions are handled elsewhere");
1336
Craig Topperd10e5c22013-07-26 06:16:11 +00001337 case CK_LValueBitCast:
John McCall2de56d12010-08-25 11:45:40 +00001338 case CK_ObjCObjectLValueCast: {
Douglas Gregore39a3892010-07-13 23:17:26 +00001339 Value *V = EmitLValue(E).getAddress();
Craig Topperd10e5c22013-07-26 06:16:11 +00001340 V = Builder.CreateBitCast(V,
Douglas Gregore39a3892010-07-13 23:17:26 +00001341 ConvertType(CGF.getContext().getPointerType(DestTy)));
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001342 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy),
1343 CE->getExprLoc());
Douglas Gregore39a3892010-07-13 23:17:26 +00001344 }
John McCalldc05b112011-09-10 01:16:55 +00001345
John McCall1d9b3b22011-09-09 05:25:32 +00001346 case CK_CPointerToObjCPointerCast:
1347 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00001348 case CK_AnyPointerToBlockPointerCast:
1349 case CK_BitCast: {
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001350 Value *Src = Visit(const_cast<Expr*>(E));
Stephen Hines651f13c2014-04-23 16:59:28 -07001351 llvm::Type *SrcTy = Src->getType();
1352 llvm::Type *DstTy = ConvertType(DestTy);
1353 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
1354 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001355 llvm_unreachable("wrong cast for pointers in different address spaces"
1356 "(must be an address space cast)!");
Stephen Hines651f13c2014-04-23 16:59:28 -07001357 }
1358 return Builder.CreateBitCast(Src, DstTy);
1359 }
1360 case CK_AddressSpaceConversion: {
1361 Value *Src = Visit(const_cast<Expr*>(E));
1362 return Builder.CreateAddrSpaceCast(Src, ConvertType(DestTy));
Anders Carlssoncb3c3082009-09-01 20:52:42 +00001363 }
David Chisnall7a7ee302012-01-16 17:27:18 +00001364 case CK_AtomicToNonAtomic:
1365 case CK_NonAtomicToAtomic:
John McCall2de56d12010-08-25 11:45:40 +00001366 case CK_NoOp:
1367 case CK_UserDefinedConversion:
Eli Friedmanad35a832009-11-16 21:33:53 +00001368 return Visit(const_cast<Expr*>(E));
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001369
John McCall2de56d12010-08-25 11:45:40 +00001370 case CK_BaseToDerived: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001371 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1372 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1373
Richard Smithc7648302013-02-13 21:18:23 +00001374 llvm::Value *V = Visit(E);
1375
Filipe Cabecinhas8593e782013-08-08 01:08:17 +00001376 llvm::Value *Derived =
1377 CGF.GetAddressOfDerivedClass(V, DerivedClassDecl,
1378 CE->path_begin(), CE->path_end(),
1379 ShouldNullCheckClassCastValue(CE));
1380
Richard Smithc7648302013-02-13 21:18:23 +00001381 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
1382 // performed and the object is not of the derived type.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001383 if (CGF.sanitizePerformTypeCheck())
Richard Smithc7648302013-02-13 21:18:23 +00001384 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
Filipe Cabecinhas8593e782013-08-08 01:08:17 +00001385 Derived, DestTy->getPointeeType());
Richard Smithc7648302013-02-13 21:18:23 +00001386
Filipe Cabecinhas8593e782013-08-08 01:08:17 +00001387 return Derived;
Anders Carlssona3697c92009-11-23 17:57:54 +00001388 }
John McCall2de56d12010-08-25 11:45:40 +00001389 case CK_UncheckedDerivedToBase:
1390 case CK_DerivedToBase: {
Jordan Rose041ce8e2012-10-03 01:08:28 +00001391 const CXXRecordDecl *DerivedClassDecl =
1392 E->getType()->getPointeeCXXRecordDecl();
1393 assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
Anders Carlsson191dfe92009-09-12 04:57:16 +00001394
Stephen Hines176edba2014-12-01 14:53:08 -08001395 return CGF.GetAddressOfBaseClass(
1396 Visit(E), DerivedClassDecl, CE->path_begin(), CE->path_end(),
1397 ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
Anders Carlsson191dfe92009-09-12 04:57:16 +00001398 }
Anders Carlsson575b3742011-04-11 02:03:26 +00001399 case CK_Dynamic: {
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001400 Value *V = Visit(const_cast<Expr*>(E));
1401 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1402 return CGF.EmitDynamicCast(V, DCE);
1403 }
Eli Friedmand8889622009-11-27 04:41:50 +00001404
John McCall2de56d12010-08-25 11:45:40 +00001405 case CK_ArrayToPointerDecay: {
Eli Friedmanad35a832009-11-16 21:33:53 +00001406 assert(E->getType()->isArrayType() &&
1407 "Array to pointer decay must have array source type!");
1408
1409 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1410
1411 // Note that VLA pointers are always decayed, so we don't need to do
1412 // anything here.
1413 if (!E->getType()->isVariableArrayType()) {
1414 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001415 V = CGF.Builder.CreatePointerCast(
1416 V, ConvertType(E->getType())->getPointerTo(
1417 V->getType()->getPointerAddressSpace()));
1418
1419 assert(isa<llvm::ArrayType>(V->getType()->getPointerElementType()) &&
Eli Friedmanad35a832009-11-16 21:33:53 +00001420 "Expected pointer to array");
1421 V = Builder.CreateStructGEP(V, 0, "arraydecay");
1422 }
1423
Chris Lattner410b12e2011-07-20 04:31:01 +00001424 // Make sure the array decay ends up being the right type. This matters if
1425 // the array type was of an incomplete type.
Stephen Hines651f13c2014-04-23 16:59:28 -07001426 return CGF.Builder.CreatePointerCast(V, ConvertType(CE->getType()));
Eli Friedmanad35a832009-11-16 21:33:53 +00001427 }
John McCall2de56d12010-08-25 11:45:40 +00001428 case CK_FunctionToPointerDecay:
Eli Friedmanad35a832009-11-16 21:33:53 +00001429 return EmitLValue(E).getAddress();
1430
John McCall404cd162010-11-13 01:35:44 +00001431 case CK_NullToPointer:
1432 if (MustVisitNullValue(E))
1433 (void) Visit(E);
1434
1435 return llvm::ConstantPointerNull::get(
1436 cast<llvm::PointerType>(ConvertType(DestTy)));
1437
John McCall2de56d12010-08-25 11:45:40 +00001438 case CK_NullToMemberPointer: {
John McCall404cd162010-11-13 01:35:44 +00001439 if (MustVisitNullValue(E))
John McCalld608cdb2010-08-22 10:59:02 +00001440 (void) Visit(E);
1441
John McCall0bab0cd2010-08-23 01:21:21 +00001442 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1443 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1444 }
Anders Carlsson191dfe92009-09-12 04:57:16 +00001445
John McCall4d4e5c12012-02-15 01:22:51 +00001446 case CK_ReinterpretMemberPointer:
John McCall2de56d12010-08-25 11:45:40 +00001447 case CK_BaseToDerivedMemberPointer:
1448 case CK_DerivedToBaseMemberPointer: {
Eli Friedmand8889622009-11-27 04:41:50 +00001449 Value *Src = Visit(E);
Craig Topperd10e5c22013-07-26 06:16:11 +00001450
John McCalld608cdb2010-08-22 10:59:02 +00001451 // Note that the AST doesn't distinguish between checked and
1452 // unchecked member pointer conversions, so we always have to
1453 // implement checked conversions here. This is inefficient when
1454 // actual control flow may be required in order to perform the
1455 // check, which it is for data member pointers (but not member
1456 // function pointers on Itanium and ARM).
John McCall0bab0cd2010-08-23 01:21:21 +00001457 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmand8889622009-11-27 04:41:50 +00001458 }
John McCallf85e1932011-06-15 23:02:42 +00001459
John McCall33e56f32011-09-10 06:18:15 +00001460 case CK_ARCProduceObject:
John McCallf85e1932011-06-15 23:02:42 +00001461 return CGF.EmitARCRetainScalarExpr(E);
John McCall33e56f32011-09-10 06:18:15 +00001462 case CK_ARCConsumeObject:
John McCallf85e1932011-06-15 23:02:42 +00001463 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall33e56f32011-09-10 06:18:15 +00001464 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00001465 llvm::Value *value = Visit(E);
1466 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1467 return CGF.EmitObjCConsumeObject(E->getType(), value);
1468 }
John McCall348f16f2011-10-04 06:23:45 +00001469 case CK_ARCExtendBlockObject:
1470 return CGF.EmitARCExtendBlockObject(E);
John McCallf85e1932011-06-15 23:02:42 +00001471
Douglas Gregorac1303e2012-02-22 05:02:47 +00001472 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmancae40c42012-02-28 01:08:45 +00001473 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001474
John McCall2bb5d002010-11-13 09:02:35 +00001475 case CK_FloatingRealToComplex:
1476 case CK_FloatingComplexCast:
1477 case CK_IntegralRealToComplex:
1478 case CK_IntegralComplexCast:
John McCallf3ea8cf2010-11-14 08:17:51 +00001479 case CK_IntegralComplexToFloatingComplex:
1480 case CK_FloatingComplexToIntegralComplex:
John McCall2de56d12010-08-25 11:45:40 +00001481 case CK_ConstructorConversion:
John McCall61ad0e62010-11-16 06:21:14 +00001482 case CK_ToUnion:
1483 llvm_unreachable("scalar cast to non-scalar value");
John McCallf6a16482010-12-04 03:47:34 +00001484
John McCall0ae287a2010-12-01 04:43:34 +00001485 case CK_LValueToRValue:
1486 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCallf6a16482010-12-04 03:47:34 +00001487 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCall0ae287a2010-12-01 04:43:34 +00001488 return Visit(const_cast<Expr*>(E));
Eli Friedman8c3e7e72009-11-27 02:07:44 +00001489
John McCall2de56d12010-08-25 11:45:40 +00001490 case CK_IntegralToPointer: {
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001491 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001492
Anders Carlsson82debc72009-10-18 18:12:03 +00001493 // First, convert to the correct width so that we control the kind of
1494 // extension.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001495 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor575a1c92011-05-20 16:38:50 +00001496 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson82debc72009-10-18 18:12:03 +00001497 llvm::Value* IntResult =
1498 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001499
Anders Carlsson82debc72009-10-18 18:12:03 +00001500 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7f9e6462009-09-15 04:48:33 +00001501 }
Eli Friedman65949422011-06-25 02:58:47 +00001502 case CK_PointerToIntegral:
1503 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1504 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbar89f176d2010-08-25 03:32:38 +00001505
John McCall2de56d12010-08-25 11:45:40 +00001506 case CK_ToVoid: {
John McCall2a416372010-12-05 02:00:02 +00001507 CGF.EmitIgnoredExpr(E);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001508 return nullptr;
Eli Friedmanad35a832009-11-16 21:33:53 +00001509 }
John McCall2de56d12010-08-25 11:45:40 +00001510 case CK_VectorSplat: {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001511 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanad35a832009-11-16 21:33:53 +00001512 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5fa56082012-02-06 05:05:50 +00001513 Elt = EmitScalarConversion(Elt, E->getType(),
1514 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanad35a832009-11-16 21:33:53 +00001515
Eli Friedmanad35a832009-11-16 21:33:53 +00001516 // Splat the element across to all elements
Eli Friedmanad35a832009-11-16 21:33:53 +00001517 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001518 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Eli Friedmanad35a832009-11-16 21:33:53 +00001519 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001520
John McCall2de56d12010-08-25 11:45:40 +00001521 case CK_IntegralCast:
1522 case CK_IntegralToFloating:
1523 case CK_FloatingToIntegral:
1524 case CK_FloatingCast:
Eli Friedmand8889622009-11-27 04:41:50 +00001525 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCalldaa8e4e2010-11-15 09:13:47 +00001526 case CK_IntegralToBoolean:
1527 return EmitIntToBoolConversion(Visit(E));
1528 case CK_PointerToBoolean:
1529 return EmitPointerToBoolConversion(Visit(E));
1530 case CK_FloatingToBoolean:
1531 return EmitFloatToBoolConversion(Visit(E));
John McCall2de56d12010-08-25 11:45:40 +00001532 case CK_MemberPointerToBoolean: {
John McCall0bab0cd2010-08-23 01:21:21 +00001533 llvm::Value *MemPtr = Visit(E);
1534 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1535 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlssone9776242009-08-24 18:26:39 +00001536 }
John McCallf3ea8cf2010-11-14 08:17:51 +00001537
1538 case CK_FloatingComplexToReal:
1539 case CK_IntegralComplexToReal:
John McCallb418d742010-11-16 10:08:07 +00001540 return CGF.EmitComplexExpr(E, false, true).first;
John McCallf3ea8cf2010-11-14 08:17:51 +00001541
1542 case CK_FloatingComplexToBoolean:
1543 case CK_IntegralComplexToBoolean: {
John McCallb418d742010-11-16 10:08:07 +00001544 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCallf3ea8cf2010-11-14 08:17:51 +00001545
1546 // TODO: kill this function off, inline appropriate case here
1547 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1548 }
1549
Guy Benyeie6b9d802013-01-20 12:31:11 +00001550 case CK_ZeroToOCLEvent: {
Stephen Hines651f13c2014-04-23 16:59:28 -07001551 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non-event type");
Guy Benyeie6b9d802013-01-20 12:31:11 +00001552 return llvm::Constant::getNullValue(ConvertType(DestTy));
1553 }
1554
John McCall0bab0cd2010-08-23 01:21:21 +00001555 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001556
John McCall61ad0e62010-11-16 06:21:14 +00001557 llvm_unreachable("unknown scalar cast");
Chris Lattner7f02f722007-08-24 05:35:26 +00001558}
1559
Chris Lattner33793202007-08-31 22:09:40 +00001560Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCall150b4622011-01-26 04:00:11 +00001561 CodeGenFunction::StmtExprEvaluation eval(CGF);
Eli Friedman2ac2fa72013-06-10 22:04:49 +00001562 llvm::Value *RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
1563 !E->getType()->isVoidType());
1564 if (!RetAlloca)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001565 return nullptr;
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001566 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
1567 E->getExprLoc());
Chris Lattner33793202007-08-31 22:09:40 +00001568}
1569
Chris Lattner7f02f722007-08-24 05:35:26 +00001570//===----------------------------------------------------------------------===//
1571// Unary Operators
1572//===----------------------------------------------------------------------===//
1573
Chris Lattner8c11a652010-06-26 22:09:34 +00001574llvm::Value *ScalarExprEmitter::
Anton Yartsev683564a2011-02-07 02:17:30 +00001575EmitAddConsiderOverflowBehavior(const UnaryOperator *E,
1576 llvm::Value *InVal,
1577 llvm::Value *NextVal, bool IsInc) {
Richard Smith7edf9e32012-11-01 22:30:59 +00001578 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev683564a2011-02-07 02:17:30 +00001579 case LangOptions::SOB_Defined:
1580 return Builder.CreateAdd(InVal, NextVal, IsInc ? "inc" : "dec");
Richard Smith9d3e2262012-08-25 00:32:28 +00001581 case LangOptions::SOB_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -08001582 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith9d3e2262012-08-25 00:32:28 +00001583 return Builder.CreateNSWAdd(InVal, NextVal, IsInc ? "inc" : "dec");
1584 // Fall through.
Anton Yartsev683564a2011-02-07 02:17:30 +00001585 case LangOptions::SOB_Trapping:
1586 BinOpInfo BinOp;
1587 BinOp.LHS = InVal;
1588 BinOp.RHS = NextVal;
1589 BinOp.Ty = E->getType();
1590 BinOp.Opcode = BO_Add;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001591 BinOp.FPContractable = false;
Anton Yartsev683564a2011-02-07 02:17:30 +00001592 BinOp.E = E;
1593 return EmitOverflowCheckedBinOp(BinOp);
Anton Yartsev683564a2011-02-07 02:17:30 +00001594 }
David Blaikieb219cfc2011-09-23 05:06:16 +00001595 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev683564a2011-02-07 02:17:30 +00001596}
1597
John McCall5936e332011-02-15 09:22:45 +00001598llvm::Value *
1599ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1600 bool isInc, bool isPre) {
Craig Topperd10e5c22013-07-26 06:16:11 +00001601
John McCall5936e332011-02-15 09:22:45 +00001602 QualType type = E->getSubExpr()->getType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001603 llvm::PHINode *atomicPHI = nullptr;
David Chisnall72c1dba2013-03-03 16:02:42 +00001604 llvm::Value *value;
1605 llvm::Value *input;
Anton Yartsev683564a2011-02-07 02:17:30 +00001606
John McCall5936e332011-02-15 09:22:45 +00001607 int amount = (isInc ? 1 : -1);
1608
David Chisnall7a7ee302012-01-16 17:27:18 +00001609 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
David Chisnall72c1dba2013-03-03 16:02:42 +00001610 type = atomicTy->getValueType();
1611 if (isInc && type->isBooleanType()) {
1612 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
1613 if (isPre) {
1614 Builder.Insert(new llvm::StoreInst(True,
1615 LV.getAddress(), LV.isVolatileQualified(),
1616 LV.getAlignment().getQuantity(),
1617 llvm::SequentiallyConsistent));
1618 return Builder.getTrue();
1619 }
1620 // For atomic bool increment, we just store true and return it for
1621 // preincrement, do an atomic swap with true for postincrement
1622 return Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
1623 LV.getAddress(), True, llvm::SequentiallyConsistent);
1624 }
1625 // Special case for atomic increment / decrement on integers, emit
1626 // atomicrmw instructions. We skip this if we want to be doing overflow
Craig Topperd10e5c22013-07-26 06:16:11 +00001627 // checking, and fall into the slow path with the atomic cmpxchg loop.
David Chisnall72c1dba2013-03-03 16:02:42 +00001628 if (!type->isBooleanType() && type->isIntegerType() &&
1629 !(type->isUnsignedIntegerType() &&
Stephen Hines176edba2014-12-01 14:53:08 -08001630 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
David Chisnall72c1dba2013-03-03 16:02:42 +00001631 CGF.getLangOpts().getSignedOverflowBehavior() !=
Stephen Hines176edba2014-12-01 14:53:08 -08001632 LangOptions::SOB_Trapping) {
David Chisnall72c1dba2013-03-03 16:02:42 +00001633 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
1634 llvm::AtomicRMWInst::Sub;
1635 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
1636 llvm::Instruction::Sub;
1637 llvm::Value *amt = CGF.EmitToMemory(
1638 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
1639 llvm::Value *old = Builder.CreateAtomicRMW(aop,
1640 LV.getAddress(), amt, llvm::SequentiallyConsistent);
1641 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
1642 }
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001643 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnall72c1dba2013-03-03 16:02:42 +00001644 input = value;
1645 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
David Chisnall7a7ee302012-01-16 17:27:18 +00001646 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1647 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
David Chisnall72c1dba2013-03-03 16:02:42 +00001648 value = CGF.EmitToMemory(value, type);
David Chisnall7a7ee302012-01-16 17:27:18 +00001649 Builder.CreateBr(opBB);
1650 Builder.SetInsertPoint(opBB);
1651 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1652 atomicPHI->addIncoming(value, startBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00001653 value = atomicPHI;
David Chisnall72c1dba2013-03-03 16:02:42 +00001654 } else {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001655 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnall72c1dba2013-03-03 16:02:42 +00001656 input = value;
David Chisnall7a7ee302012-01-16 17:27:18 +00001657 }
1658
John McCall5936e332011-02-15 09:22:45 +00001659 // Special case of integer increment that we have to check first: bool++.
1660 // Due to promotion rules, we get:
1661 // bool++ -> bool = bool + 1
1662 // -> bool = (int)bool + 1
1663 // -> bool = ((int)bool + 1 != 0)
1664 // An interesting aspect of this is that increment is always true.
1665 // Decrement does not have this property.
1666 if (isInc && type->isBooleanType()) {
1667 value = Builder.getTrue();
1668
1669 // Most common case by far: integer increment.
1670 } else if (type->isIntegerType()) {
1671
Michael Liao36d5cea2012-08-28 16:55:13 +00001672 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCall5936e332011-02-15 09:22:45 +00001673
Eli Friedmanfa0b4092011-03-02 01:49:12 +00001674 // Note that signed integer inc/dec with width less than int can't
1675 // overflow because of promotion rules; we're just eliding a few steps here.
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001676 bool CanOverflow = value->getType()->getIntegerBitWidth() >=
1677 CGF.IntTy->getIntegerBitWidth();
1678 if (CanOverflow && type->isSignedIntegerOrEnumerationType()) {
John McCall5936e332011-02-15 09:22:45 +00001679 value = EmitAddConsiderOverflowBehavior(E, value, amt, isInc);
Stephen Hinesc568f1e2014-07-21 00:47:37 -07001680 } else if (CanOverflow && type->isUnsignedIntegerType() &&
Stephen Hines176edba2014-12-01 14:53:08 -08001681 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
Will Dietzb8540362012-11-27 15:01:55 +00001682 BinOpInfo BinOp;
1683 BinOp.LHS = value;
1684 BinOp.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
1685 BinOp.Ty = E->getType();
1686 BinOp.Opcode = isInc ? BO_Add : BO_Sub;
1687 BinOp.FPContractable = false;
1688 BinOp.E = E;
1689 value = EmitOverflowCheckedBinOp(BinOp);
1690 } else
John McCall5936e332011-02-15 09:22:45 +00001691 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
Craig Topperd10e5c22013-07-26 06:16:11 +00001692
John McCall5936e332011-02-15 09:22:45 +00001693 // Next most common: pointer increment.
1694 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1695 QualType type = ptr->getPointeeType();
1696
1697 // VLA types don't have constant size.
John McCall913dab22011-06-25 01:32:37 +00001698 if (const VariableArrayType *vla
1699 = CGF.getContext().getAsVariableArrayType(type)) {
1700 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCallbc8d40d2011-06-24 21:55:10 +00001701 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Richard Smith7edf9e32012-11-01 22:30:59 +00001702 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCallbc8d40d2011-06-24 21:55:10 +00001703 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2cb42222011-03-01 00:03:48 +00001704 else
John McCallbc8d40d2011-06-24 21:55:10 +00001705 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
Craig Topperd10e5c22013-07-26 06:16:11 +00001706
John McCall5936e332011-02-15 09:22:45 +00001707 // Arithmetic on function pointers (!) is just +-1.
1708 } else if (type->isFunctionType()) {
Chris Lattner48431f92011-04-19 22:55:03 +00001709 llvm::Value *amt = Builder.getInt32(amount);
John McCall5936e332011-02-15 09:22:45 +00001710
1711 value = CGF.EmitCastToVoidPtr(value);
Richard Smith7edf9e32012-11-01 22:30:59 +00001712 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001713 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1714 else
1715 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCall5936e332011-02-15 09:22:45 +00001716 value = Builder.CreateBitCast(value, input->getType());
1717
1718 // For everything else, we can just do a simple increment.
Anton Yartsev683564a2011-02-07 02:17:30 +00001719 } else {
Chris Lattner48431f92011-04-19 22:55:03 +00001720 llvm::Value *amt = Builder.getInt32(amount);
Richard Smith7edf9e32012-11-01 22:30:59 +00001721 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001722 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1723 else
1724 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCall5936e332011-02-15 09:22:45 +00001725 }
1726
1727 // Vector increment/decrement.
1728 } else if (type->isVectorType()) {
1729 if (type->hasIntegerRepresentation()) {
1730 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1731
Eli Friedmand4b9ee32011-05-06 18:04:18 +00001732 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCall5936e332011-02-15 09:22:45 +00001733 } else {
1734 value = Builder.CreateFAdd(
1735 value,
1736 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev683564a2011-02-07 02:17:30 +00001737 isInc ? "inc" : "dec");
1738 }
Anton Yartsev683564a2011-02-07 02:17:30 +00001739
John McCall5936e332011-02-15 09:22:45 +00001740 // Floating point.
1741 } else if (type->isRealFloatingType()) {
Chris Lattner8c11a652010-06-26 22:09:34 +00001742 // Add the inc/dec to the real part.
John McCall5936e332011-02-15 09:22:45 +00001743 llvm::Value *amt;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001744
Stephen Hines176edba2014-12-01 14:53:08 -08001745 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1746 !CGF.getContext().getLangOpts().HalfArgsAndReturns) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001747 // Another special case: half FP increment should be done via float
Stephen Hines176edba2014-12-01 14:53:08 -08001748 value = Builder.CreateCall(
1749 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1750 CGF.CGM.FloatTy),
1751 input);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001752 }
1753
John McCall5936e332011-02-15 09:22:45 +00001754 if (value->getType()->isFloatTy())
1755 amt = llvm::ConstantFP::get(VMContext,
1756 llvm::APFloat(static_cast<float>(amount)));
1757 else if (value->getType()->isDoubleTy())
1758 amt = llvm::ConstantFP::get(VMContext,
1759 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner8c11a652010-06-26 22:09:34 +00001760 else {
John McCall5936e332011-02-15 09:22:45 +00001761 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner8c11a652010-06-26 22:09:34 +00001762 bool ignored;
John McCall64aa4b32013-04-16 22:48:15 +00001763 F.convert(CGF.getTarget().getLongDoubleFormat(),
1764 llvm::APFloat::rmTowardZero, &ignored);
John McCall5936e332011-02-15 09:22:45 +00001765 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner8c11a652010-06-26 22:09:34 +00001766 }
John McCall5936e332011-02-15 09:22:45 +00001767 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1768
Stephen Hines176edba2014-12-01 14:53:08 -08001769 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1770 !CGF.getContext().getLangOpts().HalfArgsAndReturns)
1771 value = Builder.CreateCall(
1772 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
1773 CGF.CGM.FloatTy),
1774 value);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001775
John McCall5936e332011-02-15 09:22:45 +00001776 // Objective-C pointer types.
1777 } else {
1778 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1779 value = CGF.EmitCastToVoidPtr(value);
1780
1781 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1782 if (!isInc) size = -size;
1783 llvm::Value *sizeValue =
1784 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1785
Richard Smith7edf9e32012-11-01 22:30:59 +00001786 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2cb42222011-03-01 00:03:48 +00001787 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1788 else
1789 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCall5936e332011-02-15 09:22:45 +00001790 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner8c11a652010-06-26 22:09:34 +00001791 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001792
David Chisnall7a7ee302012-01-16 17:27:18 +00001793 if (atomicPHI) {
1794 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1795 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07001796 auto Pair = CGF.EmitAtomicCompareExchange(
1797 LV, RValue::get(atomicPHI), RValue::get(CGF.EmitToMemory(value, type)),
1798 E->getExprLoc());
1799 llvm::Value *old = Pair.first.getScalarVal();
1800 llvm::Value *success = Pair.second.getScalarVal();
David Chisnall7a7ee302012-01-16 17:27:18 +00001801 atomicPHI->addIncoming(old, opBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00001802 Builder.CreateCondBr(success, contBB, opBB);
1803 Builder.SetInsertPoint(contBB);
1804 return isPre ? value : input;
1805 }
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001806
Chris Lattner8c11a652010-06-26 22:09:34 +00001807 // Store the updated result through the lvalue.
1808 if (LV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00001809 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner8c11a652010-06-26 22:09:34 +00001810 else
John McCall545d9962011-06-25 02:11:03 +00001811 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001812
Chris Lattner8c11a652010-06-26 22:09:34 +00001813 // If this is a postinc, return the value read from memory, otherwise use the
1814 // updated value.
John McCall5936e332011-02-15 09:22:45 +00001815 return isPre ? value : input;
Chris Lattner8c11a652010-06-26 22:09:34 +00001816}
1817
1818
1819
Chris Lattner7f02f722007-08-24 05:35:26 +00001820Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001821 TestAndClearIgnoreResultAssign();
Chris Lattner9a207232010-06-26 21:48:21 +00001822 // Emit unary minus with EmitSub so we handle overflow cases etc.
1823 BinOpInfo BinOp;
Chris Lattner4ac0d832010-06-28 17:12:37 +00001824 BinOp.RHS = Visit(E->getSubExpr());
Craig Topperd10e5c22013-07-26 06:16:11 +00001825
Chris Lattner4ac0d832010-06-28 17:12:37 +00001826 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1827 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00001828 else
Chris Lattner4ac0d832010-06-28 17:12:37 +00001829 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner9a207232010-06-26 21:48:21 +00001830 BinOp.Ty = E->getType();
John McCall2de56d12010-08-25 11:45:40 +00001831 BinOp.Opcode = BO_Sub;
Benjamin Kramerddc57332012-10-03 20:58:04 +00001832 BinOp.FPContractable = false;
Chris Lattner9a207232010-06-26 21:48:21 +00001833 BinOp.E = E;
1834 return EmitSub(BinOp);
Chris Lattner7f02f722007-08-24 05:35:26 +00001835}
1836
1837Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00001838 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00001839 Value *Op = Visit(E->getSubExpr());
1840 return Builder.CreateNot(Op, "neg");
1841}
1842
1843Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner4f692c22012-01-16 21:02:28 +00001844 // Perform vector logical not on comparison with zero vector.
1845 if (E->getType()->isExtVectorType()) {
1846 Value *Oper = Visit(E->getSubExpr());
1847 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
Joey Gouly52e933b2013-02-21 11:49:56 +00001848 Value *Result;
1849 if (Oper->getType()->isFPOrFPVectorTy())
1850 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
1851 else
1852 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
Tanya Lattner4f692c22012-01-16 21:02:28 +00001853 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1854 }
Craig Topperd10e5c22013-07-26 06:16:11 +00001855
Chris Lattner7f02f722007-08-24 05:35:26 +00001856 // Compare operand to zero.
1857 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001858
Chris Lattner7f02f722007-08-24 05:35:26 +00001859 // Invert value.
1860 // TODO: Could dynamically modify easy computations here. For example, if
1861 // the operand is an icmp ne, turn into icmp eq.
1862 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001863
Anders Carlsson9f84d882009-05-19 18:44:53 +00001864 // ZExt result to the expr type.
1865 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00001866}
1867
Eli Friedman0027d2b2010-08-05 09:58:49 +00001868Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1869 // Try folding the offsetof to a constant.
Richard Smith80d4b552011-12-28 19:48:30 +00001870 llvm::APSInt Value;
1871 if (E->EvaluateAsInt(Value, CGF.getContext()))
1872 return Builder.getInt(Value);
Eli Friedman0027d2b2010-08-05 09:58:49 +00001873
1874 // Loop over the components of the offsetof to compute the value.
1875 unsigned n = E->getNumComponents();
Chris Lattner2acc6e32011-07-18 04:24:23 +00001876 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001877 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1878 QualType CurrentType = E->getTypeSourceInfo()->getType();
1879 for (unsigned i = 0; i != n; ++i) {
1880 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001881 llvm::Value *Offset = nullptr;
Eli Friedman0027d2b2010-08-05 09:58:49 +00001882 switch (ON.getKind()) {
1883 case OffsetOfExpr::OffsetOfNode::Array: {
1884 // Compute the index
1885 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1886 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001887 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedman0027d2b2010-08-05 09:58:49 +00001888 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1889
1890 // Save the element type
1891 CurrentType =
1892 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1893
1894 // Compute the element size
1895 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1896 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1897
1898 // Multiply out to compute the result
1899 Offset = Builder.CreateMul(Idx, ElemSize);
1900 break;
1901 }
1902
1903 case OffsetOfExpr::OffsetOfNode::Field: {
1904 FieldDecl *MemberDecl = ON.getField();
1905 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1906 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1907
1908 // Compute the index of the field in its parent.
1909 unsigned i = 0;
1910 // FIXME: It would be nice if we didn't have to loop here!
1911 for (RecordDecl::field_iterator Field = RD->field_begin(),
1912 FieldEnd = RD->field_end();
David Blaikie262bc182012-04-30 02:36:29 +00001913 Field != FieldEnd; ++Field, ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00001914 if (*Field == MemberDecl)
Eli Friedman0027d2b2010-08-05 09:58:49 +00001915 break;
1916 }
1917 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1918
1919 // Compute the offset to the field
1920 int64_t OffsetInt = RL.getFieldOffset(i) /
1921 CGF.getContext().getCharWidth();
1922 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1923
1924 // Save the element type.
1925 CurrentType = MemberDecl->getType();
1926 break;
1927 }
Eli Friedman16fd39f2010-08-06 16:37:05 +00001928
Eli Friedman0027d2b2010-08-05 09:58:49 +00001929 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedman6d4e44b2010-08-06 01:17:25 +00001930 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman16fd39f2010-08-06 16:37:05 +00001931
Eli Friedman0027d2b2010-08-05 09:58:49 +00001932 case OffsetOfExpr::OffsetOfNode::Base: {
1933 if (ON.getBase()->isVirtual()) {
1934 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1935 continue;
1936 }
1937
1938 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1939 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1940
1941 // Save the element type.
1942 CurrentType = ON.getBase()->getType();
Craig Topperd10e5c22013-07-26 06:16:11 +00001943
Eli Friedman0027d2b2010-08-05 09:58:49 +00001944 // Compute the offset to the base.
1945 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
1946 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramerd4f51982012-07-04 18:45:14 +00001947 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
1948 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedman0027d2b2010-08-05 09:58:49 +00001949 break;
1950 }
1951 }
1952 Result = Builder.CreateAdd(Result, Offset);
1953 }
1954 return Result;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00001955}
1956
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001957/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl05189992008-11-11 17:56:53 +00001958/// argument of the sizeof expression as an integer.
1959Value *
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001960ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
1961 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl05189992008-11-11 17:56:53 +00001962 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00001963 if (E->getKind() == UETT_SizeOf) {
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001964 if (const VariableArrayType *VAT =
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001965 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
1966 if (E->isArgumentType()) {
1967 // sizeof(type) - make sure to emit the VLA size.
John McCallbc8d40d2011-06-24 21:55:10 +00001968 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman8f426fa2009-04-20 03:21:44 +00001969 } else {
1970 // C99 6.5.3.4p2: If the argument is an expression of type
1971 // VLA, it is evaluated.
John McCall2a416372010-12-05 02:00:02 +00001972 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001973 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001974
John McCallbc8d40d2011-06-24 21:55:10 +00001975 QualType eltType;
1976 llvm::Value *numElts;
Stephen Hines651f13c2014-04-23 16:59:28 -07001977 std::tie(numElts, eltType) = CGF.getVLASize(VAT);
John McCallbc8d40d2011-06-24 21:55:10 +00001978
1979 llvm::Value *size = numElts;
1980
1981 // Scale the number of non-VLA elements by the non-VLA element size.
1982 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
1983 if (!eltSize.isOne())
1984 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
1985
1986 return size;
Anders Carlssonb50525b2008-12-21 03:33:21 +00001987 }
Anders Carlsson5d463152008-12-12 07:38:43 +00001988 }
Eli Friedmanf2da9df2009-01-24 22:19:05 +00001989
Mike Stumpdb52dcd2009-09-09 13:00:44 +00001990 // If this isn't sizeof(vla), the result must be constant; use the constant
1991 // folding logic so we don't have to duplicate it here.
Richard Smith80d4b552011-12-28 19:48:30 +00001992 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner7f02f722007-08-24 05:35:26 +00001993}
1994
Chris Lattner46f93d02007-08-24 21:20:17 +00001995Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
1996 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00001997 if (Op->getType()->isAnyComplexType()) {
1998 // If it's an l-value, load through the appropriate subobject l-value.
1999 // Note that we have to ask E because Op might be an l-value that
2000 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00002001 if (E->isGLValue())
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002002 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2003 E->getExprLoc()).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00002004
2005 // Otherwise, calculate and project.
2006 return CGF.EmitComplexExpr(Op, false, true).first;
2007 }
2008
Chris Lattner46f93d02007-08-24 21:20:17 +00002009 return Visit(Op);
2010}
John McCallb418d742010-11-16 10:08:07 +00002011
Chris Lattner46f93d02007-08-24 21:20:17 +00002012Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2013 Expr *Op = E->getSubExpr();
John McCallb418d742010-11-16 10:08:07 +00002014 if (Op->getType()->isAnyComplexType()) {
2015 // If it's an l-value, load through the appropriate subobject l-value.
2016 // Note that we have to ask E because Op might be an l-value that
2017 // this won't work for, e.g. an Obj-C property.
John McCall7eb0a9e2010-11-24 05:12:34 +00002018 if (Op->isGLValue())
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002019 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2020 E->getExprLoc()).getScalarVal();
John McCallb418d742010-11-16 10:08:07 +00002021
2022 // Otherwise, calculate and project.
2023 return CGF.EmitComplexExpr(Op, true, false).second;
2024 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002025
Mike Stump7f79f9b2009-05-29 15:46:01 +00002026 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2027 // effects are evaluated, but not the actual value.
Richard Smithdfb80de2012-02-18 20:53:32 +00002028 if (Op->isGLValue())
2029 CGF.EmitLValue(Op);
2030 else
2031 CGF.EmitScalarExpr(Op, true);
Owen Andersonc9c88b42009-07-31 20:28:54 +00002032 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner46f93d02007-08-24 21:20:17 +00002033}
2034
Chris Lattner7f02f722007-08-24 05:35:26 +00002035//===----------------------------------------------------------------------===//
2036// Binary Operators
2037//===----------------------------------------------------------------------===//
2038
2039BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002040 TestAndClearIgnoreResultAssign();
Chris Lattner7f02f722007-08-24 05:35:26 +00002041 BinOpInfo Result;
2042 Result.LHS = Visit(E->getLHS());
2043 Result.RHS = Visit(E->getRHS());
Chris Lattner1f1ded92007-08-24 21:00:35 +00002044 Result.Ty = E->getType();
Chris Lattner9a207232010-06-26 21:48:21 +00002045 Result.Opcode = E->getOpcode();
Lang Hamesbe9af122012-10-02 04:45:10 +00002046 Result.FPContractable = E->isFPContractable();
Chris Lattner7f02f722007-08-24 05:35:26 +00002047 Result.E = E;
2048 return Result;
2049}
2050
Douglas Gregor6a03e342010-04-23 04:16:32 +00002051LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2052 const CompoundAssignOperator *E,
2053 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002054 Value *&Result) {
Benjamin Kramer54d76db2009-12-25 15:43:36 +00002055 QualType LHSTy = E->getLHS()->getType();
Chris Lattner1f1ded92007-08-24 21:00:35 +00002056 BinOpInfo OpInfo;
Craig Topperd10e5c22013-07-26 06:16:11 +00002057
Eli Friedman0934e182013-06-12 01:40:06 +00002058 if (E->getComputationResultType()->isAnyComplexType())
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002059 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
Craig Topperd10e5c22013-07-26 06:16:11 +00002060
Mike Stumpcc0442f2009-05-22 19:07:20 +00002061 // Emit the RHS first. __block variables need to have the rhs evaluated
2062 // first, plus this should improve codegen a little.
2063 OpInfo.RHS = Visit(E->getRHS());
2064 OpInfo.Ty = E->getComputationResultType();
Chris Lattner9a207232010-06-26 21:48:21 +00002065 OpInfo.Opcode = E->getOpcode();
Benjamin Kramerddc57332012-10-03 20:58:04 +00002066 OpInfo.FPContractable = false;
Mike Stumpcc0442f2009-05-22 19:07:20 +00002067 OpInfo.E = E;
Eli Friedmanab3a8522009-03-28 01:22:36 +00002068 // Load/convert the LHS.
Richard Smith7ac9ef12012-09-08 02:08:36 +00002069 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
David Chisnall7a7ee302012-01-16 17:27:18 +00002070
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002071 llvm::PHINode *atomicPHI = nullptr;
David Chisnall72c1dba2013-03-03 16:02:42 +00002072 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2073 QualType type = atomicTy->getValueType();
2074 if (!type->isBooleanType() && type->isIntegerType() &&
Stephen Hines176edba2014-12-01 14:53:08 -08002075 !(type->isUnsignedIntegerType() &&
2076 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2077 CGF.getLangOpts().getSignedOverflowBehavior() !=
2078 LangOptions::SOB_Trapping) {
David Chisnall72c1dba2013-03-03 16:02:42 +00002079 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2080 switch (OpInfo.Opcode) {
2081 // We don't have atomicrmw operands for *, %, /, <<, >>
2082 case BO_MulAssign: case BO_DivAssign:
2083 case BO_RemAssign:
2084 case BO_ShlAssign:
2085 case BO_ShrAssign:
2086 break;
2087 case BO_AddAssign:
2088 aop = llvm::AtomicRMWInst::Add;
2089 break;
2090 case BO_SubAssign:
2091 aop = llvm::AtomicRMWInst::Sub;
2092 break;
2093 case BO_AndAssign:
2094 aop = llvm::AtomicRMWInst::And;
2095 break;
2096 case BO_XorAssign:
2097 aop = llvm::AtomicRMWInst::Xor;
2098 break;
2099 case BO_OrAssign:
2100 aop = llvm::AtomicRMWInst::Or;
2101 break;
2102 default:
2103 llvm_unreachable("Invalid compound assignment type");
2104 }
2105 if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
2106 llvm::Value *amt = CGF.EmitToMemory(EmitScalarConversion(OpInfo.RHS,
2107 E->getRHS()->getType(), LHSTy), LHSTy);
2108 Builder.CreateAtomicRMW(aop, LHSLV.getAddress(), amt,
2109 llvm::SequentiallyConsistent);
2110 return LHSLV;
2111 }
2112 }
David Chisnall7a7ee302012-01-16 17:27:18 +00002113 // FIXME: For floating point types, we should be saving and restoring the
2114 // floating point environment in the loop.
2115 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2116 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002117 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
David Chisnall72c1dba2013-03-03 16:02:42 +00002118 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
David Chisnall7a7ee302012-01-16 17:27:18 +00002119 Builder.CreateBr(opBB);
2120 Builder.SetInsertPoint(opBB);
2121 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2122 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00002123 OpInfo.LHS = atomicPHI;
2124 }
David Chisnall72c1dba2013-03-03 16:02:42 +00002125 else
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002126 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
Eli Friedman860a3192012-06-16 02:19:17 +00002127
2128 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
2129 E->getComputationLHSType());
2130
Chris Lattner1f1ded92007-08-24 21:00:35 +00002131 // Expand the binary operator.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002132 Result = (this->*Func)(OpInfo);
Craig Topperd10e5c22013-07-26 06:16:11 +00002133
Daniel Dunbar8c6f57c2008-08-06 02:00:38 +00002134 // Convert the result back to the LHS type.
Eli Friedmanab3a8522009-03-28 01:22:36 +00002135 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnall7a7ee302012-01-16 17:27:18 +00002136
2137 if (atomicPHI) {
2138 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2139 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Stephen Hines0e2c34f2015-03-23 12:09:02 -07002140 auto Pair = CGF.EmitAtomicCompareExchange(
2141 LHSLV, RValue::get(atomicPHI),
2142 RValue::get(CGF.EmitToMemory(Result, LHSTy)), E->getExprLoc());
2143 llvm::Value *old = Pair.first.getScalarVal();
2144 llvm::Value *success = Pair.second.getScalarVal();
David Chisnall7a7ee302012-01-16 17:27:18 +00002145 atomicPHI->addIncoming(old, opBB);
David Chisnall7a7ee302012-01-16 17:27:18 +00002146 Builder.CreateCondBr(success, contBB, opBB);
2147 Builder.SetInsertPoint(contBB);
2148 return LHSLV;
2149 }
Craig Topperd10e5c22013-07-26 06:16:11 +00002150
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002151 // Store the result value into the LHS lvalue. Bit-fields are handled
2152 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2153 // 'An assignment expression has the value of the left operand after the
2154 // assignment...'.
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002155 if (LHSLV.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002156 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002157 else
John McCall545d9962011-06-25 02:11:03 +00002158 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002159
Douglas Gregor6a03e342010-04-23 04:16:32 +00002160 return LHSLV;
2161}
2162
2163Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2164 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2165 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002166 Value *RHS;
2167 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2168
2169 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002170 if (Ignore)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002171 return nullptr;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002172
John McCallb418d742010-11-16 10:08:07 +00002173 // The result of an assignment in C is the assigned r-value.
Richard Smith7edf9e32012-11-01 22:30:59 +00002174 if (!CGF.getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00002175 return RHS;
2176
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002177 // If the lvalue is non-volatile, return the computed value of the assignment.
2178 if (!LHS.isVolatileQualified())
2179 return RHS;
2180
2181 // Otherwise, reload the value.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002182 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner1f1ded92007-08-24 21:00:35 +00002183}
2184
Chris Lattner80230302010-09-11 21:47:09 +00002185void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith7ac9ef12012-09-08 02:08:36 +00002186 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Stephen Hines176edba2014-12-01 14:53:08 -08002187 SmallVector<std::pair<llvm::Value *, SanitizerKind>, 2> Checks;
Chris Lattner80230302010-09-11 21:47:09 +00002188
Stephen Hines176edba2014-12-01 14:53:08 -08002189 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2190 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2191 SanitizerKind::IntegerDivideByZero));
2192 }
Richard Smithc54e25f2012-11-06 02:30:30 +00002193
Stephen Hines176edba2014-12-01 14:53:08 -08002194 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
Richard Smithc54e25f2012-11-06 02:30:30 +00002195 Ops.Ty->hasSignedIntegerRepresentation()) {
2196 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2197
Chris Lattner80230302010-09-11 21:47:09 +00002198 llvm::Value *IntMin =
Chris Lattner48431f92011-04-19 22:55:03 +00002199 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner80230302010-09-11 21:47:09 +00002200 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2201
Richard Smith7ac9ef12012-09-08 02:08:36 +00002202 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2203 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
Stephen Hines176edba2014-12-01 14:53:08 -08002204 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2205 Checks.push_back(
2206 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
Chris Lattner80230302010-09-11 21:47:09 +00002207 }
Richard Smithc54e25f2012-11-06 02:30:30 +00002208
Stephen Hines176edba2014-12-01 14:53:08 -08002209 if (Checks.size() > 0)
2210 EmitBinOpCheck(Checks, Ops);
Chris Lattner80230302010-09-11 21:47:09 +00002211}
Chris Lattner1f1ded92007-08-24 21:00:35 +00002212
Chris Lattner7f02f722007-08-24 05:35:26 +00002213Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Stephen Hines176edba2014-12-01 14:53:08 -08002214 {
2215 CodeGenFunction::SanitizerScope SanScope(&CGF);
2216 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2217 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
2218 Ops.Ty->isIntegerType()) {
2219 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2220 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
2221 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
2222 Ops.Ty->isRealFloatingType()) {
2223 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2224 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
2225 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
2226 Ops);
2227 }
Chris Lattner80230302010-09-11 21:47:09 +00002228 }
Will Dietzb8540362012-11-27 15:01:55 +00002229
Peter Collingbournec5096cb2011-10-27 19:19:51 +00002230 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
2231 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Richard Smith7edf9e32012-11-01 22:30:59 +00002232 if (CGF.getLangOpts().OpenCL) {
Peter Collingbournec5096cb2011-10-27 19:19:51 +00002233 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
2234 llvm::Type *ValTy = Val->getType();
2235 if (ValTy->isFloatTy() ||
2236 (isa<llvm::VectorType>(ValTy) &&
2237 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sands82500162012-04-10 08:23:07 +00002238 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbournec5096cb2011-10-27 19:19:51 +00002239 }
2240 return Val;
2241 }
Douglas Gregorf6094622010-07-23 15:58:24 +00002242 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002243 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2244 else
2245 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2246}
2247
2248Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
2249 // Rem in C can't be a floating point type: C99 6.5.5p2.
Stephen Hines176edba2014-12-01 14:53:08 -08002250 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
2251 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattner80230302010-09-11 21:47:09 +00002252 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2253
Will Dietzb8540362012-11-27 15:01:55 +00002254 if (Ops.Ty->isIntegerType())
Chris Lattner80230302010-09-11 21:47:09 +00002255 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2256 }
2257
Eli Friedman52d68742011-04-10 04:44:11 +00002258 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002259 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2260 else
2261 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2262}
2263
Mike Stump2add4732009-04-01 20:28:16 +00002264Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2265 unsigned IID;
2266 unsigned OpID = 0;
Mike Stump5d8b2cf2009-04-02 01:03:55 +00002267
Will Dietzb8540362012-11-27 15:01:55 +00002268 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
Chris Lattner9a207232010-06-26 21:48:21 +00002269 switch (Ops.Opcode) {
John McCall2de56d12010-08-25 11:45:40 +00002270 case BO_Add:
2271 case BO_AddAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002272 OpID = 1;
Will Dietzb8540362012-11-27 15:01:55 +00002273 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2274 llvm::Intrinsic::uadd_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002275 break;
John McCall2de56d12010-08-25 11:45:40 +00002276 case BO_Sub:
2277 case BO_SubAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002278 OpID = 2;
Will Dietzb8540362012-11-27 15:01:55 +00002279 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2280 llvm::Intrinsic::usub_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002281 break;
John McCall2de56d12010-08-25 11:45:40 +00002282 case BO_Mul:
2283 case BO_MulAssign:
Mike Stump035cf892009-04-02 18:15:54 +00002284 OpID = 3;
Will Dietzb8540362012-11-27 15:01:55 +00002285 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2286 llvm::Intrinsic::umul_with_overflow;
Mike Stump035cf892009-04-02 18:15:54 +00002287 break;
2288 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00002289 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump2add4732009-04-01 20:28:16 +00002290 }
Mike Stump035cf892009-04-02 18:15:54 +00002291 OpID <<= 1;
Will Dietzb8540362012-11-27 15:01:55 +00002292 if (isSigned)
2293 OpID |= 1;
Mike Stump035cf892009-04-02 18:15:54 +00002294
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002295 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump2add4732009-04-01 20:28:16 +00002296
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002297 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump2add4732009-04-01 20:28:16 +00002298
2299 Value *resultAndOverflow = Builder.CreateCall2(intrinsic, Ops.LHS, Ops.RHS);
2300 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2301 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2302
Richard Smith7ac9ef12012-09-08 02:08:36 +00002303 // Handle overflow with llvm.trap if no custom handler has been specified.
2304 const std::string *handlerName =
Richard Smith7edf9e32012-11-01 22:30:59 +00002305 &CGF.getLangOpts().OverflowHandler;
Richard Smith7ac9ef12012-09-08 02:08:36 +00002306 if (handlerName->empty()) {
Richard Smithd6396a62012-11-05 22:21:05 +00002307 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
Richard Smithcc305612012-11-01 22:15:34 +00002308 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
Stephen Hines176edba2014-12-01 14:53:08 -08002309 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
2310 CodeGenFunction::SanitizerScope SanScope(&CGF);
2311 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
2312 SanitizerKind Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
2313 : SanitizerKind::UnsignedIntegerOverflow;
2314 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
2315 } else
Chad Rosier78d85b12013-01-29 23:31:22 +00002316 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
Richard Smith7ac9ef12012-09-08 02:08:36 +00002317 return result;
2318 }
2319
Mike Stump2add4732009-04-01 20:28:16 +00002320 // Branch in case of overflow.
David Chisnall7f18e672010-09-17 18:29:54 +00002321 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendling14ef3192011-07-07 21:13:10 +00002322 llvm::Function::iterator insertPt = initialBB;
2323 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
Stephen Hines651f13c2014-04-23 16:59:28 -07002324 std::next(insertPt));
Chris Lattner93a00352010-08-07 00:20:46 +00002325 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump2add4732009-04-01 20:28:16 +00002326
2327 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2328
David Chisnall7f18e672010-09-17 18:29:54 +00002329 // If an overflow handler is set, then we want to call it and then use its
2330 // result, if it returns.
2331 Builder.SetInsertPoint(overflowBB);
2332
2333 // Get the overflow handler.
Chris Lattner8b418682012-02-07 00:39:47 +00002334 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002335 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnall7f18e672010-09-17 18:29:54 +00002336 llvm::FunctionType *handlerTy =
2337 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2338 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2339
2340 // Sign extend the args to 64-bit, so that we can use the same handler for
2341 // all types of overflow.
2342 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2343 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2344
2345 // Call the handler with the two arguments, the operation, and the size of
2346 // the result.
John McCallbd7370a2013-02-28 19:01:20 +00002347 llvm::Value *handlerArgs[] = {
2348 lhs,
2349 rhs,
2350 Builder.getInt8(OpID),
2351 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2352 };
2353 llvm::Value *handlerResult =
2354 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
David Chisnall7f18e672010-09-17 18:29:54 +00002355
2356 // Truncate the result back to the desired size.
2357 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2358 Builder.CreateBr(continueBB);
2359
Mike Stump2add4732009-04-01 20:28:16 +00002360 Builder.SetInsertPoint(continueBB);
Jay Foadbbf3bac2011-03-30 11:28:58 +00002361 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnall7f18e672010-09-17 18:29:54 +00002362 phi->addIncoming(result, initialBB);
2363 phi->addIncoming(handlerResult, overflowBB);
2364
2365 return phi;
Mike Stump2add4732009-04-01 20:28:16 +00002366}
Chris Lattner7f02f722007-08-24 05:35:26 +00002367
John McCall913dab22011-06-25 01:32:37 +00002368/// Emit pointer + index arithmetic.
2369static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2370 const BinOpInfo &op,
2371 bool isSubtraction) {
2372 // Must have binary (not unary) expr here. Unary pointer
2373 // increment/decrement doesn't use this path.
2374 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
Craig Topperd10e5c22013-07-26 06:16:11 +00002375
John McCall913dab22011-06-25 01:32:37 +00002376 Value *pointer = op.LHS;
2377 Expr *pointerOperand = expr->getLHS();
2378 Value *index = op.RHS;
2379 Expr *indexOperand = expr->getRHS();
2380
2381 // In a subtraction, the LHS is always the pointer.
2382 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2383 std::swap(pointer, index);
2384 std::swap(pointerOperand, indexOperand);
2385 }
2386
2387 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2388 if (width != CGF.PointerWidthInBits) {
2389 // Zero-extend or sign-extend the pointer value according to
2390 // whether the index is signed or not.
2391 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2392 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2393 "idx.ext");
2394 }
2395
2396 // If this is subtraction, negate the index.
2397 if (isSubtraction)
2398 index = CGF.Builder.CreateNeg(index, "idx.neg");
2399
Stephen Hines176edba2014-12-01 14:53:08 -08002400 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smitha0a628f2013-02-23 02:53:19 +00002401 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2402 /*Accessed*/ false);
2403
John McCall913dab22011-06-25 01:32:37 +00002404 const PointerType *pointerType
2405 = pointerOperand->getType()->getAs<PointerType>();
2406 if (!pointerType) {
2407 QualType objectType = pointerOperand->getType()
2408 ->castAs<ObjCObjectPointerType>()
2409 ->getPointeeType();
2410 llvm::Value *objectSize
2411 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2412
2413 index = CGF.Builder.CreateMul(index, objectSize);
2414
2415 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2416 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2417 return CGF.Builder.CreateBitCast(result, pointer->getType());
2418 }
2419
2420 QualType elementType = pointerType->getPointeeType();
2421 if (const VariableArrayType *vla
2422 = CGF.getContext().getAsVariableArrayType(elementType)) {
2423 // The element count here is the total number of non-VLA elements.
2424 llvm::Value *numElements = CGF.getVLASize(vla).first;
2425
2426 // Effectively, the multiply by the VLA size is part of the GEP.
2427 // GEP indexes are signed, and scaling an index isn't permitted to
2428 // signed-overflow, so we use the same semantics for our explicit
2429 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikie4e4d0842012-03-11 07:00:24 +00002430 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall913dab22011-06-25 01:32:37 +00002431 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2432 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2433 } else {
2434 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2435 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattnera4d71452010-06-26 21:25:03 +00002436 }
John McCall913dab22011-06-25 01:32:37 +00002437 return pointer;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002438 }
Daniel Dunbar2a866252009-04-25 05:08:32 +00002439
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002440 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2441 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2442 // future proof.
John McCall913dab22011-06-25 01:32:37 +00002443 if (elementType->isVoidType() || elementType->isFunctionType()) {
2444 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2445 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2446 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002447 }
2448
David Blaikie4e4d0842012-03-11 07:00:24 +00002449 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall913dab22011-06-25 01:32:37 +00002450 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2451
2452 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner7f02f722007-08-24 05:35:26 +00002453}
2454
Lang Hamesbe9af122012-10-02 04:45:10 +00002455// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2456// Addend. Use negMul and negAdd to negate the first operand of the Mul or
2457// the add operand respectively. This allows fmuladd to represent a*b-c, or
2458// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2459// efficient operations.
2460static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2461 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2462 bool negMul, bool negAdd) {
2463 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
Craig Topperd10e5c22013-07-26 06:16:11 +00002464
Lang Hamesbe9af122012-10-02 04:45:10 +00002465 Value *MulOp0 = MulOp->getOperand(0);
2466 Value *MulOp1 = MulOp->getOperand(1);
2467 if (negMul) {
2468 MulOp0 =
2469 Builder.CreateFSub(
2470 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2471 "neg");
2472 } else if (negAdd) {
2473 Addend =
2474 Builder.CreateFSub(
2475 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2476 "neg");
2477 }
2478
2479 Value *FMulAdd =
2480 Builder.CreateCall3(
2481 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
2482 MulOp0, MulOp1, Addend);
2483 MulOp->eraseFromParent();
2484
2485 return FMulAdd;
2486}
2487
2488// Check whether it would be legal to emit an fmuladd intrinsic call to
2489// represent op and if so, build the fmuladd.
2490//
2491// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2492// Does NOT check the type of the operation - it's assumed that this function
2493// will be called from contexts where it's known that the type is contractable.
Craig Topperd10e5c22013-07-26 06:16:11 +00002494static Value* tryEmitFMulAdd(const BinOpInfo &op,
Lang Hamesbe9af122012-10-02 04:45:10 +00002495 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2496 bool isSub=false) {
2497
2498 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2499 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2500 "Only fadd/fsub can be the root of an fmuladd.");
2501
2502 // Check whether this op is marked as fusable.
2503 if (!op.FPContractable)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002504 return nullptr;
Lang Hamesbe9af122012-10-02 04:45:10 +00002505
2506 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2507 // either disabled, or handled entirely by the LLVM backend).
Lang Hames931c0832012-11-15 07:51:26 +00002508 if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002509 return nullptr;
Lang Hamesbe9af122012-10-02 04:45:10 +00002510
2511 // We have a potentially fusable op. Look for a mul on one of the operands.
2512 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2513 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002514 assert(LHSBinOp->getNumUses() == 0 &&
2515 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002516 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2517 }
2518 } else if (llvm::BinaryOperator* RHSBinOp =
2519 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2520 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hamesff4ae6d2012-10-04 03:23:25 +00002521 assert(RHSBinOp->getNumUses() == 0 &&
2522 "Operations with multiple uses shouldn't be contracted.");
Lang Hamesbe9af122012-10-02 04:45:10 +00002523 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2524 }
2525 }
2526
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002527 return nullptr;
Lang Hamesbe9af122012-10-02 04:45:10 +00002528}
2529
John McCall913dab22011-06-25 01:32:37 +00002530Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2531 if (op.LHS->getType()->isPointerTy() ||
2532 op.RHS->getType()->isPointerTy())
2533 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2534
2535 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002536 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
John McCall913dab22011-06-25 01:32:37 +00002537 case LangOptions::SOB_Defined:
2538 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith9d3e2262012-08-25 00:32:28 +00002539 case LangOptions::SOB_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -08002540 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith9d3e2262012-08-25 00:32:28 +00002541 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2542 // Fall through.
John McCall913dab22011-06-25 01:32:37 +00002543 case LangOptions::SOB_Trapping:
2544 return EmitOverflowCheckedBinOp(op);
2545 }
2546 }
Will Dietzb8540362012-11-27 15:01:55 +00002547
Stephen Hines176edba2014-12-01 14:53:08 -08002548 if (op.Ty->isUnsignedIntegerType() &&
2549 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietzb8540362012-11-27 15:01:55 +00002550 return EmitOverflowCheckedBinOp(op);
2551
Lang Hamesbe9af122012-10-02 04:45:10 +00002552 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2553 // Try to form an fmuladd.
2554 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2555 return FMulAdd;
2556
John McCall913dab22011-06-25 01:32:37 +00002557 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
Lang Hamesbe9af122012-10-02 04:45:10 +00002558 }
John McCall913dab22011-06-25 01:32:37 +00002559
2560 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2561}
2562
2563Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2564 // The LHS is always a pointer if either side is.
2565 if (!op.LHS->getType()->isPointerTy()) {
2566 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith7edf9e32012-11-01 22:30:59 +00002567 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattnera4d71452010-06-26 21:25:03 +00002568 case LangOptions::SOB_Defined:
John McCall913dab22011-06-25 01:32:37 +00002569 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith9d3e2262012-08-25 00:32:28 +00002570 case LangOptions::SOB_Undefined:
Stephen Hines176edba2014-12-01 14:53:08 -08002571 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith9d3e2262012-08-25 00:32:28 +00002572 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2573 // Fall through.
Chris Lattnera4d71452010-06-26 21:25:03 +00002574 case LangOptions::SOB_Trapping:
John McCall913dab22011-06-25 01:32:37 +00002575 return EmitOverflowCheckedBinOp(op);
Chris Lattnera4d71452010-06-26 21:25:03 +00002576 }
2577 }
Will Dietzb8540362012-11-27 15:01:55 +00002578
Stephen Hines176edba2014-12-01 14:53:08 -08002579 if (op.Ty->isUnsignedIntegerType() &&
2580 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietzb8540362012-11-27 15:01:55 +00002581 return EmitOverflowCheckedBinOp(op);
2582
Lang Hamesbe9af122012-10-02 04:45:10 +00002583 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2584 // Try to form an fmuladd.
2585 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2586 return FMulAdd;
John McCall913dab22011-06-25 01:32:37 +00002587 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Lang Hamesbe9af122012-10-02 04:45:10 +00002588 }
Chris Lattner2eb91e42010-03-29 17:28:16 +00002589
John McCall913dab22011-06-25 01:32:37 +00002590 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump2add4732009-04-01 20:28:16 +00002591 }
Chris Lattner1f1ded92007-08-24 21:00:35 +00002592
John McCall913dab22011-06-25 01:32:37 +00002593 // If the RHS is not a pointer, then we have normal pointer
2594 // arithmetic.
2595 if (!op.RHS->getType()->isPointerTy())
2596 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmandaa24a22009-03-28 02:45:41 +00002597
John McCall913dab22011-06-25 01:32:37 +00002598 // Otherwise, this is a pointer subtraction.
Daniel Dunbarb09fae72009-01-23 18:51:09 +00002599
John McCall913dab22011-06-25 01:32:37 +00002600 // Do the raw subtraction part.
2601 llvm::Value *LHS
2602 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2603 llvm::Value *RHS
2604 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2605 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbar2a866252009-04-25 05:08:32 +00002606
John McCall913dab22011-06-25 01:32:37 +00002607 // Okay, figure out the element size.
2608 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2609 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002610
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002611 llvm::Value *divisor = nullptr;
John McCall913dab22011-06-25 01:32:37 +00002612
2613 // For a variable-length array, this is going to be non-constant.
2614 if (const VariableArrayType *vla
2615 = CGF.getContext().getAsVariableArrayType(elementType)) {
2616 llvm::Value *numElements;
Stephen Hines651f13c2014-04-23 16:59:28 -07002617 std::tie(numElements, elementType) = CGF.getVLASize(vla);
John McCall913dab22011-06-25 01:32:37 +00002618
2619 divisor = numElements;
2620
2621 // Scale the number of non-VLA elements by the non-VLA element size.
2622 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2623 if (!eltSize.isOne())
2624 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2625
2626 // For everything elese, we can just compute it, safe in the
2627 // assumption that Sema won't let anything through that we can't
2628 // safely compute the size of.
2629 } else {
2630 CharUnits elementSize;
2631 // Handle GCC extension for pointer arithmetic on void* and
2632 // function pointer types.
2633 if (elementType->isVoidType() || elementType->isFunctionType())
2634 elementSize = CharUnits::One();
2635 else
2636 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2637
2638 // Don't even emit the divide for element size of 1.
2639 if (elementSize.isOne())
2640 return diffInChars;
2641
2642 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner7f02f722007-08-24 05:35:26 +00002643 }
Craig Topperd10e5c22013-07-26 06:16:11 +00002644
Chris Lattner2cb42222011-03-01 00:03:48 +00002645 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2646 // pointer difference in C is only defined in the case where both operands
2647 // are pointing to elements of an array.
John McCall913dab22011-06-25 01:32:37 +00002648 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner7f02f722007-08-24 05:35:26 +00002649}
2650
David Tweed7a834212013-01-07 16:43:27 +00002651Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
David Tweedf20318f2013-01-10 09:11:33 +00002652 llvm::IntegerType *Ty;
2653 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2654 Ty = cast<llvm::IntegerType>(VT->getElementType());
2655 else
2656 Ty = cast<llvm::IntegerType>(LHS->getType());
2657 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
David Tweed7a834212013-01-07 16:43:27 +00002658}
2659
Chris Lattner7f02f722007-08-24 05:35:26 +00002660Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2661 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2662 // RHS to the same size as the LHS.
2663 Value *RHS = Ops.RHS;
2664 if (Ops.LHS->getType() != RHS->getType())
2665 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002666
Stephen Hines176edba2014-12-01 14:53:08 -08002667 if (CGF.SanOpts.has(SanitizerKind::Shift) && !CGF.getLangOpts().OpenCL &&
Will Dietz4f45bc02013-01-18 11:30:38 +00002668 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Stephen Hines176edba2014-12-01 14:53:08 -08002669 CodeGenFunction::SanitizerScope SanScope(&CGF);
David Tweed7a834212013-01-07 16:43:27 +00002670 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, RHS);
Will Dietzbb60fc62013-02-25 22:37:49 +00002671 llvm::Value *Valid = Builder.CreateICmpULE(RHS, WidthMinusOne);
Richard Smith9d3e2262012-08-25 00:32:28 +00002672
2673 if (Ops.Ty->hasSignedIntegerRepresentation()) {
Will Dietzbb60fc62013-02-25 22:37:49 +00002674 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
2675 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
2676 llvm::BasicBlock *CheckBitsShifted = CGF.createBasicBlock("check");
2677 Builder.CreateCondBr(Valid, CheckBitsShifted, Cont);
2678
Richard Smith9d3e2262012-08-25 00:32:28 +00002679 // Check whether we are shifting any non-zero bits off the top of the
2680 // integer.
Will Dietzbb60fc62013-02-25 22:37:49 +00002681 CGF.EmitBlock(CheckBitsShifted);
Richard Smith9d3e2262012-08-25 00:32:28 +00002682 llvm::Value *BitsShiftedOff =
2683 Builder.CreateLShr(Ops.LHS,
2684 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2685 /*NUW*/true, /*NSW*/true),
2686 "shl.check");
2687 if (CGF.getLangOpts().CPlusPlus) {
2688 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2689 // Under C++11's rules, shifting a 1 bit into the sign bit is
2690 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2691 // define signed left shifts, so we use the C99 and C++11 rules there).
2692 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2693 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2694 }
2695 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Will Dietzbb60fc62013-02-25 22:37:49 +00002696 llvm::Value *SecondCheck = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
2697 CGF.EmitBlock(Cont);
2698 llvm::PHINode *P = Builder.CreatePHI(Valid->getType(), 2);
2699 P->addIncoming(Valid, Orig);
2700 P->addIncoming(SecondCheck, CheckBitsShifted);
2701 Valid = P;
Richard Smith9d3e2262012-08-25 00:32:28 +00002702 }
Will Dietzbb60fc62013-02-25 22:37:49 +00002703
Stephen Hines176edba2014-12-01 14:53:08 -08002704 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::Shift), Ops);
Mike Stumpbe07f602009-12-14 21:58:14 +00002705 }
David Tweed7a834212013-01-07 16:43:27 +00002706 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2707 if (CGF.getLangOpts().OpenCL)
2708 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
Mike Stumpbe07f602009-12-14 21:58:14 +00002709
Chris Lattner7f02f722007-08-24 05:35:26 +00002710 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2711}
2712
2713Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2714 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2715 // RHS to the same size as the LHS.
2716 Value *RHS = Ops.RHS;
2717 if (Ops.LHS->getType() != RHS->getType())
2718 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002719
Stephen Hines176edba2014-12-01 14:53:08 -08002720 if (CGF.SanOpts.has(SanitizerKind::Shift) && !CGF.getLangOpts().OpenCL &&
2721 isa<llvm::IntegerType>(Ops.LHS->getType())) {
2722 CodeGenFunction::SanitizerScope SanScope(&CGF);
2723 llvm::Value *Valid =
2724 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
2725 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::Shift), Ops);
2726 }
David Tweed7a834212013-01-07 16:43:27 +00002727
2728 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2729 if (CGF.getLangOpts().OpenCL)
2730 RHS = Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
Mike Stumpbe07f602009-12-14 21:58:14 +00002731
Douglas Gregorf6094622010-07-23 15:58:24 +00002732 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner7f02f722007-08-24 05:35:26 +00002733 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2734 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2735}
2736
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002737enum IntrinsicType { VCMPEQ, VCMPGT };
2738// return corresponding comparison intrinsic for given vector type
2739static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2740 BuiltinType::Kind ElemKind) {
2741 switch (ElemKind) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002742 default: llvm_unreachable("unexpected element type");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002743 case BuiltinType::Char_U:
2744 case BuiltinType::UChar:
2745 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2746 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002747 case BuiltinType::Char_S:
2748 case BuiltinType::SChar:
2749 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2750 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002751 case BuiltinType::UShort:
2752 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2753 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002754 case BuiltinType::Short:
2755 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2756 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002757 case BuiltinType::UInt:
2758 case BuiltinType::ULong:
2759 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2760 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002761 case BuiltinType::Int:
2762 case BuiltinType::Long:
2763 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2764 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002765 case BuiltinType::Float:
2766 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2767 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002768 }
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002769}
2770
Chris Lattner7f02f722007-08-24 05:35:26 +00002771Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2772 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002773 TestAndClearIgnoreResultAssign();
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002774 Value *Result;
Chris Lattner7f02f722007-08-24 05:35:26 +00002775 QualType LHSTy = E->getLHS()->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08002776 QualType RHSTy = E->getRHS()->getType();
John McCall0bab0cd2010-08-23 01:21:21 +00002777 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCall2de56d12010-08-25 11:45:40 +00002778 assert(E->getOpcode() == BO_EQ ||
2779 E->getOpcode() == BO_NE);
John McCalld608cdb2010-08-22 10:59:02 +00002780 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2781 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall0bab0cd2010-08-23 01:21:21 +00002782 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCall2de56d12010-08-25 11:45:40 +00002783 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Stephen Hines176edba2014-12-01 14:53:08 -08002784 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002785 Value *LHS = Visit(E->getLHS());
2786 Value *RHS = Visit(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002787
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002788 // If AltiVec, the comparison results in a numeric type, so we use
2789 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev6305f722011-03-28 21:00:05 +00002790 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002791 // constants for mapping CR6 register bits to predicate result
2792 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2793
2794 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2795
2796 // in several cases vector arguments order will be reversed
2797 Value *FirstVecArg = LHS,
2798 *SecondVecArg = RHS;
2799
2800 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCallf4c73712011-01-19 06:33:43 +00002801 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002802 BuiltinType::Kind ElementKind = BTy->getKind();
2803
2804 switch(E->getOpcode()) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002805 default: llvm_unreachable("is not a comparison operation");
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002806 case BO_EQ:
2807 CR6 = CR6_LT;
2808 ID = GetIntrinsic(VCMPEQ, ElementKind);
2809 break;
2810 case BO_NE:
2811 CR6 = CR6_EQ;
2812 ID = GetIntrinsic(VCMPEQ, ElementKind);
2813 break;
2814 case BO_LT:
2815 CR6 = CR6_LT;
2816 ID = GetIntrinsic(VCMPGT, ElementKind);
2817 std::swap(FirstVecArg, SecondVecArg);
2818 break;
2819 case BO_GT:
2820 CR6 = CR6_LT;
2821 ID = GetIntrinsic(VCMPGT, ElementKind);
2822 break;
2823 case BO_LE:
2824 if (ElementKind == BuiltinType::Float) {
2825 CR6 = CR6_LT;
2826 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2827 std::swap(FirstVecArg, SecondVecArg);
2828 }
2829 else {
2830 CR6 = CR6_EQ;
2831 ID = GetIntrinsic(VCMPGT, ElementKind);
2832 }
2833 break;
2834 case BO_GE:
2835 if (ElementKind == BuiltinType::Float) {
2836 CR6 = CR6_LT;
2837 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2838 }
2839 else {
2840 CR6 = CR6_EQ;
2841 ID = GetIntrinsic(VCMPGT, ElementKind);
2842 std::swap(FirstVecArg, SecondVecArg);
2843 }
2844 break;
2845 }
2846
Chris Lattner48431f92011-04-19 22:55:03 +00002847 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsevaa4fe052010-11-18 03:19:30 +00002848 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
2849 Result = Builder.CreateCall3(F, CR6Param, FirstVecArg, SecondVecArg, "");
2850 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2851 }
2852
Duncan Sandsf177d9d2010-02-15 16:14:01 +00002853 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begeman7a66d7b2008-07-25 20:16:05 +00002854 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002855 LHS, RHS, "cmp");
Douglas Gregorf6094622010-07-23 15:58:24 +00002856 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002857 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002858 LHS, RHS, "cmp");
2859 } else {
Eli Friedmanec2c1262008-05-29 15:09:15 +00002860 // Unsigned integers and pointers.
2861 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner7f02f722007-08-24 05:35:26 +00002862 LHS, RHS, "cmp");
2863 }
Chris Lattner9c10fcf2009-07-08 01:08:03 +00002864
2865 // If this is a vector comparison, sign extend the result to the appropriate
2866 // vector integer type and return it (don't convert to bool).
2867 if (LHSTy->isVectorType())
2868 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002869
Chris Lattner7f02f722007-08-24 05:35:26 +00002870 } else {
2871 // Complex Comparison: can only be an equality comparison.
Stephen Hines176edba2014-12-01 14:53:08 -08002872 CodeGenFunction::ComplexPairTy LHS, RHS;
2873 QualType CETy;
2874 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
2875 LHS = CGF.EmitComplexExpr(E->getLHS());
2876 CETy = CTy->getElementType();
2877 } else {
2878 LHS.first = Visit(E->getLHS());
2879 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
2880 CETy = LHSTy;
2881 }
2882 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
2883 RHS = CGF.EmitComplexExpr(E->getRHS());
2884 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
2885 CTy->getElementType()) &&
2886 "The element types must always match.");
2887 (void)CTy;
2888 } else {
2889 RHS.first = Visit(E->getRHS());
2890 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
2891 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
2892 "The element types must always match.");
2893 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002894
Chris Lattner4f1a7b32007-08-26 16:34:22 +00002895 Value *ResultR, *ResultI;
Chris Lattner7f02f722007-08-24 05:35:26 +00002896 if (CETy->isRealFloatingType()) {
2897 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2898 LHS.first, RHS.first, "cmp.r");
2899 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2900 LHS.second, RHS.second, "cmp.i");
2901 } else {
2902 // Complex comparisons can only be equality comparisons. As such, signed
2903 // and unsigned opcodes are the same.
2904 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2905 LHS.first, RHS.first, "cmp.r");
2906 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2907 LHS.second, RHS.second, "cmp.i");
2908 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002909
John McCall2de56d12010-08-25 11:45:40 +00002910 if (E->getOpcode() == BO_EQ) {
Chris Lattner7f02f722007-08-24 05:35:26 +00002911 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2912 } else {
John McCall2de56d12010-08-25 11:45:40 +00002913 assert(E->getOpcode() == BO_NE &&
Chris Lattner7f02f722007-08-24 05:35:26 +00002914 "Complex comparison other than == or != ?");
2915 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2916 }
2917 }
Nuno Lopes32f62092009-01-11 23:22:37 +00002918
2919 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner7f02f722007-08-24 05:35:26 +00002920}
2921
2922Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00002923 bool Ignore = TestAndClearIgnoreResultAssign();
2924
John McCallf85e1932011-06-15 23:02:42 +00002925 Value *RHS;
2926 LValue LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00002927
John McCallf85e1932011-06-15 23:02:42 +00002928 switch (E->getLHS()->getType().getObjCLifetime()) {
2929 case Qualifiers::OCL_Strong:
Stephen Hines651f13c2014-04-23 16:59:28 -07002930 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
John McCallf85e1932011-06-15 23:02:42 +00002931 break;
2932
2933 case Qualifiers::OCL_Autoreleasing:
Stephen Hines651f13c2014-04-23 16:59:28 -07002934 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
John McCallf85e1932011-06-15 23:02:42 +00002935 break;
2936
2937 case Qualifiers::OCL_Weak:
2938 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002939 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002940 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
2941 break;
2942
2943 // No reason to do any of these differently.
2944 case Qualifiers::OCL_None:
2945 case Qualifiers::OCL_ExplicitNone:
2946 // __block variables need to have the rhs evaluated first, plus
2947 // this should improve codegen just a little.
2948 RHS = Visit(E->getRHS());
Richard Smith7ac9ef12012-09-08 02:08:36 +00002949 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCallf85e1932011-06-15 23:02:42 +00002950
2951 // Store the value into the LHS. Bit-fields are handled specially
2952 // because the result is altered by the store, i.e., [C99 6.5.16p1]
2953 // 'An assignment expression has the value of the left operand after
2954 // the assignment...'.
2955 if (LHS.isBitField())
John McCall545d9962011-06-25 02:11:03 +00002956 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCallf85e1932011-06-15 23:02:42 +00002957 else
John McCall545d9962011-06-25 02:11:03 +00002958 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCallf85e1932011-06-15 23:02:42 +00002959 }
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002960
2961 // If the result is clearly ignored, return now.
Mike Stump7f79f9b2009-05-29 15:46:01 +00002962 if (Ignore)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002963 return nullptr;
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002964
John McCallb418d742010-11-16 10:08:07 +00002965 // The result of an assignment in C is the assigned r-value.
Richard Smith7edf9e32012-11-01 22:30:59 +00002966 if (!CGF.getLangOpts().CPlusPlus)
John McCallb418d742010-11-16 10:08:07 +00002967 return RHS;
2968
Daniel Dunbard7f7d082010-06-29 22:00:45 +00002969 // If the lvalue is non-volatile, return the computed value of the assignment.
2970 if (!LHS.isVolatileQualified())
2971 return RHS;
2972
2973 // Otherwise, reload the value.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002974 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner7f02f722007-08-24 05:35:26 +00002975}
2976
2977Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002978 RegionCounter Cnt = CGF.getPGORegionCounter(E);
2979
Tanya Lattner4f692c22012-01-16 21:02:28 +00002980 // Perform vector logical and on comparisons with zero vectors.
2981 if (E->getType()->isVectorType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002982 Cnt.beginRegion(Builder);
2983
Tanya Lattner4f692c22012-01-16 21:02:28 +00002984 Value *LHS = Visit(E->getLHS());
2985 Value *RHS = Visit(E->getRHS());
2986 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly52e933b2013-02-21 11:49:56 +00002987 if (LHS->getType()->isFPOrFPVectorTy()) {
2988 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
2989 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
2990 } else {
2991 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
2992 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
2993 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00002994 Value *And = Builder.CreateAnd(LHS, RHS);
Joey Gouly52e933b2013-02-21 11:49:56 +00002995 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
Tanya Lattner4f692c22012-01-16 21:02:28 +00002996 }
Craig Topperd10e5c22013-07-26 06:16:11 +00002997
Chris Lattner2acc6e32011-07-18 04:24:23 +00002998 llvm::Type *ResTy = ConvertType(E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00002999
Chris Lattner20eb09d2008-11-12 08:26:50 +00003000 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
3001 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00003002 bool LHSCondVal;
3003 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3004 if (LHSCondVal) { // If we have 1 && X, just emit X.
Stephen Hines651f13c2014-04-23 16:59:28 -07003005 Cnt.beginRegion(Builder);
3006
Chris Lattner0946ccd2008-11-11 07:41:27 +00003007 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00003008 // ZExt result to int or bool.
3009 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00003010 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003011
Chris Lattner7804bcb2009-10-17 04:24:20 +00003012 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner20eb09d2008-11-12 08:26:50 +00003013 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00003014 return llvm::Constant::getNullValue(ResTy);
Chris Lattner0946ccd2008-11-11 07:41:27 +00003015 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003016
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00003017 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3018 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner20eb09d2008-11-12 08:26:50 +00003019
John McCall150b4622011-01-26 04:00:11 +00003020 CodeGenFunction::ConditionalEvaluation eval(CGF);
3021
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003022 // Branch on the LHS first. If it is false, go to the failure (cont) block.
Stephen Hines651f13c2014-04-23 16:59:28 -07003023 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock, Cnt.getCount());
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003024
3025 // Any edges into the ContBlock are now from an (indeterminate number of)
3026 // edges from this first condition. All of these values will be false. Start
3027 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00003028 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00003029 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003030 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3031 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00003032 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003033
John McCall150b4622011-01-26 04:00:11 +00003034 eval.begin(CGF);
Chris Lattner7f02f722007-08-24 05:35:26 +00003035 CGF.EmitBlock(RHSBlock);
Stephen Hines651f13c2014-04-23 16:59:28 -07003036 Cnt.beginRegion(Builder);
Chris Lattner7f02f722007-08-24 05:35:26 +00003037 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCall150b4622011-01-26 04:00:11 +00003038 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003039
Chris Lattner7f02f722007-08-24 05:35:26 +00003040 // Reaquire the RHS block, as there may be subblocks inserted.
3041 RHSBlock = Builder.GetInsertBlock();
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003042
Stephen Hines176edba2014-12-01 14:53:08 -08003043 // Emit an unconditional branch from this block to ContBlock.
3044 {
Devang Patelacd72362011-03-30 00:08:31 +00003045 // There is no need to emit line number for unconditional branch.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003046 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
Stephen Hines176edba2014-12-01 14:53:08 -08003047 CGF.EmitBlock(ContBlock);
3048 }
3049 // Insert an entry into the phi node for the edge with the value of RHSCond.
Chris Lattner7f02f722007-08-24 05:35:26 +00003050 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003051
Chris Lattner7f02f722007-08-24 05:35:26 +00003052 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00003053 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00003054}
3055
3056Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003057 RegionCounter Cnt = CGF.getPGORegionCounter(E);
3058
Tanya Lattner4f692c22012-01-16 21:02:28 +00003059 // Perform vector logical or on comparisons with zero vectors.
3060 if (E->getType()->isVectorType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003061 Cnt.beginRegion(Builder);
3062
Tanya Lattner4f692c22012-01-16 21:02:28 +00003063 Value *LHS = Visit(E->getLHS());
3064 Value *RHS = Visit(E->getRHS());
3065 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly52e933b2013-02-21 11:49:56 +00003066 if (LHS->getType()->isFPOrFPVectorTy()) {
3067 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3068 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3069 } else {
3070 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3071 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3072 }
Tanya Lattner4f692c22012-01-16 21:02:28 +00003073 Value *Or = Builder.CreateOr(LHS, RHS);
Joey Gouly52e933b2013-02-21 11:49:56 +00003074 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
Tanya Lattner4f692c22012-01-16 21:02:28 +00003075 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003076
Chris Lattner2acc6e32011-07-18 04:24:23 +00003077 llvm::Type *ResTy = ConvertType(E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00003078
Chris Lattner20eb09d2008-11-12 08:26:50 +00003079 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
3080 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattnerc2c90012011-02-27 23:02:32 +00003081 bool LHSCondVal;
3082 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3083 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Stephen Hines651f13c2014-04-23 16:59:28 -07003084 Cnt.beginRegion(Builder);
3085
Chris Lattner0946ccd2008-11-11 07:41:27 +00003086 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner7804bcb2009-10-17 04:24:20 +00003087 // ZExt result to int or bool.
3088 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner0946ccd2008-11-11 07:41:27 +00003089 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003090
Chris Lattner7804bcb2009-10-17 04:24:20 +00003091 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner20eb09d2008-11-12 08:26:50 +00003092 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner7804bcb2009-10-17 04:24:20 +00003093 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner0946ccd2008-11-11 07:41:27 +00003094 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003095
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00003096 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
3097 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003098
John McCall150b4622011-01-26 04:00:11 +00003099 CodeGenFunction::ConditionalEvaluation eval(CGF);
3100
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003101 // Branch on the LHS first. If it is true, go to the success (cont) block.
Stephen Hines651f13c2014-04-23 16:59:28 -07003102 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
3103 Cnt.getParentCount() - Cnt.getCount());
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003104
3105 // Any edges into the ContBlock are now from an (indeterminate number of)
3106 // edges from this first condition. All of these values will be true. Start
3107 // setting up the PHI node in the Cont Block for this.
Jay Foadbbf3bac2011-03-30 11:28:58 +00003108 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson0032b272009-08-13 21:57:51 +00003109 "", ContBlock);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003110 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3111 PI != PE; ++PI)
Owen Anderson3b144ba2009-07-31 17:39:36 +00003112 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003113
John McCall150b4622011-01-26 04:00:11 +00003114 eval.begin(CGF);
Anders Carlsson33da07d2009-06-04 02:53:13 +00003115
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003116 // Emit the RHS condition as a bool value.
Chris Lattner7f02f722007-08-24 05:35:26 +00003117 CGF.EmitBlock(RHSBlock);
Stephen Hines651f13c2014-04-23 16:59:28 -07003118 Cnt.beginRegion(Builder);
Chris Lattner7f02f722007-08-24 05:35:26 +00003119 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003120
John McCall150b4622011-01-26 04:00:11 +00003121 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003122
Chris Lattner7f02f722007-08-24 05:35:26 +00003123 // Reaquire the RHS block, as there may be subblocks inserted.
3124 RHSBlock = Builder.GetInsertBlock();
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003125
Chris Lattnerf7b5ea92008-11-12 08:38:24 +00003126 // Emit an unconditional branch from this block to ContBlock. Insert an entry
3127 // into the phi node for the edge with the value of RHSCond.
3128 CGF.EmitBlock(ContBlock);
Chris Lattner7f02f722007-08-24 05:35:26 +00003129 PN->addIncoming(RHSCond, RHSBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003130
Chris Lattner7f02f722007-08-24 05:35:26 +00003131 // ZExt result to int.
Chris Lattner7804bcb2009-10-17 04:24:20 +00003132 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner7f02f722007-08-24 05:35:26 +00003133}
3134
3135Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCall2a416372010-12-05 02:00:02 +00003136 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbara448fb22008-11-11 23:11:34 +00003137 CGF.EnsureInsertPoint();
Chris Lattner7f02f722007-08-24 05:35:26 +00003138 return Visit(E->getRHS());
3139}
3140
3141//===----------------------------------------------------------------------===//
3142// Other Operators
3143//===----------------------------------------------------------------------===//
3144
Chris Lattner9802a512008-11-12 08:55:54 +00003145/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
3146/// expression is cheap enough and side-effect-free enough to evaluate
3147/// unconditionally instead of conditionally. This is used to convert control
3148/// flow into selects in some cases.
Mike Stumpdf317bf2009-11-03 23:25:48 +00003149static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
3150 CodeGenFunction &CGF) {
Chris Lattnerc6bea672011-04-16 23:15:35 +00003151 // Anything that is an integer or floating point constant is fine.
Nick Lewyckyc5699172013-11-08 23:00:12 +00003152 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003153
Nick Lewyckyc5699172013-11-08 23:00:12 +00003154 // Even non-volatile automatic variables can't be evaluated unconditionally.
3155 // Referencing a thread_local may cause non-trivial initialization work to
3156 // occur. If we're inside a lambda and one of the variables is from the scope
3157 // outside the lambda, that function may have returned already. Reading its
3158 // locals is a bad idea. Also, these reads may introduce races there didn't
3159 // exist in the source-level program.
Chris Lattner9802a512008-11-12 08:55:54 +00003160}
3161
3162
Chris Lattner7f02f722007-08-24 05:35:26 +00003163Value *ScalarExprEmitter::
John McCall56ca35d2011-02-17 10:25:35 +00003164VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stump7f79f9b2009-05-29 15:46:01 +00003165 TestAndClearIgnoreResultAssign();
John McCall56ca35d2011-02-17 10:25:35 +00003166
3167 // Bind the common expression if necessary.
Eli Friedmand97927d2012-01-06 20:42:20 +00003168 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
Stephen Hines651f13c2014-04-23 16:59:28 -07003169 RegionCounter Cnt = CGF.getPGORegionCounter(E);
John McCall56ca35d2011-02-17 10:25:35 +00003170
3171 Expr *condExpr = E->getCond();
3172 Expr *lhsExpr = E->getTrueExpr();
3173 Expr *rhsExpr = E->getFalseExpr();
3174
Chris Lattner31a09842008-11-12 08:04:58 +00003175 // If the condition constant folds and can be elided, try to avoid emitting
3176 // the condition and the dead arm.
Chris Lattnerc2c90012011-02-27 23:02:32 +00003177 bool CondExprBool;
3178 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCall56ca35d2011-02-17 10:25:35 +00003179 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattnerc2c90012011-02-27 23:02:32 +00003180 if (!CondExprBool) std::swap(live, dead);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003181
Eli Friedmanc8645e32011-10-15 02:10:40 +00003182 // If the dead side doesn't have labels we need, just emit the Live part.
3183 if (!CGF.ContainsLabel(dead)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003184 if (CondExprBool)
3185 Cnt.beginRegion(Builder);
Eli Friedmanc8645e32011-10-15 02:10:40 +00003186 Value *Result = Visit(live);
3187
3188 // If the live part is a throw expression, it acts like it has a void
3189 // type, so evaluating it returns a null Value*. However, a conditional
3190 // with non-void type must return a non-null Value*.
3191 if (!Result && !E->getType()->isVoidType())
3192 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
3193
3194 return Result;
3195 }
Chris Lattnerc657e922008-11-11 18:56:45 +00003196 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003197
Nate Begeman6155d732010-09-20 22:41:17 +00003198 // OpenCL: If the condition is a vector, we can treat this condition like
3199 // the select function.
Craig Topperd10e5c22013-07-26 06:16:11 +00003200 if (CGF.getLangOpts().OpenCL
John McCall56ca35d2011-02-17 10:25:35 +00003201 && condExpr->getType()->isVectorType()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003202 Cnt.beginRegion(Builder);
3203
John McCall56ca35d2011-02-17 10:25:35 +00003204 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3205 llvm::Value *LHS = Visit(lhsExpr);
3206 llvm::Value *RHS = Visit(rhsExpr);
Craig Topperd10e5c22013-07-26 06:16:11 +00003207
Chris Lattner2acc6e32011-07-18 04:24:23 +00003208 llvm::Type *condType = ConvertType(condExpr->getType());
3209 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Craig Topperd10e5c22013-07-26 06:16:11 +00003210
3211 unsigned numElem = vecTy->getNumElements();
Chris Lattner2acc6e32011-07-18 04:24:23 +00003212 llvm::Type *elemType = vecTy->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00003213
Chris Lattner2ce88422012-01-25 05:34:41 +00003214 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begeman6155d732010-09-20 22:41:17 +00003215 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
Craig Topperd10e5c22013-07-26 06:16:11 +00003216 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
Nate Begeman6155d732010-09-20 22:41:17 +00003217 llvm::VectorType::get(elemType,
Craig Topperd10e5c22013-07-26 06:16:11 +00003218 numElem),
Nate Begeman6155d732010-09-20 22:41:17 +00003219 "sext");
3220 llvm::Value *tmp2 = Builder.CreateNot(tmp);
Craig Topperd10e5c22013-07-26 06:16:11 +00003221
Nate Begeman6155d732010-09-20 22:41:17 +00003222 // Cast float to int to perform ANDs if necessary.
3223 llvm::Value *RHSTmp = RHS;
3224 llvm::Value *LHSTmp = LHS;
3225 bool wasCast = false;
Chris Lattner2acc6e32011-07-18 04:24:23 +00003226 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourne565204d2012-05-29 00:35:18 +00003227 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begeman6155d732010-09-20 22:41:17 +00003228 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
3229 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
3230 wasCast = true;
3231 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003232
Nate Begeman6155d732010-09-20 22:41:17 +00003233 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
3234 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
3235 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
3236 if (wasCast)
3237 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3238
3239 return tmp5;
3240 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003241
Chris Lattner9802a512008-11-12 08:55:54 +00003242 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3243 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner531a5502008-11-16 06:16:27 +00003244 // safe to evaluate the LHS and RHS unconditionally.
John McCall56ca35d2011-02-17 10:25:35 +00003245 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
3246 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003247 Cnt.beginRegion(Builder);
3248
John McCall56ca35d2011-02-17 10:25:35 +00003249 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3250 llvm::Value *LHS = Visit(lhsExpr);
3251 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman1e4f68c2011-12-08 22:01:56 +00003252 if (!LHS) {
3253 // If the conditional has void type, make sure we return a null Value*.
3254 assert(!RHS && "LHS and RHS types must match");
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003255 return nullptr;
Eli Friedman1e4f68c2011-12-08 22:01:56 +00003256 }
Chris Lattner9802a512008-11-12 08:55:54 +00003257 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3258 }
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003259
Daniel Dunbarbe65abc2008-11-12 10:13:37 +00003260 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3261 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbar9615ecb2008-11-13 01:38:36 +00003262 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCall150b4622011-01-26 04:00:11 +00003263
3264 CodeGenFunction::ConditionalEvaluation eval(CGF);
Stephen Hines651f13c2014-04-23 16:59:28 -07003265 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock, Cnt.getCount());
Anders Carlssonfb6fa302009-06-04 03:00:32 +00003266
Chris Lattner7f02f722007-08-24 05:35:26 +00003267 CGF.EmitBlock(LHSBlock);
Stephen Hines651f13c2014-04-23 16:59:28 -07003268 Cnt.beginRegion(Builder);
John McCall150b4622011-01-26 04:00:11 +00003269 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00003270 Value *LHS = Visit(lhsExpr);
John McCall150b4622011-01-26 04:00:11 +00003271 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003272
Chris Lattner7f02f722007-08-24 05:35:26 +00003273 LHSBlock = Builder.GetInsertBlock();
John McCall150b4622011-01-26 04:00:11 +00003274 Builder.CreateBr(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003275
Chris Lattner7f02f722007-08-24 05:35:26 +00003276 CGF.EmitBlock(RHSBlock);
John McCall150b4622011-01-26 04:00:11 +00003277 eval.begin(CGF);
John McCall56ca35d2011-02-17 10:25:35 +00003278 Value *RHS = Visit(rhsExpr);
John McCall150b4622011-01-26 04:00:11 +00003279 eval.end(CGF);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003280
John McCall150b4622011-01-26 04:00:11 +00003281 RHSBlock = Builder.GetInsertBlock();
Chris Lattner7f02f722007-08-24 05:35:26 +00003282 CGF.EmitBlock(ContBlock);
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003283
Eli Friedman48daf592009-12-07 20:25:53 +00003284 // If the LHS or RHS is a throw expression, it will be legitimately null.
3285 if (!LHS)
3286 return RHS;
3287 if (!RHS)
3288 return LHS;
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003289
Chris Lattner7f02f722007-08-24 05:35:26 +00003290 // Create a PHI node for the real part.
Jay Foadbbf3bac2011-03-30 11:28:58 +00003291 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner7f02f722007-08-24 05:35:26 +00003292 PN->addIncoming(LHS, LHSBlock);
3293 PN->addIncoming(RHS, RHSBlock);
3294 return PN;
3295}
3296
3297Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedmana5e66012013-07-20 00:40:58 +00003298 return Visit(E->getChosenSubExpr());
Chris Lattner7f02f722007-08-24 05:35:26 +00003299}
3300
Chris Lattner2202bce2007-11-30 17:56:23 +00003301Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003302 QualType Ty = VE->getType();
Stephen Hines176edba2014-12-01 14:53:08 -08003303
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003304 if (Ty->isVariablyModifiedType())
3305 CGF.EmitVariablyModifiedType(Ty);
3306
Eli Friedman4fd0aa52009-01-20 17:46:04 +00003307 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00003308 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
Stephen Hines176edba2014-12-01 14:53:08 -08003309 llvm::Type *ArgTy = ConvertType(VE->getType());
Anders Carlssonddf7cac2008-11-04 05:30:00 +00003310
3311 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003312 if (!ArgPtr)
Stephen Hines176edba2014-12-01 14:53:08 -08003313 return Builder.CreateVAArg(ArgValue, ArgTy);
Anders Carlssonddf7cac2008-11-04 05:30:00 +00003314
Mike Stump7f79f9b2009-05-29 15:46:01 +00003315 // FIXME Volatility.
Stephen Hines176edba2014-12-01 14:53:08 -08003316 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
3317
3318 // If EmitVAArg promoted the type, we must truncate it.
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003319 if (ArgTy != Val->getType()) {
3320 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
3321 Val = Builder.CreateIntToPtr(Val, ArgTy);
3322 else
3323 Val = Builder.CreateTrunc(Val, ArgTy);
3324 }
Stephen Hines176edba2014-12-01 14:53:08 -08003325
3326 return Val;
Anders Carlsson7c50aca2007-10-15 20:28:48 +00003327}
3328
John McCall6b5a61b2011-02-07 10:33:21 +00003329Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3330 return CGF.EmitBlockLiteral(block);
Mike Stumpdf6b68c2009-02-12 18:29:15 +00003331}
3332
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003333Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3334 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2acc6e32011-07-18 04:24:23 +00003335 llvm::Type *DstTy = ConvertType(E->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00003336
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003337 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
3338 // a shuffle vector instead of a bitcast.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003339 llvm::Type *SrcTy = Src->getType();
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003340 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
3341 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
3342 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
Craig Topperd10e5c22013-07-26 06:16:11 +00003343 if ((numElementsDst == 3 && numElementsSrc == 4)
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003344 || (numElementsDst == 4 && numElementsSrc == 3)) {
Craig Topperd10e5c22013-07-26 06:16:11 +00003345
3346
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003347 // In the case of going from int4->float3, a bitcast is needed before
3348 // doing a shuffle.
Craig Topperd10e5c22013-07-26 06:16:11 +00003349 llvm::Type *srcElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003350 cast<llvm::VectorType>(SrcTy)->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00003351 llvm::Type *dstElemTy =
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003352 cast<llvm::VectorType>(DstTy)->getElementType();
Craig Topperd10e5c22013-07-26 06:16:11 +00003353
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003354 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
3355 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
3356 // Create a float type of the same size as the source or destination.
Chris Lattner2acc6e32011-07-18 04:24:23 +00003357 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003358 numElementsSrc);
Craig Topperd10e5c22013-07-26 06:16:11 +00003359
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003360 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
3361 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003362
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003363 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
Craig Topperd10e5c22013-07-26 06:16:11 +00003364
Chris Lattner5f9e2722011-07-23 10:55:15 +00003365 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003366 Args.push_back(Builder.getInt32(0));
3367 Args.push_back(Builder.getInt32(1));
3368 Args.push_back(Builder.getInt32(2));
Craig Topperd10e5c22013-07-26 06:16:11 +00003369
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003370 if (numElementsDst == 4)
Chris Lattner8b418682012-02-07 00:39:47 +00003371 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Craig Topperd10e5c22013-07-26 06:16:11 +00003372
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003373 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Craig Topperd10e5c22013-07-26 06:16:11 +00003374
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003375 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3376 }
3377 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003378
Tanya Lattner61eee0c2011-06-04 00:47:47 +00003379 return Builder.CreateBitCast(Src, DstTy, "astype");
3380}
3381
Eli Friedman276b0612011-10-11 02:20:01 +00003382Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3383 return CGF.EmitAtomicExpr(E).getScalarVal();
3384}
3385
Chris Lattner7f02f722007-08-24 05:35:26 +00003386//===----------------------------------------------------------------------===//
3387// Entry Point into this File
3388//===----------------------------------------------------------------------===//
3389
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003390/// EmitScalarExpr - Emit the computation of the specified expression of scalar
3391/// type, ignoring the result.
Mike Stump7f79f9b2009-05-29 15:46:01 +00003392Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
John McCall9d232c82013-03-07 21:37:08 +00003393 assert(E && hasScalarEvaluationKind(E->getType()) &&
Chris Lattner7f02f722007-08-24 05:35:26 +00003394 "Invalid scalar expression to emit");
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003395
Stephen Hines0e2c34f2015-03-23 12:09:02 -07003396 return ScalarExprEmitter(*this, IgnoreResultAssign)
3397 .Visit(const_cast<Expr *>(E));
Chris Lattner7f02f722007-08-24 05:35:26 +00003398}
Chris Lattner3707b252007-08-26 06:48:56 +00003399
3400/// EmitScalarConversion - Emit a conversion from the specified type to the
3401/// specified destination type, both of which are LLVM scalar types.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003402Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3403 QualType DstTy) {
John McCall9d232c82013-03-07 21:37:08 +00003404 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
Chris Lattner3707b252007-08-26 06:48:56 +00003405 "Invalid scalar expression to emit");
3406 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3407}
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003408
Mike Stumpdb52dcd2009-09-09 13:00:44 +00003409/// EmitComplexToScalarConversion - Emit a conversion from the specified complex
3410/// type to the specified destination type, where the destination type is an
3411/// LLVM scalar type.
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003412Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3413 QualType SrcTy,
3414 QualType DstTy) {
John McCall9d232c82013-03-07 21:37:08 +00003415 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
Chris Lattner4f1a7b32007-08-26 16:34:22 +00003416 "Invalid complex -> scalar conversion");
3417 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3418 DstTy);
3419}
Anders Carlssoncc23aca2007-12-10 19:35:18 +00003420
Chris Lattner8c11a652010-06-26 22:09:34 +00003421
3422llvm::Value *CodeGenFunction::
3423EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3424 bool isInc, bool isPre) {
3425 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3426}
3427
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003428LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3429 llvm::Value *V;
3430 // object->isa or (*object).isa
3431 // Generate code as for: *(Class*)object
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003432 // build Class* type
Chris Lattner2acc6e32011-07-18 04:24:23 +00003433 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003434
3435 Expr *BaseExpr = E->getBase();
John McCall7eb0a9e2010-11-24 05:12:34 +00003436 if (BaseExpr->isRValue()) {
Eli Friedmand71f4422011-12-19 23:03:09 +00003437 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003438 llvm::Value *Src = EmitScalarExpr(BaseExpr);
3439 Builder.CreateStore(Src, V);
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003440 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00003441 MakeNaturalAlignAddrLValue(V, E->getType()), E->getExprLoc());
Daniel Dunbar9f553f52010-08-21 03:08:16 +00003442 } else {
3443 if (E->isArrow())
3444 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3445 else
3446 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003447 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003448
Fariborz Jahanian5ed676c2010-02-05 19:18:30 +00003449 // build Class* type
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003450 ClassPtrTy = ClassPtrTy->getPointerTo();
3451 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedmand71f4422011-12-19 23:03:09 +00003452 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian820bca42009-12-09 23:35:29 +00003453}
3454
Douglas Gregor6a03e342010-04-23 04:16:32 +00003455
John McCall2a416372010-12-05 02:00:02 +00003456LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor6a03e342010-04-23 04:16:32 +00003457 const CompoundAssignOperator *E) {
3458 ScalarExprEmitter Scalar(*this);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003459 Value *Result = nullptr;
Douglas Gregor6a03e342010-04-23 04:16:32 +00003460 switch (E->getOpcode()) {
3461#define COMPOUND_OP(Op) \
John McCall2de56d12010-08-25 11:45:40 +00003462 case BO_##Op##Assign: \
Douglas Gregor6a03e342010-04-23 04:16:32 +00003463 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbard7f7d082010-06-29 22:00:45 +00003464 Result)
Douglas Gregor6a03e342010-04-23 04:16:32 +00003465 COMPOUND_OP(Mul);
3466 COMPOUND_OP(Div);
3467 COMPOUND_OP(Rem);
3468 COMPOUND_OP(Add);
3469 COMPOUND_OP(Sub);
3470 COMPOUND_OP(Shl);
3471 COMPOUND_OP(Shr);
3472 COMPOUND_OP(And);
3473 COMPOUND_OP(Xor);
3474 COMPOUND_OP(Or);
3475#undef COMPOUND_OP
Craig Topperd10e5c22013-07-26 06:16:11 +00003476
John McCall2de56d12010-08-25 11:45:40 +00003477 case BO_PtrMemD:
3478 case BO_PtrMemI:
3479 case BO_Mul:
3480 case BO_Div:
3481 case BO_Rem:
3482 case BO_Add:
3483 case BO_Sub:
3484 case BO_Shl:
3485 case BO_Shr:
3486 case BO_LT:
3487 case BO_GT:
3488 case BO_LE:
3489 case BO_GE:
3490 case BO_EQ:
3491 case BO_NE:
3492 case BO_And:
3493 case BO_Xor:
3494 case BO_Or:
3495 case BO_LAnd:
3496 case BO_LOr:
3497 case BO_Assign:
3498 case BO_Comma:
David Blaikieb219cfc2011-09-23 05:06:16 +00003499 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor6a03e342010-04-23 04:16:32 +00003500 }
Craig Topperd10e5c22013-07-26 06:16:11 +00003501
Douglas Gregor6a03e342010-04-23 04:16:32 +00003502 llvm_unreachable("Unhandled compound assignment operator");
3503}