blob: 29d153b7278d58d769641cbca7b232ae87ce031e [file] [log] [blame]
Chris Lattner2da04b32007-08-24 05:35:26 +00001//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner2da04b32007-08-24 05:35:26 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
John McCall5d865c322010-08-31 07:33:07 +000013#include "CGCXXABI.h"
Leonard Chan99bda372018-10-15 16:07:02 +000014#include "CGCleanup.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CGDebugInfo.h"
Fariborz Jahanian07ca7272009-10-10 20:07:56 +000016#include "CGObjCRuntime.h"
Leonard Chan99bda372018-10-15 16:07:02 +000017#include "CodeGenFunction.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"
Yaxun Liu402804b2016-12-15 08:09:08 +000022#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000023#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000024#include "clang/AST/StmtVisitor.h"
Richard Trieu63688182018-12-11 03:18:39 +000025#include "clang/Basic/CodeGenOptions.h"
Leonard Chan99bda372018-10-15 16:07:02 +000026#include "clang/Basic/FixedPoint.h"
Chris Lattnerff2367c2008-04-20 00:50:39 +000027#include "clang/Basic/TargetInfo.h"
Vedant Kumar82ee16b2017-02-25 00:43:36 +000028#include "llvm/ADT/Optional.h"
Chandler Carruth735e6d82014-03-04 11:46:22 +000029#include "llvm/IR/CFG.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000030#include "llvm/IR/Constants.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Function.h"
Vedant Kumara125eb52017-06-01 19:22:18 +000033#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000034#include "llvm/IR/GlobalVariable.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/Module.h"
Chris Lattner1800c182008-01-03 07:05:49 +000037#include <cstdarg>
Ted Kremenekf182e812007-12-10 23:44:32 +000038
Chris Lattner2da04b32007-08-24 05:35:26 +000039using namespace clang;
40using namespace CodeGen;
41using llvm::Value;
42
43//===----------------------------------------------------------------------===//
44// Scalar Expression Emitter
45//===----------------------------------------------------------------------===//
46
Benjamin Kramerfb5e5842010-10-22 16:48:22 +000047namespace {
Vedant Kumara125eb52017-06-01 19:22:18 +000048
49/// Determine whether the given binary operation may overflow.
50/// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
51/// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
52/// the returned overflow check is precise. The returned value is 'true' for
53/// all other opcodes, to be conservative.
54bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
55 BinaryOperator::Opcode Opcode, bool Signed,
56 llvm::APInt &Result) {
57 // Assume overflow is possible, unless we can prove otherwise.
58 bool Overflow = true;
59 const auto &LHSAP = LHS->getValue();
60 const auto &RHSAP = RHS->getValue();
61 if (Opcode == BO_Add) {
62 if (Signed)
63 Result = LHSAP.sadd_ov(RHSAP, Overflow);
64 else
65 Result = LHSAP.uadd_ov(RHSAP, Overflow);
66 } else if (Opcode == BO_Sub) {
67 if (Signed)
68 Result = LHSAP.ssub_ov(RHSAP, Overflow);
69 else
70 Result = LHSAP.usub_ov(RHSAP, Overflow);
71 } else if (Opcode == BO_Mul) {
72 if (Signed)
73 Result = LHSAP.smul_ov(RHSAP, Overflow);
74 else
75 Result = LHSAP.umul_ov(RHSAP, Overflow);
76 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
77 if (Signed && !RHS->isZero())
78 Result = LHSAP.sdiv_ov(RHSAP, Overflow);
79 else
80 return false;
81 }
82 return Overflow;
83}
84
Chris Lattner2da04b32007-08-24 05:35:26 +000085struct BinOpInfo {
86 Value *LHS;
87 Value *RHS;
Chris Lattner3d966d62007-08-24 21:00:35 +000088 QualType Ty; // Computation Type.
Chris Lattner0bf27622010-06-26 21:48:21 +000089 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
Adam Nemet484aa452017-03-27 19:17:25 +000090 FPOptions FPFeatures;
Chris Lattner0bf27622010-06-26 21:48:21 +000091 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Vedant Kumard9191152017-05-02 23:46:56 +000092
93 /// Check if the binop can result in integer overflow.
94 bool mayHaveIntegerOverflow() const {
95 // Without constant input, we can't rule out overflow.
Vedant Kumara125eb52017-06-01 19:22:18 +000096 auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
97 auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
Vedant Kumard9191152017-05-02 23:46:56 +000098 if (!LHSCI || !RHSCI)
99 return true;
100
Vedant Kumara125eb52017-06-01 19:22:18 +0000101 llvm::APInt Result;
102 return ::mayHaveIntegerOverflow(
103 LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
Vedant Kumard9191152017-05-02 23:46:56 +0000104 }
105
106 /// Check if the binop computes a division or a remainder.
Vedant Kumar94cb34b2017-05-09 00:12:33 +0000107 bool isDivremOp() const {
Vedant Kumard9191152017-05-02 23:46:56 +0000108 return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
109 Opcode == BO_RemAssign;
110 }
111
112 /// Check if the binop can result in an integer division by zero.
113 bool mayHaveIntegerDivisionByZero() const {
Vedant Kumar94cb34b2017-05-09 00:12:33 +0000114 if (isDivremOp())
Vedant Kumard9191152017-05-02 23:46:56 +0000115 if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
116 return CI->isZero();
117 return true;
118 }
119
120 /// Check if the binop can result in a float division by zero.
121 bool mayHaveFloatDivisionByZero() const {
Vedant Kumar94cb34b2017-05-09 00:12:33 +0000122 if (isDivremOp())
Vedant Kumard9191152017-05-02 23:46:56 +0000123 if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
124 return CFP->isZero();
125 return true;
126 }
Leonard Chan2044ac82019-01-16 18:13:59 +0000127
128 /// Check if either operand is a fixed point type, in which case, this
129 /// operation did not follow usual arithmetic conversion and both operands may
130 /// not be the same.
131 bool isFixedPointBinOp() const {
132 return isa<BinaryOperator>(E) && Ty->isFixedPointType();
133 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000134};
135
John McCalle84af4e2010-11-13 01:35:44 +0000136static bool MustVisitNullValue(const Expr *E) {
137 // If a null pointer expression's type is the C++0x nullptr_t, then
138 // it's not necessarily a simple constant and it must be evaluated
139 // for its potential side effects.
140 return E->getType()->isNullPtrType();
141}
142
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000143/// If \p E is a widened promoted integer, get its base (unpromoted) type.
144static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
145 const Expr *E) {
146 const Expr *Base = E->IgnoreImpCasts();
147 if (E == Base)
148 return llvm::None;
149
150 QualType BaseTy = Base->getType();
151 if (!BaseTy->isPromotableIntegerType() ||
152 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
153 return llvm::None;
154
155 return BaseTy;
156}
157
158/// Check if \p E is a widened promoted integer.
159static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
160 return getUnwidenedIntegerType(Ctx, E).hasValue();
161}
162
163/// Check if we can skip the overflow check for \p Op.
164static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
Vedant Kumar66c00cc2017-02-25 06:47:00 +0000165 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
166 "Expected a unary or binary operator");
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000167
Vedant Kumard9191152017-05-02 23:46:56 +0000168 // If the binop has constant inputs and we can prove there is no overflow,
169 // we can elide the overflow check.
170 if (!Op.mayHaveIntegerOverflow())
171 return true;
Malcolm Parsonsfab36802018-04-16 08:31:08 +0000172
173 // If a unary op has a widened operand, the op cannot overflow.
174 if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
175 return !UO->canOverflow();
176
177 // We usually don't need overflow checks for binops with widened operands.
178 // Multiplication with promoted unsigned operands is a special case.
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000179 const auto *BO = cast<BinaryOperator>(Op.E);
180 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
181 if (!OptionalLHSTy)
182 return false;
183
184 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
185 if (!OptionalRHSTy)
186 return false;
187
188 QualType LHSTy = *OptionalLHSTy;
189 QualType RHSTy = *OptionalRHSTy;
190
Vedant Kumard9191152017-05-02 23:46:56 +0000191 // This is the simple case: binops without unsigned multiplication, and with
192 // widened operands. No overflow check is needed here.
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000193 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
194 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
195 return true;
196
Vedant Kumard9191152017-05-02 23:46:56 +0000197 // For unsigned multiplication the overflow check can be elided if either one
198 // of the unpromoted types are less than half the size of the promoted type.
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000199 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
200 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
201 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
202}
203
Adam Nemet370d0872017-04-04 21:18:30 +0000204/// Update the FastMathFlags of LLVM IR from the FPOptions in LangOptions.
205static void updateFastMathFlags(llvm::FastMathFlags &FMF,
206 FPOptions FPFeatures) {
207 FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
208}
209
210/// Propagate fast-math flags from \p Op to the instruction in \p V.
211static Value *propagateFMFlags(Value *V, const BinOpInfo &Op) {
212 if (auto *I = dyn_cast<llvm::Instruction>(V)) {
213 llvm::FastMathFlags FMF = I->getFastMathFlags();
214 updateFastMathFlags(FMF, Op.FPFeatures);
215 I->setFastMathFlags(FMF);
216 }
217 return V;
218}
219
Benjamin Kramer337e3a52009-11-28 19:45:26 +0000220class ScalarExprEmitter
Chris Lattner2da04b32007-08-24 05:35:26 +0000221 : public StmtVisitor<ScalarExprEmitter, Value*> {
222 CodeGenFunction &CGF;
Daniel Dunbarcb463852008-11-01 01:53:16 +0000223 CGBuilderTy &Builder;
Mike Stumpdf0fe272009-05-29 15:46:01 +0000224 bool IgnoreResultAssign;
Owen Anderson170229f2009-07-14 23:10:40 +0000225 llvm::LLVMContext &VMContext;
Chris Lattner2da04b32007-08-24 05:35:26 +0000226public:
227
Mike Stumpdf0fe272009-05-29 15:46:01 +0000228 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stump4a3999f2009-09-09 13:00:44 +0000229 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Anderson170229f2009-07-14 23:10:40 +0000230 VMContext(cgf.getLLVMContext()) {
Chris Lattner2da04b32007-08-24 05:35:26 +0000231 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000232
Chris Lattner2da04b32007-08-24 05:35:26 +0000233 //===--------------------------------------------------------------------===//
234 // Utilities
235 //===--------------------------------------------------------------------===//
236
Mike Stumpdf0fe272009-05-29 15:46:01 +0000237 bool TestAndClearIgnoreResultAssign() {
Chris Lattner2a7deb62009-07-08 01:08:03 +0000238 bool I = IgnoreResultAssign;
239 IgnoreResultAssign = false;
240 return I;
241 }
Mike Stumpdf0fe272009-05-29 15:46:01 +0000242
Chris Lattner2192fe52011-07-18 04:24:23 +0000243 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner2da04b32007-08-24 05:35:26 +0000244 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith4d1458e2012-09-08 02:08:36 +0000245 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
246 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith69d0d262012-08-24 00:54:33 +0000247 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000248
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000249 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000250 const BinOpInfo &Info);
Richard Smithe30752c2012-10-09 19:52:38 +0000251
Nick Lewycky2d84e842013-10-02 02:29:49 +0000252 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
253 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
Chris Lattner2da04b32007-08-24 05:35:26 +0000254 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000255
Hal Finkel64567a82014-10-04 15:26:49 +0000256 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
257 const AlignValueAttr *AVAttr = nullptr;
258 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
259 const ValueDecl *VD = DRE->getDecl();
260
261 if (VD->getType()->isReferenceType()) {
262 if (const auto *TTy =
263 dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
264 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
265 } else {
266 // Assumptions for function parameters are emitted at the start of the
Roman Lebedevbd1c0872019-01-15 09:44:25 +0000267 // function, so there is no need to repeat that here,
268 // unless the alignment-assumption sanitizer is enabled,
269 // then we prefer the assumption over alignment attribute
270 // on IR function param.
271 if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
Hal Finkel64567a82014-10-04 15:26:49 +0000272 return;
273
274 AVAttr = VD->getAttr<AlignValueAttr>();
275 }
276 }
277
278 if (!AVAttr)
279 if (const auto *TTy =
280 dyn_cast<TypedefType>(E->getType()))
281 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
282
283 if (!AVAttr)
284 return;
285
286 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
287 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
Roman Lebedevbd1c0872019-01-15 09:44:25 +0000288 CGF.EmitAlignmentAssumption(V, E, AVAttr->getLocation(),
289 AlignmentCI->getZExtValue());
Hal Finkel64567a82014-10-04 15:26:49 +0000290 }
291
Chris Lattner2da04b32007-08-24 05:35:26 +0000292 /// EmitLoadOfLValue - Given an expression with complex type that represents a
293 /// value l-value, this method emits the address of the l-value, then loads
294 /// and returns the result.
295 Value *EmitLoadOfLValue(const Expr *E) {
Hal Finkel64567a82014-10-04 15:26:49 +0000296 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
297 E->getExprLoc());
298
299 EmitLValueAlignmentAssumption(E, V);
300 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000301 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000302
Chris Lattnere0044382007-08-26 16:42:57 +0000303 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000304 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000305 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stump4a3999f2009-09-09 13:00:44 +0000306
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000307 /// Emit a check that a conversion to or from a floating-point type does not
308 /// overflow.
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000309 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000310 Value *Src, QualType SrcType, QualType DstType,
311 llvm::Type *DstTy, SourceLocation Loc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000312
Roman Lebedevb69ba222018-07-30 18:58:30 +0000313 /// Known implicit conversion check kinds.
314 /// Keep in sync with the enum of the same name in ubsan_handlers.h
315 enum ImplicitConversionCheckKind : unsigned char {
Roman Lebedevdd403572018-10-11 09:09:50 +0000316 ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
317 ICCK_UnsignedIntegerTruncation = 1,
318 ICCK_SignedIntegerTruncation = 2,
Roman Lebedev62debd802018-10-30 21:58:56 +0000319 ICCK_IntegerSignChange = 3,
320 ICCK_SignedIntegerTruncationOrSignChange = 4,
Roman Lebedevb69ba222018-07-30 18:58:30 +0000321 };
322
323 /// Emit a check that an [implicit] truncation of an integer does not
324 /// discard any bits. It is not UB, so we use the value after truncation.
325 void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
326 QualType DstType, SourceLocation Loc);
327
Roman Lebedev62debd802018-10-30 21:58:56 +0000328 /// Emit a check that an [implicit] conversion of an integer does not change
329 /// the sign of the value. It is not UB, so we use the value after conversion.
330 /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
331 void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
332 QualType DstType, SourceLocation Loc);
333
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000334 /// Emit a conversion from the specified type to the specified destination
335 /// type, both of which are LLVM scalar types.
Roman Lebedevb69ba222018-07-30 18:58:30 +0000336 struct ScalarConversionOpts {
337 bool TreatBooleanAsSigned;
338 bool EmitImplicitIntegerTruncationChecks;
Roman Lebedev62debd802018-10-30 21:58:56 +0000339 bool EmitImplicitIntegerSignChangeChecks;
Chris Lattner42e6b812007-08-26 16:34:22 +0000340
Roman Lebedevb69ba222018-07-30 18:58:30 +0000341 ScalarConversionOpts()
342 : TreatBooleanAsSigned(false),
Roman Lebedev62debd802018-10-30 21:58:56 +0000343 EmitImplicitIntegerTruncationChecks(false),
344 EmitImplicitIntegerSignChangeChecks(false) {}
Roman Lebedevd677c3f2018-11-19 19:56:43 +0000345
346 ScalarConversionOpts(clang::SanitizerSet SanOpts)
347 : TreatBooleanAsSigned(false),
348 EmitImplicitIntegerTruncationChecks(
349 SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
350 EmitImplicitIntegerSignChangeChecks(
351 SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
Roman Lebedevb69ba222018-07-30 18:58:30 +0000352 };
353 Value *
354 EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
355 SourceLocation Loc,
356 ScalarConversionOpts Opts = ScalarConversionOpts());
Anastasia Stulovab02e7832015-10-05 11:27:41 +0000357
Leonard Chan99bda372018-10-15 16:07:02 +0000358 Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
359 SourceLocation Loc);
Leonard Chan2044ac82019-01-16 18:13:59 +0000360 Value *EmitFixedPointConversion(Value *Src, FixedPointSemantics &SrcFixedSema,
361 FixedPointSemantics &DstFixedSema,
362 SourceLocation Loc);
Leonard Chan99bda372018-10-15 16:07:02 +0000363
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000364 /// Emit a conversion from the specified complex type to the specified
365 /// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000366 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000367 QualType SrcTy, QualType DstTy,
368 SourceLocation Loc);
Mike Stumpab3afd82009-02-12 18:29:15 +0000369
Anders Carlsson5b944432010-05-22 17:45:10 +0000370 /// EmitNullValue - Emit a value that corresponds to null for the given type.
371 Value *EmitNullValue(QualType Ty);
372
John McCall8cb679e2010-11-15 09:13:47 +0000373 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
374 Value *EmitFloatToBoolConversion(Value *V) {
375 // Compare against 0.0 for fp scalars.
376 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
377 return Builder.CreateFCmpUNE(V, Zero, "tobool");
378 }
379
380 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
Yaxun Liu402804b2016-12-15 08:09:08 +0000381 Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
382 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
383
John McCall8cb679e2010-11-15 09:13:47 +0000384 return Builder.CreateICmpNE(V, Zero, "tobool");
385 }
386
387 Value *EmitIntToBoolConversion(Value *V) {
388 // Because of the type rules of C, we often end up computing a
389 // logical value, then zero extending it to int, then wanting it
390 // as a logical value again. Optimize this common case.
391 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
392 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
393 Value *Result = ZI->getOperand(0);
394 // If there aren't any more uses, zap the instruction to save space.
395 // Note that there can be more uses, for example if this
396 // is the result of an assignment.
397 if (ZI->use_empty())
398 ZI->eraseFromParent();
399 return Result;
400 }
401 }
402
Chris Lattner2531eb42011-04-19 22:55:03 +0000403 return Builder.CreateIsNotNull(V, "tobool");
John McCall8cb679e2010-11-15 09:13:47 +0000404 }
405
Chris Lattner2da04b32007-08-24 05:35:26 +0000406 //===--------------------------------------------------------------------===//
407 // Visitor Methods
408 //===--------------------------------------------------------------------===//
409
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000410 Value *Visit(Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000411 ApplyDebugLocation DL(CGF, E);
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000412 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
413 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000414
Chris Lattner2da04b32007-08-24 05:35:26 +0000415 Value *VisitStmt(Stmt *S) {
Ted Kremenekd4e5fba2007-12-11 21:27:55 +0000416 S->dump(CGF.getContext().getSourceManager());
David Blaikie83d382b2011-09-23 05:06:16 +0000417 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner2da04b32007-08-24 05:35:26 +0000418 }
419 Value *VisitExpr(Expr *S);
Craig Toppera97d7e72013-07-26 06:16:11 +0000420
Bill Wendling8003edc2018-11-09 00:41:36 +0000421 Value *VisitConstantExpr(ConstantExpr *E) {
422 return Visit(E->getSubExpr());
423 }
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000424 Value *VisitParenExpr(ParenExpr *PE) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000425 return Visit(PE->getSubExpr());
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000426 }
John McCall7c454bb2011-07-15 05:09:51 +0000427 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000428 return Visit(E->getReplacement());
John McCall7c454bb2011-07-15 05:09:51 +0000429 }
Peter Collingbourne91147592011-04-15 00:35:48 +0000430 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
431 return Visit(GE->getResultExpr());
432 }
Gor Nishanov5eb58582017-03-26 02:18:05 +0000433 Value *VisitCoawaitExpr(CoawaitExpr *S) {
434 return CGF.EmitCoawaitExpr(*S).getScalarVal();
435 }
436 Value *VisitCoyieldExpr(CoyieldExpr *S) {
437 return CGF.EmitCoyieldExpr(*S).getScalarVal();
438 }
439 Value *VisitUnaryCoawait(const UnaryOperator *E) {
440 return Visit(E->getSubExpr());
441 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000442
443 // Leaves.
444 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000445 return Builder.getInt(E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000446 }
Leonard Chandb01c3a2018-06-20 17:19:40 +0000447 Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
448 return Builder.getInt(E->getValue());
449 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000450 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersone05f2ed2009-07-27 21:00:51 +0000451 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000452 }
453 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000454 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000455 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000456 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
457 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
458 }
Nate Begeman4c18c232007-11-15 05:40:03 +0000459 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000460 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begeman4c18c232007-11-15 05:40:03 +0000461 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000462 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000463 return EmitNullValue(E->getType());
Argyrios Kyrtzidisce4528f2008-08-23 19:35:47 +0000464 }
Anders Carlsson39def3a2008-12-21 22:39:40 +0000465 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000466 return EmitNullValue(E->getType());
Anders Carlsson39def3a2008-12-21 22:39:40 +0000467 }
Eli Friedmand7c72322010-08-05 09:58:49 +0000468 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournee190dee2011-03-11 19:24:49 +0000469 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000470 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattner6c4d2552009-10-28 23:59:40 +0000471 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
472 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000473 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000474
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000475 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000476 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000477 }
John McCall1bf58462011-02-16 08:02:54 +0000478
John McCallfe96e0b2011-11-06 09:01:30 +0000479 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
480 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
481 }
482
John McCall1bf58462011-02-16 08:02:54 +0000483 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCallc07a0c72011-02-17 10:25:35 +0000484 if (E->isGLValue())
Akira Hatanaka797afe32018-03-20 01:47:58 +0000485 return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
486 E->getExprLoc());
John McCall1bf58462011-02-16 08:02:54 +0000487
488 // Otherwise, assume the mapping is the scalar directly.
Akira Hatanaka797afe32018-03-20 01:47:58 +0000489 return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
John McCall1bf58462011-02-16 08:02:54 +0000490 }
John McCall71335052012-03-10 03:05:10 +0000491
Chris Lattner2da04b32007-08-24 05:35:26 +0000492 // l-values.
John McCall113bee02012-03-10 09:33:50 +0000493 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +0000494 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
Volodymyr Sapsaief1899b2018-11-01 21:57:05 +0000495 return CGF.emitScalarConstant(Constant, E);
John McCall113bee02012-03-10 09:33:50 +0000496 return EmitLoadOfLValue(E);
John McCall71335052012-03-10 03:05:10 +0000497 }
498
Mike Stump4a3999f2009-09-09 13:00:44 +0000499 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
500 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000501 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000502 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
503 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000504 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000505 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar55310df2008-08-27 06:57:25 +0000506 return EmitLoadOfLValue(E);
507 }
Daniel Dunbar55310df2008-08-27 06:57:25 +0000508 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000509 if (E->getMethodDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +0000510 E->getMethodDecl()->getReturnType()->isReferenceType())
Fariborz Jahanianff989032011-03-02 20:09:49 +0000511 return EmitLoadOfLValue(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000512 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000513 }
514
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000515 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000516 LValue LV = CGF.EmitObjCIsaExpr(E);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000517 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000518 return V;
519 }
520
Erik Pilkington9c42a8d2017-02-23 21:08:08 +0000521 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
522 VersionTuple Version = E->getVersion();
523
524 // If we're checking for a platform older than our minimum deployment
525 // target, we can fold the check away.
526 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
527 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
528
529 Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
530 llvm::Value *Args[] = {
531 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()),
532 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0),
533 llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0),
534 };
535
536 return CGF.EmitBuiltinAvailable(Args);
537 }
538
Chris Lattner2da04b32007-08-24 05:35:26 +0000539 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000540 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Hal Finkelc4d7c822013-09-18 03:29:45 +0000541 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
Eli Friedmancb422f12009-11-26 03:22:21 +0000542 Value *VisitMemberExpr(MemberExpr *E);
Nate Begemance4d7fc2008-04-18 23:10:10 +0000543 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattner084bc322008-10-26 23:53:12 +0000544 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
545 return EmitLoadOfLValue(E);
546 }
Devang Patel43fc86d2007-10-24 17:18:43 +0000547
Nate Begeman19351632009-10-18 20:10:40 +0000548 Value *VisitInitListExpr(InitListExpr *E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000549
Richard Smith410306b2016-12-12 02:53:20 +0000550 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
551 assert(CGF.getArrayInitIndex() &&
552 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
553 return CGF.getArrayInitIndex();
554 }
555
Douglas Gregor0202cb42009-01-29 17:44:32 +0000556 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithd82a2ce2012-12-21 03:17:28 +0000557 return EmitNullValue(E->getType());
Douglas Gregor0202cb42009-01-29 17:44:32 +0000558 }
John McCall23c29fe2011-06-24 21:55:10 +0000559 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000560 CGF.CGM.EmitExplicitCastExprType(E, &CGF);
John McCall23c29fe2011-06-24 21:55:10 +0000561 return VisitCastExpr(E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000562 }
John McCall23c29fe2011-06-24 21:55:10 +0000563 Value *VisitCastExpr(CastExpr *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000564
565 Value *VisitCallExpr(const CallExpr *E) {
David Majnemerced8bdf2015-02-25 17:36:15 +0000566 if (E->getCallReturnType(CGF.getContext())->isReferenceType())
Anders Carlssond8b7ae22009-05-27 03:37:57 +0000567 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000568
Hal Finkel64567a82014-10-04 15:26:49 +0000569 Value *V = CGF.EmitCallExpr(E).getScalarVal();
570
571 EmitLValueAlignmentAssumption(E, V);
572 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000573 }
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000574
Chris Lattner04a913b2007-08-31 22:09:40 +0000575 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000576
Chris Lattner2da04b32007-08-24 05:35:26 +0000577 // Unary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000578 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000579 LValue LV = EmitLValue(E->getSubExpr());
580 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000581 }
582 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000583 LValue LV = EmitLValue(E->getSubExpr());
584 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000585 }
586 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000587 LValue LV = EmitLValue(E->getSubExpr());
588 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000589 }
590 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000591 LValue LV = EmitLValue(E->getSubExpr());
592 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000593 }
Chris Lattner05dc78c2010-06-26 22:09:34 +0000594
Alexey Samsonovf6246502015-04-23 01:50:45 +0000595 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
596 llvm::Value *InVal,
597 bool IsInc);
Anton Yartsev85129b82011-02-07 02:17:30 +0000598
Chris Lattner05dc78c2010-06-26 22:09:34 +0000599 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
600 bool isInc, bool isPre);
601
Craig Toppera97d7e72013-07-26 06:16:11 +0000602
Chris Lattner2da04b32007-08-24 05:35:26 +0000603 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCallf3a88602011-02-03 08:15:49 +0000604 if (isa<MemberPointerType>(E->getType())) // never sugared
605 return CGF.CGM.getMemberPointerConstant(E);
606
John McCall7f416cc2015-09-08 08:05:57 +0000607 return EmitLValue(E->getSubExpr()).getPointer();
Chris Lattner2da04b32007-08-24 05:35:26 +0000608 }
John McCall59482722010-12-04 12:43:24 +0000609 Value *VisitUnaryDeref(const UnaryOperator *E) {
610 if (E->getType()->isVoidType())
611 return Visit(E->getSubExpr()); // the actual value should be unused
612 return EmitLoadOfLValue(E);
613 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000614 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000615 // This differs from gcc, though, most likely due to a bug in gcc.
616 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +0000617 return Visit(E->getSubExpr());
618 }
619 Value *VisitUnaryMinus (const UnaryOperator *E);
620 Value *VisitUnaryNot (const UnaryOperator *E);
621 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner9f0ad962007-08-24 21:20:17 +0000622 Value *VisitUnaryReal (const UnaryOperator *E);
623 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000624 Value *VisitUnaryExtension(const UnaryOperator *E) {
625 return Visit(E->getSubExpr());
626 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000627
Anders Carlssona5d077d2009-04-14 16:58:56 +0000628 // C++
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000629 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedman0be39702011-08-14 04:50:34 +0000630 return EmitLoadOfLValue(E);
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000631 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000632
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000633 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
634 return Visit(DAE->getExpr());
635 }
Richard Smith852c9db2013-04-20 22:23:05 +0000636 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
637 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
638 return Visit(DIE->getExpr());
639 }
Anders Carlssona5d077d2009-04-14 16:58:56 +0000640 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
641 return CGF.LoadCXXThis();
Mike Stump4a3999f2009-09-09 13:00:44 +0000642 }
643
Reid Kleckner092d0652017-03-06 22:18:34 +0000644 Value *VisitExprWithCleanups(ExprWithCleanups *E);
Anders Carlsson4a7b49b2009-05-31 01:40:14 +0000645 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
646 return CGF.EmitCXXNewExpr(E);
647 }
Anders Carlsson81f0df92009-08-16 21:13:42 +0000648 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
649 CGF.EmitCXXDeleteExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000650 return nullptr;
Anders Carlsson81f0df92009-08-16 21:13:42 +0000651 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000652
Alp Tokercbb90342013-12-13 20:49:58 +0000653 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
Francois Pichet34b21132010-12-08 22:35:30 +0000654 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet9dfa3ce2010-12-07 00:08:36 +0000655 }
656
John Wiegley6242b6a2011-04-28 00:16:57 +0000657 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
658 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
659 }
660
John Wiegleyf9f65842011-04-25 06:54:41 +0000661 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
662 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
663 }
664
Douglas Gregorad8a3362009-09-04 17:36:40 +0000665 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
666 // C++ [expr.pseudo]p1:
Mike Stump4a3999f2009-09-09 13:00:44 +0000667 // The result shall only be used as the operand for the function call
Douglas Gregorad8a3362009-09-04 17:36:40 +0000668 // operator (), and the result of such a call has type void. The only
669 // effect is the evaluation of the postfix-expression before the dot or
670 // arrow.
671 CGF.EmitScalarExpr(E->getBase());
Craig Topper8a13c412014-05-21 05:09:00 +0000672 return nullptr;
Douglas Gregorad8a3362009-09-04 17:36:40 +0000673 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000674
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000675 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000676 return EmitNullValue(E->getType());
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000677 }
Anders Carlsson4b08db72009-10-30 01:42:31 +0000678
679 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
680 CGF.EmitCXXThrowExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000681 return nullptr;
Anders Carlsson4b08db72009-10-30 01:42:31 +0000682 }
683
Sebastian Redlb67655f2010-09-10 21:04:00 +0000684 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000685 return Builder.getInt1(E->getValue());
Sebastian Redlb67655f2010-09-10 21:04:00 +0000686 }
687
Chris Lattner2da04b32007-08-24 05:35:26 +0000688 // Binary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000689 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000690 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000691 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +0000692 case LangOptions::SOB_Defined:
693 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith3e056de2012-08-25 00:32:28 +0000694 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000695 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +0000696 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000697 LLVM_FALLTHROUGH;
Chris Lattner51924e512010-06-26 21:25:03 +0000698 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000699 if (CanElideOverflowCheck(CGF.getContext(), Ops))
700 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner51924e512010-06-26 21:25:03 +0000701 return EmitOverflowCheckedBinOp(Ops);
702 }
703 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000704
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000705 if (Ops.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000706 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
707 !CanElideOverflowCheck(CGF.getContext(), Ops))
Will Dietz1897cb32012-11-27 15:01:55 +0000708 return EmitOverflowCheckedBinOp(Ops);
709
Adam Nemet370d0872017-04-04 21:18:30 +0000710 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
711 Value *V = Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
712 return propagateFMFlags(V, Ops);
713 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000714 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
715 }
Mike Stump0c61b732009-04-01 20:28:16 +0000716 /// Create a binary op that checks for overflow.
717 /// Currently only supports +, - and *.
718 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith4d1458e2012-09-08 02:08:36 +0000719
Chris Lattner8ee6a412010-09-11 21:47:09 +0000720 // Check for undefined division and modulus behaviors.
Craig Toppera97d7e72013-07-26 06:16:11 +0000721 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
Chris Lattner8ee6a412010-09-11 21:47:09 +0000722 llvm::Value *Zero,bool isDiv);
David Tweed042e0882013-01-07 16:43:27 +0000723 // Common helper for getting how wide LHS of shift is.
724 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
Chris Lattner2da04b32007-08-24 05:35:26 +0000725 Value *EmitDiv(const BinOpInfo &Ops);
726 Value *EmitRem(const BinOpInfo &Ops);
727 Value *EmitAdd(const BinOpInfo &Ops);
728 Value *EmitSub(const BinOpInfo &Ops);
729 Value *EmitShl(const BinOpInfo &Ops);
730 Value *EmitShr(const BinOpInfo &Ops);
731 Value *EmitAnd(const BinOpInfo &Ops) {
732 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
733 }
734 Value *EmitXor(const BinOpInfo &Ops) {
735 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
736 }
737 Value *EmitOr (const BinOpInfo &Ops) {
738 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
739 }
740
Leonard Chan2044ac82019-01-16 18:13:59 +0000741 // Helper functions for fixed point binary operations.
Leonard Chan837da5d2019-01-16 19:53:50 +0000742 Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
Leonard Chan2044ac82019-01-16 18:13:59 +0000743
Chris Lattner3d966d62007-08-24 21:00:35 +0000744 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor914af212010-04-23 04:16:32 +0000745 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
746 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +0000747 Value *&Result);
Douglas Gregor914af212010-04-23 04:16:32 +0000748
Chris Lattnerb6334692007-08-26 21:41:21 +0000749 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner3d966d62007-08-24 21:00:35 +0000750 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
751
752 // Binary operators and binary compound assignment operators.
753#define HANDLEBINOP(OP) \
Chris Lattnerb6334692007-08-26 21:41:21 +0000754 Value *VisitBin ## OP(const BinaryOperator *E) { \
755 return Emit ## OP(EmitBinOps(E)); \
756 } \
757 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
758 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner3d966d62007-08-24 21:00:35 +0000759 }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000760 HANDLEBINOP(Mul)
761 HANDLEBINOP(Div)
762 HANDLEBINOP(Rem)
763 HANDLEBINOP(Add)
764 HANDLEBINOP(Sub)
765 HANDLEBINOP(Shl)
766 HANDLEBINOP(Shr)
767 HANDLEBINOP(And)
768 HANDLEBINOP(Xor)
769 HANDLEBINOP(Or)
Chris Lattner3d966d62007-08-24 21:00:35 +0000770#undef HANDLEBINOP
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +0000771
Chris Lattner2da04b32007-08-24 05:35:26 +0000772 // Comparisons.
Craig Topperc82f8962015-12-16 06:24:28 +0000773 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
774 llvm::CmpInst::Predicate SICmpOpc,
775 llvm::CmpInst::Predicate FCmpOpc);
Chris Lattner2da04b32007-08-24 05:35:26 +0000776#define VISITCOMP(CODE, UI, SI, FP) \
777 Value *VisitBin##CODE(const BinaryOperator *E) { \
778 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
779 llvm::FCmpInst::FP); }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000780 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT)
781 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT)
782 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE)
783 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE)
784 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ)
785 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE)
Chris Lattner2da04b32007-08-24 05:35:26 +0000786#undef VISITCOMP
Mike Stump4a3999f2009-09-09 13:00:44 +0000787
Chris Lattner2da04b32007-08-24 05:35:26 +0000788 Value *VisitBinAssign (const BinaryOperator *E);
789
790 Value *VisitBinLAnd (const BinaryOperator *E);
791 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000792 Value *VisitBinComma (const BinaryOperator *E);
793
Eli Friedmanacfb1df2009-11-18 09:41:26 +0000794 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
795 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
796
Chris Lattner2da04b32007-08-24 05:35:26 +0000797 // Other Operators.
Mike Stumpab3afd82009-02-12 18:29:15 +0000798 Value *VisitBlockExpr(const BlockExpr *BE);
John McCallc07a0c72011-02-17 10:25:35 +0000799 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner2da04b32007-08-24 05:35:26 +0000800 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000801 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000802 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
803 return CGF.EmitObjCStringLiteral(E);
804 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000805 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
806 return CGF.EmitObjCBoxedExpr(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000807 }
808 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
809 return CGF.EmitObjCArrayLiteral(E);
810 }
811 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
812 return CGF.EmitObjCDictionaryLiteral(E);
813 }
Tanya Lattner55808c12011-06-04 00:47:47 +0000814 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000815 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000816};
817} // end anonymous namespace.
818
819//===----------------------------------------------------------------------===//
820// Utilities
821//===----------------------------------------------------------------------===//
822
Chris Lattnere0044382007-08-26 16:42:57 +0000823/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000824/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000825Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCallb692a092009-10-22 20:10:53 +0000826 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stump4a3999f2009-09-09 13:00:44 +0000827
John McCall8cb679e2010-11-15 09:13:47 +0000828 if (SrcType->isRealFloatingType())
829 return EmitFloatToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000830
John McCall7a9aac22010-08-23 01:21:21 +0000831 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
832 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stump4a3999f2009-09-09 13:00:44 +0000833
Daniel Dunbaref957f32008-08-25 10:38:11 +0000834 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnere0044382007-08-26 16:42:57 +0000835 "Unknown scalar type to convert");
Mike Stump4a3999f2009-09-09 13:00:44 +0000836
John McCall8cb679e2010-11-15 09:13:47 +0000837 if (isa<llvm::IntegerType>(Src->getType()))
838 return EmitIntToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000839
John McCall8cb679e2010-11-15 09:13:47 +0000840 assert(isa<llvm::PointerType>(Src->getType()));
Yaxun Liu402804b2016-12-15 08:09:08 +0000841 return EmitPointerToBoolConversion(Src, SrcType);
Chris Lattnere0044382007-08-26 16:42:57 +0000842}
843
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000844void ScalarExprEmitter::EmitFloatConversionCheck(
845 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
846 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
Alexey Samsonov24cad992014-07-17 18:46:27 +0000847 CodeGenFunction::SanitizerScope SanScope(&CGF);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000848 using llvm::APFloat;
849 using llvm::APSInt;
850
851 llvm::Type *SrcTy = Src->getType();
852
Craig Topper8a13c412014-05-21 05:09:00 +0000853 llvm::Value *Check = nullptr;
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000854 if (llvm::IntegerType *IntTy = dyn_cast<llvm::IntegerType>(SrcTy)) {
855 // Integer to floating-point. This can fail for unsigned short -> __half
856 // or unsigned __int128 -> float.
857 assert(DstType->isFloatingType());
858 bool SrcIsUnsigned = OrigSrcType->isUnsignedIntegerOrEnumerationType();
859
860 APFloat LargestFloat =
861 APFloat::getLargest(CGF.getContext().getFloatTypeSemantics(DstType));
862 APSInt LargestInt(IntTy->getBitWidth(), SrcIsUnsigned);
863
864 bool IsExact;
865 if (LargestFloat.convertToInteger(LargestInt, APFloat::rmTowardZero,
866 &IsExact) != APFloat::opOK)
867 // The range of representable values of this floating point type includes
868 // all values of this integer type. Don't need an overflow check.
869 return;
870
871 llvm::Value *Max = llvm::ConstantInt::get(VMContext, LargestInt);
872 if (SrcIsUnsigned)
873 Check = Builder.CreateICmpULE(Src, Max);
874 else {
875 llvm::Value *Min = llvm::ConstantInt::get(VMContext, -LargestInt);
876 llvm::Value *GE = Builder.CreateICmpSGE(Src, Min);
877 llvm::Value *LE = Builder.CreateICmpSLE(Src, Max);
878 Check = Builder.CreateAnd(GE, LE);
879 }
880 } else {
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000881 const llvm::fltSemantics &SrcSema =
882 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000883 if (isa<llvm::IntegerType>(DstTy)) {
Richard Smith2b01d502013-03-27 23:20:25 +0000884 // Floating-point to integer. This has undefined behavior if the source is
885 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
886 // to an integer).
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000887 unsigned Width = CGF.getContext().getIntWidth(DstType);
888 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
889
890 APSInt Min = APSInt::getMinValue(Width, Unsigned);
Richard Smith2b01d502013-03-27 23:20:25 +0000891 APFloat MinSrc(SrcSema, APFloat::uninitialized);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000892 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
893 APFloat::opOverflow)
894 // Don't need an overflow check for lower bound. Just check for
895 // -Inf/NaN.
Richard Smith4af40c42013-03-19 00:01:12 +0000896 MinSrc = APFloat::getInf(SrcSema, true);
897 else
898 // Find the largest value which is too small to represent (before
899 // truncation toward zero).
900 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000901
902 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
Richard Smith2b01d502013-03-27 23:20:25 +0000903 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000904 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
905 APFloat::opOverflow)
906 // Don't need an overflow check for upper bound. Just check for
907 // +Inf/NaN.
Richard Smith4af40c42013-03-19 00:01:12 +0000908 MaxSrc = APFloat::getInf(SrcSema, false);
909 else
910 // Find the smallest value which is too large to represent (before
911 // truncation toward zero).
912 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000913
Richard Smith2b01d502013-03-27 23:20:25 +0000914 // If we're converting from __half, convert the range to float to match
915 // the type of src.
916 if (OrigSrcType->isHalfType()) {
917 const llvm::fltSemantics &Sema =
918 CGF.getContext().getFloatTypeSemantics(SrcType);
919 bool IsInexact;
920 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
921 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
922 }
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000923
Richard Smith4af40c42013-03-19 00:01:12 +0000924 llvm::Value *GE =
925 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
926 llvm::Value *LE =
927 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
928 Check = Builder.CreateAnd(GE, LE);
929 } else {
Richard Smith2b01d502013-03-27 23:20:25 +0000930 // FIXME: Maybe split this sanitizer out from float-cast-overflow.
931 //
932 // Floating-point to floating-point. This has undefined behavior if the
933 // source is not in the range of representable values of the destination
934 // type. The C and C++ standards are spectacularly unclear here. We
935 // diagnose finite out-of-range conversions, but allow infinities and NaNs
936 // to convert to the corresponding value in the smaller type.
937 //
938 // C11 Annex F gives all such conversions defined behavior for IEC 60559
939 // conforming implementations. Unfortunately, LLVM's fptrunc instruction
940 // does not.
941
942 // Converting from a lower rank to a higher rank can never have
943 // undefined behavior, since higher-rank types must have a superset
944 // of values of lower-rank types.
945 if (CGF.getContext().getFloatingTypeOrder(OrigSrcType, DstType) != 1)
946 return;
947
948 assert(!OrigSrcType->isHalfType() &&
949 "should not check conversion from __half, it has the lowest rank");
950
951 const llvm::fltSemantics &DstSema =
952 CGF.getContext().getFloatTypeSemantics(DstType);
953 APFloat MinBad = APFloat::getLargest(DstSema, false);
954 APFloat MaxBad = APFloat::getInf(DstSema, false);
955
956 bool IsInexact;
957 MinBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
958 MaxBad.convert(SrcSema, APFloat::rmTowardZero, &IsInexact);
959
960 Value *AbsSrc = CGF.EmitNounwindRuntimeCall(
961 CGF.CGM.getIntrinsic(llvm::Intrinsic::fabs, Src->getType()), Src);
Richard Smith4af40c42013-03-19 00:01:12 +0000962 llvm::Value *GE =
Richard Smith2b01d502013-03-27 23:20:25 +0000963 Builder.CreateFCmpOGT(AbsSrc, llvm::ConstantFP::get(VMContext, MinBad));
Richard Smith4af40c42013-03-19 00:01:12 +0000964 llvm::Value *LE =
Richard Smith2b01d502013-03-27 23:20:25 +0000965 Builder.CreateFCmpOLT(AbsSrc, llvm::ConstantFP::get(VMContext, MaxBad));
966 Check = Builder.CreateNot(Builder.CreateAnd(GE, LE));
Richard Smith4af40c42013-03-19 00:01:12 +0000967 }
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000968 }
969
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000970 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
971 CGF.EmitCheckTypeDescriptor(OrigSrcType),
972 CGF.EmitCheckTypeDescriptor(DstType)};
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000973 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000974 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000975}
976
Roman Lebedev62debd802018-10-30 21:58:56 +0000977// Should be called within CodeGenFunction::SanitizerScope RAII scope.
978// Returns 'i1 false' when the truncation Src -> Dst was lossy.
979static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
980 std::pair<llvm::Value *, SanitizerMask>>
981EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
982 QualType DstType, CGBuilderTy &Builder) {
983 llvm::Type *SrcTy = Src->getType();
984 llvm::Type *DstTy = Dst->getType();
Richard Trieu161121f2018-10-30 23:01:15 +0000985 (void)DstTy; // Only used in assert()
Roman Lebedev62debd802018-10-30 21:58:56 +0000986
987 // This should be truncation of integral types.
988 assert(Src != Dst);
989 assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
990 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
991 "non-integer llvm type");
992
993 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
994 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
995
996 // If both (src and dst) types are unsigned, then it's an unsigned truncation.
997 // Else, it is a signed truncation.
998 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
999 SanitizerMask Mask;
1000 if (!SrcSigned && !DstSigned) {
1001 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1002 Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
1003 } else {
1004 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1005 Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
1006 }
1007
1008 llvm::Value *Check = nullptr;
1009 // 1. Extend the truncated value back to the same width as the Src.
1010 Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
1011 // 2. Equality-compare with the original source value
1012 Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
1013 // If the comparison result is 'i1 false', then the truncation was lossy.
1014 return std::make_pair(Kind, std::make_pair(Check, Mask));
1015}
1016
Roman Lebedevb69ba222018-07-30 18:58:30 +00001017void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
1018 Value *Dst, QualType DstType,
1019 SourceLocation Loc) {
Roman Lebedevdd403572018-10-11 09:09:50 +00001020 if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
Roman Lebedevb69ba222018-07-30 18:58:30 +00001021 return;
1022
Roman Lebedev62debd802018-10-30 21:58:56 +00001023 // We only care about int->int conversions here.
1024 // We ignore conversions to/from pointer and/or bool.
1025 if (!(SrcType->isIntegerType() && DstType->isIntegerType()))
1026 return;
1027
1028 unsigned SrcBits = Src->getType()->getScalarSizeInBits();
1029 unsigned DstBits = Dst->getType()->getScalarSizeInBits();
1030 // This must be truncation. Else we do not care.
1031 if (SrcBits <= DstBits)
1032 return;
1033
1034 assert(!DstType->isBooleanType() && "we should not get here with booleans.");
1035
1036 // If the integer sign change sanitizer is enabled,
1037 // and we are truncating from larger unsigned type to smaller signed type,
1038 // let that next sanitizer deal with it.
1039 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1040 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1041 if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
1042 (!SrcSigned && DstSigned))
1043 return;
1044
1045 CodeGenFunction::SanitizerScope SanScope(&CGF);
1046
1047 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1048 std::pair<llvm::Value *, SanitizerMask>>
1049 Check =
1050 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1051 // If the comparison result is 'i1 false', then the truncation was lossy.
1052
1053 // Do we care about this type of truncation?
1054 if (!CGF.SanOpts.has(Check.second.second))
1055 return;
1056
1057 llvm::Constant *StaticArgs[] = {
1058 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1059 CGF.EmitCheckTypeDescriptor(DstType),
1060 llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
1061 CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
1062 {Src, Dst});
1063}
1064
1065// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1066// Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1067static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1068 std::pair<llvm::Value *, SanitizerMask>>
1069EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1070 QualType DstType, CGBuilderTy &Builder) {
1071 llvm::Type *SrcTy = Src->getType();
1072 llvm::Type *DstTy = Dst->getType();
1073
1074 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1075 "non-integer llvm type");
1076
1077 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1078 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
Richard Trieu161121f2018-10-30 23:01:15 +00001079 (void)SrcSigned; // Only used in assert()
1080 (void)DstSigned; // Only used in assert()
Roman Lebedev62debd802018-10-30 21:58:56 +00001081 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1082 unsigned DstBits = DstTy->getScalarSizeInBits();
1083 (void)SrcBits; // Only used in assert()
1084 (void)DstBits; // Only used in assert()
1085
1086 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1087 "either the widths should be different, or the signednesses.");
1088
1089 // NOTE: zero value is considered to be non-negative.
1090 auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
1091 const char *Name) -> Value * {
1092 // Is this value a signed type?
1093 bool VSigned = VType->isSignedIntegerOrEnumerationType();
1094 llvm::Type *VTy = V->getType();
1095 if (!VSigned) {
1096 // If the value is unsigned, then it is never negative.
1097 // FIXME: can we encounter non-scalar VTy here?
1098 return llvm::ConstantInt::getFalse(VTy->getContext());
1099 }
1100 // Get the zero of the same type with which we will be comparing.
1101 llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
1102 // %V.isnegative = icmp slt %V, 0
1103 // I.e is %V *strictly* less than zero, does it have negative value?
1104 return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
1105 llvm::Twine(Name) + "." + V->getName() +
1106 ".negativitycheck");
1107 };
1108
1109 // 1. Was the old Value negative?
1110 llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
1111 // 2. Is the new Value negative?
1112 llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
1113 // 3. Now, was the 'negativity status' preserved during the conversion?
1114 // NOTE: conversion from negative to zero is considered to change the sign.
1115 // (We want to get 'false' when the conversion changed the sign)
1116 // So we should just equality-compare the negativity statuses.
1117 llvm::Value *Check = nullptr;
1118 Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
1119 // If the comparison result is 'false', then the conversion changed the sign.
1120 return std::make_pair(
1121 ScalarExprEmitter::ICCK_IntegerSignChange,
1122 std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
1123}
1124
1125void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1126 Value *Dst, QualType DstType,
1127 SourceLocation Loc) {
1128 if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
1129 return;
1130
Roman Lebedevb69ba222018-07-30 18:58:30 +00001131 llvm::Type *SrcTy = Src->getType();
1132 llvm::Type *DstTy = Dst->getType();
1133
1134 // We only care about int->int conversions here.
1135 // We ignore conversions to/from pointer and/or bool.
1136 if (!(SrcType->isIntegerType() && DstType->isIntegerType()))
1137 return;
1138
Roman Lebedevdd403572018-10-11 09:09:50 +00001139 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1140 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
Roman Lebedev62debd802018-10-30 21:58:56 +00001141 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1142 unsigned DstBits = DstTy->getScalarSizeInBits();
Roman Lebedevdd403572018-10-11 09:09:50 +00001143
Roman Lebedev62debd802018-10-30 21:58:56 +00001144 // Now, we do not need to emit the check in *all* of the cases.
1145 // We can avoid emitting it in some obvious cases where it would have been
1146 // dropped by the opt passes (instcombine) always anyways.
Roman Lebedev1bb9aea2018-11-01 08:56:51 +00001147 // If it's a cast between effectively the same type, no check.
1148 // NOTE: this is *not* equivalent to checking the canonical types.
1149 if (SrcSigned == DstSigned && SrcBits == DstBits)
Roman Lebedevdd403572018-10-11 09:09:50 +00001150 return;
Roman Lebedev62debd802018-10-30 21:58:56 +00001151 // At least one of the values needs to have signed type.
1152 // If both are unsigned, then obviously, neither of them can be negative.
1153 if (!SrcSigned && !DstSigned)
1154 return;
1155 // If the conversion is to *larger* *signed* type, then no check is needed.
1156 // Because either sign-extension happens (so the sign will remain),
1157 // or zero-extension will happen (the sign bit will be zero.)
1158 if ((DstBits > SrcBits) && DstSigned)
1159 return;
1160 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1161 (SrcBits > DstBits) && SrcSigned) {
1162 // If the signed integer truncation sanitizer is enabled,
1163 // and this is a truncation from signed type, then no check is needed.
1164 // Because here sign change check is interchangeable with truncation check.
1165 return;
1166 }
1167 // That's it. We can't rule out any more cases with the data we have.
Roman Lebedevdd403572018-10-11 09:09:50 +00001168
Roman Lebedevb69ba222018-07-30 18:58:30 +00001169 CodeGenFunction::SanitizerScope SanScope(&CGF);
1170
Roman Lebedev62debd802018-10-30 21:58:56 +00001171 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1172 std::pair<llvm::Value *, SanitizerMask>>
1173 Check;
Roman Lebedevb69ba222018-07-30 18:58:30 +00001174
Roman Lebedev62debd802018-10-30 21:58:56 +00001175 // Each of these checks needs to return 'false' when an issue was detected.
1176 ImplicitConversionCheckKind CheckKind;
1177 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
1178 // So we can 'and' all the checks together, and still get 'false',
1179 // if at least one of the checks detected an issue.
1180
1181 Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1182 CheckKind = Check.first;
1183 Checks.emplace_back(Check.second);
1184
1185 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1186 (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1187 // If the signed integer truncation sanitizer was enabled,
1188 // and we are truncating from larger unsigned type to smaller signed type,
1189 // let's handle the case we skipped in that check.
1190 Check =
1191 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1192 CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1193 Checks.emplace_back(Check.second);
1194 // If the comparison result is 'i1 false', then the truncation was lossy.
1195 }
Roman Lebedevb69ba222018-07-30 18:58:30 +00001196
1197 llvm::Constant *StaticArgs[] = {
1198 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1199 CGF.EmitCheckTypeDescriptor(DstType),
Roman Lebedev62debd802018-10-30 21:58:56 +00001200 llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
1201 // EmitCheck() will 'and' all the checks together.
1202 CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
1203 {Src, Dst});
Roman Lebedevb69ba222018-07-30 18:58:30 +00001204}
1205
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00001206/// Emit a conversion from the specified type to the specified destination type,
1207/// both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00001208Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001209 QualType DstType,
Anastasia Stulovab02e7832015-10-05 11:27:41 +00001210 SourceLocation Loc,
Roman Lebedevb69ba222018-07-30 18:58:30 +00001211 ScalarConversionOpts Opts) {
Leonard Chanb4ba4672018-10-23 17:55:35 +00001212 // All conversions involving fixed point types should be handled by the
1213 // EmitFixedPoint family functions. This is done to prevent bloating up this
1214 // function more, and although fixed point numbers are represented by
1215 // integers, we do not want to follow any logic that assumes they should be
1216 // treated as integers.
1217 // TODO(leonardchan): When necessary, add another if statement checking for
1218 // conversions to fixed point types from other types.
1219 if (SrcType->isFixedPointType()) {
1220 if (DstType->isFixedPointType()) {
1221 return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1222 } else if (DstType->isBooleanType()) {
1223 // We do not need to check the padding bit on unsigned types if unsigned
1224 // padding is enabled because overflow into this bit is undefined
1225 // behavior.
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001226 return Builder.CreateIsNotNull(Src, "tobool");
Leonard Chanb4ba4672018-10-23 17:55:35 +00001227 }
1228
1229 llvm_unreachable(
1230 "Unhandled scalar conversion involving a fixed point type.");
1231 }
Leonard Chan99bda372018-10-15 16:07:02 +00001232
Roman Lebedevb69ba222018-07-30 18:58:30 +00001233 QualType NoncanonicalSrcType = SrcType;
1234 QualType NoncanonicalDstType = DstType;
1235
Chris Lattner0f398c42008-07-26 22:37:01 +00001236 SrcType = CGF.getContext().getCanonicalType(SrcType);
1237 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3474c202007-08-26 06:48:56 +00001238 if (SrcType == DstType) return Src;
Mike Stump4a3999f2009-09-09 13:00:44 +00001239
Craig Topper8a13c412014-05-21 05:09:00 +00001240 if (DstType->isVoidType()) return nullptr;
Mike Stump4a3999f2009-09-09 13:00:44 +00001241
Richard Smithf9a1e4a2012-10-12 22:57:06 +00001242 llvm::Value *OrigSrc = Src;
1243 QualType OrigSrcType = SrcType;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001244 llvm::Type *SrcTy = Src->getType();
1245
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +00001246 // Handle conversions to bool first, they are special: comparisons against 0.
1247 if (DstType->isBooleanType())
1248 return EmitConversionToBool(Src, SrcType);
1249
1250 llvm::Type *DstTy = ConvertType(DstType);
1251
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001252 // Cast from half through float if half isn't a native type.
1253 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1254 // Cast to FP using the intrinsic if the half type itself isn't supported.
1255 if (DstTy->isFloatingPointTy()) {
Akira Hatanaka502775a2017-12-09 00:02:37 +00001256 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001257 return Builder.CreateCall(
1258 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
1259 Src);
1260 } else {
1261 // Cast to other types through float, using either the intrinsic or FPExt,
1262 // depending on whether the half type itself is supported
1263 // (as opposed to operations on half, available with NativeHalfType).
Akira Hatanaka502775a2017-12-09 00:02:37 +00001264 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001265 Src = Builder.CreateCall(
1266 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1267 CGF.CGM.FloatTy),
1268 Src);
1269 } else {
1270 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
1271 }
1272 SrcType = CGF.getContext().FloatTy;
1273 SrcTy = CGF.FloatTy;
1274 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001275 }
1276
Chris Lattner3474c202007-08-26 06:48:56 +00001277 // Ignore conversions like int -> uint.
Roman Lebedev62debd802018-10-30 21:58:56 +00001278 if (SrcTy == DstTy) {
1279 if (Opts.EmitImplicitIntegerSignChangeChecks)
1280 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
1281 NoncanonicalDstType, Loc);
1282
Chris Lattner3474c202007-08-26 06:48:56 +00001283 return Src;
Roman Lebedev62debd802018-10-30 21:58:56 +00001284 }
Chris Lattner3474c202007-08-26 06:48:56 +00001285
Mike Stump4a3999f2009-09-09 13:00:44 +00001286 // Handle pointer conversions next: pointers can only be converted to/from
1287 // other pointers and integers. Check for pointer types in terms of LLVM, as
1288 // some native types (like Obj-C id) may map to a pointer type.
Yaxun Liu26f75662016-08-19 05:17:25 +00001289 if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +00001290 // The source value may be an integer, or a pointer.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001291 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3474c202007-08-26 06:48:56 +00001292 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson12f5a252009-09-12 04:57:16 +00001293
Chris Lattner3474c202007-08-26 06:48:56 +00001294 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman42d2a3a2009-03-04 04:02:35 +00001295 // First, convert to the correct width so that we control the kind of
1296 // extension.
Yaxun Liu26f75662016-08-19 05:17:25 +00001297 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001298 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman42d2a3a2009-03-04 04:02:35 +00001299 llvm::Value* IntResult =
1300 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1301 // Then, cast to pointer.
1302 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +00001303 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001304
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001305 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +00001306 // Must be an ptr to int cast.
1307 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlssone89b84a2007-10-31 23:18:02 +00001308 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +00001309 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001310
Nate Begemance4d7fc2008-04-18 23:10:10 +00001311 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman5ec4b312009-08-10 23:49:36 +00001312 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
George Burgess IVdf1ed002016-01-13 01:52:39 +00001313 // Sema should add casts to make sure that the source expression's type is
1314 // the same as the vector's element type (sans qualifiers)
1315 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1316 SrcType.getTypePtr() &&
1317 "Splatted expr doesn't match with vector element type?");
Nate Begemanb699c9b2009-01-18 06:42:49 +00001318
Nate Begemanb699c9b2009-01-18 06:42:49 +00001319 // Splat the element across to all elements
Craig Topperf2f1a092016-07-08 02:17:35 +00001320 unsigned NumElements = DstTy->getVectorNumElements();
George Burgess IVdf1ed002016-01-13 01:52:39 +00001321 return Builder.CreateVectorSplat(NumElements, Src, "splat");
Nate Begemanb699c9b2009-01-18 06:42:49 +00001322 }
Nate Begeman330aaa72007-12-30 02:59:45 +00001323
Akira Hatanaka34b5dbc2017-09-23 05:02:02 +00001324 if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
1325 // Allow bitcast from vector to integer/fp of the same size.
1326 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1327 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1328 if (SrcSize == DstSize)
1329 return Builder.CreateBitCast(Src, DstTy, "conv");
1330
1331 // Conversions between vectors of different sizes are not allowed except
1332 // when vectors of half are involved. Operations on storage-only half
1333 // vectors require promoting half vector operands to float vectors and
1334 // truncating the result, which is either an int or float vector, to a
1335 // short or half vector.
1336
1337 // Source and destination are both expected to be vectors.
1338 llvm::Type *SrcElementTy = SrcTy->getVectorElementType();
1339 llvm::Type *DstElementTy = DstTy->getVectorElementType();
Benjamin Kramer5c42bcc2017-09-23 16:08:48 +00001340 (void)DstElementTy;
Akira Hatanaka34b5dbc2017-09-23 05:02:02 +00001341
1342 assert(((SrcElementTy->isIntegerTy() &&
1343 DstElementTy->isIntegerTy()) ||
1344 (SrcElementTy->isFloatingPointTy() &&
1345 DstElementTy->isFloatingPointTy())) &&
1346 "unexpected conversion between a floating-point vector and an "
1347 "integer vector");
1348
1349 // Truncate an i32 vector to an i16 vector.
1350 if (SrcElementTy->isIntegerTy())
1351 return Builder.CreateIntCast(Src, DstTy, false, "conv");
1352
1353 // Truncate a float vector to a half vector.
1354 if (SrcSize > DstSize)
1355 return Builder.CreateFPTrunc(Src, DstTy, "conv");
1356
1357 // Promote a half vector to a float vector.
1358 return Builder.CreateFPExt(Src, DstTy, "conv");
1359 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001360
Chris Lattner3474c202007-08-26 06:48:56 +00001361 // Finally, we have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +00001362 Value *Res = nullptr;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001363 llvm::Type *ResTy = DstTy;
1364
Richard Smithf9a1e4a2012-10-12 22:57:06 +00001365 // An overflowing conversion has undefined behavior if either the source type
1366 // or the destination type is a floating-point type.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001367 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
Richard Smithf9a1e4a2012-10-12 22:57:06 +00001368 (OrigSrcType->isFloatingType() || DstType->isFloatingType()))
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001369 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1370 Loc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +00001371
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001372 // Cast to half through float if half isn't a native type.
1373 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1374 // Make sure we cast in a single step if from another FP type.
1375 if (SrcTy->isFloatingPointTy()) {
1376 // Use the intrinsic if the half type itself isn't supported
1377 // (as opposed to operations on half, available with NativeHalfType).
Akira Hatanaka502775a2017-12-09 00:02:37 +00001378 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001379 return Builder.CreateCall(
1380 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
1381 // If the half type is supported, just use an fptrunc.
1382 return Builder.CreateFPTrunc(Src, DstTy);
1383 }
Chris Lattnerece04092012-02-07 00:39:47 +00001384 DstTy = CGF.FloatTy;
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +00001385 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001386
1387 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001388 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Roman Lebedevb69ba222018-07-30 18:58:30 +00001389 if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) {
Anastasia Stulovab02e7832015-10-05 11:27:41 +00001390 InputSigned = true;
1391 }
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001392 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001393 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001394 else if (InputSigned)
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001395 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001396 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001397 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1398 } else if (isa<llvm::IntegerType>(DstTy)) {
1399 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001400 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001401 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001402 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001403 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1404 } else {
1405 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
1406 "Unknown real conversion");
1407 if (DstTy->getTypeID() < SrcTy->getTypeID())
1408 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1409 else
1410 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +00001411 }
1412
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001413 if (DstTy != ResTy) {
Akira Hatanaka502775a2017-12-09 00:02:37 +00001414 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001415 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
1416 Res = Builder.CreateCall(
Tim Northover6dbcbac2014-07-17 10:51:31 +00001417 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
1418 Res);
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001419 } else {
1420 Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
1421 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001422 }
1423
Roman Lebedevb69ba222018-07-30 18:58:30 +00001424 if (Opts.EmitImplicitIntegerTruncationChecks)
1425 EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
1426 NoncanonicalDstType, Loc);
1427
Roman Lebedev62debd802018-10-30 21:58:56 +00001428 if (Opts.EmitImplicitIntegerSignChangeChecks)
1429 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
1430 NoncanonicalDstType, Loc);
1431
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001432 return Res;
Chris Lattner3474c202007-08-26 06:48:56 +00001433}
1434
Leonard Chan99bda372018-10-15 16:07:02 +00001435Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1436 QualType DstTy,
1437 SourceLocation Loc) {
Leonard Chan99bda372018-10-15 16:07:02 +00001438 assert(SrcTy->isFixedPointType());
1439 assert(DstTy->isFixedPointType());
1440
1441 FixedPointSemantics SrcFPSema =
1442 CGF.getContext().getFixedPointSemantics(SrcTy);
1443 FixedPointSemantics DstFPSema =
1444 CGF.getContext().getFixedPointSemantics(DstTy);
Leonard Chan2044ac82019-01-16 18:13:59 +00001445 return EmitFixedPointConversion(Src, SrcFPSema, DstFPSema, Loc);
1446}
1447
1448Value *ScalarExprEmitter::EmitFixedPointConversion(
1449 Value *Src, FixedPointSemantics &SrcFPSema, FixedPointSemantics &DstFPSema,
1450 SourceLocation Loc) {
1451 using llvm::APInt;
1452 using llvm::ConstantInt;
1453 using llvm::Value;
1454
Leonard Chan99bda372018-10-15 16:07:02 +00001455 unsigned SrcWidth = SrcFPSema.getWidth();
1456 unsigned DstWidth = DstFPSema.getWidth();
1457 unsigned SrcScale = SrcFPSema.getScale();
1458 unsigned DstScale = DstFPSema.getScale();
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001459 bool SrcIsSigned = SrcFPSema.isSigned();
1460 bool DstIsSigned = DstFPSema.isSigned();
1461
1462 llvm::Type *DstIntTy = Builder.getIntNTy(DstWidth);
Leonard Chan99bda372018-10-15 16:07:02 +00001463
1464 Value *Result = Src;
1465 unsigned ResultWidth = SrcWidth;
1466
1467 if (!DstFPSema.isSaturated()) {
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001468 // Downscale.
1469 if (DstScale < SrcScale)
1470 Result = SrcIsSigned ?
1471 Builder.CreateAShr(Result, SrcScale - DstScale, "downscale") :
1472 Builder.CreateLShr(Result, SrcScale - DstScale, "downscale");
Leonard Chan99bda372018-10-15 16:07:02 +00001473
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001474 // Resize.
1475 Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
Leonard Chan99bda372018-10-15 16:07:02 +00001476
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001477 // Upscale.
Leonard Chan99bda372018-10-15 16:07:02 +00001478 if (DstScale > SrcScale)
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001479 Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
Leonard Chan99bda372018-10-15 16:07:02 +00001480 } else {
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001481 // Adjust the number of fractional bits.
Leonard Chan99bda372018-10-15 16:07:02 +00001482 if (DstScale > SrcScale) {
Leonard Chan2044ac82019-01-16 18:13:59 +00001483 // Compare to DstWidth to prevent resizing twice.
1484 ResultWidth = std::max(SrcWidth + DstScale - SrcScale, DstWidth);
Leonard Chan99bda372018-10-15 16:07:02 +00001485 llvm::Type *UpscaledTy = Builder.getIntNTy(ResultWidth);
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001486 Result = Builder.CreateIntCast(Result, UpscaledTy, SrcIsSigned, "resize");
1487 Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
Leonard Chan99bda372018-10-15 16:07:02 +00001488 } else if (DstScale < SrcScale) {
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001489 Result = SrcIsSigned ?
1490 Builder.CreateAShr(Result, SrcScale - DstScale, "downscale") :
1491 Builder.CreateLShr(Result, SrcScale - DstScale, "downscale");
Leonard Chan99bda372018-10-15 16:07:02 +00001492 }
1493
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001494 // Handle saturation.
1495 bool LessIntBits = DstFPSema.getIntegralBits() < SrcFPSema.getIntegralBits();
1496 if (LessIntBits) {
1497 Value *Max = ConstantInt::get(
Leonard Chan99bda372018-10-15 16:07:02 +00001498 CGF.getLLVMContext(),
1499 APFixedPoint::getMax(DstFPSema).getValue().extOrTrunc(ResultWidth));
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001500 Value *TooHigh = SrcIsSigned ? Builder.CreateICmpSGT(Result, Max)
1501 : Builder.CreateICmpUGT(Result, Max);
1502 Result = Builder.CreateSelect(TooHigh, Max, Result, "satmax");
1503 }
1504 // Cannot overflow min to dest type if src is unsigned since all fixed
1505 // point types can cover the unsigned min of 0.
1506 if (SrcIsSigned && (LessIntBits || !DstIsSigned)) {
1507 Value *Min = ConstantInt::get(
1508 CGF.getLLVMContext(),
1509 APFixedPoint::getMin(DstFPSema).getValue().extOrTrunc(ResultWidth));
1510 Value *TooLow = Builder.CreateICmpSLT(Result, Min);
1511 Result = Builder.CreateSelect(TooLow, Min, Result, "satmin");
Leonard Chan99bda372018-10-15 16:07:02 +00001512 }
1513
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001514 // Resize the integer part to get the final destination size.
Leonard Chan2044ac82019-01-16 18:13:59 +00001515 if (ResultWidth != DstWidth)
1516 Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
Leonard Chan99bda372018-10-15 16:07:02 +00001517 }
1518 return Result;
1519}
1520
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00001521/// Emit a conversion from the specified complex type to the specified
1522/// destination type, where the destination type is an LLVM scalar type.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001523Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1524 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1525 SourceLocation Loc) {
Chris Lattnerc141c1b2007-08-26 16:52:28 +00001526 // Get the source element type.
John McCall47fb9502013-03-07 21:37:08 +00001527 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001528
Chris Lattnerc141c1b2007-08-26 16:52:28 +00001529 // Handle conversions to bool first, they are special: comparisons against 0.
1530 if (DstTy->isBooleanType()) {
1531 // Complex != 0 -> (Real != 0) | (Imag != 0)
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001532 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1533 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
Chris Lattnerc141c1b2007-08-26 16:52:28 +00001534 return Builder.CreateOr(Src.first, Src.second, "tobool");
1535 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001536
Chris Lattner42e6b812007-08-26 16:34:22 +00001537 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1538 // the imaginary part of the complex value is discarded and the value of the
1539 // real part is converted according to the conversion rules for the
Mike Stump4a3999f2009-09-09 13:00:44 +00001540 // corresponding real type.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001541 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
Chris Lattner42e6b812007-08-26 16:34:22 +00001542}
1543
Anders Carlsson5b944432010-05-22 17:45:10 +00001544Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
Richard Smithd82a2ce2012-12-21 03:17:28 +00001545 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
Anders Carlsson5b944432010-05-22 17:45:10 +00001546}
Chris Lattner42e6b812007-08-26 16:34:22 +00001547
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001548/// Emit a sanitization check for the given "binary" operation (which
Richard Smithe30752c2012-10-09 19:52:38 +00001549/// might actually be a unary increment which has been lowered to a binary
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001550/// operation). The check passes if all values in \p Checks (which are \c i1),
1551/// are \c true.
1552void ScalarExprEmitter::EmitBinOpCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001553 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001554 assert(CGF.IsSanitizerScope);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001555 SanitizerHandler Check;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001556 SmallVector<llvm::Constant *, 4> StaticData;
1557 SmallVector<llvm::Value *, 2> DynamicData;
Richard Smithe30752c2012-10-09 19:52:38 +00001558
1559 BinaryOperatorKind Opcode = Info.Opcode;
1560 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
1561 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
1562
1563 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
1564 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1565 if (UO && UO->getOpcode() == UO_Minus) {
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001566 Check = SanitizerHandler::NegateOverflow;
Richard Smithe30752c2012-10-09 19:52:38 +00001567 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
1568 DynamicData.push_back(Info.RHS);
1569 } else {
1570 if (BinaryOperator::isShiftOp(Opcode)) {
1571 // Shift LHS negative or too large, or RHS out of bounds.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001572 Check = SanitizerHandler::ShiftOutOfBounds;
Richard Smithe30752c2012-10-09 19:52:38 +00001573 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
1574 StaticData.push_back(
1575 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
1576 StaticData.push_back(
1577 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
1578 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1579 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001580 Check = SanitizerHandler::DivremOverflow;
Will Dietzcefb4482013-01-07 22:25:52 +00001581 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +00001582 } else {
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001583 // Arithmetic overflow (+, -, *).
Richard Smithe30752c2012-10-09 19:52:38 +00001584 switch (Opcode) {
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001585 case BO_Add: Check = SanitizerHandler::AddOverflow; break;
1586 case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
1587 case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
Richard Smithe30752c2012-10-09 19:52:38 +00001588 default: llvm_unreachable("unexpected opcode for bin op check");
1589 }
Will Dietzcefb4482013-01-07 22:25:52 +00001590 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +00001591 }
1592 DynamicData.push_back(Info.LHS);
1593 DynamicData.push_back(Info.RHS);
1594 }
1595
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001596 CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
Richard Smithe30752c2012-10-09 19:52:38 +00001597}
1598
Chris Lattner2da04b32007-08-24 05:35:26 +00001599//===----------------------------------------------------------------------===//
1600// Visitor Methods
1601//===----------------------------------------------------------------------===//
1602
1603Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +00001604 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner2da04b32007-08-24 05:35:26 +00001605 if (E->getType()->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001606 return nullptr;
Owen Anderson7ec07a52009-07-30 23:11:26 +00001607 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner2da04b32007-08-24 05:35:26 +00001608}
1609
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001610Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begemana0110022010-06-08 00:16:34 +00001611 // Vector Mask Case
Craig Topperb3174a82016-05-18 04:11:25 +00001612 if (E->getNumSubExprs() == 2) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00001613 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
1614 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
1615 Value *Mask;
Craig Toppera97d7e72013-07-26 06:16:11 +00001616
Chris Lattner2192fe52011-07-18 04:24:23 +00001617 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begemana0110022010-06-08 00:16:34 +00001618 unsigned LHSElts = LTy->getNumElements();
1619
Craig Topperb3174a82016-05-18 04:11:25 +00001620 Mask = RHS;
Craig Toppera97d7e72013-07-26 06:16:11 +00001621
Chris Lattner2192fe52011-07-18 04:24:23 +00001622 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001623
Nate Begemana0110022010-06-08 00:16:34 +00001624 // Mask off the high bits of each shuffle index.
Benjamin Kramer99383102015-07-28 16:25:32 +00001625 Value *MaskBits =
1626 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
Nate Begemana0110022010-06-08 00:16:34 +00001627 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
Craig Toppera97d7e72013-07-26 06:16:11 +00001628
Nate Begemana0110022010-06-08 00:16:34 +00001629 // newv = undef
1630 // mask = mask & maskbits
1631 // for each elt
1632 // n = extract mask i
1633 // x = extract val n
1634 // newv = insert newv, x, i
Chris Lattner2192fe52011-07-18 04:24:23 +00001635 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Craig Topper18243fb2013-07-27 05:00:42 +00001636 MTy->getNumElements());
Nate Begemana0110022010-06-08 00:16:34 +00001637 Value* NewV = llvm::UndefValue::get(RTy);
1638 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Michael J. Spencerdd597752014-05-31 00:22:12 +00001639 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
Eli Friedman1fa36052012-04-05 21:48:40 +00001640 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Craig Toppera97d7e72013-07-26 06:16:11 +00001641
Nate Begemana0110022010-06-08 00:16:34 +00001642 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman1fa36052012-04-05 21:48:40 +00001643 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begemana0110022010-06-08 00:16:34 +00001644 }
1645 return NewV;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001646 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001647
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001648 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1649 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Craig Toppera97d7e72013-07-26 06:16:11 +00001650
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001651 SmallVector<llvm::Constant*, 32> indices;
Craig Topper0ed37bd2013-08-01 04:51:48 +00001652 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
Craig Topper50ad5b72013-08-03 17:40:38 +00001653 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1654 // Check for -1 and output it as undef in the IR.
1655 if (Idx.isSigned() && Idx.isAllOnesValue())
1656 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1657 else
1658 indices.push_back(Builder.getInt32(Idx.getZExtValue()));
Nate Begemana0110022010-06-08 00:16:34 +00001659 }
1660
Chris Lattner91c08ad2011-02-15 00:14:06 +00001661 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001662 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1663}
Hal Finkelc4d7c822013-09-18 03:29:45 +00001664
1665Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1666 QualType SrcType = E->getSrcExpr()->getType(),
1667 DstType = E->getType();
1668
1669 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1670
1671 SrcType = CGF.getContext().getCanonicalType(SrcType);
1672 DstType = CGF.getContext().getCanonicalType(DstType);
1673 if (SrcType == DstType) return Src;
1674
1675 assert(SrcType->isVectorType() &&
1676 "ConvertVector source type must be a vector");
1677 assert(DstType->isVectorType() &&
1678 "ConvertVector destination type must be a vector");
1679
1680 llvm::Type *SrcTy = Src->getType();
1681 llvm::Type *DstTy = ConvertType(DstType);
1682
1683 // Ignore conversions like int -> uint.
1684 if (SrcTy == DstTy)
1685 return Src;
1686
1687 QualType SrcEltType = SrcType->getAs<VectorType>()->getElementType(),
1688 DstEltType = DstType->getAs<VectorType>()->getElementType();
1689
1690 assert(SrcTy->isVectorTy() &&
1691 "ConvertVector source IR type must be a vector");
1692 assert(DstTy->isVectorTy() &&
1693 "ConvertVector destination IR type must be a vector");
1694
1695 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1696 *DstEltTy = DstTy->getVectorElementType();
1697
1698 if (DstEltType->isBooleanType()) {
1699 assert((SrcEltTy->isFloatingPointTy() ||
1700 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1701
1702 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1703 if (SrcEltTy->isFloatingPointTy()) {
1704 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1705 } else {
1706 return Builder.CreateICmpNE(Src, Zero, "tobool");
1707 }
1708 }
1709
1710 // We have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +00001711 Value *Res = nullptr;
Hal Finkelc4d7c822013-09-18 03:29:45 +00001712
1713 if (isa<llvm::IntegerType>(SrcEltTy)) {
1714 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1715 if (isa<llvm::IntegerType>(DstEltTy))
1716 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1717 else if (InputSigned)
1718 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1719 else
1720 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1721 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1722 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1723 if (DstEltType->isSignedIntegerOrEnumerationType())
1724 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1725 else
1726 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1727 } else {
1728 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1729 "Unknown real conversion");
1730 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1731 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1732 else
1733 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1734 }
1735
1736 return Res;
1737}
1738
Eli Friedmancb422f12009-11-26 03:22:21 +00001739Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +00001740 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
1741 CGF.EmitIgnoredExpr(E->getBase());
Volodymyr Sapsaief1899b2018-11-01 21:57:05 +00001742 return CGF.emitScalarConstant(Constant, E);
Alex Lorenz6cc83172017-08-25 10:07:00 +00001743 } else {
Fangrui Song407659a2018-11-30 23:41:18 +00001744 Expr::EvalResult Result;
1745 if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1746 llvm::APSInt Value = Result.Val.getInt();
Alex Lorenz6cc83172017-08-25 10:07:00 +00001747 CGF.EmitIgnoredExpr(E->getBase());
1748 return Builder.getInt(Value);
1749 }
Eli Friedmancb422f12009-11-26 03:22:21 +00001750 }
Devang Patel44b8bf02010-10-04 21:46:04 +00001751
Eli Friedmancb422f12009-11-26 03:22:21 +00001752 return EmitLoadOfLValue(E);
1753}
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001754
Chris Lattner2da04b32007-08-24 05:35:26 +00001755Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001756 TestAndClearIgnoreResultAssign();
1757
Chris Lattner2da04b32007-08-24 05:35:26 +00001758 // Emit subscript expressions in rvalue context's. For most cases, this just
1759 // loads the lvalue formed by the subscript expr. However, we have to be
1760 // careful, because the base of a vector subscript is occasionally an rvalue,
1761 // so we can't get it as an lvalue.
1762 if (!E->getBase()->getType()->isVectorType())
1763 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +00001764
Chris Lattner2da04b32007-08-24 05:35:26 +00001765 // Handle the vector case. The base must be a vector, the index must be an
1766 // integer value.
1767 Value *Base = Visit(E->getBase());
1768 Value *Idx = Visit(E->getIdx());
Richard Smith539e4a72013-02-23 02:53:19 +00001769 QualType IdxTy = E->getIdx()->getType();
1770
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001771 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00001772 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1773
Chris Lattner2da04b32007-08-24 05:35:26 +00001774 return Builder.CreateExtractElement(Base, Idx, "vecext");
1775}
1776
Nate Begeman19351632009-10-18 20:10:40 +00001777static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2192fe52011-07-18 04:24:23 +00001778 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman19351632009-10-18 20:10:40 +00001779 int MV = SVI->getMaskValue(Idx);
Craig Toppera97d7e72013-07-26 06:16:11 +00001780 if (MV == -1)
Nate Begeman19351632009-10-18 20:10:40 +00001781 return llvm::UndefValue::get(I32Ty);
1782 return llvm::ConstantInt::get(I32Ty, Off+MV);
1783}
1784
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001785static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1786 if (C->getBitWidth() != 32) {
1787 assert(llvm::ConstantInt::isValueValidForType(I32Ty,
1788 C->getZExtValue()) &&
1789 "Index operand too large for shufflevector mask!");
1790 return llvm::ConstantInt::get(I32Ty, C->getZExtValue());
1791 }
1792 return C;
1793}
1794
Nate Begeman19351632009-10-18 20:10:40 +00001795Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1796 bool Ignore = TestAndClearIgnoreResultAssign();
1797 (void)Ignore;
1798 assert (Ignore == false && "init list ignored");
1799 unsigned NumInitElements = E->getNumInits();
Craig Toppera97d7e72013-07-26 06:16:11 +00001800
Nate Begeman19351632009-10-18 20:10:40 +00001801 if (E->hadArrayRangeDesignator())
1802 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Craig Toppera97d7e72013-07-26 06:16:11 +00001803
Chris Lattner2192fe52011-07-18 04:24:23 +00001804 llvm::VectorType *VType =
Nate Begeman19351632009-10-18 20:10:40 +00001805 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
Craig Toppera97d7e72013-07-26 06:16:11 +00001806
Sebastian Redl12757ab2011-09-24 17:48:14 +00001807 if (!VType) {
1808 if (NumInitElements == 0) {
1809 // C++11 value-initialization for the scalar.
1810 return EmitNullValue(E->getType());
1811 }
1812 // We have a scalar in braces. Just use the first element.
Nate Begeman19351632009-10-18 20:10:40 +00001813 return Visit(E->getInit(0));
Sebastian Redl12757ab2011-09-24 17:48:14 +00001814 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001815
Nate Begeman19351632009-10-18 20:10:40 +00001816 unsigned ResElts = VType->getNumElements();
Craig Toppera97d7e72013-07-26 06:16:11 +00001817
1818 // Loop over initializers collecting the Value for each, and remembering
Nate Begeman19351632009-10-18 20:10:40 +00001819 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1820 // us to fold the shuffle for the swizzle into the shuffle for the vector
1821 // initializer, since LLVM optimizers generally do not want to touch
1822 // shuffles.
1823 unsigned CurIdx = 0;
1824 bool VIsUndefShuffle = false;
1825 llvm::Value *V = llvm::UndefValue::get(VType);
1826 for (unsigned i = 0; i != NumInitElements; ++i) {
1827 Expr *IE = E->getInit(i);
1828 Value *Init = Visit(IE);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001829 SmallVector<llvm::Constant*, 16> Args;
Craig Toppera97d7e72013-07-26 06:16:11 +00001830
Chris Lattner2192fe52011-07-18 04:24:23 +00001831 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001832
Nate Begeman19351632009-10-18 20:10:40 +00001833 // Handle scalar elements. If the scalar initializer is actually one
Craig Toppera97d7e72013-07-26 06:16:11 +00001834 // element of a different vector of the same width, use shuffle instead of
Nate Begeman19351632009-10-18 20:10:40 +00001835 // extract+insert.
1836 if (!VVT) {
1837 if (isa<ExtVectorElementExpr>(IE)) {
1838 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1839
1840 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1841 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
Craig Topper8a13c412014-05-21 05:09:00 +00001842 Value *LHS = nullptr, *RHS = nullptr;
Nate Begeman19351632009-10-18 20:10:40 +00001843 if (CurIdx == 0) {
1844 // insert into undef -> shuffle (src, undef)
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001845 // shufflemask must use an i32
1846 Args.push_back(getAsInt32(C, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001847 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001848
1849 LHS = EI->getVectorOperand();
1850 RHS = V;
1851 VIsUndefShuffle = true;
1852 } else if (VIsUndefShuffle) {
1853 // insert into undefshuffle && size match -> shuffle (v, src)
1854 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1855 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001856 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner2531eb42011-04-19 22:55:03 +00001857 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001858 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1859
Nate Begeman19351632009-10-18 20:10:40 +00001860 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1861 RHS = EI->getVectorOperand();
1862 VIsUndefShuffle = false;
1863 }
1864 if (!Args.empty()) {
Chris Lattner91c08ad2011-02-15 00:14:06 +00001865 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001866 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1867 ++CurIdx;
1868 continue;
1869 }
1870 }
1871 }
Chris Lattner2531eb42011-04-19 22:55:03 +00001872 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1873 "vecinit");
Nate Begeman19351632009-10-18 20:10:40 +00001874 VIsUndefShuffle = false;
1875 ++CurIdx;
1876 continue;
1877 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001878
Nate Begeman19351632009-10-18 20:10:40 +00001879 unsigned InitElts = VVT->getNumElements();
1880
Craig Toppera97d7e72013-07-26 06:16:11 +00001881 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
Nate Begeman19351632009-10-18 20:10:40 +00001882 // input is the same width as the vector being constructed, generate an
1883 // optimized shuffle of the swizzle input into the result.
Nate Begemanb8326be2009-10-25 02:26:01 +00001884 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman19351632009-10-18 20:10:40 +00001885 if (isa<ExtVectorElementExpr>(IE)) {
1886 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1887 Value *SVOp = SVI->getOperand(0);
Chris Lattner2192fe52011-07-18 04:24:23 +00001888 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001889
Nate Begeman19351632009-10-18 20:10:40 +00001890 if (OpTy->getNumElements() == ResElts) {
Nate Begeman19351632009-10-18 20:10:40 +00001891 for (unsigned j = 0; j != CurIdx; ++j) {
1892 // If the current vector initializer is a shuffle with undef, merge
1893 // this shuffle directly into it.
1894 if (VIsUndefShuffle) {
1895 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner5e016ae2010-06-27 07:15:29 +00001896 CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001897 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00001898 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001899 }
1900 }
1901 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001902 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001903 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001904
1905 if (VIsUndefShuffle)
1906 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1907
1908 Init = SVOp;
1909 }
1910 }
1911
1912 // Extend init to result vector length, and then shuffle its contribution
1913 // to the vector initializer into V.
1914 if (Args.empty()) {
1915 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001916 Args.push_back(Builder.getInt32(j));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001917 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001918 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001919 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemanb8326be2009-10-25 02:26:01 +00001920 Mask, "vext");
Nate Begeman19351632009-10-18 20:10:40 +00001921
1922 Args.clear();
1923 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001924 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001925 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001926 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001927 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001928 }
1929
1930 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1931 // merging subsequent shuffles into this one.
1932 if (CurIdx == 0)
1933 std::swap(V, Init);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001934 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001935 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1936 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1937 CurIdx += InitElts;
1938 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001939
Nate Begeman19351632009-10-18 20:10:40 +00001940 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1941 // Emit remaining default initializers.
Chris Lattner2192fe52011-07-18 04:24:23 +00001942 llvm::Type *EltTy = VType->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00001943
Nate Begeman19351632009-10-18 20:10:40 +00001944 // Emit remaining default initializers
1945 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner2531eb42011-04-19 22:55:03 +00001946 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman19351632009-10-18 20:10:40 +00001947 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1948 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1949 }
1950 return V;
1951}
1952
John McCall7f416cc2015-09-08 08:05:57 +00001953bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001954 const Expr *E = CE->getSubExpr();
John McCalld9c7c6562010-03-30 23:58:03 +00001955
John McCalle3027922010-08-25 11:45:40 +00001956 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCalld9c7c6562010-03-30 23:58:03 +00001957 return false;
Craig Toppera97d7e72013-07-26 06:16:11 +00001958
John McCall7f416cc2015-09-08 08:05:57 +00001959 if (isa<CXXThisExpr>(E->IgnoreParens())) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001960 // We always assume that 'this' is never null.
1961 return false;
1962 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001963
Anders Carlsson8c793172009-11-23 17:57:54 +00001964 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001965 // And that glvalue casts are never null.
John McCall2536c6d2010-08-25 10:28:54 +00001966 if (ICE->getValueKind() != VK_RValue)
Anders Carlsson8c793172009-11-23 17:57:54 +00001967 return false;
1968 }
1969
1970 return true;
1971}
1972
Chris Lattner2da04b32007-08-24 05:35:26 +00001973// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1974// have to handle a more broad range of conversions than explicit casts, as they
1975// handle things like function to ptr-to-function decay etc.
John McCall23c29fe2011-06-24 21:55:10 +00001976Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001977 Expr *E = CE->getSubExpr();
Anders Carlsson8c978b42009-09-22 22:00:46 +00001978 QualType DestTy = CE->getType();
John McCalle3027922010-08-25 11:45:40 +00001979 CastKind Kind = CE->getCastKind();
Craig Toppera97d7e72013-07-26 06:16:11 +00001980
John McCalle399e5b2016-01-27 18:32:30 +00001981 // These cases are generally not written to ignore the result of
1982 // evaluating their sub-expressions, so we clear this now.
1983 bool Ignored = TestAndClearIgnoreResultAssign();
Mike Stump4a3999f2009-09-09 13:00:44 +00001984
Eli Friedman0dfc6802009-11-27 02:07:44 +00001985 // Since almost all cast kinds apply to scalars, this switch doesn't have
1986 // a default case, so the compiler will warn on a missing case. The cases
1987 // are in the same order as in the CastKind enum.
Anders Carlsson3df53bc2009-08-24 18:26:39 +00001988 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +00001989 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00001990 case CK_BuiltinFnToFnPtr:
1991 llvm_unreachable("builtin functions are handled elsewhere");
1992
Craig Toppera97d7e72013-07-26 06:16:11 +00001993 case CK_LValueBitCast:
John McCalle3027922010-08-25 11:45:40 +00001994 case CK_ObjCObjectLValueCast: {
John McCall7f416cc2015-09-08 08:05:57 +00001995 Address Addr = EmitLValue(E).getAddress();
Alexey Bataevf2440332015-10-07 10:22:08 +00001996 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
John McCall7f416cc2015-09-08 08:05:57 +00001997 LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
1998 return EmitLoadOfLValue(LV, CE->getExprLoc());
Douglas Gregor51954272010-07-13 23:17:26 +00001999 }
John McCallcd78e802011-09-10 01:16:55 +00002000
John McCall9320b872011-09-09 05:25:32 +00002001 case CK_CPointerToObjCPointerCast:
2002 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002003 case CK_AnyPointerToBlockPointerCast:
2004 case CK_BitCast: {
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00002005 Value *Src = Visit(const_cast<Expr*>(E));
David Tweede1468322013-12-11 13:39:46 +00002006 llvm::Type *SrcTy = Src->getType();
2007 llvm::Type *DstTy = ConvertType(DestTy);
Bob Wilson95a27b02014-02-17 19:20:59 +00002008 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
David Tweede1468322013-12-11 13:39:46 +00002009 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00002010 llvm_unreachable("wrong cast for pointers in different address spaces"
2011 "(must be an address space cast)!");
David Tweede1468322013-12-11 13:39:46 +00002012 }
Peter Collingbourned2926c92015-03-14 02:42:25 +00002013
2014 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
2015 if (auto PT = DestTy->getAs<PointerType>())
2016 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002017 /*MayBeNull=*/true,
2018 CodeGenFunction::CFITCK_UnrelatedCast,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002019 CE->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00002020 }
2021
Piotr Padlewski07058292018-07-02 19:21:36 +00002022 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2023 const QualType SrcType = E->getType();
2024
2025 if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
2026 // Casting to pointer that could carry dynamic information (provided by
2027 // invariant.group) requires launder.
2028 Src = Builder.CreateLaunderInvariantGroup(Src);
2029 } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
2030 // Casting to pointer that does not carry dynamic information (provided
2031 // by invariant.group) requires stripping it. Note that we don't do it
2032 // if the source could not be dynamic type and destination could be
2033 // dynamic because dynamic information is already laundered. It is
2034 // because launder(strip(src)) == launder(src), so there is no need to
2035 // add extra strip before launder.
2036 Src = Builder.CreateStripInvariantGroup(Src);
2037 }
2038 }
2039
David Tweede1468322013-12-11 13:39:46 +00002040 return Builder.CreateBitCast(Src, DstTy);
2041 }
2042 case CK_AddressSpaceConversion: {
Yaxun Liu402804b2016-12-15 08:09:08 +00002043 Expr::EvalResult Result;
2044 if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
2045 Result.Val.isNullPointer()) {
2046 // If E has side effect, it is emitted even if its final result is a
2047 // null pointer. In that case, a DCE pass should be able to
2048 // eliminate the useless instructions emitted during translating E.
2049 if (Result.HasSideEffects)
2050 Visit(E);
2051 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
2052 ConvertType(DestTy)), DestTy);
2053 }
Yaxun Liub7b6d0f2016-04-12 19:03:49 +00002054 // Since target may map different address spaces in AST to the same address
2055 // space, an address space conversion may end up as a bitcast.
Yaxun Liu6d96f1632017-05-18 18:51:09 +00002056 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
2057 CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
2058 DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00002059 }
David Chisnallfa35df62012-01-16 17:27:18 +00002060 case CK_AtomicToNonAtomic:
2061 case CK_NonAtomicToAtomic:
John McCalle3027922010-08-25 11:45:40 +00002062 case CK_NoOp:
2063 case CK_UserDefinedConversion:
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002064 return Visit(const_cast<Expr*>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00002065
John McCalle3027922010-08-25 11:45:40 +00002066 case CK_BaseToDerived: {
Jordan Rose7bb26112012-10-03 01:08:28 +00002067 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2068 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2069
John McCall7f416cc2015-09-08 08:05:57 +00002070 Address Base = CGF.EmitPointerWithAlignment(E);
2071 Address Derived =
2072 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00002073 CE->path_begin(), CE->path_end(),
John McCall7f416cc2015-09-08 08:05:57 +00002074 CGF.ShouldNullCheckClassCastValue(CE));
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00002075
Richard Smith2c5868c2013-02-13 21:18:23 +00002076 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2077 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00002078 if (CGF.sanitizePerformTypeCheck())
Richard Smith2c5868c2013-02-13 21:18:23 +00002079 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00002080 Derived.getPointer(), DestTy->getPointeeType());
Richard Smith2c5868c2013-02-13 21:18:23 +00002081
Peter Collingbourned2926c92015-03-14 02:42:25 +00002082 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002083 CGF.EmitVTablePtrCheckForCast(
2084 DestTy->getPointeeType(), Derived.getPointer(),
2085 /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
2086 CE->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00002087
John McCall7f416cc2015-09-08 08:05:57 +00002088 return Derived.getPointer();
Anders Carlsson8c793172009-11-23 17:57:54 +00002089 }
John McCalle3027922010-08-25 11:45:40 +00002090 case CK_UncheckedDerivedToBase:
2091 case CK_DerivedToBase: {
John McCall7f416cc2015-09-08 08:05:57 +00002092 // The EmitPointerWithAlignment path does this fine; just discard
2093 // the alignment.
2094 return CGF.EmitPointerWithAlignment(CE).getPointer();
Anders Carlsson12f5a252009-09-12 04:57:16 +00002095 }
John McCall7f416cc2015-09-08 08:05:57 +00002096
Anders Carlsson8a01a752011-04-11 02:03:26 +00002097 case CK_Dynamic: {
John McCall7f416cc2015-09-08 08:05:57 +00002098 Address V = CGF.EmitPointerWithAlignment(E);
Eli Friedman0dfc6802009-11-27 02:07:44 +00002099 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
2100 return CGF.EmitDynamicCast(V, DCE);
2101 }
Eli Friedmane96f1d32009-11-27 04:41:50 +00002102
John McCall7f416cc2015-09-08 08:05:57 +00002103 case CK_ArrayToPointerDecay:
2104 return CGF.EmitArrayToPointerDecay(E).getPointer();
John McCalle3027922010-08-25 11:45:40 +00002105 case CK_FunctionToPointerDecay:
John McCall7f416cc2015-09-08 08:05:57 +00002106 return EmitLValue(E).getPointer();
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002107
John McCalle84af4e2010-11-13 01:35:44 +00002108 case CK_NullToPointer:
2109 if (MustVisitNullValue(E))
Richard Smith35018952018-11-03 02:23:33 +00002110 (void) Visit(E);
John McCalle84af4e2010-11-13 01:35:44 +00002111
Yaxun Liu402804b2016-12-15 08:09:08 +00002112 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
2113 DestTy);
John McCalle84af4e2010-11-13 01:35:44 +00002114
John McCalle3027922010-08-25 11:45:40 +00002115 case CK_NullToMemberPointer: {
John McCalle84af4e2010-11-13 01:35:44 +00002116 if (MustVisitNullValue(E))
Richard Smith35018952018-11-03 02:23:33 +00002117 (void) Visit(E);
John McCalla1dee5302010-08-22 10:59:02 +00002118
John McCall7a9aac22010-08-23 01:21:21 +00002119 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2120 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2121 }
Anders Carlsson12f5a252009-09-12 04:57:16 +00002122
John McCallc62bb392012-02-15 01:22:51 +00002123 case CK_ReinterpretMemberPointer:
John McCalle3027922010-08-25 11:45:40 +00002124 case CK_BaseToDerivedMemberPointer:
2125 case CK_DerivedToBaseMemberPointer: {
Eli Friedmane96f1d32009-11-27 04:41:50 +00002126 Value *Src = Visit(E);
Craig Toppera97d7e72013-07-26 06:16:11 +00002127
John McCalla1dee5302010-08-22 10:59:02 +00002128 // Note that the AST doesn't distinguish between checked and
2129 // unchecked member pointer conversions, so we always have to
2130 // implement checked conversions here. This is inefficient when
2131 // actual control flow may be required in order to perform the
2132 // check, which it is for data member pointers (but not member
2133 // function pointers on Itanium and ARM).
John McCall7a9aac22010-08-23 01:21:21 +00002134 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmane96f1d32009-11-27 04:41:50 +00002135 }
John McCall31168b02011-06-15 23:02:42 +00002136
John McCall2d637d22011-09-10 06:18:15 +00002137 case CK_ARCProduceObject:
John McCall31168b02011-06-15 23:02:42 +00002138 return CGF.EmitARCRetainScalarExpr(E);
John McCall2d637d22011-09-10 06:18:15 +00002139 case CK_ARCConsumeObject:
John McCall31168b02011-06-15 23:02:42 +00002140 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCalle399e5b2016-01-27 18:32:30 +00002141 case CK_ARCReclaimReturnedObject:
2142 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
John McCallff613032011-10-04 06:23:45 +00002143 case CK_ARCExtendBlockObject:
2144 return CGF.EmitARCExtendBlockObject(E);
John McCall31168b02011-06-15 23:02:42 +00002145
Douglas Gregored90df32012-02-22 05:02:47 +00002146 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmanec75fec2012-02-28 01:08:45 +00002147 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00002148
John McCallc5e62b42010-11-13 09:02:35 +00002149 case CK_FloatingRealToComplex:
2150 case CK_FloatingComplexCast:
2151 case CK_IntegralRealToComplex:
2152 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002153 case CK_IntegralComplexToFloatingComplex:
2154 case CK_FloatingComplexToIntegralComplex:
John McCalle3027922010-08-25 11:45:40 +00002155 case CK_ConstructorConversion:
John McCall3eba6e62010-11-16 06:21:14 +00002156 case CK_ToUnion:
2157 llvm_unreachable("scalar cast to non-scalar value");
John McCall34376a62010-12-04 03:47:34 +00002158
John McCallf3735e02010-12-01 04:43:34 +00002159 case CK_LValueToRValue:
2160 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCall34376a62010-12-04 03:47:34 +00002161 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCallf3735e02010-12-01 04:43:34 +00002162 return Visit(const_cast<Expr*>(E));
Eli Friedman0dfc6802009-11-27 02:07:44 +00002163
John McCalle3027922010-08-25 11:45:40 +00002164 case CK_IntegralToPointer: {
Anders Carlsson7cd39e02009-09-15 04:48:33 +00002165 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002166
Anders Carlsson094c4592009-10-18 18:12:03 +00002167 // First, convert to the correct width so that we control the kind of
2168 // extension.
Yaxun Liu26f75662016-08-19 05:17:25 +00002169 auto DestLLVMTy = ConvertType(DestTy);
2170 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002171 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson094c4592009-10-18 18:12:03 +00002172 llvm::Value* IntResult =
2173 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002174
Piotr Padlewski07058292018-07-02 19:21:36 +00002175 auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002176
Piotr Padlewski07058292018-07-02 19:21:36 +00002177 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2178 // Going from integer to pointer that could be dynamic requires reloading
2179 // dynamic information from invariant.group.
2180 if (DestTy.mayBeDynamicClass())
2181 IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
2182 }
2183 return IntToPtr;
2184 }
2185 case CK_PointerToIntegral: {
2186 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
2187 auto *PtrExpr = Visit(E);
2188
2189 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2190 const QualType SrcType = E->getType();
2191
2192 // Casting to integer requires stripping dynamic information as it does
2193 // not carries it.
2194 if (SrcType.mayBeDynamicClass())
2195 PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
2196 }
2197
2198 return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
2199 }
John McCalle3027922010-08-25 11:45:40 +00002200 case CK_ToVoid: {
John McCalla2342eb2010-12-05 02:00:02 +00002201 CGF.EmitIgnoredExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002202 return nullptr;
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002203 }
John McCalle3027922010-08-25 11:45:40 +00002204 case CK_VectorSplat: {
Chris Lattner2192fe52011-07-18 04:24:23 +00002205 llvm::Type *DstTy = ConvertType(DestTy);
George Burgess IVdf1ed002016-01-13 01:52:39 +00002206 Value *Elt = Visit(const_cast<Expr*>(E));
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002207 // Splat the element across to all elements
Craig Topperf2f1a092016-07-08 02:17:35 +00002208 unsigned NumElements = DstTy->getVectorNumElements();
Alp Toker5f072d82014-04-19 23:55:49 +00002209 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002210 }
John McCall8cb679e2010-11-15 09:13:47 +00002211
Leonard Chan99bda372018-10-15 16:07:02 +00002212 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +00002213 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2214 CE->getExprLoc());
2215
2216 case CK_FixedPointToBoolean:
2217 assert(E->getType()->isFixedPointType() &&
2218 "Expected src type to be fixed point type");
2219 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
2220 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2221 CE->getExprLoc());
Leonard Chan99bda372018-10-15 16:07:02 +00002222
Roman Lebedevb69ba222018-07-30 18:58:30 +00002223 case CK_IntegralCast: {
2224 ScalarConversionOpts Opts;
Roman Lebedev62debd802018-10-30 21:58:56 +00002225 if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Roman Lebedevd677c3f2018-11-19 19:56:43 +00002226 if (!ICE->isPartOfExplicitCast())
2227 Opts = ScalarConversionOpts(CGF.SanOpts);
Roman Lebedevb69ba222018-07-30 18:58:30 +00002228 }
2229 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2230 CE->getExprLoc(), Opts);
2231 }
John McCalle3027922010-08-25 11:45:40 +00002232 case CK_IntegralToFloating:
2233 case CK_FloatingToIntegral:
2234 case CK_FloatingCast:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002235 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2236 CE->getExprLoc());
Roman Lebedevb69ba222018-07-30 18:58:30 +00002237 case CK_BooleanToSignedIntegral: {
2238 ScalarConversionOpts Opts;
2239 Opts.TreatBooleanAsSigned = true;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002240 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
Roman Lebedevb69ba222018-07-30 18:58:30 +00002241 CE->getExprLoc(), Opts);
2242 }
John McCall8cb679e2010-11-15 09:13:47 +00002243 case CK_IntegralToBoolean:
2244 return EmitIntToBoolConversion(Visit(E));
2245 case CK_PointerToBoolean:
Yaxun Liu402804b2016-12-15 08:09:08 +00002246 return EmitPointerToBoolConversion(Visit(E), E->getType());
John McCall8cb679e2010-11-15 09:13:47 +00002247 case CK_FloatingToBoolean:
2248 return EmitFloatToBoolConversion(Visit(E));
John McCalle3027922010-08-25 11:45:40 +00002249 case CK_MemberPointerToBoolean: {
John McCall7a9aac22010-08-23 01:21:21 +00002250 llvm::Value *MemPtr = Visit(E);
2251 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
2252 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlsson3df53bc2009-08-24 18:26:39 +00002253 }
John McCalld7646252010-11-14 08:17:51 +00002254
2255 case CK_FloatingComplexToReal:
2256 case CK_IntegralComplexToReal:
John McCall07bb1962010-11-16 10:08:07 +00002257 return CGF.EmitComplexExpr(E, false, true).first;
John McCalld7646252010-11-14 08:17:51 +00002258
2259 case CK_FloatingComplexToBoolean:
2260 case CK_IntegralComplexToBoolean: {
John McCall07bb1962010-11-16 10:08:07 +00002261 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCalld7646252010-11-14 08:17:51 +00002262
2263 // TODO: kill this function off, inline appropriate case here
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002264 return EmitComplexToScalarConversion(V, E->getType(), DestTy,
2265 CE->getExprLoc());
John McCalld7646252010-11-14 08:17:51 +00002266 }
2267
Andrew Savonichevb555b762018-10-23 15:19:20 +00002268 case CK_ZeroToOCLOpaqueType: {
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002269 assert((DestTy->isEventT() || DestTy->isQueueT() ||
2270 DestTy->isOCLIntelSubgroupAVCType()) &&
Andrew Savonichevb555b762018-10-23 15:19:20 +00002271 "CK_ZeroToOCLEvent cast on non-event type");
Egor Churaev89831422016-12-23 14:55:49 +00002272 return llvm::Constant::getNullValue(ConvertType(DestTy));
2273 }
2274
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002275 case CK_IntToOCLSampler:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002276 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002277
2278 } // end of switch
Mike Stump4a3999f2009-09-09 13:00:44 +00002279
John McCall3eba6e62010-11-16 06:21:14 +00002280 llvm_unreachable("unknown scalar cast");
Chris Lattner2da04b32007-08-24 05:35:26 +00002281}
2282
Chris Lattner04a913b2007-08-31 22:09:40 +00002283Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +00002284 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002285 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
2286 !E->getType()->isVoidType());
2287 if (!RetAlloca.isValid())
Craig Topper8a13c412014-05-21 05:09:00 +00002288 return nullptr;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002289 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
2290 E->getExprLoc());
Chris Lattner04a913b2007-08-31 22:09:40 +00002291}
2292
Reid Kleckner092d0652017-03-06 22:18:34 +00002293Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
2294 CGF.enterFullExpression(E);
2295 CodeGenFunction::RunCleanupsScope Scope(CGF);
2296 Value *V = Visit(E->getSubExpr());
2297 // Defend against dominance problems caused by jumps out of expression
2298 // evaluation through the shared cleanup block.
2299 Scope.ForceCleanup({&V});
2300 return V;
2301}
2302
Chris Lattner2da04b32007-08-24 05:35:26 +00002303//===----------------------------------------------------------------------===//
2304// Unary Operators
2305//===----------------------------------------------------------------------===//
2306
Alexey Samsonovf6246502015-04-23 01:50:45 +00002307static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
2308 llvm::Value *InVal, bool IsInc) {
2309 BinOpInfo BinOp;
2310 BinOp.LHS = InVal;
2311 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
2312 BinOp.Ty = E->getType();
2313 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
Adam Nemet484aa452017-03-27 19:17:25 +00002314 // FIXME: once UnaryOperator carries FPFeatures, copy it here.
Alexey Samsonovf6246502015-04-23 01:50:45 +00002315 BinOp.E = E;
2316 return BinOp;
2317}
2318
2319llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
2320 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
2321 llvm::Value *Amount =
2322 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
2323 StringRef Name = IsInc ? "inc" : "dec";
Richard Smith9c6890a2012-11-01 22:30:59 +00002324 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00002325 case LangOptions::SOB_Defined:
Alexey Samsonovf6246502015-04-23 01:50:45 +00002326 return Builder.CreateAdd(InVal, Amount, Name);
Richard Smith3e056de2012-08-25 00:32:28 +00002327 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002328 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002329 return Builder.CreateNSWAdd(InVal, Amount, Name);
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00002330 LLVM_FALLTHROUGH;
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002331 case LangOptions::SOB_Trapping:
2332 if (!E->canOverflow())
2333 return Builder.CreateNSWAdd(InVal, Amount, Name);
2334 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc));
2335 }
David Blaikie83d382b2011-09-23 05:06:16 +00002336 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev85129b82011-02-07 02:17:30 +00002337}
2338
John McCalle3dc1702011-02-15 09:22:45 +00002339llvm::Value *
2340ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2341 bool isInc, bool isPre) {
Craig Toppera97d7e72013-07-26 06:16:11 +00002342
John McCalle3dc1702011-02-15 09:22:45 +00002343 QualType type = E->getSubExpr()->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00002344 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00002345 llvm::Value *value;
2346 llvm::Value *input;
Anton Yartsev85129b82011-02-07 02:17:30 +00002347
John McCalle3dc1702011-02-15 09:22:45 +00002348 int amount = (isInc ? 1 : -1);
Vedant Kumar175b6d12017-07-13 20:55:26 +00002349 bool isSubtraction = !isInc;
John McCalle3dc1702011-02-15 09:22:45 +00002350
David Chisnallfa35df62012-01-16 17:27:18 +00002351 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
David Chisnallef78c302013-03-03 16:02:42 +00002352 type = atomicTy->getValueType();
2353 if (isInc && type->isBooleanType()) {
2354 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
2355 if (isPre) {
John McCall7f416cc2015-09-08 08:05:57 +00002356 Builder.CreateStore(True, LV.getAddress(), LV.isVolatileQualified())
JF Bastien92f4ef12016-04-06 17:26:42 +00002357 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002358 return Builder.getTrue();
2359 }
2360 // For atomic bool increment, we just store true and return it for
2361 // preincrement, do an atomic swap with true for postincrement
JF Bastien92f4ef12016-04-06 17:26:42 +00002362 return Builder.CreateAtomicRMW(
2363 llvm::AtomicRMWInst::Xchg, LV.getPointer(), True,
2364 llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002365 }
2366 // Special case for atomic increment / decrement on integers, emit
2367 // atomicrmw instructions. We skip this if we want to be doing overflow
Craig Toppera97d7e72013-07-26 06:16:11 +00002368 // checking, and fall into the slow path with the atomic cmpxchg loop.
David Chisnallef78c302013-03-03 16:02:42 +00002369 if (!type->isBooleanType() && type->isIntegerType() &&
2370 !(type->isUnsignedIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002371 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
David Chisnallef78c302013-03-03 16:02:42 +00002372 CGF.getLangOpts().getSignedOverflowBehavior() !=
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002373 LangOptions::SOB_Trapping) {
David Chisnallef78c302013-03-03 16:02:42 +00002374 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
2375 llvm::AtomicRMWInst::Sub;
2376 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
2377 llvm::Instruction::Sub;
2378 llvm::Value *amt = CGF.EmitToMemory(
2379 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
2380 llvm::Value *old = Builder.CreateAtomicRMW(aop,
JF Bastien92f4ef12016-04-06 17:26:42 +00002381 LV.getPointer(), amt, llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002382 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
2383 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00002384 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002385 input = value;
2386 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
David Chisnallfa35df62012-01-16 17:27:18 +00002387 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2388 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
David Chisnallef78c302013-03-03 16:02:42 +00002389 value = CGF.EmitToMemory(value, type);
David Chisnallfa35df62012-01-16 17:27:18 +00002390 Builder.CreateBr(opBB);
2391 Builder.SetInsertPoint(opBB);
2392 atomicPHI = Builder.CreatePHI(value->getType(), 2);
2393 atomicPHI->addIncoming(value, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002394 value = atomicPHI;
David Chisnallef78c302013-03-03 16:02:42 +00002395 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002396 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002397 input = value;
David Chisnallfa35df62012-01-16 17:27:18 +00002398 }
2399
John McCalle3dc1702011-02-15 09:22:45 +00002400 // Special case of integer increment that we have to check first: bool++.
2401 // Due to promotion rules, we get:
2402 // bool++ -> bool = bool + 1
2403 // -> bool = (int)bool + 1
2404 // -> bool = ((int)bool + 1 != 0)
2405 // An interesting aspect of this is that increment is always true.
2406 // Decrement does not have this property.
2407 if (isInc && type->isBooleanType()) {
2408 value = Builder.getTrue();
2409
2410 // Most common case by far: integer increment.
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002411 } else if (type->isIntegerType()) {
2412 // Note that signed integer inc/dec with width less than int can't
2413 // overflow because of promotion rules; we're just eliding a few steps here.
2414 if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
2415 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
2416 } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
2417 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
2418 value =
2419 EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc));
Alexey Samsonovf6246502015-04-23 01:50:45 +00002420 } else {
2421 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCalle3dc1702011-02-15 09:22:45 +00002422 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
Alexey Samsonovf6246502015-04-23 01:50:45 +00002423 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002424
John McCalle3dc1702011-02-15 09:22:45 +00002425 // Next most common: pointer increment.
2426 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
2427 QualType type = ptr->getPointeeType();
2428
2429 // VLA types don't have constant size.
John McCall77527a82011-06-25 01:32:37 +00002430 if (const VariableArrayType *vla
2431 = CGF.getContext().getAsVariableArrayType(type)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +00002432 llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
John McCall23c29fe2011-06-24 21:55:10 +00002433 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Richard Smith9c6890a2012-11-01 22:30:59 +00002434 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall23c29fe2011-06-24 21:55:10 +00002435 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2e72da942011-03-01 00:03:48 +00002436 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002437 value = CGF.EmitCheckedInBoundsGEP(
2438 value, numElts, /*SignedIndices=*/false, isSubtraction,
2439 E->getExprLoc(), "vla.inc");
Craig Toppera97d7e72013-07-26 06:16:11 +00002440
John McCalle3dc1702011-02-15 09:22:45 +00002441 // Arithmetic on function pointers (!) is just +-1.
2442 } else if (type->isFunctionType()) {
Chris Lattner2531eb42011-04-19 22:55:03 +00002443 llvm::Value *amt = Builder.getInt32(amount);
John McCalle3dc1702011-02-15 09:22:45 +00002444
2445 value = CGF.EmitCastToVoidPtr(value);
Richard Smith9c6890a2012-11-01 22:30:59 +00002446 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002447 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
2448 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002449 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2450 isSubtraction, E->getExprLoc(),
2451 "incdec.funcptr");
John McCalle3dc1702011-02-15 09:22:45 +00002452 value = Builder.CreateBitCast(value, input->getType());
2453
2454 // For everything else, we can just do a simple increment.
Anton Yartsev85129b82011-02-07 02:17:30 +00002455 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00002456 llvm::Value *amt = Builder.getInt32(amount);
Richard Smith9c6890a2012-11-01 22:30:59 +00002457 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002458 value = Builder.CreateGEP(value, amt, "incdec.ptr");
2459 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002460 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2461 isSubtraction, E->getExprLoc(),
2462 "incdec.ptr");
John McCalle3dc1702011-02-15 09:22:45 +00002463 }
2464
2465 // Vector increment/decrement.
2466 } else if (type->isVectorType()) {
2467 if (type->hasIntegerRepresentation()) {
2468 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
2469
Eli Friedman409943e2011-05-06 18:04:18 +00002470 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCalle3dc1702011-02-15 09:22:45 +00002471 } else {
2472 value = Builder.CreateFAdd(
2473 value,
2474 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev85129b82011-02-07 02:17:30 +00002475 isInc ? "inc" : "dec");
2476 }
Anton Yartsev85129b82011-02-07 02:17:30 +00002477
John McCalle3dc1702011-02-15 09:22:45 +00002478 // Floating point.
2479 } else if (type->isRealFloatingType()) {
Chris Lattner05dc78c2010-06-26 22:09:34 +00002480 // Add the inc/dec to the real part.
John McCalle3dc1702011-02-15 09:22:45 +00002481 llvm::Value *amt;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002482
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002483 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002484 // Another special case: half FP increment should be done via float
Akira Hatanaka502775a2017-12-09 00:02:37 +00002485 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002486 value = Builder.CreateCall(
2487 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
2488 CGF.CGM.FloatTy),
2489 input, "incdec.conv");
2490 } else {
2491 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
2492 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002493 }
2494
John McCalle3dc1702011-02-15 09:22:45 +00002495 if (value->getType()->isFloatTy())
2496 amt = llvm::ConstantFP::get(VMContext,
2497 llvm::APFloat(static_cast<float>(amount)));
2498 else if (value->getType()->isDoubleTy())
2499 amt = llvm::ConstantFP::get(VMContext,
2500 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner05dc78c2010-06-26 22:09:34 +00002501 else {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002502 // Remaining types are Half, LongDouble or __float128. Convert from float.
John McCalle3dc1702011-02-15 09:22:45 +00002503 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner05dc78c2010-06-26 22:09:34 +00002504 bool ignored;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002505 const llvm::fltSemantics *FS;
Ahmed Bougacha6ba38312015-03-24 23:44:42 +00002506 // Don't use getFloatTypeSemantics because Half isn't
2507 // necessarily represented using the "half" LLVM type.
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002508 if (value->getType()->isFP128Ty())
2509 FS = &CGF.getTarget().getFloat128Format();
2510 else if (value->getType()->isHalfTy())
2511 FS = &CGF.getTarget().getHalfFormat();
2512 else
2513 FS = &CGF.getTarget().getLongDoubleFormat();
2514 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
John McCalle3dc1702011-02-15 09:22:45 +00002515 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner05dc78c2010-06-26 22:09:34 +00002516 }
John McCalle3dc1702011-02-15 09:22:45 +00002517 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
2518
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002519 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Akira Hatanaka502775a2017-12-09 00:02:37 +00002520 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002521 value = Builder.CreateCall(
2522 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
2523 CGF.CGM.FloatTy),
2524 value, "incdec.conv");
2525 } else {
2526 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
2527 }
2528 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002529
John McCalle3dc1702011-02-15 09:22:45 +00002530 // Objective-C pointer types.
2531 } else {
2532 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
2533 value = CGF.EmitCastToVoidPtr(value);
2534
2535 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
2536 if (!isInc) size = -size;
2537 llvm::Value *sizeValue =
2538 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
2539
Richard Smith9c6890a2012-11-01 22:30:59 +00002540 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002541 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
2542 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002543 value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
2544 /*SignedIndices=*/false, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00002545 E->getExprLoc(), "incdec.objptr");
John McCalle3dc1702011-02-15 09:22:45 +00002546 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner05dc78c2010-06-26 22:09:34 +00002547 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002548
David Chisnallfa35df62012-01-16 17:27:18 +00002549 if (atomicPHI) {
2550 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2551 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00002552 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00002553 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
2554 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
2555 llvm::Value *success = Pair.second;
David Chisnallfa35df62012-01-16 17:27:18 +00002556 atomicPHI->addIncoming(old, opBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002557 Builder.CreateCondBr(success, contBB, opBB);
2558 Builder.SetInsertPoint(contBB);
2559 return isPre ? value : input;
2560 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002561
Chris Lattner05dc78c2010-06-26 22:09:34 +00002562 // Store the updated result through the lvalue.
2563 if (LV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00002564 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner05dc78c2010-06-26 22:09:34 +00002565 else
John McCall55e1fbc2011-06-25 02:11:03 +00002566 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002567
Chris Lattner05dc78c2010-06-26 22:09:34 +00002568 // If this is a postinc, return the value read from memory, otherwise use the
2569 // updated value.
John McCalle3dc1702011-02-15 09:22:45 +00002570 return isPre ? value : input;
Chris Lattner05dc78c2010-06-26 22:09:34 +00002571}
2572
2573
2574
Chris Lattner2da04b32007-08-24 05:35:26 +00002575Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002576 TestAndClearIgnoreResultAssign();
Chris Lattner0bf27622010-06-26 21:48:21 +00002577 // Emit unary minus with EmitSub so we handle overflow cases etc.
2578 BinOpInfo BinOp;
Chris Lattnerc1028f62010-06-28 17:12:37 +00002579 BinOp.RHS = Visit(E->getSubExpr());
Craig Toppera97d7e72013-07-26 06:16:11 +00002580
Chris Lattnerc1028f62010-06-28 17:12:37 +00002581 if (BinOp.RHS->getType()->isFPOrFPVectorTy())
2582 BinOp.LHS = llvm::ConstantFP::getZeroValueForNegation(BinOp.RHS->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00002583 else
Chris Lattnerc1028f62010-06-28 17:12:37 +00002584 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner0bf27622010-06-26 21:48:21 +00002585 BinOp.Ty = E->getType();
John McCalle3027922010-08-25 11:45:40 +00002586 BinOp.Opcode = BO_Sub;
Adam Nemet484aa452017-03-27 19:17:25 +00002587 // FIXME: once UnaryOperator carries FPFeatures, copy it here.
Chris Lattner0bf27622010-06-26 21:48:21 +00002588 BinOp.E = E;
2589 return EmitSub(BinOp);
Chris Lattner2da04b32007-08-24 05:35:26 +00002590}
2591
2592Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002593 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00002594 Value *Op = Visit(E->getSubExpr());
2595 return Builder.CreateNot(Op, "neg");
2596}
2597
2598Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00002599 // Perform vector logical not on comparison with zero vector.
2600 if (E->getType()->isExtVectorType()) {
2601 Value *Oper = Visit(E->getSubExpr());
2602 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00002603 Value *Result;
2604 if (Oper->getType()->isFPOrFPVectorTy())
2605 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
2606 else
2607 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
Tanya Lattner20248222012-01-16 21:02:28 +00002608 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2609 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002610
Chris Lattner2da04b32007-08-24 05:35:26 +00002611 // Compare operand to zero.
2612 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002613
Chris Lattner2da04b32007-08-24 05:35:26 +00002614 // Invert value.
2615 // TODO: Could dynamically modify easy computations here. For example, if
2616 // the operand is an icmp ne, turn into icmp eq.
2617 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stump4a3999f2009-09-09 13:00:44 +00002618
Anders Carlsson775640d2009-05-19 18:44:53 +00002619 // ZExt result to the expr type.
2620 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00002621}
2622
Eli Friedmand7c72322010-08-05 09:58:49 +00002623Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2624 // Try folding the offsetof to a constant.
Fangrui Song407659a2018-11-30 23:41:18 +00002625 Expr::EvalResult EVResult;
2626 if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
2627 llvm::APSInt Value = EVResult.Val.getInt();
Richard Smith5fab0c92011-12-28 19:48:30 +00002628 return Builder.getInt(Value);
Fangrui Song407659a2018-11-30 23:41:18 +00002629 }
Eli Friedmand7c72322010-08-05 09:58:49 +00002630
2631 // Loop over the components of the offsetof to compute the value.
2632 unsigned n = E->getNumComponents();
Chris Lattner2192fe52011-07-18 04:24:23 +00002633 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedmand7c72322010-08-05 09:58:49 +00002634 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2635 QualType CurrentType = E->getTypeSourceInfo()->getType();
2636 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00002637 OffsetOfNode ON = E->getComponent(i);
Craig Topper8a13c412014-05-21 05:09:00 +00002638 llvm::Value *Offset = nullptr;
Eli Friedmand7c72322010-08-05 09:58:49 +00002639 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00002640 case OffsetOfNode::Array: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002641 // Compute the index
2642 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2643 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002644 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedmand7c72322010-08-05 09:58:49 +00002645 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2646
2647 // Save the element type
2648 CurrentType =
2649 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2650
2651 // Compute the element size
2652 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2653 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2654
2655 // Multiply out to compute the result
2656 Offset = Builder.CreateMul(Idx, ElemSize);
2657 break;
2658 }
2659
James Y Knight7281c352015-12-29 22:31:18 +00002660 case OffsetOfNode::Field: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002661 FieldDecl *MemberDecl = ON.getField();
2662 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
2663 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2664
2665 // Compute the index of the field in its parent.
2666 unsigned i = 0;
2667 // FIXME: It would be nice if we didn't have to loop here!
2668 for (RecordDecl::field_iterator Field = RD->field_begin(),
2669 FieldEnd = RD->field_end();
David Blaikie2d7c57e2012-04-30 02:36:29 +00002670 Field != FieldEnd; ++Field, ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002671 if (*Field == MemberDecl)
Eli Friedmand7c72322010-08-05 09:58:49 +00002672 break;
2673 }
2674 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2675
2676 // Compute the offset to the field
2677 int64_t OffsetInt = RL.getFieldOffset(i) /
2678 CGF.getContext().getCharWidth();
2679 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2680
2681 // Save the element type.
2682 CurrentType = MemberDecl->getType();
2683 break;
2684 }
Eli Friedman165301d2010-08-06 16:37:05 +00002685
James Y Knight7281c352015-12-29 22:31:18 +00002686 case OffsetOfNode::Identifier:
Eli Friedmane83d2b762010-08-06 01:17:25 +00002687 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman165301d2010-08-06 16:37:05 +00002688
James Y Knight7281c352015-12-29 22:31:18 +00002689 case OffsetOfNode::Base: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002690 if (ON.getBase()->isVirtual()) {
2691 CGF.ErrorUnsupported(E, "virtual base in offsetof");
2692 continue;
2693 }
2694
2695 RecordDecl *RD = CurrentType->getAs<RecordType>()->getDecl();
2696 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2697
2698 // Save the element type.
2699 CurrentType = ON.getBase()->getType();
Craig Toppera97d7e72013-07-26 06:16:11 +00002700
Eli Friedmand7c72322010-08-05 09:58:49 +00002701 // Compute the offset to the base.
2702 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2703 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002704 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2705 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedmand7c72322010-08-05 09:58:49 +00002706 break;
2707 }
2708 }
2709 Result = Builder.CreateAdd(Result, Offset);
2710 }
2711 return Result;
Douglas Gregor882211c2010-04-28 22:16:22 +00002712}
2713
Peter Collingbournee190dee2011-03-11 19:24:49 +00002714/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl6f282892008-11-11 17:56:53 +00002715/// argument of the sizeof expression as an integer.
2716Value *
Peter Collingbournee190dee2011-03-11 19:24:49 +00002717ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2718 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl6f282892008-11-11 17:56:53 +00002719 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002720 if (E->getKind() == UETT_SizeOf) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002721 if (const VariableArrayType *VAT =
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002722 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2723 if (E->isArgumentType()) {
2724 // sizeof(type) - make sure to emit the VLA size.
John McCall23c29fe2011-06-24 21:55:10 +00002725 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman3253e182009-04-20 03:21:44 +00002726 } else {
2727 // C99 6.5.3.4p2: If the argument is an expression of type
2728 // VLA, it is evaluated.
John McCalla2342eb2010-12-05 02:00:02 +00002729 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002730 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002731
Sander de Smalen891af03a2018-02-03 13:55:59 +00002732 auto VlaSize = CGF.getVLASize(VAT);
2733 llvm::Value *size = VlaSize.NumElts;
John McCall23c29fe2011-06-24 21:55:10 +00002734
2735 // Scale the number of non-VLA elements by the non-VLA element size.
Sander de Smalen891af03a2018-02-03 13:55:59 +00002736 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
John McCall23c29fe2011-06-24 21:55:10 +00002737 if (!eltSize.isOne())
Sander de Smalen891af03a2018-02-03 13:55:59 +00002738 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
John McCall23c29fe2011-06-24 21:55:10 +00002739
2740 return size;
Anders Carlsson76dbc042008-12-21 03:33:21 +00002741 }
Alexey Bataev00396512015-07-02 03:40:19 +00002742 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2743 auto Alignment =
2744 CGF.getContext()
2745 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2746 E->getTypeOfArgument()->getPointeeType()))
2747 .getQuantity();
2748 return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
Anders Carlsson30032882008-12-12 07:38:43 +00002749 }
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002750
Mike Stump4a3999f2009-09-09 13:00:44 +00002751 // If this isn't sizeof(vla), the result must be constant; use the constant
2752 // folding logic so we don't have to duplicate it here.
Richard Smith5fab0c92011-12-28 19:48:30 +00002753 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner2da04b32007-08-24 05:35:26 +00002754}
2755
Chris Lattner9f0ad962007-08-24 21:20:17 +00002756Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2757 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002758 if (Op->getType()->isAnyComplexType()) {
2759 // If it's an l-value, load through the appropriate subobject l-value.
2760 // Note that we have to ask E because Op might be an l-value that
2761 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002762 if (E->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002763 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2764 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002765
2766 // Otherwise, calculate and project.
2767 return CGF.EmitComplexExpr(Op, false, true).first;
2768 }
2769
Chris Lattner9f0ad962007-08-24 21:20:17 +00002770 return Visit(Op);
2771}
John McCall07bb1962010-11-16 10:08:07 +00002772
Chris Lattner9f0ad962007-08-24 21:20:17 +00002773Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2774 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002775 if (Op->getType()->isAnyComplexType()) {
2776 // If it's an l-value, load through the appropriate subobject l-value.
2777 // Note that we have to ask E because Op might be an l-value that
2778 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002779 if (Op->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002780 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2781 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002782
2783 // Otherwise, calculate and project.
2784 return CGF.EmitComplexExpr(Op, true, false).second;
2785 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002786
Mike Stumpdf0fe272009-05-29 15:46:01 +00002787 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2788 // effects are evaluated, but not the actual value.
Richard Smith0b6b8e42012-02-18 20:53:32 +00002789 if (Op->isGLValue())
2790 CGF.EmitLValue(Op);
2791 else
2792 CGF.EmitScalarExpr(Op, true);
Owen Anderson0b75f232009-07-31 20:28:54 +00002793 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner9f0ad962007-08-24 21:20:17 +00002794}
2795
Chris Lattner2da04b32007-08-24 05:35:26 +00002796//===----------------------------------------------------------------------===//
2797// Binary Operators
2798//===----------------------------------------------------------------------===//
2799
2800BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002801 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00002802 BinOpInfo Result;
2803 Result.LHS = Visit(E->getLHS());
2804 Result.RHS = Visit(E->getRHS());
Chris Lattner3d966d62007-08-24 21:00:35 +00002805 Result.Ty = E->getType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002806 Result.Opcode = E->getOpcode();
Adam Nemet484aa452017-03-27 19:17:25 +00002807 Result.FPFeatures = E->getFPFeatures();
Chris Lattner2da04b32007-08-24 05:35:26 +00002808 Result.E = E;
2809 return Result;
2810}
2811
Douglas Gregor914af212010-04-23 04:16:32 +00002812LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2813 const CompoundAssignOperator *E,
2814 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002815 Value *&Result) {
Benjamin Kramerd20ef752009-12-25 15:43:36 +00002816 QualType LHSTy = E->getLHS()->getType();
Chris Lattner3d966d62007-08-24 21:00:35 +00002817 BinOpInfo OpInfo;
Craig Toppera97d7e72013-07-26 06:16:11 +00002818
Eli Friedmanf0450072013-06-12 01:40:06 +00002819 if (E->getComputationResultType()->isAnyComplexType())
Richard Smith527473d2015-02-12 21:23:20 +00002820 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
Craig Toppera97d7e72013-07-26 06:16:11 +00002821
Mike Stumpc63428b2009-05-22 19:07:20 +00002822 // Emit the RHS first. __block variables need to have the rhs evaluated
2823 // first, plus this should improve codegen a little.
2824 OpInfo.RHS = Visit(E->getRHS());
2825 OpInfo.Ty = E->getComputationResultType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002826 OpInfo.Opcode = E->getOpcode();
Adam Nemet484aa452017-03-27 19:17:25 +00002827 OpInfo.FPFeatures = E->getFPFeatures();
Mike Stumpc63428b2009-05-22 19:07:20 +00002828 OpInfo.E = E;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00002829 // Load/convert the LHS.
Richard Smith4d1458e2012-09-08 02:08:36 +00002830 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
David Chisnallfa35df62012-01-16 17:27:18 +00002831
Craig Topper8a13c412014-05-21 05:09:00 +00002832 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00002833 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2834 QualType type = atomicTy->getValueType();
2835 if (!type->isBooleanType() && type->isIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002836 !(type->isUnsignedIntegerType() &&
2837 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2838 CGF.getLangOpts().getSignedOverflowBehavior() !=
2839 LangOptions::SOB_Trapping) {
David Chisnallef78c302013-03-03 16:02:42 +00002840 llvm::AtomicRMWInst::BinOp aop = llvm::AtomicRMWInst::BAD_BINOP;
2841 switch (OpInfo.Opcode) {
2842 // We don't have atomicrmw operands for *, %, /, <<, >>
2843 case BO_MulAssign: case BO_DivAssign:
2844 case BO_RemAssign:
2845 case BO_ShlAssign:
2846 case BO_ShrAssign:
2847 break;
2848 case BO_AddAssign:
2849 aop = llvm::AtomicRMWInst::Add;
2850 break;
2851 case BO_SubAssign:
2852 aop = llvm::AtomicRMWInst::Sub;
2853 break;
2854 case BO_AndAssign:
2855 aop = llvm::AtomicRMWInst::And;
2856 break;
2857 case BO_XorAssign:
2858 aop = llvm::AtomicRMWInst::Xor;
2859 break;
2860 case BO_OrAssign:
2861 aop = llvm::AtomicRMWInst::Or;
2862 break;
2863 default:
2864 llvm_unreachable("Invalid compound assignment type");
2865 }
2866 if (aop != llvm::AtomicRMWInst::BAD_BINOP) {
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002867 llvm::Value *amt = CGF.EmitToMemory(
2868 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
2869 E->getExprLoc()),
2870 LHSTy);
John McCall7f416cc2015-09-08 08:05:57 +00002871 Builder.CreateAtomicRMW(aop, LHSLV.getPointer(), amt,
JF Bastien92f4ef12016-04-06 17:26:42 +00002872 llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002873 return LHSLV;
2874 }
2875 }
David Chisnallfa35df62012-01-16 17:27:18 +00002876 // FIXME: For floating point types, we should be saving and restoring the
2877 // floating point environment in the loop.
2878 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2879 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
Nick Lewycky2d84e842013-10-02 02:29:49 +00002880 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002881 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
David Chisnallfa35df62012-01-16 17:27:18 +00002882 Builder.CreateBr(opBB);
2883 Builder.SetInsertPoint(opBB);
2884 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
2885 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002886 OpInfo.LHS = atomicPHI;
2887 }
David Chisnallef78c302013-03-03 16:02:42 +00002888 else
Nick Lewycky2d84e842013-10-02 02:29:49 +00002889 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002890
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002891 SourceLocation Loc = E->getExprLoc();
2892 OpInfo.LHS =
2893 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
Eli Friedman93ee5ca2012-06-16 02:19:17 +00002894
Chris Lattner3d966d62007-08-24 21:00:35 +00002895 // Expand the binary operator.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002896 Result = (this->*Func)(OpInfo);
Craig Toppera97d7e72013-07-26 06:16:11 +00002897
Roman Lebedevd677c3f2018-11-19 19:56:43 +00002898 // Convert the result back to the LHS type,
2899 // potentially with Implicit Conversion sanitizer check.
2900 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
2901 Loc, ScalarConversionOpts(CGF.SanOpts));
David Chisnallfa35df62012-01-16 17:27:18 +00002902
2903 if (atomicPHI) {
2904 llvm::BasicBlock *opBB = Builder.GetInsertBlock();
2905 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00002906 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00002907 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
2908 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
2909 llvm::Value *success = Pair.second;
David Chisnallfa35df62012-01-16 17:27:18 +00002910 atomicPHI->addIncoming(old, opBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002911 Builder.CreateCondBr(success, contBB, opBB);
2912 Builder.SetInsertPoint(contBB);
2913 return LHSLV;
2914 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002915
Mike Stump4a3999f2009-09-09 13:00:44 +00002916 // Store the result value into the LHS lvalue. Bit-fields are handled
2917 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
2918 // 'An assignment expression has the value of the left operand after the
2919 // assignment...'.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002920 if (LHSLV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00002921 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002922 else
John McCall55e1fbc2011-06-25 02:11:03 +00002923 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002924
Douglas Gregor914af212010-04-23 04:16:32 +00002925 return LHSLV;
2926}
2927
2928Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
2929 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
2930 bool Ignore = TestAndClearIgnoreResultAssign();
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002931 Value *RHS;
2932 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
2933
2934 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00002935 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00002936 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002937
John McCall07bb1962010-11-16 10:08:07 +00002938 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00002939 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00002940 return RHS;
2941
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002942 // If the lvalue is non-volatile, return the computed value of the assignment.
2943 if (!LHS.isVolatileQualified())
2944 return RHS;
2945
2946 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002947 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner3d966d62007-08-24 21:00:35 +00002948}
2949
Chris Lattner8ee6a412010-09-11 21:47:09 +00002950void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith4d1458e2012-09-08 02:08:36 +00002951 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +00002952 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
Chris Lattner8ee6a412010-09-11 21:47:09 +00002953
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002954 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002955 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
2956 SanitizerKind::IntegerDivideByZero));
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00002957 }
Richard Smithc86a1142012-11-06 02:30:30 +00002958
Vedant Kumar82ee16b2017-02-25 00:43:36 +00002959 const auto *BO = cast<BinaryOperator>(Ops.E);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002960 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00002961 Ops.Ty->hasSignedIntegerRepresentation() &&
Vedant Kumard9191152017-05-02 23:46:56 +00002962 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
2963 Ops.mayHaveIntegerOverflow()) {
Richard Smithc86a1142012-11-06 02:30:30 +00002964 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
2965
Chris Lattner8ee6a412010-09-11 21:47:09 +00002966 llvm::Value *IntMin =
Chris Lattner2531eb42011-04-19 22:55:03 +00002967 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner8ee6a412010-09-11 21:47:09 +00002968 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
2969
Richard Smith4d1458e2012-09-08 02:08:36 +00002970 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
2971 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002972 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
2973 Checks.push_back(
2974 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
Chris Lattner8ee6a412010-09-11 21:47:09 +00002975 }
Richard Smithc86a1142012-11-06 02:30:30 +00002976
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002977 if (Checks.size() > 0)
2978 EmitBinOpCheck(Checks, Ops);
Chris Lattner8ee6a412010-09-11 21:47:09 +00002979}
Chris Lattner3d966d62007-08-24 21:00:35 +00002980
Chris Lattner2da04b32007-08-24 05:35:26 +00002981Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002982 {
2983 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002984 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
2985 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Vedant Kumard9191152017-05-02 23:46:56 +00002986 Ops.Ty->isIntegerType() &&
2987 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002988 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
2989 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002990 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
Vedant Kumard9191152017-05-02 23:46:56 +00002991 Ops.Ty->isRealFloatingType() &&
2992 Ops.mayHaveFloatDivisionByZero()) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00002993 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00002994 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
2995 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
2996 Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00002997 }
Chris Lattner8ee6a412010-09-11 21:47:09 +00002998 }
Will Dietz1897cb32012-11-27 15:01:55 +00002999
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003000 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
3001 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Yaxun Liuffb60902016-08-09 20:10:18 +00003002 if (CGF.getLangOpts().OpenCL &&
3003 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
3004 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
3005 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
3006 // build option allows an application to specify that single precision
3007 // floating-point divide (x/y and 1/x) and sqrt used in the program
3008 // source are correctly rounded.
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003009 llvm::Type *ValTy = Val->getType();
3010 if (ValTy->isFloatTy() ||
3011 (isa<llvm::VectorType>(ValTy) &&
3012 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sandse81111c2012-04-10 08:23:07 +00003013 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003014 }
3015 return Val;
3016 }
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003017 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003018 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3019 else
3020 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3021}
3022
3023Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3024 // Rem in C can't be a floating point type: C99 6.5.5p2.
Vedant Kumar42de3802017-02-25 00:43:39 +00003025 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3026 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Vedant Kumard9191152017-05-02 23:46:56 +00003027 Ops.Ty->isIntegerType() &&
3028 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003029 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattner8ee6a412010-09-11 21:47:09 +00003030 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Vedant Kumar42de3802017-02-25 00:43:39 +00003031 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
Chris Lattner8ee6a412010-09-11 21:47:09 +00003032 }
3033
Eli Friedman493c34a2011-04-10 04:44:11 +00003034 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003035 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3036 else
3037 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3038}
3039
Mike Stump0c61b732009-04-01 20:28:16 +00003040Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3041 unsigned IID;
3042 unsigned OpID = 0;
Mike Stump40968592009-04-02 01:03:55 +00003043
Will Dietz1897cb32012-11-27 15:01:55 +00003044 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
Chris Lattner0bf27622010-06-26 21:48:21 +00003045 switch (Ops.Opcode) {
John McCalle3027922010-08-25 11:45:40 +00003046 case BO_Add:
3047 case BO_AddAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003048 OpID = 1;
Will Dietz1897cb32012-11-27 15:01:55 +00003049 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
3050 llvm::Intrinsic::uadd_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003051 break;
John McCalle3027922010-08-25 11:45:40 +00003052 case BO_Sub:
3053 case BO_SubAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003054 OpID = 2;
Will Dietz1897cb32012-11-27 15:01:55 +00003055 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
3056 llvm::Intrinsic::usub_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003057 break;
John McCalle3027922010-08-25 11:45:40 +00003058 case BO_Mul:
3059 case BO_MulAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003060 OpID = 3;
Will Dietz1897cb32012-11-27 15:01:55 +00003061 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
3062 llvm::Intrinsic::umul_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003063 break;
3064 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003065 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump0c61b732009-04-01 20:28:16 +00003066 }
Mike Stumpd3e38852009-04-02 18:15:54 +00003067 OpID <<= 1;
Will Dietz1897cb32012-11-27 15:01:55 +00003068 if (isSigned)
3069 OpID |= 1;
Mike Stumpd3e38852009-04-02 18:15:54 +00003070
Vedant Kumar4b62b5c2017-05-09 23:34:49 +00003071 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattnera5f58b02011-07-09 17:41:47 +00003072 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump0c61b732009-04-01 20:28:16 +00003073
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003074 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump0c61b732009-04-01 20:28:16 +00003075
David Blaikie43f9bb72015-05-18 22:14:03 +00003076 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
Mike Stump0c61b732009-04-01 20:28:16 +00003077 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3078 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3079
Richard Smith4d1458e2012-09-08 02:08:36 +00003080 // Handle overflow with llvm.trap if no custom handler has been specified.
3081 const std::string *handlerName =
Richard Smith9c6890a2012-11-01 22:30:59 +00003082 &CGF.getLangOpts().OverflowHandler;
Richard Smith4d1458e2012-09-08 02:08:36 +00003083 if (handlerName->empty()) {
Richard Smithb1b0ab42012-11-05 22:21:05 +00003084 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
Richard Smithde670682012-11-01 22:15:34 +00003085 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003086 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003087 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003088 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003089 : SanitizerKind::UnsignedIntegerOverflow;
3090 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00003091 } else
Chad Rosierae229d52013-01-29 23:31:22 +00003092 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
Richard Smith4d1458e2012-09-08 02:08:36 +00003093 return result;
3094 }
3095
Mike Stump0c61b732009-04-01 20:28:16 +00003096 // Branch in case of overflow.
David Chisnalldd84ef12010-09-17 18:29:54 +00003097 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Duncan P. N. Exon Smith01f574c2016-08-17 03:15:29 +00003098 llvm::BasicBlock *continueBB =
3099 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
Chris Lattner8139c982010-08-07 00:20:46 +00003100 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump0c61b732009-04-01 20:28:16 +00003101
3102 Builder.CreateCondBr(overflow, overflowBB, continueBB);
3103
David Chisnalldd84ef12010-09-17 18:29:54 +00003104 // If an overflow handler is set, then we want to call it and then use its
3105 // result, if it returns.
3106 Builder.SetInsertPoint(overflowBB);
3107
3108 // Get the overflow handler.
Chris Lattnerece04092012-02-07 00:39:47 +00003109 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattnera5f58b02011-07-09 17:41:47 +00003110 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnalldd84ef12010-09-17 18:29:54 +00003111 llvm::FunctionType *handlerTy =
3112 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
3113 llvm::Value *handler = CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
3114
3115 // Sign extend the args to 64-bit, so that we can use the same handler for
3116 // all types of overflow.
3117 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3118 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3119
3120 // Call the handler with the two arguments, the operation, and the size of
3121 // the result.
John McCall882987f2013-02-28 19:01:20 +00003122 llvm::Value *handlerArgs[] = {
3123 lhs,
3124 rhs,
3125 Builder.getInt8(OpID),
3126 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3127 };
3128 llvm::Value *handlerResult =
3129 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
David Chisnalldd84ef12010-09-17 18:29:54 +00003130
3131 // Truncate the result back to the desired size.
3132 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3133 Builder.CreateBr(continueBB);
3134
Mike Stump0c61b732009-04-01 20:28:16 +00003135 Builder.SetInsertPoint(continueBB);
Jay Foad20c0f022011-03-30 11:28:58 +00003136 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnalldd84ef12010-09-17 18:29:54 +00003137 phi->addIncoming(result, initialBB);
3138 phi->addIncoming(handlerResult, overflowBB);
3139
3140 return phi;
Mike Stump0c61b732009-04-01 20:28:16 +00003141}
Chris Lattner2da04b32007-08-24 05:35:26 +00003142
John McCall77527a82011-06-25 01:32:37 +00003143/// Emit pointer + index arithmetic.
3144static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3145 const BinOpInfo &op,
3146 bool isSubtraction) {
3147 // Must have binary (not unary) expr here. Unary pointer
3148 // increment/decrement doesn't use this path.
3149 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
Craig Toppera97d7e72013-07-26 06:16:11 +00003150
John McCall77527a82011-06-25 01:32:37 +00003151 Value *pointer = op.LHS;
3152 Expr *pointerOperand = expr->getLHS();
3153 Value *index = op.RHS;
3154 Expr *indexOperand = expr->getRHS();
3155
3156 // In a subtraction, the LHS is always the pointer.
3157 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
3158 std::swap(pointer, index);
3159 std::swap(pointerOperand, indexOperand);
3160 }
3161
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003162 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003163
John McCall77527a82011-06-25 01:32:37 +00003164 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
Yaxun Liu26f75662016-08-19 05:17:25 +00003165 auto &DL = CGF.CGM.getDataLayout();
3166 auto PtrTy = cast<llvm::PointerType>(pointer->getType());
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00003167
3168 // Some versions of glibc and gcc use idioms (particularly in their malloc
3169 // routines) that add a pointer-sized integer (known to be a pointer value)
3170 // to a null pointer in order to cast the value back to an integer or as
3171 // part of a pointer alignment algorithm. This is undefined behavior, but
3172 // we'd like to be able to compile programs that use it.
3173 //
3174 // Normally, we'd generate a GEP with a null-pointer base here in response
3175 // to that code, but it's also UB to dereference a pointer created that
3176 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
3177 // generate a direct cast of the integer value to a pointer.
3178 //
3179 // The idiom (p = nullptr + N) is not met if any of the following are true:
3180 //
3181 // The operation is subtraction.
3182 // The index is not pointer-sized.
3183 // The pointer type is not byte-sized.
3184 //
3185 if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
3186 op.Opcode,
Fangrui Song6907ce22018-07-30 19:24:48 +00003187 expr->getLHS(),
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00003188 expr->getRHS()))
3189 return CGF.Builder.CreateIntToPtr(index, pointer->getType());
3190
Yaxun Liu26f75662016-08-19 05:17:25 +00003191 if (width != DL.getTypeSizeInBits(PtrTy)) {
John McCall77527a82011-06-25 01:32:37 +00003192 // Zero-extend or sign-extend the pointer value according to
3193 // whether the index is signed or not.
Yaxun Liu26f75662016-08-19 05:17:25 +00003194 index = CGF.Builder.CreateIntCast(index, DL.getIntPtrType(PtrTy), isSigned,
John McCall77527a82011-06-25 01:32:37 +00003195 "idx.ext");
3196 }
3197
3198 // If this is subtraction, negate the index.
3199 if (isSubtraction)
3200 index = CGF.Builder.CreateNeg(index, "idx.neg");
3201
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003202 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00003203 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
3204 /*Accessed*/ false);
3205
John McCall77527a82011-06-25 01:32:37 +00003206 const PointerType *pointerType
3207 = pointerOperand->getType()->getAs<PointerType>();
3208 if (!pointerType) {
3209 QualType objectType = pointerOperand->getType()
3210 ->castAs<ObjCObjectPointerType>()
3211 ->getPointeeType();
3212 llvm::Value *objectSize
3213 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
3214
3215 index = CGF.Builder.CreateMul(index, objectSize);
3216
3217 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3218 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3219 return CGF.Builder.CreateBitCast(result, pointer->getType());
3220 }
3221
3222 QualType elementType = pointerType->getPointeeType();
3223 if (const VariableArrayType *vla
3224 = CGF.getContext().getAsVariableArrayType(elementType)) {
3225 // The element count here is the total number of non-VLA elements.
Sander de Smalen891af03a2018-02-03 13:55:59 +00003226 llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
John McCall77527a82011-06-25 01:32:37 +00003227
3228 // Effectively, the multiply by the VLA size is part of the GEP.
3229 // GEP indexes are signed, and scaling an index isn't permitted to
3230 // signed-overflow, so we use the same semantics for our explicit
3231 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003232 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003233 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
3234 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3235 } else {
3236 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003237 pointer =
Vedant Kumar175b6d12017-07-13 20:55:26 +00003238 CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003239 op.E->getExprLoc(), "add.ptr");
Chris Lattner51924e512010-06-26 21:25:03 +00003240 }
John McCall77527a82011-06-25 01:32:37 +00003241 return pointer;
Mike Stump4a3999f2009-09-09 13:00:44 +00003242 }
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003243
Mike Stump4a3999f2009-09-09 13:00:44 +00003244 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
3245 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
3246 // future proof.
John McCall77527a82011-06-25 01:32:37 +00003247 if (elementType->isVoidType() || elementType->isFunctionType()) {
3248 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3249 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3250 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stump4a3999f2009-09-09 13:00:44 +00003251 }
3252
David Blaikiebbafb8a2012-03-11 07:00:24 +00003253 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall77527a82011-06-25 01:32:37 +00003254 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3255
Vedant Kumar175b6d12017-07-13 20:55:26 +00003256 return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003257 op.E->getExprLoc(), "add.ptr");
Chris Lattner2da04b32007-08-24 05:35:26 +00003258}
3259
Lang Hames5de91cc2012-10-02 04:45:10 +00003260// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
3261// Addend. Use negMul and negAdd to negate the first operand of the Mul or
3262// the add operand respectively. This allows fmuladd to represent a*b-c, or
3263// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
3264// efficient operations.
3265static Value* buildFMulAdd(llvm::BinaryOperator *MulOp, Value *Addend,
3266 const CodeGenFunction &CGF, CGBuilderTy &Builder,
3267 bool negMul, bool negAdd) {
3268 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
Craig Toppera97d7e72013-07-26 06:16:11 +00003269
Lang Hames5de91cc2012-10-02 04:45:10 +00003270 Value *MulOp0 = MulOp->getOperand(0);
3271 Value *MulOp1 = MulOp->getOperand(1);
3272 if (negMul) {
3273 MulOp0 =
3274 Builder.CreateFSub(
3275 llvm::ConstantFP::getZeroValueForNegation(MulOp0->getType()), MulOp0,
3276 "neg");
3277 } else if (negAdd) {
3278 Addend =
3279 Builder.CreateFSub(
3280 llvm::ConstantFP::getZeroValueForNegation(Addend->getType()), Addend,
3281 "neg");
3282 }
3283
David Blaikie43f9bb72015-05-18 22:14:03 +00003284 Value *FMulAdd = Builder.CreateCall(
Lang Hames5de91cc2012-10-02 04:45:10 +00003285 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
David Blaikie43f9bb72015-05-18 22:14:03 +00003286 {MulOp0, MulOp1, Addend});
Lang Hames5de91cc2012-10-02 04:45:10 +00003287 MulOp->eraseFromParent();
3288
3289 return FMulAdd;
3290}
3291
3292// Check whether it would be legal to emit an fmuladd intrinsic call to
3293// represent op and if so, build the fmuladd.
3294//
3295// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
3296// Does NOT check the type of the operation - it's assumed that this function
3297// will be called from contexts where it's known that the type is contractable.
Craig Toppera97d7e72013-07-26 06:16:11 +00003298static Value* tryEmitFMulAdd(const BinOpInfo &op,
Lang Hames5de91cc2012-10-02 04:45:10 +00003299 const CodeGenFunction &CGF, CGBuilderTy &Builder,
3300 bool isSub=false) {
3301
3302 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
3303 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
3304 "Only fadd/fsub can be the root of an fmuladd.");
3305
3306 // Check whether this op is marked as fusable.
Adam Nemet049a31d2017-03-29 21:54:24 +00003307 if (!op.FPFeatures.allowFPContractWithinStatement())
Craig Topper8a13c412014-05-21 05:09:00 +00003308 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00003309
3310 // We have a potentially fusable op. Look for a mul on one of the operands.
Sanjay Patela30cee62015-12-03 01:25:12 +00003311 // Also, make sure that the mul result isn't used directly. In that case,
3312 // there's no point creating a muladd operation.
3313 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
3314 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3315 LHSBinOp->use_empty())
Lang Hames5de91cc2012-10-02 04:45:10 +00003316 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
Sanjay Patela30cee62015-12-03 01:25:12 +00003317 }
3318 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
3319 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3320 RHSBinOp->use_empty())
Lang Hames5de91cc2012-10-02 04:45:10 +00003321 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
Lang Hames5de91cc2012-10-02 04:45:10 +00003322 }
3323
Craig Topper8a13c412014-05-21 05:09:00 +00003324 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00003325}
3326
John McCall77527a82011-06-25 01:32:37 +00003327Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
3328 if (op.LHS->getType()->isPointerTy() ||
3329 op.RHS->getType()->isPointerTy())
Vedant Kumar175b6d12017-07-13 20:55:26 +00003330 return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
John McCall77527a82011-06-25 01:32:37 +00003331
3332 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003333 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
John McCall77527a82011-06-25 01:32:37 +00003334 case LangOptions::SOB_Defined:
3335 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith3e056de2012-08-25 00:32:28 +00003336 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003337 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00003338 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003339 LLVM_FALLTHROUGH;
John McCall77527a82011-06-25 01:32:37 +00003340 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003341 if (CanElideOverflowCheck(CGF.getContext(), op))
3342 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
John McCall77527a82011-06-25 01:32:37 +00003343 return EmitOverflowCheckedBinOp(op);
3344 }
3345 }
Will Dietz1897cb32012-11-27 15:01:55 +00003346
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003347 if (op.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003348 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3349 !CanElideOverflowCheck(CGF.getContext(), op))
Will Dietz1897cb32012-11-27 15:01:55 +00003350 return EmitOverflowCheckedBinOp(op);
3351
Lang Hames5de91cc2012-10-02 04:45:10 +00003352 if (op.LHS->getType()->isFPOrFPVectorTy()) {
3353 // Try to form an fmuladd.
3354 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
3355 return FMulAdd;
3356
Adam Nemet370d0872017-04-04 21:18:30 +00003357 Value *V = Builder.CreateFAdd(op.LHS, op.RHS, "add");
3358 return propagateFMFlags(V, op);
Lang Hames5de91cc2012-10-02 04:45:10 +00003359 }
John McCall77527a82011-06-25 01:32:37 +00003360
Leonard Chan2044ac82019-01-16 18:13:59 +00003361 if (op.isFixedPointBinOp())
Leonard Chan837da5d2019-01-16 19:53:50 +00003362 return EmitFixedPointBinOp(op);
Leonard Chan2044ac82019-01-16 18:13:59 +00003363
John McCall77527a82011-06-25 01:32:37 +00003364 return Builder.CreateAdd(op.LHS, op.RHS, "add");
3365}
3366
Leonard Chan2044ac82019-01-16 18:13:59 +00003367/// The resulting value must be calculated with exact precision, so the operands
3368/// may not be the same type.
Leonard Chan837da5d2019-01-16 19:53:50 +00003369Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
Leonard Chan2044ac82019-01-16 18:13:59 +00003370 using llvm::APSInt;
3371 using llvm::ConstantInt;
3372
3373 const auto *BinOp = cast<BinaryOperator>(op.E);
Leonard Chan837da5d2019-01-16 19:53:50 +00003374 assert((BinOp->getOpcode() == BO_Add || BinOp->getOpcode() == BO_Sub) &&
3375 "Expected operation to be addition or subtraction");
Leonard Chan2044ac82019-01-16 18:13:59 +00003376
3377 // The result is a fixed point type and at least one of the operands is fixed
3378 // point while the other is either fixed point or an int. This resulting type
3379 // should be determined by Sema::handleFixedPointConversions().
3380 QualType ResultTy = op.Ty;
3381 QualType LHSTy = BinOp->getLHS()->getType();
3382 QualType RHSTy = BinOp->getRHS()->getType();
3383 ASTContext &Ctx = CGF.getContext();
3384 Value *LHS = op.LHS;
3385 Value *RHS = op.RHS;
3386
3387 auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
3388 auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
3389 auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
3390 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
3391
3392 // Convert the operands to the full precision type.
3393 Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema,
3394 BinOp->getExprLoc());
3395 Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema,
3396 BinOp->getExprLoc());
3397
3398 // Perform the actual addition.
3399 Value *Result;
Leonard Chan837da5d2019-01-16 19:53:50 +00003400 switch (BinOp->getOpcode()) {
3401 case BO_Add: {
3402 if (ResultFixedSema.isSaturated()) {
3403 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3404 ? llvm::Intrinsic::sadd_sat
3405 : llvm::Intrinsic::uadd_sat;
3406 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3407 } else {
3408 Result = Builder.CreateAdd(FullLHS, FullRHS);
3409 }
3410 break;
3411 }
3412 case BO_Sub: {
3413 if (ResultFixedSema.isSaturated()) {
3414 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3415 ? llvm::Intrinsic::ssub_sat
3416 : llvm::Intrinsic::usub_sat;
3417 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3418 } else {
3419 Result = Builder.CreateSub(FullLHS, FullRHS);
3420 }
3421 break;
3422 }
3423 case BO_Mul:
3424 case BO_Div:
3425 case BO_Shl:
3426 case BO_Shr:
3427 case BO_Cmp:
3428 case BO_LT:
3429 case BO_GT:
3430 case BO_LE:
3431 case BO_GE:
3432 case BO_EQ:
3433 case BO_NE:
3434 case BO_LAnd:
3435 case BO_LOr:
3436 case BO_MulAssign:
3437 case BO_DivAssign:
3438 case BO_AddAssign:
3439 case BO_SubAssign:
3440 case BO_ShlAssign:
3441 case BO_ShrAssign:
3442 llvm_unreachable("Found unimplemented fixed point binary operation");
3443 case BO_PtrMemD:
3444 case BO_PtrMemI:
3445 case BO_Rem:
3446 case BO_Xor:
3447 case BO_And:
3448 case BO_Or:
3449 case BO_Assign:
3450 case BO_RemAssign:
3451 case BO_AndAssign:
3452 case BO_XorAssign:
3453 case BO_OrAssign:
3454 case BO_Comma:
3455 llvm_unreachable("Found unsupported binary operation for fixed point types.");
Leonard Chan2044ac82019-01-16 18:13:59 +00003456 }
3457
3458 // Convert to the result type.
3459 return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema,
3460 BinOp->getExprLoc());
3461}
3462
John McCall77527a82011-06-25 01:32:37 +00003463Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
3464 // The LHS is always a pointer if either side is.
3465 if (!op.LHS->getType()->isPointerTy()) {
3466 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003467 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +00003468 case LangOptions::SOB_Defined:
John McCall77527a82011-06-25 01:32:37 +00003469 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith3e056de2012-08-25 00:32:28 +00003470 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003471 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00003472 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003473 LLVM_FALLTHROUGH;
Chris Lattner51924e512010-06-26 21:25:03 +00003474 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003475 if (CanElideOverflowCheck(CGF.getContext(), op))
3476 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
John McCall77527a82011-06-25 01:32:37 +00003477 return EmitOverflowCheckedBinOp(op);
Chris Lattner51924e512010-06-26 21:25:03 +00003478 }
3479 }
Will Dietz1897cb32012-11-27 15:01:55 +00003480
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003481 if (op.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003482 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3483 !CanElideOverflowCheck(CGF.getContext(), op))
Will Dietz1897cb32012-11-27 15:01:55 +00003484 return EmitOverflowCheckedBinOp(op);
3485
Lang Hames5de91cc2012-10-02 04:45:10 +00003486 if (op.LHS->getType()->isFPOrFPVectorTy()) {
3487 // Try to form an fmuladd.
3488 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
3489 return FMulAdd;
Adam Nemet370d0872017-04-04 21:18:30 +00003490 Value *V = Builder.CreateFSub(op.LHS, op.RHS, "sub");
3491 return propagateFMFlags(V, op);
Lang Hames5de91cc2012-10-02 04:45:10 +00003492 }
Chris Lattner5902e7b2010-03-29 17:28:16 +00003493
Leonard Chan837da5d2019-01-16 19:53:50 +00003494 if (op.isFixedPointBinOp())
3495 return EmitFixedPointBinOp(op);
3496
John McCall77527a82011-06-25 01:32:37 +00003497 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump0c61b732009-04-01 20:28:16 +00003498 }
Chris Lattner3d966d62007-08-24 21:00:35 +00003499
John McCall77527a82011-06-25 01:32:37 +00003500 // If the RHS is not a pointer, then we have normal pointer
3501 // arithmetic.
3502 if (!op.RHS->getType()->isPointerTy())
Vedant Kumar175b6d12017-07-13 20:55:26 +00003503 return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
Eli Friedmane381f7e2009-03-28 02:45:41 +00003504
John McCall77527a82011-06-25 01:32:37 +00003505 // Otherwise, this is a pointer subtraction.
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00003506
John McCall77527a82011-06-25 01:32:37 +00003507 // Do the raw subtraction part.
3508 llvm::Value *LHS
3509 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
3510 llvm::Value *RHS
3511 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
3512 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003513
John McCall77527a82011-06-25 01:32:37 +00003514 // Okay, figure out the element size.
3515 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3516 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00003517
Craig Topper8a13c412014-05-21 05:09:00 +00003518 llvm::Value *divisor = nullptr;
John McCall77527a82011-06-25 01:32:37 +00003519
3520 // For a variable-length array, this is going to be non-constant.
3521 if (const VariableArrayType *vla
3522 = CGF.getContext().getAsVariableArrayType(elementType)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +00003523 auto VlaSize = CGF.getVLASize(vla);
3524 elementType = VlaSize.Type;
3525 divisor = VlaSize.NumElts;
John McCall77527a82011-06-25 01:32:37 +00003526
3527 // Scale the number of non-VLA elements by the non-VLA element size.
3528 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
3529 if (!eltSize.isOne())
3530 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
3531
3532 // For everything elese, we can just compute it, safe in the
3533 // assumption that Sema won't let anything through that we can't
3534 // safely compute the size of.
3535 } else {
3536 CharUnits elementSize;
3537 // Handle GCC extension for pointer arithmetic on void* and
3538 // function pointer types.
3539 if (elementType->isVoidType() || elementType->isFunctionType())
3540 elementSize = CharUnits::One();
3541 else
3542 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
3543
3544 // Don't even emit the divide for element size of 1.
3545 if (elementSize.isOne())
3546 return diffInChars;
3547
3548 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner2da04b32007-08-24 05:35:26 +00003549 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003550
Chris Lattner2e72da942011-03-01 00:03:48 +00003551 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
3552 // pointer difference in C is only defined in the case where both operands
3553 // are pointing to elements of an array.
John McCall77527a82011-06-25 01:32:37 +00003554 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner2da04b32007-08-24 05:35:26 +00003555}
3556
David Tweed042e0882013-01-07 16:43:27 +00003557Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
David Tweed9fb566c2013-01-10 09:11:33 +00003558 llvm::IntegerType *Ty;
3559 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3560 Ty = cast<llvm::IntegerType>(VT->getElementType());
3561 else
3562 Ty = cast<llvm::IntegerType>(LHS->getType());
3563 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
David Tweed042e0882013-01-07 16:43:27 +00003564}
3565
Chris Lattner2da04b32007-08-24 05:35:26 +00003566Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
3567 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3568 // RHS to the same size as the LHS.
3569 Value *RHS = Ops.RHS;
3570 if (Ops.LHS->getType() != RHS->getType())
3571 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00003572
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003573 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
James Molloy59802322016-08-16 09:45:36 +00003574 Ops.Ty->hasSignedIntegerRepresentation() &&
3575 !CGF.getLangOpts().isSignedOverflowDefined();
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003576 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
3577 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3578 if (CGF.getLangOpts().OpenCL)
3579 RHS =
3580 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
3581 else if ((SanitizeBase || SanitizeExponent) &&
3582 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003583 CodeGenFunction::SanitizerScope SanScope(&CGF);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003584 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
Vedant Kumard3a601b2017-01-30 23:38:54 +00003585 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
3586 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
Richard Smith3e056de2012-08-25 00:32:28 +00003587
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003588 if (SanitizeExponent) {
3589 Checks.push_back(
3590 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
3591 }
3592
3593 if (SanitizeBase) {
3594 // Check whether we are shifting any non-zero bits off the top of the
3595 // integer. We only emit this check if exponent is valid - otherwise
3596 // instructions below will have undefined behavior themselves.
Alexey Samsonov48a9db02015-03-05 21:57:35 +00003597 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
3598 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003599 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
3600 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
Vedant Kumard3a601b2017-01-30 23:38:54 +00003601 llvm::Value *PromotedWidthMinusOne =
3602 (RHS == Ops.RHS) ? WidthMinusOne
3603 : GetWidthMinusOneValue(Ops.LHS, RHS);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003604 CGF.EmitBlock(CheckShiftBase);
Vedant Kumard3a601b2017-01-30 23:38:54 +00003605 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
3606 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
3607 /*NUW*/ true, /*NSW*/ true),
3608 "shl.check");
Richard Smith3e056de2012-08-25 00:32:28 +00003609 if (CGF.getLangOpts().CPlusPlus) {
3610 // In C99, we are not permitted to shift a 1 bit into the sign bit.
3611 // Under C++11's rules, shifting a 1 bit into the sign bit is
3612 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
3613 // define signed left shifts, so we use the C99 and C++11 rules there).
3614 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
3615 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
3616 }
3617 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003618 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
Alexey Samsonov48a9db02015-03-05 21:57:35 +00003619 CGF.EmitBlock(Cont);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003620 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
3621 BaseCheck->addIncoming(Builder.getTrue(), Orig);
3622 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
3623 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
Richard Smith3e056de2012-08-25 00:32:28 +00003624 }
Will Dietz11d0a9f2013-02-25 22:37:49 +00003625
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003626 assert(!Checks.empty());
3627 EmitBinOpCheck(Checks, Ops);
Mike Stumpba6a0c42009-12-14 21:58:14 +00003628 }
3629
Chris Lattner2da04b32007-08-24 05:35:26 +00003630 return Builder.CreateShl(Ops.LHS, RHS, "shl");
3631}
3632
3633Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
3634 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3635 // RHS to the same size as the LHS.
3636 Value *RHS = Ops.RHS;
3637 if (Ops.LHS->getType() != RHS->getType())
3638 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00003639
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003640 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3641 if (CGF.getLangOpts().OpenCL)
3642 RHS =
3643 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
3644 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
3645 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003646 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003647 llvm::Value *Valid =
3648 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003649 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00003650 }
David Tweed042e0882013-01-07 16:43:27 +00003651
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003652 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003653 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
3654 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
3655}
3656
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003657enum IntrinsicType { VCMPEQ, VCMPGT };
3658// return corresponding comparison intrinsic for given vector type
3659static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
3660 BuiltinType::Kind ElemKind) {
3661 switch (ElemKind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003662 default: llvm_unreachable("unexpected element type");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003663 case BuiltinType::Char_U:
3664 case BuiltinType::UChar:
3665 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3666 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003667 case BuiltinType::Char_S:
3668 case BuiltinType::SChar:
3669 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3670 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003671 case BuiltinType::UShort:
3672 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3673 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003674 case BuiltinType::Short:
3675 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3676 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003677 case BuiltinType::UInt:
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003678 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3679 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003680 case BuiltinType::Int:
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003681 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3682 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Guozhi Wei769095b2017-10-19 20:11:23 +00003683 case BuiltinType::ULong:
3684 case BuiltinType::ULongLong:
3685 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3686 llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
3687 case BuiltinType::Long:
3688 case BuiltinType::LongLong:
3689 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3690 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003691 case BuiltinType::Float:
3692 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
3693 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Guozhi Wei769095b2017-10-19 20:11:23 +00003694 case BuiltinType::Double:
3695 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
3696 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003697 }
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003698}
3699
Craig Topperc82f8962015-12-16 06:24:28 +00003700Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
3701 llvm::CmpInst::Predicate UICmpOpc,
3702 llvm::CmpInst::Predicate SICmpOpc,
3703 llvm::CmpInst::Predicate FCmpOpc) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00003704 TestAndClearIgnoreResultAssign();
Chris Lattner42e6b812007-08-26 16:34:22 +00003705 Value *Result;
Chris Lattner2da04b32007-08-24 05:35:26 +00003706 QualType LHSTy = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00003707 QualType RHSTy = E->getRHS()->getType();
John McCall7a9aac22010-08-23 01:21:21 +00003708 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCalle3027922010-08-25 11:45:40 +00003709 assert(E->getOpcode() == BO_EQ ||
3710 E->getOpcode() == BO_NE);
John McCalla1dee5302010-08-22 10:59:02 +00003711 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
3712 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall7a9aac22010-08-23 01:21:21 +00003713 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCalle3027922010-08-25 11:45:40 +00003714 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Chandler Carruthb29a7432014-10-11 11:03:30 +00003715 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
Chris Lattner2da04b32007-08-24 05:35:26 +00003716 Value *LHS = Visit(E->getLHS());
3717 Value *RHS = Visit(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00003718
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003719 // If AltiVec, the comparison results in a numeric type, so we use
3720 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev93900c72011-03-28 21:00:05 +00003721 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003722 // constants for mapping CR6 register bits to predicate result
3723 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
3724
3725 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
3726
3727 // in several cases vector arguments order will be reversed
3728 Value *FirstVecArg = LHS,
3729 *SecondVecArg = RHS;
3730
3731 QualType ElTy = LHSTy->getAs<VectorType>()->getElementType();
John McCall424cec92011-01-19 06:33:43 +00003732 const BuiltinType *BTy = ElTy->getAs<BuiltinType>();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003733 BuiltinType::Kind ElementKind = BTy->getKind();
3734
3735 switch(E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003736 default: llvm_unreachable("is not a comparison operation");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003737 case BO_EQ:
3738 CR6 = CR6_LT;
3739 ID = GetIntrinsic(VCMPEQ, ElementKind);
3740 break;
3741 case BO_NE:
3742 CR6 = CR6_EQ;
3743 ID = GetIntrinsic(VCMPEQ, ElementKind);
3744 break;
3745 case BO_LT:
3746 CR6 = CR6_LT;
3747 ID = GetIntrinsic(VCMPGT, ElementKind);
3748 std::swap(FirstVecArg, SecondVecArg);
3749 break;
3750 case BO_GT:
3751 CR6 = CR6_LT;
3752 ID = GetIntrinsic(VCMPGT, ElementKind);
3753 break;
3754 case BO_LE:
3755 if (ElementKind == BuiltinType::Float) {
3756 CR6 = CR6_LT;
3757 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3758 std::swap(FirstVecArg, SecondVecArg);
3759 }
3760 else {
3761 CR6 = CR6_EQ;
3762 ID = GetIntrinsic(VCMPGT, ElementKind);
3763 }
3764 break;
3765 case BO_GE:
3766 if (ElementKind == BuiltinType::Float) {
3767 CR6 = CR6_LT;
3768 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3769 }
3770 else {
3771 CR6 = CR6_EQ;
3772 ID = GetIntrinsic(VCMPGT, ElementKind);
3773 std::swap(FirstVecArg, SecondVecArg);
3774 }
3775 break;
3776 }
3777
Chris Lattner2531eb42011-04-19 22:55:03 +00003778 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003779 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
David Blaikie43f9bb72015-05-18 22:14:03 +00003780 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
Guozhi Wei3625f3e2017-10-10 20:31:27 +00003781
3782 // The result type of intrinsic may not be same as E->getType().
3783 // If E->getType() is not BoolTy, EmitScalarConversion will do the
3784 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
3785 // do nothing, if ResultTy is not i1 at the same time, it will cause
3786 // crash later.
3787 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
3788 if (ResultTy->getBitWidth() > 1 &&
3789 E->getType() == CGF.getContext().BoolTy)
3790 Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003791 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
3792 E->getExprLoc());
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003793 }
3794
Duncan Sands998f9d92010-02-15 16:14:01 +00003795 if (LHS->getType()->isFPOrFPVectorTy()) {
Craig Topperc82f8962015-12-16 06:24:28 +00003796 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003797 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Craig Topperc82f8962015-12-16 06:24:28 +00003798 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
Chris Lattner2da04b32007-08-24 05:35:26 +00003799 } else {
Eli Friedman3c285242008-05-29 15:09:15 +00003800 // Unsigned integers and pointers.
Piotr Padlewski07058292018-07-02 19:21:36 +00003801
3802 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
3803 !isa<llvm::ConstantPointerNull>(LHS) &&
3804 !isa<llvm::ConstantPointerNull>(RHS)) {
3805
3806 // Dynamic information is required to be stripped for comparisons,
3807 // because it could leak the dynamic information. Based on comparisons
3808 // of pointers to dynamic objects, the optimizer can replace one pointer
3809 // with another, which might be incorrect in presence of invariant
3810 // groups. Comparison with null is safe because null does not carry any
3811 // dynamic information.
3812 if (LHSTy.mayBeDynamicClass())
3813 LHS = Builder.CreateStripInvariantGroup(LHS);
3814 if (RHSTy.mayBeDynamicClass())
3815 RHS = Builder.CreateStripInvariantGroup(RHS);
3816 }
3817
Craig Topperc82f8962015-12-16 06:24:28 +00003818 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
Chris Lattner2da04b32007-08-24 05:35:26 +00003819 }
Chris Lattner2a7deb62009-07-08 01:08:03 +00003820
3821 // If this is a vector comparison, sign extend the result to the appropriate
3822 // vector integer type and return it (don't convert to bool).
3823 if (LHSTy->isVectorType())
3824 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stump4a3999f2009-09-09 13:00:44 +00003825
Chris Lattner2da04b32007-08-24 05:35:26 +00003826 } else {
3827 // Complex Comparison: can only be an equality comparison.
Chandler Carruthb29a7432014-10-11 11:03:30 +00003828 CodeGenFunction::ComplexPairTy LHS, RHS;
3829 QualType CETy;
3830 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
3831 LHS = CGF.EmitComplexExpr(E->getLHS());
3832 CETy = CTy->getElementType();
3833 } else {
3834 LHS.first = Visit(E->getLHS());
3835 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
3836 CETy = LHSTy;
3837 }
3838 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
3839 RHS = CGF.EmitComplexExpr(E->getRHS());
3840 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
3841 CTy->getElementType()) &&
3842 "The element types must always match.");
Chandler Carruth60fdc412014-10-11 11:29:26 +00003843 (void)CTy;
Chandler Carruthb29a7432014-10-11 11:03:30 +00003844 } else {
3845 RHS.first = Visit(E->getRHS());
3846 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
3847 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
3848 "The element types must always match.");
3849 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003850
Chris Lattner42e6b812007-08-26 16:34:22 +00003851 Value *ResultR, *ResultI;
Chris Lattner2da04b32007-08-24 05:35:26 +00003852 if (CETy->isRealFloatingType()) {
Craig Topperc82f8962015-12-16 06:24:28 +00003853 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
3854 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
Chris Lattner2da04b32007-08-24 05:35:26 +00003855 } else {
3856 // Complex comparisons can only be equality comparisons. As such, signed
3857 // and unsigned opcodes are the same.
Craig Topperc82f8962015-12-16 06:24:28 +00003858 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
3859 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
Chris Lattner2da04b32007-08-24 05:35:26 +00003860 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003861
John McCalle3027922010-08-25 11:45:40 +00003862 if (E->getOpcode() == BO_EQ) {
Chris Lattner2da04b32007-08-24 05:35:26 +00003863 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
3864 } else {
John McCalle3027922010-08-25 11:45:40 +00003865 assert(E->getOpcode() == BO_NE &&
Chris Lattner2da04b32007-08-24 05:35:26 +00003866 "Complex comparison other than == or != ?");
3867 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
3868 }
3869 }
Nuno Lopesa0abe622009-01-11 23:22:37 +00003870
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003871 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
3872 E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00003873}
3874
3875Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00003876 bool Ignore = TestAndClearIgnoreResultAssign();
3877
John McCall31168b02011-06-15 23:02:42 +00003878 Value *RHS;
3879 LValue LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00003880
John McCall31168b02011-06-15 23:02:42 +00003881 switch (E->getLHS()->getType().getObjCLifetime()) {
3882 case Qualifiers::OCL_Strong:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003883 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
John McCall31168b02011-06-15 23:02:42 +00003884 break;
3885
3886 case Qualifiers::OCL_Autoreleasing:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00003887 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
John McCall31168b02011-06-15 23:02:42 +00003888 break;
3889
John McCalle399e5b2016-01-27 18:32:30 +00003890 case Qualifiers::OCL_ExplicitNone:
3891 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
3892 break;
3893
John McCall31168b02011-06-15 23:02:42 +00003894 case Qualifiers::OCL_Weak:
3895 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00003896 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall31168b02011-06-15 23:02:42 +00003897 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
3898 break;
3899
John McCall31168b02011-06-15 23:02:42 +00003900 case Qualifiers::OCL_None:
John McCall31168b02011-06-15 23:02:42 +00003901 // __block variables need to have the rhs evaluated first, plus
3902 // this should improve codegen just a little.
3903 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00003904 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall31168b02011-06-15 23:02:42 +00003905
3906 // Store the value into the LHS. Bit-fields are handled specially
3907 // because the result is altered by the store, i.e., [C99 6.5.16p1]
3908 // 'An assignment expression has the value of the left operand after
3909 // the assignment...'.
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003910 if (LHS.isBitField()) {
John McCall55e1fbc2011-06-25 02:11:03 +00003911 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003912 } else {
3913 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00003914 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +00003915 }
John McCall31168b02011-06-15 23:02:42 +00003916 }
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003917
3918 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00003919 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00003920 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003921
John McCall07bb1962010-11-16 10:08:07 +00003922 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00003923 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00003924 return RHS;
3925
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003926 // If the lvalue is non-volatile, return the computed value of the assignment.
3927 if (!LHS.isVolatileQualified())
3928 return RHS;
3929
3930 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00003931 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00003932}
3933
3934Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00003935 // Perform vector logical and on comparisons with zero vectors.
3936 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00003937 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003938
Tanya Lattner20248222012-01-16 21:02:28 +00003939 Value *LHS = Visit(E->getLHS());
3940 Value *RHS = Visit(E->getRHS());
3941 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00003942 if (LHS->getType()->isFPOrFPVectorTy()) {
3943 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
3944 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
3945 } else {
3946 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
3947 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
3948 }
Tanya Lattner20248222012-01-16 21:02:28 +00003949 Value *And = Builder.CreateAnd(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00003950 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00003951 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003952
Chris Lattner2192fe52011-07-18 04:24:23 +00003953 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00003954
Chris Lattner8b084582008-11-12 08:26:50 +00003955 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
3956 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00003957 bool LHSCondVal;
3958 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
3959 if (LHSCondVal) { // If we have 1 && X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00003960 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00003961
Chris Lattner5b1964b2008-11-11 07:41:27 +00003962 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00003963 // ZExt result to int or bool.
3964 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00003965 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003966
Chris Lattner671fec82009-10-17 04:24:20 +00003967 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner8b084582008-11-12 08:26:50 +00003968 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00003969 return llvm::Constant::getNullValue(ResTy);
Chris Lattner5b1964b2008-11-11 07:41:27 +00003970 }
Mike Stump4a3999f2009-09-09 13:00:44 +00003971
Daniel Dunbara612e792008-11-13 01:38:36 +00003972 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
3973 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner8b084582008-11-12 08:26:50 +00003974
John McCallce1de612011-01-26 04:00:11 +00003975 CodeGenFunction::ConditionalEvaluation eval(CGF);
3976
Chris Lattner35710d182008-11-12 08:38:24 +00003977 // Branch on the LHS first. If it is false, go to the failure (cont) block.
Justin Bogner66242d62015-04-23 23:06:47 +00003978 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
3979 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00003980
3981 // Any edges into the ContBlock are now from an (indeterminate number of)
3982 // edges from this first condition. All of these values will be false. Start
3983 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00003984 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00003985 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00003986 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
3987 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00003988 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stump4a3999f2009-09-09 13:00:44 +00003989
John McCallce1de612011-01-26 04:00:11 +00003990 eval.begin(CGF);
Chris Lattner2da04b32007-08-24 05:35:26 +00003991 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00003992 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00003993 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCallce1de612011-01-26 04:00:11 +00003994 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00003995
Chris Lattner2da04b32007-08-24 05:35:26 +00003996 // Reaquire the RHS block, as there may be subblocks inserted.
3997 RHSBlock = Builder.GetInsertBlock();
Chris Lattner35710d182008-11-12 08:38:24 +00003998
David Blaikie1b5adb82014-07-10 20:42:59 +00003999 // Emit an unconditional branch from this block to ContBlock.
4000 {
Devang Patel4d761272011-03-30 00:08:31 +00004001 // There is no need to emit line number for unconditional branch.
Adrian Prantl95b24e92015-02-03 20:00:54 +00004002 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
David Blaikie1b5adb82014-07-10 20:42:59 +00004003 CGF.EmitBlock(ContBlock);
4004 }
4005 // Insert an entry into the phi node for the edge with the value of RHSCond.
Chris Lattner2da04b32007-08-24 05:35:26 +00004006 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004007
Anastasis Grammenosdfe8fe52018-06-21 16:53:48 +00004008 // Artificial location to preserve the scope information
4009 {
4010 auto NL = ApplyDebugLocation::CreateArtificial(CGF);
4011 PN->setDebugLoc(Builder.getCurrentDebugLocation());
4012 }
4013
Chris Lattner2da04b32007-08-24 05:35:26 +00004014 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00004015 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00004016}
4017
4018Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00004019 // Perform vector logical or on comparisons with zero vectors.
4020 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00004021 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004022
Tanya Lattner20248222012-01-16 21:02:28 +00004023 Value *LHS = Visit(E->getLHS());
4024 Value *RHS = Visit(E->getRHS());
4025 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00004026 if (LHS->getType()->isFPOrFPVectorTy()) {
4027 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4028 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4029 } else {
4030 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4031 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4032 }
Tanya Lattner20248222012-01-16 21:02:28 +00004033 Value *Or = Builder.CreateOr(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00004034 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00004035 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004036
Chris Lattner2192fe52011-07-18 04:24:23 +00004037 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00004038
Chris Lattner8b084582008-11-12 08:26:50 +00004039 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
4040 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00004041 bool LHSCondVal;
4042 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4043 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00004044 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004045
Chris Lattner5b1964b2008-11-11 07:41:27 +00004046 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00004047 // ZExt result to int or bool.
4048 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00004049 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004050
Chris Lattner671fec82009-10-17 04:24:20 +00004051 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner8b084582008-11-12 08:26:50 +00004052 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00004053 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner5b1964b2008-11-11 07:41:27 +00004054 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004055
Daniel Dunbara612e792008-11-13 01:38:36 +00004056 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
4057 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stump4a3999f2009-09-09 13:00:44 +00004058
John McCallce1de612011-01-26 04:00:11 +00004059 CodeGenFunction::ConditionalEvaluation eval(CGF);
4060
Chris Lattner35710d182008-11-12 08:38:24 +00004061 // Branch on the LHS first. If it is true, go to the success (cont) block.
Justin Bogneref512b92014-01-06 22:27:43 +00004062 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00004063 CGF.getCurrentProfileCount() -
4064 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00004065
4066 // Any edges into the ContBlock are now from an (indeterminate number of)
4067 // edges from this first condition. All of these values will be true. Start
4068 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00004069 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00004070 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00004071 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4072 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00004073 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattner35710d182008-11-12 08:38:24 +00004074
John McCallce1de612011-01-26 04:00:11 +00004075 eval.begin(CGF);
Anders Carlssonf47a3de2009-06-04 02:53:13 +00004076
Chris Lattner35710d182008-11-12 08:38:24 +00004077 // Emit the RHS condition as a bool value.
Chris Lattner2da04b32007-08-24 05:35:26 +00004078 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004079 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00004080 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00004081
John McCallce1de612011-01-26 04:00:11 +00004082 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004083
Chris Lattner2da04b32007-08-24 05:35:26 +00004084 // Reaquire the RHS block, as there may be subblocks inserted.
4085 RHSBlock = Builder.GetInsertBlock();
Mike Stump4a3999f2009-09-09 13:00:44 +00004086
Chris Lattner35710d182008-11-12 08:38:24 +00004087 // Emit an unconditional branch from this block to ContBlock. Insert an entry
4088 // into the phi node for the edge with the value of RHSCond.
4089 CGF.EmitBlock(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00004090 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004091
Chris Lattner2da04b32007-08-24 05:35:26 +00004092 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00004093 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00004094}
4095
4096Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +00004097 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004098 CGF.EnsureInsertPoint();
Chris Lattner2da04b32007-08-24 05:35:26 +00004099 return Visit(E->getRHS());
4100}
4101
4102//===----------------------------------------------------------------------===//
4103// Other Operators
4104//===----------------------------------------------------------------------===//
4105
Chris Lattner3fd91f832008-11-12 08:55:54 +00004106/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
4107/// expression is cheap enough and side-effect-free enough to evaluate
4108/// unconditionally instead of conditionally. This is used to convert control
4109/// flow into selects in some cases.
Mike Stump53f9ded2009-11-03 23:25:48 +00004110static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
4111 CodeGenFunction &CGF) {
Chris Lattner56784f92011-04-16 23:15:35 +00004112 // Anything that is an integer or floating point constant is fine.
Nick Lewycky22e55a02013-11-08 23:00:12 +00004113 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
Mike Stump4a3999f2009-09-09 13:00:44 +00004114
Nick Lewycky22e55a02013-11-08 23:00:12 +00004115 // Even non-volatile automatic variables can't be evaluated unconditionally.
4116 // Referencing a thread_local may cause non-trivial initialization work to
4117 // occur. If we're inside a lambda and one of the variables is from the scope
4118 // outside the lambda, that function may have returned already. Reading its
4119 // locals is a bad idea. Also, these reads may introduce races there didn't
4120 // exist in the source-level program.
Chris Lattner3fd91f832008-11-12 08:55:54 +00004121}
4122
4123
Chris Lattner2da04b32007-08-24 05:35:26 +00004124Value *ScalarExprEmitter::
John McCallc07a0c72011-02-17 10:25:35 +00004125VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00004126 TestAndClearIgnoreResultAssign();
John McCallc07a0c72011-02-17 10:25:35 +00004127
4128 // Bind the common expression if necessary.
Eli Friedman48fd89a2012-01-06 20:42:20 +00004129 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCallc07a0c72011-02-17 10:25:35 +00004130
4131 Expr *condExpr = E->getCond();
4132 Expr *lhsExpr = E->getTrueExpr();
4133 Expr *rhsExpr = E->getFalseExpr();
4134
Chris Lattnercd439292008-11-12 08:04:58 +00004135 // If the condition constant folds and can be elided, try to avoid emitting
4136 // the condition and the dead arm.
Chris Lattner41c6ab52011-02-27 23:02:32 +00004137 bool CondExprBool;
4138 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00004139 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattner41c6ab52011-02-27 23:02:32 +00004140 if (!CondExprBool) std::swap(live, dead);
Mike Stump4a3999f2009-09-09 13:00:44 +00004141
Eli Friedman27ef75b2011-10-15 02:10:40 +00004142 // If the dead side doesn't have labels we need, just emit the Live part.
4143 if (!CGF.ContainsLabel(dead)) {
Justin Bogneref512b92014-01-06 22:27:43 +00004144 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00004145 CGF.incrementProfileCounter(E);
Eli Friedman27ef75b2011-10-15 02:10:40 +00004146 Value *Result = Visit(live);
4147
4148 // If the live part is a throw expression, it acts like it has a void
4149 // type, so evaluating it returns a null Value*. However, a conditional
4150 // with non-void type must return a non-null Value*.
4151 if (!Result && !E->getType()->isVoidType())
4152 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
4153
4154 return Result;
4155 }
Chris Lattnerd53e2332008-11-11 18:56:45 +00004156 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004157
Nate Begemanabb5a732010-09-20 22:41:17 +00004158 // OpenCL: If the condition is a vector, we can treat this condition like
4159 // the select function.
Craig Toppera97d7e72013-07-26 06:16:11 +00004160 if (CGF.getLangOpts().OpenCL
John McCallc07a0c72011-02-17 10:25:35 +00004161 && condExpr->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00004162 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004163
John McCallc07a0c72011-02-17 10:25:35 +00004164 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4165 llvm::Value *LHS = Visit(lhsExpr);
4166 llvm::Value *RHS = Visit(rhsExpr);
Craig Toppera97d7e72013-07-26 06:16:11 +00004167
Chris Lattner2192fe52011-07-18 04:24:23 +00004168 llvm::Type *condType = ConvertType(condExpr->getType());
4169 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Craig Toppera97d7e72013-07-26 06:16:11 +00004170
4171 unsigned numElem = vecTy->getNumElements();
Chris Lattner2192fe52011-07-18 04:24:23 +00004172 llvm::Type *elemType = vecTy->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00004173
Chris Lattner2d6b7b92012-01-25 05:34:41 +00004174 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begemanabb5a732010-09-20 22:41:17 +00004175 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
Craig Toppera97d7e72013-07-26 06:16:11 +00004176 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
Nate Begemanabb5a732010-09-20 22:41:17 +00004177 llvm::VectorType::get(elemType,
Craig Toppera97d7e72013-07-26 06:16:11 +00004178 numElem),
Nate Begemanabb5a732010-09-20 22:41:17 +00004179 "sext");
4180 llvm::Value *tmp2 = Builder.CreateNot(tmp);
Craig Toppera97d7e72013-07-26 06:16:11 +00004181
Nate Begemanabb5a732010-09-20 22:41:17 +00004182 // Cast float to int to perform ANDs if necessary.
4183 llvm::Value *RHSTmp = RHS;
4184 llvm::Value *LHSTmp = LHS;
4185 bool wasCast = false;
Chris Lattner2192fe52011-07-18 04:24:23 +00004186 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourneaac265c2012-05-29 00:35:18 +00004187 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begemanabb5a732010-09-20 22:41:17 +00004188 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
4189 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
4190 wasCast = true;
4191 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004192
Nate Begemanabb5a732010-09-20 22:41:17 +00004193 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
4194 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
4195 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
4196 if (wasCast)
4197 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
4198
4199 return tmp5;
4200 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004201
Chris Lattner3fd91f832008-11-12 08:55:54 +00004202 // If this is a really simple expression (like x ? 4 : 5), emit this as a
4203 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner9ce8a532008-11-16 06:16:27 +00004204 // safe to evaluate the LHS and RHS unconditionally.
John McCallc07a0c72011-02-17 10:25:35 +00004205 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
4206 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
4207 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
Vedant Kumar502bbfa2017-02-25 06:35:45 +00004208 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
4209
4210 CGF.incrementProfileCounter(E, StepV);
4211
John McCallc07a0c72011-02-17 10:25:35 +00004212 llvm::Value *LHS = Visit(lhsExpr);
4213 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman516c2ad2011-12-08 22:01:56 +00004214 if (!LHS) {
4215 // If the conditional has void type, make sure we return a null Value*.
4216 assert(!RHS && "LHS and RHS types must match");
Craig Topper8a13c412014-05-21 05:09:00 +00004217 return nullptr;
Eli Friedman516c2ad2011-12-08 22:01:56 +00004218 }
Chris Lattner3fd91f832008-11-12 08:55:54 +00004219 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
4220 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004221
Daniel Dunbard2a53a72008-11-12 10:13:37 +00004222 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
4223 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbara612e792008-11-13 01:38:36 +00004224 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCallce1de612011-01-26 04:00:11 +00004225
4226 CodeGenFunction::ConditionalEvaluation eval(CGF);
Justin Bogner66242d62015-04-23 23:06:47 +00004227 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
4228 CGF.getProfileCount(lhsExpr));
Anders Carlsson43c52cd2009-06-04 03:00:32 +00004229
Chris Lattner2da04b32007-08-24 05:35:26 +00004230 CGF.EmitBlock(LHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004231 CGF.incrementProfileCounter(E);
John McCallce1de612011-01-26 04:00:11 +00004232 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00004233 Value *LHS = Visit(lhsExpr);
John McCallce1de612011-01-26 04:00:11 +00004234 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004235
Chris Lattner2da04b32007-08-24 05:35:26 +00004236 LHSBlock = Builder.GetInsertBlock();
John McCallce1de612011-01-26 04:00:11 +00004237 Builder.CreateBr(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004238
Chris Lattner2da04b32007-08-24 05:35:26 +00004239 CGF.EmitBlock(RHSBlock);
John McCallce1de612011-01-26 04:00:11 +00004240 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00004241 Value *RHS = Visit(rhsExpr);
John McCallce1de612011-01-26 04:00:11 +00004242 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004243
John McCallce1de612011-01-26 04:00:11 +00004244 RHSBlock = Builder.GetInsertBlock();
Chris Lattner2da04b32007-08-24 05:35:26 +00004245 CGF.EmitBlock(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004246
Eli Friedmanf6c175b2009-12-07 20:25:53 +00004247 // If the LHS or RHS is a throw expression, it will be legitimately null.
4248 if (!LHS)
4249 return RHS;
4250 if (!RHS)
4251 return LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00004252
Chris Lattner2da04b32007-08-24 05:35:26 +00004253 // Create a PHI node for the real part.
Jay Foad20c0f022011-03-30 11:28:58 +00004254 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner2da04b32007-08-24 05:35:26 +00004255 PN->addIncoming(LHS, LHSBlock);
4256 PN->addIncoming(RHS, RHSBlock);
4257 return PN;
4258}
4259
4260Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman75807f22013-07-20 00:40:58 +00004261 return Visit(E->getChosenSubExpr());
Chris Lattner2da04b32007-08-24 05:35:26 +00004262}
4263
Chris Lattnerb6a7b582007-11-30 17:56:23 +00004264Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Richard Smitha1a808c2014-04-14 23:47:48 +00004265 QualType Ty = VE->getType();
Daniel Sanders59229dc2014-11-19 10:01:35 +00004266
Richard Smitha1a808c2014-04-14 23:47:48 +00004267 if (Ty->isVariablyModifiedType())
4268 CGF.EmitVariablyModifiedType(Ty);
4269
Charles Davisc7d5c942015-09-17 20:55:33 +00004270 Address ArgValue = Address::invalid();
4271 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
4272
Daniel Sanders59229dc2014-11-19 10:01:35 +00004273 llvm::Type *ArgTy = ConvertType(VE->getType());
Anders Carlsson13abd7e2008-11-04 05:30:00 +00004274
James Y Knight29b5f082016-02-24 02:59:33 +00004275 // If EmitVAArg fails, emit an error.
4276 if (!ArgPtr.isValid()) {
4277 CGF.ErrorUnsupported(VE, "va_arg expression");
4278 return llvm::UndefValue::get(ArgTy);
4279 }
Anders Carlsson13abd7e2008-11-04 05:30:00 +00004280
Mike Stumpdf0fe272009-05-29 15:46:01 +00004281 // FIXME Volatility.
Daniel Sanders59229dc2014-11-19 10:01:35 +00004282 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
4283
4284 // If EmitVAArg promoted the type, we must truncate it.
Daniel Sanderscdcb5802015-01-13 10:47:00 +00004285 if (ArgTy != Val->getType()) {
4286 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
4287 Val = Builder.CreateIntToPtr(Val, ArgTy);
4288 else
4289 Val = Builder.CreateTrunc(Val, ArgTy);
4290 }
Daniel Sanders59229dc2014-11-19 10:01:35 +00004291
4292 return Val;
Anders Carlsson7e13ab82007-10-15 20:28:48 +00004293}
4294
John McCall351762c2011-02-07 10:33:21 +00004295Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
4296 return CGF.EmitBlockLiteral(block);
Mike Stumpab3afd82009-02-12 18:29:15 +00004297}
4298
Yaxun Liuc5647012016-06-08 15:11:21 +00004299// Convert a vec3 to vec4, or vice versa.
4300static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
4301 Value *Src, unsigned NumElementsDst) {
4302 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
4303 SmallVector<llvm::Constant*, 4> Args;
4304 Args.push_back(Builder.getInt32(0));
4305 Args.push_back(Builder.getInt32(1));
4306 Args.push_back(Builder.getInt32(2));
4307 if (NumElementsDst == 4)
4308 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
4309 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
4310 return Builder.CreateShuffleVector(Src, UnV, Mask);
4311}
4312
Yaxun Liuea6b7962016-10-03 14:41:50 +00004313// Create cast instructions for converting LLVM value \p Src to LLVM type \p
4314// DstTy. \p Src has the same size as \p DstTy. Both are single value types
4315// but could be scalar or vectors of different lengths, and either can be
4316// pointer.
4317// There are 4 cases:
4318// 1. non-pointer -> non-pointer : needs 1 bitcast
4319// 2. pointer -> pointer : needs 1 bitcast or addrspacecast
4320// 3. pointer -> non-pointer
4321// a) pointer -> intptr_t : needs 1 ptrtoint
4322// b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
4323// 4. non-pointer -> pointer
4324// a) intptr_t -> pointer : needs 1 inttoptr
4325// b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
4326// Note: for cases 3b and 4b two casts are required since LLVM casts do not
4327// allow casting directly between pointer types and non-integer non-pointer
4328// types.
4329static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
4330 const llvm::DataLayout &DL,
4331 Value *Src, llvm::Type *DstTy,
4332 StringRef Name = "") {
4333 auto SrcTy = Src->getType();
4334
4335 // Case 1.
4336 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
4337 return Builder.CreateBitCast(Src, DstTy, Name);
4338
4339 // Case 2.
4340 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
4341 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
4342
4343 // Case 3.
4344 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
4345 // Case 3b.
4346 if (!DstTy->isIntegerTy())
4347 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
4348 // Cases 3a and 3b.
4349 return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
4350 }
4351
4352 // Case 4b.
4353 if (!SrcTy->isIntegerTy())
4354 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
4355 // Cases 4a and 4b.
4356 return Builder.CreateIntToPtr(Src, DstTy, Name);
4357}
4358
Tanya Lattner55808c12011-06-04 00:47:47 +00004359Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
4360 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2192fe52011-07-18 04:24:23 +00004361 llvm::Type *DstTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00004362
Chris Lattner2192fe52011-07-18 04:24:23 +00004363 llvm::Type *SrcTy = Src->getType();
Yaxun Liuc5647012016-06-08 15:11:21 +00004364 unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
4365 cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
4366 unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
4367 cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
Craig Toppera97d7e72013-07-26 06:16:11 +00004368
Yaxun Liuc5647012016-06-08 15:11:21 +00004369 // Going from vec3 to non-vec3 is a special case and requires a shuffle
4370 // vector to get a vec4, then a bitcast if the target type is different.
4371 if (NumElementsSrc == 3 && NumElementsDst != 3) {
4372 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00004373
4374 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4375 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4376 DstTy);
4377 }
4378
Yaxun Liuc5647012016-06-08 15:11:21 +00004379 Src->setName("astype");
4380 return Src;
4381 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004382
Yaxun Liuc5647012016-06-08 15:11:21 +00004383 // Going from non-vec3 to vec3 is a special case and requires a bitcast
4384 // to vec4 if the original type is not vec4, then a shuffle vector to
4385 // get a vec3.
4386 if (NumElementsSrc != 3 && NumElementsDst == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00004387 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4388 auto Vec4Ty = llvm::VectorType::get(DstTy->getVectorElementType(), 4);
4389 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4390 Vec4Ty);
4391 }
4392
Yaxun Liuc5647012016-06-08 15:11:21 +00004393 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
4394 Src->setName("astype");
4395 return Src;
Tanya Lattner55808c12011-06-04 00:47:47 +00004396 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004397
Yaxun Liuea6b7962016-10-03 14:41:50 +00004398 return Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
4399 Src, DstTy, "astype");
Tanya Lattner55808c12011-06-04 00:47:47 +00004400}
4401
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004402Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
4403 return CGF.EmitAtomicExpr(E).getScalarVal();
4404}
4405
Chris Lattner2da04b32007-08-24 05:35:26 +00004406//===----------------------------------------------------------------------===//
4407// Entry Point into this File
4408//===----------------------------------------------------------------------===//
4409
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004410/// Emit the computation of the specified expression of scalar type, ignoring
4411/// the result.
Mike Stumpdf0fe272009-05-29 15:46:01 +00004412Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
John McCall47fb9502013-03-07 21:37:08 +00004413 assert(E && hasScalarEvaluationKind(E->getType()) &&
Chris Lattner2da04b32007-08-24 05:35:26 +00004414 "Invalid scalar expression to emit");
Mike Stump4a3999f2009-09-09 13:00:44 +00004415
David Blaikie38b25912015-02-09 19:13:51 +00004416 return ScalarExprEmitter(*this, IgnoreResultAssign)
4417 .Visit(const_cast<Expr *>(E));
Chris Lattner2da04b32007-08-24 05:35:26 +00004418}
Chris Lattner3474c202007-08-26 06:48:56 +00004419
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004420/// Emit a conversion from the specified type to the specified destination type,
4421/// both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00004422Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004423 QualType DstTy,
4424 SourceLocation Loc) {
John McCall47fb9502013-03-07 21:37:08 +00004425 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
Chris Lattner3474c202007-08-26 06:48:56 +00004426 "Invalid scalar expression to emit");
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004427 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
Chris Lattner3474c202007-08-26 06:48:56 +00004428}
Chris Lattner42e6b812007-08-26 16:34:22 +00004429
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004430/// Emit a conversion from the specified complex type to the specified
4431/// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +00004432Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
4433 QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004434 QualType DstTy,
4435 SourceLocation Loc) {
John McCall47fb9502013-03-07 21:37:08 +00004436 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
Chris Lattner42e6b812007-08-26 16:34:22 +00004437 "Invalid complex -> scalar conversion");
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004438 return ScalarExprEmitter(*this)
4439 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
Chris Lattner42e6b812007-08-26 16:34:22 +00004440}
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00004441
Chris Lattner05dc78c2010-06-26 22:09:34 +00004442
4443llvm::Value *CodeGenFunction::
4444EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
4445 bool isInc, bool isPre) {
4446 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
4447}
4448
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004449LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004450 // object->isa or (*object).isa
4451 // Generate code as for: *(Class*)object
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00004452
4453 Expr *BaseExpr = E->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00004454 Address Addr = Address::invalid();
John McCall086a4642010-11-24 05:12:34 +00004455 if (BaseExpr->isRValue()) {
John McCall7f416cc2015-09-08 08:05:57 +00004456 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00004457 } else {
John McCall7f416cc2015-09-08 08:05:57 +00004458 Addr = EmitLValue(BaseExpr).getAddress();
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00004459 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004460
John McCall7f416cc2015-09-08 08:05:57 +00004461 // Cast the address to Class*.
4462 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
4463 return MakeAddrLValue(Addr, E->getType());
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004464}
4465
Douglas Gregor914af212010-04-23 04:16:32 +00004466
John McCalla2342eb2010-12-05 02:00:02 +00004467LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor914af212010-04-23 04:16:32 +00004468 const CompoundAssignOperator *E) {
4469 ScalarExprEmitter Scalar(*this);
Craig Topper8a13c412014-05-21 05:09:00 +00004470 Value *Result = nullptr;
Douglas Gregor914af212010-04-23 04:16:32 +00004471 switch (E->getOpcode()) {
4472#define COMPOUND_OP(Op) \
John McCalle3027922010-08-25 11:45:40 +00004473 case BO_##Op##Assign: \
Douglas Gregor914af212010-04-23 04:16:32 +00004474 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004475 Result)
Douglas Gregor914af212010-04-23 04:16:32 +00004476 COMPOUND_OP(Mul);
4477 COMPOUND_OP(Div);
4478 COMPOUND_OP(Rem);
4479 COMPOUND_OP(Add);
4480 COMPOUND_OP(Sub);
4481 COMPOUND_OP(Shl);
4482 COMPOUND_OP(Shr);
4483 COMPOUND_OP(And);
4484 COMPOUND_OP(Xor);
4485 COMPOUND_OP(Or);
4486#undef COMPOUND_OP
Craig Toppera97d7e72013-07-26 06:16:11 +00004487
John McCalle3027922010-08-25 11:45:40 +00004488 case BO_PtrMemD:
4489 case BO_PtrMemI:
4490 case BO_Mul:
4491 case BO_Div:
4492 case BO_Rem:
4493 case BO_Add:
4494 case BO_Sub:
4495 case BO_Shl:
4496 case BO_Shr:
4497 case BO_LT:
4498 case BO_GT:
4499 case BO_LE:
4500 case BO_GE:
4501 case BO_EQ:
4502 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00004503 case BO_Cmp:
John McCalle3027922010-08-25 11:45:40 +00004504 case BO_And:
4505 case BO_Xor:
4506 case BO_Or:
4507 case BO_LAnd:
4508 case BO_LOr:
4509 case BO_Assign:
4510 case BO_Comma:
David Blaikie83d382b2011-09-23 05:06:16 +00004511 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor914af212010-04-23 04:16:32 +00004512 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004513
Douglas Gregor914af212010-04-23 04:16:32 +00004514 llvm_unreachable("Unhandled compound assignment operator");
4515}
Vedant Kumara125eb52017-06-01 19:22:18 +00004516
4517Value *CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr,
4518 ArrayRef<Value *> IdxList,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004519 bool SignedIndices,
Vedant Kumar175b6d12017-07-13 20:55:26 +00004520 bool IsSubtraction,
Vedant Kumara125eb52017-06-01 19:22:18 +00004521 SourceLocation Loc,
4522 const Twine &Name) {
4523 Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
4524
4525 // If the pointer overflow sanitizer isn't enabled, do nothing.
4526 if (!SanOpts.has(SanitizerKind::PointerOverflow))
4527 return GEPVal;
4528
4529 // If the GEP has already been reduced to a constant, leave it be.
4530 if (isa<llvm::Constant>(GEPVal))
4531 return GEPVal;
4532
4533 // Only check for overflows in the default address space.
4534 if (GEPVal->getType()->getPointerAddressSpace())
4535 return GEPVal;
4536
4537 auto *GEP = cast<llvm::GEPOperator>(GEPVal);
4538 assert(GEP->isInBounds() && "Expected inbounds GEP");
4539
4540 SanitizerScope SanScope(this);
4541 auto &VMContext = getLLVMContext();
4542 const auto &DL = CGM.getDataLayout();
4543 auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
4544
4545 // Grab references to the signed add/mul overflow intrinsics for intptr_t.
4546 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4547 auto *SAddIntrinsic =
4548 CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
4549 auto *SMulIntrinsic =
4550 CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
4551
4552 // The total (signed) byte offset for the GEP.
4553 llvm::Value *TotalOffset = nullptr;
4554 // The offset overflow flag - true if the total offset overflows.
4555 llvm::Value *OffsetOverflows = Builder.getFalse();
4556
4557 /// Return the result of the given binary operation.
4558 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
4559 llvm::Value *RHS) -> llvm::Value * {
Davide Italiano77378e42017-06-01 23:55:18 +00004560 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
Vedant Kumara125eb52017-06-01 19:22:18 +00004561
4562 // If the operands are constants, return a constant result.
4563 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
4564 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
4565 llvm::APInt N;
4566 bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
4567 /*Signed=*/true, N);
4568 if (HasOverflow)
4569 OffsetOverflows = Builder.getTrue();
4570 return llvm::ConstantInt::get(VMContext, N);
4571 }
4572 }
4573
4574 // Otherwise, compute the result with checked arithmetic.
4575 auto *ResultAndOverflow = Builder.CreateCall(
4576 (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
4577 OffsetOverflows = Builder.CreateOr(
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004578 Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
Vedant Kumara125eb52017-06-01 19:22:18 +00004579 return Builder.CreateExtractValue(ResultAndOverflow, 0);
4580 };
4581
4582 // Determine the total byte offset by looking at each GEP operand.
4583 for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
4584 GTI != GTE; ++GTI) {
4585 llvm::Value *LocalOffset;
4586 auto *Index = GTI.getOperand();
4587 // Compute the local offset contributed by this indexing step:
4588 if (auto *STy = GTI.getStructTypeOrNull()) {
4589 // For struct indexing, the local offset is the byte position of the
4590 // specified field.
4591 unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
4592 LocalOffset = llvm::ConstantInt::get(
4593 IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
4594 } else {
4595 // Otherwise this is array-like indexing. The local offset is the index
4596 // multiplied by the element size.
4597 auto *ElementSize = llvm::ConstantInt::get(
4598 IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
4599 auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
4600 LocalOffset = eval(BO_Mul, ElementSize, IndexS);
4601 }
4602
4603 // If this is the first offset, set it as the total offset. Otherwise, add
4604 // the local offset into the running total.
4605 if (!TotalOffset || TotalOffset == Zero)
4606 TotalOffset = LocalOffset;
4607 else
4608 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
4609 }
4610
4611 // Common case: if the total offset is zero, don't emit a check.
4612 if (TotalOffset == Zero)
4613 return GEPVal;
4614
4615 // Now that we've computed the total offset, add it to the base pointer (with
4616 // wrapping semantics).
4617 auto *IntPtr = Builder.CreatePtrToInt(GEP->getPointerOperand(), IntPtrTy);
4618 auto *ComputedGEP = Builder.CreateAdd(IntPtr, TotalOffset);
4619
4620 // The GEP is valid if:
4621 // 1) The total offset doesn't overflow, and
4622 // 2) The sign of the difference between the computed address and the base
4623 // pointer matches the sign of the total offset.
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004624 llvm::Value *ValidGEP;
4625 auto *NoOffsetOverflow = Builder.CreateNot(OffsetOverflows);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004626 if (SignedIndices) {
Vedant Kumar175b6d12017-07-13 20:55:26 +00004627 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004628 auto *PosOrZeroOffset = Builder.CreateICmpSGE(TotalOffset, Zero);
4629 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
4630 ValidGEP = Builder.CreateAnd(
4631 Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid),
4632 NoOffsetOverflow);
Vedant Kumar175b6d12017-07-13 20:55:26 +00004633 } else if (!SignedIndices && !IsSubtraction) {
4634 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004635 ValidGEP = Builder.CreateAnd(PosOrZeroValid, NoOffsetOverflow);
Vedant Kumar175b6d12017-07-13 20:55:26 +00004636 } else {
4637 auto *NegOrZeroValid = Builder.CreateICmpULE(ComputedGEP, IntPtr);
4638 ValidGEP = Builder.CreateAnd(NegOrZeroValid, NoOffsetOverflow);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004639 }
Vedant Kumara125eb52017-06-01 19:22:18 +00004640
4641 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
4642 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
4643 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
4644 EmitCheck(std::make_pair(ValidGEP, SanitizerKind::PointerOverflow),
4645 SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
4646
4647 return GEPVal;
4648}