blob: 953a23f90603cc792e087170b3dc3f431be99cdd [file] [log] [blame]
Chris Lattner2da04b32007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner2da04b32007-08-24 05:35:26 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGDebugInfo.h"
Fariborz Jahanian07ca7272009-10-10 20:07:56 +000017#include "CGObjCRuntime.h"
Chris Lattner2da04b32007-08-24 05:35:26 +000018#include "CodeGenModule.h"
Alexey Bataev00396512015-07-02 03:40:19 +000019#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000020#include "clang/AST/ASTContext.h"
Daniel Dunbar6630e102008-08-12 05:08:18 +000021#include "clang/AST/DeclObjC.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000022#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000023#include "clang/AST/StmtVisitor.h"
Chris Lattnerff2367c2008-04-20 00:50:39 +000024#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Frontend/CodeGenOptions.h"
Chandler Carruth735e6d82014-03-04 11:46:22 +000026#include "llvm/IR/CFG.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000027#include "llvm/IR/Constants.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/Function.h"
30#include "llvm/IR/GlobalVariable.h"
31#include "llvm/IR/Intrinsics.h"
32#include "llvm/IR/Module.h"
Chris Lattner1800c182008-01-03 07:05:49 +000033#include <cstdarg>
Ted Kremenekf182e812007-12-10 23:44:32 +000034
Chris Lattner2da04b32007-08-24 05:35:26 +000035using namespace clang;
36using namespace CodeGen;
37using llvm::Value;
38
39//===----------------------------------------------------------------------===//
40// Scalar Expression Emitter
41//===----------------------------------------------------------------------===//
42
Benjamin Kramerfb5e5842010-10-22 16:48:22 +000043namespace {
Chris Lattner2da04b32007-08-24 05:35:26 +000044struct BinOpInfo {
45 Value *LHS;
46 Value *RHS;
Chris Lattner3d966d62007-08-24 21:00:35 +000047 QualType Ty; // Computation Type.
Chris Lattner0bf27622010-06-26 21:48:21 +000048 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
Lang Hames5de91cc2012-10-02 04:45:10 +000049 bool FPContractable;
Chris Lattner0bf27622010-06-26 21:48:21 +000050 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Chris Lattner2da04b32007-08-24 05:35:26 +000051};
52
John McCalle84af4e2010-11-13 01:35:44 +000053static bool MustVisitNullValue(const Expr *E) {
54 // If a null pointer expression's type is the C++0x nullptr_t, then
55 // it's not necessarily a simple constant and it must be evaluated
56 // for its potential side effects.
57 return E->getType()->isNullPtrType();
58}
59
Benjamin Kramer337e3a52009-11-28 19:45:26 +000060class ScalarExprEmitter
Chris Lattner2da04b32007-08-24 05:35:26 +000061 : public StmtVisitor<ScalarExprEmitter, Value*> {
62 CodeGenFunction &CGF;
Daniel Dunbarcb463852008-11-01 01:53:16 +000063 CGBuilderTy &Builder;
Mike Stumpdf0fe272009-05-29 15:46:01 +000064 bool IgnoreResultAssign;
Owen Anderson170229f2009-07-14 23:10:40 +000065 llvm::LLVMContext &VMContext;
Chris Lattner2da04b32007-08-24 05:35:26 +000066public:
67
Mike Stumpdf0fe272009-05-29 15:46:01 +000068 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stump4a3999f2009-09-09 13:00:44 +000069 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Anderson170229f2009-07-14 23:10:40 +000070 VMContext(cgf.getLLVMContext()) {
Chris Lattner2da04b32007-08-24 05:35:26 +000071 }
Mike Stump4a3999f2009-09-09 13:00:44 +000072
Chris Lattner2da04b32007-08-24 05:35:26 +000073 //===--------------------------------------------------------------------===//
74 // Utilities
75 //===--------------------------------------------------------------------===//
76
Mike Stumpdf0fe272009-05-29 15:46:01 +000077 bool TestAndClearIgnoreResultAssign() {
Chris Lattner2a7deb62009-07-08 01:08:03 +000078 bool I = IgnoreResultAssign;
79 IgnoreResultAssign = false;
80 return I;
81 }
Mike Stumpdf0fe272009-05-29 15:46:01 +000082
Chris Lattner2192fe52011-07-18 04:24:23 +000083 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner2da04b32007-08-24 05:35:26 +000084 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith4d1458e2012-09-08 02:08:36 +000085 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
86 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith69d0d262012-08-24 00:54:33 +000087 }
Chris Lattner2da04b32007-08-24 05:35:26 +000088
Peter Collingbourne3eea6772015-05-11 21:39:14 +000089 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
Alexey Samsonove396bfc2014-11-11 22:03:54 +000090 const BinOpInfo &Info);
Richard Smithe30752c2012-10-09 19:52:38 +000091
Nick Lewycky2d84e842013-10-02 02:29:49 +000092 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
93 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
Chris Lattner2da04b32007-08-24 05:35:26 +000094 }
Mike Stump4a3999f2009-09-09 13:00:44 +000095
Hal Finkel64567a82014-10-04 15:26:49 +000096 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
97 const AlignValueAttr *AVAttr = nullptr;
98 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
99 const ValueDecl *VD = DRE->getDecl();
100
101 if (VD->getType()->isReferenceType()) {
102 if (const auto *TTy =
103 dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
104 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
105 } else {
106 // Assumptions for function parameters are emitted at the start of the
107 // function, so there is no need to repeat that here.
108 if (isa<ParmVarDecl>(VD))
109 return;
110
111 AVAttr = VD->getAttr<AlignValueAttr>();
112 }
113 }
114
115 if (!AVAttr)
116 if (const auto *TTy =
117 dyn_cast<TypedefType>(E->getType()))
118 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
119
120 if (!AVAttr)
121 return;
122
123 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
124 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
125 CGF.EmitAlignmentAssumption(V, AlignmentCI->getZExtValue());
126 }
127
Chris Lattner2da04b32007-08-24 05:35:26 +0000128 /// EmitLoadOfLValue - Given an expression with complex type that represents a
129 /// value l-value, this method emits the address of the l-value, then loads
130 /// and returns the result.
131 Value *EmitLoadOfLValue(const Expr *E) {
Hal Finkel64567a82014-10-04 15:26:49 +0000132 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
133 E->getExprLoc());
134
135 EmitLValueAlignmentAssumption(E, V);
136 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000137 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000138
Chris Lattnere0044382007-08-26 16:42:57 +0000139 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000140 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000141 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stump4a3999f2009-09-09 13:00:44 +0000142
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000143 /// Emit a check that a conversion to or from a floating-point type does not
144 /// overflow.
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000145 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
146 Value *Src, QualType SrcType,
147 QualType DstType, llvm::Type *DstTy);
148
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000149 /// Emit a conversion from the specified type to the specified destination
150 /// type, both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +0000151 Value *EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy);
152
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000153 /// Emit a conversion from the specified complex type to the specified
154 /// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000155 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
156 QualType SrcTy, QualType DstTy);
Mike Stumpab3afd82009-02-12 18:29:15 +0000157
Anders Carlsson5b944432010-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 McCall8cb679e2010-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 Lattner2531eb42011-04-19 22:55:03 +0000191 return Builder.CreateIsNotNull(V, "tobool");
John McCall8cb679e2010-11-15 09:13:47 +0000192 }
193
Chris Lattner2da04b32007-08-24 05:35:26 +0000194 //===--------------------------------------------------------------------===//
195 // Visitor Methods
196 //===--------------------------------------------------------------------===//
197
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000198 Value *Visit(Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000199 ApplyDebugLocation DL(CGF, E);
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000200 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
201 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000202
Chris Lattner2da04b32007-08-24 05:35:26 +0000203 Value *VisitStmt(Stmt *S) {
Ted Kremenekd4e5fba2007-12-11 21:27:55 +0000204 S->dump(CGF.getContext().getSourceManager());
David Blaikie83d382b2011-09-23 05:06:16 +0000205 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner2da04b32007-08-24 05:35:26 +0000206 }
207 Value *VisitExpr(Expr *S);
Craig Toppera97d7e72013-07-26 06:16:11 +0000208
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000209 Value *VisitParenExpr(ParenExpr *PE) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000210 return Visit(PE->getSubExpr());
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000211 }
John McCall7c454bb2011-07-15 05:09:51 +0000212 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000213 return Visit(E->getReplacement());
John McCall7c454bb2011-07-15 05:09:51 +0000214 }
Peter Collingbourne91147592011-04-15 00:35:48 +0000215 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
216 return Visit(GE->getResultExpr());
217 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000218
219 // Leaves.
220 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000221 return Builder.getInt(E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000222 }
223 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersone05f2ed2009-07-27 21:00:51 +0000224 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000225 }
226 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000227 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000228 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000229 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
230 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
231 }
Nate Begeman4c18c232007-11-15 05:40:03 +0000232 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000233 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begeman4c18c232007-11-15 05:40:03 +0000234 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000235 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000236 return EmitNullValue(E->getType());
Argyrios Kyrtzidisce4528f2008-08-23 19:35:47 +0000237 }
Anders Carlsson39def3a2008-12-21 22:39:40 +0000238 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000239 return EmitNullValue(E->getType());
Anders Carlsson39def3a2008-12-21 22:39:40 +0000240 }
Eli Friedmand7c72322010-08-05 09:58:49 +0000241 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournee190dee2011-03-11 19:24:49 +0000242 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000243 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattner6c4d2552009-10-28 23:59:40 +0000244 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
245 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000246 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000247
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000248 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000249 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000250 }
John McCall1bf58462011-02-16 08:02:54 +0000251
John McCallfe96e0b2011-11-06 09:01:30 +0000252 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
253 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
254 }
255
John McCall1bf58462011-02-16 08:02:54 +0000256 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCallc07a0c72011-02-17 10:25:35 +0000257 if (E->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +0000258 return EmitLoadOfLValue(CGF.getOpaqueLValueMapping(E), E->getExprLoc());
John McCall1bf58462011-02-16 08:02:54 +0000259
260 // Otherwise, assume the mapping is the scalar directly.
John McCallc07a0c72011-02-17 10:25:35 +0000261 return CGF.getOpaqueRValueMapping(E).getScalarVal();
John McCall1bf58462011-02-16 08:02:54 +0000262 }
John McCall71335052012-03-10 03:05:10 +0000263
Chris Lattner2da04b32007-08-24 05:35:26 +0000264 // l-values.
John McCall113bee02012-03-10 09:33:50 +0000265 Value *VisitDeclRefExpr(DeclRefExpr *E) {
266 if (CodeGenFunction::ConstantEmission result = CGF.tryEmitAsConstant(E)) {
John McCall71335052012-03-10 03:05:10 +0000267 if (result.isReference())
Nick Lewycky2d84e842013-10-02 02:29:49 +0000268 return EmitLoadOfLValue(result.getReferenceLValue(CGF, E),
269 E->getExprLoc());
John McCall71335052012-03-10 03:05:10 +0000270 return result.getValue();
Richard Smithbc6387672012-03-02 23:27:11 +0000271 }
John McCall113bee02012-03-10 09:33:50 +0000272 return EmitLoadOfLValue(E);
John McCall71335052012-03-10 03:05:10 +0000273 }
274
Mike Stump4a3999f2009-09-09 13:00:44 +0000275 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
276 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000277 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000278 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
279 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000280 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000281 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar55310df2008-08-27 06:57:25 +0000282 return EmitLoadOfLValue(E);
283 }
Daniel Dunbar55310df2008-08-27 06:57:25 +0000284 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000285 if (E->getMethodDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +0000286 E->getMethodDecl()->getReturnType()->isReferenceType())
Fariborz Jahanianff989032011-03-02 20:09:49 +0000287 return EmitLoadOfLValue(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000288 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000289 }
290
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000291 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000292 LValue LV = CGF.EmitObjCIsaExpr(E);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000293 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000294 return V;
295 }
296
Chris Lattner2da04b32007-08-24 05:35:26 +0000297 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000298 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Hal Finkelc4d7c822013-09-18 03:29:45 +0000299 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
Eli Friedmancb422f12009-11-26 03:22:21 +0000300 Value *VisitMemberExpr(MemberExpr *E);
Nate Begemance4d7fc2008-04-18 23:10:10 +0000301 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattner084bc322008-10-26 23:53:12 +0000302 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
303 return EmitLoadOfLValue(E);
304 }
Devang Patel43fc86d2007-10-24 17:18:43 +0000305
Nate Begeman19351632009-10-18 20:10:40 +0000306 Value *VisitInitListExpr(InitListExpr *E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000307
Douglas Gregor0202cb42009-01-29 17:44:32 +0000308 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithd82a2ce2012-12-21 03:17:28 +0000309 return EmitNullValue(E->getType());
Douglas Gregor0202cb42009-01-29 17:44:32 +0000310 }
John McCall23c29fe2011-06-24 21:55:10 +0000311 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +0000312 if (E->getType()->isVariablyModifiedType())
John McCall23c29fe2011-06-24 21:55:10 +0000313 CGF.EmitVariablyModifiedType(E->getType());
David Blaikie66088d52014-09-24 17:01:27 +0000314
315 if (CGDebugInfo *DI = CGF.getDebugInfo())
316 DI->EmitExplicitCastType(E->getType());
317
John McCall23c29fe2011-06-24 21:55:10 +0000318 return VisitCastExpr(E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000319 }
John McCall23c29fe2011-06-24 21:55:10 +0000320 Value *VisitCastExpr(CastExpr *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000321
322 Value *VisitCallExpr(const CallExpr *E) {
David Majnemerced8bdf2015-02-25 17:36:15 +0000323 if (E->getCallReturnType(CGF.getContext())->isReferenceType())
Anders Carlssond8b7ae22009-05-27 03:37:57 +0000324 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000325
Hal Finkel64567a82014-10-04 15:26:49 +0000326 Value *V = CGF.EmitCallExpr(E).getScalarVal();
327
328 EmitLValueAlignmentAssumption(E, V);
329 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000330 }
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000331
Chris Lattner04a913b2007-08-31 22:09:40 +0000332 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000333
Chris Lattner2da04b32007-08-24 05:35:26 +0000334 // Unary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000335 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000336 LValue LV = EmitLValue(E->getSubExpr());
337 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000338 }
339 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000340 LValue LV = EmitLValue(E->getSubExpr());
341 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000342 }
343 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000344 LValue LV = EmitLValue(E->getSubExpr());
345 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000346 }
347 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000348 LValue LV = EmitLValue(E->getSubExpr());
349 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000350 }
Chris Lattner05dc78c2010-06-26 22:09:34 +0000351
Alexey Samsonovf6246502015-04-23 01:50:45 +0000352 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
353 llvm::Value *InVal,
354 bool IsInc);
Anton Yartsev85129b82011-02-07 02:17:30 +0000355
Chris Lattner05dc78c2010-06-26 22:09:34 +0000356 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
357 bool isInc, bool isPre);
358
Craig Toppera97d7e72013-07-26 06:16:11 +0000359
Chris Lattner2da04b32007-08-24 05:35:26 +0000360 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCallf3a88602011-02-03 08:15:49 +0000361 if (isa<MemberPointerType>(E->getType())) // never sugared
362 return CGF.CGM.getMemberPointerConstant(E);
363
Chris Lattner2da04b32007-08-24 05:35:26 +0000364 return EmitLValue(E->getSubExpr()).getAddress();
365 }
John McCall59482722010-12-04 12:43:24 +0000366 Value *VisitUnaryDeref(const UnaryOperator *E) {
367 if (E->getType()->isVoidType())
368 return Visit(E->getSubExpr()); // the actual value should be unused
369 return EmitLoadOfLValue(E);
370 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000371 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000372 // This differs from gcc, though, most likely due to a bug in gcc.
373 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +0000374 return Visit(E->getSubExpr());
375 }
376 Value *VisitUnaryMinus (const UnaryOperator *E);
377 Value *VisitUnaryNot (const UnaryOperator *E);
378 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner9f0ad962007-08-24 21:20:17 +0000379 Value *VisitUnaryReal (const UnaryOperator *E);
380 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000381 Value *VisitUnaryExtension(const UnaryOperator *E) {
382 return Visit(E->getSubExpr());
383 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000384
Anders Carlssona5d077d2009-04-14 16:58:56 +0000385 // C++
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000386 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedman0be39702011-08-14 04:50:34 +0000387 return EmitLoadOfLValue(E);
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000388 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000389
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000390 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
391 return Visit(DAE->getExpr());
392 }
Richard Smith852c9db2013-04-20 22:23:05 +0000393 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
394 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
395 return Visit(DIE->getExpr());
396 }
Anders Carlssona5d077d2009-04-14 16:58:56 +0000397 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
398 return CGF.LoadCXXThis();
Mike Stump4a3999f2009-09-09 13:00:44 +0000399 }
400
John McCall5d413782010-12-06 08:20:24 +0000401 Value *VisitExprWithCleanups(ExprWithCleanups *E) {
John McCall08ef4662011-11-10 08:15:53 +0000402 CGF.enterFullExpression(E);
403 CodeGenFunction::RunCleanupsScope Scope(CGF);
David Blaikie1b5adb82014-07-10 20:42:59 +0000404 return Visit(E->getSubExpr());
Anders Carlssonc82b86d2009-05-19 04:48:36 +0000405 }
Anders Carlsson4a7b49b2009-05-31 01:40:14 +0000406 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
407 return CGF.EmitCXXNewExpr(E);
408 }
Anders Carlsson81f0df92009-08-16 21:13:42 +0000409 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
410 CGF.EmitCXXDeleteExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000411 return nullptr;
Anders Carlsson81f0df92009-08-16 21:13:42 +0000412 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000413
Alp Tokercbb90342013-12-13 20:49:58 +0000414 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
Francois Pichet34b21132010-12-08 22:35:30 +0000415 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet9dfa3ce2010-12-07 00:08:36 +0000416 }
417
John Wiegley6242b6a2011-04-28 00:16:57 +0000418 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
419 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
420 }
421
John Wiegleyf9f65842011-04-25 06:54:41 +0000422 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
423 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
424 }
425
Douglas Gregorad8a3362009-09-04 17:36:40 +0000426 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
427 // C++ [expr.pseudo]p1:
Mike Stump4a3999f2009-09-09 13:00:44 +0000428 // The result shall only be used as the operand for the function call
Douglas Gregorad8a3362009-09-04 17:36:40 +0000429 // operator (), and the result of such a call has type void. The only
430 // effect is the evaluation of the postfix-expression before the dot or
431 // arrow.
432 CGF.EmitScalarExpr(E->getBase());
Craig Topper8a13c412014-05-21 05:09:00 +0000433 return nullptr;
Douglas Gregorad8a3362009-09-04 17:36:40 +0000434 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000435
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000436 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000437 return EmitNullValue(E->getType());
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000438 }
Anders Carlsson4b08db72009-10-30 01:42:31 +0000439
440 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
441 CGF.EmitCXXThrowExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000442 return nullptr;
Anders Carlsson4b08db72009-10-30 01:42:31 +0000443 }
444
Sebastian Redlb67655f2010-09-10 21:04:00 +0000445 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000446 return Builder.getInt1(E->getValue());
Sebastian Redlb67655f2010-09-10 21:04:00 +0000447 }
448
Chris Lattner2da04b32007-08-24 05:35:26 +0000449 // Binary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000450 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000451 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000452 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +0000453 case LangOptions::SOB_Defined:
454 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith3e056de2012-08-25 00:32:28 +0000455 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000456 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +0000457 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
458 // Fall through.
Chris Lattner51924e512010-06-26 21:25:03 +0000459 case LangOptions::SOB_Trapping:
460 return EmitOverflowCheckedBinOp(Ops);
461 }
462 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000463
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000464 if (Ops.Ty->isUnsignedIntegerType() &&
465 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietz1897cb32012-11-27 15:01:55 +0000466 return EmitOverflowCheckedBinOp(Ops);
467
Duncan Sands998f9d92010-02-15 16:14:01 +0000468 if (Ops.LHS->getType()->isFPOrFPVectorTy())
Chris Lattner94dfae22009-06-17 06:36:24 +0000469 return Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner2da04b32007-08-24 05:35:26 +0000470 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
471 }
Mike Stump0c61b732009-04-01 20:28:16 +0000472 /// Create a binary op that checks for overflow.
473 /// Currently only supports +, - and *.
474 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith4d1458e2012-09-08 02:08:36 +0000475
Chris Lattner8ee6a412010-09-11 21:47:09 +0000476 // Check for undefined division and modulus behaviors.
Craig Toppera97d7e72013-07-26 06:16:11 +0000477 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
Chris Lattner8ee6a412010-09-11 21:47:09 +0000478 llvm::Value *Zero,bool isDiv);
David Tweed042e0882013-01-07 16:43:27 +0000479 // Common helper for getting how wide LHS of shift is.
480 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
Chris Lattner2da04b32007-08-24 05:35:26 +0000481 Value *EmitDiv(const BinOpInfo &Ops);
482 Value *EmitRem(const BinOpInfo &Ops);
483 Value *EmitAdd(const BinOpInfo &Ops);
484 Value *EmitSub(const BinOpInfo &Ops);
485 Value *EmitShl(const BinOpInfo &Ops);
486 Value *EmitShr(const BinOpInfo &Ops);
487 Value *EmitAnd(const BinOpInfo &Ops) {
488 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
489 }
490 Value *EmitXor(const BinOpInfo &Ops) {
491 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
492 }
493 Value *EmitOr (const BinOpInfo &Ops) {
494 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
495 }
496
Chris Lattner3d966d62007-08-24 21:00:35 +0000497 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor914af212010-04-23 04:16:32 +0000498 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
499 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +0000500 Value *&Result);
Douglas Gregor914af212010-04-23 04:16:32 +0000501
Chris Lattnerb6334692007-08-26 21:41:21 +0000502 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner3d966d62007-08-24 21:00:35 +0000503 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
504
505 // Binary operators and binary compound assignment operators.
506#define HANDLEBINOP(OP) \
Chris Lattnerb6334692007-08-26 21:41:21 +0000507 Value *VisitBin ## OP(const BinaryOperator *E) { \
508 return Emit ## OP(EmitBinOps(E)); \
509 } \
510 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
511 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner3d966d62007-08-24 21:00:35 +0000512 }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000513 HANDLEBINOP(Mul)
514 HANDLEBINOP(Div)
515 HANDLEBINOP(Rem)
516 HANDLEBINOP(Add)
517 HANDLEBINOP(Sub)
518 HANDLEBINOP(Shl)
519 HANDLEBINOP(Shr)
520 HANDLEBINOP(And)
521 HANDLEBINOP(Xor)
522 HANDLEBINOP(Or)
Chris Lattner3d966d62007-08-24 21:00:35 +0000523#undef HANDLEBINOP
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +0000524
Chris Lattner2da04b32007-08-24 05:35:26 +0000525 // Comparisons.
526 Value *EmitCompare(const BinaryOperator *E, unsigned UICmpOpc,
527 unsigned SICmpOpc, unsigned FCmpOpc);
528#define VISITCOMP(CODE, UI, SI, FP) \
529 Value *VisitBin##CODE(const BinaryOperator *E) { \
530 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
531 llvm::FCmpInst::FP); }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000532 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
533 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
534 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
535 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
536 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
537 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner2da04b32007-08-24 05:35:26 +0000538#undef VISITCOMP
Mike Stump4a3999f2009-09-09 13:00:44 +0000539
Chris Lattner2da04b32007-08-24 05:35:26 +0000540 Value *VisitBinAssign (const BinaryOperator *E);
541
542 Value *VisitBinLAnd (const BinaryOperator *E);
543 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000544 Value *VisitBinComma (const BinaryOperator *E);
545
Eli Friedmanacfb1df2009-11-18 09:41:26 +0000546 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
547 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
548
Chris Lattner2da04b32007-08-24 05:35:26 +0000549 // Other Operators.
Mike Stumpab3afd82009-02-12 18:29:15 +0000550 Value *VisitBlockExpr(const BlockExpr *BE);
John McCallc07a0c72011-02-17 10:25:35 +0000551 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner2da04b32007-08-24 05:35:26 +0000552 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000553 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000554 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
555 return CGF.EmitObjCStringLiteral(E);
556 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000557 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
558 return CGF.EmitObjCBoxedExpr(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000559 }
560 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
561 return CGF.EmitObjCArrayLiteral(E);
562 }
563 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
564 return CGF.EmitObjCDictionaryLiteral(E);
565 }
Tanya Lattner55808c12011-06-04 00:47:47 +0000566 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000567 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000568};
569} // end anonymous namespace.
570
571//===----------------------------------------------------------------------===//
572// Utilities
573//===----------------------------------------------------------------------===//
574
Chris Lattnere0044382007-08-26 16:42:57 +0000575/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000576/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000577Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCallb692a092009-10-22 20:10:53 +0000578 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stump4a3999f2009-09-09 13:00:44 +0000579
John McCall8cb679e2010-11-15 09:13:47 +0000580 if (SrcType->isRealFloatingType())
581 return EmitFloatToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000582
John McCall7a9aac22010-08-23 01:21:21 +0000583 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
584 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stump4a3999f2009-09-09 13:00:44 +0000585
Daniel Dunbaref957f32008-08-25 10:38:11 +0000586 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnere0044382007-08-26 16:42:57 +0000587 "Unknown scalar type to convert");
Mike Stump4a3999f2009-09-09 13:00:44 +0000588
John McCall8cb679e2010-11-15 09:13:47 +0000589 if (isa<llvm::IntegerType>(Src->getType()))
590 return EmitIntToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000591
John McCall8cb679e2010-11-15 09:13:47 +0000592 assert(isa<llvm::PointerType>(Src->getType()));
593 return EmitPointerToBoolConversion(Src);
Chris Lattnere0044382007-08-26 16:42:57 +0000594}
595
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000596void ScalarExprEmitter::EmitFloatConversionCheck(Value *OrigSrc,
597 QualType OrigSrcType,
598 Value *Src, QualType SrcType,
599 QualType DstType,
600 llvm::Type *DstTy) {
Alexey Samsonov24cad992014-07-17 18:46:27 +0000601 CodeGenFunction::SanitizerScope SanScope(&CGF);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000602 using llvm::APFloat;
603 using llvm::APSInt;
604
605 llvm::Type *SrcTy = Src->getType();
606
Craig Topper8a13c412014-05-21 05:09:00 +0000607 llvm::Value *Check = nullptr;
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000608 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
609 // Integer to floating-point. This can fail for unsigned short -> __half
610 // or unsigned __int128 -> float.
611 assert(DstType->isFloatingType());
612 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
613
614 APFloat LargestFloat =
615 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
616 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
617
618 bool IsExact;
619 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
620 &IsExact) != APFloat::opOK)
621 // The range of representable values of this floating point type includes
622 // all values of this integer type. Don't need an overflow check.
623 return;
624
625 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
626 if (SrcIsUnsigned)
627 Check = Builder.CreateICmpULE(Src, Max);
628 else {
629 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
630 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
631 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
632 Check = Builder.CreateAnd(GE, LE);
633 }
634 } else {
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000635 const llvm::fltSemantics &SrcSema =
636 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000637 if (isa<llvm::IntegerType>(DstTy)) {
Richard Smith2b01d502013-03-27 23:20:25 +0000638 // Floating-point to integer. This has undefined behavior if the source is
639 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
640 // to an integer).
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000641 unsigned Width = CGF.getContext().getIntWidth(DstType);
642 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
643
644 APSInt Min = APSInt::getMinValue(Width, Unsigned);
Richard Smith2b01d502013-03-27 23:20:25 +0000645 APFloat MinSrc(SrcSema, APFloat::uninitialized);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000646 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
647 APFloat::opOverflow)
648 // Don't need an overflow check for lower bound. Just check for
649 // -Inf/NaN.
Richard Smith4af40c42013-03-19 00:01:12 +0000650 MinSrc = APFloat::getInf(SrcSema, true);
651 else
652 // Find the largest value which is too small to represent (before
653 // truncation toward zero).
654 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000655
656 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
Richard Smith2b01d502013-03-27 23:20:25 +0000657 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000658 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
659 APFloat::opOverflow)
660 // Don't need an overflow check for upper bound. Just check for
661 // +Inf/NaN.
Richard Smith4af40c42013-03-19 00:01:12 +0000662 MaxSrc = APFloat::getInf(SrcSema, false);
663 else
664 // Find the smallest value which is too large to represent (before
665 // truncation toward zero).
666 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000667
Richard Smith2b01d502013-03-27 23:20:25 +0000668 // If we're converting from __half, convert the range to float to match
669 // the type of src.
670 if (OrigSrcType->isHalfType()) {
671 const llvm::fltSemantics &Sema =
672 CGF.getContext().getFloatTypeSemantics(SrcType);
673 bool IsInexact;
674 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
675 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
676 }
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000677
Richard Smith4af40c42013-03-19 00:01:12 +0000678 llvm::Value *GE =
679 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
680 llvm::Value *LE =
681 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
682 Check = Builder.CreateAnd(GE, LE);
683 } else {
Richard Smith2b01d502013-03-27 23:20:25 +0000684 // FIXME: Maybe split this sanitizer out from float-cast-overflow.
685 //
686 // Floating-point to floating-point. This has undefined behavior if the
687 // source is not in the range of representable values of the destination
688 // type. The C and C++ standards are spectacularly unclear here. We
689 // diagnose finite out-of-range conversions, but allow infinities and NaNs
690 // to convert to the corresponding value in the smaller type.
691 //
692 // C11 Annex F gives all such conversions defined behavior for IEC 60559
693 // conforming implementations. Unfortunately, LLVM's fptrunc instruction
694 // does not.
695
696 // Converting from a lower rank to a higher rank can never have
697 // undefined behavior, since higher-rank types must have a superset
698 // of values of lower-rank types.
699 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
700 return;
701
702 assert(!OrigSrcType->isHalfType() &&
703 "should not check conversion from __half, it has the lowest rank");
704
705 const llvm::fltSemantics &DstSema =
706 CGF.getContext().getFloatTypeSemantics(DstType);
707 APFloat MinBad = APFloat::getLargest(DstSema, false);
708 APFloat MaxBad = APFloat::getInf(DstSema, false);
709
710 bool IsInexact;
711 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
712 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
713
714 Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
715 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
Richard Smith4af40c42013-03-19 00:01:12 +0000716 llvm::Value *GE =
Richard Smith2b01d502013-03-27 23:20:25 +0000717 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
Richard Smith4af40c42013-03-19 00:01:12 +0000718 llvm::Value *LE =
Richard Smith2b01d502013-03-27 23:20:25 +0000719 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
720 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
Richard Smith4af40c42013-03-19 00:01:12 +0000721 }
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000722 }
723
724 // FIXME: Provide a SourceLocation.
725 llvm::Constant *StaticArgs[] = {
726 CGF.EmitCheckTypeDescriptor(OrigSrcType),
727 CGF.EmitCheckTypeDescriptor(DstType)
728 };
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000729 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
730 "float_cast_overflow", StaticArgs, OrigSrc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000731}
732
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000733/// Emit a conversion from the specified type to the specified destination type,
734/// both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +0000735Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
736 QualType DstType) {
Chris Lattner0f398c42008-07-26 22:37:01 +0000737 SrcType = CGF.getContext().getCanonicalType(SrcType);
738 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3474c202007-08-26 06:48:56 +0000739 if (SrcType == DstType) return Src;
Mike Stump4a3999f2009-09-09 13:00:44 +0000740
Craig Topper8a13c412014-05-21 05:09:00 +0000741 if (DstType->isVoidType()) return nullptr;
Mike Stump4a3999f2009-09-09 13:00:44 +0000742
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000743 llvm::Value *OrigSrc = Src;
744 QualType OrigSrcType = SrcType;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000745 llvm::Type *SrcTy = Src->getType();
746
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +0000747 // Handle conversions to bool first, they are special: comparisons against 0.
748 if (DstType->isBooleanType())
749 return EmitConversionToBool(Src, SrcType);
750
751 llvm::Type *DstTy = ConvertType(DstType);
752
Ahmed Bougachad1801af2015-03-23 17:54:16 +0000753 // Cast from half through float if half isn't a native type.
754 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
755 // Cast to FP using the intrinsic if the half type itself isn't supported.
756 if (DstTy->isFloatingPointTy()) {
757 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns)
758 return Builder.CreateCall(
759 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
760 Src);
761 } else {
762 // Cast to other types through float, using either the intrinsic or FPExt,
763 // depending on whether the half type itself is supported
764 // (as opposed to operations on half, available with NativeHalfType).
765 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
766 Src = Builder.CreateCall(
767 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
768 CGF.CGM.FloatTy),
769 Src);
770 } else {
771 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
772 }
773 SrcType = CGF.getContext().FloatTy;
774 SrcTy = CGF.FloatTy;
775 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000776 }
777
Chris Lattner3474c202007-08-26 06:48:56 +0000778 // Ignore conversions like int -> uint.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000779 if (SrcTy == DstTy)
Chris Lattner3474c202007-08-26 06:48:56 +0000780 return Src;
781
Mike Stump4a3999f2009-09-09 13:00:44 +0000782 // Handle pointer conversions next: pointers can only be converted to/from
783 // other pointers and integers. Check for pointer types in terms of LLVM, as
784 // some native types (like Obj-C id) may map to a pointer type.
Daniel Dunbar427f8732008-08-25 09:51:32 +0000785 if (isa<llvm::PointerType>(DstTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +0000786 // The source value may be an integer, or a pointer.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000787 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3474c202007-08-26 06:48:56 +0000788 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson12f5a252009-09-12 04:57:16 +0000789
Chris Lattner3474c202007-08-26 06:48:56 +0000790 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman42d2a3a2009-03-04 04:02:35 +0000791 // First, convert to the correct width so that we control the kind of
792 // extension.
Chris Lattner2192fe52011-07-18 04:24:23 +0000793 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000794 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman42d2a3a2009-03-04 04:02:35 +0000795 llvm::Value* IntResult =
796 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
797 // Then, cast to pointer.
798 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000799 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000800
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000801 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +0000802 // Must be an ptr to int cast.
803 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlssone89b84a2007-10-31 23:18:02 +0000804 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000805 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000806
Nate Begemance4d7fc2008-04-18 23:10:10 +0000807 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman5ec4b312009-08-10 23:49:36 +0000808 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
Nate Begemanb699c9b2009-01-18 06:42:49 +0000809 // Cast the scalar to element type
John McCall9dd450b2009-09-21 23:43:11 +0000810 QualType EltTy = DstType->getAs<ExtVectorType>()->getElementType();
Nate Begemanb699c9b2009-01-18 06:42:49 +0000811 llvm::Value *Elt = EmitScalarConversion(Src, SrcType, EltTy);
812
Nate Begemanb699c9b2009-01-18 06:42:49 +0000813 // Splat the element across to all elements
Nate Begemanb699c9b2009-01-18 06:42:49 +0000814 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Benjamin Kramer7a14bc02013-01-01 20:08:10 +0000815 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Nate Begemanb699c9b2009-01-18 06:42:49 +0000816 }
Nate Begeman330aaa72007-12-30 02:59:45 +0000817
Chris Lattner6cba8e92008-02-02 04:51:41 +0000818 // Allow bitcast from vector to integer/fp of the same size.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000819 if (isa<llvm::VectorType>(SrcTy) ||
Chris Lattner6cba8e92008-02-02 04:51:41 +0000820 isa<llvm::VectorType>(DstTy))
Anders Carlssona297e7a2007-12-05 07:36:10 +0000821 return Builder.CreateBitCast(Src, DstTy, "conv");
Mike Stump4a3999f2009-09-09 13:00:44 +0000822
Chris Lattner3474c202007-08-26 06:48:56 +0000823 // Finally, we have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +0000824 Value *Res = nullptr;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000825 llvm::Type *ResTy = DstTy;
826
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000827 // An overflowing conversion has undefined behavior if either the source type
828 // or the destination type is a floating-point type.
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000829 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000830 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
Will Dietzf54319c2013-01-18 11:30:38 +0000831 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType,
832 DstTy);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000833
Ahmed Bougachad1801af2015-03-23 17:54:16 +0000834 // Cast to half through float if half isn't a native type.
835 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
836 // Make sure we cast in a single step if from another FP type.
837 if (SrcTy->isFloatingPointTy()) {
838 // Use the intrinsic if the half type itself isn't supported
839 // (as opposed to operations on half, available with NativeHalfType).
840 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns)
841 return Builder.CreateCall(
842 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
843 // If the half type is supported, just use an fptrunc.
844 return Builder.CreateFPTrunc(Src, DstTy);
845 }
Chris Lattnerece04092012-02-07 00:39:47 +0000846 DstTy = CGF.FloatTy;
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +0000847 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000848
849 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000850 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000851 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000852 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000853 else if (InputSigned)
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000854 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000855 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000856 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
857 } else if (isa<llvm::IntegerType>(DstTy)) {
858 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000859 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000860 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +0000861 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000862 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
863 } else {
864 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
865 "Unknown real conversion");
866 if (DstTy->getTypeID() < SrcTy->getTypeID())
867 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
868 else
869 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +0000870 }
871
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000872 if (DstTy != ResTy) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +0000873 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
874 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
875 Res = Builder.CreateCall(
Tim Northover6dbcbac2014-07-17 10:51:31 +0000876 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
877 Res);
Ahmed Bougachad1801af2015-03-23 17:54:16 +0000878 } else {
879 Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
880 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +0000881 }
882
883 return Res;
Chris Lattner3474c202007-08-26 06:48:56 +0000884}
885
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000886/// Emit a conversion from the specified complex type to the specified
887/// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000888Value *ScalarExprEmitter::
889EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
890 QualType SrcTy, QualType DstTy) {
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000891 // Get the source element type.
John McCall47fb9502013-03-07 21:37:08 +0000892 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
Mike Stump4a3999f2009-09-09 13:00:44 +0000893
Chris Lattnerc141c1b2007-08-26 16:52:28 +0000894 // Handle conversions to bool first, they are special: comparisons against 0.
895 if (DstTy->isBooleanType()) {
896 // Complex != 0 -> (Real != 0) | (Imag != 0)
897 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy);
898 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy);
899 return Builder.CreateOr(Src.first, Src.second, "tobool");
900 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000901
Chris Lattner42e6b812007-08-26 16:34:22 +0000902 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
903 // the imaginary part of the complex value is discarded and the value of the
904 // real part is converted according to the conversion rules for the
Mike Stump4a3999f2009-09-09 13:00:44 +0000905 // corresponding real type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000906 return EmitScalarConversion(Src.first, SrcTy, DstTy);
907}
908
Anders Carlsson5b944432010-05-22 17:45:10 +0000909Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
Richard Smithd82a2ce2012-12-21 03:17:28 +0000910 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
Anders Carlsson5b944432010-05-22 17:45:10 +0000911}
Chris Lattner42e6b812007-08-26 16:34:22 +0000912
Richard Smithe30752c2012-10-09 19:52:38 +0000913/// \brief Emit a sanitization check for the given "binary" operation (which
914/// might actually be a unary increment which has been lowered to a binary
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000915/// operation). The check passes if all values in \p Checks (which are \c i1),
916/// are \c true.
917void ScalarExprEmitter::EmitBinOpCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000918 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
Alexey Samsonov24cad992014-07-17 18:46:27 +0000919 assert(CGF.IsSanitizerScope);
Richard Smithe30752c2012-10-09 19:52:38 +0000920 StringRef CheckName;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000921 SmallVector<llvm::Constant *, 4> StaticData;
922 SmallVector<llvm::Value *, 2> DynamicData;
Richard Smithe30752c2012-10-09 19:52:38 +0000923
924 BinaryOperatorKind Opcode = Info.Opcode;
925 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
926 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
927
928 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
929 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
930 if (UO && UO->getOpcode() == UO_Minus) {
931 CheckName = "negate_overflow";
932 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
933 DynamicData.push_back(Info.RHS);
934 } else {
935 if (BinaryOperator::isShiftOp(Opcode)) {
936 // Shift LHS negative or too large, or RHS out of bounds.
937 CheckName = "shift_out_of_bounds";
938 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
939 StaticData.push_back(
940 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
941 StaticData.push_back(
942 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
943 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
944 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
945 CheckName = "divrem_overflow";
Will Dietzcefb4482013-01-07 22:25:52 +0000946 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +0000947 } else {
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +0000948 // Arithmetic overflow (+, -, *).
Richard Smithe30752c2012-10-09 19:52:38 +0000949 switch (Opcode) {
950 case BO_Add: CheckName = "add_overflow"; break;
951 case BO_Sub: CheckName = "sub_overflow"; break;
952 case BO_Mul: CheckName = "mul_overflow"; break;
953 default: llvm_unreachable("unexpected opcode for bin op check");
954 }
Will Dietzcefb4482013-01-07 22:25:52 +0000955 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +0000956 }
957 DynamicData.push_back(Info.LHS);
958 DynamicData.push_back(Info.RHS);
959 }
960
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000961 CGF.EmitCheck(Checks, CheckName, StaticData, DynamicData);
Richard Smithe30752c2012-10-09 19:52:38 +0000962}
963
Chris Lattner2da04b32007-08-24 05:35:26 +0000964//===----------------------------------------------------------------------===//
965// Visitor Methods
966//===----------------------------------------------------------------------===//
967
968Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +0000969 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner2da04b32007-08-24 05:35:26 +0000970 if (E->getType()->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +0000971 return nullptr;
Owen Anderson7ec07a52009-07-30 23:11:26 +0000972 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner2da04b32007-08-24 05:35:26 +0000973}
974
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000975Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begemana0110022010-06-08 00:16:34 +0000976 // Vector Mask Case
Craig Toppera97d7e72013-07-26 06:16:11 +0000977 if (E->getNumSubExprs() == 2 ||
Rafael Espindola9cdbd9d2010-06-09 02:17:08 +0000978 (E->getNumSubExprs() == 3 && E->getExpr(2)->getType()->isVectorType())) {
Chris Lattner5e016ae2010-06-27 07:15:29 +0000979 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
980 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
981 Value *Mask;
Craig Toppera97d7e72013-07-26 06:16:11 +0000982
Chris Lattner2192fe52011-07-18 04:24:23 +0000983 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begemana0110022010-06-08 00:16:34 +0000984 unsigned LHSElts = LTy->getNumElements();
985
986 if (E->getNumSubExprs() == 3) {
987 Mask = CGF.EmitScalarExpr(E->getExpr(2));
Craig Toppera97d7e72013-07-26 06:16:11 +0000988
Nate Begemana0110022010-06-08 00:16:34 +0000989 // Shuffle LHS & RHS into one input vector.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000990 SmallVector<llvm::Constant*, 32> concat;
Nate Begemana0110022010-06-08 00:16:34 +0000991 for (unsigned i = 0; i != LHSElts; ++i) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000992 concat.push_back(Builder.getInt32(2*i));
993 concat.push_back(Builder.getInt32(2*i+1));
Nate Begemana0110022010-06-08 00:16:34 +0000994 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000995
Chris Lattner91c08ad2011-02-15 00:14:06 +0000996 Value* CV = llvm::ConstantVector::get(concat);
Nate Begemana0110022010-06-08 00:16:34 +0000997 LHS = Builder.CreateShuffleVector(LHS, RHS, CV, "concat");
998 LHSElts *= 2;
999 } else {
1000 Mask = RHS;
1001 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001002
Chris Lattner2192fe52011-07-18 04:24:23 +00001003 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001004
Nate Begemana0110022010-06-08 00:16:34 +00001005 // Mask off the high bits of each shuffle index.
Benjamin Kramer99383102015-07-28 16:25:32 +00001006 Value *MaskBits =
1007 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
Nate Begemana0110022010-06-08 00:16:34 +00001008 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
Craig Toppera97d7e72013-07-26 06:16:11 +00001009
Nate Begemana0110022010-06-08 00:16:34 +00001010 // newv = undef
1011 // mask = mask & maskbits
1012 // for each elt
1013 // n = extract mask i
1014 // x = extract val n
1015 // newv = insert newv, x, i
Chris Lattner2192fe52011-07-18 04:24:23 +00001016 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Craig Topper18243fb2013-07-27 05:00:42 +00001017 MTy->getNumElements());
Nate Begemana0110022010-06-08 00:16:34 +00001018 Value* NewV = llvm::UndefValue::get(RTy);
1019 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Michael J. Spencerdd597752014-05-31 00:22:12 +00001020 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
Eli Friedman1fa36052012-04-05 21:48:40 +00001021 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Craig Toppera97d7e72013-07-26 06:16:11 +00001022
Nate Begemana0110022010-06-08 00:16:34 +00001023 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman1fa36052012-04-05 21:48:40 +00001024 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begemana0110022010-06-08 00:16:34 +00001025 }
1026 return NewV;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001027 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001028
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001029 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1030 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Craig Toppera97d7e72013-07-26 06:16:11 +00001031
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001032 SmallVector<llvm::Constant*, 32> indices;
Craig Topper0ed37bd2013-08-01 04:51:48 +00001033 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
Craig Topper50ad5b72013-08-03 17:40:38 +00001034 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1035 // Check for -1 and output it as undef in the IR.
1036 if (Idx.isSigned() && Idx.isAllOnesValue())
1037 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1038 else
1039 indices.push_back(Builder.getInt32(Idx.getZExtValue()));
Nate Begemana0110022010-06-08 00:16:34 +00001040 }
1041
Chris Lattner91c08ad2011-02-15 00:14:06 +00001042 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001043 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1044}
Hal Finkelc4d7c822013-09-18 03:29:45 +00001045
1046Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1047 QualType SrcType = E->getSrcExpr()->getType(),
1048 DstType = E->getType();
1049
1050 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1051
1052 SrcType = CGF.getContext().getCanonicalType(SrcType);
1053 DstType = CGF.getContext().getCanonicalType(DstType);
1054 if (SrcType == DstType) return Src;
1055
1056 assert(SrcType->isVectorType() &&
1057 "ConvertVector source type must be a vector");
1058 assert(DstType->isVectorType() &&
1059 "ConvertVector destination type must be a vector");
1060
1061 llvm::Type *SrcTy = Src->getType();
1062 llvm::Type *DstTy = ConvertType(DstType);
1063
1064 // Ignore conversions like int -> uint.
1065 if (SrcTy == DstTy)
1066 return Src;
1067
1068 QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(),
1069 DstEltType = DstType->getAs<VectorType>()->getElementType();
1070
1071 assert(SrcTy->isVectorTy() &&
1072 "ConvertVector source IR type must be a vector");
1073 assert(DstTy->isVectorTy() &&
1074 "ConvertVector destination IR type must be a vector");
1075
1076 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1077 *DstEltTy = DstTy->getVectorElementType();
1078
1079 if (DstEltType->isBooleanType()) {
1080 assert((SrcEltTy->isFloatingPointTy() ||
1081 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1082
1083 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1084 if (SrcEltTy->isFloatingPointTy()) {
1085 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1086 } else {
1087 return Builder.CreateICmpNE(Src, Zero, "tobool");
1088 }
1089 }
1090
1091 // We have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +00001092 Value *Res = nullptr;
Hal Finkelc4d7c822013-09-18 03:29:45 +00001093
1094 if (isa<llvm::IntegerType>(SrcEltTy)) {
1095 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1096 if (isa<llvm::IntegerType>(DstEltTy))
1097 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1098 else if (InputSigned)
1099 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1100 else
1101 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1102 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1103 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1104 if (DstEltType->isSignedIntegerOrEnumerationType())
1105 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1106 else
1107 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1108 } else {
1109 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1110 "Unknown real conversion");
1111 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1112 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1113 else
1114 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1115 }
1116
1117 return Res;
1118}
1119
Eli Friedmancb422f12009-11-26 03:22:21 +00001120Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Richard Smith5fab0c92011-12-28 19:48:30 +00001121 llvm::APSInt Value;
1122 if (E->EvaluateAsInt(Value, CGF.getContext(), Expr::SE_AllowSideEffects)) {
Eli Friedmancb422f12009-11-26 03:22:21 +00001123 if (E->isArrow())
1124 CGF.EmitScalarExpr(E->getBase());
1125 else
1126 EmitLValue(E->getBase());
Richard Smith5fab0c92011-12-28 19:48:30 +00001127 return Builder.getInt(Value);
Eli Friedmancb422f12009-11-26 03:22:21 +00001128 }
Devang Patel44b8bf02010-10-04 21:46:04 +00001129
Eli Friedmancb422f12009-11-26 03:22:21 +00001130 return EmitLoadOfLValue(E);
1131}
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001132
Chris Lattner2da04b32007-08-24 05:35:26 +00001133Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001134 TestAndClearIgnoreResultAssign();
1135
Chris Lattner2da04b32007-08-24 05:35:26 +00001136 // Emit subscript expressions in rvalue context's. For most cases, this just
1137 // loads the lvalue formed by the subscript expr. However, we have to be
1138 // careful, because the base of a vector subscript is occasionally an rvalue,
1139 // so we can't get it as an lvalue.
1140 if (!E->getBase()->getType()->isVectorType())
1141 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +00001142
Chris Lattner2da04b32007-08-24 05:35:26 +00001143 // Handle the vector case. The base must be a vector, the index must be an
1144 // integer value.
1145 Value *Base = Visit(E->getBase());
1146 Value *Idx = Visit(E->getIdx());
Richard Smith539e4a72013-02-23 02:53:19 +00001147 QualType IdxTy = E->getIdx()->getType();
1148
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001149 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00001150 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1151
Chris Lattner2da04b32007-08-24 05:35:26 +00001152 return Builder.CreateExtractElement(Base, Idx, "vecext");
1153}
1154
Nate Begeman19351632009-10-18 20:10:40 +00001155static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2192fe52011-07-18 04:24:23 +00001156 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman19351632009-10-18 20:10:40 +00001157 int MV = SVI->getMaskValue(Idx);
Craig Toppera97d7e72013-07-26 06:16:11 +00001158 if (MV == -1)
Nate Begeman19351632009-10-18 20:10:40 +00001159 return llvm::UndefValue::get(I32Ty);
1160 return llvm::ConstantInt::get(I32Ty, Off+MV);
1161}
1162
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001163static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1164 if (C->getBitWidth() != 32) {
1165 assert(llvm::ConstantInt::isValueValidForType(I32Ty,
1166 C->getZExtValue()) &&
1167 "Index operand too large for shufflevector mask!");
1168 return llvm::ConstantInt::get(I32Ty, C->getZExtValue());
1169 }
1170 return C;
1171}
1172
Nate Begeman19351632009-10-18 20:10:40 +00001173Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1174 bool Ignore = TestAndClearIgnoreResultAssign();
1175 (void)Ignore;
1176 assert (Ignore == false && "init list ignored");
1177 unsigned NumInitElements = E->getNumInits();
Craig Toppera97d7e72013-07-26 06:16:11 +00001178
Nate Begeman19351632009-10-18 20:10:40 +00001179 if (E->hadArrayRangeDesignator())
1180 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Craig Toppera97d7e72013-07-26 06:16:11 +00001181
Chris Lattner2192fe52011-07-18 04:24:23 +00001182 llvm::VectorType *VType =
Nate Begeman19351632009-10-18 20:10:40 +00001183 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
Craig Toppera97d7e72013-07-26 06:16:11 +00001184
Sebastian Redl12757ab2011-09-24 17:48:14 +00001185 if (!VType) {
1186 if (NumInitElements == 0) {
1187 // C++11 value-initialization for the scalar.
1188 return EmitNullValue(E->getType());
1189 }
1190 // We have a scalar in braces. Just use the first element.
Nate Begeman19351632009-10-18 20:10:40 +00001191 return Visit(E->getInit(0));
Sebastian Redl12757ab2011-09-24 17:48:14 +00001192 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001193
Nate Begeman19351632009-10-18 20:10:40 +00001194 unsigned ResElts = VType->getNumElements();
Craig Toppera97d7e72013-07-26 06:16:11 +00001195
1196 // Loop over initializers collecting the Value for each, and remembering
Nate Begeman19351632009-10-18 20:10:40 +00001197 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1198 // us to fold the shuffle for the swizzle into the shuffle for the vector
1199 // initializer, since LLVM optimizers generally do not want to touch
1200 // shuffles.
1201 unsigned CurIdx = 0;
1202 bool VIsUndefShuffle = false;
1203 llvm::Value *V = llvm::UndefValue::get(VType);
1204 for (unsigned i = 0; i != NumInitElements; ++i) {
1205 Expr *IE = E->getInit(i);
1206 Value *Init = Visit(IE);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001207 SmallVector<llvm::Constant*, 16> Args;
Craig Toppera97d7e72013-07-26 06:16:11 +00001208
Chris Lattner2192fe52011-07-18 04:24:23 +00001209 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001210
Nate Begeman19351632009-10-18 20:10:40 +00001211 // Handle scalar elements. If the scalar initializer is actually one
Craig Toppera97d7e72013-07-26 06:16:11 +00001212 // element of a different vector of the same width, use shuffle instead of
Nate Begeman19351632009-10-18 20:10:40 +00001213 // extract+insert.
1214 if (!VVT) {
1215 if (isa<ExtVectorElementExpr>(IE)) {
1216 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1217
1218 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1219 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
Craig Topper8a13c412014-05-21 05:09:00 +00001220 Value *LHS = nullptr, *RHS = nullptr;
Nate Begeman19351632009-10-18 20:10:40 +00001221 if (CurIdx == 0) {
1222 // insert into undef -> shuffle (src, undef)
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001223 // shufflemask must use an i32
1224 Args.push_back(getAsInt32(C, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001225 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001226
1227 LHS = EI->getVectorOperand();
1228 RHS = V;
1229 VIsUndefShuffle = true;
1230 } else if (VIsUndefShuffle) {
1231 // insert into undefshuffle && size match -> shuffle (v, src)
1232 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1233 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001234 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner2531eb42011-04-19 22:55:03 +00001235 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001236 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1237
Nate Begeman19351632009-10-18 20:10:40 +00001238 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1239 RHS = EI->getVectorOperand();
1240 VIsUndefShuffle = false;
1241 }
1242 if (!Args.empty()) {
Chris Lattner91c08ad2011-02-15 00:14:06 +00001243 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001244 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1245 ++CurIdx;
1246 continue;
1247 }
1248 }
1249 }
Chris Lattner2531eb42011-04-19 22:55:03 +00001250 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1251 "vecinit");
Nate Begeman19351632009-10-18 20:10:40 +00001252 VIsUndefShuffle = false;
1253 ++CurIdx;
1254 continue;
1255 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001256
Nate Begeman19351632009-10-18 20:10:40 +00001257 unsigned InitElts = VVT->getNumElements();
1258
Craig Toppera97d7e72013-07-26 06:16:11 +00001259 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
Nate Begeman19351632009-10-18 20:10:40 +00001260 // input is the same width as the vector being constructed, generate an
1261 // optimized shuffle of the swizzle input into the result.
Nate Begemanb8326be2009-10-25 02:26:01 +00001262 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman19351632009-10-18 20:10:40 +00001263 if (isa<ExtVectorElementExpr>(IE)) {
1264 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1265 Value *SVOp = SVI->getOperand(0);
Chris Lattner2192fe52011-07-18 04:24:23 +00001266 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001267
Nate Begeman19351632009-10-18 20:10:40 +00001268 if (OpTy->getNumElements() == ResElts) {
Nate Begeman19351632009-10-18 20:10:40 +00001269 for (unsigned j = 0; j != CurIdx; ++j) {
1270 // If the current vector initializer is a shuffle with undef, merge
1271 // this shuffle directly into it.
1272 if (VIsUndefShuffle) {
1273 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner5e016ae2010-06-27 07:15:29 +00001274 CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001275 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00001276 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001277 }
1278 }
1279 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001280 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001281 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001282
1283 if (VIsUndefShuffle)
1284 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1285
1286 Init = SVOp;
1287 }
1288 }
1289
1290 // Extend init to result vector length, and then shuffle its contribution
1291 // to the vector initializer into V.
1292 if (Args.empty()) {
1293 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001294 Args.push_back(Builder.getInt32(j));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001295 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001296 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001297 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemanb8326be2009-10-25 02:26:01 +00001298 Mask, "vext");
Nate Begeman19351632009-10-18 20:10:40 +00001299
1300 Args.clear();
1301 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001302 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001303 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001304 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001305 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001306 }
1307
1308 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1309 // merging subsequent shuffles into this one.
1310 if (CurIdx == 0)
1311 std::swap(V, Init);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001312 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001313 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1314 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1315 CurIdx += InitElts;
1316 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001317
Nate Begeman19351632009-10-18 20:10:40 +00001318 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1319 // Emit remaining default initializers.
Chris Lattner2192fe52011-07-18 04:24:23 +00001320 llvm::Type *EltTy = VType->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00001321
Nate Begeman19351632009-10-18 20:10:40 +00001322 // Emit remaining default initializers
1323 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner2531eb42011-04-19 22:55:03 +00001324 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman19351632009-10-18 20:10:40 +00001325 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1326 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1327 }
1328 return V;
1329}
1330
Anders Carlsson8c793172009-11-23 17:57:54 +00001331static bool ShouldNullCheckClassCastValue(const CastExpr *CE) {
1332 const Expr *E = CE->getSubExpr();
John McCalld9c7c6562010-03-30 23:58:03 +00001333
John McCalle3027922010-08-25 11:45:40 +00001334 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCalld9c7c6562010-03-30 23:58:03 +00001335 return false;
Craig Toppera97d7e72013-07-26 06:16:11 +00001336
Anders Carlsson8c793172009-11-23 17:57:54 +00001337 if (isa<CXXThisExpr>(E)) {
1338 // We always assume that 'this' is never null.
1339 return false;
1340 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001341
Anders Carlsson8c793172009-11-23 17:57:54 +00001342 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001343 // And that glvalue casts are never null.
John McCall2536c6d2010-08-25 10:28:54 +00001344 if (ICE->getValueKind() != VK_RValue)
Anders Carlsson8c793172009-11-23 17:57:54 +00001345 return false;
1346 }
1347
1348 return true;
1349}
1350
Chris Lattner2da04b32007-08-24 05:35:26 +00001351// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1352// have to handle a more broad range of conversions than explicit casts, as they
1353// handle things like function to ptr-to-function decay etc.
John McCall23c29fe2011-06-24 21:55:10 +00001354Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001355 Expr *E = CE->getSubExpr();
Anders Carlsson8c978b42009-09-22 22:00:46 +00001356 QualType DestTy = CE->getType();
John McCalle3027922010-08-25 11:45:40 +00001357 CastKind Kind = CE->getCastKind();
Craig Toppera97d7e72013-07-26 06:16:11 +00001358
Mike Stumpdf0fe272009-05-29 15:46:01 +00001359 if (!DestTy->isVoidType())
1360 TestAndClearIgnoreResultAssign();
Mike Stump4a3999f2009-09-09 13:00:44 +00001361
Eli Friedman0dfc6802009-11-27 02:07:44 +00001362 // Since almost all cast kinds apply to scalars, this switch doesn't have
1363 // a default case, so the compiler will warn on a missing case. The cases
1364 // are in the same order as in the CastKind enum.
Anders Carlsson3df53bc2009-08-24 18:26:39 +00001365 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +00001366 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00001367 case CK_BuiltinFnToFnPtr:
1368 llvm_unreachable("builtin functions are handled elsewhere");
1369
Craig Toppera97d7e72013-07-26 06:16:11 +00001370 case CK_LValueBitCast:
John McCalle3027922010-08-25 11:45:40 +00001371 case CK_ObjCObjectLValueCast: {
Douglas Gregor51954272010-07-13 23:17:26 +00001372 Value *V = EmitLValue(E).getAddress();
Craig Toppera97d7e72013-07-26 06:16:11 +00001373 V = Builder.CreateBitCast(V,
Douglas Gregor51954272010-07-13 23:17:26 +00001374 ConvertType(CGF.getContext().getPointerType(DestTy)));
Nick Lewycky2d84e842013-10-02 02:29:49 +00001375 return EmitLoadOfLValue(CGF.MakeNaturalAlignAddrLValue(V, DestTy),
1376 CE->getExprLoc());
Douglas Gregor51954272010-07-13 23:17:26 +00001377 }
John McCallcd78e802011-09-10 01:16:55 +00001378
John McCall9320b872011-09-09 05:25:32 +00001379 case CK_CPointerToObjCPointerCast:
1380 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00001381 case CK_AnyPointerToBlockPointerCast:
1382 case CK_BitCast: {
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001383 Value *Src = Visit(const_cast<Expr*>(E));
David Tweede1468322013-12-11 13:39:46 +00001384 llvm::Type *SrcTy = Src->getType();
1385 llvm::Type *DstTy = ConvertType(DestTy);
Bob Wilson95a27b02014-02-17 19:20:59 +00001386 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
David Tweede1468322013-12-11 13:39:46 +00001387 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00001388 llvm_unreachable("wrong cast for pointers in different address spaces"
1389 "(must be an address space cast)!");
David Tweede1468322013-12-11 13:39:46 +00001390 }
Peter Collingbourned2926c92015-03-14 02:42:25 +00001391
1392 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
1393 if (auto PT = DestTy->getAs<PointerType>())
1394 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001395 /*MayBeNull=*/true,
1396 CodeGenFunction::CFITCK_UnrelatedCast,
1397 CE->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00001398 }
1399
David Tweede1468322013-12-11 13:39:46 +00001400 return Builder.CreateBitCast(Src, DstTy);
1401 }
1402 case CK_AddressSpaceConversion: {
1403 Value *Src = Visit(const_cast<Expr*>(E));
1404 return Builder.CreateAddrSpaceCast(Src, ConvertType(DestTy));
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00001405 }
David Chisnallfa35df62012-01-16 17:27:18 +00001406 case CK_AtomicToNonAtomic:
1407 case CK_NonAtomicToAtomic:
John McCalle3027922010-08-25 11:45:40 +00001408 case CK_NoOp:
1409 case CK_UserDefinedConversion:
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001410 return Visit(const_cast<Expr*>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00001411
John McCalle3027922010-08-25 11:45:40 +00001412 case CK_BaseToDerived: {
Jordan Rose7bb26112012-10-03 01:08:28 +00001413 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
1414 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
1415
Richard Smith2c5868c2013-02-13 21:18:23 +00001416 llvm::Value *V = Visit(E);
1417
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00001418 llvm::Value *Derived =
1419 CGF.GetAddressOfDerivedClass(V, DerivedClassDecl,
1420 CE->path_begin(), CE->path_end(),
1421 ShouldNullCheckClassCastValue(CE));
1422
Richard Smith2c5868c2013-02-13 21:18:23 +00001423 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
1424 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00001425 if (CGF.sanitizePerformTypeCheck())
Richard Smith2c5868c2013-02-13 21:18:23 +00001426 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00001427 Derived, DestTy->getPointeeType());
Richard Smith2c5868c2013-02-13 21:18:23 +00001428
Peter Collingbourned2926c92015-03-14 02:42:25 +00001429 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
1430 CGF.EmitVTablePtrCheckForCast(DestTy->getPointeeType(), Derived,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00001431 /*MayBeNull=*/true,
1432 CodeGenFunction::CFITCK_DerivedCast,
1433 CE->getLocStart());
Peter Collingbourned2926c92015-03-14 02:42:25 +00001434
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00001435 return Derived;
Anders Carlsson8c793172009-11-23 17:57:54 +00001436 }
John McCalle3027922010-08-25 11:45:40 +00001437 case CK_UncheckedDerivedToBase:
1438 case CK_DerivedToBase: {
Jordan Rose7bb26112012-10-03 01:08:28 +00001439 const CXXRecordDecl *DerivedClassDecl =
1440 E->getType()->getPointeeCXXRecordDecl();
1441 assert(DerivedClassDecl && "DerivedToBase arg isn't a C++ object pointer!");
Anders Carlsson12f5a252009-09-12 04:57:16 +00001442
Alexey Samsonoveb47d8a2014-10-13 23:59:00 +00001443 return CGF.GetAddressOfBaseClass(
1444 Visit(E), DerivedClassDecl, CE->path_begin(), CE->path_end(),
1445 ShouldNullCheckClassCastValue(CE), CE->getExprLoc());
Anders Carlsson12f5a252009-09-12 04:57:16 +00001446 }
Anders Carlsson8a01a752011-04-11 02:03:26 +00001447 case CK_Dynamic: {
Eli Friedman0dfc6802009-11-27 02:07:44 +00001448 Value *V = Visit(const_cast<Expr*>(E));
1449 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
1450 return CGF.EmitDynamicCast(V, DCE);
1451 }
Eli Friedmane96f1d32009-11-27 04:41:50 +00001452
John McCalle3027922010-08-25 11:45:40 +00001453 case CK_ArrayToPointerDecay: {
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001454 assert(E->getType()->isArrayType() &&
1455 "Array to pointer decay must have array source type!");
1456
1457 Value *V = EmitLValue(E).getAddress(); // Bitfields can't be arrays.
1458
1459 // Note that VLA pointers are always decayed, so we don't need to do
1460 // anything here.
1461 if (!E->getType()->isVariableArrayType()) {
1462 assert(isa<llvm::PointerType>(V->getType()) && "Expected pointer");
David Blaikie1ed728c2015-04-05 22:45:47 +00001463 llvm::Type *NewTy = ConvertType(E->getType());
David Majnemer17e26332014-12-14 12:16:43 +00001464 V = CGF.Builder.CreatePointerCast(
David Blaikie1ed728c2015-04-05 22:45:47 +00001465 V, NewTy->getPointerTo(V->getType()->getPointerAddressSpace()));
David Majnemer17e26332014-12-14 12:16:43 +00001466
1467 assert(isa<llvm::ArrayType>(V->getType()->getPointerElementType()) &&
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001468 "Expected pointer to array");
David Blaikie1ed728c2015-04-05 22:45:47 +00001469 V = Builder.CreateStructGEP(NewTy, V, 0, "arraydecay");
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001470 }
1471
Chris Lattner71bd0c32011-07-20 04:31:01 +00001472 // Make sure the array decay ends up being the right type. This matters if
1473 // the array type was of an incomplete type.
David Tweede1468322013-12-11 13:39:46 +00001474 return CGF.Builder.CreatePointerCast(V, ConvertType(CE->getType()));
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001475 }
John McCalle3027922010-08-25 11:45:40 +00001476 case CK_FunctionToPointerDecay:
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001477 return EmitLValue(E).getAddress();
1478
John McCalle84af4e2010-11-13 01:35:44 +00001479 case CK_NullToPointer:
1480 if (MustVisitNullValue(E))
1481 (void) Visit(E);
1482
1483 return llvm::ConstantPointerNull::get(
1484 cast<llvm::PointerType>(ConvertType(DestTy)));
1485
John McCalle3027922010-08-25 11:45:40 +00001486 case CK_NullToMemberPointer: {
John McCalle84af4e2010-11-13 01:35:44 +00001487 if (MustVisitNullValue(E))
John McCalla1dee5302010-08-22 10:59:02 +00001488 (void) Visit(E);
1489
John McCall7a9aac22010-08-23 01:21:21 +00001490 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
1491 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
1492 }
Anders Carlsson12f5a252009-09-12 04:57:16 +00001493
John McCallc62bb392012-02-15 01:22:51 +00001494 case CK_ReinterpretMemberPointer:
John McCalle3027922010-08-25 11:45:40 +00001495 case CK_BaseToDerivedMemberPointer:
1496 case CK_DerivedToBaseMemberPointer: {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001497 Value *Src = Visit(E);
Craig Toppera97d7e72013-07-26 06:16:11 +00001498
John McCalla1dee5302010-08-22 10:59:02 +00001499 // Note that the AST doesn't distinguish between checked and
1500 // unchecked member pointer conversions, so we always have to
1501 // implement checked conversions here. This is inefficient when
1502 // actual control flow may be required in order to perform the
1503 // check, which it is for data member pointers (but not member
1504 // function pointers on Itanium and ARM).
John McCall7a9aac22010-08-23 01:21:21 +00001505 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmane96f1d32009-11-27 04:41:50 +00001506 }
John McCall31168b02011-06-15 23:02:42 +00001507
John McCall2d637d22011-09-10 06:18:15 +00001508 case CK_ARCProduceObject:
John McCall31168b02011-06-15 23:02:42 +00001509 return CGF.EmitARCRetainScalarExpr(E);
John McCall2d637d22011-09-10 06:18:15 +00001510 case CK_ARCConsumeObject:
John McCall31168b02011-06-15 23:02:42 +00001511 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCall2d637d22011-09-10 06:18:15 +00001512 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00001513 llvm::Value *value = Visit(E);
1514 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
1515 return CGF.EmitObjCConsumeObject(E->getType(), value);
1516 }
John McCallff613032011-10-04 06:23:45 +00001517 case CK_ARCExtendBlockObject:
1518 return CGF.EmitARCExtendBlockObject(E);
John McCall31168b02011-06-15 23:02:42 +00001519
Douglas Gregored90df32012-02-22 05:02:47 +00001520 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmanec75fec2012-02-28 01:08:45 +00001521 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001522
John McCallc5e62b42010-11-13 09:02:35 +00001523 case CK_FloatingRealToComplex:
1524 case CK_FloatingComplexCast:
1525 case CK_IntegralRealToComplex:
1526 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00001527 case CK_IntegralComplexToFloatingComplex:
1528 case CK_FloatingComplexToIntegralComplex:
John McCalle3027922010-08-25 11:45:40 +00001529 case CK_ConstructorConversion:
John McCall3eba6e62010-11-16 06:21:14 +00001530 case CK_ToUnion:
1531 llvm_unreachable("scalar cast to non-scalar value");
John McCall34376a62010-12-04 03:47:34 +00001532
John McCallf3735e02010-12-01 04:43:34 +00001533 case CK_LValueToRValue:
1534 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCall34376a62010-12-04 03:47:34 +00001535 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCallf3735e02010-12-01 04:43:34 +00001536 return Visit(const_cast<Expr*>(E));
Eli Friedman0dfc6802009-11-27 02:07:44 +00001537
John McCalle3027922010-08-25 11:45:40 +00001538 case CK_IntegralToPointer: {
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001539 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001540
Anders Carlsson094c4592009-10-18 18:12:03 +00001541 // First, convert to the correct width so that we control the kind of
1542 // extension.
Chris Lattner2192fe52011-07-18 04:24:23 +00001543 llvm::Type *MiddleTy = CGF.IntPtrTy;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001544 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson094c4592009-10-18 18:12:03 +00001545 llvm::Value* IntResult =
1546 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001547
Anders Carlsson094c4592009-10-18 18:12:03 +00001548 return Builder.CreateIntToPtr(IntResult, ConvertType(DestTy));
Anders Carlsson7cd39e02009-09-15 04:48:33 +00001549 }
Eli Friedman58368522011-06-25 02:58:47 +00001550 case CK_PointerToIntegral:
1551 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
1552 return Builder.CreatePtrToInt(Visit(E), ConvertType(DestTy));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00001553
John McCalle3027922010-08-25 11:45:40 +00001554 case CK_ToVoid: {
John McCalla2342eb2010-12-05 02:00:02 +00001555 CGF.EmitIgnoredExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +00001556 return nullptr;
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001557 }
John McCalle3027922010-08-25 11:45:40 +00001558 case CK_VectorSplat: {
Chris Lattner2192fe52011-07-18 04:24:23 +00001559 llvm::Type *DstTy = ConvertType(DestTy);
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001560 Value *Elt = Visit(const_cast<Expr*>(E));
Craig Topper5b5935d2012-02-06 05:05:50 +00001561 Elt = EmitScalarConversion(Elt, E->getType(),
1562 DestTy->getAs<VectorType>()->getElementType());
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001563
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001564 // Splat the element across to all elements
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001565 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Alp Toker5f072d82014-04-19 23:55:49 +00001566 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Eli Friedmanc08bdea2009-11-16 21:33:53 +00001567 }
John McCall8cb679e2010-11-15 09:13:47 +00001568
John McCalle3027922010-08-25 11:45:40 +00001569 case CK_IntegralCast:
1570 case CK_IntegralToFloating:
1571 case CK_FloatingToIntegral:
1572 case CK_FloatingCast:
Eli Friedmane96f1d32009-11-27 04:41:50 +00001573 return EmitScalarConversion(Visit(E), E->getType(), DestTy);
John McCall8cb679e2010-11-15 09:13:47 +00001574 case CK_IntegralToBoolean:
1575 return EmitIntToBoolConversion(Visit(E));
1576 case CK_PointerToBoolean:
1577 return EmitPointerToBoolConversion(Visit(E));
1578 case CK_FloatingToBoolean:
1579 return EmitFloatToBoolConversion(Visit(E));
John McCalle3027922010-08-25 11:45:40 +00001580 case CK_MemberPointerToBoolean: {
John McCall7a9aac22010-08-23 01:21:21 +00001581 llvm::Value *MemPtr = Visit(E);
1582 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
1583 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlsson3df53bc2009-08-24 18:26:39 +00001584 }
John McCalld7646252010-11-14 08:17:51 +00001585
1586 case CK_FloatingComplexToReal:
1587 case CK_IntegralComplexToReal:
John McCall07bb1962010-11-16 10:08:07 +00001588 return CGF.EmitComplexExpr(E, false, true).first;
John McCalld7646252010-11-14 08:17:51 +00001589
1590 case CK_FloatingComplexToBoolean:
1591 case CK_IntegralComplexToBoolean: {
John McCall07bb1962010-11-16 10:08:07 +00001592 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCalld7646252010-11-14 08:17:51 +00001593
1594 // TODO: kill this function off, inline appropriate case here
1595 return EmitComplexToScalarConversion(V, E->getType(), DestTy);
1596 }
1597
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001598 case CK_ZeroToOCLEvent: {
Alp Tokerd4733632013-12-05 04:47:09 +00001599 assert(DestTy->isEventT() && "CK_ZeroToOCLEvent cast on non-event type");
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001600 return llvm::Constant::getNullValue(ConvertType(DestTy));
1601 }
1602
John McCall7a9aac22010-08-23 01:21:21 +00001603 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001604
John McCall3eba6e62010-11-16 06:21:14 +00001605 llvm_unreachable("unknown scalar cast");
Chris Lattner2da04b32007-08-24 05:35:26 +00001606}
1607
Chris Lattner04a913b2007-08-31 22:09:40 +00001608Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +00001609 CodeGenFunction::StmtExprEvaluation eval(CGF);
Eli Friedman4871a462013-06-10 22:04:49 +00001610 llvm::Value *RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
1611 !E->getType()->isVoidType());
1612 if (!RetAlloca)
Craig Topper8a13c412014-05-21 05:09:00 +00001613 return nullptr;
Nick Lewycky2d84e842013-10-02 02:29:49 +00001614 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
1615 E->getExprLoc());
Chris Lattner04a913b2007-08-31 22:09:40 +00001616}
1617
Chris Lattner2da04b32007-08-24 05:35:26 +00001618//===----------------------------------------------------------------------===//
1619// Unary Operators
1620//===----------------------------------------------------------------------===//
1621
Alexey Samsonovf6246502015-04-23 01:50:45 +00001622static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
1623 llvm::Value *InVal, bool IsInc) {
1624 BinOpInfo BinOp;
1625 BinOp.LHS = InVal;
1626 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
1627 BinOp.Ty = E->getType();
1628 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
1629 BinOp.FPContractable = false;
1630 BinOp.E = E;
1631 return BinOp;
1632}
1633
1634llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
1635 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
1636 llvm::Value *Amount =
1637 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
1638 StringRef Name = IsInc ? "inc" : "dec";
Richard Smith9c6890a2012-11-01 22:30:59 +00001639 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00001640 case LangOptions::SOB_Defined:
Alexey Samsonovf6246502015-04-23 01:50:45 +00001641 return Builder.CreateAdd(InVal, Amount, Name);
Richard Smith3e056de2012-08-25 00:32:28 +00001642 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001643 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Alexey Samsonovf6246502015-04-23 01:50:45 +00001644 return Builder.CreateNSWAdd(InVal, Amount, Name);
Richard Smith3e056de2012-08-25 00:32:28 +00001645 // Fall through.
Anton Yartsev85129b82011-02-07 02:17:30 +00001646 case LangOptions::SOB_Trapping:
Alexey Samsonovf6246502015-04-23 01:50:45 +00001647 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc));
Anton Yartsev85129b82011-02-07 02:17:30 +00001648 }
David Blaikie83d382b2011-09-23 05:06:16 +00001649 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev85129b82011-02-07 02:17:30 +00001650}
1651
John McCalle3dc1702011-02-15 09:22:45 +00001652llvm::Value *
1653ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
1654 bool isInc, bool isPre) {
Craig Toppera97d7e72013-07-26 06:16:11 +00001655
John McCalle3dc1702011-02-15 09:22:45 +00001656 QualType type = E->getSubExpr()->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00001657 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00001658 llvm::Value *value;
1659 llvm::Value *input;
Anton Yartsev85129b82011-02-07 02:17:30 +00001660
John McCalle3dc1702011-02-15 09:22:45 +00001661 int amount = (isInc ? 1 : -1);
1662
David Chisnallfa35df62012-01-16 17:27:18 +00001663 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
David Chisnallef78c302013-03-03 16:02:42 +00001664 type = atomicTy->getValueType();
1665 if (isInc && type->isBooleanType()) {
1666 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
1667 if (isPre) {
1668 Builder.Insert(new llvm::StoreInst(True,
1669 LV.getAddress(), LV.isVolatileQualified(),
1670 LV.getAlignment().getQuantity(),
1671 llvm::SequentiallyConsistent));
1672 return Builder.getTrue();
1673 }
1674 // For atomic bool increment, we just store true and return it for
1675 // preincrement, do an atomic swap with true for postincrement
1676 return Builder.CreateAtomicRMW(llvm::AtomicRMWInst::Xchg,
1677 LV.getAddress(), True, llvm::SequentiallyConsistent);
1678 }
1679 // Special case for atomic increment / decrement on integers, emit
1680 // atomicrmw instructions. We skip this if we want to be doing overflow
Craig Toppera97d7e72013-07-26 06:16:11 +00001681 // checking, and fall into the slow path with the atomic cmpxchg loop.
David Chisnallef78c302013-03-03 16:02:42 +00001682 if (!type->isBooleanType() && type->isIntegerType() &&
1683 !(type->isUnsignedIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001684 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
David Chisnallef78c302013-03-03 16:02:42 +00001685 CGF.getLangOpts().getSignedOverflowBehavior() !=
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001686 LangOptions::SOB_Trapping) {
David Chisnallef78c302013-03-03 16:02:42 +00001687 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
1688 llvm::AtomicRMWInst::Sub;
1689 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
1690 llvm::Instruction::Sub;
1691 llvm::Value *amt = CGF.EmitToMemory(
1692 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
1693 llvm::Value *old = Builder.CreateAtomicRMW(aop,
1694 LV.getAddress(), amt, llvm::SequentiallyConsistent);
1695 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
1696 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00001697 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00001698 input = value;
1699 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
David Chisnallfa35df62012-01-16 17:27:18 +00001700 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
1701 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
David Chisnallef78c302013-03-03 16:02:42 +00001702 value = CGF.EmitToMemory(value, type);
David Chisnallfa35df62012-01-16 17:27:18 +00001703 Builder.CreateBr(opBB);
1704 Builder.SetInsertPoint(opBB);
1705 atomicPHI = Builder.CreatePHI(value->getType(), 2);
1706 atomicPHI->addIncoming(value, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00001707 value = atomicPHI;
David Chisnallef78c302013-03-03 16:02:42 +00001708 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00001709 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00001710 input = value;
David Chisnallfa35df62012-01-16 17:27:18 +00001711 }
1712
John McCalle3dc1702011-02-15 09:22:45 +00001713 // Special case of integer increment that we have to check first: bool++.
1714 // Due to promotion rules, we get:
1715 // bool++ -> bool = bool + 1
1716 // -> bool = (int)bool + 1
1717 // -> bool = ((int)bool + 1 != 0)
1718 // An interesting aspect of this is that increment is always true.
1719 // Decrement does not have this property.
1720 if (isInc && type->isBooleanType()) {
1721 value = Builder.getTrue();
1722
1723 // Most common case by far: integer increment.
1724 } else if (type->isIntegerType()) {
Eli Friedman846ded22011-03-02 01:49:12 +00001725 // Note that signed integer inc/dec with width less than int can't
1726 // overflow because of promotion rules; we're just eliding a few steps here.
Richard Smith45d099b2014-07-07 05:36:14 +00001727 bool CanOverflow = value->getType()->getIntegerBitWidth() >=
1728 CGF.IntTy->getIntegerBitWidth();
1729 if (CanOverflow && type->isSignedIntegerOrEnumerationType()) {
Alexey Samsonovf6246502015-04-23 01:50:45 +00001730 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
Richard Smith45d099b2014-07-07 05:36:14 +00001731 } else if (CanOverflow && type->isUnsignedIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001732 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
Alexey Samsonovf6246502015-04-23 01:50:45 +00001733 value =
1734 EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc));
1735 } else {
1736 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCalle3dc1702011-02-15 09:22:45 +00001737 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
Alexey Samsonovf6246502015-04-23 01:50:45 +00001738 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001739
John McCalle3dc1702011-02-15 09:22:45 +00001740 // Next most common: pointer increment.
1741 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
1742 QualType type = ptr->getPointeeType();
1743
1744 // VLA types don't have constant size.
John McCall77527a82011-06-25 01:32:37 +00001745 if (const VariableArrayType *vla
1746 = CGF.getContext().getAsVariableArrayType(type)) {
1747 llvm::Value *numElts = CGF.getVLASize(vla).first;
John McCall23c29fe2011-06-24 21:55:10 +00001748 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Richard Smith9c6890a2012-11-01 22:30:59 +00001749 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall23c29fe2011-06-24 21:55:10 +00001750 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2e72da942011-03-01 00:03:48 +00001751 else
John McCall23c29fe2011-06-24 21:55:10 +00001752 value = Builder.CreateInBoundsGEP(value, numElts, "vla.inc");
Craig Toppera97d7e72013-07-26 06:16:11 +00001753
John McCalle3dc1702011-02-15 09:22:45 +00001754 // Arithmetic on function pointers (!) is just +-1.
1755 } else if (type->isFunctionType()) {
Chris Lattner2531eb42011-04-19 22:55:03 +00001756 llvm::Value *amt = Builder.getInt32(amount);
John McCalle3dc1702011-02-15 09:22:45 +00001757
1758 value = CGF.EmitCastToVoidPtr(value);
Richard Smith9c6890a2012-11-01 22:30:59 +00001759 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001760 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
1761 else
1762 value = Builder.CreateInBoundsGEP(value, amt, "incdec.funcptr");
John McCalle3dc1702011-02-15 09:22:45 +00001763 value = Builder.CreateBitCast(value, input->getType());
1764
1765 // For everything else, we can just do a simple increment.
Anton Yartsev85129b82011-02-07 02:17:30 +00001766 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00001767 llvm::Value *amt = Builder.getInt32(amount);
Richard Smith9c6890a2012-11-01 22:30:59 +00001768 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001769 value = Builder.CreateGEP(value, amt, "incdec.ptr");
1770 else
1771 value = Builder.CreateInBoundsGEP(value, amt, "incdec.ptr");
John McCalle3dc1702011-02-15 09:22:45 +00001772 }
1773
1774 // Vector increment/decrement.
1775 } else if (type->isVectorType()) {
1776 if (type->hasIntegerRepresentation()) {
1777 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
1778
Eli Friedman409943e2011-05-06 18:04:18 +00001779 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCalle3dc1702011-02-15 09:22:45 +00001780 } else {
1781 value = Builder.CreateFAdd(
1782 value,
1783 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev85129b82011-02-07 02:17:30 +00001784 isInc ? "inc" : "dec");
1785 }
Anton Yartsev85129b82011-02-07 02:17:30 +00001786
John McCalle3dc1702011-02-15 09:22:45 +00001787 // Floating point.
1788 } else if (type->isRealFloatingType()) {
Chris Lattner05dc78c2010-06-26 22:09:34 +00001789 // Add the inc/dec to the real part.
John McCalle3dc1702011-02-15 09:22:45 +00001790 llvm::Value *amt;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001791
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001792 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001793 // Another special case: half FP increment should be done via float
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001794 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
1795 value = Builder.CreateCall(
1796 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1797 CGF.CGM.FloatTy),
1798 input, "incdec.conv");
1799 } else {
1800 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
1801 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001802 }
1803
John McCalle3dc1702011-02-15 09:22:45 +00001804 if (value->getType()->isFloatTy())
1805 amt = llvm::ConstantFP::get(VMContext,
1806 llvm::APFloat(static_cast<float>(amount)));
1807 else if (value->getType()->isDoubleTy())
1808 amt = llvm::ConstantFP::get(VMContext,
1809 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner05dc78c2010-06-26 22:09:34 +00001810 else {
Ahmed Bougacha6ba38312015-03-24 23:44:42 +00001811 // Remaining types are either Half or LongDouble. Convert from float.
John McCalle3dc1702011-02-15 09:22:45 +00001812 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner05dc78c2010-06-26 22:09:34 +00001813 bool ignored;
Ahmed Bougacha6ba38312015-03-24 23:44:42 +00001814 // Don't use getFloatTypeSemantics because Half isn't
1815 // necessarily represented using the "half" LLVM type.
1816 F.convert(value->getType()->isHalfTy()
1817 ? CGF.getTarget().getHalfFormat()
1818 : CGF.getTarget().getLongDoubleFormat(),
John McCallc8e01702013-04-16 22:48:15 +00001819 llvm::APFloat::rmTowardZero, &ignored);
John McCalle3dc1702011-02-15 09:22:45 +00001820 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner05dc78c2010-06-26 22:09:34 +00001821 }
John McCalle3dc1702011-02-15 09:22:45 +00001822 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
1823
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001824 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1825 if (!CGF.getContext().getLangOpts().HalfArgsAndReturns) {
1826 value = Builder.CreateCall(
1827 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
1828 CGF.CGM.FloatTy),
1829 value, "incdec.conv");
1830 } else {
1831 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
1832 }
1833 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001834
John McCalle3dc1702011-02-15 09:22:45 +00001835 // Objective-C pointer types.
1836 } else {
1837 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
1838 value = CGF.EmitCastToVoidPtr(value);
1839
1840 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
1841 if (!isInc) size = -size;
1842 llvm::Value *sizeValue =
1843 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
1844
Richard Smith9c6890a2012-11-01 22:30:59 +00001845 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00001846 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
1847 else
1848 value = Builder.CreateInBoundsGEP(value, sizeValue, "incdec.objptr");
John McCalle3dc1702011-02-15 09:22:45 +00001849 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner05dc78c2010-06-26 22:09:34 +00001850 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001851
David Chisnallfa35df62012-01-16 17:27:18 +00001852 if (atomicPHI) {
1853 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
1854 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00001855 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00001856 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
1857 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
1858 llvm::Value *success = Pair.second;
David Chisnallfa35df62012-01-16 17:27:18 +00001859 atomicPHI->addIncoming(old, opBB);
David Chisnallfa35df62012-01-16 17:27:18 +00001860 Builder.CreateCondBr(success, contBB, opBB);
1861 Builder.SetInsertPoint(contBB);
1862 return isPre ? value : input;
1863 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001864
Chris Lattner05dc78c2010-06-26 22:09:34 +00001865 // Store the updated result through the lvalue.
1866 if (LV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00001867 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner05dc78c2010-06-26 22:09:34 +00001868 else
John McCall55e1fbc2011-06-25 02:11:03 +00001869 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001870
Chris Lattner05dc78c2010-06-26 22:09:34 +00001871 // If this is a postinc, return the value read from memory, otherwise use the
1872 // updated value.
John McCalle3dc1702011-02-15 09:22:45 +00001873 return isPre ? value : input;
Chris Lattner05dc78c2010-06-26 22:09:34 +00001874}
1875
1876
1877
Chris Lattner2da04b32007-08-24 05:35:26 +00001878Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001879 TestAndClearIgnoreResultAssign();
Chris Lattner0bf27622010-06-26 21:48:21 +00001880 // Emit unary minus with EmitSub so we handle overflow cases etc.
1881 BinOpInfo BinOp;
Chris Lattnerc1028f62010-06-28 17:12:37 +00001882 BinOp.RHS = Visit(E->getSubExpr());
Craig Toppera97d7e72013-07-26 06:16:11 +00001883
Chris Lattnerc1028f62010-06-28 17:12:37 +00001884 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
1885 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001886 else
Chris Lattnerc1028f62010-06-28 17:12:37 +00001887 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner0bf27622010-06-26 21:48:21 +00001888 BinOp.Ty = E->getType();
John McCalle3027922010-08-25 11:45:40 +00001889 BinOp.Opcode = BO_Sub;
Benjamin Kramerb15b97e2012-10-03 20:58:04 +00001890 BinOp.FPContractable = false;
Chris Lattner0bf27622010-06-26 21:48:21 +00001891 BinOp.E = E;
1892 return EmitSub(BinOp);
Chris Lattner2da04b32007-08-24 05:35:26 +00001893}
1894
1895Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001896 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00001897 Value *Op = Visit(E->getSubExpr());
1898 return Builder.CreateNot(Op, "neg");
1899}
1900
1901Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00001902 // Perform vector logical not on comparison with zero vector.
1903 if (E->getType()->isExtVectorType()) {
1904 Value *Oper = Visit(E->getSubExpr());
1905 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00001906 Value *Result;
1907 if (Oper->getType()->isFPOrFPVectorTy())
1908 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
1909 else
1910 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
Tanya Lattner20248222012-01-16 21:02:28 +00001911 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
1912 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001913
Chris Lattner2da04b32007-08-24 05:35:26 +00001914 // Compare operand to zero.
1915 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00001916
Chris Lattner2da04b32007-08-24 05:35:26 +00001917 // Invert value.
1918 // TODO: Could dynamically modify easy computations here. For example, if
1919 // the operand is an icmp ne, turn into icmp eq.
1920 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stump4a3999f2009-09-09 13:00:44 +00001921
Anders Carlsson775640d2009-05-19 18:44:53 +00001922 // ZExt result to the expr type.
1923 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00001924}
1925
Eli Friedmand7c72322010-08-05 09:58:49 +00001926Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
1927 // Try folding the offsetof to a constant.
Richard Smith5fab0c92011-12-28 19:48:30 +00001928 llvm::APSInt Value;
1929 if (E->EvaluateAsInt(Value, CGF.getContext()))
1930 return Builder.getInt(Value);
Eli Friedmand7c72322010-08-05 09:58:49 +00001931
1932 // Loop over the components of the offsetof to compute the value.
1933 unsigned n = E->getNumComponents();
Chris Lattner2192fe52011-07-18 04:24:23 +00001934 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedmand7c72322010-08-05 09:58:49 +00001935 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
1936 QualType CurrentType = E->getTypeSourceInfo()->getType();
1937 for (unsigned i = 0; i != n; ++i) {
1938 OffsetOfExpr::OffsetOfNode ON = E->getComponent(i);
Craig Topper8a13c412014-05-21 05:09:00 +00001939 llvm::Value *Offset = nullptr;
Eli Friedmand7c72322010-08-05 09:58:49 +00001940 switch (ON.getKind()) {
1941 case OffsetOfExpr::OffsetOfNode::Array: {
1942 // Compute the index
1943 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
1944 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001945 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedmand7c72322010-08-05 09:58:49 +00001946 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
1947
1948 // Save the element type
1949 CurrentType =
1950 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
1951
1952 // Compute the element size
1953 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
1954 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
1955
1956 // Multiply out to compute the result
1957 Offset = Builder.CreateMul(Idx, ElemSize);
1958 break;
1959 }
1960
1961 case OffsetOfExpr::OffsetOfNode::Field: {
1962 FieldDecl *MemberDecl = ON.getField();
1963 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1964 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1965
1966 // Compute the index of the field in its parent.
1967 unsigned i = 0;
1968 // FIXME: It would be nice if we didn't have to loop here!
1969 for (RecordDecl::field_iterator Field = RD->field_begin(),
1970 FieldEnd = RD->field_end();
David Blaikie2d7c57e2012-04-30 02:36:29 +00001971 Field != FieldEnd; ++Field, ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00001972 if (*Field == MemberDecl)
Eli Friedmand7c72322010-08-05 09:58:49 +00001973 break;
1974 }
1975 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
1976
1977 // Compute the offset to the field
1978 int64_t OffsetInt = RL.getFieldOffset(i) /
1979 CGF.getContext().getCharWidth();
1980 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
1981
1982 // Save the element type.
1983 CurrentType = MemberDecl->getType();
1984 break;
1985 }
Eli Friedman165301d2010-08-06 16:37:05 +00001986
Eli Friedmand7c72322010-08-05 09:58:49 +00001987 case OffsetOfExpr::OffsetOfNode::Identifier:
Eli Friedmane83d2b762010-08-06 01:17:25 +00001988 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman165301d2010-08-06 16:37:05 +00001989
Eli Friedmand7c72322010-08-05 09:58:49 +00001990 case OffsetOfExpr::OffsetOfNode::Base: {
1991 if (ON.getBase()->isVirtual()) {
1992 CGF.ErrorUnsupported(E, "virtual base in offsetof");
1993 continue;
1994 }
1995
1996 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
1997 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
1998
1999 // Save the element type.
2000 CurrentType = ON.getBase()->getType();
Craig Toppera97d7e72013-07-26 06:16:11 +00002001
Eli Friedmand7c72322010-08-05 09:58:49 +00002002 // Compute the offset to the base.
2003 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2004 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002005 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2006 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedmand7c72322010-08-05 09:58:49 +00002007 break;
2008 }
2009 }
2010 Result = Builder.CreateAdd(Result, Offset);
2011 }
2012 return Result;
Douglas Gregor882211c2010-04-28 22:16:22 +00002013}
2014
Peter Collingbournee190dee2011-03-11 19:24:49 +00002015/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl6f282892008-11-11 17:56:53 +00002016/// argument of the sizeof expression as an integer.
2017Value *
Peter Collingbournee190dee2011-03-11 19:24:49 +00002018ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2019 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl6f282892008-11-11 17:56:53 +00002020 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002021 if (E->getKind() == UETT_SizeOf) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002022 if (const VariableArrayType *VAT =
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002023 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2024 if (E->isArgumentType()) {
2025 // sizeof(type) - make sure to emit the VLA size.
John McCall23c29fe2011-06-24 21:55:10 +00002026 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman3253e182009-04-20 03:21:44 +00002027 } else {
2028 // C99 6.5.3.4p2: If the argument is an expression of type
2029 // VLA, it is evaluated.
John McCalla2342eb2010-12-05 02:00:02 +00002030 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002031 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002032
John McCall23c29fe2011-06-24 21:55:10 +00002033 QualType eltType;
2034 llvm::Value *numElts;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002035 std::tie(numElts, eltType) = CGF.getVLASize(VAT);
John McCall23c29fe2011-06-24 21:55:10 +00002036
2037 llvm::Value *size = numElts;
2038
2039 // Scale the number of non-VLA elements by the non-VLA element size.
2040 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(eltType);
2041 if (!eltSize.isOne())
2042 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), numElts);
2043
2044 return size;
Anders Carlsson76dbc042008-12-21 03:33:21 +00002045 }
Alexey Bataev00396512015-07-02 03:40:19 +00002046 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2047 auto Alignment =
2048 CGF.getContext()
2049 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2050 E->getTypeOfArgument()->getPointeeType()))
2051 .getQuantity();
2052 return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
Anders Carlsson30032882008-12-12 07:38:43 +00002053 }
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002054
Mike Stump4a3999f2009-09-09 13:00:44 +00002055 // If this isn't sizeof(vla), the result must be constant; use the constant
2056 // folding logic so we don't have to duplicate it here.
Richard Smith5fab0c92011-12-28 19:48:30 +00002057 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner2da04b32007-08-24 05:35:26 +00002058}
2059
Chris Lattner9f0ad962007-08-24 21:20:17 +00002060Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2061 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002062 if (Op->getType()->isAnyComplexType()) {
2063 // If it's an l-value, load through the appropriate subobject l-value.
2064 // Note that we have to ask E because Op might be an l-value that
2065 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002066 if (E->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002067 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2068 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002069
2070 // Otherwise, calculate and project.
2071 return CGF.EmitComplexExpr(Op, false, true).first;
2072 }
2073
Chris Lattner9f0ad962007-08-24 21:20:17 +00002074 return Visit(Op);
2075}
John McCall07bb1962010-11-16 10:08:07 +00002076
Chris Lattner9f0ad962007-08-24 21:20:17 +00002077Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2078 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002079 if (Op->getType()->isAnyComplexType()) {
2080 // If it's an l-value, load through the appropriate subobject l-value.
2081 // Note that we have to ask E because Op might be an l-value that
2082 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002083 if (Op->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002084 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2085 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002086
2087 // Otherwise, calculate and project.
2088 return CGF.EmitComplexExpr(Op, true, false).second;
2089 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002090
Mike Stumpdf0fe272009-05-29 15:46:01 +00002091 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2092 // effects are evaluated, but not the actual value.
Richard Smith0b6b8e42012-02-18 20:53:32 +00002093 if (Op->isGLValue())
2094 CGF.EmitLValue(Op);
2095 else
2096 CGF.EmitScalarExpr(Op, true);
Owen Anderson0b75f232009-07-31 20:28:54 +00002097 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner9f0ad962007-08-24 21:20:17 +00002098}
2099
Chris Lattner2da04b32007-08-24 05:35:26 +00002100//===----------------------------------------------------------------------===//
2101// Binary Operators
2102//===----------------------------------------------------------------------===//
2103
2104BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002105 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00002106 BinOpInfo Result;
2107 Result.LHS = Visit(E->getLHS());
2108 Result.RHS = Visit(E->getRHS());
Chris Lattner3d966d62007-08-24 21:00:35 +00002109 Result.Ty = E->getType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002110 Result.Opcode = E->getOpcode();
Lang Hames5de91cc2012-10-02 04:45:10 +00002111 Result.FPContractable = E->isFPContractable();
Chris Lattner2da04b32007-08-24 05:35:26 +00002112 Result.E = E;
2113 return Result;
2114}
2115
Douglas Gregor914af212010-04-23 04:16:32 +00002116LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2117 const CompoundAssignOperator *E,
2118 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002119 Value *&Result) {
Benjamin Kramerd20ef752009-12-25 15:43:36 +00002120 QualType LHSTy = E->getLHS()->getType();
Chris Lattner3d966d62007-08-24 21:00:35 +00002121 BinOpInfo OpInfo;
Craig Toppera97d7e72013-07-26 06:16:11 +00002122
Eli Friedmanf0450072013-06-12 01:40:06 +00002123 if (E->getComputationResultType()->isAnyComplexType())
Richard Smith527473d2015-02-12 21:23:20 +00002124 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
Craig Toppera97d7e72013-07-26 06:16:11 +00002125
Mike Stumpc63428b2009-05-22 19:07:20 +00002126 // Emit the RHS first. __block variables need to have the rhs evaluated
2127 // first, plus this should improve codegen a little.
2128 OpInfo.RHS = Visit(E->getRHS());
2129 OpInfo.Ty = E->getComputationResultType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002130 OpInfo.Opcode = E->getOpcode();
Benjamin Kramerb15b97e2012-10-03 20:58:04 +00002131 OpInfo.FPContractable = false;
Mike Stumpc63428b2009-05-22 19:07:20 +00002132 OpInfo.E = E;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00002133 // Load/convert the LHS.
Richard Smith4d1458e2012-09-08 02:08:36 +00002134 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
David Chisnallfa35df62012-01-16 17:27:18 +00002135
Craig Topper8a13c412014-05-21 05:09:00 +00002136 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00002137 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2138 QualType type = atomicTy->getValueType();
2139 if (!type->isBooleanType() && type->isIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002140 !(type->isUnsignedIntegerType() &&
2141 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2142 CGF.getLangOpts().getSignedOverflowBehavior() !=
2143 LangOptions::SOB_Trapping) {
David Chisnallef78c302013-03-03 16:02:42 +00002144 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2145 switch (OpInfo.Opcode) {
2146 // We don't have atomicrmw operands for *, %, /, <<, >>
2147 case BO_MulAssign: case BO_DivAssign:
2148 case BO_RemAssign:
2149 case BO_ShlAssign:
2150 case BO_ShrAssign:
2151 break;
2152 case BO_AddAssign:
2153 aop = llvm::AtomicRMWInst::Add;
2154 break;
2155 case BO_SubAssign:
2156 aop = llvm::AtomicRMWInst::Sub;
2157 break;
2158 case BO_AndAssign:
2159 aop = llvm::AtomicRMWInst::And;
2160 break;
2161 case BO_XorAssign:
2162 aop = llvm::AtomicRMWInst::Xor;
2163 break;
2164 case BO_OrAssign:
2165 aop = llvm::AtomicRMWInst::Or;
2166 break;
2167 default:
2168 llvm_unreachable("Invalid compound assignment type");
2169 }
2170 if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
2171 llvm::Value *amt = CGF.EmitToMemory(EmitScalarConversion(OpInfo.RHS,
2172 E->getRHS()->getType(), LHSTy), LHSTy);
2173 Builder.CreateAtomicRMW(aop, LHSLV.getAddress(), amt,
2174 llvm::SequentiallyConsistent);
2175 return LHSLV;
2176 }
2177 }
David Chisnallfa35df62012-01-16 17:27:18 +00002178 // FIXME: For floating point types, we should be saving and restoring the
2179 // floating point environment in the loop.
2180 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2181 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002182 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002183 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
David Chisnallfa35df62012-01-16 17:27:18 +00002184 Builder.CreateBr(opBB);
2185 Builder.SetInsertPoint(opBB);
2186 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2187 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002188 OpInfo.LHS = atomicPHI;
2189 }
David Chisnallef78c302013-03-03 16:02:42 +00002190 else
Nick Lewycky2d84e842013-10-02 02:29:49 +00002191 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002192
2193 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
2194 E->getComputationLHSType());
2195
Chris Lattner3d966d62007-08-24 21:00:35 +00002196 // Expand the binary operator.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002197 Result = (this->*Func)(OpInfo);
Craig Toppera97d7e72013-07-26 06:16:11 +00002198
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +00002199 // Convert the result back to the LHS type.
Eli Friedman8b7b1b12009-03-28 01:22:36 +00002200 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy);
David Chisnallfa35df62012-01-16 17:27:18 +00002201
2202 if (atomicPHI) {
2203 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2204 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00002205 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00002206 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
2207 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
2208 llvm::Value *success = Pair.second;
David Chisnallfa35df62012-01-16 17:27:18 +00002209 atomicPHI->addIncoming(old, opBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002210 Builder.CreateCondBr(success, contBB, opBB);
2211 Builder.SetInsertPoint(contBB);
2212 return LHSLV;
2213 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002214
Mike Stump4a3999f2009-09-09 13:00:44 +00002215 // Store the result value into the LHS lvalue. Bit-fields are handled
2216 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2217 // 'An assignment expression has the value of the left operand after the
2218 // assignment...'.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002219 if (LHSLV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00002220 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002221 else
John McCall55e1fbc2011-06-25 02:11:03 +00002222 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002223
Douglas Gregor914af212010-04-23 04:16:32 +00002224 return LHSLV;
2225}
2226
2227Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2228 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2229 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002230 Value *RHS;
2231 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2232
2233 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00002234 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00002235 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002236
John McCall07bb1962010-11-16 10:08:07 +00002237 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00002238 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00002239 return RHS;
2240
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002241 // If the lvalue is non-volatile, return the computed value of the assignment.
2242 if (!LHS.isVolatileQualified())
2243 return RHS;
2244
2245 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002246 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner3d966d62007-08-24 21:00:35 +00002247}
2248
Chris Lattner8ee6a412010-09-11 21:47:09 +00002249void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith4d1458e2012-09-08 02:08:36 +00002250 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002251 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
Chris Lattner8ee6a412010-09-11 21:47:09 +00002252
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002253 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002254 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2255 SanitizerKind::IntegerDivideByZero));
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002256 }
Richard Smithc86a1142012-11-06 02:30:30 +00002257
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002258 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
Richard Smithc86a1142012-11-06 02:30:30 +00002259 Ops.Ty->hasSignedIntegerRepresentation()) {
2260 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2261
Chris Lattner8ee6a412010-09-11 21:47:09 +00002262 llvm::Value *IntMin =
Chris Lattner2531eb42011-04-19 22:55:03 +00002263 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner8ee6a412010-09-11 21:47:09 +00002264 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2265
Richard Smith4d1458e2012-09-08 02:08:36 +00002266 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2267 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002268 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2269 Checks.push_back(
2270 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
Chris Lattner8ee6a412010-09-11 21:47:09 +00002271 }
Richard Smithc86a1142012-11-06 02:30:30 +00002272
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002273 if (Checks.size() > 0)
2274 EmitBinOpCheck(Checks, Ops);
Chris Lattner8ee6a412010-09-11 21:47:09 +00002275}
Chris Lattner3d966d62007-08-24 21:00:35 +00002276
Chris Lattner2da04b32007-08-24 05:35:26 +00002277Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002278 {
2279 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002280 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2281 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Alexey Samsonov24cad992014-07-17 18:46:27 +00002282 Ops.Ty->isIntegerType()) {
2283 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2284 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002285 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
Alexey Samsonov24cad992014-07-17 18:46:27 +00002286 Ops.Ty->isRealFloatingType()) {
2287 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002288 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
2289 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
2290 Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00002291 }
Chris Lattner8ee6a412010-09-11 21:47:09 +00002292 }
Will Dietz1897cb32012-11-27 15:01:55 +00002293
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00002294 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
2295 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Richard Smith9c6890a2012-11-01 22:30:59 +00002296 if (CGF.getLangOpts().OpenCL) {
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00002297 // OpenCL 1.1 7.4: minimum accuracy of single precision / is 2.5ulp
2298 llvm::Type *ValTy = Val->getType();
2299 if (ValTy->isFloatTy() ||
2300 (isa<llvm::VectorType>(ValTy) &&
2301 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sandse81111c2012-04-10 08:23:07 +00002302 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00002303 }
2304 return Val;
2305 }
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002306 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00002307 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
2308 else
2309 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
2310}
2311
2312Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
2313 // Rem in C can't be a floating point type: C99 6.5.5p2.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002314 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002315 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattner8ee6a412010-09-11 21:47:09 +00002316 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2317
Will Dietz1897cb32012-11-27 15:01:55 +00002318 if (Ops.Ty->isIntegerType())
Chris Lattner8ee6a412010-09-11 21:47:09 +00002319 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
2320 }
2321
Eli Friedman493c34a2011-04-10 04:44:11 +00002322 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00002323 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
2324 else
2325 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
2326}
2327
Mike Stump0c61b732009-04-01 20:28:16 +00002328Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
2329 unsigned IID;
2330 unsigned OpID = 0;
Mike Stump40968592009-04-02 01:03:55 +00002331
Will Dietz1897cb32012-11-27 15:01:55 +00002332 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002333 switch (Ops.Opcode) {
John McCalle3027922010-08-25 11:45:40 +00002334 case BO_Add:
2335 case BO_AddAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00002336 OpID = 1;
Will Dietz1897cb32012-11-27 15:01:55 +00002337 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
2338 llvm::Intrinsic::uadd_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00002339 break;
John McCalle3027922010-08-25 11:45:40 +00002340 case BO_Sub:
2341 case BO_SubAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00002342 OpID = 2;
Will Dietz1897cb32012-11-27 15:01:55 +00002343 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
2344 llvm::Intrinsic::usub_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00002345 break;
John McCalle3027922010-08-25 11:45:40 +00002346 case BO_Mul:
2347 case BO_MulAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00002348 OpID = 3;
Will Dietz1897cb32012-11-27 15:01:55 +00002349 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
2350 llvm::Intrinsic::umul_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00002351 break;
2352 default:
David Blaikie83d382b2011-09-23 05:06:16 +00002353 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump0c61b732009-04-01 20:28:16 +00002354 }
Mike Stumpd3e38852009-04-02 18:15:54 +00002355 OpID <<= 1;
Will Dietz1897cb32012-11-27 15:01:55 +00002356 if (isSigned)
2357 OpID |= 1;
Mike Stumpd3e38852009-04-02 18:15:54 +00002358
Chris Lattnera5f58b02011-07-09 17:41:47 +00002359 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump0c61b732009-04-01 20:28:16 +00002360
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00002361 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump0c61b732009-04-01 20:28:16 +00002362
David Blaikie43f9bb72015-05-18 22:14:03 +00002363 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
Mike Stump0c61b732009-04-01 20:28:16 +00002364 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
2365 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
2366
Richard Smith4d1458e2012-09-08 02:08:36 +00002367 // Handle overflow with llvm.trap if no custom handler has been specified.
2368 const std::string *handlerName =
Richard Smith9c6890a2012-11-01 22:30:59 +00002369 &CGF.getLangOpts().OverflowHandler;
Richard Smith4d1458e2012-09-08 02:08:36 +00002370 if (handlerName->empty()) {
Richard Smithb1b0ab42012-11-05 22:21:05 +00002371 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
Richard Smithde670682012-11-01 22:15:34 +00002372 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002373 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002374 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002375 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002376 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002377 : SanitizerKind::UnsignedIntegerOverflow;
2378 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00002379 } else
Chad Rosierae229d52013-01-29 23:31:22 +00002380 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
Richard Smith4d1458e2012-09-08 02:08:36 +00002381 return result;
2382 }
2383
Mike Stump0c61b732009-04-01 20:28:16 +00002384 // Branch in case of overflow.
David Chisnalldd84ef12010-09-17 18:29:54 +00002385 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Bill Wendlinge367f382011-07-07 21:13:10 +00002386 llvm::Function::iterator insertPt = initialBB;
2387 llvm::BasicBlock *continueBB = CGF.createBasicBlock("nooverflow", CGF.CurFn,
Benjamin Kramer167e9992014-03-02 12:20:24 +00002388 std::next(insertPt));
Chris Lattner8139c982010-08-07 00:20:46 +00002389 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump0c61b732009-04-01 20:28:16 +00002390
2391 Builder.CreateCondBr(overflow, overflowBB, continueBB);
2392
David Chisnalldd84ef12010-09-17 18:29:54 +00002393 // If an overflow handler is set, then we want to call it and then use its
2394 // result, if it returns.
2395 Builder.SetInsertPoint(overflowBB);
2396
2397 // Get the overflow handler.
Chris Lattnerece04092012-02-07 00:39:47 +00002398 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattnera5f58b02011-07-09 17:41:47 +00002399 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnalldd84ef12010-09-17 18:29:54 +00002400 llvm::FunctionType *handlerTy =
2401 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
2402 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
2403
2404 // Sign extend the args to 64-bit, so that we can use the same handler for
2405 // all types of overflow.
2406 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
2407 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
2408
2409 // Call the handler with the two arguments, the operation, and the size of
2410 // the result.
John McCall882987f2013-02-28 19:01:20 +00002411 llvm::Value *handlerArgs[] = {
2412 lhs,
2413 rhs,
2414 Builder.getInt8(OpID),
2415 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
2416 };
2417 llvm::Value *handlerResult =
2418 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
David Chisnalldd84ef12010-09-17 18:29:54 +00002419
2420 // Truncate the result back to the desired size.
2421 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
2422 Builder.CreateBr(continueBB);
2423
Mike Stump0c61b732009-04-01 20:28:16 +00002424 Builder.SetInsertPoint(continueBB);
Jay Foad20c0f022011-03-30 11:28:58 +00002425 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnalldd84ef12010-09-17 18:29:54 +00002426 phi->addIncoming(result, initialBB);
2427 phi->addIncoming(handlerResult, overflowBB);
2428
2429 return phi;
Mike Stump0c61b732009-04-01 20:28:16 +00002430}
Chris Lattner2da04b32007-08-24 05:35:26 +00002431
John McCall77527a82011-06-25 01:32:37 +00002432/// Emit pointer + index arithmetic.
2433static Value *emitPointerArithmetic(CodeGenFunction &CGF,
2434 const BinOpInfo &op,
2435 bool isSubtraction) {
2436 // Must have binary (not unary) expr here. Unary pointer
2437 // increment/decrement doesn't use this path.
2438 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
Craig Toppera97d7e72013-07-26 06:16:11 +00002439
John McCall77527a82011-06-25 01:32:37 +00002440 Value *pointer = op.LHS;
2441 Expr *pointerOperand = expr->getLHS();
2442 Value *index = op.RHS;
2443 Expr *indexOperand = expr->getRHS();
2444
2445 // In a subtraction, the LHS is always the pointer.
2446 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
2447 std::swap(pointer, index);
2448 std::swap(pointerOperand, indexOperand);
2449 }
2450
2451 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
2452 if (width != CGF.PointerWidthInBits) {
2453 // Zero-extend or sign-extend the pointer value according to
2454 // whether the index is signed or not.
2455 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
2456 index = CGF.Builder.CreateIntCast(index, CGF.PtrDiffTy, isSigned,
2457 "idx.ext");
2458 }
2459
2460 // If this is subtraction, negate the index.
2461 if (isSubtraction)
2462 index = CGF.Builder.CreateNeg(index, "idx.neg");
2463
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002464 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00002465 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
2466 /*Accessed*/ false);
2467
John McCall77527a82011-06-25 01:32:37 +00002468 const PointerType *pointerType
2469 = pointerOperand->getType()->getAs<PointerType>();
2470 if (!pointerType) {
2471 QualType objectType = pointerOperand->getType()
2472 ->castAs<ObjCObjectPointerType>()
2473 ->getPointeeType();
2474 llvm::Value *objectSize
2475 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
2476
2477 index = CGF.Builder.CreateMul(index, objectSize);
2478
2479 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2480 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2481 return CGF.Builder.CreateBitCast(result, pointer->getType());
2482 }
2483
2484 QualType elementType = pointerType->getPointeeType();
2485 if (const VariableArrayType *vla
2486 = CGF.getContext().getAsVariableArrayType(elementType)) {
2487 // The element count here is the total number of non-VLA elements.
2488 llvm::Value *numElements = CGF.getVLASize(vla).first;
2489
2490 // Effectively, the multiply by the VLA size is part of the GEP.
2491 // GEP indexes are signed, and scaling an index isn't permitted to
2492 // signed-overflow, so we use the same semantics for our explicit
2493 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002494 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00002495 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
2496 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2497 } else {
2498 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
2499 pointer = CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner51924e512010-06-26 21:25:03 +00002500 }
John McCall77527a82011-06-25 01:32:37 +00002501 return pointer;
Mike Stump4a3999f2009-09-09 13:00:44 +00002502 }
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002503
Mike Stump4a3999f2009-09-09 13:00:44 +00002504 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
2505 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
2506 // future proof.
John McCall77527a82011-06-25 01:32:37 +00002507 if (elementType->isVoidType() || elementType->isFunctionType()) {
2508 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
2509 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
2510 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stump4a3999f2009-09-09 13:00:44 +00002511 }
2512
David Blaikiebbafb8a2012-03-11 07:00:24 +00002513 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall77527a82011-06-25 01:32:37 +00002514 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
2515
2516 return CGF.Builder.CreateInBoundsGEP(pointer, index, "add.ptr");
Chris Lattner2da04b32007-08-24 05:35:26 +00002517}
2518
Lang Hames5de91cc2012-10-02 04:45:10 +00002519// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
2520// Addend. Use negMul and negAdd to negate the first operand of the Mul or
2521// the add operand respectively. This allows fmuladd to represent a*b-c, or
2522// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
2523// efficient operations.
2524static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
2525 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2526 bool negMul, bool negAdd) {
2527 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
Craig Toppera97d7e72013-07-26 06:16:11 +00002528
Lang Hames5de91cc2012-10-02 04:45:10 +00002529 Value *MulOp0 = MulOp->getOperand(0);
2530 Value *MulOp1 = MulOp->getOperand(1);
2531 if (negMul) {
2532 MulOp0 =
2533 Builder.CreateFSub(
2534 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
2535 "neg");
2536 } else if (negAdd) {
2537 Addend =
2538 Builder.CreateFSub(
2539 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
2540 "neg");
2541 }
2542
David Blaikie43f9bb72015-05-18 22:14:03 +00002543 Value *FMulAdd = Builder.CreateCall(
Lang Hames5de91cc2012-10-02 04:45:10 +00002544 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
David Blaikie43f9bb72015-05-18 22:14:03 +00002545 {MulOp0, MulOp1, Addend});
Lang Hames5de91cc2012-10-02 04:45:10 +00002546 MulOp->eraseFromParent();
2547
2548 return FMulAdd;
2549}
2550
2551// Check whether it would be legal to emit an fmuladd intrinsic call to
2552// represent op and if so, build the fmuladd.
2553//
2554// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
2555// Does NOT check the type of the operation - it's assumed that this function
2556// will be called from contexts where it's known that the type is contractable.
Craig Toppera97d7e72013-07-26 06:16:11 +00002557static Value* tryEmitFMulAdd(const BinOpInfo &op,
Lang Hames5de91cc2012-10-02 04:45:10 +00002558 const CodeGenFunction &CGF, CGBuilderTy &Builder,
2559 bool isSub=false) {
2560
2561 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
2562 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
2563 "Only fadd/fsub can be the root of an fmuladd.");
2564
2565 // Check whether this op is marked as fusable.
2566 if (!op.FPContractable)
Craig Topper8a13c412014-05-21 05:09:00 +00002567 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00002568
2569 // Check whether -ffp-contract=on. (If -ffp-contract=off/fast, fusing is
2570 // either disabled, or handled entirely by the LLVM backend).
Lang Hames65992f42012-11-15 07:51:26 +00002571 if (CGF.CGM.getCodeGenOpts().getFPContractMode() != CodeGenOptions::FPC_On)
Craig Topper8a13c412014-05-21 05:09:00 +00002572 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00002573
2574 // We have a potentially fusable op. Look for a mul on one of the operands.
2575 if (llvm::BinaryOperator* LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
2576 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hames4c8559e2012-10-04 03:23:25 +00002577 assert(LHSBinOp->getNumUses() == 0 &&
2578 "Operations with multiple uses shouldn't be contracted.");
Lang Hames5de91cc2012-10-02 04:45:10 +00002579 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
2580 }
2581 } else if (llvm::BinaryOperator* RHSBinOp =
2582 dyn_cast<llvm::BinaryOperator>(op.RHS)) {
2583 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul) {
Lang Hames4c8559e2012-10-04 03:23:25 +00002584 assert(RHSBinOp->getNumUses() == 0 &&
2585 "Operations with multiple uses shouldn't be contracted.");
Lang Hames5de91cc2012-10-02 04:45:10 +00002586 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
2587 }
2588 }
2589
Craig Topper8a13c412014-05-21 05:09:00 +00002590 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00002591}
2592
John McCall77527a82011-06-25 01:32:37 +00002593Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
2594 if (op.LHS->getType()->isPointerTy() ||
2595 op.RHS->getType()->isPointerTy())
2596 return emitPointerArithmetic(CGF, op, /*subtraction*/ false);
2597
2598 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002599 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
John McCall77527a82011-06-25 01:32:37 +00002600 case LangOptions::SOB_Defined:
2601 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith3e056de2012-08-25 00:32:28 +00002602 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002603 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00002604 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
2605 // Fall through.
John McCall77527a82011-06-25 01:32:37 +00002606 case LangOptions::SOB_Trapping:
2607 return EmitOverflowCheckedBinOp(op);
2608 }
2609 }
Will Dietz1897cb32012-11-27 15:01:55 +00002610
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002611 if (op.Ty->isUnsignedIntegerType() &&
2612 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietz1897cb32012-11-27 15:01:55 +00002613 return EmitOverflowCheckedBinOp(op);
2614
Lang Hames5de91cc2012-10-02 04:45:10 +00002615 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2616 // Try to form an fmuladd.
2617 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
2618 return FMulAdd;
2619
John McCall77527a82011-06-25 01:32:37 +00002620 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
Lang Hames5de91cc2012-10-02 04:45:10 +00002621 }
John McCall77527a82011-06-25 01:32:37 +00002622
2623 return Builder.CreateAdd(op.LHS, op.RHS, "add");
2624}
2625
2626Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
2627 // The LHS is always a pointer if either side is.
2628 if (!op.LHS->getType()->isPointerTy()) {
2629 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00002630 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +00002631 case LangOptions::SOB_Defined:
John McCall77527a82011-06-25 01:32:37 +00002632 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith3e056de2012-08-25 00:32:28 +00002633 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002634 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00002635 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
2636 // Fall through.
Chris Lattner51924e512010-06-26 21:25:03 +00002637 case LangOptions::SOB_Trapping:
John McCall77527a82011-06-25 01:32:37 +00002638 return EmitOverflowCheckedBinOp(op);
Chris Lattner51924e512010-06-26 21:25:03 +00002639 }
2640 }
Will Dietz1897cb32012-11-27 15:01:55 +00002641
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002642 if (op.Ty->isUnsignedIntegerType() &&
2643 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow))
Will Dietz1897cb32012-11-27 15:01:55 +00002644 return EmitOverflowCheckedBinOp(op);
2645
Lang Hames5de91cc2012-10-02 04:45:10 +00002646 if (op.LHS->getType()->isFPOrFPVectorTy()) {
2647 // Try to form an fmuladd.
2648 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
2649 return FMulAdd;
John McCall77527a82011-06-25 01:32:37 +00002650 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
Lang Hames5de91cc2012-10-02 04:45:10 +00002651 }
Chris Lattner5902e7b2010-03-29 17:28:16 +00002652
John McCall77527a82011-06-25 01:32:37 +00002653 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump0c61b732009-04-01 20:28:16 +00002654 }
Chris Lattner3d966d62007-08-24 21:00:35 +00002655
John McCall77527a82011-06-25 01:32:37 +00002656 // If the RHS is not a pointer, then we have normal pointer
2657 // arithmetic.
2658 if (!op.RHS->getType()->isPointerTy())
2659 return emitPointerArithmetic(CGF, op, /*subtraction*/ true);
Eli Friedmane381f7e2009-03-28 02:45:41 +00002660
John McCall77527a82011-06-25 01:32:37 +00002661 // Otherwise, this is a pointer subtraction.
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00002662
John McCall77527a82011-06-25 01:32:37 +00002663 // Do the raw subtraction part.
2664 llvm::Value *LHS
2665 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
2666 llvm::Value *RHS
2667 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
2668 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00002669
John McCall77527a82011-06-25 01:32:37 +00002670 // Okay, figure out the element size.
2671 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
2672 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00002673
Craig Topper8a13c412014-05-21 05:09:00 +00002674 llvm::Value *divisor = nullptr;
John McCall77527a82011-06-25 01:32:37 +00002675
2676 // For a variable-length array, this is going to be non-constant.
2677 if (const VariableArrayType *vla
2678 = CGF.getContext().getAsVariableArrayType(elementType)) {
2679 llvm::Value *numElements;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002680 std::tie(numElements, elementType) = CGF.getVLASize(vla);
John McCall77527a82011-06-25 01:32:37 +00002681
2682 divisor = numElements;
2683
2684 // Scale the number of non-VLA elements by the non-VLA element size.
2685 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
2686 if (!eltSize.isOne())
2687 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
2688
2689 // For everything elese, we can just compute it, safe in the
2690 // assumption that Sema won't let anything through that we can't
2691 // safely compute the size of.
2692 } else {
2693 CharUnits elementSize;
2694 // Handle GCC extension for pointer arithmetic on void* and
2695 // function pointer types.
2696 if (elementType->isVoidType() || elementType->isFunctionType())
2697 elementSize = CharUnits::One();
2698 else
2699 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
2700
2701 // Don't even emit the divide for element size of 1.
2702 if (elementSize.isOne())
2703 return diffInChars;
2704
2705 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner2da04b32007-08-24 05:35:26 +00002706 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002707
Chris Lattner2e72da942011-03-01 00:03:48 +00002708 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
2709 // pointer difference in C is only defined in the case where both operands
2710 // are pointing to elements of an array.
John McCall77527a82011-06-25 01:32:37 +00002711 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner2da04b32007-08-24 05:35:26 +00002712}
2713
David Tweed042e0882013-01-07 16:43:27 +00002714Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
David Tweed9fb566c2013-01-10 09:11:33 +00002715 llvm::IntegerType *Ty;
2716 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
2717 Ty = cast<llvm::IntegerType>(VT->getElementType());
2718 else
2719 Ty = cast<llvm::IntegerType>(LHS->getType());
2720 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
David Tweed042e0882013-01-07 16:43:27 +00002721}
2722
Chris Lattner2da04b32007-08-24 05:35:26 +00002723Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
2724 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2725 // RHS to the same size as the LHS.
2726 Value *RHS = Ops.RHS;
2727 if (Ops.LHS->getType() != RHS->getType())
2728 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00002729
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002730 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
2731 Ops.Ty->hasSignedIntegerRepresentation();
2732 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
2733 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2734 if (CGF.getLangOpts().OpenCL)
2735 RHS =
2736 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
2737 else if ((SanitizeBase || SanitizeExponent) &&
2738 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002739 CodeGenFunction::SanitizerScope SanScope(&CGF);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002740 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
Alexey Samsonov48a9db02015-03-05 21:57:35 +00002741 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, RHS);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002742 llvm::Value *ValidExponent = Builder.CreateICmpULE(RHS, WidthMinusOne);
Richard Smith3e056de2012-08-25 00:32:28 +00002743
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002744 if (SanitizeExponent) {
2745 Checks.push_back(
2746 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
2747 }
2748
2749 if (SanitizeBase) {
2750 // Check whether we are shifting any non-zero bits off the top of the
2751 // integer. We only emit this check if exponent is valid - otherwise
2752 // instructions below will have undefined behavior themselves.
Alexey Samsonov48a9db02015-03-05 21:57:35 +00002753 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
2754 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002755 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
2756 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
2757 CGF.EmitBlock(CheckShiftBase);
Richard Smith3e056de2012-08-25 00:32:28 +00002758 llvm::Value *BitsShiftedOff =
2759 Builder.CreateLShr(Ops.LHS,
2760 Builder.CreateSub(WidthMinusOne, RHS, "shl.zeros",
2761 /*NUW*/true, /*NSW*/true),
2762 "shl.check");
2763 if (CGF.getLangOpts().CPlusPlus) {
2764 // In C99, we are not permitted to shift a 1 bit into the sign bit.
2765 // Under C++11's rules, shifting a 1 bit into the sign bit is
2766 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
2767 // define signed left shifts, so we use the C99 and C++11 rules there).
2768 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
2769 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
2770 }
2771 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002772 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
Alexey Samsonov48a9db02015-03-05 21:57:35 +00002773 CGF.EmitBlock(Cont);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002774 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
2775 BaseCheck->addIncoming(Builder.getTrue(), Orig);
2776 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
2777 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
Richard Smith3e056de2012-08-25 00:32:28 +00002778 }
Will Dietz11d0a9f2013-02-25 22:37:49 +00002779
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002780 assert(!Checks.empty());
2781 EmitBinOpCheck(Checks, Ops);
Mike Stumpba6a0c42009-12-14 21:58:14 +00002782 }
2783
Chris Lattner2da04b32007-08-24 05:35:26 +00002784 return Builder.CreateShl(Ops.LHS, RHS, "shl");
2785}
2786
2787Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
2788 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
2789 // RHS to the same size as the LHS.
2790 Value *RHS = Ops.RHS;
2791 if (Ops.LHS->getType() != RHS->getType())
2792 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00002793
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002794 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2795 if (CGF.getLangOpts().OpenCL)
2796 RHS =
2797 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
2798 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
2799 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002800 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002801 llvm::Value *Valid =
2802 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00002803 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00002804 }
David Tweed042e0882013-01-07 16:43:27 +00002805
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002806 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00002807 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
2808 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
2809}
2810
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002811enum IntrinsicType { VCMPEQ, VCMPGT };
2812// return corresponding comparison intrinsic for given vector type
2813static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
2814 BuiltinType::Kind ElemKind) {
2815 switch (ElemKind) {
David Blaikie83d382b2011-09-23 05:06:16 +00002816 default: llvm_unreachable("unexpected element type");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002817 case BuiltinType::Char_U:
2818 case BuiltinType::UChar:
2819 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2820 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002821 case BuiltinType::Char_S:
2822 case BuiltinType::SChar:
2823 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
2824 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002825 case BuiltinType::UShort:
2826 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2827 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002828 case BuiltinType::Short:
2829 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
2830 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002831 case BuiltinType::UInt:
2832 case BuiltinType::ULong:
2833 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2834 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002835 case BuiltinType::Int:
2836 case BuiltinType::Long:
2837 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
2838 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002839 case BuiltinType::Float:
2840 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
2841 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002842 }
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002843}
2844
Chris Lattner2da04b32007-08-24 05:35:26 +00002845Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,unsigned UICmpOpc,
2846 unsigned SICmpOpc, unsigned FCmpOpc) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002847 TestAndClearIgnoreResultAssign();
Chris Lattner42e6b812007-08-26 16:34:22 +00002848 Value *Result;
Chris Lattner2da04b32007-08-24 05:35:26 +00002849 QualType LHSTy = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00002850 QualType RHSTy = E->getRHS()->getType();
John McCall7a9aac22010-08-23 01:21:21 +00002851 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCalle3027922010-08-25 11:45:40 +00002852 assert(E->getOpcode() == BO_EQ ||
2853 E->getOpcode() == BO_NE);
John McCalla1dee5302010-08-22 10:59:02 +00002854 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
2855 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall7a9aac22010-08-23 01:21:21 +00002856 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCalle3027922010-08-25 11:45:40 +00002857 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Chandler Carruthb29a7432014-10-11 11:03:30 +00002858 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
Chris Lattner2da04b32007-08-24 05:35:26 +00002859 Value *LHS = Visit(E->getLHS());
2860 Value *RHS = Visit(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00002861
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002862 // If AltiVec, the comparison results in a numeric type, so we use
2863 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev93900c72011-03-28 21:00:05 +00002864 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002865 // constants for mapping CR6 register bits to predicate result
2866 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
2867
2868 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
2869
2870 // in several cases vector arguments order will be reversed
2871 Value *FirstVecArg = LHS,
2872 *SecondVecArg = RHS;
2873
2874 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCall424cec92011-01-19 06:33:43 +00002875 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002876 BuiltinType::Kind ElementKind = BTy->getKind();
2877
2878 switch(E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00002879 default: llvm_unreachable("is not a comparison operation");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002880 case BO_EQ:
2881 CR6 = CR6_LT;
2882 ID = GetIntrinsic(VCMPEQ, ElementKind);
2883 break;
2884 case BO_NE:
2885 CR6 = CR6_EQ;
2886 ID = GetIntrinsic(VCMPEQ, ElementKind);
2887 break;
2888 case BO_LT:
2889 CR6 = CR6_LT;
2890 ID = GetIntrinsic(VCMPGT, ElementKind);
2891 std::swap(FirstVecArg, SecondVecArg);
2892 break;
2893 case BO_GT:
2894 CR6 = CR6_LT;
2895 ID = GetIntrinsic(VCMPGT, ElementKind);
2896 break;
2897 case BO_LE:
2898 if (ElementKind == BuiltinType::Float) {
2899 CR6 = CR6_LT;
2900 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2901 std::swap(FirstVecArg, SecondVecArg);
2902 }
2903 else {
2904 CR6 = CR6_EQ;
2905 ID = GetIntrinsic(VCMPGT, ElementKind);
2906 }
2907 break;
2908 case BO_GE:
2909 if (ElementKind == BuiltinType::Float) {
2910 CR6 = CR6_LT;
2911 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
2912 }
2913 else {
2914 CR6 = CR6_EQ;
2915 ID = GetIntrinsic(VCMPGT, ElementKind);
2916 std::swap(FirstVecArg, SecondVecArg);
2917 }
2918 break;
2919 }
2920
Chris Lattner2531eb42011-04-19 22:55:03 +00002921 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002922 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
David Blaikie43f9bb72015-05-18 22:14:03 +00002923 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
Anton Yartsev3f8f2882010-11-18 03:19:30 +00002924 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
2925 }
2926
Duncan Sands998f9d92010-02-15 16:14:01 +00002927 if (LHS->getType()->isFPOrFPVectorTy()) {
Nate Begemanfe79ca22008-07-25 20:16:05 +00002928 Result = Builder.CreateFCmp((llvm::CmpInst::Predicate)FCmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00002929 LHS, RHS, "cmp");
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00002930 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Eli Friedman3c285242008-05-29 15:09:15 +00002931 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)SICmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00002932 LHS, RHS, "cmp");
2933 } else {
Eli Friedman3c285242008-05-29 15:09:15 +00002934 // Unsigned integers and pointers.
2935 Result = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
Chris Lattner2da04b32007-08-24 05:35:26 +00002936 LHS, RHS, "cmp");
2937 }
Chris Lattner2a7deb62009-07-08 01:08:03 +00002938
2939 // If this is a vector comparison, sign extend the result to the appropriate
2940 // vector integer type and return it (don't convert to bool).
2941 if (LHSTy->isVectorType())
2942 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stump4a3999f2009-09-09 13:00:44 +00002943
Chris Lattner2da04b32007-08-24 05:35:26 +00002944 } else {
2945 // Complex Comparison: can only be an equality comparison.
Chandler Carruthb29a7432014-10-11 11:03:30 +00002946 CodeGenFunction::ComplexPairTy LHS, RHS;
2947 QualType CETy;
2948 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
2949 LHS = CGF.EmitComplexExpr(E->getLHS());
2950 CETy = CTy->getElementType();
2951 } else {
2952 LHS.first = Visit(E->getLHS());
2953 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
2954 CETy = LHSTy;
2955 }
2956 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
2957 RHS = CGF.EmitComplexExpr(E->getRHS());
2958 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
2959 CTy->getElementType()) &&
2960 "The element types must always match.");
Chandler Carruth60fdc412014-10-11 11:29:26 +00002961 (void)CTy;
Chandler Carruthb29a7432014-10-11 11:03:30 +00002962 } else {
2963 RHS.first = Visit(E->getRHS());
2964 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
2965 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
2966 "The element types must always match.");
2967 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002968
Chris Lattner42e6b812007-08-26 16:34:22 +00002969 Value *ResultR, *ResultI;
Chris Lattner2da04b32007-08-24 05:35:26 +00002970 if (CETy->isRealFloatingType()) {
2971 ResultR = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2972 LHS.first, RHS.first, "cmp.r");
2973 ResultI = Builder.CreateFCmp((llvm::FCmpInst::Predicate)FCmpOpc,
2974 LHS.second, RHS.second, "cmp.i");
2975 } else {
2976 // Complex comparisons can only be equality comparisons. As such, signed
2977 // and unsigned opcodes are the same.
2978 ResultR = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2979 LHS.first, RHS.first, "cmp.r");
2980 ResultI = Builder.CreateICmp((llvm::ICmpInst::Predicate)UICmpOpc,
2981 LHS.second, RHS.second, "cmp.i");
2982 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002983
John McCalle3027922010-08-25 11:45:40 +00002984 if (E->getOpcode() == BO_EQ) {
Chris Lattner2da04b32007-08-24 05:35:26 +00002985 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
2986 } else {
John McCalle3027922010-08-25 11:45:40 +00002987 assert(E->getOpcode() == BO_NE &&
Chris Lattner2da04b32007-08-24 05:35:26 +00002988 "Complex comparison other than == or != ?");
2989 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
2990 }
2991 }
Nuno Lopesa0abe622009-01-11 23:22:37 +00002992
2993 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType());
Chris Lattner2da04b32007-08-24 05:35:26 +00002994}
2995
2996Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002997 bool Ignore = TestAndClearIgnoreResultAssign();
2998
John McCall31168b02011-06-15 23:02:42 +00002999 Value *RHS;
3000 LValue LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00003001
John McCall31168b02011-06-15 23:02:42 +00003002 switch (E->getLHS()->getType().getObjCLifetime()) {
3003 case Qualifiers::OCL_Strong:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003004 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
John McCall31168b02011-06-15 23:02:42 +00003005 break;
3006
3007 case Qualifiers::OCL_Autoreleasing:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003008 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
John McCall31168b02011-06-15 23:02:42 +00003009 break;
3010
3011 case Qualifiers::OCL_Weak:
3012 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00003013 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall31168b02011-06-15 23:02:42 +00003014 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
3015 break;
3016
3017 // No reason to do any of these differently.
3018 case Qualifiers::OCL_None:
3019 case Qualifiers::OCL_ExplicitNone:
3020 // __block variables need to have the rhs evaluated first, plus
3021 // this should improve codegen just a little.
3022 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00003023 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall31168b02011-06-15 23:02:42 +00003024
3025 // Store the value into the LHS. Bit-fields are handled specially
3026 // because the result is altered by the store, i.e., [C99 6.5.16p1]
3027 // 'An assignment expression has the value of the left operand after
3028 // the assignment...'.
3029 if (LHS.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00003030 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
John McCall31168b02011-06-15 23:02:42 +00003031 else
John McCall55e1fbc2011-06-25 02:11:03 +00003032 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
John McCall31168b02011-06-15 23:02:42 +00003033 }
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003034
3035 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00003036 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00003037 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003038
John McCall07bb1962010-11-16 10:08:07 +00003039 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00003040 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00003041 return RHS;
3042
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003043 // If the lvalue is non-volatile, return the computed value of the assignment.
3044 if (!LHS.isVolatileQualified())
3045 return RHS;
3046
3047 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00003048 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00003049}
3050
3051Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00003052 // Perform vector logical and on comparisons with zero vectors.
3053 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00003054 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003055
Tanya Lattner20248222012-01-16 21:02:28 +00003056 Value *LHS = Visit(E->getLHS());
3057 Value *RHS = Visit(E->getRHS());
3058 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00003059 if (LHS->getType()->isFPOrFPVectorTy()) {
3060 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3061 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3062 } else {
3063 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3064 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3065 }
Tanya Lattner20248222012-01-16 21:02:28 +00003066 Value *And = Builder.CreateAnd(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00003067 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00003068 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003069
Chris Lattner2192fe52011-07-18 04:24:23 +00003070 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003071
Chris Lattner8b084582008-11-12 08:26:50 +00003072 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
3073 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00003074 bool LHSCondVal;
3075 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3076 if (LHSCondVal) { // If we have 1 && X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00003077 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003078
Chris Lattner5b1964b2008-11-11 07:41:27 +00003079 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00003080 // ZExt result to int or bool.
3081 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00003082 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003083
Chris Lattner671fec82009-10-17 04:24:20 +00003084 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner8b084582008-11-12 08:26:50 +00003085 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00003086 return llvm::Constant::getNullValue(ResTy);
Chris Lattner5b1964b2008-11-11 07:41:27 +00003087 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003088
Daniel Dunbara612e792008-11-13 01:38:36 +00003089 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3090 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner8b084582008-11-12 08:26:50 +00003091
John McCallce1de612011-01-26 04:00:11 +00003092 CodeGenFunction::ConditionalEvaluation eval(CGF);
3093
Chris Lattner35710d182008-11-12 08:38:24 +00003094 // Branch on the LHS first. If it is false, go to the failure (cont) block.
Justin Bogner66242d62015-04-23 23:06:47 +00003095 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
3096 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00003097
3098 // Any edges into the ContBlock are now from an (indeterminate number of)
3099 // edges from this first condition. All of these values will be false. Start
3100 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00003101 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00003102 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00003103 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3104 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00003105 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stump4a3999f2009-09-09 13:00:44 +00003106
John McCallce1de612011-01-26 04:00:11 +00003107 eval.begin(CGF);
Chris Lattner2da04b32007-08-24 05:35:26 +00003108 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003109 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00003110 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCallce1de612011-01-26 04:00:11 +00003111 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003112
Chris Lattner2da04b32007-08-24 05:35:26 +00003113 // Reaquire the RHS block, as there may be subblocks inserted.
3114 RHSBlock = Builder.GetInsertBlock();
Chris Lattner35710d182008-11-12 08:38:24 +00003115
David Blaikie1b5adb82014-07-10 20:42:59 +00003116 // Emit an unconditional branch from this block to ContBlock.
3117 {
Devang Patel4d761272011-03-30 00:08:31 +00003118 // There is no need to emit line number for unconditional branch.
Adrian Prantl95b24e92015-02-03 20:00:54 +00003119 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
David Blaikie1b5adb82014-07-10 20:42:59 +00003120 CGF.EmitBlock(ContBlock);
3121 }
3122 // Insert an entry into the phi node for the edge with the value of RHSCond.
Chris Lattner2da04b32007-08-24 05:35:26 +00003123 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003124
Chris Lattner2da04b32007-08-24 05:35:26 +00003125 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00003126 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00003127}
3128
3129Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00003130 // Perform vector logical or on comparisons with zero vectors.
3131 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00003132 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003133
Tanya Lattner20248222012-01-16 21:02:28 +00003134 Value *LHS = Visit(E->getLHS());
3135 Value *RHS = Visit(E->getRHS());
3136 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00003137 if (LHS->getType()->isFPOrFPVectorTy()) {
3138 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3139 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3140 } else {
3141 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3142 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3143 }
Tanya Lattner20248222012-01-16 21:02:28 +00003144 Value *Or = Builder.CreateOr(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00003145 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00003146 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003147
Chris Lattner2192fe52011-07-18 04:24:23 +00003148 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003149
Chris Lattner8b084582008-11-12 08:26:50 +00003150 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
3151 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00003152 bool LHSCondVal;
3153 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3154 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00003155 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003156
Chris Lattner5b1964b2008-11-11 07:41:27 +00003157 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00003158 // ZExt result to int or bool.
3159 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00003160 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003161
Chris Lattner671fec82009-10-17 04:24:20 +00003162 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner8b084582008-11-12 08:26:50 +00003163 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00003164 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner5b1964b2008-11-11 07:41:27 +00003165 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003166
Daniel Dunbara612e792008-11-13 01:38:36 +00003167 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
3168 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stump4a3999f2009-09-09 13:00:44 +00003169
John McCallce1de612011-01-26 04:00:11 +00003170 CodeGenFunction::ConditionalEvaluation eval(CGF);
3171
Chris Lattner35710d182008-11-12 08:38:24 +00003172 // Branch on the LHS first. If it is true, go to the success (cont) block.
Justin Bogneref512b92014-01-06 22:27:43 +00003173 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00003174 CGF.getCurrentProfileCount() -
3175 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00003176
3177 // Any edges into the ContBlock are now from an (indeterminate number of)
3178 // edges from this first condition. All of these values will be true. Start
3179 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00003180 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00003181 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00003182 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3183 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00003184 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattner35710d182008-11-12 08:38:24 +00003185
John McCallce1de612011-01-26 04:00:11 +00003186 eval.begin(CGF);
Anders Carlssonf47a3de2009-06-04 02:53:13 +00003187
Chris Lattner35710d182008-11-12 08:38:24 +00003188 // Emit the RHS condition as a bool value.
Chris Lattner2da04b32007-08-24 05:35:26 +00003189 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003190 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00003191 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00003192
John McCallce1de612011-01-26 04:00:11 +00003193 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003194
Chris Lattner2da04b32007-08-24 05:35:26 +00003195 // Reaquire the RHS block, as there may be subblocks inserted.
3196 RHSBlock = Builder.GetInsertBlock();
Mike Stump4a3999f2009-09-09 13:00:44 +00003197
Chris Lattner35710d182008-11-12 08:38:24 +00003198 // Emit an unconditional branch from this block to ContBlock. Insert an entry
3199 // into the phi node for the edge with the value of RHSCond.
3200 CGF.EmitBlock(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00003201 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003202
Chris Lattner2da04b32007-08-24 05:35:26 +00003203 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00003204 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00003205}
3206
3207Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +00003208 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00003209 CGF.EnsureInsertPoint();
Chris Lattner2da04b32007-08-24 05:35:26 +00003210 return Visit(E->getRHS());
3211}
3212
3213//===----------------------------------------------------------------------===//
3214// Other Operators
3215//===----------------------------------------------------------------------===//
3216
Chris Lattner3fd91f832008-11-12 08:55:54 +00003217/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
3218/// expression is cheap enough and side-effect-free enough to evaluate
3219/// unconditionally instead of conditionally. This is used to convert control
3220/// flow into selects in some cases.
Mike Stump53f9ded2009-11-03 23:25:48 +00003221static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
3222 CodeGenFunction &CGF) {
Chris Lattner56784f92011-04-16 23:15:35 +00003223 // Anything that is an integer or floating point constant is fine.
Nick Lewycky22e55a02013-11-08 23:00:12 +00003224 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
Mike Stump4a3999f2009-09-09 13:00:44 +00003225
Nick Lewycky22e55a02013-11-08 23:00:12 +00003226 // Even non-volatile automatic variables can't be evaluated unconditionally.
3227 // Referencing a thread_local may cause non-trivial initialization work to
3228 // occur. If we're inside a lambda and one of the variables is from the scope
3229 // outside the lambda, that function may have returned already. Reading its
3230 // locals is a bad idea. Also, these reads may introduce races there didn't
3231 // exist in the source-level program.
Chris Lattner3fd91f832008-11-12 08:55:54 +00003232}
3233
3234
Chris Lattner2da04b32007-08-24 05:35:26 +00003235Value *ScalarExprEmitter::
John McCallc07a0c72011-02-17 10:25:35 +00003236VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00003237 TestAndClearIgnoreResultAssign();
John McCallc07a0c72011-02-17 10:25:35 +00003238
3239 // Bind the common expression if necessary.
Eli Friedman48fd89a2012-01-06 20:42:20 +00003240 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCallc07a0c72011-02-17 10:25:35 +00003241
3242 Expr *condExpr = E->getCond();
3243 Expr *lhsExpr = E->getTrueExpr();
3244 Expr *rhsExpr = E->getFalseExpr();
3245
Chris Lattnercd439292008-11-12 08:04:58 +00003246 // If the condition constant folds and can be elided, try to avoid emitting
3247 // the condition and the dead arm.
Chris Lattner41c6ab52011-02-27 23:02:32 +00003248 bool CondExprBool;
3249 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00003250 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattner41c6ab52011-02-27 23:02:32 +00003251 if (!CondExprBool) std::swap(live, dead);
Mike Stump4a3999f2009-09-09 13:00:44 +00003252
Eli Friedman27ef75b2011-10-15 02:10:40 +00003253 // If the dead side doesn't have labels we need, just emit the Live part.
3254 if (!CGF.ContainsLabel(dead)) {
Justin Bogneref512b92014-01-06 22:27:43 +00003255 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00003256 CGF.incrementProfileCounter(E);
Eli Friedman27ef75b2011-10-15 02:10:40 +00003257 Value *Result = Visit(live);
3258
3259 // If the live part is a throw expression, it acts like it has a void
3260 // type, so evaluating it returns a null Value*. However, a conditional
3261 // with non-void type must return a non-null Value*.
3262 if (!Result && !E->getType()->isVoidType())
3263 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
3264
3265 return Result;
3266 }
Chris Lattnerd53e2332008-11-11 18:56:45 +00003267 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003268
Nate Begemanabb5a732010-09-20 22:41:17 +00003269 // OpenCL: If the condition is a vector, we can treat this condition like
3270 // the select function.
Craig Toppera97d7e72013-07-26 06:16:11 +00003271 if (CGF.getLangOpts().OpenCL
John McCallc07a0c72011-02-17 10:25:35 +00003272 && condExpr->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00003273 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003274
John McCallc07a0c72011-02-17 10:25:35 +00003275 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
3276 llvm::Value *LHS = Visit(lhsExpr);
3277 llvm::Value *RHS = Visit(rhsExpr);
Craig Toppera97d7e72013-07-26 06:16:11 +00003278
Chris Lattner2192fe52011-07-18 04:24:23 +00003279 llvm::Type *condType = ConvertType(condExpr->getType());
3280 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Craig Toppera97d7e72013-07-26 06:16:11 +00003281
3282 unsigned numElem = vecTy->getNumElements();
Chris Lattner2192fe52011-07-18 04:24:23 +00003283 llvm::Type *elemType = vecTy->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00003284
Chris Lattner2d6b7b92012-01-25 05:34:41 +00003285 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begemanabb5a732010-09-20 22:41:17 +00003286 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
Craig Toppera97d7e72013-07-26 06:16:11 +00003287 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
Nate Begemanabb5a732010-09-20 22:41:17 +00003288 llvm::VectorType::get(elemType,
Craig Toppera97d7e72013-07-26 06:16:11 +00003289 numElem),
Nate Begemanabb5a732010-09-20 22:41:17 +00003290 "sext");
3291 llvm::Value *tmp2 = Builder.CreateNot(tmp);
Craig Toppera97d7e72013-07-26 06:16:11 +00003292
Nate Begemanabb5a732010-09-20 22:41:17 +00003293 // Cast float to int to perform ANDs if necessary.
3294 llvm::Value *RHSTmp = RHS;
3295 llvm::Value *LHSTmp = LHS;
3296 bool wasCast = false;
Chris Lattner2192fe52011-07-18 04:24:23 +00003297 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourneaac265c2012-05-29 00:35:18 +00003298 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begemanabb5a732010-09-20 22:41:17 +00003299 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
3300 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
3301 wasCast = true;
3302 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003303
Nate Begemanabb5a732010-09-20 22:41:17 +00003304 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
3305 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
3306 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
3307 if (wasCast)
3308 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
3309
3310 return tmp5;
3311 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003312
Chris Lattner3fd91f832008-11-12 08:55:54 +00003313 // If this is a really simple expression (like x ? 4 : 5), emit this as a
3314 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner9ce8a532008-11-16 06:16:27 +00003315 // safe to evaluate the LHS and RHS unconditionally.
John McCallc07a0c72011-02-17 10:25:35 +00003316 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
3317 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
Justin Bogner66242d62015-04-23 23:06:47 +00003318 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003319
John McCallc07a0c72011-02-17 10:25:35 +00003320 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
3321 llvm::Value *LHS = Visit(lhsExpr);
3322 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman516c2ad2011-12-08 22:01:56 +00003323 if (!LHS) {
3324 // If the conditional has void type, make sure we return a null Value*.
3325 assert(!RHS && "LHS and RHS types must match");
Craig Topper8a13c412014-05-21 05:09:00 +00003326 return nullptr;
Eli Friedman516c2ad2011-12-08 22:01:56 +00003327 }
Chris Lattner3fd91f832008-11-12 08:55:54 +00003328 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
3329 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003330
Daniel Dunbard2a53a72008-11-12 10:13:37 +00003331 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
3332 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbara612e792008-11-13 01:38:36 +00003333 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCallce1de612011-01-26 04:00:11 +00003334
3335 CodeGenFunction::ConditionalEvaluation eval(CGF);
Justin Bogner66242d62015-04-23 23:06:47 +00003336 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
3337 CGF.getProfileCount(lhsExpr));
Anders Carlsson43c52cd2009-06-04 03:00:32 +00003338
Chris Lattner2da04b32007-08-24 05:35:26 +00003339 CGF.EmitBlock(LHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003340 CGF.incrementProfileCounter(E);
John McCallce1de612011-01-26 04:00:11 +00003341 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00003342 Value *LHS = Visit(lhsExpr);
John McCallce1de612011-01-26 04:00:11 +00003343 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003344
Chris Lattner2da04b32007-08-24 05:35:26 +00003345 LHSBlock = Builder.GetInsertBlock();
John McCallce1de612011-01-26 04:00:11 +00003346 Builder.CreateBr(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003347
Chris Lattner2da04b32007-08-24 05:35:26 +00003348 CGF.EmitBlock(RHSBlock);
John McCallce1de612011-01-26 04:00:11 +00003349 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00003350 Value *RHS = Visit(rhsExpr);
John McCallce1de612011-01-26 04:00:11 +00003351 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003352
John McCallce1de612011-01-26 04:00:11 +00003353 RHSBlock = Builder.GetInsertBlock();
Chris Lattner2da04b32007-08-24 05:35:26 +00003354 CGF.EmitBlock(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00003355
Eli Friedmanf6c175b2009-12-07 20:25:53 +00003356 // If the LHS or RHS is a throw expression, it will be legitimately null.
3357 if (!LHS)
3358 return RHS;
3359 if (!RHS)
3360 return LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00003361
Chris Lattner2da04b32007-08-24 05:35:26 +00003362 // Create a PHI node for the real part.
Jay Foad20c0f022011-03-30 11:28:58 +00003363 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner2da04b32007-08-24 05:35:26 +00003364 PN->addIncoming(LHS, LHSBlock);
3365 PN->addIncoming(RHS, RHSBlock);
3366 return PN;
3367}
3368
3369Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman75807f22013-07-20 00:40:58 +00003370 return Visit(E->getChosenSubExpr());
Chris Lattner2da04b32007-08-24 05:35:26 +00003371}
3372
Chris Lattnerb6a7b582007-11-30 17:56:23 +00003373Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Richard Smitha1a808c2014-04-14 23:47:48 +00003374 QualType Ty = VE->getType();
Daniel Sanders59229dc2014-11-19 10:01:35 +00003375
Richard Smitha1a808c2014-04-14 23:47:48 +00003376 if (Ty->isVariablyModifiedType())
3377 CGF.EmitVariablyModifiedType(Ty);
3378
Eli Friedmanddea0ad2009-01-20 17:46:04 +00003379 llvm::Value *ArgValue = CGF.EmitVAListRef(VE->getSubExpr());
Anders Carlsson13abd7e2008-11-04 05:30:00 +00003380 llvm::Value *ArgPtr = CGF.EmitVAArg(ArgValue, VE->getType());
Daniel Sanders59229dc2014-11-19 10:01:35 +00003381 llvm::Type *ArgTy = ConvertType(VE->getType());
Anders Carlsson13abd7e2008-11-04 05:30:00 +00003382
3383 // If EmitVAArg fails, we fall back to the LLVM instruction.
Mike Stump4a3999f2009-09-09 13:00:44 +00003384 if (!ArgPtr)
Daniel Sanders59229dc2014-11-19 10:01:35 +00003385 return Builder.CreateVAArg(ArgValue, ArgTy);
Anders Carlsson13abd7e2008-11-04 05:30:00 +00003386
Mike Stumpdf0fe272009-05-29 15:46:01 +00003387 // FIXME Volatility.
Daniel Sanders59229dc2014-11-19 10:01:35 +00003388 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
3389
3390 // If EmitVAArg promoted the type, we must truncate it.
Daniel Sanderscdcb5802015-01-13 10:47:00 +00003391 if (ArgTy != Val->getType()) {
3392 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
3393 Val = Builder.CreateIntToPtr(Val, ArgTy);
3394 else
3395 Val = Builder.CreateTrunc(Val, ArgTy);
3396 }
Daniel Sanders59229dc2014-11-19 10:01:35 +00003397
3398 return Val;
Anders Carlsson7e13ab82007-10-15 20:28:48 +00003399}
3400
John McCall351762c2011-02-07 10:33:21 +00003401Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
3402 return CGF.EmitBlockLiteral(block);
Mike Stumpab3afd82009-02-12 18:29:15 +00003403}
3404
Tanya Lattner55808c12011-06-04 00:47:47 +00003405Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
3406 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2192fe52011-07-18 04:24:23 +00003407 llvm::Type *DstTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003408
Tanya Lattner55808c12011-06-04 00:47:47 +00003409 // Going from vec4->vec3 or vec3->vec4 is a special case and requires
3410 // a shuffle vector instead of a bitcast.
Chris Lattner2192fe52011-07-18 04:24:23 +00003411 llvm::Type *SrcTy = Src->getType();
Tanya Lattner55808c12011-06-04 00:47:47 +00003412 if (isa<llvm::VectorType>(DstTy) && isa<llvm::VectorType>(SrcTy)) {
3413 unsigned numElementsDst = cast<llvm::VectorType>(DstTy)->getNumElements();
3414 unsigned numElementsSrc = cast<llvm::VectorType>(SrcTy)->getNumElements();
Craig Toppera97d7e72013-07-26 06:16:11 +00003415 if ((numElementsDst == 3 && numElementsSrc == 4)
Tanya Lattner55808c12011-06-04 00:47:47 +00003416 || (numElementsDst == 4 && numElementsSrc == 3)) {
Craig Toppera97d7e72013-07-26 06:16:11 +00003417
3418
Tanya Lattner55808c12011-06-04 00:47:47 +00003419 // In the case of going from int4->float3, a bitcast is needed before
3420 // doing a shuffle.
Craig Toppera97d7e72013-07-26 06:16:11 +00003421 llvm::Type *srcElemTy =
Tanya Lattner55808c12011-06-04 00:47:47 +00003422 cast<llvm::VectorType>(SrcTy)->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00003423 llvm::Type *dstElemTy =
Tanya Lattner55808c12011-06-04 00:47:47 +00003424 cast<llvm::VectorType>(DstTy)->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00003425
Tanya Lattner55808c12011-06-04 00:47:47 +00003426 if ((srcElemTy->isIntegerTy() && dstElemTy->isFloatTy())
3427 || (srcElemTy->isFloatTy() && dstElemTy->isIntegerTy())) {
3428 // Create a float type of the same size as the source or destination.
Chris Lattner2192fe52011-07-18 04:24:23 +00003429 llvm::VectorType *newSrcTy = llvm::VectorType::get(dstElemTy,
Tanya Lattner55808c12011-06-04 00:47:47 +00003430 numElementsSrc);
Craig Toppera97d7e72013-07-26 06:16:11 +00003431
Tanya Lattner55808c12011-06-04 00:47:47 +00003432 Src = Builder.CreateBitCast(Src, newSrcTy, "astypeCast");
3433 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003434
Tanya Lattner55808c12011-06-04 00:47:47 +00003435 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003436
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003437 SmallVector<llvm::Constant*, 3> Args;
Tanya Lattner55808c12011-06-04 00:47:47 +00003438 Args.push_back(Builder.getInt32(0));
3439 Args.push_back(Builder.getInt32(1));
3440 Args.push_back(Builder.getInt32(2));
Craig Toppera97d7e72013-07-26 06:16:11 +00003441
Tanya Lattner55808c12011-06-04 00:47:47 +00003442 if (numElementsDst == 4)
Chris Lattnerece04092012-02-07 00:39:47 +00003443 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
Craig Toppera97d7e72013-07-26 06:16:11 +00003444
Tanya Lattner55808c12011-06-04 00:47:47 +00003445 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Craig Toppera97d7e72013-07-26 06:16:11 +00003446
Tanya Lattner55808c12011-06-04 00:47:47 +00003447 return Builder.CreateShuffleVector(Src, UnV, Mask, "astype");
3448 }
3449 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003450
Tanya Lattner55808c12011-06-04 00:47:47 +00003451 return Builder.CreateBitCast(Src, DstTy, "astype");
3452}
3453
Eli Friedmandf14b3a2011-10-11 02:20:01 +00003454Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
3455 return CGF.EmitAtomicExpr(E).getScalarVal();
3456}
3457
Chris Lattner2da04b32007-08-24 05:35:26 +00003458//===----------------------------------------------------------------------===//
3459// Entry Point into this File
3460//===----------------------------------------------------------------------===//
3461
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00003462/// Emit the computation of the specified expression of scalar type, ignoring
3463/// the result.
Mike Stumpdf0fe272009-05-29 15:46:01 +00003464Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
John McCall47fb9502013-03-07 21:37:08 +00003465 assert(E && hasScalarEvaluationKind(E->getType()) &&
Chris Lattner2da04b32007-08-24 05:35:26 +00003466 "Invalid scalar expression to emit");
Mike Stump4a3999f2009-09-09 13:00:44 +00003467
David Blaikie38b25912015-02-09 19:13:51 +00003468 return ScalarExprEmitter(*this, IgnoreResultAssign)
3469 .Visit(const_cast<Expr *>(E));
Chris Lattner2da04b32007-08-24 05:35:26 +00003470}
Chris Lattner3474c202007-08-26 06:48:56 +00003471
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00003472/// Emit a conversion from the specified type to the specified destination type,
3473/// both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00003474Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
3475 QualType DstTy) {
John McCall47fb9502013-03-07 21:37:08 +00003476 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
Chris Lattner3474c202007-08-26 06:48:56 +00003477 "Invalid scalar expression to emit");
3478 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy);
3479}
Chris Lattner42e6b812007-08-26 16:34:22 +00003480
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00003481/// Emit a conversion from the specified complex type to the specified
3482/// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +00003483Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
3484 QualType SrcTy,
3485 QualType DstTy) {
John McCall47fb9502013-03-07 21:37:08 +00003486 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
Chris Lattner42e6b812007-08-26 16:34:22 +00003487 "Invalid complex -> scalar conversion");
3488 return ScalarExprEmitter(*this).EmitComplexToScalarConversion(Src, SrcTy,
3489 DstTy);
3490}
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00003491
Chris Lattner05dc78c2010-06-26 22:09:34 +00003492
3493llvm::Value *CodeGenFunction::
3494EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3495 bool isInc, bool isPre) {
3496 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
3497}
3498
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00003499LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
3500 llvm::Value *V;
3501 // object->isa or (*object).isa
3502 // Generate code as for: *(Class*)object
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00003503 // build Class* type
Chris Lattner2192fe52011-07-18 04:24:23 +00003504 llvm::Type *ClassPtrTy = ConvertType(E->getType());
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00003505
3506 Expr *BaseExpr = E->getBase();
John McCall086a4642010-11-24 05:12:34 +00003507 if (BaseExpr->isRValue()) {
Eli Friedman3184a5e2011-12-19 23:03:09 +00003508 V = CreateMemTemp(E->getType(), "resval");
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00003509 llvm::Value *Src = EmitScalarExpr(BaseExpr);
3510 Builder.CreateStore(Src, V);
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003511 V = ScalarExprEmitter(*this).EmitLoadOfLValue(
Nick Lewycky2d84e842013-10-02 02:29:49 +00003512 MakeNaturalAlignAddrLValue(V, E->getType()), E->getExprLoc());
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00003513 } else {
3514 if (E->isArrow())
3515 V = ScalarExprEmitter(*this).EmitLoadOfLValue(BaseExpr);
3516 else
3517 V = EmitLValue(BaseExpr).getAddress();
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00003518 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003519
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00003520 // build Class* type
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00003521 ClassPtrTy = ClassPtrTy->getPointerTo();
3522 V = Builder.CreateBitCast(V, ClassPtrTy);
Eli Friedman3184a5e2011-12-19 23:03:09 +00003523 return MakeNaturalAlignAddrLValue(V, E->getType());
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00003524}
3525
Douglas Gregor914af212010-04-23 04:16:32 +00003526
John McCalla2342eb2010-12-05 02:00:02 +00003527LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor914af212010-04-23 04:16:32 +00003528 const CompoundAssignOperator *E) {
3529 ScalarExprEmitter Scalar(*this);
Craig Topper8a13c412014-05-21 05:09:00 +00003530 Value *Result = nullptr;
Douglas Gregor914af212010-04-23 04:16:32 +00003531 switch (E->getOpcode()) {
3532#define COMPOUND_OP(Op) \
John McCalle3027922010-08-25 11:45:40 +00003533 case BO_##Op##Assign: \
Douglas Gregor914af212010-04-23 04:16:32 +00003534 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003535 Result)
Douglas Gregor914af212010-04-23 04:16:32 +00003536 COMPOUND_OP(Mul);
3537 COMPOUND_OP(Div);
3538 COMPOUND_OP(Rem);
3539 COMPOUND_OP(Add);
3540 COMPOUND_OP(Sub);
3541 COMPOUND_OP(Shl);
3542 COMPOUND_OP(Shr);
3543 COMPOUND_OP(And);
3544 COMPOUND_OP(Xor);
3545 COMPOUND_OP(Or);
3546#undef COMPOUND_OP
Craig Toppera97d7e72013-07-26 06:16:11 +00003547
John McCalle3027922010-08-25 11:45:40 +00003548 case BO_PtrMemD:
3549 case BO_PtrMemI:
3550 case BO_Mul:
3551 case BO_Div:
3552 case BO_Rem:
3553 case BO_Add:
3554 case BO_Sub:
3555 case BO_Shl:
3556 case BO_Shr:
3557 case BO_LT:
3558 case BO_GT:
3559 case BO_LE:
3560 case BO_GE:
3561 case BO_EQ:
3562 case BO_NE:
3563 case BO_And:
3564 case BO_Xor:
3565 case BO_Or:
3566 case BO_LAnd:
3567 case BO_LOr:
3568 case BO_Assign:
3569 case BO_Comma:
David Blaikie83d382b2011-09-23 05:06:16 +00003570 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor914af212010-04-23 04:16:32 +00003571 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003572
Douglas Gregor914af212010-04-23 04:16:32 +00003573 llvm_unreachable("Unhandled compound assignment operator");
3574}