blob: 75be18e23e2f27c32c961b4801aa067cd9041f1f [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"
Alexey Bataeva58da1a2019-12-27 09:44:43 -050017#include "CGOpenMPRuntime.h"
Leonard Chan99bda372018-10-15 16:07:02 +000018#include "CodeGenFunction.h"
Chris Lattner2da04b32007-08-24 05:35:26 +000019#include "CodeGenModule.h"
Eric Fiselier708afb52019-05-16 21:04:15 +000020#include "ConstantEmitter.h"
Alexey Bataev00396512015-07-02 03:40:19 +000021#include "TargetInfo.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000022#include "clang/AST/ASTContext.h"
Reid Kleckner98031782019-12-09 16:11:56 -080023#include "clang/AST/Attr.h"
Daniel Dunbar6630e102008-08-12 05:08:18 +000024#include "clang/AST/DeclObjC.h"
Yaxun Liu402804b2016-12-15 08:09:08 +000025#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000026#include "clang/AST/RecordLayout.h"
Daniel Dunbarad319a72008-08-11 05:00:27 +000027#include "clang/AST/StmtVisitor.h"
Richard Trieu63688182018-12-11 03:18:39 +000028#include "clang/Basic/CodeGenOptions.h"
Leonard Chan99bda372018-10-15 16:07:02 +000029#include "clang/Basic/FixedPoint.h"
Chris Lattnerff2367c2008-04-20 00:50:39 +000030#include "clang/Basic/TargetInfo.h"
Vedant Kumar82ee16b2017-02-25 00:43:36 +000031#include "llvm/ADT/Optional.h"
Chandler Carruth735e6d82014-03-04 11:46:22 +000032#include "llvm/IR/CFG.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000033#include "llvm/IR/Constants.h"
34#include "llvm/IR/DataLayout.h"
35#include "llvm/IR/Function.h"
Vedant Kumara125eb52017-06-01 19:22:18 +000036#include "llvm/IR/GetElementPtrTypeIterator.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000037#include "llvm/IR/GlobalVariable.h"
38#include "llvm/IR/Intrinsics.h"
Reid Kleckner5d986952019-12-11 07:55:26 -080039#include "llvm/IR/IntrinsicsPowerPC.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000040#include "llvm/IR/Module.h"
Chris Lattner1800c182008-01-03 07:05:49 +000041#include <cstdarg>
Ted Kremenekf182e812007-12-10 23:44:32 +000042
Chris Lattner2da04b32007-08-24 05:35:26 +000043using namespace clang;
44using namespace CodeGen;
45using llvm::Value;
46
47//===----------------------------------------------------------------------===//
48// Scalar Expression Emitter
49//===----------------------------------------------------------------------===//
50
Benjamin Kramerfb5e5842010-10-22 16:48:22 +000051namespace {
Vedant Kumara125eb52017-06-01 19:22:18 +000052
53/// Determine whether the given binary operation may overflow.
54/// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
55/// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
56/// the returned overflow check is precise. The returned value is 'true' for
57/// all other opcodes, to be conservative.
58bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
59 BinaryOperator::Opcode Opcode, bool Signed,
60 llvm::APInt &Result) {
61 // Assume overflow is possible, unless we can prove otherwise.
62 bool Overflow = true;
63 const auto &LHSAP = LHS->getValue();
64 const auto &RHSAP = RHS->getValue();
65 if (Opcode == BO_Add) {
66 if (Signed)
67 Result = LHSAP.sadd_ov(RHSAP, Overflow);
68 else
69 Result = LHSAP.uadd_ov(RHSAP, Overflow);
70 } else if (Opcode == BO_Sub) {
71 if (Signed)
72 Result = LHSAP.ssub_ov(RHSAP, Overflow);
73 else
74 Result = LHSAP.usub_ov(RHSAP, Overflow);
75 } else if (Opcode == BO_Mul) {
76 if (Signed)
77 Result = LHSAP.smul_ov(RHSAP, Overflow);
78 else
79 Result = LHSAP.umul_ov(RHSAP, Overflow);
80 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
81 if (Signed && !RHS->isZero())
82 Result = LHSAP.sdiv_ov(RHSAP, Overflow);
83 else
84 return false;
85 }
86 return Overflow;
87}
88
Chris Lattner2da04b32007-08-24 05:35:26 +000089struct BinOpInfo {
90 Value *LHS;
91 Value *RHS;
Chris Lattner3d966d62007-08-24 21:00:35 +000092 QualType Ty; // Computation Type.
Chris Lattner0bf27622010-06-26 21:48:21 +000093 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
Adam Nemet484aa452017-03-27 19:17:25 +000094 FPOptions FPFeatures;
Chris Lattner0bf27622010-06-26 21:48:21 +000095 const Expr *E; // Entire expr, for error unsupported. May not be binop.
Vedant Kumard9191152017-05-02 23:46:56 +000096
97 /// Check if the binop can result in integer overflow.
98 bool mayHaveIntegerOverflow() const {
99 // Without constant input, we can't rule out overflow.
Vedant Kumara125eb52017-06-01 19:22:18 +0000100 auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
101 auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
Vedant Kumard9191152017-05-02 23:46:56 +0000102 if (!LHSCI || !RHSCI)
103 return true;
104
Vedant Kumara125eb52017-06-01 19:22:18 +0000105 llvm::APInt Result;
106 return ::mayHaveIntegerOverflow(
107 LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
Vedant Kumard9191152017-05-02 23:46:56 +0000108 }
109
110 /// Check if the binop computes a division or a remainder.
Vedant Kumar94cb34b2017-05-09 00:12:33 +0000111 bool isDivremOp() const {
Vedant Kumard9191152017-05-02 23:46:56 +0000112 return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
113 Opcode == BO_RemAssign;
114 }
115
116 /// Check if the binop can result in an integer division by zero.
117 bool mayHaveIntegerDivisionByZero() const {
Vedant Kumar94cb34b2017-05-09 00:12:33 +0000118 if (isDivremOp())
Vedant Kumard9191152017-05-02 23:46:56 +0000119 if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
120 return CI->isZero();
121 return true;
122 }
123
124 /// Check if the binop can result in a float division by zero.
125 bool mayHaveFloatDivisionByZero() const {
Vedant Kumar94cb34b2017-05-09 00:12:33 +0000126 if (isDivremOp())
Vedant Kumard9191152017-05-02 23:46:56 +0000127 if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
128 return CFP->isZero();
129 return true;
130 }
Leonard Chan2044ac82019-01-16 18:13:59 +0000131
Bevin Hansson39baaab2020-01-08 11:12:55 +0100132 /// Check if at least one operand is a fixed point type. In such cases, this
133 /// operation did not follow usual arithmetic conversion and both operands
134 /// might not be of the same type.
135 bool isFixedPointOp() const {
Leonard Chance1d4f12019-02-21 20:50:09 +0000136 // We cannot simply check the result type since comparison operations return
137 // an int.
138 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
139 QualType LHSType = BinOp->getLHS()->getType();
140 QualType RHSType = BinOp->getRHS()->getType();
141 return LHSType->isFixedPointType() || RHSType->isFixedPointType();
142 }
Bevin Hansson39baaab2020-01-08 11:12:55 +0100143 if (const auto *UnOp = dyn_cast<UnaryOperator>(E))
144 return UnOp->getSubExpr()->getType()->isFixedPointType();
Leonard Chance1d4f12019-02-21 20:50:09 +0000145 return false;
Leonard Chan2044ac82019-01-16 18:13:59 +0000146 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000147};
148
John McCalle84af4e2010-11-13 01:35:44 +0000149static bool MustVisitNullValue(const Expr *E) {
150 // If a null pointer expression's type is the C++0x nullptr_t, then
151 // it's not necessarily a simple constant and it must be evaluated
152 // for its potential side effects.
153 return E->getType()->isNullPtrType();
154}
155
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000156/// If \p E is a widened promoted integer, get its base (unpromoted) type.
157static llvm::Optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
158 const Expr *E) {
159 const Expr *Base = E->IgnoreImpCasts();
160 if (E == Base)
161 return llvm::None;
162
163 QualType BaseTy = Base->getType();
164 if (!BaseTy->isPromotableIntegerType() ||
165 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
166 return llvm::None;
167
168 return BaseTy;
169}
170
171/// Check if \p E is a widened promoted integer.
172static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
173 return getUnwidenedIntegerType(Ctx, E).hasValue();
174}
175
176/// Check if we can skip the overflow check for \p Op.
177static bool CanElideOverflowCheck(const ASTContext &Ctx, const BinOpInfo &Op) {
Vedant Kumar66c00cc2017-02-25 06:47:00 +0000178 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
179 "Expected a unary or binary operator");
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000180
Vedant Kumard9191152017-05-02 23:46:56 +0000181 // If the binop has constant inputs and we can prove there is no overflow,
182 // we can elide the overflow check.
183 if (!Op.mayHaveIntegerOverflow())
184 return true;
Malcolm Parsonsfab36802018-04-16 08:31:08 +0000185
186 // If a unary op has a widened operand, the op cannot overflow.
187 if (const auto *UO = dyn_cast<UnaryOperator>(Op.E))
188 return !UO->canOverflow();
189
190 // We usually don't need overflow checks for binops with widened operands.
191 // Multiplication with promoted unsigned operands is a special case.
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000192 const auto *BO = cast<BinaryOperator>(Op.E);
193 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
194 if (!OptionalLHSTy)
195 return false;
196
197 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
198 if (!OptionalRHSTy)
199 return false;
200
201 QualType LHSTy = *OptionalLHSTy;
202 QualType RHSTy = *OptionalRHSTy;
203
Vedant Kumard9191152017-05-02 23:46:56 +0000204 // This is the simple case: binops without unsigned multiplication, and with
205 // widened operands. No overflow check is needed here.
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000206 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
207 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
208 return true;
209
Vedant Kumard9191152017-05-02 23:46:56 +0000210 // For unsigned multiplication the overflow check can be elided if either one
211 // of the unpromoted types are less than half the size of the promoted type.
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000212 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
213 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
214 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
215}
216
Adam Nemet370d0872017-04-04 21:18:30 +0000217/// Update the FastMathFlags of LLVM IR from the FPOptions in LangOptions.
218static void updateFastMathFlags(llvm::FastMathFlags &FMF,
219 FPOptions FPFeatures) {
220 FMF.setAllowContract(FPFeatures.allowFPContractAcrossStatement());
221}
222
223/// Propagate fast-math flags from \p Op to the instruction in \p V.
224static Value *propagateFMFlags(Value *V, const BinOpInfo &Op) {
225 if (auto *I = dyn_cast<llvm::Instruction>(V)) {
226 llvm::FastMathFlags FMF = I->getFastMathFlags();
227 updateFastMathFlags(FMF, Op.FPFeatures);
228 I->setFastMathFlags(FMF);
229 }
230 return V;
231}
232
Benjamin Kramer337e3a52009-11-28 19:45:26 +0000233class ScalarExprEmitter
Chris Lattner2da04b32007-08-24 05:35:26 +0000234 : public StmtVisitor<ScalarExprEmitter, Value*> {
235 CodeGenFunction &CGF;
Daniel Dunbarcb463852008-11-01 01:53:16 +0000236 CGBuilderTy &Builder;
Mike Stumpdf0fe272009-05-29 15:46:01 +0000237 bool IgnoreResultAssign;
Owen Anderson170229f2009-07-14 23:10:40 +0000238 llvm::LLVMContext &VMContext;
Chris Lattner2da04b32007-08-24 05:35:26 +0000239public:
240
Mike Stumpdf0fe272009-05-29 15:46:01 +0000241 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
Mike Stump4a3999f2009-09-09 13:00:44 +0000242 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
Owen Anderson170229f2009-07-14 23:10:40 +0000243 VMContext(cgf.getLLVMContext()) {
Chris Lattner2da04b32007-08-24 05:35:26 +0000244 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000245
Chris Lattner2da04b32007-08-24 05:35:26 +0000246 //===--------------------------------------------------------------------===//
247 // Utilities
248 //===--------------------------------------------------------------------===//
249
Mike Stumpdf0fe272009-05-29 15:46:01 +0000250 bool TestAndClearIgnoreResultAssign() {
Chris Lattner2a7deb62009-07-08 01:08:03 +0000251 bool I = IgnoreResultAssign;
252 IgnoreResultAssign = false;
253 return I;
254 }
Mike Stumpdf0fe272009-05-29 15:46:01 +0000255
Chris Lattner2192fe52011-07-18 04:24:23 +0000256 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
Chris Lattner2da04b32007-08-24 05:35:26 +0000257 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
Richard Smith4d1458e2012-09-08 02:08:36 +0000258 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
259 return CGF.EmitCheckedLValue(E, TCK);
Richard Smith69d0d262012-08-24 00:54:33 +0000260 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000261
Peter Collingbourne3eea6772015-05-11 21:39:14 +0000262 void EmitBinOpCheck(ArrayRef<std::pair<Value *, SanitizerMask>> Checks,
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000263 const BinOpInfo &Info);
Richard Smithe30752c2012-10-09 19:52:38 +0000264
Nick Lewycky2d84e842013-10-02 02:29:49 +0000265 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
266 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
Chris Lattner2da04b32007-08-24 05:35:26 +0000267 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000268
Hal Finkel64567a82014-10-04 15:26:49 +0000269 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
270 const AlignValueAttr *AVAttr = nullptr;
271 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
272 const ValueDecl *VD = DRE->getDecl();
273
274 if (VD->getType()->isReferenceType()) {
275 if (const auto *TTy =
276 dyn_cast<TypedefType>(VD->getType().getNonReferenceType()))
277 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
278 } else {
279 // Assumptions for function parameters are emitted at the start of the
Roman Lebedevbd1c0872019-01-15 09:44:25 +0000280 // function, so there is no need to repeat that here,
281 // unless the alignment-assumption sanitizer is enabled,
282 // then we prefer the assumption over alignment attribute
283 // on IR function param.
284 if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
Hal Finkel64567a82014-10-04 15:26:49 +0000285 return;
286
287 AVAttr = VD->getAttr<AlignValueAttr>();
288 }
289 }
290
291 if (!AVAttr)
292 if (const auto *TTy =
293 dyn_cast<TypedefType>(E->getType()))
294 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
295
296 if (!AVAttr)
297 return;
298
299 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
300 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
Fangrui Song1d49eb02020-02-13 16:36:27 -0800301 CGF.emitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI);
Hal Finkel64567a82014-10-04 15:26:49 +0000302 }
303
Chris Lattner2da04b32007-08-24 05:35:26 +0000304 /// EmitLoadOfLValue - Given an expression with complex type that represents a
305 /// value l-value, this method emits the address of the l-value, then loads
306 /// and returns the result.
307 Value *EmitLoadOfLValue(const Expr *E) {
Hal Finkel64567a82014-10-04 15:26:49 +0000308 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
309 E->getExprLoc());
310
311 EmitLValueAlignmentAssumption(E, V);
312 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000313 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000314
Chris Lattnere0044382007-08-26 16:42:57 +0000315 /// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000316 /// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000317 Value *EmitConversionToBool(Value *Src, QualType DstTy);
Mike Stump4a3999f2009-09-09 13:00:44 +0000318
Richard Smith9e52c432019-07-06 21:05:52 +0000319 /// Emit a check that a conversion from a floating-point type does not
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000320 /// overflow.
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000321 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000322 Value *Src, QualType SrcType, QualType DstType,
323 llvm::Type *DstTy, SourceLocation Loc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000324
Roman Lebedevb69ba222018-07-30 18:58:30 +0000325 /// Known implicit conversion check kinds.
326 /// Keep in sync with the enum of the same name in ubsan_handlers.h
327 enum ImplicitConversionCheckKind : unsigned char {
Roman Lebedevdd403572018-10-11 09:09:50 +0000328 ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
329 ICCK_UnsignedIntegerTruncation = 1,
330 ICCK_SignedIntegerTruncation = 2,
Roman Lebedev62debd802018-10-30 21:58:56 +0000331 ICCK_IntegerSignChange = 3,
332 ICCK_SignedIntegerTruncationOrSignChange = 4,
Roman Lebedevb69ba222018-07-30 18:58:30 +0000333 };
334
335 /// Emit a check that an [implicit] truncation of an integer does not
336 /// discard any bits. It is not UB, so we use the value after truncation.
337 void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
338 QualType DstType, SourceLocation Loc);
339
Roman Lebedev62debd802018-10-30 21:58:56 +0000340 /// Emit a check that an [implicit] conversion of an integer does not change
341 /// the sign of the value. It is not UB, so we use the value after conversion.
342 /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
343 void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
344 QualType DstType, SourceLocation Loc);
345
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000346 /// Emit a conversion from the specified type to the specified destination
347 /// type, both of which are LLVM scalar types.
Roman Lebedevb69ba222018-07-30 18:58:30 +0000348 struct ScalarConversionOpts {
349 bool TreatBooleanAsSigned;
350 bool EmitImplicitIntegerTruncationChecks;
Roman Lebedev62debd802018-10-30 21:58:56 +0000351 bool EmitImplicitIntegerSignChangeChecks;
Chris Lattner42e6b812007-08-26 16:34:22 +0000352
Roman Lebedevb69ba222018-07-30 18:58:30 +0000353 ScalarConversionOpts()
354 : TreatBooleanAsSigned(false),
Roman Lebedev62debd802018-10-30 21:58:56 +0000355 EmitImplicitIntegerTruncationChecks(false),
356 EmitImplicitIntegerSignChangeChecks(false) {}
Roman Lebedevd677c3f2018-11-19 19:56:43 +0000357
358 ScalarConversionOpts(clang::SanitizerSet SanOpts)
359 : TreatBooleanAsSigned(false),
360 EmitImplicitIntegerTruncationChecks(
361 SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
362 EmitImplicitIntegerSignChangeChecks(
363 SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)) {}
Roman Lebedevb69ba222018-07-30 18:58:30 +0000364 };
365 Value *
366 EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
367 SourceLocation Loc,
368 ScalarConversionOpts Opts = ScalarConversionOpts());
Anastasia Stulovab02e7832015-10-05 11:27:41 +0000369
Leonard Chan8f7caae2019-03-06 00:28:43 +0000370 /// Convert between either a fixed point and other fixed point or fixed point
371 /// and an integer.
Leonard Chan99bda372018-10-15 16:07:02 +0000372 Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
373 SourceLocation Loc);
Leonard Chan2044ac82019-01-16 18:13:59 +0000374 Value *EmitFixedPointConversion(Value *Src, FixedPointSemantics &SrcFixedSema,
375 FixedPointSemantics &DstFixedSema,
Leonard Chan8f7caae2019-03-06 00:28:43 +0000376 SourceLocation Loc,
377 bool DstIsInteger = false);
Leonard Chan99bda372018-10-15 16:07:02 +0000378
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +0000379 /// Emit a conversion from the specified complex type to the specified
380 /// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +0000381 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000382 QualType SrcTy, QualType DstTy,
383 SourceLocation Loc);
Mike Stumpab3afd82009-02-12 18:29:15 +0000384
Anders Carlsson5b944432010-05-22 17:45:10 +0000385 /// EmitNullValue - Emit a value that corresponds to null for the given type.
386 Value *EmitNullValue(QualType Ty);
387
John McCall8cb679e2010-11-15 09:13:47 +0000388 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
389 Value *EmitFloatToBoolConversion(Value *V) {
390 // Compare against 0.0 for fp scalars.
391 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
392 return Builder.CreateFCmpUNE(V, Zero, "tobool");
393 }
394
395 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
Yaxun Liu402804b2016-12-15 08:09:08 +0000396 Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
397 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
398
John McCall8cb679e2010-11-15 09:13:47 +0000399 return Builder.CreateICmpNE(V, Zero, "tobool");
400 }
401
402 Value *EmitIntToBoolConversion(Value *V) {
403 // Because of the type rules of C, we often end up computing a
404 // logical value, then zero extending it to int, then wanting it
405 // as a logical value again. Optimize this common case.
406 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
407 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
408 Value *Result = ZI->getOperand(0);
409 // If there aren't any more uses, zap the instruction to save space.
410 // Note that there can be more uses, for example if this
411 // is the result of an assignment.
412 if (ZI->use_empty())
413 ZI->eraseFromParent();
414 return Result;
415 }
416 }
417
Chris Lattner2531eb42011-04-19 22:55:03 +0000418 return Builder.CreateIsNotNull(V, "tobool");
John McCall8cb679e2010-11-15 09:13:47 +0000419 }
420
Chris Lattner2da04b32007-08-24 05:35:26 +0000421 //===--------------------------------------------------------------------===//
422 // Visitor Methods
423 //===--------------------------------------------------------------------===//
424
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000425 Value *Visit(Expr *E) {
David Blaikie9b479662015-01-25 01:19:10 +0000426 ApplyDebugLocation DL(CGF, E);
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000427 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
428 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000429
Chris Lattner2da04b32007-08-24 05:35:26 +0000430 Value *VisitStmt(Stmt *S) {
Ted Kremenekd4e5fba2007-12-11 21:27:55 +0000431 S->dump(CGF.getContext().getSourceManager());
David Blaikie83d382b2011-09-23 05:06:16 +0000432 llvm_unreachable("Stmt can't have complex result type!");
Chris Lattner2da04b32007-08-24 05:35:26 +0000433 }
434 Value *VisitExpr(Expr *S);
Craig Toppera97d7e72013-07-26 06:16:11 +0000435
Bill Wendling8003edc2018-11-09 00:41:36 +0000436 Value *VisitConstantExpr(ConstantExpr *E) {
437 return Visit(E->getSubExpr());
438 }
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000439 Value *VisitParenExpr(ParenExpr *PE) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000440 return Visit(PE->getSubExpr());
Fariborz Jahanian5bbd1b02010-09-17 15:51:28 +0000441 }
John McCall7c454bb2011-07-15 05:09:51 +0000442 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000443 return Visit(E->getReplacement());
John McCall7c454bb2011-07-15 05:09:51 +0000444 }
Peter Collingbourne91147592011-04-15 00:35:48 +0000445 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
446 return Visit(GE->getResultExpr());
447 }
Gor Nishanov5eb58582017-03-26 02:18:05 +0000448 Value *VisitCoawaitExpr(CoawaitExpr *S) {
449 return CGF.EmitCoawaitExpr(*S).getScalarVal();
450 }
451 Value *VisitCoyieldExpr(CoyieldExpr *S) {
452 return CGF.EmitCoyieldExpr(*S).getScalarVal();
453 }
454 Value *VisitUnaryCoawait(const UnaryOperator *E) {
455 return Visit(E->getSubExpr());
456 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000457
458 // Leaves.
459 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000460 return Builder.getInt(E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000461 }
Leonard Chandb01c3a2018-06-20 17:19:40 +0000462 Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
463 return Builder.getInt(E->getValue());
464 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000465 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
Owen Andersone05f2ed2009-07-27 21:00:51 +0000466 return llvm::ConstantFP::get(VMContext, E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000467 }
468 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000469 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Chris Lattner2da04b32007-08-24 05:35:26 +0000470 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000471 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
472 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
473 }
Nate Begeman4c18c232007-11-15 05:40:03 +0000474 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Owen Andersonb7a2fe62009-07-24 23:12:58 +0000475 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Nate Begeman4c18c232007-11-15 05:40:03 +0000476 }
Douglas Gregor747eb782010-07-08 06:14:04 +0000477 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000478 return EmitNullValue(E->getType());
Argyrios Kyrtzidisce4528f2008-08-23 19:35:47 +0000479 }
Anders Carlsson39def3a2008-12-21 22:39:40 +0000480 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000481 return EmitNullValue(E->getType());
Anders Carlsson39def3a2008-12-21 22:39:40 +0000482 }
Eli Friedmand7c72322010-08-05 09:58:49 +0000483 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
Peter Collingbournee190dee2011-03-11 19:24:49 +0000484 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000485 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
Chris Lattner6c4d2552009-10-28 23:59:40 +0000486 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
487 return Builder.CreateBitCast(V, ConvertType(E->getType()));
Daniel Dunbar88402ce2008-08-04 16:51:22 +0000488 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000489
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000490 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000491 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
Douglas Gregorbe7b5482011-01-12 22:11:34 +0000492 }
John McCall1bf58462011-02-16 08:02:54 +0000493
John McCallfe96e0b2011-11-06 09:01:30 +0000494 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
495 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
496 }
497
John McCall1bf58462011-02-16 08:02:54 +0000498 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
John McCallc07a0c72011-02-17 10:25:35 +0000499 if (E->isGLValue())
Akira Hatanaka797afe32018-03-20 01:47:58 +0000500 return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
501 E->getExprLoc());
John McCall1bf58462011-02-16 08:02:54 +0000502
503 // Otherwise, assume the mapping is the scalar directly.
Akira Hatanaka797afe32018-03-20 01:47:58 +0000504 return CGF.getOrCreateOpaqueRValueMapping(E).getScalarVal();
John McCall1bf58462011-02-16 08:02:54 +0000505 }
John McCall71335052012-03-10 03:05:10 +0000506
Chris Lattner2da04b32007-08-24 05:35:26 +0000507 // l-values.
John McCall113bee02012-03-10 09:33:50 +0000508 Value *VisitDeclRefExpr(DeclRefExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +0000509 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
Volodymyr Sapsaief1899b2018-11-01 21:57:05 +0000510 return CGF.emitScalarConstant(Constant, E);
John McCall113bee02012-03-10 09:33:50 +0000511 return EmitLoadOfLValue(E);
John McCall71335052012-03-10 03:05:10 +0000512 }
513
Mike Stump4a3999f2009-09-09 13:00:44 +0000514 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
515 return CGF.EmitObjCSelectorExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000516 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000517 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
518 return CGF.EmitObjCProtocolExpr(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000519 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000520 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
Daniel Dunbar55310df2008-08-27 06:57:25 +0000521 return EmitLoadOfLValue(E);
522 }
Daniel Dunbar55310df2008-08-27 06:57:25 +0000523 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
Craig Toppera97d7e72013-07-26 06:16:11 +0000524 if (E->getMethodDecl() &&
Alp Toker314cc812014-01-25 16:55:45 +0000525 E->getMethodDecl()->getReturnType()->isReferenceType())
Fariborz Jahanianff989032011-03-02 20:09:49 +0000526 return EmitLoadOfLValue(E);
Daniel Dunbar55310df2008-08-27 06:57:25 +0000527 return CGF.EmitObjCMessageExpr(E).getScalarVal();
Daniel Dunbarc8317a42008-08-23 10:51:21 +0000528 }
529
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000530 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +0000531 LValue LV = CGF.EmitObjCIsaExpr(E);
Nick Lewycky2d84e842013-10-02 02:29:49 +0000532 Value *V = CGF.EmitLoadOfLValue(LV, E->getExprLoc()).getScalarVal();
Fariborz Jahaniana5fee262009-12-09 19:05:56 +0000533 return V;
534 }
535
Erik Pilkington9c42a8d2017-02-23 21:08:08 +0000536 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
537 VersionTuple Version = E->getVersion();
538
539 // If we're checking for a platform older than our minimum deployment
540 // target, we can fold the check away.
541 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
542 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
543
544 Optional<unsigned> Min = Version.getMinor(), SMin = Version.getSubminor();
545 llvm::Value *Args[] = {
546 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Version.getMajor()),
547 llvm::ConstantInt::get(CGF.CGM.Int32Ty, Min ? *Min : 0),
548 llvm::ConstantInt::get(CGF.CGM.Int32Ty, SMin ? *SMin : 0),
549 };
550
551 return CGF.EmitBuiltinAvailable(Args);
552 }
553
Chris Lattner2da04b32007-08-24 05:35:26 +0000554 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
Eli Friedmana1b4ed82008-05-14 19:38:39 +0000555 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
Hal Finkelc4d7c822013-09-18 03:29:45 +0000556 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
Eli Friedmancb422f12009-11-26 03:22:21 +0000557 Value *VisitMemberExpr(MemberExpr *E);
Nate Begemance4d7fc2008-04-18 23:10:10 +0000558 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
Chris Lattner084bc322008-10-26 23:53:12 +0000559 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
Akira Hatanaka40568fe2020-03-10 14:06:25 -0700560 // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which
561 // transitively calls EmitCompoundLiteralLValue, here in C++ since compound
562 // literals aren't l-values in C++. We do so simply because that's the
563 // cleanest way to handle compound literals in C++.
564 // See the discussion here: https://reviews.llvm.org/D64464
Chris Lattner084bc322008-10-26 23:53:12 +0000565 return EmitLoadOfLValue(E);
566 }
Devang Patel43fc86d2007-10-24 17:18:43 +0000567
Nate Begeman19351632009-10-18 20:10:40 +0000568 Value *VisitInitListExpr(InitListExpr *E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000569
Richard Smith410306b2016-12-12 02:53:20 +0000570 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
571 assert(CGF.getArrayInitIndex() &&
572 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
573 return CGF.getArrayInitIndex();
574 }
575
Douglas Gregor0202cb42009-01-29 17:44:32 +0000576 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithd82a2ce2012-12-21 03:17:28 +0000577 return EmitNullValue(E->getType());
Douglas Gregor0202cb42009-01-29 17:44:32 +0000578 }
John McCall23c29fe2011-06-24 21:55:10 +0000579 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
Alexey Bataev2bf9b4c2015-10-20 04:24:12 +0000580 CGF.CGM.EmitExplicitCastExprType(E, &CGF);
John McCall23c29fe2011-06-24 21:55:10 +0000581 return VisitCastExpr(E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000582 }
John McCall23c29fe2011-06-24 21:55:10 +0000583 Value *VisitCastExpr(CastExpr *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000584
585 Value *VisitCallExpr(const CallExpr *E) {
David Majnemerced8bdf2015-02-25 17:36:15 +0000586 if (E->getCallReturnType(CGF.getContext())->isReferenceType())
Anders Carlssond8b7ae22009-05-27 03:37:57 +0000587 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +0000588
Hal Finkel64567a82014-10-04 15:26:49 +0000589 Value *V = CGF.EmitCallExpr(E).getScalarVal();
590
591 EmitLValueAlignmentAssumption(E, V);
592 return V;
Chris Lattner2da04b32007-08-24 05:35:26 +0000593 }
Daniel Dunbar97db84c2008-08-23 03:46:30 +0000594
Chris Lattner04a913b2007-08-31 22:09:40 +0000595 Value *VisitStmtExpr(const StmtExpr *E);
Mike Stumpcb2fbcb2009-02-21 20:00:35 +0000596
Chris Lattner2da04b32007-08-24 05:35:26 +0000597 // Unary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000598 Value *VisitUnaryPostDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000599 LValue LV = EmitLValue(E->getSubExpr());
600 return EmitScalarPrePostIncDec(E, LV, false, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000601 }
602 Value *VisitUnaryPostInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000603 LValue LV = EmitLValue(E->getSubExpr());
604 return EmitScalarPrePostIncDec(E, LV, true, false);
Chris Lattner2da04b32007-08-24 05:35:26 +0000605 }
606 Value *VisitUnaryPreDec(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000607 LValue LV = EmitLValue(E->getSubExpr());
608 return EmitScalarPrePostIncDec(E, LV, false, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000609 }
610 Value *VisitUnaryPreInc(const UnaryOperator *E) {
Chris Lattner05dc78c2010-06-26 22:09:34 +0000611 LValue LV = EmitLValue(E->getSubExpr());
612 return EmitScalarPrePostIncDec(E, LV, true, true);
Chris Lattner2da04b32007-08-24 05:35:26 +0000613 }
Chris Lattner05dc78c2010-06-26 22:09:34 +0000614
Alexey Samsonovf6246502015-04-23 01:50:45 +0000615 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
616 llvm::Value *InVal,
617 bool IsInc);
Anton Yartsev85129b82011-02-07 02:17:30 +0000618
Chris Lattner05dc78c2010-06-26 22:09:34 +0000619 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
620 bool isInc, bool isPre);
621
Craig Toppera97d7e72013-07-26 06:16:11 +0000622
Chris Lattner2da04b32007-08-24 05:35:26 +0000623 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
John McCallf3a88602011-02-03 08:15:49 +0000624 if (isa<MemberPointerType>(E->getType())) // never sugared
625 return CGF.CGM.getMemberPointerConstant(E);
626
Akira Hatanakaf139ae32019-12-03 15:17:01 -0800627 return EmitLValue(E->getSubExpr()).getPointer(CGF);
Chris Lattner2da04b32007-08-24 05:35:26 +0000628 }
John McCall59482722010-12-04 12:43:24 +0000629 Value *VisitUnaryDeref(const UnaryOperator *E) {
630 if (E->getType()->isVoidType())
631 return Visit(E->getSubExpr()); // the actual value should be unused
632 return EmitLoadOfLValue(E);
633 }
Chris Lattner2da04b32007-08-24 05:35:26 +0000634 Value *VisitUnaryPlus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +0000635 // This differs from gcc, though, most likely due to a bug in gcc.
636 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +0000637 return Visit(E->getSubExpr());
638 }
639 Value *VisitUnaryMinus (const UnaryOperator *E);
640 Value *VisitUnaryNot (const UnaryOperator *E);
641 Value *VisitUnaryLNot (const UnaryOperator *E);
Chris Lattner9f0ad962007-08-24 21:20:17 +0000642 Value *VisitUnaryReal (const UnaryOperator *E);
643 Value *VisitUnaryImag (const UnaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000644 Value *VisitUnaryExtension(const UnaryOperator *E) {
645 return Visit(E->getSubExpr());
646 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000647
Anders Carlssona5d077d2009-04-14 16:58:56 +0000648 // C++
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000649 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
Eli Friedman0be39702011-08-14 04:50:34 +0000650 return EmitLoadOfLValue(E);
Douglas Gregor34f6c6d2011-08-09 00:37:14 +0000651 }
Eric Fiselier708afb52019-05-16 21:04:15 +0000652 Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
653 auto &Ctx = CGF.getContext();
654 APValue Evaluated =
655 SLE->EvaluateInContext(Ctx, CGF.CurSourceLocExprScope.getDefaultExpr());
Johannes Altmanninger1ac700c2019-11-15 02:12:58 +0100656 return ConstantEmitter(CGF).emitAbstract(SLE->getLocation(), Evaluated,
657 SLE->getType());
Eric Fiselier708afb52019-05-16 21:04:15 +0000658 }
Craig Toppera97d7e72013-07-26 06:16:11 +0000659
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000660 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000661 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000662 return Visit(DAE->getExpr());
663 }
Richard Smith852c9db2013-04-20 22:23:05 +0000664 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
Eric Fiselier708afb52019-05-16 21:04:15 +0000665 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
Richard Smith852c9db2013-04-20 22:23:05 +0000666 return Visit(DIE->getExpr());
667 }
Anders Carlssona5d077d2009-04-14 16:58:56 +0000668 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
669 return CGF.LoadCXXThis();
Mike Stump4a3999f2009-09-09 13:00:44 +0000670 }
671
Reid Kleckner092d0652017-03-06 22:18:34 +0000672 Value *VisitExprWithCleanups(ExprWithCleanups *E);
Anders Carlsson4a7b49b2009-05-31 01:40:14 +0000673 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
674 return CGF.EmitCXXNewExpr(E);
675 }
Anders Carlsson81f0df92009-08-16 21:13:42 +0000676 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
677 CGF.EmitCXXDeleteExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000678 return nullptr;
Anders Carlsson81f0df92009-08-16 21:13:42 +0000679 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000680
Alp Tokercbb90342013-12-13 20:49:58 +0000681 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
Francois Pichet34b21132010-12-08 22:35:30 +0000682 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
Francois Pichet9dfa3ce2010-12-07 00:08:36 +0000683 }
684
Saar Raz5d98ba62019-10-15 15:24:26 +0000685 Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
686 return Builder.getInt1(E->isSatisfied());
687 }
688
Saar Raza0f50d72020-01-18 09:11:43 +0200689 Value *VisitRequiresExpr(const RequiresExpr *E) {
690 return Builder.getInt1(E->isSatisfied());
691 }
692
John Wiegley6242b6a2011-04-28 00:16:57 +0000693 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
694 return llvm::ConstantInt::get(Builder.getInt32Ty(), E->getValue());
695 }
696
John Wiegleyf9f65842011-04-25 06:54:41 +0000697 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
698 return llvm::ConstantInt::get(Builder.getInt1Ty(), E->getValue());
699 }
700
Douglas Gregorad8a3362009-09-04 17:36:40 +0000701 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
702 // C++ [expr.pseudo]p1:
Mike Stump4a3999f2009-09-09 13:00:44 +0000703 // The result shall only be used as the operand for the function call
Douglas Gregorad8a3362009-09-04 17:36:40 +0000704 // operator (), and the result of such a call has type void. The only
705 // effect is the evaluation of the postfix-expression before the dot or
706 // arrow.
707 CGF.EmitScalarExpr(E->getBase());
Craig Topper8a13c412014-05-21 05:09:00 +0000708 return nullptr;
Douglas Gregorad8a3362009-09-04 17:36:40 +0000709 }
Mike Stump4a3999f2009-09-09 13:00:44 +0000710
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000711 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Anders Carlsson5b944432010-05-22 17:45:10 +0000712 return EmitNullValue(E->getType());
Anders Carlsson04c3bf42009-09-15 04:39:46 +0000713 }
Anders Carlsson4b08db72009-10-30 01:42:31 +0000714
715 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
716 CGF.EmitCXXThrowExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +0000717 return nullptr;
Anders Carlsson4b08db72009-10-30 01:42:31 +0000718 }
719
Sebastian Redlb67655f2010-09-10 21:04:00 +0000720 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
Chris Lattner2531eb42011-04-19 22:55:03 +0000721 return Builder.getInt1(E->getValue());
Sebastian Redlb67655f2010-09-10 21:04:00 +0000722 }
723
Chris Lattner2da04b32007-08-24 05:35:26 +0000724 // Binary Operators.
Chris Lattner2da04b32007-08-24 05:35:26 +0000725 Value *EmitMul(const BinOpInfo &Ops) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +0000726 if (Ops.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +0000727 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +0000728 case LangOptions::SOB_Defined:
729 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
Richard Smith3e056de2012-08-25 00:32:28 +0000730 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000731 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +0000732 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +0000733 LLVM_FALLTHROUGH;
Chris Lattner51924e512010-06-26 21:25:03 +0000734 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000735 if (CanElideOverflowCheck(CGF.getContext(), Ops))
736 return Builder.CreateNSWMul(Ops.LHS, Ops.RHS, "mul");
Chris Lattner51924e512010-06-26 21:25:03 +0000737 return EmitOverflowCheckedBinOp(Ops);
738 }
739 }
Richard Smithb1b0ab42012-11-05 22:21:05 +0000740
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000741 if (Ops.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +0000742 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
743 !CanElideOverflowCheck(CGF.getContext(), Ops))
Will Dietz1897cb32012-11-27 15:01:55 +0000744 return EmitOverflowCheckedBinOp(Ops);
745
Adam Nemet370d0872017-04-04 21:18:30 +0000746 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
747 Value *V = Builder.CreateFMul(Ops.LHS, Ops.RHS, "mul");
748 return propagateFMFlags(V, Ops);
749 }
Bevin Hansson39baaab2020-01-08 11:12:55 +0100750 if (Ops.isFixedPointOp())
Bevin Hansson0b9922e2019-11-19 13:15:06 +0100751 return EmitFixedPointBinOp(Ops);
Chris Lattner2da04b32007-08-24 05:35:26 +0000752 return Builder.CreateMul(Ops.LHS, Ops.RHS, "mul");
753 }
Mike Stump0c61b732009-04-01 20:28:16 +0000754 /// Create a binary op that checks for overflow.
755 /// Currently only supports +, - and *.
756 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
Richard Smith4d1458e2012-09-08 02:08:36 +0000757
Chris Lattner8ee6a412010-09-11 21:47:09 +0000758 // Check for undefined division and modulus behaviors.
Craig Toppera97d7e72013-07-26 06:16:11 +0000759 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
Chris Lattner8ee6a412010-09-11 21:47:09 +0000760 llvm::Value *Zero,bool isDiv);
David Tweed042e0882013-01-07 16:43:27 +0000761 // Common helper for getting how wide LHS of shift is.
762 static Value *GetWidthMinusOneValue(Value* LHS,Value* RHS);
Chris Lattner2da04b32007-08-24 05:35:26 +0000763 Value *EmitDiv(const BinOpInfo &Ops);
764 Value *EmitRem(const BinOpInfo &Ops);
765 Value *EmitAdd(const BinOpInfo &Ops);
766 Value *EmitSub(const BinOpInfo &Ops);
767 Value *EmitShl(const BinOpInfo &Ops);
768 Value *EmitShr(const BinOpInfo &Ops);
769 Value *EmitAnd(const BinOpInfo &Ops) {
770 return Builder.CreateAnd(Ops.LHS, Ops.RHS, "and");
771 }
772 Value *EmitXor(const BinOpInfo &Ops) {
773 return Builder.CreateXor(Ops.LHS, Ops.RHS, "xor");
774 }
775 Value *EmitOr (const BinOpInfo &Ops) {
776 return Builder.CreateOr(Ops.LHS, Ops.RHS, "or");
777 }
778
Leonard Chan2044ac82019-01-16 18:13:59 +0000779 // Helper functions for fixed point binary operations.
Leonard Chan837da5d2019-01-16 19:53:50 +0000780 Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
Leonard Chan2044ac82019-01-16 18:13:59 +0000781
Chris Lattner3d966d62007-08-24 21:00:35 +0000782 BinOpInfo EmitBinOps(const BinaryOperator *E);
Douglas Gregor914af212010-04-23 04:16:32 +0000783 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
784 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +0000785 Value *&Result);
Douglas Gregor914af212010-04-23 04:16:32 +0000786
Chris Lattnerb6334692007-08-26 21:41:21 +0000787 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
Chris Lattner3d966d62007-08-24 21:00:35 +0000788 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
789
790 // Binary operators and binary compound assignment operators.
791#define HANDLEBINOP(OP) \
Chris Lattnerb6334692007-08-26 21:41:21 +0000792 Value *VisitBin ## OP(const BinaryOperator *E) { \
793 return Emit ## OP(EmitBinOps(E)); \
794 } \
795 Value *VisitBin ## OP ## Assign(const CompoundAssignOperator *E) { \
796 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit ## OP); \
Chris Lattner3d966d62007-08-24 21:00:35 +0000797 }
Daniel Dunbare017ecc2009-12-19 17:50:07 +0000798 HANDLEBINOP(Mul)
799 HANDLEBINOP(Div)
800 HANDLEBINOP(Rem)
801 HANDLEBINOP(Add)
802 HANDLEBINOP(Sub)
803 HANDLEBINOP(Shl)
804 HANDLEBINOP(Shr)
805 HANDLEBINOP(And)
806 HANDLEBINOP(Xor)
807 HANDLEBINOP(Or)
Chris Lattner3d966d62007-08-24 21:00:35 +0000808#undef HANDLEBINOP
Daniel Dunbarbfb1cd72008-08-06 02:00:38 +0000809
Chris Lattner2da04b32007-08-24 05:35:26 +0000810 // Comparisons.
Craig Topperc82f8962015-12-16 06:24:28 +0000811 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
812 llvm::CmpInst::Predicate SICmpOpc,
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +0100813 llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
814#define VISITCOMP(CODE, UI, SI, FP, SIG) \
Chris Lattner2da04b32007-08-24 05:35:26 +0000815 Value *VisitBin##CODE(const BinaryOperator *E) { \
816 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +0100817 llvm::FCmpInst::FP, SIG); }
818 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true)
819 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true)
820 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true)
821 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true)
822 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false)
823 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false)
Chris Lattner2da04b32007-08-24 05:35:26 +0000824#undef VISITCOMP
Mike Stump4a3999f2009-09-09 13:00:44 +0000825
Chris Lattner2da04b32007-08-24 05:35:26 +0000826 Value *VisitBinAssign (const BinaryOperator *E);
827
828 Value *VisitBinLAnd (const BinaryOperator *E);
829 Value *VisitBinLOr (const BinaryOperator *E);
Chris Lattner2da04b32007-08-24 05:35:26 +0000830 Value *VisitBinComma (const BinaryOperator *E);
831
Eli Friedmanacfb1df2009-11-18 09:41:26 +0000832 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
833 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
834
Richard Smith778dc0f2019-10-19 00:04:38 +0000835 Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
836 return Visit(E->getSemanticForm());
837 }
838
Chris Lattner2da04b32007-08-24 05:35:26 +0000839 // Other Operators.
Mike Stumpab3afd82009-02-12 18:29:15 +0000840 Value *VisitBlockExpr(const BlockExpr *BE);
John McCallc07a0c72011-02-17 10:25:35 +0000841 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
Chris Lattner2da04b32007-08-24 05:35:26 +0000842 Value *VisitChooseExpr(ChooseExpr *CE);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000843 Value *VisitVAArgExpr(VAArgExpr *VE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000844 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
845 return CGF.EmitObjCStringLiteral(E);
846 }
Patrick Beard0caa3942012-04-19 00:25:12 +0000847 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
848 return CGF.EmitObjCBoxedExpr(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000849 }
850 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
851 return CGF.EmitObjCArrayLiteral(E);
852 }
853 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
854 return CGF.EmitObjCDictionaryLiteral(E);
855 }
Tanya Lattner55808c12011-06-04 00:47:47 +0000856 Value *VisitAsTypeExpr(AsTypeExpr *CE);
Eli Friedmandf14b3a2011-10-11 02:20:01 +0000857 Value *VisitAtomicExpr(AtomicExpr *AE);
Chris Lattner2da04b32007-08-24 05:35:26 +0000858};
859} // end anonymous namespace.
860
861//===----------------------------------------------------------------------===//
862// Utilities
863//===----------------------------------------------------------------------===//
864
Chris Lattnere0044382007-08-26 16:42:57 +0000865/// EmitConversionToBool - Convert the specified expression value to a
Chris Lattner2e928882007-08-26 17:25:57 +0000866/// boolean (i1) truth value. This is equivalent to "Val != 0".
Chris Lattnere0044382007-08-26 16:42:57 +0000867Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
John McCallb692a092009-10-22 20:10:53 +0000868 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
Mike Stump4a3999f2009-09-09 13:00:44 +0000869
John McCall8cb679e2010-11-15 09:13:47 +0000870 if (SrcType->isRealFloatingType())
871 return EmitFloatToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000872
John McCall7a9aac22010-08-23 01:21:21 +0000873 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(SrcType))
874 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, Src, MPT);
Mike Stump4a3999f2009-09-09 13:00:44 +0000875
Daniel Dunbaref957f32008-08-25 10:38:11 +0000876 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
Chris Lattnere0044382007-08-26 16:42:57 +0000877 "Unknown scalar type to convert");
Mike Stump4a3999f2009-09-09 13:00:44 +0000878
John McCall8cb679e2010-11-15 09:13:47 +0000879 if (isa<llvm::IntegerType>(Src->getType()))
880 return EmitIntToBoolConversion(Src);
Mike Stump4a3999f2009-09-09 13:00:44 +0000881
John McCall8cb679e2010-11-15 09:13:47 +0000882 assert(isa<llvm::PointerType>(Src->getType()));
Yaxun Liu402804b2016-12-15 08:09:08 +0000883 return EmitPointerToBoolConversion(Src, SrcType);
Chris Lattnere0044382007-08-26 16:42:57 +0000884}
885
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000886void ScalarExprEmitter::EmitFloatConversionCheck(
887 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
888 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
Richard Smith9e52c432019-07-06 21:05:52 +0000889 assert(SrcType->isFloatingType() && "not a conversion from floating point");
890 if (!isa<llvm::IntegerType>(DstTy))
891 return;
892
Alexey Samsonov24cad992014-07-17 18:46:27 +0000893 CodeGenFunction::SanitizerScope SanScope(&CGF);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000894 using llvm::APFloat;
895 using llvm::APSInt;
896
Craig Topper8a13c412014-05-21 05:09:00 +0000897 llvm::Value *Check = nullptr;
Richard Smith9e52c432019-07-06 21:05:52 +0000898 const llvm::fltSemantics &SrcSema =
899 CGF.getContext().getFloatTypeSemantics(OrigSrcType);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000900
Richard Smith9e52c432019-07-06 21:05:52 +0000901 // Floating-point to integer. This has undefined behavior if the source is
902 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
903 // to an integer).
904 unsigned Width = CGF.getContext().getIntWidth(DstType);
905 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000906
Richard Smith9e52c432019-07-06 21:05:52 +0000907 APSInt Min = APSInt::getMinValue(Width, Unsigned);
908 APFloat MinSrc(SrcSema, APFloat::uninitialized);
909 if (MinSrc.convertFromAPInt(Min, !Unsigned, APFloat::rmTowardZero) &
910 APFloat::opOverflow)
911 // Don't need an overflow check for lower bound. Just check for
912 // -Inf/NaN.
913 MinSrc = APFloat::getInf(SrcSema, true);
914 else
915 // Find the largest value which is too small to represent (before
916 // truncation toward zero).
917 MinSrc.subtract(APFloat(SrcSema, 1), APFloat::rmTowardNegative);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000918
Richard Smith9e52c432019-07-06 21:05:52 +0000919 APSInt Max = APSInt::getMaxValue(Width, Unsigned);
920 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
921 if (MaxSrc.convertFromAPInt(Max, !Unsigned, APFloat::rmTowardZero) &
922 APFloat::opOverflow)
923 // Don't need an overflow check for upper bound. Just check for
924 // +Inf/NaN.
925 MaxSrc = APFloat::getInf(SrcSema, false);
926 else
927 // Find the smallest value which is too large to represent (before
928 // truncation toward zero).
929 MaxSrc.add(APFloat(SrcSema, 1), APFloat::rmTowardPositive);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000930
Richard Smith9e52c432019-07-06 21:05:52 +0000931 // If we're converting from __half, convert the range to float to match
932 // the type of src.
933 if (OrigSrcType->isHalfType()) {
934 const llvm::fltSemantics &Sema =
935 CGF.getContext().getFloatTypeSemantics(SrcType);
936 bool IsInexact;
937 MinSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
938 MaxSrc.convert(Sema, APFloat::rmTowardZero, &IsInexact);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000939 }
940
Richard Smith9e52c432019-07-06 21:05:52 +0000941 llvm::Value *GE =
942 Builder.CreateFCmpOGT(Src, llvm::ConstantFP::get(VMContext, MinSrc));
943 llvm::Value *LE =
944 Builder.CreateFCmpOLT(Src, llvm::ConstantFP::get(VMContext, MaxSrc));
945 Check = Builder.CreateAnd(GE, LE);
946
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +0000947 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
948 CGF.EmitCheckTypeDescriptor(OrigSrcType),
949 CGF.EmitCheckTypeDescriptor(DstType)};
Alexey Samsonove396bfc2014-11-11 22:03:54 +0000950 CGF.EmitCheck(std::make_pair(Check, SanitizerKind::FloatCastOverflow),
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +0000951 SanitizerHandler::FloatCastOverflow, StaticArgs, OrigSrc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +0000952}
953
Roman Lebedev62debd802018-10-30 21:58:56 +0000954// Should be called within CodeGenFunction::SanitizerScope RAII scope.
955// Returns 'i1 false' when the truncation Src -> Dst was lossy.
956static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
957 std::pair<llvm::Value *, SanitizerMask>>
958EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
959 QualType DstType, CGBuilderTy &Builder) {
960 llvm::Type *SrcTy = Src->getType();
961 llvm::Type *DstTy = Dst->getType();
Richard Trieu161121f2018-10-30 23:01:15 +0000962 (void)DstTy; // Only used in assert()
Roman Lebedev62debd802018-10-30 21:58:56 +0000963
964 // This should be truncation of integral types.
965 assert(Src != Dst);
966 assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
967 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
968 "non-integer llvm type");
969
970 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
971 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
972
973 // If both (src and dst) types are unsigned, then it's an unsigned truncation.
974 // Else, it is a signed truncation.
975 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
976 SanitizerMask Mask;
977 if (!SrcSigned && !DstSigned) {
978 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
979 Mask = SanitizerKind::ImplicitUnsignedIntegerTruncation;
980 } else {
981 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
982 Mask = SanitizerKind::ImplicitSignedIntegerTruncation;
983 }
984
985 llvm::Value *Check = nullptr;
986 // 1. Extend the truncated value back to the same width as the Src.
987 Check = Builder.CreateIntCast(Dst, SrcTy, DstSigned, "anyext");
988 // 2. Equality-compare with the original source value
989 Check = Builder.CreateICmpEQ(Check, Src, "truncheck");
990 // If the comparison result is 'i1 false', then the truncation was lossy.
991 return std::make_pair(Kind, std::make_pair(Check, Mask));
992}
993
Roman Lebedevb98a0c72019-11-27 17:07:06 +0300994static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
995 QualType SrcType, QualType DstType) {
996 return SrcType->isIntegerType() && DstType->isIntegerType();
997}
998
Roman Lebedevb69ba222018-07-30 18:58:30 +0000999void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
1000 Value *Dst, QualType DstType,
1001 SourceLocation Loc) {
Roman Lebedevdd403572018-10-11 09:09:50 +00001002 if (!CGF.SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation))
Roman Lebedevb69ba222018-07-30 18:58:30 +00001003 return;
1004
Roman Lebedev62debd802018-10-30 21:58:56 +00001005 // We only care about int->int conversions here.
1006 // We ignore conversions to/from pointer and/or bool.
Roman Lebedevb98a0c72019-11-27 17:07:06 +03001007 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1008 DstType))
Roman Lebedev62debd802018-10-30 21:58:56 +00001009 return;
1010
1011 unsigned SrcBits = Src->getType()->getScalarSizeInBits();
1012 unsigned DstBits = Dst->getType()->getScalarSizeInBits();
1013 // This must be truncation. Else we do not care.
1014 if (SrcBits <= DstBits)
1015 return;
1016
1017 assert(!DstType->isBooleanType() && "we should not get here with booleans.");
1018
1019 // If the integer sign change sanitizer is enabled,
1020 // and we are truncating from larger unsigned type to smaller signed type,
1021 // let that next sanitizer deal with it.
1022 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1023 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1024 if (CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange) &&
1025 (!SrcSigned && DstSigned))
1026 return;
1027
1028 CodeGenFunction::SanitizerScope SanScope(&CGF);
1029
1030 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1031 std::pair<llvm::Value *, SanitizerMask>>
1032 Check =
1033 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1034 // If the comparison result is 'i1 false', then the truncation was lossy.
1035
1036 // Do we care about this type of truncation?
1037 if (!CGF.SanOpts.has(Check.second.second))
1038 return;
1039
1040 llvm::Constant *StaticArgs[] = {
1041 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1042 CGF.EmitCheckTypeDescriptor(DstType),
1043 llvm::ConstantInt::get(Builder.getInt8Ty(), Check.first)};
1044 CGF.EmitCheck(Check.second, SanitizerHandler::ImplicitConversion, StaticArgs,
1045 {Src, Dst});
1046}
1047
1048// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1049// Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1050static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1051 std::pair<llvm::Value *, SanitizerMask>>
1052EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1053 QualType DstType, CGBuilderTy &Builder) {
1054 llvm::Type *SrcTy = Src->getType();
1055 llvm::Type *DstTy = Dst->getType();
1056
1057 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1058 "non-integer llvm type");
1059
1060 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1061 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
Richard Trieu161121f2018-10-30 23:01:15 +00001062 (void)SrcSigned; // Only used in assert()
1063 (void)DstSigned; // Only used in assert()
Roman Lebedev62debd802018-10-30 21:58:56 +00001064 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1065 unsigned DstBits = DstTy->getScalarSizeInBits();
1066 (void)SrcBits; // Only used in assert()
1067 (void)DstBits; // Only used in assert()
1068
1069 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1070 "either the widths should be different, or the signednesses.");
1071
1072 // NOTE: zero value is considered to be non-negative.
1073 auto EmitIsNegativeTest = [&Builder](Value *V, QualType VType,
1074 const char *Name) -> Value * {
1075 // Is this value a signed type?
1076 bool VSigned = VType->isSignedIntegerOrEnumerationType();
1077 llvm::Type *VTy = V->getType();
1078 if (!VSigned) {
1079 // If the value is unsigned, then it is never negative.
1080 // FIXME: can we encounter non-scalar VTy here?
1081 return llvm::ConstantInt::getFalse(VTy->getContext());
1082 }
1083 // Get the zero of the same type with which we will be comparing.
1084 llvm::Constant *Zero = llvm::ConstantInt::get(VTy, 0);
1085 // %V.isnegative = icmp slt %V, 0
1086 // I.e is %V *strictly* less than zero, does it have negative value?
1087 return Builder.CreateICmp(llvm::ICmpInst::ICMP_SLT, V, Zero,
1088 llvm::Twine(Name) + "." + V->getName() +
1089 ".negativitycheck");
1090 };
1091
1092 // 1. Was the old Value negative?
1093 llvm::Value *SrcIsNegative = EmitIsNegativeTest(Src, SrcType, "src");
1094 // 2. Is the new Value negative?
1095 llvm::Value *DstIsNegative = EmitIsNegativeTest(Dst, DstType, "dst");
1096 // 3. Now, was the 'negativity status' preserved during the conversion?
1097 // NOTE: conversion from negative to zero is considered to change the sign.
1098 // (We want to get 'false' when the conversion changed the sign)
1099 // So we should just equality-compare the negativity statuses.
1100 llvm::Value *Check = nullptr;
1101 Check = Builder.CreateICmpEQ(SrcIsNegative, DstIsNegative, "signchangecheck");
1102 // If the comparison result is 'false', then the conversion changed the sign.
1103 return std::make_pair(
1104 ScalarExprEmitter::ICCK_IntegerSignChange,
1105 std::make_pair(Check, SanitizerKind::ImplicitIntegerSignChange));
1106}
1107
1108void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1109 Value *Dst, QualType DstType,
1110 SourceLocation Loc) {
1111 if (!CGF.SanOpts.has(SanitizerKind::ImplicitIntegerSignChange))
1112 return;
1113
Roman Lebedevb69ba222018-07-30 18:58:30 +00001114 llvm::Type *SrcTy = Src->getType();
1115 llvm::Type *DstTy = Dst->getType();
1116
1117 // We only care about int->int conversions here.
1118 // We ignore conversions to/from pointer and/or bool.
Roman Lebedevb98a0c72019-11-27 17:07:06 +03001119 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1120 DstType))
Roman Lebedevb69ba222018-07-30 18:58:30 +00001121 return;
1122
Roman Lebedevdd403572018-10-11 09:09:50 +00001123 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1124 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
Roman Lebedev62debd802018-10-30 21:58:56 +00001125 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1126 unsigned DstBits = DstTy->getScalarSizeInBits();
Roman Lebedevdd403572018-10-11 09:09:50 +00001127
Roman Lebedev62debd802018-10-30 21:58:56 +00001128 // Now, we do not need to emit the check in *all* of the cases.
1129 // We can avoid emitting it in some obvious cases where it would have been
1130 // dropped by the opt passes (instcombine) always anyways.
Roman Lebedev1bb9aea2018-11-01 08:56:51 +00001131 // If it's a cast between effectively the same type, no check.
1132 // NOTE: this is *not* equivalent to checking the canonical types.
1133 if (SrcSigned == DstSigned && SrcBits == DstBits)
Roman Lebedevdd403572018-10-11 09:09:50 +00001134 return;
Roman Lebedev62debd802018-10-30 21:58:56 +00001135 // At least one of the values needs to have signed type.
1136 // If both are unsigned, then obviously, neither of them can be negative.
1137 if (!SrcSigned && !DstSigned)
1138 return;
1139 // If the conversion is to *larger* *signed* type, then no check is needed.
1140 // Because either sign-extension happens (so the sign will remain),
1141 // or zero-extension will happen (the sign bit will be zero.)
1142 if ((DstBits > SrcBits) && DstSigned)
1143 return;
1144 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1145 (SrcBits > DstBits) && SrcSigned) {
1146 // If the signed integer truncation sanitizer is enabled,
1147 // and this is a truncation from signed type, then no check is needed.
1148 // Because here sign change check is interchangeable with truncation check.
1149 return;
1150 }
1151 // That's it. We can't rule out any more cases with the data we have.
Roman Lebedevdd403572018-10-11 09:09:50 +00001152
Roman Lebedevb69ba222018-07-30 18:58:30 +00001153 CodeGenFunction::SanitizerScope SanScope(&CGF);
1154
Roman Lebedev62debd802018-10-30 21:58:56 +00001155 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1156 std::pair<llvm::Value *, SanitizerMask>>
1157 Check;
Roman Lebedevb69ba222018-07-30 18:58:30 +00001158
Roman Lebedev62debd802018-10-30 21:58:56 +00001159 // Each of these checks needs to return 'false' when an issue was detected.
1160 ImplicitConversionCheckKind CheckKind;
1161 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
1162 // So we can 'and' all the checks together, and still get 'false',
1163 // if at least one of the checks detected an issue.
1164
1165 Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1166 CheckKind = Check.first;
1167 Checks.emplace_back(Check.second);
1168
1169 if (CGF.SanOpts.has(SanitizerKind::ImplicitSignedIntegerTruncation) &&
1170 (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1171 // If the signed integer truncation sanitizer was enabled,
1172 // and we are truncating from larger unsigned type to smaller signed type,
1173 // let's handle the case we skipped in that check.
1174 Check =
1175 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1176 CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1177 Checks.emplace_back(Check.second);
1178 // If the comparison result is 'i1 false', then the truncation was lossy.
1179 }
Roman Lebedevb69ba222018-07-30 18:58:30 +00001180
1181 llvm::Constant *StaticArgs[] = {
1182 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(SrcType),
1183 CGF.EmitCheckTypeDescriptor(DstType),
Roman Lebedev62debd802018-10-30 21:58:56 +00001184 llvm::ConstantInt::get(Builder.getInt8Ty(), CheckKind)};
1185 // EmitCheck() will 'and' all the checks together.
1186 CGF.EmitCheck(Checks, SanitizerHandler::ImplicitConversion, StaticArgs,
1187 {Src, Dst});
Roman Lebedevb69ba222018-07-30 18:58:30 +00001188}
1189
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00001190/// Emit a conversion from the specified type to the specified destination type,
1191/// both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00001192Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001193 QualType DstType,
Anastasia Stulovab02e7832015-10-05 11:27:41 +00001194 SourceLocation Loc,
Roman Lebedevb69ba222018-07-30 18:58:30 +00001195 ScalarConversionOpts Opts) {
Leonard Chanb4ba4672018-10-23 17:55:35 +00001196 // All conversions involving fixed point types should be handled by the
1197 // EmitFixedPoint family functions. This is done to prevent bloating up this
1198 // function more, and although fixed point numbers are represented by
1199 // integers, we do not want to follow any logic that assumes they should be
1200 // treated as integers.
1201 // TODO(leonardchan): When necessary, add another if statement checking for
1202 // conversions to fixed point types from other types.
1203 if (SrcType->isFixedPointType()) {
Leonard Chan8f7caae2019-03-06 00:28:43 +00001204 if (DstType->isBooleanType())
1205 // It is important that we check this before checking if the dest type is
1206 // an integer because booleans are technically integer types.
Leonard Chanb4ba4672018-10-23 17:55:35 +00001207 // We do not need to check the padding bit on unsigned types if unsigned
1208 // padding is enabled because overflow into this bit is undefined
1209 // behavior.
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001210 return Builder.CreateIsNotNull(Src, "tobool");
Leonard Chan8f7caae2019-03-06 00:28:43 +00001211 if (DstType->isFixedPointType() || DstType->isIntegerType())
1212 return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
Leonard Chanb4ba4672018-10-23 17:55:35 +00001213
1214 llvm_unreachable(
Leonard Chan8f7caae2019-03-06 00:28:43 +00001215 "Unhandled scalar conversion from a fixed point type to another type.");
1216 } else if (DstType->isFixedPointType()) {
1217 if (SrcType->isIntegerType())
1218 // This also includes converting booleans and enums to fixed point types.
1219 return EmitFixedPointConversion(Src, SrcType, DstType, Loc);
1220
1221 llvm_unreachable(
1222 "Unhandled scalar conversion to a fixed point type from another type.");
Leonard Chanb4ba4672018-10-23 17:55:35 +00001223 }
Leonard Chan99bda372018-10-15 16:07:02 +00001224
Roman Lebedevb69ba222018-07-30 18:58:30 +00001225 QualType NoncanonicalSrcType = SrcType;
1226 QualType NoncanonicalDstType = DstType;
1227
Chris Lattner0f398c42008-07-26 22:37:01 +00001228 SrcType = CGF.getContext().getCanonicalType(SrcType);
1229 DstType = CGF.getContext().getCanonicalType(DstType);
Chris Lattner3474c202007-08-26 06:48:56 +00001230 if (SrcType == DstType) return Src;
Mike Stump4a3999f2009-09-09 13:00:44 +00001231
Craig Topper8a13c412014-05-21 05:09:00 +00001232 if (DstType->isVoidType()) return nullptr;
Mike Stump4a3999f2009-09-09 13:00:44 +00001233
Richard Smithf9a1e4a2012-10-12 22:57:06 +00001234 llvm::Value *OrigSrc = Src;
1235 QualType OrigSrcType = SrcType;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001236 llvm::Type *SrcTy = Src->getType();
1237
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +00001238 // Handle conversions to bool first, they are special: comparisons against 0.
1239 if (DstType->isBooleanType())
1240 return EmitConversionToBool(Src, SrcType);
1241
1242 llvm::Type *DstTy = ConvertType(DstType);
1243
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001244 // Cast from half through float if half isn't a native type.
1245 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1246 // Cast to FP using the intrinsic if the half type itself isn't supported.
1247 if (DstTy->isFloatingPointTy()) {
Akira Hatanaka502775a2017-12-09 00:02:37 +00001248 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001249 return Builder.CreateCall(
1250 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16, DstTy),
1251 Src);
1252 } else {
1253 // Cast to other types through float, using either the intrinsic or FPExt,
1254 // depending on whether the half type itself is supported
1255 // (as opposed to operations on half, available with NativeHalfType).
Akira Hatanaka502775a2017-12-09 00:02:37 +00001256 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001257 Src = Builder.CreateCall(
1258 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
1259 CGF.CGM.FloatTy),
1260 Src);
1261 } else {
1262 Src = Builder.CreateFPExt(Src, CGF.CGM.FloatTy, "conv");
1263 }
1264 SrcType = CGF.getContext().FloatTy;
1265 SrcTy = CGF.FloatTy;
1266 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001267 }
1268
Chris Lattner3474c202007-08-26 06:48:56 +00001269 // Ignore conversions like int -> uint.
Roman Lebedev62debd802018-10-30 21:58:56 +00001270 if (SrcTy == DstTy) {
1271 if (Opts.EmitImplicitIntegerSignChangeChecks)
1272 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Src,
1273 NoncanonicalDstType, Loc);
1274
Chris Lattner3474c202007-08-26 06:48:56 +00001275 return Src;
Roman Lebedev62debd802018-10-30 21:58:56 +00001276 }
Chris Lattner3474c202007-08-26 06:48:56 +00001277
Mike Stump4a3999f2009-09-09 13:00:44 +00001278 // Handle pointer conversions next: pointers can only be converted to/from
1279 // other pointers and integers. Check for pointer types in terms of LLVM, as
1280 // some native types (like Obj-C id) may map to a pointer type.
Yaxun Liu26f75662016-08-19 05:17:25 +00001281 if (auto DstPT = dyn_cast<llvm::PointerType>(DstTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +00001282 // The source value may be an integer, or a pointer.
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001283 if (isa<llvm::PointerType>(SrcTy))
Chris Lattner3474c202007-08-26 06:48:56 +00001284 return Builder.CreateBitCast(Src, DstTy, "conv");
Anders Carlsson12f5a252009-09-12 04:57:16 +00001285
Chris Lattner3474c202007-08-26 06:48:56 +00001286 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
Eli Friedman42d2a3a2009-03-04 04:02:35 +00001287 // First, convert to the correct width so that we control the kind of
1288 // extension.
Yaxun Liu26f75662016-08-19 05:17:25 +00001289 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001290 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Eli Friedman42d2a3a2009-03-04 04:02:35 +00001291 llvm::Value* IntResult =
1292 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
1293 // Then, cast to pointer.
1294 return Builder.CreateIntToPtr(IntResult, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +00001295 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001296
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001297 if (isa<llvm::PointerType>(SrcTy)) {
Chris Lattner3474c202007-08-26 06:48:56 +00001298 // Must be an ptr to int cast.
1299 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
Anders Carlssone89b84a2007-10-31 23:18:02 +00001300 return Builder.CreatePtrToInt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +00001301 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001302
Nate Begemance4d7fc2008-04-18 23:10:10 +00001303 // A scalar can be splatted to an extended vector of the same element type
Nate Begeman5ec4b312009-08-10 23:49:36 +00001304 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
George Burgess IVdf1ed002016-01-13 01:52:39 +00001305 // Sema should add casts to make sure that the source expression's type is
1306 // the same as the vector's element type (sans qualifiers)
1307 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1308 SrcType.getTypePtr() &&
1309 "Splatted expr doesn't match with vector element type?");
Nate Begemanb699c9b2009-01-18 06:42:49 +00001310
Nate Begemanb699c9b2009-01-18 06:42:49 +00001311 // Splat the element across to all elements
Christopher Tetreaultf22fbe32020-04-13 12:30:53 -07001312 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
George Burgess IVdf1ed002016-01-13 01:52:39 +00001313 return Builder.CreateVectorSplat(NumElements, Src, "splat");
Nate Begemanb699c9b2009-01-18 06:42:49 +00001314 }
Nate Begeman330aaa72007-12-30 02:59:45 +00001315
Akira Hatanaka34b5dbc2017-09-23 05:02:02 +00001316 if (isa<llvm::VectorType>(SrcTy) || isa<llvm::VectorType>(DstTy)) {
1317 // Allow bitcast from vector to integer/fp of the same size.
1318 unsigned SrcSize = SrcTy->getPrimitiveSizeInBits();
1319 unsigned DstSize = DstTy->getPrimitiveSizeInBits();
1320 if (SrcSize == DstSize)
1321 return Builder.CreateBitCast(Src, DstTy, "conv");
1322
1323 // Conversions between vectors of different sizes are not allowed except
1324 // when vectors of half are involved. Operations on storage-only half
1325 // vectors require promoting half vector operands to float vectors and
1326 // truncating the result, which is either an int or float vector, to a
1327 // short or half vector.
1328
1329 // Source and destination are both expected to be vectors.
Christopher Tetreaultf22fbe32020-04-13 12:30:53 -07001330 llvm::Type *SrcElementTy = cast<llvm::VectorType>(SrcTy)->getElementType();
1331 llvm::Type *DstElementTy = cast<llvm::VectorType>(DstTy)->getElementType();
Benjamin Kramer5c42bcc2017-09-23 16:08:48 +00001332 (void)DstElementTy;
Akira Hatanaka34b5dbc2017-09-23 05:02:02 +00001333
1334 assert(((SrcElementTy->isIntegerTy() &&
1335 DstElementTy->isIntegerTy()) ||
1336 (SrcElementTy->isFloatingPointTy() &&
1337 DstElementTy->isFloatingPointTy())) &&
1338 "unexpected conversion between a floating-point vector and an "
1339 "integer vector");
1340
1341 // Truncate an i32 vector to an i16 vector.
1342 if (SrcElementTy->isIntegerTy())
1343 return Builder.CreateIntCast(Src, DstTy, false, "conv");
1344
1345 // Truncate a float vector to a half vector.
1346 if (SrcSize > DstSize)
1347 return Builder.CreateFPTrunc(Src, DstTy, "conv");
1348
1349 // Promote a half vector to a float vector.
1350 return Builder.CreateFPExt(Src, DstTy, "conv");
1351 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001352
Chris Lattner3474c202007-08-26 06:48:56 +00001353 // Finally, we have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +00001354 Value *Res = nullptr;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001355 llvm::Type *ResTy = DstTy;
1356
Richard Smithf9a1e4a2012-10-12 22:57:06 +00001357 // An overflowing conversion has undefined behavior if either the source type
Richard Smith9e52c432019-07-06 21:05:52 +00001358 // or the destination type is a floating-point type. However, we consider the
1359 // range of representable values for all floating-point types to be
1360 // [-inf,+inf], so no overflow can ever happen when the destination type is a
1361 // floating-point type.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001362 if (CGF.SanOpts.has(SanitizerKind::FloatCastOverflow) &&
Richard Smith9e52c432019-07-06 21:05:52 +00001363 OrigSrcType->isFloatingType())
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001364 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1365 Loc);
Richard Smithf9a1e4a2012-10-12 22:57:06 +00001366
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001367 // Cast to half through float if half isn't a native type.
1368 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1369 // Make sure we cast in a single step if from another FP type.
1370 if (SrcTy->isFloatingPointTy()) {
1371 // Use the intrinsic if the half type itself isn't supported
1372 // (as opposed to operations on half, available with NativeHalfType).
Akira Hatanaka502775a2017-12-09 00:02:37 +00001373 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics())
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001374 return Builder.CreateCall(
1375 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, SrcTy), Src);
1376 // If the half type is supported, just use an fptrunc.
1377 return Builder.CreateFPTrunc(Src, DstTy);
1378 }
Chris Lattnerece04092012-02-07 00:39:47 +00001379 DstTy = CGF.FloatTy;
Ahmed Bougacha47ec2c72015-03-23 17:48:07 +00001380 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001381
1382 if (isa<llvm::IntegerType>(SrcTy)) {
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001383 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
Roman Lebedevb69ba222018-07-30 18:58:30 +00001384 if (SrcType->isBooleanType() && Opts.TreatBooleanAsSigned) {
Anastasia Stulovab02e7832015-10-05 11:27:41 +00001385 InputSigned = true;
1386 }
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001387 if (isa<llvm::IntegerType>(DstTy))
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001388 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001389 else if (InputSigned)
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001390 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001391 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001392 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1393 } else if (isa<llvm::IntegerType>(DstTy)) {
1394 assert(SrcTy->isFloatingPointTy() && "Unknown real conversion");
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001395 if (DstType->isSignedIntegerOrEnumerationType())
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001396 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
Anders Carlssonc9d41e72007-12-26 18:20:19 +00001397 else
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001398 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1399 } else {
1400 assert(SrcTy->isFloatingPointTy() && DstTy->isFloatingPointTy() &&
1401 "Unknown real conversion");
1402 if (DstTy->getTypeID() < SrcTy->getTypeID())
1403 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1404 else
1405 Res = Builder.CreateFPExt(Src, DstTy, "conv");
Chris Lattner3474c202007-08-26 06:48:56 +00001406 }
1407
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001408 if (DstTy != ResTy) {
Akira Hatanaka502775a2017-12-09 00:02:37 +00001409 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001410 assert(ResTy->isIntegerTy(16) && "Only half FP requires extra conversion");
1411 Res = Builder.CreateCall(
Tim Northover6dbcbac2014-07-17 10:51:31 +00001412 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16, CGF.CGM.FloatTy),
1413 Res);
Ahmed Bougachad1801af2015-03-23 17:54:16 +00001414 } else {
1415 Res = Builder.CreateFPTrunc(Res, ResTy, "conv");
1416 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001417 }
1418
Roman Lebedevb69ba222018-07-30 18:58:30 +00001419 if (Opts.EmitImplicitIntegerTruncationChecks)
1420 EmitIntegerTruncationCheck(Src, NoncanonicalSrcType, Res,
1421 NoncanonicalDstType, Loc);
1422
Roman Lebedev62debd802018-10-30 21:58:56 +00001423 if (Opts.EmitImplicitIntegerSignChangeChecks)
1424 EmitIntegerSignChangeCheck(Src, NoncanonicalSrcType, Res,
1425 NoncanonicalDstType, Loc);
1426
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001427 return Res;
Chris Lattner3474c202007-08-26 06:48:56 +00001428}
1429
Leonard Chan99bda372018-10-15 16:07:02 +00001430Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1431 QualType DstTy,
1432 SourceLocation Loc) {
Leonard Chan99bda372018-10-15 16:07:02 +00001433 FixedPointSemantics SrcFPSema =
1434 CGF.getContext().getFixedPointSemantics(SrcTy);
1435 FixedPointSemantics DstFPSema =
1436 CGF.getContext().getFixedPointSemantics(DstTy);
Leonard Chan8f7caae2019-03-06 00:28:43 +00001437 return EmitFixedPointConversion(Src, SrcFPSema, DstFPSema, Loc,
1438 DstTy->isIntegerType());
Leonard Chan2044ac82019-01-16 18:13:59 +00001439}
1440
1441Value *ScalarExprEmitter::EmitFixedPointConversion(
1442 Value *Src, FixedPointSemantics &SrcFPSema, FixedPointSemantics &DstFPSema,
Leonard Chan8f7caae2019-03-06 00:28:43 +00001443 SourceLocation Loc, bool DstIsInteger) {
Leonard Chan2044ac82019-01-16 18:13:59 +00001444 using llvm::APInt;
1445 using llvm::ConstantInt;
1446 using llvm::Value;
1447
Leonard Chan99bda372018-10-15 16:07:02 +00001448 unsigned SrcWidth = SrcFPSema.getWidth();
1449 unsigned DstWidth = DstFPSema.getWidth();
1450 unsigned SrcScale = SrcFPSema.getScale();
1451 unsigned DstScale = DstFPSema.getScale();
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001452 bool SrcIsSigned = SrcFPSema.isSigned();
1453 bool DstIsSigned = DstFPSema.isSigned();
1454
1455 llvm::Type *DstIntTy = Builder.getIntNTy(DstWidth);
Leonard Chan99bda372018-10-15 16:07:02 +00001456
1457 Value *Result = Src;
1458 unsigned ResultWidth = SrcWidth;
1459
Leonard Chan8f7caae2019-03-06 00:28:43 +00001460 // Downscale.
1461 if (DstScale < SrcScale) {
1462 // When converting to integers, we round towards zero. For negative numbers,
1463 // right shifting rounds towards negative infinity. In this case, we can
1464 // just round up before shifting.
1465 if (DstIsInteger && SrcIsSigned) {
1466 Value *Zero = llvm::Constant::getNullValue(Result->getType());
1467 Value *IsNegative = Builder.CreateICmpSLT(Result, Zero);
1468 Value *LowBits = ConstantInt::get(
1469 CGF.getLLVMContext(), APInt::getLowBitsSet(ResultWidth, SrcScale));
1470 Value *Rounded = Builder.CreateAdd(Result, LowBits);
1471 Result = Builder.CreateSelect(IsNegative, Rounded, Result);
1472 }
Leonard Chan99bda372018-10-15 16:07:02 +00001473
Leonard Chan8f7caae2019-03-06 00:28:43 +00001474 Result = SrcIsSigned
1475 ? Builder.CreateAShr(Result, SrcScale - DstScale, "downscale")
1476 : Builder.CreateLShr(Result, SrcScale - DstScale, "downscale");
1477 }
1478
1479 if (!DstFPSema.isSaturated()) {
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001480 // Resize.
1481 Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
Leonard Chan99bda372018-10-15 16:07:02 +00001482
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001483 // Upscale.
Leonard Chan99bda372018-10-15 16:07:02 +00001484 if (DstScale > SrcScale)
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001485 Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
Leonard Chan99bda372018-10-15 16:07:02 +00001486 } else {
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001487 // Adjust the number of fractional bits.
Leonard Chan99bda372018-10-15 16:07:02 +00001488 if (DstScale > SrcScale) {
Leonard Chan2044ac82019-01-16 18:13:59 +00001489 // Compare to DstWidth to prevent resizing twice.
1490 ResultWidth = std::max(SrcWidth + DstScale - SrcScale, DstWidth);
Leonard Chan99bda372018-10-15 16:07:02 +00001491 llvm::Type *UpscaledTy = Builder.getIntNTy(ResultWidth);
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001492 Result = Builder.CreateIntCast(Result, UpscaledTy, SrcIsSigned, "resize");
1493 Result = Builder.CreateShl(Result, DstScale - SrcScale, "upscale");
Leonard Chan99bda372018-10-15 16:07:02 +00001494 }
1495
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001496 // Handle saturation.
1497 bool LessIntBits = DstFPSema.getIntegralBits() < SrcFPSema.getIntegralBits();
1498 if (LessIntBits) {
1499 Value *Max = ConstantInt::get(
Leonard Chan99bda372018-10-15 16:07:02 +00001500 CGF.getLLVMContext(),
1501 APFixedPoint::getMax(DstFPSema).getValue().extOrTrunc(ResultWidth));
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001502 Value *TooHigh = SrcIsSigned ? Builder.CreateICmpSGT(Result, Max)
1503 : Builder.CreateICmpUGT(Result, Max);
1504 Result = Builder.CreateSelect(TooHigh, Max, Result, "satmax");
1505 }
1506 // Cannot overflow min to dest type if src is unsigned since all fixed
1507 // point types can cover the unsigned min of 0.
1508 if (SrcIsSigned && (LessIntBits || !DstIsSigned)) {
1509 Value *Min = ConstantInt::get(
1510 CGF.getLLVMContext(),
1511 APFixedPoint::getMin(DstFPSema).getValue().extOrTrunc(ResultWidth));
1512 Value *TooLow = Builder.CreateICmpSLT(Result, Min);
1513 Result = Builder.CreateSelect(TooLow, Min, Result, "satmin");
Leonard Chan99bda372018-10-15 16:07:02 +00001514 }
1515
Bjorn Petterssonb2534022018-10-26 16:12:12 +00001516 // Resize the integer part to get the final destination size.
Leonard Chan2044ac82019-01-16 18:13:59 +00001517 if (ResultWidth != DstWidth)
1518 Result = Builder.CreateIntCast(Result, DstIntTy, SrcIsSigned, "resize");
Leonard Chan99bda372018-10-15 16:07:02 +00001519 }
1520 return Result;
1521}
1522
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00001523/// Emit a conversion from the specified complex type to the specified
1524/// destination type, where the destination type is an LLVM scalar type.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001525Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1526 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1527 SourceLocation Loc) {
Chris Lattnerc141c1b2007-08-26 16:52:28 +00001528 // Get the source element type.
John McCall47fb9502013-03-07 21:37:08 +00001529 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
Mike Stump4a3999f2009-09-09 13:00:44 +00001530
Chris Lattnerc141c1b2007-08-26 16:52:28 +00001531 // Handle conversions to bool first, they are special: comparisons against 0.
1532 if (DstTy->isBooleanType()) {
1533 // Complex != 0 -> (Real != 0) | (Imag != 0)
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001534 Src.first = EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
1535 Src.second = EmitScalarConversion(Src.second, SrcTy, DstTy, Loc);
Chris Lattnerc141c1b2007-08-26 16:52:28 +00001536 return Builder.CreateOr(Src.first, Src.second, "tobool");
1537 }
Mike Stump4a3999f2009-09-09 13:00:44 +00001538
Chris Lattner42e6b812007-08-26 16:34:22 +00001539 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1540 // the imaginary part of the complex value is discarded and the value of the
1541 // real part is converted according to the conversion rules for the
Mike Stump4a3999f2009-09-09 13:00:44 +00001542 // corresponding real type.
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00001543 return EmitScalarConversion(Src.first, SrcTy, DstTy, Loc);
Chris Lattner42e6b812007-08-26 16:34:22 +00001544}
1545
Anders Carlsson5b944432010-05-22 17:45:10 +00001546Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
Richard Smithd82a2ce2012-12-21 03:17:28 +00001547 return CGF.EmitFromMemory(CGF.CGM.EmitNullConstant(Ty), Ty);
Anders Carlsson5b944432010-05-22 17:45:10 +00001548}
Chris Lattner42e6b812007-08-26 16:34:22 +00001549
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001550/// Emit a sanitization check for the given "binary" operation (which
Richard Smithe30752c2012-10-09 19:52:38 +00001551/// might actually be a unary increment which has been lowered to a binary
Alexey Samsonove396bfc2014-11-11 22:03:54 +00001552/// operation). The check passes if all values in \p Checks (which are \c i1),
1553/// are \c true.
1554void ScalarExprEmitter::EmitBinOpCheck(
Peter Collingbourne3eea6772015-05-11 21:39:14 +00001555 ArrayRef<std::pair<Value *, SanitizerMask>> Checks, const BinOpInfo &Info) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00001556 assert(CGF.IsSanitizerScope);
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001557 SanitizerHandler Check;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001558 SmallVector<llvm::Constant *, 4> StaticData;
1559 SmallVector<llvm::Value *, 2> DynamicData;
Richard Smithe30752c2012-10-09 19:52:38 +00001560
1561 BinaryOperatorKind Opcode = Info.Opcode;
1562 if (BinaryOperator::isCompoundAssignmentOp(Opcode))
1563 Opcode = BinaryOperator::getOpForCompoundAssignment(Opcode);
1564
1565 StaticData.push_back(CGF.EmitCheckSourceLocation(Info.E->getExprLoc()));
1566 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Info.E);
1567 if (UO && UO->getOpcode() == UO_Minus) {
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001568 Check = SanitizerHandler::NegateOverflow;
Richard Smithe30752c2012-10-09 19:52:38 +00001569 StaticData.push_back(CGF.EmitCheckTypeDescriptor(UO->getType()));
1570 DynamicData.push_back(Info.RHS);
1571 } else {
1572 if (BinaryOperator::isShiftOp(Opcode)) {
1573 // Shift LHS negative or too large, or RHS out of bounds.
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001574 Check = SanitizerHandler::ShiftOutOfBounds;
Richard Smithe30752c2012-10-09 19:52:38 +00001575 const BinaryOperator *BO = cast<BinaryOperator>(Info.E);
1576 StaticData.push_back(
1577 CGF.EmitCheckTypeDescriptor(BO->getLHS()->getType()));
1578 StaticData.push_back(
1579 CGF.EmitCheckTypeDescriptor(BO->getRHS()->getType()));
1580 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1581 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001582 Check = SanitizerHandler::DivremOverflow;
Will Dietzcefb4482013-01-07 22:25:52 +00001583 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +00001584 } else {
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00001585 // Arithmetic overflow (+, -, *).
Richard Smithe30752c2012-10-09 19:52:38 +00001586 switch (Opcode) {
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001587 case BO_Add: Check = SanitizerHandler::AddOverflow; break;
1588 case BO_Sub: Check = SanitizerHandler::SubOverflow; break;
1589 case BO_Mul: Check = SanitizerHandler::MulOverflow; break;
Richard Smithe30752c2012-10-09 19:52:38 +00001590 default: llvm_unreachable("unexpected opcode for bin op check");
1591 }
Will Dietzcefb4482013-01-07 22:25:52 +00001592 StaticData.push_back(CGF.EmitCheckTypeDescriptor(Info.Ty));
Richard Smithe30752c2012-10-09 19:52:38 +00001593 }
1594 DynamicData.push_back(Info.LHS);
1595 DynamicData.push_back(Info.RHS);
1596 }
1597
Filipe Cabecinhas322ecd92016-12-12 16:18:40 +00001598 CGF.EmitCheck(Checks, Check, StaticData, DynamicData);
Richard Smithe30752c2012-10-09 19:52:38 +00001599}
1600
Chris Lattner2da04b32007-08-24 05:35:26 +00001601//===----------------------------------------------------------------------===//
1602// Visitor Methods
1603//===----------------------------------------------------------------------===//
1604
1605Value *ScalarExprEmitter::VisitExpr(Expr *E) {
Daniel Dunbara7c8cf62008-08-16 00:56:44 +00001606 CGF.ErrorUnsupported(E, "scalar expression");
Chris Lattner2da04b32007-08-24 05:35:26 +00001607 if (E->getType()->isVoidType())
Craig Topper8a13c412014-05-21 05:09:00 +00001608 return nullptr;
Owen Anderson7ec07a52009-07-30 23:11:26 +00001609 return llvm::UndefValue::get(CGF.ConvertType(E->getType()));
Chris Lattner2da04b32007-08-24 05:35:26 +00001610}
1611
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001612Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
Nate Begemana0110022010-06-08 00:16:34 +00001613 // Vector Mask Case
Craig Topperb3174a82016-05-18 04:11:25 +00001614 if (E->getNumSubExprs() == 2) {
Chris Lattner5e016ae2010-06-27 07:15:29 +00001615 Value *LHS = CGF.EmitScalarExpr(E->getExpr(0));
1616 Value *RHS = CGF.EmitScalarExpr(E->getExpr(1));
1617 Value *Mask;
Craig Toppera97d7e72013-07-26 06:16:11 +00001618
Chris Lattner2192fe52011-07-18 04:24:23 +00001619 llvm::VectorType *LTy = cast<llvm::VectorType>(LHS->getType());
Nate Begemana0110022010-06-08 00:16:34 +00001620 unsigned LHSElts = LTy->getNumElements();
1621
Craig Topperb3174a82016-05-18 04:11:25 +00001622 Mask = RHS;
Craig Toppera97d7e72013-07-26 06:16:11 +00001623
Chris Lattner2192fe52011-07-18 04:24:23 +00001624 llvm::VectorType *MTy = cast<llvm::VectorType>(Mask->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001625
Nate Begemana0110022010-06-08 00:16:34 +00001626 // Mask off the high bits of each shuffle index.
Benjamin Kramer99383102015-07-28 16:25:32 +00001627 Value *MaskBits =
1628 llvm::ConstantInt::get(MTy, llvm::NextPowerOf2(LHSElts - 1) - 1);
Nate Begemana0110022010-06-08 00:16:34 +00001629 Mask = Builder.CreateAnd(Mask, MaskBits, "mask");
Craig Toppera97d7e72013-07-26 06:16:11 +00001630
Nate Begemana0110022010-06-08 00:16:34 +00001631 // newv = undef
1632 // mask = mask & maskbits
1633 // for each elt
1634 // n = extract mask i
1635 // x = extract val n
1636 // newv = insert newv, x, i
Chris Lattner2192fe52011-07-18 04:24:23 +00001637 llvm::VectorType *RTy = llvm::VectorType::get(LTy->getElementType(),
Craig Topper18243fb2013-07-27 05:00:42 +00001638 MTy->getNumElements());
Nate Begemana0110022010-06-08 00:16:34 +00001639 Value* NewV = llvm::UndefValue::get(RTy);
1640 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
Michael J. Spencerdd597752014-05-31 00:22:12 +00001641 Value *IIndx = llvm::ConstantInt::get(CGF.SizeTy, i);
Eli Friedman1fa36052012-04-05 21:48:40 +00001642 Value *Indx = Builder.CreateExtractElement(Mask, IIndx, "shuf_idx");
Craig Toppera97d7e72013-07-26 06:16:11 +00001643
Nate Begemana0110022010-06-08 00:16:34 +00001644 Value *VExt = Builder.CreateExtractElement(LHS, Indx, "shuf_elt");
Eli Friedman1fa36052012-04-05 21:48:40 +00001645 NewV = Builder.CreateInsertElement(NewV, VExt, IIndx, "shuf_ins");
Nate Begemana0110022010-06-08 00:16:34 +00001646 }
1647 return NewV;
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001648 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001649
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001650 Value* V1 = CGF.EmitScalarExpr(E->getExpr(0));
1651 Value* V2 = CGF.EmitScalarExpr(E->getExpr(1));
Craig Toppera97d7e72013-07-26 06:16:11 +00001652
Benjamin Kramer6f64dac2020-04-15 12:41:54 +02001653 SmallVector<int, 32> Indices;
Craig Topper0ed37bd2013-08-01 04:51:48 +00001654 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
Craig Topper50ad5b72013-08-03 17:40:38 +00001655 llvm::APSInt Idx = E->getShuffleMaskIdx(CGF.getContext(), i-2);
1656 // Check for -1 and output it as undef in the IR.
1657 if (Idx.isSigned() && Idx.isAllOnesValue())
Benjamin Kramer6f64dac2020-04-15 12:41:54 +02001658 Indices.push_back(-1);
Craig Topper50ad5b72013-08-03 17:40:38 +00001659 else
Benjamin Kramer6f64dac2020-04-15 12:41:54 +02001660 Indices.push_back(Idx.getZExtValue());
Nate Begemana0110022010-06-08 00:16:34 +00001661 }
1662
Benjamin Kramer6f64dac2020-04-15 12:41:54 +02001663 return Builder.CreateShuffleVector(V1, V2, Indices, "shuffle");
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001664}
Hal Finkelc4d7c822013-09-18 03:29:45 +00001665
1666Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1667 QualType SrcType = E->getSrcExpr()->getType(),
1668 DstType = E->getType();
1669
1670 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1671
1672 SrcType = CGF.getContext().getCanonicalType(SrcType);
1673 DstType = CGF.getContext().getCanonicalType(DstType);
1674 if (SrcType == DstType) return Src;
1675
1676 assert(SrcType->isVectorType() &&
1677 "ConvertVector source type must be a vector");
1678 assert(DstType->isVectorType() &&
1679 "ConvertVector destination type must be a vector");
1680
1681 llvm::Type *SrcTy = Src->getType();
1682 llvm::Type *DstTy = ConvertType(DstType);
1683
1684 // Ignore conversions like int -> uint.
1685 if (SrcTy == DstTy)
1686 return Src;
1687
Simon Pilgrime0712012019-10-02 15:31:25 +00001688 QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
1689 DstEltType = DstType->castAs<VectorType>()->getElementType();
Hal Finkelc4d7c822013-09-18 03:29:45 +00001690
1691 assert(SrcTy->isVectorTy() &&
1692 "ConvertVector source IR type must be a vector");
1693 assert(DstTy->isVectorTy() &&
1694 "ConvertVector destination IR type must be a vector");
1695
Christopher Tetreaultf22fbe32020-04-13 12:30:53 -07001696 llvm::Type *SrcEltTy = cast<llvm::VectorType>(SrcTy)->getElementType(),
1697 *DstEltTy = cast<llvm::VectorType>(DstTy)->getElementType();
Hal Finkelc4d7c822013-09-18 03:29:45 +00001698
1699 if (DstEltType->isBooleanType()) {
1700 assert((SrcEltTy->isFloatingPointTy() ||
1701 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1702
1703 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1704 if (SrcEltTy->isFloatingPointTy()) {
1705 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1706 } else {
1707 return Builder.CreateICmpNE(Src, Zero, "tobool");
1708 }
1709 }
1710
1711 // We have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +00001712 Value *Res = nullptr;
Hal Finkelc4d7c822013-09-18 03:29:45 +00001713
1714 if (isa<llvm::IntegerType>(SrcEltTy)) {
1715 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1716 if (isa<llvm::IntegerType>(DstEltTy))
1717 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1718 else if (InputSigned)
1719 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1720 else
1721 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1722 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1723 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1724 if (DstEltType->isSignedIntegerOrEnumerationType())
1725 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1726 else
1727 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1728 } else {
1729 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1730 "Unknown real conversion");
1731 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1732 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1733 else
1734 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1735 }
1736
1737 return Res;
1738}
1739
Eli Friedmancb422f12009-11-26 03:22:21 +00001740Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +00001741 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
1742 CGF.EmitIgnoredExpr(E->getBase());
Volodymyr Sapsaief1899b2018-11-01 21:57:05 +00001743 return CGF.emitScalarConstant(Constant, E);
Alex Lorenz6cc83172017-08-25 10:07:00 +00001744 } else {
Fangrui Song407659a2018-11-30 23:41:18 +00001745 Expr::EvalResult Result;
1746 if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1747 llvm::APSInt Value = Result.Val.getInt();
Alex Lorenz6cc83172017-08-25 10:07:00 +00001748 CGF.EmitIgnoredExpr(E->getBase());
1749 return Builder.getInt(Value);
1750 }
Eli Friedmancb422f12009-11-26 03:22:21 +00001751 }
Devang Patel44b8bf02010-10-04 21:46:04 +00001752
Eli Friedmancb422f12009-11-26 03:22:21 +00001753 return EmitLoadOfLValue(E);
1754}
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001755
Chris Lattner2da04b32007-08-24 05:35:26 +00001756Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001757 TestAndClearIgnoreResultAssign();
1758
Chris Lattner2da04b32007-08-24 05:35:26 +00001759 // Emit subscript expressions in rvalue context's. For most cases, this just
1760 // loads the lvalue formed by the subscript expr. However, we have to be
1761 // careful, because the base of a vector subscript is occasionally an rvalue,
1762 // so we can't get it as an lvalue.
1763 if (!E->getBase()->getType()->isVectorType())
1764 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +00001765
Chris Lattner2da04b32007-08-24 05:35:26 +00001766 // Handle the vector case. The base must be a vector, the index must be an
1767 // integer value.
1768 Value *Base = Visit(E->getBase());
1769 Value *Idx = Visit(E->getIdx());
Richard Smith539e4a72013-02-23 02:53:19 +00001770 QualType IdxTy = E->getIdx()->getType();
1771
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001772 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00001773 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1774
Chris Lattner2da04b32007-08-24 05:35:26 +00001775 return Builder.CreateExtractElement(Base, Idx, "vecext");
1776}
1777
Nate Begeman19351632009-10-18 20:10:40 +00001778static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2192fe52011-07-18 04:24:23 +00001779 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman19351632009-10-18 20:10:40 +00001780 int MV = SVI->getMaskValue(Idx);
Craig Toppera97d7e72013-07-26 06:16:11 +00001781 if (MV == -1)
Nate Begeman19351632009-10-18 20:10:40 +00001782 return llvm::UndefValue::get(I32Ty);
1783 return llvm::ConstantInt::get(I32Ty, Off+MV);
1784}
1785
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001786static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1787 if (C->getBitWidth() != 32) {
1788 assert(llvm::ConstantInt::isValueValidForType(I32Ty,
1789 C->getZExtValue()) &&
1790 "Index operand too large for shufflevector mask!");
1791 return llvm::ConstantInt::get(I32Ty, C->getZExtValue());
1792 }
1793 return C;
1794}
1795
Nate Begeman19351632009-10-18 20:10:40 +00001796Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1797 bool Ignore = TestAndClearIgnoreResultAssign();
1798 (void)Ignore;
1799 assert (Ignore == false && "init list ignored");
1800 unsigned NumInitElements = E->getNumInits();
Craig Toppera97d7e72013-07-26 06:16:11 +00001801
Nate Begeman19351632009-10-18 20:10:40 +00001802 if (E->hadArrayRangeDesignator())
1803 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Craig Toppera97d7e72013-07-26 06:16:11 +00001804
Chris Lattner2192fe52011-07-18 04:24:23 +00001805 llvm::VectorType *VType =
Nate Begeman19351632009-10-18 20:10:40 +00001806 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
Craig Toppera97d7e72013-07-26 06:16:11 +00001807
Sebastian Redl12757ab2011-09-24 17:48:14 +00001808 if (!VType) {
1809 if (NumInitElements == 0) {
1810 // C++11 value-initialization for the scalar.
1811 return EmitNullValue(E->getType());
1812 }
1813 // We have a scalar in braces. Just use the first element.
Nate Begeman19351632009-10-18 20:10:40 +00001814 return Visit(E->getInit(0));
Sebastian Redl12757ab2011-09-24 17:48:14 +00001815 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001816
Nate Begeman19351632009-10-18 20:10:40 +00001817 unsigned ResElts = VType->getNumElements();
Craig Toppera97d7e72013-07-26 06:16:11 +00001818
1819 // Loop over initializers collecting the Value for each, and remembering
Nate Begeman19351632009-10-18 20:10:40 +00001820 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1821 // us to fold the shuffle for the swizzle into the shuffle for the vector
1822 // initializer, since LLVM optimizers generally do not want to touch
1823 // shuffles.
1824 unsigned CurIdx = 0;
1825 bool VIsUndefShuffle = false;
1826 llvm::Value *V = llvm::UndefValue::get(VType);
1827 for (unsigned i = 0; i != NumInitElements; ++i) {
1828 Expr *IE = E->getInit(i);
1829 Value *Init = Visit(IE);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001830 SmallVector<llvm::Constant*, 16> Args;
Craig Toppera97d7e72013-07-26 06:16:11 +00001831
Chris Lattner2192fe52011-07-18 04:24:23 +00001832 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001833
Nate Begeman19351632009-10-18 20:10:40 +00001834 // Handle scalar elements. If the scalar initializer is actually one
Craig Toppera97d7e72013-07-26 06:16:11 +00001835 // element of a different vector of the same width, use shuffle instead of
Nate Begeman19351632009-10-18 20:10:40 +00001836 // extract+insert.
1837 if (!VVT) {
1838 if (isa<ExtVectorElementExpr>(IE)) {
1839 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1840
1841 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1842 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
Craig Topper8a13c412014-05-21 05:09:00 +00001843 Value *LHS = nullptr, *RHS = nullptr;
Nate Begeman19351632009-10-18 20:10:40 +00001844 if (CurIdx == 0) {
1845 // insert into undef -> shuffle (src, undef)
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001846 // shufflemask must use an i32
1847 Args.push_back(getAsInt32(C, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001848 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001849
1850 LHS = EI->getVectorOperand();
1851 RHS = V;
1852 VIsUndefShuffle = true;
1853 } else if (VIsUndefShuffle) {
1854 // insert into undefshuffle && size match -> shuffle (v, src)
1855 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1856 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001857 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner2531eb42011-04-19 22:55:03 +00001858 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001859 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1860
Nate Begeman19351632009-10-18 20:10:40 +00001861 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1862 RHS = EI->getVectorOperand();
1863 VIsUndefShuffle = false;
1864 }
1865 if (!Args.empty()) {
Chris Lattner91c08ad2011-02-15 00:14:06 +00001866 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001867 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1868 ++CurIdx;
1869 continue;
1870 }
1871 }
1872 }
Chris Lattner2531eb42011-04-19 22:55:03 +00001873 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1874 "vecinit");
Nate Begeman19351632009-10-18 20:10:40 +00001875 VIsUndefShuffle = false;
1876 ++CurIdx;
1877 continue;
1878 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001879
Nate Begeman19351632009-10-18 20:10:40 +00001880 unsigned InitElts = VVT->getNumElements();
1881
Craig Toppera97d7e72013-07-26 06:16:11 +00001882 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
Nate Begeman19351632009-10-18 20:10:40 +00001883 // input is the same width as the vector being constructed, generate an
1884 // optimized shuffle of the swizzle input into the result.
Nate Begemanb8326be2009-10-25 02:26:01 +00001885 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman19351632009-10-18 20:10:40 +00001886 if (isa<ExtVectorElementExpr>(IE)) {
1887 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1888 Value *SVOp = SVI->getOperand(0);
Chris Lattner2192fe52011-07-18 04:24:23 +00001889 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001890
Nate Begeman19351632009-10-18 20:10:40 +00001891 if (OpTy->getNumElements() == ResElts) {
Nate Begeman19351632009-10-18 20:10:40 +00001892 for (unsigned j = 0; j != CurIdx; ++j) {
1893 // If the current vector initializer is a shuffle with undef, merge
1894 // this shuffle directly into it.
1895 if (VIsUndefShuffle) {
1896 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner5e016ae2010-06-27 07:15:29 +00001897 CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001898 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00001899 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001900 }
1901 }
1902 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001903 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001904 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001905
1906 if (VIsUndefShuffle)
1907 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1908
1909 Init = SVOp;
1910 }
1911 }
1912
1913 // Extend init to result vector length, and then shuffle its contribution
1914 // to the vector initializer into V.
1915 if (Args.empty()) {
1916 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001917 Args.push_back(Builder.getInt32(j));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001918 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001919 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001920 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemanb8326be2009-10-25 02:26:01 +00001921 Mask, "vext");
Nate Begeman19351632009-10-18 20:10:40 +00001922
1923 Args.clear();
1924 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001925 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001926 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001927 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001928 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001929 }
1930
1931 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1932 // merging subsequent shuffles into this one.
1933 if (CurIdx == 0)
1934 std::swap(V, Init);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001935 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001936 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1937 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1938 CurIdx += InitElts;
1939 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001940
Nate Begeman19351632009-10-18 20:10:40 +00001941 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1942 // Emit remaining default initializers.
Chris Lattner2192fe52011-07-18 04:24:23 +00001943 llvm::Type *EltTy = VType->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00001944
Nate Begeman19351632009-10-18 20:10:40 +00001945 // Emit remaining default initializers
1946 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner2531eb42011-04-19 22:55:03 +00001947 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman19351632009-10-18 20:10:40 +00001948 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1949 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1950 }
1951 return V;
1952}
1953
John McCall7f416cc2015-09-08 08:05:57 +00001954bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001955 const Expr *E = CE->getSubExpr();
John McCalld9c7c6562010-03-30 23:58:03 +00001956
John McCalle3027922010-08-25 11:45:40 +00001957 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCalld9c7c6562010-03-30 23:58:03 +00001958 return false;
Craig Toppera97d7e72013-07-26 06:16:11 +00001959
John McCall7f416cc2015-09-08 08:05:57 +00001960 if (isa<CXXThisExpr>(E->IgnoreParens())) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001961 // We always assume that 'this' is never null.
1962 return false;
1963 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001964
Anders Carlsson8c793172009-11-23 17:57:54 +00001965 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001966 // And that glvalue casts are never null.
John McCall2536c6d2010-08-25 10:28:54 +00001967 if (ICE->getValueKind() != VK_RValue)
Anders Carlsson8c793172009-11-23 17:57:54 +00001968 return false;
1969 }
1970
1971 return true;
1972}
1973
Chris Lattner2da04b32007-08-24 05:35:26 +00001974// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1975// have to handle a more broad range of conversions than explicit casts, as they
1976// handle things like function to ptr-to-function decay etc.
John McCall23c29fe2011-06-24 21:55:10 +00001977Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001978 Expr *E = CE->getSubExpr();
Anders Carlsson8c978b42009-09-22 22:00:46 +00001979 QualType DestTy = CE->getType();
John McCalle3027922010-08-25 11:45:40 +00001980 CastKind Kind = CE->getCastKind();
Craig Toppera97d7e72013-07-26 06:16:11 +00001981
John McCalle399e5b2016-01-27 18:32:30 +00001982 // These cases are generally not written to ignore the result of
1983 // evaluating their sub-expressions, so we clear this now.
1984 bool Ignored = TestAndClearIgnoreResultAssign();
Mike Stump4a3999f2009-09-09 13:00:44 +00001985
Eli Friedman0dfc6802009-11-27 02:07:44 +00001986 // Since almost all cast kinds apply to scalars, this switch doesn't have
1987 // a default case, so the compiler will warn on a missing case. The cases
1988 // are in the same order as in the CastKind enum.
Anders Carlsson3df53bc2009-08-24 18:26:39 +00001989 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +00001990 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00001991 case CK_BuiltinFnToFnPtr:
1992 llvm_unreachable("builtin functions are handled elsewhere");
1993
Craig Toppera97d7e72013-07-26 06:16:11 +00001994 case CK_LValueBitCast:
John McCalle3027922010-08-25 11:45:40 +00001995 case CK_ObjCObjectLValueCast: {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001996 Address Addr = EmitLValue(E).getAddress(CGF);
Alexey Bataevf2440332015-10-07 10:22:08 +00001997 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
John McCall7f416cc2015-09-08 08:05:57 +00001998 LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
1999 return EmitLoadOfLValue(LV, CE->getExprLoc());
Douglas Gregor51954272010-07-13 23:17:26 +00002000 }
John McCallcd78e802011-09-10 01:16:55 +00002001
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00002002 case CK_LValueToRValueBitCast: {
2003 LValue SourceLVal = CGF.EmitLValue(E);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002004 Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(CGF),
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00002005 CGF.ConvertTypeForMem(DestTy));
2006 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
2007 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2008 return EmitLoadOfLValue(DestLV, CE->getExprLoc());
2009 }
2010
John McCall9320b872011-09-09 05:25:32 +00002011 case CK_CPointerToObjCPointerCast:
2012 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002013 case CK_AnyPointerToBlockPointerCast:
2014 case CK_BitCast: {
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00002015 Value *Src = Visit(const_cast<Expr*>(E));
David Tweede1468322013-12-11 13:39:46 +00002016 llvm::Type *SrcTy = Src->getType();
2017 llvm::Type *DstTy = ConvertType(DestTy);
Bob Wilson95a27b02014-02-17 19:20:59 +00002018 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
David Tweede1468322013-12-11 13:39:46 +00002019 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00002020 llvm_unreachable("wrong cast for pointers in different address spaces"
2021 "(must be an address space cast)!");
David Tweede1468322013-12-11 13:39:46 +00002022 }
Peter Collingbourned2926c92015-03-14 02:42:25 +00002023
2024 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
2025 if (auto PT = DestTy->getAs<PointerType>())
2026 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002027 /*MayBeNull=*/true,
2028 CodeGenFunction::CFITCK_UnrelatedCast,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002029 CE->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00002030 }
2031
Piotr Padlewski07058292018-07-02 19:21:36 +00002032 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2033 const QualType SrcType = E->getType();
2034
2035 if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
2036 // Casting to pointer that could carry dynamic information (provided by
2037 // invariant.group) requires launder.
2038 Src = Builder.CreateLaunderInvariantGroup(Src);
2039 } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
2040 // Casting to pointer that does not carry dynamic information (provided
2041 // by invariant.group) requires stripping it. Note that we don't do it
2042 // if the source could not be dynamic type and destination could be
2043 // dynamic because dynamic information is already laundered. It is
2044 // because launder(strip(src)) == launder(src), so there is no need to
2045 // add extra strip before launder.
2046 Src = Builder.CreateStripInvariantGroup(Src);
2047 }
2048 }
2049
Amy Huang301a5bb2019-05-02 20:07:35 +00002050 // Update heapallocsite metadata when there is an explicit cast.
2051 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(Src))
2052 if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE))
2053 CGF.getDebugInfo()->
2054 addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc());
2055
David Tweede1468322013-12-11 13:39:46 +00002056 return Builder.CreateBitCast(Src, DstTy);
2057 }
2058 case CK_AddressSpaceConversion: {
Yaxun Liu402804b2016-12-15 08:09:08 +00002059 Expr::EvalResult Result;
2060 if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
2061 Result.Val.isNullPointer()) {
2062 // If E has side effect, it is emitted even if its final result is a
2063 // null pointer. In that case, a DCE pass should be able to
2064 // eliminate the useless instructions emitted during translating E.
2065 if (Result.HasSideEffects)
2066 Visit(E);
2067 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
2068 ConvertType(DestTy)), DestTy);
2069 }
Yaxun Liub7b6d0f2016-04-12 19:03:49 +00002070 // Since target may map different address spaces in AST to the same address
2071 // space, an address space conversion may end up as a bitcast.
Yaxun Liu6d96f1632017-05-18 18:51:09 +00002072 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
2073 CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
2074 DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00002075 }
David Chisnallfa35df62012-01-16 17:27:18 +00002076 case CK_AtomicToNonAtomic:
2077 case CK_NonAtomicToAtomic:
John McCalle3027922010-08-25 11:45:40 +00002078 case CK_NoOp:
2079 case CK_UserDefinedConversion:
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002080 return Visit(const_cast<Expr*>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00002081
John McCalle3027922010-08-25 11:45:40 +00002082 case CK_BaseToDerived: {
Jordan Rose7bb26112012-10-03 01:08:28 +00002083 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2084 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2085
John McCall7f416cc2015-09-08 08:05:57 +00002086 Address Base = CGF.EmitPointerWithAlignment(E);
2087 Address Derived =
2088 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00002089 CE->path_begin(), CE->path_end(),
John McCall7f416cc2015-09-08 08:05:57 +00002090 CGF.ShouldNullCheckClassCastValue(CE));
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00002091
Richard Smith2c5868c2013-02-13 21:18:23 +00002092 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2093 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00002094 if (CGF.sanitizePerformTypeCheck())
Richard Smith2c5868c2013-02-13 21:18:23 +00002095 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00002096 Derived.getPointer(), DestTy->getPointeeType());
Richard Smith2c5868c2013-02-13 21:18:23 +00002097
Peter Collingbourned2926c92015-03-14 02:42:25 +00002098 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002099 CGF.EmitVTablePtrCheckForCast(
2100 DestTy->getPointeeType(), Derived.getPointer(),
2101 /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
2102 CE->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00002103
John McCall7f416cc2015-09-08 08:05:57 +00002104 return Derived.getPointer();
Anders Carlsson8c793172009-11-23 17:57:54 +00002105 }
John McCalle3027922010-08-25 11:45:40 +00002106 case CK_UncheckedDerivedToBase:
2107 case CK_DerivedToBase: {
John McCall7f416cc2015-09-08 08:05:57 +00002108 // The EmitPointerWithAlignment path does this fine; just discard
2109 // the alignment.
2110 return CGF.EmitPointerWithAlignment(CE).getPointer();
Anders Carlsson12f5a252009-09-12 04:57:16 +00002111 }
John McCall7f416cc2015-09-08 08:05:57 +00002112
Anders Carlsson8a01a752011-04-11 02:03:26 +00002113 case CK_Dynamic: {
John McCall7f416cc2015-09-08 08:05:57 +00002114 Address V = CGF.EmitPointerWithAlignment(E);
Eli Friedman0dfc6802009-11-27 02:07:44 +00002115 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
2116 return CGF.EmitDynamicCast(V, DCE);
2117 }
Eli Friedmane96f1d32009-11-27 04:41:50 +00002118
John McCall7f416cc2015-09-08 08:05:57 +00002119 case CK_ArrayToPointerDecay:
2120 return CGF.EmitArrayToPointerDecay(E).getPointer();
John McCalle3027922010-08-25 11:45:40 +00002121 case CK_FunctionToPointerDecay:
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002122 return EmitLValue(E).getPointer(CGF);
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002123
John McCalle84af4e2010-11-13 01:35:44 +00002124 case CK_NullToPointer:
2125 if (MustVisitNullValue(E))
Richard Smith27252a12019-06-14 17:46:38 +00002126 CGF.EmitIgnoredExpr(E);
John McCalle84af4e2010-11-13 01:35:44 +00002127
Yaxun Liu402804b2016-12-15 08:09:08 +00002128 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
2129 DestTy);
John McCalle84af4e2010-11-13 01:35:44 +00002130
John McCalle3027922010-08-25 11:45:40 +00002131 case CK_NullToMemberPointer: {
John McCalle84af4e2010-11-13 01:35:44 +00002132 if (MustVisitNullValue(E))
Richard Smith27252a12019-06-14 17:46:38 +00002133 CGF.EmitIgnoredExpr(E);
John McCalla1dee5302010-08-22 10:59:02 +00002134
John McCall7a9aac22010-08-23 01:21:21 +00002135 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2136 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2137 }
Anders Carlsson12f5a252009-09-12 04:57:16 +00002138
John McCallc62bb392012-02-15 01:22:51 +00002139 case CK_ReinterpretMemberPointer:
John McCalle3027922010-08-25 11:45:40 +00002140 case CK_BaseToDerivedMemberPointer:
2141 case CK_DerivedToBaseMemberPointer: {
Eli Friedmane96f1d32009-11-27 04:41:50 +00002142 Value *Src = Visit(E);
Craig Toppera97d7e72013-07-26 06:16:11 +00002143
John McCalla1dee5302010-08-22 10:59:02 +00002144 // Note that the AST doesn't distinguish between checked and
2145 // unchecked member pointer conversions, so we always have to
2146 // implement checked conversions here. This is inefficient when
2147 // actual control flow may be required in order to perform the
2148 // check, which it is for data member pointers (but not member
2149 // function pointers on Itanium and ARM).
John McCall7a9aac22010-08-23 01:21:21 +00002150 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmane96f1d32009-11-27 04:41:50 +00002151 }
John McCall31168b02011-06-15 23:02:42 +00002152
John McCall2d637d22011-09-10 06:18:15 +00002153 case CK_ARCProduceObject:
John McCall31168b02011-06-15 23:02:42 +00002154 return CGF.EmitARCRetainScalarExpr(E);
John McCall2d637d22011-09-10 06:18:15 +00002155 case CK_ARCConsumeObject:
John McCall31168b02011-06-15 23:02:42 +00002156 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCalle399e5b2016-01-27 18:32:30 +00002157 case CK_ARCReclaimReturnedObject:
2158 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
John McCallff613032011-10-04 06:23:45 +00002159 case CK_ARCExtendBlockObject:
2160 return CGF.EmitARCExtendBlockObject(E);
John McCall31168b02011-06-15 23:02:42 +00002161
Douglas Gregored90df32012-02-22 05:02:47 +00002162 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmanec75fec2012-02-28 01:08:45 +00002163 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00002164
John McCallc5e62b42010-11-13 09:02:35 +00002165 case CK_FloatingRealToComplex:
2166 case CK_FloatingComplexCast:
2167 case CK_IntegralRealToComplex:
2168 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002169 case CK_IntegralComplexToFloatingComplex:
2170 case CK_FloatingComplexToIntegralComplex:
John McCalle3027922010-08-25 11:45:40 +00002171 case CK_ConstructorConversion:
John McCall3eba6e62010-11-16 06:21:14 +00002172 case CK_ToUnion:
2173 llvm_unreachable("scalar cast to non-scalar value");
John McCall34376a62010-12-04 03:47:34 +00002174
John McCallf3735e02010-12-01 04:43:34 +00002175 case CK_LValueToRValue:
2176 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCall34376a62010-12-04 03:47:34 +00002177 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCallf3735e02010-12-01 04:43:34 +00002178 return Visit(const_cast<Expr*>(E));
Eli Friedman0dfc6802009-11-27 02:07:44 +00002179
John McCalle3027922010-08-25 11:45:40 +00002180 case CK_IntegralToPointer: {
Anders Carlsson7cd39e02009-09-15 04:48:33 +00002181 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002182
Anders Carlsson094c4592009-10-18 18:12:03 +00002183 // First, convert to the correct width so that we control the kind of
2184 // extension.
Yaxun Liu26f75662016-08-19 05:17:25 +00002185 auto DestLLVMTy = ConvertType(DestTy);
2186 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002187 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson094c4592009-10-18 18:12:03 +00002188 llvm::Value* IntResult =
2189 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002190
Piotr Padlewski07058292018-07-02 19:21:36 +00002191 auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002192
Piotr Padlewski07058292018-07-02 19:21:36 +00002193 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2194 // Going from integer to pointer that could be dynamic requires reloading
2195 // dynamic information from invariant.group.
2196 if (DestTy.mayBeDynamicClass())
2197 IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
2198 }
2199 return IntToPtr;
2200 }
2201 case CK_PointerToIntegral: {
2202 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
2203 auto *PtrExpr = Visit(E);
2204
2205 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2206 const QualType SrcType = E->getType();
2207
2208 // Casting to integer requires stripping dynamic information as it does
2209 // not carries it.
2210 if (SrcType.mayBeDynamicClass())
2211 PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
2212 }
2213
2214 return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
2215 }
John McCalle3027922010-08-25 11:45:40 +00002216 case CK_ToVoid: {
John McCalla2342eb2010-12-05 02:00:02 +00002217 CGF.EmitIgnoredExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002218 return nullptr;
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002219 }
John McCalle3027922010-08-25 11:45:40 +00002220 case CK_VectorSplat: {
Chris Lattner2192fe52011-07-18 04:24:23 +00002221 llvm::Type *DstTy = ConvertType(DestTy);
George Burgess IVdf1ed002016-01-13 01:52:39 +00002222 Value *Elt = Visit(const_cast<Expr*>(E));
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002223 // Splat the element across to all elements
Christopher Tetreaultf22fbe32020-04-13 12:30:53 -07002224 unsigned NumElements = cast<llvm::VectorType>(DstTy)->getNumElements();
Alp Toker5f072d82014-04-19 23:55:49 +00002225 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002226 }
John McCall8cb679e2010-11-15 09:13:47 +00002227
Leonard Chan99bda372018-10-15 16:07:02 +00002228 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +00002229 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2230 CE->getExprLoc());
2231
2232 case CK_FixedPointToBoolean:
2233 assert(E->getType()->isFixedPointType() &&
2234 "Expected src type to be fixed point type");
2235 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
2236 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2237 CE->getExprLoc());
Leonard Chan99bda372018-10-15 16:07:02 +00002238
Leonard Chan8f7caae2019-03-06 00:28:43 +00002239 case CK_FixedPointToIntegral:
2240 assert(E->getType()->isFixedPointType() &&
2241 "Expected src type to be fixed point type");
2242 assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
2243 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2244 CE->getExprLoc());
2245
2246 case CK_IntegralToFixedPoint:
2247 assert(E->getType()->isIntegerType() &&
2248 "Expected src type to be an integer");
2249 assert(DestTy->isFixedPointType() &&
2250 "Expected dest type to be fixed point type");
2251 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2252 CE->getExprLoc());
2253
Roman Lebedevb69ba222018-07-30 18:58:30 +00002254 case CK_IntegralCast: {
2255 ScalarConversionOpts Opts;
Roman Lebedev62debd802018-10-30 21:58:56 +00002256 if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Roman Lebedevd677c3f2018-11-19 19:56:43 +00002257 if (!ICE->isPartOfExplicitCast())
2258 Opts = ScalarConversionOpts(CGF.SanOpts);
Roman Lebedevb69ba222018-07-30 18:58:30 +00002259 }
2260 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2261 CE->getExprLoc(), Opts);
2262 }
John McCalle3027922010-08-25 11:45:40 +00002263 case CK_IntegralToFloating:
2264 case CK_FloatingToIntegral:
2265 case CK_FloatingCast:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002266 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2267 CE->getExprLoc());
Roman Lebedevb69ba222018-07-30 18:58:30 +00002268 case CK_BooleanToSignedIntegral: {
2269 ScalarConversionOpts Opts;
2270 Opts.TreatBooleanAsSigned = true;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002271 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
Roman Lebedevb69ba222018-07-30 18:58:30 +00002272 CE->getExprLoc(), Opts);
2273 }
John McCall8cb679e2010-11-15 09:13:47 +00002274 case CK_IntegralToBoolean:
2275 return EmitIntToBoolConversion(Visit(E));
2276 case CK_PointerToBoolean:
Yaxun Liu402804b2016-12-15 08:09:08 +00002277 return EmitPointerToBoolConversion(Visit(E), E->getType());
John McCall8cb679e2010-11-15 09:13:47 +00002278 case CK_FloatingToBoolean:
2279 return EmitFloatToBoolConversion(Visit(E));
John McCalle3027922010-08-25 11:45:40 +00002280 case CK_MemberPointerToBoolean: {
John McCall7a9aac22010-08-23 01:21:21 +00002281 llvm::Value *MemPtr = Visit(E);
2282 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
2283 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlsson3df53bc2009-08-24 18:26:39 +00002284 }
John McCalld7646252010-11-14 08:17:51 +00002285
2286 case CK_FloatingComplexToReal:
2287 case CK_IntegralComplexToReal:
John McCall07bb1962010-11-16 10:08:07 +00002288 return CGF.EmitComplexExpr(E, false, true).first;
John McCalld7646252010-11-14 08:17:51 +00002289
2290 case CK_FloatingComplexToBoolean:
2291 case CK_IntegralComplexToBoolean: {
John McCall07bb1962010-11-16 10:08:07 +00002292 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCalld7646252010-11-14 08:17:51 +00002293
2294 // TODO: kill this function off, inline appropriate case here
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002295 return EmitComplexToScalarConversion(V, E->getType(), DestTy,
2296 CE->getExprLoc());
John McCalld7646252010-11-14 08:17:51 +00002297 }
2298
Andrew Savonichevb555b762018-10-23 15:19:20 +00002299 case CK_ZeroToOCLOpaqueType: {
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002300 assert((DestTy->isEventT() || DestTy->isQueueT() ||
2301 DestTy->isOCLIntelSubgroupAVCType()) &&
Andrew Savonichevb555b762018-10-23 15:19:20 +00002302 "CK_ZeroToOCLEvent cast on non-event type");
Egor Churaev89831422016-12-23 14:55:49 +00002303 return llvm::Constant::getNullValue(ConvertType(DestTy));
2304 }
2305
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002306 case CK_IntToOCLSampler:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002307 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002308
2309 } // end of switch
Mike Stump4a3999f2009-09-09 13:00:44 +00002310
John McCall3eba6e62010-11-16 06:21:14 +00002311 llvm_unreachable("unknown scalar cast");
Chris Lattner2da04b32007-08-24 05:35:26 +00002312}
2313
Chris Lattner04a913b2007-08-31 22:09:40 +00002314Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +00002315 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002316 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
2317 !E->getType()->isVoidType());
2318 if (!RetAlloca.isValid())
Craig Topper8a13c412014-05-21 05:09:00 +00002319 return nullptr;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002320 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
2321 E->getExprLoc());
Chris Lattner04a913b2007-08-31 22:09:40 +00002322}
2323
Reid Kleckner092d0652017-03-06 22:18:34 +00002324Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
2325 CGF.enterFullExpression(E);
2326 CodeGenFunction::RunCleanupsScope Scope(CGF);
2327 Value *V = Visit(E->getSubExpr());
2328 // Defend against dominance problems caused by jumps out of expression
2329 // evaluation through the shared cleanup block.
2330 Scope.ForceCleanup({&V});
2331 return V;
2332}
2333
Chris Lattner2da04b32007-08-24 05:35:26 +00002334//===----------------------------------------------------------------------===//
2335// Unary Operators
2336//===----------------------------------------------------------------------===//
2337
Alexey Samsonovf6246502015-04-23 01:50:45 +00002338static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
2339 llvm::Value *InVal, bool IsInc) {
2340 BinOpInfo BinOp;
2341 BinOp.LHS = InVal;
2342 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
2343 BinOp.Ty = E->getType();
2344 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
Adam Nemet484aa452017-03-27 19:17:25 +00002345 // FIXME: once UnaryOperator carries FPFeatures, copy it here.
Alexey Samsonovf6246502015-04-23 01:50:45 +00002346 BinOp.E = E;
2347 return BinOp;
2348}
2349
2350llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
2351 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
2352 llvm::Value *Amount =
2353 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
2354 StringRef Name = IsInc ? "inc" : "dec";
Richard Smith9c6890a2012-11-01 22:30:59 +00002355 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00002356 case LangOptions::SOB_Defined:
Alexey Samsonovf6246502015-04-23 01:50:45 +00002357 return Builder.CreateAdd(InVal, Amount, Name);
Richard Smith3e056de2012-08-25 00:32:28 +00002358 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002359 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002360 return Builder.CreateNSWAdd(InVal, Amount, Name);
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00002361 LLVM_FALLTHROUGH;
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002362 case LangOptions::SOB_Trapping:
2363 if (!E->canOverflow())
2364 return Builder.CreateNSWAdd(InVal, Amount, Name);
2365 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc));
2366 }
David Blaikie83d382b2011-09-23 05:06:16 +00002367 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev85129b82011-02-07 02:17:30 +00002368}
2369
Alexey Bataev7b518dc2020-01-06 16:14:34 -05002370namespace {
2371/// Handles check and update for lastprivate conditional variables.
2372class OMPLastprivateConditionalUpdateRAII {
2373private:
2374 CodeGenFunction &CGF;
2375 const UnaryOperator *E;
2376
2377public:
2378 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
2379 const UnaryOperator *E)
2380 : CGF(CGF), E(E) {}
2381 ~OMPLastprivateConditionalUpdateRAII() {
2382 if (CGF.getLangOpts().OpenMP)
2383 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
2384 CGF, E->getSubExpr());
2385 }
2386};
2387} // namespace
2388
John McCalle3dc1702011-02-15 09:22:45 +00002389llvm::Value *
2390ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2391 bool isInc, bool isPre) {
Alexey Bataev7b518dc2020-01-06 16:14:34 -05002392 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
John McCalle3dc1702011-02-15 09:22:45 +00002393 QualType type = E->getSubExpr()->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00002394 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00002395 llvm::Value *value;
2396 llvm::Value *input;
Anton Yartsev85129b82011-02-07 02:17:30 +00002397
John McCalle3dc1702011-02-15 09:22:45 +00002398 int amount = (isInc ? 1 : -1);
Vedant Kumar175b6d12017-07-13 20:55:26 +00002399 bool isSubtraction = !isInc;
John McCalle3dc1702011-02-15 09:22:45 +00002400
David Chisnallfa35df62012-01-16 17:27:18 +00002401 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
David Chisnallef78c302013-03-03 16:02:42 +00002402 type = atomicTy->getValueType();
2403 if (isInc && type->isBooleanType()) {
2404 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
2405 if (isPre) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002406 Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified())
2407 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002408 return Builder.getTrue();
2409 }
2410 // For atomic bool increment, we just store true and return it for
2411 // preincrement, do an atomic swap with true for postincrement
JF Bastien92f4ef12016-04-06 17:26:42 +00002412 return Builder.CreateAtomicRMW(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002413 llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True,
JF Bastien92f4ef12016-04-06 17:26:42 +00002414 llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002415 }
2416 // Special case for atomic increment / decrement on integers, emit
2417 // atomicrmw instructions. We skip this if we want to be doing overflow
Craig Toppera97d7e72013-07-26 06:16:11 +00002418 // checking, and fall into the slow path with the atomic cmpxchg loop.
David Chisnallef78c302013-03-03 16:02:42 +00002419 if (!type->isBooleanType() && type->isIntegerType() &&
2420 !(type->isUnsignedIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002421 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
David Chisnallef78c302013-03-03 16:02:42 +00002422 CGF.getLangOpts().getSignedOverflowBehavior() !=
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002423 LangOptions::SOB_Trapping) {
David Chisnallef78c302013-03-03 16:02:42 +00002424 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
2425 llvm::AtomicRMWInst::Sub;
2426 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
2427 llvm::Instruction::Sub;
2428 llvm::Value *amt = CGF.EmitToMemory(
2429 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002430 llvm::Value *old =
2431 Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt,
2432 llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002433 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
2434 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00002435 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002436 input = value;
2437 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
David Chisnallfa35df62012-01-16 17:27:18 +00002438 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2439 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
David Chisnallef78c302013-03-03 16:02:42 +00002440 value = CGF.EmitToMemory(value, type);
David Chisnallfa35df62012-01-16 17:27:18 +00002441 Builder.CreateBr(opBB);
2442 Builder.SetInsertPoint(opBB);
2443 atomicPHI = Builder.CreatePHI(value->getType(), 2);
2444 atomicPHI->addIncoming(value, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002445 value = atomicPHI;
David Chisnallef78c302013-03-03 16:02:42 +00002446 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002447 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002448 input = value;
David Chisnallfa35df62012-01-16 17:27:18 +00002449 }
2450
John McCalle3dc1702011-02-15 09:22:45 +00002451 // Special case of integer increment that we have to check first: bool++.
2452 // Due to promotion rules, we get:
2453 // bool++ -> bool = bool + 1
2454 // -> bool = (int)bool + 1
2455 // -> bool = ((int)bool + 1 != 0)
2456 // An interesting aspect of this is that increment is always true.
2457 // Decrement does not have this property.
2458 if (isInc && type->isBooleanType()) {
2459 value = Builder.getTrue();
2460
2461 // Most common case by far: integer increment.
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002462 } else if (type->isIntegerType()) {
Roman Lebedevb98a0c72019-11-27 17:07:06 +03002463 QualType promotedType;
2464 bool canPerformLossyDemotionCheck = false;
2465 if (type->isPromotableIntegerType()) {
2466 promotedType = CGF.getContext().getPromotedIntegerType(type);
2467 assert(promotedType != type && "Shouldn't promote to the same type.");
2468 canPerformLossyDemotionCheck = true;
2469 canPerformLossyDemotionCheck &=
2470 CGF.getContext().getCanonicalType(type) !=
2471 CGF.getContext().getCanonicalType(promotedType);
2472 canPerformLossyDemotionCheck &=
2473 PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
2474 type, promotedType);
2475 assert((!canPerformLossyDemotionCheck ||
2476 type->isSignedIntegerOrEnumerationType() ||
2477 promotedType->isSignedIntegerOrEnumerationType() ||
2478 ConvertType(type)->getScalarSizeInBits() ==
2479 ConvertType(promotedType)->getScalarSizeInBits()) &&
2480 "The following check expects that if we do promotion to different "
2481 "underlying canonical type, at least one of the types (either "
2482 "base or promoted) will be signed, or the bitwidths will match.");
2483 }
2484 if (CGF.SanOpts.hasOneOf(
2485 SanitizerKind::ImplicitIntegerArithmeticValueChange) &&
2486 canPerformLossyDemotionCheck) {
2487 // While `x += 1` (for `x` with width less than int) is modeled as
2488 // promotion+arithmetics+demotion, and we can catch lossy demotion with
2489 // ease; inc/dec with width less than int can't overflow because of
2490 // promotion rules, so we omit promotion+demotion, which means that we can
2491 // not catch lossy "demotion". Because we still want to catch these cases
2492 // when the sanitizer is enabled, we perform the promotion, then perform
2493 // the increment/decrement in the wider type, and finally
2494 // perform the demotion. This will catch lossy demotions.
2495
2496 value = EmitScalarConversion(value, type, promotedType, E->getExprLoc());
2497 Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2498 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2499 // Do pass non-default ScalarConversionOpts so that sanitizer check is
2500 // emitted.
2501 value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(),
2502 ScalarConversionOpts(CGF.SanOpts));
2503
2504 // Note that signed integer inc/dec with width less than int can't
2505 // overflow because of promotion rules; we're just eliding a few steps
2506 // here.
2507 } else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002508 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
2509 } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
2510 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
2511 value =
2512 EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc));
Alexey Samsonovf6246502015-04-23 01:50:45 +00002513 } else {
2514 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCalle3dc1702011-02-15 09:22:45 +00002515 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
Alexey Samsonovf6246502015-04-23 01:50:45 +00002516 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002517
John McCalle3dc1702011-02-15 09:22:45 +00002518 // Next most common: pointer increment.
2519 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
2520 QualType type = ptr->getPointeeType();
2521
2522 // VLA types don't have constant size.
John McCall77527a82011-06-25 01:32:37 +00002523 if (const VariableArrayType *vla
2524 = CGF.getContext().getAsVariableArrayType(type)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +00002525 llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
John McCall23c29fe2011-06-24 21:55:10 +00002526 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Richard Smith9c6890a2012-11-01 22:30:59 +00002527 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall23c29fe2011-06-24 21:55:10 +00002528 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2e72da942011-03-01 00:03:48 +00002529 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002530 value = CGF.EmitCheckedInBoundsGEP(
2531 value, numElts, /*SignedIndices=*/false, isSubtraction,
2532 E->getExprLoc(), "vla.inc");
Craig Toppera97d7e72013-07-26 06:16:11 +00002533
John McCalle3dc1702011-02-15 09:22:45 +00002534 // Arithmetic on function pointers (!) is just +-1.
2535 } else if (type->isFunctionType()) {
Chris Lattner2531eb42011-04-19 22:55:03 +00002536 llvm::Value *amt = Builder.getInt32(amount);
John McCalle3dc1702011-02-15 09:22:45 +00002537
2538 value = CGF.EmitCastToVoidPtr(value);
Richard Smith9c6890a2012-11-01 22:30:59 +00002539 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002540 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
2541 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002542 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2543 isSubtraction, E->getExprLoc(),
2544 "incdec.funcptr");
John McCalle3dc1702011-02-15 09:22:45 +00002545 value = Builder.CreateBitCast(value, input->getType());
2546
2547 // For everything else, we can just do a simple increment.
Anton Yartsev85129b82011-02-07 02:17:30 +00002548 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00002549 llvm::Value *amt = Builder.getInt32(amount);
Richard Smith9c6890a2012-11-01 22:30:59 +00002550 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002551 value = Builder.CreateGEP(value, amt, "incdec.ptr");
2552 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002553 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2554 isSubtraction, E->getExprLoc(),
2555 "incdec.ptr");
John McCalle3dc1702011-02-15 09:22:45 +00002556 }
2557
2558 // Vector increment/decrement.
2559 } else if (type->isVectorType()) {
2560 if (type->hasIntegerRepresentation()) {
2561 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
2562
Eli Friedman409943e2011-05-06 18:04:18 +00002563 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCalle3dc1702011-02-15 09:22:45 +00002564 } else {
2565 value = Builder.CreateFAdd(
2566 value,
2567 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev85129b82011-02-07 02:17:30 +00002568 isInc ? "inc" : "dec");
2569 }
Anton Yartsev85129b82011-02-07 02:17:30 +00002570
John McCalle3dc1702011-02-15 09:22:45 +00002571 // Floating point.
2572 } else if (type->isRealFloatingType()) {
Chris Lattner05dc78c2010-06-26 22:09:34 +00002573 // Add the inc/dec to the real part.
John McCalle3dc1702011-02-15 09:22:45 +00002574 llvm::Value *amt;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002575
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002576 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002577 // Another special case: half FP increment should be done via float
Akira Hatanaka502775a2017-12-09 00:02:37 +00002578 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002579 value = Builder.CreateCall(
2580 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
2581 CGF.CGM.FloatTy),
2582 input, "incdec.conv");
2583 } else {
2584 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
2585 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002586 }
2587
John McCalle3dc1702011-02-15 09:22:45 +00002588 if (value->getType()->isFloatTy())
2589 amt = llvm::ConstantFP::get(VMContext,
2590 llvm::APFloat(static_cast<float>(amount)));
2591 else if (value->getType()->isDoubleTy())
2592 amt = llvm::ConstantFP::get(VMContext,
2593 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner05dc78c2010-06-26 22:09:34 +00002594 else {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002595 // Remaining types are Half, LongDouble or __float128. Convert from float.
John McCalle3dc1702011-02-15 09:22:45 +00002596 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner05dc78c2010-06-26 22:09:34 +00002597 bool ignored;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002598 const llvm::fltSemantics *FS;
Ahmed Bougacha6ba38312015-03-24 23:44:42 +00002599 // Don't use getFloatTypeSemantics because Half isn't
2600 // necessarily represented using the "half" LLVM type.
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002601 if (value->getType()->isFP128Ty())
2602 FS = &CGF.getTarget().getFloat128Format();
2603 else if (value->getType()->isHalfTy())
2604 FS = &CGF.getTarget().getHalfFormat();
2605 else
2606 FS = &CGF.getTarget().getLongDoubleFormat();
2607 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
John McCalle3dc1702011-02-15 09:22:45 +00002608 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner05dc78c2010-06-26 22:09:34 +00002609 }
John McCalle3dc1702011-02-15 09:22:45 +00002610 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
2611
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002612 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Akira Hatanaka502775a2017-12-09 00:02:37 +00002613 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002614 value = Builder.CreateCall(
2615 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
2616 CGF.CGM.FloatTy),
2617 value, "incdec.conv");
2618 } else {
2619 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
2620 }
2621 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002622
Bevin Hansson39baaab2020-01-08 11:12:55 +01002623 // Fixed-point types.
2624 } else if (type->isFixedPointType()) {
2625 // Fixed-point types are tricky. In some cases, it isn't possible to
2626 // represent a 1 or a -1 in the type at all. Piggyback off of
2627 // EmitFixedPointBinOp to avoid having to reimplement saturation.
2628 BinOpInfo Info;
2629 Info.E = E;
2630 Info.Ty = E->getType();
2631 Info.Opcode = isInc ? BO_Add : BO_Sub;
2632 Info.LHS = value;
2633 Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
2634 // If the type is signed, it's better to represent this as +(-1) or -(-1),
2635 // since -1 is guaranteed to be representable.
2636 if (type->isSignedFixedPointType()) {
2637 Info.Opcode = isInc ? BO_Sub : BO_Add;
2638 Info.RHS = Builder.CreateNeg(Info.RHS);
2639 }
2640 // Now, convert from our invented integer literal to the type of the unary
2641 // op. This will upscale and saturate if necessary. This value can become
2642 // undef in some cases.
2643 FixedPointSemantics SrcSema =
2644 FixedPointSemantics::GetIntegerSemantics(value->getType()
2645 ->getScalarSizeInBits(),
2646 /*IsSigned=*/true);
2647 FixedPointSemantics DstSema =
2648 CGF.getContext().getFixedPointSemantics(Info.Ty);
2649 Info.RHS = EmitFixedPointConversion(Info.RHS, SrcSema, DstSema,
2650 E->getExprLoc());
2651 value = EmitFixedPointBinOp(Info);
2652
John McCalle3dc1702011-02-15 09:22:45 +00002653 // Objective-C pointer types.
2654 } else {
2655 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
2656 value = CGF.EmitCastToVoidPtr(value);
2657
2658 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
2659 if (!isInc) size = -size;
2660 llvm::Value *sizeValue =
2661 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
2662
Richard Smith9c6890a2012-11-01 22:30:59 +00002663 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002664 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
2665 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002666 value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
2667 /*SignedIndices=*/false, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00002668 E->getExprLoc(), "incdec.objptr");
John McCalle3dc1702011-02-15 09:22:45 +00002669 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner05dc78c2010-06-26 22:09:34 +00002670 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002671
David Chisnallfa35df62012-01-16 17:27:18 +00002672 if (atomicPHI) {
Erik Pilkington53e43f42019-02-28 00:47:55 +00002673 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
David Chisnallfa35df62012-01-16 17:27:18 +00002674 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00002675 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00002676 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
2677 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
2678 llvm::Value *success = Pair.second;
Erik Pilkington53e43f42019-02-28 00:47:55 +00002679 atomicPHI->addIncoming(old, curBlock);
2680 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
David Chisnallfa35df62012-01-16 17:27:18 +00002681 Builder.SetInsertPoint(contBB);
2682 return isPre ? value : input;
2683 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002684
Chris Lattner05dc78c2010-06-26 22:09:34 +00002685 // Store the updated result through the lvalue.
2686 if (LV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00002687 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner05dc78c2010-06-26 22:09:34 +00002688 else
John McCall55e1fbc2011-06-25 02:11:03 +00002689 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002690
Chris Lattner05dc78c2010-06-26 22:09:34 +00002691 // If this is a postinc, return the value read from memory, otherwise use the
2692 // updated value.
John McCalle3dc1702011-02-15 09:22:45 +00002693 return isPre ? value : input;
Chris Lattner05dc78c2010-06-26 22:09:34 +00002694}
2695
2696
2697
Chris Lattner2da04b32007-08-24 05:35:26 +00002698Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002699 TestAndClearIgnoreResultAssign();
Cameron McInally20b8ed22019-10-14 15:35:01 +00002700 Value *Op = Visit(E->getSubExpr());
2701
2702 // Generate a unary FNeg for FP ops.
2703 if (Op->getType()->isFPOrFPVectorTy())
2704 return Builder.CreateFNeg(Op, "fneg");
2705
Chris Lattner0bf27622010-06-26 21:48:21 +00002706 // Emit unary minus with EmitSub so we handle overflow cases etc.
2707 BinOpInfo BinOp;
Cameron McInally20b8ed22019-10-14 15:35:01 +00002708 BinOp.RHS = Op;
2709 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner0bf27622010-06-26 21:48:21 +00002710 BinOp.Ty = E->getType();
John McCalle3027922010-08-25 11:45:40 +00002711 BinOp.Opcode = BO_Sub;
Adam Nemet484aa452017-03-27 19:17:25 +00002712 // FIXME: once UnaryOperator carries FPFeatures, copy it here.
Chris Lattner0bf27622010-06-26 21:48:21 +00002713 BinOp.E = E;
2714 return EmitSub(BinOp);
Chris Lattner2da04b32007-08-24 05:35:26 +00002715}
2716
2717Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002718 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00002719 Value *Op = Visit(E->getSubExpr());
2720 return Builder.CreateNot(Op, "neg");
2721}
2722
2723Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00002724 // Perform vector logical not on comparison with zero vector.
2725 if (E->getType()->isExtVectorType()) {
2726 Value *Oper = Visit(E->getSubExpr());
2727 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00002728 Value *Result;
2729 if (Oper->getType()->isFPOrFPVectorTy())
2730 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
2731 else
2732 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
Tanya Lattner20248222012-01-16 21:02:28 +00002733 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2734 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002735
Chris Lattner2da04b32007-08-24 05:35:26 +00002736 // Compare operand to zero.
2737 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002738
Chris Lattner2da04b32007-08-24 05:35:26 +00002739 // Invert value.
2740 // TODO: Could dynamically modify easy computations here. For example, if
2741 // the operand is an icmp ne, turn into icmp eq.
2742 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stump4a3999f2009-09-09 13:00:44 +00002743
Anders Carlsson775640d2009-05-19 18:44:53 +00002744 // ZExt result to the expr type.
2745 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00002746}
2747
Eli Friedmand7c72322010-08-05 09:58:49 +00002748Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2749 // Try folding the offsetof to a constant.
Fangrui Song407659a2018-11-30 23:41:18 +00002750 Expr::EvalResult EVResult;
2751 if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
2752 llvm::APSInt Value = EVResult.Val.getInt();
Richard Smith5fab0c92011-12-28 19:48:30 +00002753 return Builder.getInt(Value);
Fangrui Song407659a2018-11-30 23:41:18 +00002754 }
Eli Friedmand7c72322010-08-05 09:58:49 +00002755
2756 // Loop over the components of the offsetof to compute the value.
2757 unsigned n = E->getNumComponents();
Chris Lattner2192fe52011-07-18 04:24:23 +00002758 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedmand7c72322010-08-05 09:58:49 +00002759 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2760 QualType CurrentType = E->getTypeSourceInfo()->getType();
2761 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00002762 OffsetOfNode ON = E->getComponent(i);
Craig Topper8a13c412014-05-21 05:09:00 +00002763 llvm::Value *Offset = nullptr;
Eli Friedmand7c72322010-08-05 09:58:49 +00002764 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00002765 case OffsetOfNode::Array: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002766 // Compute the index
2767 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2768 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002769 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedmand7c72322010-08-05 09:58:49 +00002770 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2771
2772 // Save the element type
2773 CurrentType =
2774 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2775
2776 // Compute the element size
2777 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2778 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2779
2780 // Multiply out to compute the result
2781 Offset = Builder.CreateMul(Idx, ElemSize);
2782 break;
2783 }
2784
James Y Knight7281c352015-12-29 22:31:18 +00002785 case OffsetOfNode::Field: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002786 FieldDecl *MemberDecl = ON.getField();
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002787 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
Eli Friedmand7c72322010-08-05 09:58:49 +00002788 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2789
2790 // Compute the index of the field in its parent.
2791 unsigned i = 0;
2792 // FIXME: It would be nice if we didn't have to loop here!
2793 for (RecordDecl::field_iterator Field = RD->field_begin(),
2794 FieldEnd = RD->field_end();
David Blaikie2d7c57e2012-04-30 02:36:29 +00002795 Field != FieldEnd; ++Field, ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002796 if (*Field == MemberDecl)
Eli Friedmand7c72322010-08-05 09:58:49 +00002797 break;
2798 }
2799 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2800
2801 // Compute the offset to the field
2802 int64_t OffsetInt = RL.getFieldOffset(i) /
2803 CGF.getContext().getCharWidth();
2804 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2805
2806 // Save the element type.
2807 CurrentType = MemberDecl->getType();
2808 break;
2809 }
Eli Friedman165301d2010-08-06 16:37:05 +00002810
James Y Knight7281c352015-12-29 22:31:18 +00002811 case OffsetOfNode::Identifier:
Eli Friedmane83d2b762010-08-06 01:17:25 +00002812 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman165301d2010-08-06 16:37:05 +00002813
James Y Knight7281c352015-12-29 22:31:18 +00002814 case OffsetOfNode::Base: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002815 if (ON.getBase()->isVirtual()) {
2816 CGF.ErrorUnsupported(E, "virtual base in offsetof");
2817 continue;
2818 }
2819
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002820 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
Eli Friedmand7c72322010-08-05 09:58:49 +00002821 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2822
2823 // Save the element type.
2824 CurrentType = ON.getBase()->getType();
Craig Toppera97d7e72013-07-26 06:16:11 +00002825
Eli Friedmand7c72322010-08-05 09:58:49 +00002826 // Compute the offset to the base.
2827 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2828 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002829 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2830 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedmand7c72322010-08-05 09:58:49 +00002831 break;
2832 }
2833 }
2834 Result = Builder.CreateAdd(Result, Offset);
2835 }
2836 return Result;
Douglas Gregor882211c2010-04-28 22:16:22 +00002837}
2838
Peter Collingbournee190dee2011-03-11 19:24:49 +00002839/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl6f282892008-11-11 17:56:53 +00002840/// argument of the sizeof expression as an integer.
2841Value *
Peter Collingbournee190dee2011-03-11 19:24:49 +00002842ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2843 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl6f282892008-11-11 17:56:53 +00002844 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002845 if (E->getKind() == UETT_SizeOf) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002846 if (const VariableArrayType *VAT =
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002847 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2848 if (E->isArgumentType()) {
2849 // sizeof(type) - make sure to emit the VLA size.
John McCall23c29fe2011-06-24 21:55:10 +00002850 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman3253e182009-04-20 03:21:44 +00002851 } else {
2852 // C99 6.5.3.4p2: If the argument is an expression of type
2853 // VLA, it is evaluated.
John McCalla2342eb2010-12-05 02:00:02 +00002854 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002855 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002856
Sander de Smalen891af03a2018-02-03 13:55:59 +00002857 auto VlaSize = CGF.getVLASize(VAT);
2858 llvm::Value *size = VlaSize.NumElts;
John McCall23c29fe2011-06-24 21:55:10 +00002859
2860 // Scale the number of non-VLA elements by the non-VLA element size.
Sander de Smalen891af03a2018-02-03 13:55:59 +00002861 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
John McCall23c29fe2011-06-24 21:55:10 +00002862 if (!eltSize.isOne())
Sander de Smalen891af03a2018-02-03 13:55:59 +00002863 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
John McCall23c29fe2011-06-24 21:55:10 +00002864
2865 return size;
Anders Carlsson76dbc042008-12-21 03:33:21 +00002866 }
Alexey Bataev00396512015-07-02 03:40:19 +00002867 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2868 auto Alignment =
2869 CGF.getContext()
2870 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2871 E->getTypeOfArgument()->getPointeeType()))
2872 .getQuantity();
2873 return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
Anders Carlsson30032882008-12-12 07:38:43 +00002874 }
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002875
Mike Stump4a3999f2009-09-09 13:00:44 +00002876 // If this isn't sizeof(vla), the result must be constant; use the constant
2877 // folding logic so we don't have to duplicate it here.
Richard Smith5fab0c92011-12-28 19:48:30 +00002878 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner2da04b32007-08-24 05:35:26 +00002879}
2880
Chris Lattner9f0ad962007-08-24 21:20:17 +00002881Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2882 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002883 if (Op->getType()->isAnyComplexType()) {
2884 // If it's an l-value, load through the appropriate subobject l-value.
2885 // Note that we have to ask E because Op might be an l-value that
2886 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002887 if (E->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002888 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2889 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002890
2891 // Otherwise, calculate and project.
2892 return CGF.EmitComplexExpr(Op, false, true).first;
2893 }
2894
Chris Lattner9f0ad962007-08-24 21:20:17 +00002895 return Visit(Op);
2896}
John McCall07bb1962010-11-16 10:08:07 +00002897
Chris Lattner9f0ad962007-08-24 21:20:17 +00002898Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2899 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002900 if (Op->getType()->isAnyComplexType()) {
2901 // If it's an l-value, load through the appropriate subobject l-value.
2902 // Note that we have to ask E because Op might be an l-value that
2903 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002904 if (Op->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002905 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2906 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002907
2908 // Otherwise, calculate and project.
2909 return CGF.EmitComplexExpr(Op, true, false).second;
2910 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002911
Mike Stumpdf0fe272009-05-29 15:46:01 +00002912 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2913 // effects are evaluated, but not the actual value.
Richard Smith0b6b8e42012-02-18 20:53:32 +00002914 if (Op->isGLValue())
2915 CGF.EmitLValue(Op);
2916 else
2917 CGF.EmitScalarExpr(Op, true);
Owen Anderson0b75f232009-07-31 20:28:54 +00002918 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner9f0ad962007-08-24 21:20:17 +00002919}
2920
Chris Lattner2da04b32007-08-24 05:35:26 +00002921//===----------------------------------------------------------------------===//
2922// Binary Operators
2923//===----------------------------------------------------------------------===//
2924
2925BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002926 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00002927 BinOpInfo Result;
2928 Result.LHS = Visit(E->getLHS());
2929 Result.RHS = Visit(E->getRHS());
Chris Lattner3d966d62007-08-24 21:00:35 +00002930 Result.Ty = E->getType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002931 Result.Opcode = E->getOpcode();
Melanie Blower2ba4e3a2020-04-10 13:34:46 -07002932 Result.FPFeatures = E->getFPFeatures(CGF.getContext());
Chris Lattner2da04b32007-08-24 05:35:26 +00002933 Result.E = E;
2934 return Result;
2935}
2936
Douglas Gregor914af212010-04-23 04:16:32 +00002937LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2938 const CompoundAssignOperator *E,
2939 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002940 Value *&Result) {
Benjamin Kramerd20ef752009-12-25 15:43:36 +00002941 QualType LHSTy = E->getLHS()->getType();
Chris Lattner3d966d62007-08-24 21:00:35 +00002942 BinOpInfo OpInfo;
Craig Toppera97d7e72013-07-26 06:16:11 +00002943
Eli Friedmanf0450072013-06-12 01:40:06 +00002944 if (E->getComputationResultType()->isAnyComplexType())
Richard Smith527473d2015-02-12 21:23:20 +00002945 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
Craig Toppera97d7e72013-07-26 06:16:11 +00002946
Mike Stumpc63428b2009-05-22 19:07:20 +00002947 // Emit the RHS first. __block variables need to have the rhs evaluated
2948 // first, plus this should improve codegen a little.
2949 OpInfo.RHS = Visit(E->getRHS());
2950 OpInfo.Ty = E->getComputationResultType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002951 OpInfo.Opcode = E->getOpcode();
Melanie Blower2ba4e3a2020-04-10 13:34:46 -07002952 OpInfo.FPFeatures = E->getFPFeatures(CGF.getContext());
Mike Stumpc63428b2009-05-22 19:07:20 +00002953 OpInfo.E = E;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00002954 // Load/convert the LHS.
Richard Smith4d1458e2012-09-08 02:08:36 +00002955 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
David Chisnallfa35df62012-01-16 17:27:18 +00002956
Craig Topper8a13c412014-05-21 05:09:00 +00002957 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00002958 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2959 QualType type = atomicTy->getValueType();
2960 if (!type->isBooleanType() && type->isIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002961 !(type->isUnsignedIntegerType() &&
2962 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2963 CGF.getLangOpts().getSignedOverflowBehavior() !=
2964 LangOptions::SOB_Trapping) {
Tim Northover10e0d642019-11-07 13:36:03 +00002965 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
2966 llvm::Instruction::BinaryOps Op;
David Chisnallef78c302013-03-03 16:02:42 +00002967 switch (OpInfo.Opcode) {
2968 // We don't have atomicrmw operands for *, %, /, <<, >>
2969 case BO_MulAssign: case BO_DivAssign:
2970 case BO_RemAssign:
2971 case BO_ShlAssign:
2972 case BO_ShrAssign:
2973 break;
2974 case BO_AddAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00002975 AtomicOp = llvm::AtomicRMWInst::Add;
2976 Op = llvm::Instruction::Add;
David Chisnallef78c302013-03-03 16:02:42 +00002977 break;
2978 case BO_SubAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00002979 AtomicOp = llvm::AtomicRMWInst::Sub;
2980 Op = llvm::Instruction::Sub;
David Chisnallef78c302013-03-03 16:02:42 +00002981 break;
2982 case BO_AndAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00002983 AtomicOp = llvm::AtomicRMWInst::And;
2984 Op = llvm::Instruction::And;
David Chisnallef78c302013-03-03 16:02:42 +00002985 break;
2986 case BO_XorAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00002987 AtomicOp = llvm::AtomicRMWInst::Xor;
2988 Op = llvm::Instruction::Xor;
David Chisnallef78c302013-03-03 16:02:42 +00002989 break;
2990 case BO_OrAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00002991 AtomicOp = llvm::AtomicRMWInst::Or;
2992 Op = llvm::Instruction::Or;
David Chisnallef78c302013-03-03 16:02:42 +00002993 break;
2994 default:
2995 llvm_unreachable("Invalid compound assignment type");
2996 }
Tim Northover10e0d642019-11-07 13:36:03 +00002997 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
2998 llvm::Value *Amt = CGF.EmitToMemory(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002999 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
3000 E->getExprLoc()),
3001 LHSTy);
Tim Northover10e0d642019-11-07 13:36:03 +00003002 Value *OldVal = Builder.CreateAtomicRMW(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003003 AtomicOp, LHSLV.getPointer(CGF), Amt,
JF Bastien92f4ef12016-04-06 17:26:42 +00003004 llvm::AtomicOrdering::SequentiallyConsistent);
Tim Northover10e0d642019-11-07 13:36:03 +00003005
3006 // Since operation is atomic, the result type is guaranteed to be the
3007 // same as the input in LLVM terms.
3008 Result = Builder.CreateBinOp(Op, OldVal, Amt);
David Chisnallef78c302013-03-03 16:02:42 +00003009 return LHSLV;
3010 }
3011 }
David Chisnallfa35df62012-01-16 17:27:18 +00003012 // FIXME: For floating point types, we should be saving and restoring the
3013 // floating point environment in the loop.
3014 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3015 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
Nick Lewycky2d84e842013-10-02 02:29:49 +00003016 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00003017 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
David Chisnallfa35df62012-01-16 17:27:18 +00003018 Builder.CreateBr(opBB);
3019 Builder.SetInsertPoint(opBB);
3020 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
3021 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00003022 OpInfo.LHS = atomicPHI;
3023 }
David Chisnallef78c302013-03-03 16:02:42 +00003024 else
Nick Lewycky2d84e842013-10-02 02:29:49 +00003025 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003026
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003027 SourceLocation Loc = E->getExprLoc();
3028 OpInfo.LHS =
3029 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003030
Chris Lattner3d966d62007-08-24 21:00:35 +00003031 // Expand the binary operator.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003032 Result = (this->*Func)(OpInfo);
Craig Toppera97d7e72013-07-26 06:16:11 +00003033
Roman Lebedevd677c3f2018-11-19 19:56:43 +00003034 // Convert the result back to the LHS type,
3035 // potentially with Implicit Conversion sanitizer check.
3036 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
3037 Loc, ScalarConversionOpts(CGF.SanOpts));
David Chisnallfa35df62012-01-16 17:27:18 +00003038
3039 if (atomicPHI) {
Erik Pilkington53e43f42019-02-28 00:47:55 +00003040 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
David Chisnallfa35df62012-01-16 17:27:18 +00003041 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00003042 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00003043 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
3044 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
3045 llvm::Value *success = Pair.second;
Erik Pilkington53e43f42019-02-28 00:47:55 +00003046 atomicPHI->addIncoming(old, curBlock);
3047 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
David Chisnallfa35df62012-01-16 17:27:18 +00003048 Builder.SetInsertPoint(contBB);
3049 return LHSLV;
3050 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003051
Mike Stump4a3999f2009-09-09 13:00:44 +00003052 // Store the result value into the LHS lvalue. Bit-fields are handled
3053 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
3054 // 'An assignment expression has the value of the left operand after the
3055 // assignment...'.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003056 if (LHSLV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00003057 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003058 else
John McCall55e1fbc2011-06-25 02:11:03 +00003059 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003060
Alexey Bataeva58da1a2019-12-27 09:44:43 -05003061 if (CGF.getLangOpts().OpenMP)
3062 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
3063 E->getLHS());
Douglas Gregor914af212010-04-23 04:16:32 +00003064 return LHSLV;
3065}
3066
3067Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
3068 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
3069 bool Ignore = TestAndClearIgnoreResultAssign();
Simon Pilgrim30aa42e2019-05-18 12:17:15 +00003070 Value *RHS = nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003071 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
3072
3073 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00003074 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00003075 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003076
John McCall07bb1962010-11-16 10:08:07 +00003077 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00003078 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00003079 return RHS;
3080
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003081 // If the lvalue is non-volatile, return the computed value of the assignment.
3082 if (!LHS.isVolatileQualified())
3083 return RHS;
3084
3085 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00003086 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner3d966d62007-08-24 21:00:35 +00003087}
3088
Chris Lattner8ee6a412010-09-11 21:47:09 +00003089void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith4d1458e2012-09-08 02:08:36 +00003090 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003091 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
Chris Lattner8ee6a412010-09-11 21:47:09 +00003092
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00003093 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003094 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
3095 SanitizerKind::IntegerDivideByZero));
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00003096 }
Richard Smithc86a1142012-11-06 02:30:30 +00003097
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003098 const auto *BO = cast<BinaryOperator>(Ops.E);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003099 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003100 Ops.Ty->hasSignedIntegerRepresentation() &&
Vedant Kumard9191152017-05-02 23:46:56 +00003101 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
3102 Ops.mayHaveIntegerOverflow()) {
Richard Smithc86a1142012-11-06 02:30:30 +00003103 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
3104
Chris Lattner8ee6a412010-09-11 21:47:09 +00003105 llvm::Value *IntMin =
Chris Lattner2531eb42011-04-19 22:55:03 +00003106 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner8ee6a412010-09-11 21:47:09 +00003107 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
3108
Richard Smith4d1458e2012-09-08 02:08:36 +00003109 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
3110 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003111 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
3112 Checks.push_back(
3113 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
Chris Lattner8ee6a412010-09-11 21:47:09 +00003114 }
Richard Smithc86a1142012-11-06 02:30:30 +00003115
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003116 if (Checks.size() > 0)
3117 EmitBinOpCheck(Checks, Ops);
Chris Lattner8ee6a412010-09-11 21:47:09 +00003118}
Chris Lattner3d966d62007-08-24 21:00:35 +00003119
Chris Lattner2da04b32007-08-24 05:35:26 +00003120Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003121 {
3122 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003123 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3124 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Vedant Kumard9191152017-05-02 23:46:56 +00003125 Ops.Ty->isIntegerType() &&
3126 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003127 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3128 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003129 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
Vedant Kumard9191152017-05-02 23:46:56 +00003130 Ops.Ty->isRealFloatingType() &&
3131 Ops.mayHaveFloatDivisionByZero()) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003132 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003133 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
3134 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
3135 Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00003136 }
Chris Lattner8ee6a412010-09-11 21:47:09 +00003137 }
Will Dietz1897cb32012-11-27 15:01:55 +00003138
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003139 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
3140 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Yaxun Liuffb60902016-08-09 20:10:18 +00003141 if (CGF.getLangOpts().OpenCL &&
3142 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
3143 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
3144 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
3145 // build option allows an application to specify that single precision
3146 // floating-point divide (x/y and 1/x) and sqrt used in the program
3147 // source are correctly rounded.
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003148 llvm::Type *ValTy = Val->getType();
3149 if (ValTy->isFloatTy() ||
3150 (isa<llvm::VectorType>(ValTy) &&
3151 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sandse81111c2012-04-10 08:23:07 +00003152 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003153 }
3154 return Val;
3155 }
Bevin Hansson39baaab2020-01-08 11:12:55 +01003156 else if (Ops.isFixedPointOp())
Bevin Hansson0b9922e2019-11-19 13:15:06 +01003157 return EmitFixedPointBinOp(Ops);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003158 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003159 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3160 else
3161 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3162}
3163
3164Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3165 // Rem in C can't be a floating point type: C99 6.5.5p2.
Vedant Kumar42de3802017-02-25 00:43:39 +00003166 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3167 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Vedant Kumard9191152017-05-02 23:46:56 +00003168 Ops.Ty->isIntegerType() &&
3169 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003170 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattner8ee6a412010-09-11 21:47:09 +00003171 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Vedant Kumar42de3802017-02-25 00:43:39 +00003172 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
Chris Lattner8ee6a412010-09-11 21:47:09 +00003173 }
3174
Eli Friedman493c34a2011-04-10 04:44:11 +00003175 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003176 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3177 else
3178 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3179}
3180
Mike Stump0c61b732009-04-01 20:28:16 +00003181Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3182 unsigned IID;
3183 unsigned OpID = 0;
Mike Stump40968592009-04-02 01:03:55 +00003184
Will Dietz1897cb32012-11-27 15:01:55 +00003185 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
Chris Lattner0bf27622010-06-26 21:48:21 +00003186 switch (Ops.Opcode) {
John McCalle3027922010-08-25 11:45:40 +00003187 case BO_Add:
3188 case BO_AddAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003189 OpID = 1;
Will Dietz1897cb32012-11-27 15:01:55 +00003190 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
3191 llvm::Intrinsic::uadd_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003192 break;
John McCalle3027922010-08-25 11:45:40 +00003193 case BO_Sub:
3194 case BO_SubAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003195 OpID = 2;
Will Dietz1897cb32012-11-27 15:01:55 +00003196 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
3197 llvm::Intrinsic::usub_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003198 break;
John McCalle3027922010-08-25 11:45:40 +00003199 case BO_Mul:
3200 case BO_MulAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003201 OpID = 3;
Will Dietz1897cb32012-11-27 15:01:55 +00003202 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
3203 llvm::Intrinsic::umul_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003204 break;
3205 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003206 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump0c61b732009-04-01 20:28:16 +00003207 }
Mike Stumpd3e38852009-04-02 18:15:54 +00003208 OpID <<= 1;
Will Dietz1897cb32012-11-27 15:01:55 +00003209 if (isSigned)
3210 OpID |= 1;
Mike Stumpd3e38852009-04-02 18:15:54 +00003211
Vedant Kumar4b62b5c2017-05-09 23:34:49 +00003212 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattnera5f58b02011-07-09 17:41:47 +00003213 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump0c61b732009-04-01 20:28:16 +00003214
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003215 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump0c61b732009-04-01 20:28:16 +00003216
David Blaikie43f9bb72015-05-18 22:14:03 +00003217 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
Mike Stump0c61b732009-04-01 20:28:16 +00003218 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3219 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3220
Richard Smith4d1458e2012-09-08 02:08:36 +00003221 // Handle overflow with llvm.trap if no custom handler has been specified.
3222 const std::string *handlerName =
Richard Smith9c6890a2012-11-01 22:30:59 +00003223 &CGF.getLangOpts().OverflowHandler;
Richard Smith4d1458e2012-09-08 02:08:36 +00003224 if (handlerName->empty()) {
Richard Smithb1b0ab42012-11-05 22:21:05 +00003225 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
Richard Smithde670682012-11-01 22:15:34 +00003226 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003227 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003228 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003229 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003230 : SanitizerKind::UnsignedIntegerOverflow;
3231 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00003232 } else
Chad Rosierae229d52013-01-29 23:31:22 +00003233 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
Richard Smith4d1458e2012-09-08 02:08:36 +00003234 return result;
3235 }
3236
Mike Stump0c61b732009-04-01 20:28:16 +00003237 // Branch in case of overflow.
David Chisnalldd84ef12010-09-17 18:29:54 +00003238 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Duncan P. N. Exon Smith01f574c2016-08-17 03:15:29 +00003239 llvm::BasicBlock *continueBB =
3240 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
Chris Lattner8139c982010-08-07 00:20:46 +00003241 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump0c61b732009-04-01 20:28:16 +00003242
3243 Builder.CreateCondBr(overflow, overflowBB, continueBB);
3244
David Chisnalldd84ef12010-09-17 18:29:54 +00003245 // If an overflow handler is set, then we want to call it and then use its
3246 // result, if it returns.
3247 Builder.SetInsertPoint(overflowBB);
3248
3249 // Get the overflow handler.
Chris Lattnerece04092012-02-07 00:39:47 +00003250 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattnera5f58b02011-07-09 17:41:47 +00003251 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnalldd84ef12010-09-17 18:29:54 +00003252 llvm::FunctionType *handlerTy =
3253 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
James Y Knight9871db02019-02-05 16:42:33 +00003254 llvm::FunctionCallee handler =
3255 CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
David Chisnalldd84ef12010-09-17 18:29:54 +00003256
3257 // Sign extend the args to 64-bit, so that we can use the same handler for
3258 // all types of overflow.
3259 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3260 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3261
3262 // Call the handler with the two arguments, the operation, and the size of
3263 // the result.
John McCall882987f2013-02-28 19:01:20 +00003264 llvm::Value *handlerArgs[] = {
3265 lhs,
3266 rhs,
3267 Builder.getInt8(OpID),
3268 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3269 };
3270 llvm::Value *handlerResult =
3271 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
David Chisnalldd84ef12010-09-17 18:29:54 +00003272
3273 // Truncate the result back to the desired size.
3274 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3275 Builder.CreateBr(continueBB);
3276
Mike Stump0c61b732009-04-01 20:28:16 +00003277 Builder.SetInsertPoint(continueBB);
Jay Foad20c0f022011-03-30 11:28:58 +00003278 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnalldd84ef12010-09-17 18:29:54 +00003279 phi->addIncoming(result, initialBB);
3280 phi->addIncoming(handlerResult, overflowBB);
3281
3282 return phi;
Mike Stump0c61b732009-04-01 20:28:16 +00003283}
Chris Lattner2da04b32007-08-24 05:35:26 +00003284
John McCall77527a82011-06-25 01:32:37 +00003285/// Emit pointer + index arithmetic.
3286static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3287 const BinOpInfo &op,
3288 bool isSubtraction) {
3289 // Must have binary (not unary) expr here. Unary pointer
3290 // increment/decrement doesn't use this path.
3291 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
Craig Toppera97d7e72013-07-26 06:16:11 +00003292
John McCall77527a82011-06-25 01:32:37 +00003293 Value *pointer = op.LHS;
3294 Expr *pointerOperand = expr->getLHS();
3295 Value *index = op.RHS;
3296 Expr *indexOperand = expr->getRHS();
3297
3298 // In a subtraction, the LHS is always the pointer.
3299 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
3300 std::swap(pointer, index);
3301 std::swap(pointerOperand, indexOperand);
3302 }
3303
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003304 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003305
John McCall77527a82011-06-25 01:32:37 +00003306 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
Yaxun Liu26f75662016-08-19 05:17:25 +00003307 auto &DL = CGF.CGM.getDataLayout();
3308 auto PtrTy = cast<llvm::PointerType>(pointer->getType());
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00003309
3310 // Some versions of glibc and gcc use idioms (particularly in their malloc
3311 // routines) that add a pointer-sized integer (known to be a pointer value)
3312 // to a null pointer in order to cast the value back to an integer or as
3313 // part of a pointer alignment algorithm. This is undefined behavior, but
3314 // we'd like to be able to compile programs that use it.
3315 //
3316 // Normally, we'd generate a GEP with a null-pointer base here in response
3317 // to that code, but it's also UB to dereference a pointer created that
3318 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
3319 // generate a direct cast of the integer value to a pointer.
3320 //
3321 // The idiom (p = nullptr + N) is not met if any of the following are true:
3322 //
3323 // The operation is subtraction.
3324 // The index is not pointer-sized.
3325 // The pointer type is not byte-sized.
3326 //
3327 if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
3328 op.Opcode,
Fangrui Song6907ce22018-07-30 19:24:48 +00003329 expr->getLHS(),
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00003330 expr->getRHS()))
3331 return CGF.Builder.CreateIntToPtr(index, pointer->getType());
3332
Nicola Zaghen97572772019-12-13 09:55:45 +00003333 if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
John McCall77527a82011-06-25 01:32:37 +00003334 // Zero-extend or sign-extend the pointer value according to
3335 // whether the index is signed or not.
Nicola Zaghen97572772019-12-13 09:55:45 +00003336 index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
John McCall77527a82011-06-25 01:32:37 +00003337 "idx.ext");
3338 }
3339
3340 // If this is subtraction, negate the index.
3341 if (isSubtraction)
3342 index = CGF.Builder.CreateNeg(index, "idx.neg");
3343
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003344 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00003345 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
3346 /*Accessed*/ false);
3347
John McCall77527a82011-06-25 01:32:37 +00003348 const PointerType *pointerType
3349 = pointerOperand->getType()->getAs<PointerType>();
3350 if (!pointerType) {
3351 QualType objectType = pointerOperand->getType()
3352 ->castAs<ObjCObjectPointerType>()
3353 ->getPointeeType();
3354 llvm::Value *objectSize
3355 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
3356
3357 index = CGF.Builder.CreateMul(index, objectSize);
3358
3359 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3360 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3361 return CGF.Builder.CreateBitCast(result, pointer->getType());
3362 }
3363
3364 QualType elementType = pointerType->getPointeeType();
3365 if (const VariableArrayType *vla
3366 = CGF.getContext().getAsVariableArrayType(elementType)) {
3367 // The element count here is the total number of non-VLA elements.
Sander de Smalen891af03a2018-02-03 13:55:59 +00003368 llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
John McCall77527a82011-06-25 01:32:37 +00003369
3370 // Effectively, the multiply by the VLA size is part of the GEP.
3371 // GEP indexes are signed, and scaling an index isn't permitted to
3372 // signed-overflow, so we use the same semantics for our explicit
3373 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003374 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003375 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
3376 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3377 } else {
3378 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003379 pointer =
Vedant Kumar175b6d12017-07-13 20:55:26 +00003380 CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003381 op.E->getExprLoc(), "add.ptr");
Chris Lattner51924e512010-06-26 21:25:03 +00003382 }
John McCall77527a82011-06-25 01:32:37 +00003383 return pointer;
Mike Stump4a3999f2009-09-09 13:00:44 +00003384 }
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003385
Mike Stump4a3999f2009-09-09 13:00:44 +00003386 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
3387 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
3388 // future proof.
John McCall77527a82011-06-25 01:32:37 +00003389 if (elementType->isVoidType() || elementType->isFunctionType()) {
Matt Arsenaultc6da9ec2019-10-31 08:41:37 -07003390 Value *result = CGF.EmitCastToVoidPtr(pointer);
John McCall77527a82011-06-25 01:32:37 +00003391 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3392 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stump4a3999f2009-09-09 13:00:44 +00003393 }
3394
David Blaikiebbafb8a2012-03-11 07:00:24 +00003395 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall77527a82011-06-25 01:32:37 +00003396 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3397
Vedant Kumar175b6d12017-07-13 20:55:26 +00003398 return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003399 op.E->getExprLoc(), "add.ptr");
Chris Lattner2da04b32007-08-24 05:35:26 +00003400}
3401
Lang Hames5de91cc2012-10-02 04:45:10 +00003402// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
3403// Addend. Use negMul and negAdd to negate the first operand of the Mul or
3404// the add operand respectively. This allows fmuladd to represent a*b-c, or
3405// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
3406// efficient operations.
Wang, Pengfei3239b502020-01-15 19:08:38 +08003407static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
Lang Hames5de91cc2012-10-02 04:45:10 +00003408 const CodeGenFunction &CGF, CGBuilderTy &Builder,
3409 bool negMul, bool negAdd) {
3410 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
Craig Toppera97d7e72013-07-26 06:16:11 +00003411
Lang Hames5de91cc2012-10-02 04:45:10 +00003412 Value *MulOp0 = MulOp->getOperand(0);
3413 Value *MulOp1 = MulOp->getOperand(1);
Craig Topper8b23b2b2019-12-30 13:24:08 -08003414 if (negMul)
3415 MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
3416 if (negAdd)
3417 Addend = Builder.CreateFNeg(Addend, "neg");
Lang Hames5de91cc2012-10-02 04:45:10 +00003418
Wang, Pengfei3239b502020-01-15 19:08:38 +08003419 Value *FMulAdd = nullptr;
3420 if (Builder.getIsFPConstrained()) {
3421 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
3422 "Only constrained operation should be created when Builder is in FP "
3423 "constrained mode");
3424 FMulAdd = Builder.CreateConstrainedFPCall(
3425 CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
3426 Addend->getType()),
3427 {MulOp0, MulOp1, Addend});
3428 } else {
3429 FMulAdd = Builder.CreateCall(
3430 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
3431 {MulOp0, MulOp1, Addend});
3432 }
3433 MulOp->eraseFromParent();
Lang Hames5de91cc2012-10-02 04:45:10 +00003434
Wang, Pengfei3239b502020-01-15 19:08:38 +08003435 return FMulAdd;
Lang Hames5de91cc2012-10-02 04:45:10 +00003436}
3437
3438// Check whether it would be legal to emit an fmuladd intrinsic call to
3439// represent op and if so, build the fmuladd.
3440//
3441// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
3442// Does NOT check the type of the operation - it's assumed that this function
3443// will be called from contexts where it's known that the type is contractable.
Craig Toppera97d7e72013-07-26 06:16:11 +00003444static Value* tryEmitFMulAdd(const BinOpInfo &op,
Lang Hames5de91cc2012-10-02 04:45:10 +00003445 const CodeGenFunction &CGF, CGBuilderTy &Builder,
3446 bool isSub=false) {
3447
3448 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
3449 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
3450 "Only fadd/fsub can be the root of an fmuladd.");
3451
3452 // Check whether this op is marked as fusable.
Adam Nemet049a31d2017-03-29 21:54:24 +00003453 if (!op.FPFeatures.allowFPContractWithinStatement())
Craig Topper8a13c412014-05-21 05:09:00 +00003454 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00003455
3456 // We have a potentially fusable op. Look for a mul on one of the operands.
Sanjay Patela30cee62015-12-03 01:25:12 +00003457 // Also, make sure that the mul result isn't used directly. In that case,
3458 // there's no point creating a muladd operation.
3459 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
3460 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3461 LHSBinOp->use_empty())
Lang Hames5de91cc2012-10-02 04:45:10 +00003462 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
Sanjay Patela30cee62015-12-03 01:25:12 +00003463 }
3464 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
3465 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3466 RHSBinOp->use_empty())
Lang Hames5de91cc2012-10-02 04:45:10 +00003467 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
Lang Hames5de91cc2012-10-02 04:45:10 +00003468 }
3469
Wang, Pengfei3239b502020-01-15 19:08:38 +08003470 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) {
3471 if (LHSBinOp->getIntrinsicID() ==
3472 llvm::Intrinsic::experimental_constrained_fmul &&
3473 LHSBinOp->use_empty())
3474 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3475 }
3476 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) {
3477 if (RHSBinOp->getIntrinsicID() ==
3478 llvm::Intrinsic::experimental_constrained_fmul &&
3479 RHSBinOp->use_empty())
3480 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3481 }
3482
Craig Topper8a13c412014-05-21 05:09:00 +00003483 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00003484}
3485
John McCall77527a82011-06-25 01:32:37 +00003486Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
3487 if (op.LHS->getType()->isPointerTy() ||
3488 op.RHS->getType()->isPointerTy())
Vedant Kumar175b6d12017-07-13 20:55:26 +00003489 return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
John McCall77527a82011-06-25 01:32:37 +00003490
3491 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003492 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
John McCall77527a82011-06-25 01:32:37 +00003493 case LangOptions::SOB_Defined:
3494 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith3e056de2012-08-25 00:32:28 +00003495 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003496 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00003497 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003498 LLVM_FALLTHROUGH;
John McCall77527a82011-06-25 01:32:37 +00003499 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003500 if (CanElideOverflowCheck(CGF.getContext(), op))
3501 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
John McCall77527a82011-06-25 01:32:37 +00003502 return EmitOverflowCheckedBinOp(op);
3503 }
3504 }
Will Dietz1897cb32012-11-27 15:01:55 +00003505
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003506 if (op.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003507 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3508 !CanElideOverflowCheck(CGF.getContext(), op))
Will Dietz1897cb32012-11-27 15:01:55 +00003509 return EmitOverflowCheckedBinOp(op);
3510
Lang Hames5de91cc2012-10-02 04:45:10 +00003511 if (op.LHS->getType()->isFPOrFPVectorTy()) {
3512 // Try to form an fmuladd.
3513 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
3514 return FMulAdd;
3515
Adam Nemet370d0872017-04-04 21:18:30 +00003516 Value *V = Builder.CreateFAdd(op.LHS, op.RHS, "add");
3517 return propagateFMFlags(V, op);
Lang Hames5de91cc2012-10-02 04:45:10 +00003518 }
John McCall77527a82011-06-25 01:32:37 +00003519
Bevin Hansson39baaab2020-01-08 11:12:55 +01003520 if (op.isFixedPointOp())
Leonard Chan837da5d2019-01-16 19:53:50 +00003521 return EmitFixedPointBinOp(op);
Leonard Chan2044ac82019-01-16 18:13:59 +00003522
John McCall77527a82011-06-25 01:32:37 +00003523 return Builder.CreateAdd(op.LHS, op.RHS, "add");
3524}
3525
Leonard Chan2044ac82019-01-16 18:13:59 +00003526/// The resulting value must be calculated with exact precision, so the operands
3527/// may not be the same type.
Leonard Chan837da5d2019-01-16 19:53:50 +00003528Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
Leonard Chan2044ac82019-01-16 18:13:59 +00003529 using llvm::APSInt;
3530 using llvm::ConstantInt;
3531
Bevin Hansson39baaab2020-01-08 11:12:55 +01003532 // This is either a binary operation where at least one of the operands is
3533 // a fixed-point type, or a unary operation where the operand is a fixed-point
3534 // type. The result type of a binary operation is determined by
3535 // Sema::handleFixedPointConversions().
Leonard Chan2044ac82019-01-16 18:13:59 +00003536 QualType ResultTy = op.Ty;
Bevin Hansson39baaab2020-01-08 11:12:55 +01003537 QualType LHSTy, RHSTy;
3538 if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
Bevin Hansson39baaab2020-01-08 11:12:55 +01003539 RHSTy = BinOp->getRHS()->getType();
Bevin Hansson313461f2020-01-08 14:01:30 +01003540 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
3541 // For compound assignment, the effective type of the LHS at this point
3542 // is the computation LHS type, not the actual LHS type, and the final
3543 // result type is not the type of the expression but rather the
3544 // computation result type.
3545 LHSTy = CAO->getComputationLHSType();
3546 ResultTy = CAO->getComputationResultType();
3547 } else
3548 LHSTy = BinOp->getLHS()->getType();
Bevin Hansson39baaab2020-01-08 11:12:55 +01003549 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
3550 LHSTy = UnOp->getSubExpr()->getType();
3551 RHSTy = UnOp->getSubExpr()->getType();
3552 }
Leonard Chan2044ac82019-01-16 18:13:59 +00003553 ASTContext &Ctx = CGF.getContext();
3554 Value *LHS = op.LHS;
3555 Value *RHS = op.RHS;
3556
3557 auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
3558 auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
3559 auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
3560 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
3561
3562 // Convert the operands to the full precision type.
3563 Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema,
Bevin Hansson39baaab2020-01-08 11:12:55 +01003564 op.E->getExprLoc());
Leonard Chan2044ac82019-01-16 18:13:59 +00003565 Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema,
Bevin Hansson39baaab2020-01-08 11:12:55 +01003566 op.E->getExprLoc());
Leonard Chan2044ac82019-01-16 18:13:59 +00003567
Bevin Hansson313461f2020-01-08 14:01:30 +01003568 // Perform the actual operation.
Leonard Chan2044ac82019-01-16 18:13:59 +00003569 Value *Result;
Bevin Hansson39baaab2020-01-08 11:12:55 +01003570 switch (op.Opcode) {
Bevin Hansson313461f2020-01-08 14:01:30 +01003571 case BO_AddAssign:
Leonard Chan837da5d2019-01-16 19:53:50 +00003572 case BO_Add: {
3573 if (ResultFixedSema.isSaturated()) {
3574 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3575 ? llvm::Intrinsic::sadd_sat
3576 : llvm::Intrinsic::uadd_sat;
3577 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3578 } else {
3579 Result = Builder.CreateAdd(FullLHS, FullRHS);
3580 }
3581 break;
3582 }
Bevin Hansson313461f2020-01-08 14:01:30 +01003583 case BO_SubAssign:
Leonard Chan837da5d2019-01-16 19:53:50 +00003584 case BO_Sub: {
3585 if (ResultFixedSema.isSaturated()) {
3586 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3587 ? llvm::Intrinsic::ssub_sat
3588 : llvm::Intrinsic::usub_sat;
3589 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3590 } else {
3591 Result = Builder.CreateSub(FullLHS, FullRHS);
3592 }
3593 break;
3594 }
Bevin Hansson313461f2020-01-08 14:01:30 +01003595 case BO_MulAssign:
Bevin Hansson0b9922e2019-11-19 13:15:06 +01003596 case BO_Mul: {
3597 llvm::Intrinsic::ID IID;
3598 if (ResultFixedSema.isSaturated())
3599 IID = ResultFixedSema.isSigned()
3600 ? llvm::Intrinsic::smul_fix_sat
3601 : llvm::Intrinsic::umul_fix_sat;
3602 else
3603 IID = ResultFixedSema.isSigned()
3604 ? llvm::Intrinsic::smul_fix
3605 : llvm::Intrinsic::umul_fix;
3606 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3607 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3608 break;
3609 }
Bevin Hansson313461f2020-01-08 14:01:30 +01003610 case BO_DivAssign:
Bevin Hansson0b9922e2019-11-19 13:15:06 +01003611 case BO_Div: {
3612 llvm::Intrinsic::ID IID;
3613 if (ResultFixedSema.isSaturated())
3614 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix_sat
3615 : llvm::Intrinsic::udiv_fix_sat;
3616 else
3617 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix
3618 : llvm::Intrinsic::udiv_fix;
3619 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3620 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3621 break;
3622 }
Leonard Chance1d4f12019-02-21 20:50:09 +00003623 case BO_LT:
3624 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS)
3625 : Builder.CreateICmpULT(FullLHS, FullRHS);
3626 case BO_GT:
3627 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS)
3628 : Builder.CreateICmpUGT(FullLHS, FullRHS);
3629 case BO_LE:
3630 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS)
3631 : Builder.CreateICmpULE(FullLHS, FullRHS);
3632 case BO_GE:
3633 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS)
3634 : Builder.CreateICmpUGE(FullLHS, FullRHS);
3635 case BO_EQ:
3636 // For equality operations, we assume any padding bits on unsigned types are
3637 // zero'd out. They could be overwritten through non-saturating operations
3638 // that cause overflow, but this leads to undefined behavior.
3639 return Builder.CreateICmpEQ(FullLHS, FullRHS);
3640 case BO_NE:
3641 return Builder.CreateICmpNE(FullLHS, FullRHS);
Leonard Chan837da5d2019-01-16 19:53:50 +00003642 case BO_Shl:
3643 case BO_Shr:
3644 case BO_Cmp:
Leonard Chan837da5d2019-01-16 19:53:50 +00003645 case BO_LAnd:
3646 case BO_LOr:
Leonard Chan837da5d2019-01-16 19:53:50 +00003647 case BO_ShlAssign:
3648 case BO_ShrAssign:
3649 llvm_unreachable("Found unimplemented fixed point binary operation");
3650 case BO_PtrMemD:
3651 case BO_PtrMemI:
3652 case BO_Rem:
3653 case BO_Xor:
3654 case BO_And:
3655 case BO_Or:
3656 case BO_Assign:
3657 case BO_RemAssign:
3658 case BO_AndAssign:
3659 case BO_XorAssign:
3660 case BO_OrAssign:
3661 case BO_Comma:
3662 llvm_unreachable("Found unsupported binary operation for fixed point types.");
Leonard Chan2044ac82019-01-16 18:13:59 +00003663 }
3664
3665 // Convert to the result type.
3666 return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema,
Bevin Hansson39baaab2020-01-08 11:12:55 +01003667 op.E->getExprLoc());
Leonard Chan2044ac82019-01-16 18:13:59 +00003668}
3669
John McCall77527a82011-06-25 01:32:37 +00003670Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
3671 // The LHS is always a pointer if either side is.
3672 if (!op.LHS->getType()->isPointerTy()) {
3673 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003674 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +00003675 case LangOptions::SOB_Defined:
John McCall77527a82011-06-25 01:32:37 +00003676 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith3e056de2012-08-25 00:32:28 +00003677 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003678 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00003679 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003680 LLVM_FALLTHROUGH;
Chris Lattner51924e512010-06-26 21:25:03 +00003681 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003682 if (CanElideOverflowCheck(CGF.getContext(), op))
3683 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
John McCall77527a82011-06-25 01:32:37 +00003684 return EmitOverflowCheckedBinOp(op);
Chris Lattner51924e512010-06-26 21:25:03 +00003685 }
3686 }
Will Dietz1897cb32012-11-27 15:01:55 +00003687
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003688 if (op.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003689 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3690 !CanElideOverflowCheck(CGF.getContext(), op))
Will Dietz1897cb32012-11-27 15:01:55 +00003691 return EmitOverflowCheckedBinOp(op);
3692
Lang Hames5de91cc2012-10-02 04:45:10 +00003693 if (op.LHS->getType()->isFPOrFPVectorTy()) {
3694 // Try to form an fmuladd.
3695 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
3696 return FMulAdd;
Adam Nemet370d0872017-04-04 21:18:30 +00003697 Value *V = Builder.CreateFSub(op.LHS, op.RHS, "sub");
3698 return propagateFMFlags(V, op);
Lang Hames5de91cc2012-10-02 04:45:10 +00003699 }
Chris Lattner5902e7b2010-03-29 17:28:16 +00003700
Bevin Hansson39baaab2020-01-08 11:12:55 +01003701 if (op.isFixedPointOp())
Leonard Chan837da5d2019-01-16 19:53:50 +00003702 return EmitFixedPointBinOp(op);
3703
John McCall77527a82011-06-25 01:32:37 +00003704 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump0c61b732009-04-01 20:28:16 +00003705 }
Chris Lattner3d966d62007-08-24 21:00:35 +00003706
John McCall77527a82011-06-25 01:32:37 +00003707 // If the RHS is not a pointer, then we have normal pointer
3708 // arithmetic.
3709 if (!op.RHS->getType()->isPointerTy())
Vedant Kumar175b6d12017-07-13 20:55:26 +00003710 return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
Eli Friedmane381f7e2009-03-28 02:45:41 +00003711
John McCall77527a82011-06-25 01:32:37 +00003712 // Otherwise, this is a pointer subtraction.
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00003713
John McCall77527a82011-06-25 01:32:37 +00003714 // Do the raw subtraction part.
3715 llvm::Value *LHS
3716 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
3717 llvm::Value *RHS
3718 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
3719 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003720
John McCall77527a82011-06-25 01:32:37 +00003721 // Okay, figure out the element size.
3722 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3723 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00003724
Craig Topper8a13c412014-05-21 05:09:00 +00003725 llvm::Value *divisor = nullptr;
John McCall77527a82011-06-25 01:32:37 +00003726
3727 // For a variable-length array, this is going to be non-constant.
3728 if (const VariableArrayType *vla
3729 = CGF.getContext().getAsVariableArrayType(elementType)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +00003730 auto VlaSize = CGF.getVLASize(vla);
3731 elementType = VlaSize.Type;
3732 divisor = VlaSize.NumElts;
John McCall77527a82011-06-25 01:32:37 +00003733
3734 // Scale the number of non-VLA elements by the non-VLA element size.
3735 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
3736 if (!eltSize.isOne())
3737 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
3738
3739 // For everything elese, we can just compute it, safe in the
3740 // assumption that Sema won't let anything through that we can't
3741 // safely compute the size of.
3742 } else {
3743 CharUnits elementSize;
3744 // Handle GCC extension for pointer arithmetic on void* and
3745 // function pointer types.
3746 if (elementType->isVoidType() || elementType->isFunctionType())
3747 elementSize = CharUnits::One();
3748 else
3749 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
3750
3751 // Don't even emit the divide for element size of 1.
3752 if (elementSize.isOne())
3753 return diffInChars;
3754
3755 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner2da04b32007-08-24 05:35:26 +00003756 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003757
Chris Lattner2e72da942011-03-01 00:03:48 +00003758 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
3759 // pointer difference in C is only defined in the case where both operands
3760 // are pointing to elements of an array.
John McCall77527a82011-06-25 01:32:37 +00003761 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner2da04b32007-08-24 05:35:26 +00003762}
3763
David Tweed042e0882013-01-07 16:43:27 +00003764Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
David Tweed9fb566c2013-01-10 09:11:33 +00003765 llvm::IntegerType *Ty;
3766 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3767 Ty = cast<llvm::IntegerType>(VT->getElementType());
3768 else
3769 Ty = cast<llvm::IntegerType>(LHS->getType());
3770 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
David Tweed042e0882013-01-07 16:43:27 +00003771}
3772
Chris Lattner2da04b32007-08-24 05:35:26 +00003773Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
3774 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3775 // RHS to the same size as the LHS.
3776 Value *RHS = Ops.RHS;
3777 if (Ops.LHS->getType() != RHS->getType())
3778 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00003779
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003780 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
James Molloy59802322016-08-16 09:45:36 +00003781 Ops.Ty->hasSignedIntegerRepresentation() &&
Richard Smith7939ba02019-06-25 01:45:26 +00003782 !CGF.getLangOpts().isSignedOverflowDefined() &&
3783 !CGF.getLangOpts().CPlusPlus2a;
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003784 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
3785 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3786 if (CGF.getLangOpts().OpenCL)
3787 RHS =
3788 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
3789 else if ((SanitizeBase || SanitizeExponent) &&
3790 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003791 CodeGenFunction::SanitizerScope SanScope(&CGF);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003792 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
Vedant Kumard3a601b2017-01-30 23:38:54 +00003793 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
3794 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
Richard Smith3e056de2012-08-25 00:32:28 +00003795
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003796 if (SanitizeExponent) {
3797 Checks.push_back(
3798 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
3799 }
3800
3801 if (SanitizeBase) {
3802 // Check whether we are shifting any non-zero bits off the top of the
3803 // integer. We only emit this check if exponent is valid - otherwise
3804 // instructions below will have undefined behavior themselves.
Alexey Samsonov48a9db02015-03-05 21:57:35 +00003805 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
3806 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003807 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
3808 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
Vedant Kumard3a601b2017-01-30 23:38:54 +00003809 llvm::Value *PromotedWidthMinusOne =
3810 (RHS == Ops.RHS) ? WidthMinusOne
3811 : GetWidthMinusOneValue(Ops.LHS, RHS);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003812 CGF.EmitBlock(CheckShiftBase);
Vedant Kumard3a601b2017-01-30 23:38:54 +00003813 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
3814 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
3815 /*NUW*/ true, /*NSW*/ true),
3816 "shl.check");
Richard Smith3e056de2012-08-25 00:32:28 +00003817 if (CGF.getLangOpts().CPlusPlus) {
3818 // In C99, we are not permitted to shift a 1 bit into the sign bit.
3819 // Under C++11's rules, shifting a 1 bit into the sign bit is
3820 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
3821 // define signed left shifts, so we use the C99 and C++11 rules there).
3822 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
3823 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
3824 }
3825 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003826 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
Alexey Samsonov48a9db02015-03-05 21:57:35 +00003827 CGF.EmitBlock(Cont);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003828 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
3829 BaseCheck->addIncoming(Builder.getTrue(), Orig);
3830 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
3831 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
Richard Smith3e056de2012-08-25 00:32:28 +00003832 }
Will Dietz11d0a9f2013-02-25 22:37:49 +00003833
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003834 assert(!Checks.empty());
3835 EmitBinOpCheck(Checks, Ops);
Mike Stumpba6a0c42009-12-14 21:58:14 +00003836 }
3837
Chris Lattner2da04b32007-08-24 05:35:26 +00003838 return Builder.CreateShl(Ops.LHS, RHS, "shl");
3839}
3840
3841Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
3842 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3843 // RHS to the same size as the LHS.
3844 Value *RHS = Ops.RHS;
3845 if (Ops.LHS->getType() != RHS->getType())
3846 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00003847
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003848 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3849 if (CGF.getLangOpts().OpenCL)
3850 RHS =
3851 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
3852 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
3853 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003854 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003855 llvm::Value *Valid =
3856 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003857 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00003858 }
David Tweed042e0882013-01-07 16:43:27 +00003859
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003860 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003861 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
3862 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
3863}
3864
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003865enum IntrinsicType { VCMPEQ, VCMPGT };
3866// return corresponding comparison intrinsic for given vector type
3867static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
3868 BuiltinType::Kind ElemKind) {
3869 switch (ElemKind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003870 default: llvm_unreachable("unexpected element type");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003871 case BuiltinType::Char_U:
3872 case BuiltinType::UChar:
3873 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3874 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003875 case BuiltinType::Char_S:
3876 case BuiltinType::SChar:
3877 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3878 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003879 case BuiltinType::UShort:
3880 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3881 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003882 case BuiltinType::Short:
3883 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3884 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003885 case BuiltinType::UInt:
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003886 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3887 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003888 case BuiltinType::Int:
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003889 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3890 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Guozhi Wei769095b2017-10-19 20:11:23 +00003891 case BuiltinType::ULong:
3892 case BuiltinType::ULongLong:
3893 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3894 llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
3895 case BuiltinType::Long:
3896 case BuiltinType::LongLong:
3897 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3898 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003899 case BuiltinType::Float:
3900 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
3901 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Guozhi Wei769095b2017-10-19 20:11:23 +00003902 case BuiltinType::Double:
3903 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
3904 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003905 }
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003906}
3907
Craig Topperc82f8962015-12-16 06:24:28 +00003908Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
3909 llvm::CmpInst::Predicate UICmpOpc,
3910 llvm::CmpInst::Predicate SICmpOpc,
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +01003911 llvm::CmpInst::Predicate FCmpOpc,
3912 bool IsSignaling) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00003913 TestAndClearIgnoreResultAssign();
Chris Lattner42e6b812007-08-26 16:34:22 +00003914 Value *Result;
Chris Lattner2da04b32007-08-24 05:35:26 +00003915 QualType LHSTy = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00003916 QualType RHSTy = E->getRHS()->getType();
John McCall7a9aac22010-08-23 01:21:21 +00003917 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCalle3027922010-08-25 11:45:40 +00003918 assert(E->getOpcode() == BO_EQ ||
3919 E->getOpcode() == BO_NE);
John McCalla1dee5302010-08-22 10:59:02 +00003920 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
3921 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall7a9aac22010-08-23 01:21:21 +00003922 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCalle3027922010-08-25 11:45:40 +00003923 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Chandler Carruthb29a7432014-10-11 11:03:30 +00003924 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
Leonard Chance1d4f12019-02-21 20:50:09 +00003925 BinOpInfo BOInfo = EmitBinOps(E);
3926 Value *LHS = BOInfo.LHS;
3927 Value *RHS = BOInfo.RHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00003928
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003929 // If AltiVec, the comparison results in a numeric type, so we use
3930 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev93900c72011-03-28 21:00:05 +00003931 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003932 // constants for mapping CR6 register bits to predicate result
3933 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
3934
3935 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
3936
3937 // in several cases vector arguments order will be reversed
3938 Value *FirstVecArg = LHS,
3939 *SecondVecArg = RHS;
3940
Simon Pilgrime0712012019-10-02 15:31:25 +00003941 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
Simon Pilgrim16c53ff2020-01-11 15:33:25 +00003942 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003943
3944 switch(E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003945 default: llvm_unreachable("is not a comparison operation");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003946 case BO_EQ:
3947 CR6 = CR6_LT;
3948 ID = GetIntrinsic(VCMPEQ, ElementKind);
3949 break;
3950 case BO_NE:
3951 CR6 = CR6_EQ;
3952 ID = GetIntrinsic(VCMPEQ, ElementKind);
3953 break;
3954 case BO_LT:
3955 CR6 = CR6_LT;
3956 ID = GetIntrinsic(VCMPGT, ElementKind);
3957 std::swap(FirstVecArg, SecondVecArg);
3958 break;
3959 case BO_GT:
3960 CR6 = CR6_LT;
3961 ID = GetIntrinsic(VCMPGT, ElementKind);
3962 break;
3963 case BO_LE:
3964 if (ElementKind == BuiltinType::Float) {
3965 CR6 = CR6_LT;
3966 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3967 std::swap(FirstVecArg, SecondVecArg);
3968 }
3969 else {
3970 CR6 = CR6_EQ;
3971 ID = GetIntrinsic(VCMPGT, ElementKind);
3972 }
3973 break;
3974 case BO_GE:
3975 if (ElementKind == BuiltinType::Float) {
3976 CR6 = CR6_LT;
3977 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3978 }
3979 else {
3980 CR6 = CR6_EQ;
3981 ID = GetIntrinsic(VCMPGT, ElementKind);
3982 std::swap(FirstVecArg, SecondVecArg);
3983 }
3984 break;
3985 }
3986
Chris Lattner2531eb42011-04-19 22:55:03 +00003987 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003988 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
David Blaikie43f9bb72015-05-18 22:14:03 +00003989 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
Guozhi Wei3625f3e2017-10-10 20:31:27 +00003990
3991 // The result type of intrinsic may not be same as E->getType().
3992 // If E->getType() is not BoolTy, EmitScalarConversion will do the
3993 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
3994 // do nothing, if ResultTy is not i1 at the same time, it will cause
3995 // crash later.
3996 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
3997 if (ResultTy->getBitWidth() > 1 &&
3998 E->getType() == CGF.getContext().BoolTy)
3999 Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004000 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4001 E->getExprLoc());
Anton Yartsev3f8f2882010-11-18 03:19:30 +00004002 }
4003
Bevin Hansson39baaab2020-01-08 11:12:55 +01004004 if (BOInfo.isFixedPointOp()) {
Leonard Chance1d4f12019-02-21 20:50:09 +00004005 Result = EmitFixedPointBinOp(BOInfo);
4006 } else if (LHS->getType()->isFPOrFPVectorTy()) {
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +01004007 if (!IsSignaling)
4008 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
4009 else
4010 Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004011 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Craig Topperc82f8962015-12-16 06:24:28 +00004012 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
Chris Lattner2da04b32007-08-24 05:35:26 +00004013 } else {
Eli Friedman3c285242008-05-29 15:09:15 +00004014 // Unsigned integers and pointers.
Piotr Padlewski07058292018-07-02 19:21:36 +00004015
4016 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
4017 !isa<llvm::ConstantPointerNull>(LHS) &&
4018 !isa<llvm::ConstantPointerNull>(RHS)) {
4019
4020 // Dynamic information is required to be stripped for comparisons,
4021 // because it could leak the dynamic information. Based on comparisons
4022 // of pointers to dynamic objects, the optimizer can replace one pointer
4023 // with another, which might be incorrect in presence of invariant
4024 // groups. Comparison with null is safe because null does not carry any
4025 // dynamic information.
4026 if (LHSTy.mayBeDynamicClass())
4027 LHS = Builder.CreateStripInvariantGroup(LHS);
4028 if (RHSTy.mayBeDynamicClass())
4029 RHS = Builder.CreateStripInvariantGroup(RHS);
4030 }
4031
Craig Topperc82f8962015-12-16 06:24:28 +00004032 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
Chris Lattner2da04b32007-08-24 05:35:26 +00004033 }
Chris Lattner2a7deb62009-07-08 01:08:03 +00004034
4035 // If this is a vector comparison, sign extend the result to the appropriate
4036 // vector integer type and return it (don't convert to bool).
4037 if (LHSTy->isVectorType())
4038 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stump4a3999f2009-09-09 13:00:44 +00004039
Chris Lattner2da04b32007-08-24 05:35:26 +00004040 } else {
4041 // Complex Comparison: can only be an equality comparison.
Chandler Carruthb29a7432014-10-11 11:03:30 +00004042 CodeGenFunction::ComplexPairTy LHS, RHS;
4043 QualType CETy;
4044 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
4045 LHS = CGF.EmitComplexExpr(E->getLHS());
4046 CETy = CTy->getElementType();
4047 } else {
4048 LHS.first = Visit(E->getLHS());
4049 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
4050 CETy = LHSTy;
4051 }
4052 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
4053 RHS = CGF.EmitComplexExpr(E->getRHS());
4054 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
4055 CTy->getElementType()) &&
4056 "The element types must always match.");
Chandler Carruth60fdc412014-10-11 11:29:26 +00004057 (void)CTy;
Chandler Carruthb29a7432014-10-11 11:03:30 +00004058 } else {
4059 RHS.first = Visit(E->getRHS());
4060 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
4061 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
4062 "The element types must always match.");
4063 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004064
Chris Lattner42e6b812007-08-26 16:34:22 +00004065 Value *ResultR, *ResultI;
Chris Lattner2da04b32007-08-24 05:35:26 +00004066 if (CETy->isRealFloatingType()) {
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +01004067 // As complex comparisons can only be equality comparisons, they
4068 // are never signaling comparisons.
Craig Topperc82f8962015-12-16 06:24:28 +00004069 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
4070 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
Chris Lattner2da04b32007-08-24 05:35:26 +00004071 } else {
4072 // Complex comparisons can only be equality comparisons. As such, signed
4073 // and unsigned opcodes are the same.
Craig Topperc82f8962015-12-16 06:24:28 +00004074 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
4075 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
Chris Lattner2da04b32007-08-24 05:35:26 +00004076 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004077
John McCalle3027922010-08-25 11:45:40 +00004078 if (E->getOpcode() == BO_EQ) {
Chris Lattner2da04b32007-08-24 05:35:26 +00004079 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
4080 } else {
John McCalle3027922010-08-25 11:45:40 +00004081 assert(E->getOpcode() == BO_NE &&
Chris Lattner2da04b32007-08-24 05:35:26 +00004082 "Complex comparison other than == or != ?");
4083 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
4084 }
4085 }
Nuno Lopesa0abe622009-01-11 23:22:37 +00004086
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004087 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4088 E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00004089}
4090
4091Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00004092 bool Ignore = TestAndClearIgnoreResultAssign();
4093
John McCall31168b02011-06-15 23:02:42 +00004094 Value *RHS;
4095 LValue LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00004096
John McCall31168b02011-06-15 23:02:42 +00004097 switch (E->getLHS()->getType().getObjCLifetime()) {
4098 case Qualifiers::OCL_Strong:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004099 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
John McCall31168b02011-06-15 23:02:42 +00004100 break;
4101
4102 case Qualifiers::OCL_Autoreleasing:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004103 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
John McCall31168b02011-06-15 23:02:42 +00004104 break;
4105
John McCalle399e5b2016-01-27 18:32:30 +00004106 case Qualifiers::OCL_ExplicitNone:
4107 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
4108 break;
4109
John McCall31168b02011-06-15 23:02:42 +00004110 case Qualifiers::OCL_Weak:
4111 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00004112 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004113 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore);
John McCall31168b02011-06-15 23:02:42 +00004114 break;
4115
John McCall31168b02011-06-15 23:02:42 +00004116 case Qualifiers::OCL_None:
John McCall31168b02011-06-15 23:02:42 +00004117 // __block variables need to have the rhs evaluated first, plus
4118 // this should improve codegen just a little.
4119 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00004120 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall31168b02011-06-15 23:02:42 +00004121
4122 // Store the value into the LHS. Bit-fields are handled specially
4123 // because the result is altered by the store, i.e., [C99 6.5.16p1]
4124 // 'An assignment expression has the value of the left operand after
4125 // the assignment...'.
Vedant Kumar42c17ec2017-03-14 01:56:34 +00004126 if (LHS.isBitField()) {
John McCall55e1fbc2011-06-25 02:11:03 +00004127 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +00004128 } else {
4129 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004130 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +00004131 }
John McCall31168b02011-06-15 23:02:42 +00004132 }
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004133
4134 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00004135 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00004136 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004137
John McCall07bb1962010-11-16 10:08:07 +00004138 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00004139 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00004140 return RHS;
4141
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004142 // If the lvalue is non-volatile, return the computed value of the assignment.
4143 if (!LHS.isVolatileQualified())
4144 return RHS;
4145
4146 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00004147 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00004148}
4149
4150Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00004151 // Perform vector logical and on comparisons with zero vectors.
4152 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00004153 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004154
Tanya Lattner20248222012-01-16 21:02:28 +00004155 Value *LHS = Visit(E->getLHS());
4156 Value *RHS = Visit(E->getRHS());
4157 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00004158 if (LHS->getType()->isFPOrFPVectorTy()) {
4159 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4160 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4161 } else {
4162 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4163 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4164 }
Tanya Lattner20248222012-01-16 21:02:28 +00004165 Value *And = Builder.CreateAnd(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00004166 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00004167 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004168
Chris Lattner2192fe52011-07-18 04:24:23 +00004169 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00004170
Chris Lattner8b084582008-11-12 08:26:50 +00004171 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
4172 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00004173 bool LHSCondVal;
4174 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4175 if (LHSCondVal) { // If we have 1 && X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00004176 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004177
Chris Lattner5b1964b2008-11-11 07:41:27 +00004178 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00004179 // ZExt result to int or bool.
4180 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00004181 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004182
Chris Lattner671fec82009-10-17 04:24:20 +00004183 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner8b084582008-11-12 08:26:50 +00004184 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00004185 return llvm::Constant::getNullValue(ResTy);
Chris Lattner5b1964b2008-11-11 07:41:27 +00004186 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004187
Daniel Dunbara612e792008-11-13 01:38:36 +00004188 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
4189 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner8b084582008-11-12 08:26:50 +00004190
John McCallce1de612011-01-26 04:00:11 +00004191 CodeGenFunction::ConditionalEvaluation eval(CGF);
4192
Chris Lattner35710d182008-11-12 08:38:24 +00004193 // Branch on the LHS first. If it is false, go to the failure (cont) block.
Justin Bogner66242d62015-04-23 23:06:47 +00004194 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
4195 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00004196
4197 // Any edges into the ContBlock are now from an (indeterminate number of)
4198 // edges from this first condition. All of these values will be false. Start
4199 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00004200 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00004201 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00004202 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4203 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00004204 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stump4a3999f2009-09-09 13:00:44 +00004205
John McCallce1de612011-01-26 04:00:11 +00004206 eval.begin(CGF);
Chris Lattner2da04b32007-08-24 05:35:26 +00004207 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004208 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00004209 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCallce1de612011-01-26 04:00:11 +00004210 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004211
Chris Lattner2da04b32007-08-24 05:35:26 +00004212 // Reaquire the RHS block, as there may be subblocks inserted.
4213 RHSBlock = Builder.GetInsertBlock();
Chris Lattner35710d182008-11-12 08:38:24 +00004214
David Blaikie1b5adb82014-07-10 20:42:59 +00004215 // Emit an unconditional branch from this block to ContBlock.
4216 {
Devang Patel4d761272011-03-30 00:08:31 +00004217 // There is no need to emit line number for unconditional branch.
Adrian Prantl95b24e92015-02-03 20:00:54 +00004218 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
David Blaikie1b5adb82014-07-10 20:42:59 +00004219 CGF.EmitBlock(ContBlock);
4220 }
4221 // Insert an entry into the phi node for the edge with the value of RHSCond.
Chris Lattner2da04b32007-08-24 05:35:26 +00004222 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004223
Anastasis Grammenosdfe8fe52018-06-21 16:53:48 +00004224 // Artificial location to preserve the scope information
4225 {
4226 auto NL = ApplyDebugLocation::CreateArtificial(CGF);
4227 PN->setDebugLoc(Builder.getCurrentDebugLocation());
4228 }
4229
Chris Lattner2da04b32007-08-24 05:35:26 +00004230 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00004231 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00004232}
4233
4234Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00004235 // Perform vector logical or on comparisons with zero vectors.
4236 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00004237 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004238
Tanya Lattner20248222012-01-16 21:02:28 +00004239 Value *LHS = Visit(E->getLHS());
4240 Value *RHS = Visit(E->getRHS());
4241 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00004242 if (LHS->getType()->isFPOrFPVectorTy()) {
4243 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4244 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4245 } else {
4246 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4247 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4248 }
Tanya Lattner20248222012-01-16 21:02:28 +00004249 Value *Or = Builder.CreateOr(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00004250 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00004251 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004252
Chris Lattner2192fe52011-07-18 04:24:23 +00004253 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00004254
Chris Lattner8b084582008-11-12 08:26:50 +00004255 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
4256 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00004257 bool LHSCondVal;
4258 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4259 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00004260 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004261
Chris Lattner5b1964b2008-11-11 07:41:27 +00004262 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00004263 // ZExt result to int or bool.
4264 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00004265 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004266
Chris Lattner671fec82009-10-17 04:24:20 +00004267 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner8b084582008-11-12 08:26:50 +00004268 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00004269 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner5b1964b2008-11-11 07:41:27 +00004270 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004271
Daniel Dunbara612e792008-11-13 01:38:36 +00004272 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
4273 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stump4a3999f2009-09-09 13:00:44 +00004274
John McCallce1de612011-01-26 04:00:11 +00004275 CodeGenFunction::ConditionalEvaluation eval(CGF);
4276
Chris Lattner35710d182008-11-12 08:38:24 +00004277 // Branch on the LHS first. If it is true, go to the success (cont) block.
Justin Bogneref512b92014-01-06 22:27:43 +00004278 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00004279 CGF.getCurrentProfileCount() -
4280 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00004281
4282 // Any edges into the ContBlock are now from an (indeterminate number of)
4283 // edges from this first condition. All of these values will be true. Start
4284 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00004285 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00004286 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00004287 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4288 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00004289 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattner35710d182008-11-12 08:38:24 +00004290
John McCallce1de612011-01-26 04:00:11 +00004291 eval.begin(CGF);
Anders Carlssonf47a3de2009-06-04 02:53:13 +00004292
Chris Lattner35710d182008-11-12 08:38:24 +00004293 // Emit the RHS condition as a bool value.
Chris Lattner2da04b32007-08-24 05:35:26 +00004294 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004295 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00004296 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00004297
John McCallce1de612011-01-26 04:00:11 +00004298 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004299
Chris Lattner2da04b32007-08-24 05:35:26 +00004300 // Reaquire the RHS block, as there may be subblocks inserted.
4301 RHSBlock = Builder.GetInsertBlock();
Mike Stump4a3999f2009-09-09 13:00:44 +00004302
Chris Lattner35710d182008-11-12 08:38:24 +00004303 // Emit an unconditional branch from this block to ContBlock. Insert an entry
4304 // into the phi node for the edge with the value of RHSCond.
4305 CGF.EmitBlock(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00004306 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004307
Chris Lattner2da04b32007-08-24 05:35:26 +00004308 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00004309 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00004310}
4311
4312Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +00004313 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004314 CGF.EnsureInsertPoint();
Chris Lattner2da04b32007-08-24 05:35:26 +00004315 return Visit(E->getRHS());
4316}
4317
4318//===----------------------------------------------------------------------===//
4319// Other Operators
4320//===----------------------------------------------------------------------===//
4321
Chris Lattner3fd91f832008-11-12 08:55:54 +00004322/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
4323/// expression is cheap enough and side-effect-free enough to evaluate
4324/// unconditionally instead of conditionally. This is used to convert control
4325/// flow into selects in some cases.
Mike Stump53f9ded2009-11-03 23:25:48 +00004326static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
4327 CodeGenFunction &CGF) {
Chris Lattner56784f92011-04-16 23:15:35 +00004328 // Anything that is an integer or floating point constant is fine.
Nick Lewycky22e55a02013-11-08 23:00:12 +00004329 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
Mike Stump4a3999f2009-09-09 13:00:44 +00004330
Nick Lewycky22e55a02013-11-08 23:00:12 +00004331 // Even non-volatile automatic variables can't be evaluated unconditionally.
4332 // Referencing a thread_local may cause non-trivial initialization work to
4333 // occur. If we're inside a lambda and one of the variables is from the scope
4334 // outside the lambda, that function may have returned already. Reading its
4335 // locals is a bad idea. Also, these reads may introduce races there didn't
4336 // exist in the source-level program.
Chris Lattner3fd91f832008-11-12 08:55:54 +00004337}
4338
4339
Chris Lattner2da04b32007-08-24 05:35:26 +00004340Value *ScalarExprEmitter::
John McCallc07a0c72011-02-17 10:25:35 +00004341VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00004342 TestAndClearIgnoreResultAssign();
John McCallc07a0c72011-02-17 10:25:35 +00004343
4344 // Bind the common expression if necessary.
Eli Friedman48fd89a2012-01-06 20:42:20 +00004345 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCallc07a0c72011-02-17 10:25:35 +00004346
4347 Expr *condExpr = E->getCond();
4348 Expr *lhsExpr = E->getTrueExpr();
4349 Expr *rhsExpr = E->getFalseExpr();
4350
Chris Lattnercd439292008-11-12 08:04:58 +00004351 // If the condition constant folds and can be elided, try to avoid emitting
4352 // the condition and the dead arm.
Chris Lattner41c6ab52011-02-27 23:02:32 +00004353 bool CondExprBool;
4354 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00004355 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattner41c6ab52011-02-27 23:02:32 +00004356 if (!CondExprBool) std::swap(live, dead);
Mike Stump4a3999f2009-09-09 13:00:44 +00004357
Eli Friedman27ef75b2011-10-15 02:10:40 +00004358 // If the dead side doesn't have labels we need, just emit the Live part.
4359 if (!CGF.ContainsLabel(dead)) {
Justin Bogneref512b92014-01-06 22:27:43 +00004360 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00004361 CGF.incrementProfileCounter(E);
Eli Friedman27ef75b2011-10-15 02:10:40 +00004362 Value *Result = Visit(live);
4363
4364 // If the live part is a throw expression, it acts like it has a void
4365 // type, so evaluating it returns a null Value*. However, a conditional
4366 // with non-void type must return a non-null Value*.
4367 if (!Result && !E->getType()->isVoidType())
4368 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
4369
4370 return Result;
4371 }
Chris Lattnerd53e2332008-11-11 18:56:45 +00004372 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004373
Nate Begemanabb5a732010-09-20 22:41:17 +00004374 // OpenCL: If the condition is a vector, we can treat this condition like
4375 // the select function.
Craig Toppera97d7e72013-07-26 06:16:11 +00004376 if (CGF.getLangOpts().OpenCL
John McCallc07a0c72011-02-17 10:25:35 +00004377 && condExpr->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00004378 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004379
John McCallc07a0c72011-02-17 10:25:35 +00004380 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4381 llvm::Value *LHS = Visit(lhsExpr);
4382 llvm::Value *RHS = Visit(rhsExpr);
Craig Toppera97d7e72013-07-26 06:16:11 +00004383
Chris Lattner2192fe52011-07-18 04:24:23 +00004384 llvm::Type *condType = ConvertType(condExpr->getType());
4385 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Craig Toppera97d7e72013-07-26 06:16:11 +00004386
4387 unsigned numElem = vecTy->getNumElements();
Chris Lattner2192fe52011-07-18 04:24:23 +00004388 llvm::Type *elemType = vecTy->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00004389
Chris Lattner2d6b7b92012-01-25 05:34:41 +00004390 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begemanabb5a732010-09-20 22:41:17 +00004391 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
Craig Toppera97d7e72013-07-26 06:16:11 +00004392 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
Nate Begemanabb5a732010-09-20 22:41:17 +00004393 llvm::VectorType::get(elemType,
Craig Toppera97d7e72013-07-26 06:16:11 +00004394 numElem),
Nate Begemanabb5a732010-09-20 22:41:17 +00004395 "sext");
4396 llvm::Value *tmp2 = Builder.CreateNot(tmp);
Craig Toppera97d7e72013-07-26 06:16:11 +00004397
Nate Begemanabb5a732010-09-20 22:41:17 +00004398 // Cast float to int to perform ANDs if necessary.
4399 llvm::Value *RHSTmp = RHS;
4400 llvm::Value *LHSTmp = LHS;
4401 bool wasCast = false;
Chris Lattner2192fe52011-07-18 04:24:23 +00004402 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourneaac265c2012-05-29 00:35:18 +00004403 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begemanabb5a732010-09-20 22:41:17 +00004404 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
4405 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
4406 wasCast = true;
4407 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004408
Nate Begemanabb5a732010-09-20 22:41:17 +00004409 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
4410 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
4411 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
4412 if (wasCast)
4413 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
4414
4415 return tmp5;
4416 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004417
Erich Keane349636d2019-12-05 06:17:39 -08004418 if (condExpr->getType()->isVectorType()) {
4419 CGF.incrementProfileCounter(E);
4420
4421 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4422 llvm::Value *LHS = Visit(lhsExpr);
4423 llvm::Value *RHS = Visit(rhsExpr);
4424
4425 llvm::Type *CondType = ConvertType(condExpr->getType());
4426 auto *VecTy = cast<llvm::VectorType>(CondType);
4427 llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
4428
4429 CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
4430 return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
4431 }
4432
Chris Lattner3fd91f832008-11-12 08:55:54 +00004433 // If this is a really simple expression (like x ? 4 : 5), emit this as a
4434 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner9ce8a532008-11-16 06:16:27 +00004435 // safe to evaluate the LHS and RHS unconditionally.
John McCallc07a0c72011-02-17 10:25:35 +00004436 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
4437 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
4438 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
Vedant Kumar502bbfa2017-02-25 06:35:45 +00004439 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
4440
4441 CGF.incrementProfileCounter(E, StepV);
4442
John McCallc07a0c72011-02-17 10:25:35 +00004443 llvm::Value *LHS = Visit(lhsExpr);
4444 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman516c2ad2011-12-08 22:01:56 +00004445 if (!LHS) {
4446 // If the conditional has void type, make sure we return a null Value*.
4447 assert(!RHS && "LHS and RHS types must match");
Craig Topper8a13c412014-05-21 05:09:00 +00004448 return nullptr;
Eli Friedman516c2ad2011-12-08 22:01:56 +00004449 }
Chris Lattner3fd91f832008-11-12 08:55:54 +00004450 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
4451 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004452
Daniel Dunbard2a53a72008-11-12 10:13:37 +00004453 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
4454 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbara612e792008-11-13 01:38:36 +00004455 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCallce1de612011-01-26 04:00:11 +00004456
4457 CodeGenFunction::ConditionalEvaluation eval(CGF);
Justin Bogner66242d62015-04-23 23:06:47 +00004458 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
4459 CGF.getProfileCount(lhsExpr));
Anders Carlsson43c52cd2009-06-04 03:00:32 +00004460
Chris Lattner2da04b32007-08-24 05:35:26 +00004461 CGF.EmitBlock(LHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004462 CGF.incrementProfileCounter(E);
John McCallce1de612011-01-26 04:00:11 +00004463 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00004464 Value *LHS = Visit(lhsExpr);
John McCallce1de612011-01-26 04:00:11 +00004465 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004466
Chris Lattner2da04b32007-08-24 05:35:26 +00004467 LHSBlock = Builder.GetInsertBlock();
John McCallce1de612011-01-26 04:00:11 +00004468 Builder.CreateBr(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004469
Chris Lattner2da04b32007-08-24 05:35:26 +00004470 CGF.EmitBlock(RHSBlock);
John McCallce1de612011-01-26 04:00:11 +00004471 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00004472 Value *RHS = Visit(rhsExpr);
John McCallce1de612011-01-26 04:00:11 +00004473 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004474
John McCallce1de612011-01-26 04:00:11 +00004475 RHSBlock = Builder.GetInsertBlock();
Chris Lattner2da04b32007-08-24 05:35:26 +00004476 CGF.EmitBlock(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004477
Eli Friedmanf6c175b2009-12-07 20:25:53 +00004478 // If the LHS or RHS is a throw expression, it will be legitimately null.
4479 if (!LHS)
4480 return RHS;
4481 if (!RHS)
4482 return LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00004483
Chris Lattner2da04b32007-08-24 05:35:26 +00004484 // Create a PHI node for the real part.
Jay Foad20c0f022011-03-30 11:28:58 +00004485 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner2da04b32007-08-24 05:35:26 +00004486 PN->addIncoming(LHS, LHSBlock);
4487 PN->addIncoming(RHS, RHSBlock);
4488 return PN;
4489}
4490
4491Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman75807f22013-07-20 00:40:58 +00004492 return Visit(E->getChosenSubExpr());
Chris Lattner2da04b32007-08-24 05:35:26 +00004493}
4494
Chris Lattnerb6a7b582007-11-30 17:56:23 +00004495Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Richard Smitha1a808c2014-04-14 23:47:48 +00004496 QualType Ty = VE->getType();
Daniel Sanders59229dc2014-11-19 10:01:35 +00004497
Richard Smitha1a808c2014-04-14 23:47:48 +00004498 if (Ty->isVariablyModifiedType())
4499 CGF.EmitVariablyModifiedType(Ty);
4500
Charles Davisc7d5c942015-09-17 20:55:33 +00004501 Address ArgValue = Address::invalid();
4502 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
4503
Daniel Sanders59229dc2014-11-19 10:01:35 +00004504 llvm::Type *ArgTy = ConvertType(VE->getType());
Anders Carlsson13abd7e2008-11-04 05:30:00 +00004505
James Y Knight29b5f082016-02-24 02:59:33 +00004506 // If EmitVAArg fails, emit an error.
4507 if (!ArgPtr.isValid()) {
4508 CGF.ErrorUnsupported(VE, "va_arg expression");
4509 return llvm::UndefValue::get(ArgTy);
4510 }
Anders Carlsson13abd7e2008-11-04 05:30:00 +00004511
Mike Stumpdf0fe272009-05-29 15:46:01 +00004512 // FIXME Volatility.
Daniel Sanders59229dc2014-11-19 10:01:35 +00004513 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
4514
4515 // If EmitVAArg promoted the type, we must truncate it.
Daniel Sanderscdcb5802015-01-13 10:47:00 +00004516 if (ArgTy != Val->getType()) {
4517 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
4518 Val = Builder.CreateIntToPtr(Val, ArgTy);
4519 else
4520 Val = Builder.CreateTrunc(Val, ArgTy);
4521 }
Daniel Sanders59229dc2014-11-19 10:01:35 +00004522
4523 return Val;
Anders Carlsson7e13ab82007-10-15 20:28:48 +00004524}
4525
John McCall351762c2011-02-07 10:33:21 +00004526Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
4527 return CGF.EmitBlockLiteral(block);
Mike Stumpab3afd82009-02-12 18:29:15 +00004528}
4529
Yaxun Liuc5647012016-06-08 15:11:21 +00004530// Convert a vec3 to vec4, or vice versa.
4531static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
4532 Value *Src, unsigned NumElementsDst) {
4533 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
Benjamin Kramer6f64dac2020-04-15 12:41:54 +02004534 static constexpr int Mask[] = {0, 1, 2, -1};
4535 return Builder.CreateShuffleVector(Src, UnV,
4536 llvm::makeArrayRef(Mask, NumElementsDst));
Yaxun Liuc5647012016-06-08 15:11:21 +00004537}
4538
Yaxun Liuea6b7962016-10-03 14:41:50 +00004539// Create cast instructions for converting LLVM value \p Src to LLVM type \p
4540// DstTy. \p Src has the same size as \p DstTy. Both are single value types
4541// but could be scalar or vectors of different lengths, and either can be
4542// pointer.
4543// There are 4 cases:
4544// 1. non-pointer -> non-pointer : needs 1 bitcast
4545// 2. pointer -> pointer : needs 1 bitcast or addrspacecast
4546// 3. pointer -> non-pointer
4547// a) pointer -> intptr_t : needs 1 ptrtoint
4548// b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
4549// 4. non-pointer -> pointer
4550// a) intptr_t -> pointer : needs 1 inttoptr
4551// b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
4552// Note: for cases 3b and 4b two casts are required since LLVM casts do not
4553// allow casting directly between pointer types and non-integer non-pointer
4554// types.
4555static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
4556 const llvm::DataLayout &DL,
4557 Value *Src, llvm::Type *DstTy,
4558 StringRef Name = "") {
4559 auto SrcTy = Src->getType();
4560
4561 // Case 1.
4562 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
4563 return Builder.CreateBitCast(Src, DstTy, Name);
4564
4565 // Case 2.
4566 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
4567 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
4568
4569 // Case 3.
4570 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
4571 // Case 3b.
4572 if (!DstTy->isIntegerTy())
4573 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
4574 // Cases 3a and 3b.
4575 return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
4576 }
4577
4578 // Case 4b.
4579 if (!SrcTy->isIntegerTy())
4580 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
4581 // Cases 4a and 4b.
4582 return Builder.CreateIntToPtr(Src, DstTy, Name);
4583}
4584
Tanya Lattner55808c12011-06-04 00:47:47 +00004585Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
4586 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2192fe52011-07-18 04:24:23 +00004587 llvm::Type *DstTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00004588
Chris Lattner2192fe52011-07-18 04:24:23 +00004589 llvm::Type *SrcTy = Src->getType();
Yaxun Liuc5647012016-06-08 15:11:21 +00004590 unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
4591 cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
4592 unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
4593 cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
Craig Toppera97d7e72013-07-26 06:16:11 +00004594
Yaxun Liuc5647012016-06-08 15:11:21 +00004595 // Going from vec3 to non-vec3 is a special case and requires a shuffle
4596 // vector to get a vec4, then a bitcast if the target type is different.
4597 if (NumElementsSrc == 3 && NumElementsDst != 3) {
4598 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00004599
4600 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4601 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4602 DstTy);
4603 }
4604
Yaxun Liuc5647012016-06-08 15:11:21 +00004605 Src->setName("astype");
4606 return Src;
4607 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004608
Yaxun Liuc5647012016-06-08 15:11:21 +00004609 // Going from non-vec3 to vec3 is a special case and requires a bitcast
4610 // to vec4 if the original type is not vec4, then a shuffle vector to
4611 // get a vec3.
4612 if (NumElementsSrc != 3 && NumElementsDst == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00004613 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
Christopher Tetreaultf22fbe32020-04-13 12:30:53 -07004614 auto Vec4Ty = llvm::VectorType::get(
4615 cast<llvm::VectorType>(DstTy)->getElementType(), 4);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00004616 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4617 Vec4Ty);
4618 }
4619
Yaxun Liuc5647012016-06-08 15:11:21 +00004620 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
4621 Src->setName("astype");
4622 return Src;
Tanya Lattner55808c12011-06-04 00:47:47 +00004623 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004624
Sylvestre Ledru4644e9a2019-10-12 15:24:00 +00004625 return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
4626 Src, DstTy, "astype");
Tanya Lattner55808c12011-06-04 00:47:47 +00004627}
4628
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004629Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
4630 return CGF.EmitAtomicExpr(E).getScalarVal();
4631}
4632
Chris Lattner2da04b32007-08-24 05:35:26 +00004633//===----------------------------------------------------------------------===//
4634// Entry Point into this File
4635//===----------------------------------------------------------------------===//
4636
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004637/// Emit the computation of the specified expression of scalar type, ignoring
4638/// the result.
Mike Stumpdf0fe272009-05-29 15:46:01 +00004639Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
John McCall47fb9502013-03-07 21:37:08 +00004640 assert(E && hasScalarEvaluationKind(E->getType()) &&
Chris Lattner2da04b32007-08-24 05:35:26 +00004641 "Invalid scalar expression to emit");
Mike Stump4a3999f2009-09-09 13:00:44 +00004642
David Blaikie38b25912015-02-09 19:13:51 +00004643 return ScalarExprEmitter(*this, IgnoreResultAssign)
4644 .Visit(const_cast<Expr *>(E));
Chris Lattner2da04b32007-08-24 05:35:26 +00004645}
Chris Lattner3474c202007-08-26 06:48:56 +00004646
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004647/// Emit a conversion from the specified type to the specified destination type,
4648/// both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00004649Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004650 QualType DstTy,
4651 SourceLocation Loc) {
John McCall47fb9502013-03-07 21:37:08 +00004652 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
Chris Lattner3474c202007-08-26 06:48:56 +00004653 "Invalid scalar expression to emit");
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004654 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
Chris Lattner3474c202007-08-26 06:48:56 +00004655}
Chris Lattner42e6b812007-08-26 16:34:22 +00004656
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004657/// Emit a conversion from the specified complex type to the specified
4658/// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +00004659Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
4660 QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004661 QualType DstTy,
4662 SourceLocation Loc) {
John McCall47fb9502013-03-07 21:37:08 +00004663 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
Chris Lattner42e6b812007-08-26 16:34:22 +00004664 "Invalid complex -> scalar conversion");
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004665 return ScalarExprEmitter(*this)
4666 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
Chris Lattner42e6b812007-08-26 16:34:22 +00004667}
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00004668
Chris Lattner05dc78c2010-06-26 22:09:34 +00004669
4670llvm::Value *CodeGenFunction::
4671EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
4672 bool isInc, bool isPre) {
4673 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
4674}
4675
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004676LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004677 // object->isa or (*object).isa
4678 // Generate code as for: *(Class*)object
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00004679
4680 Expr *BaseExpr = E->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00004681 Address Addr = Address::invalid();
John McCall086a4642010-11-24 05:12:34 +00004682 if (BaseExpr->isRValue()) {
John McCall7f416cc2015-09-08 08:05:57 +00004683 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00004684 } else {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004685 Addr = EmitLValue(BaseExpr).getAddress(*this);
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00004686 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004687
John McCall7f416cc2015-09-08 08:05:57 +00004688 // Cast the address to Class*.
4689 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
4690 return MakeAddrLValue(Addr, E->getType());
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004691}
4692
Douglas Gregor914af212010-04-23 04:16:32 +00004693
John McCalla2342eb2010-12-05 02:00:02 +00004694LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor914af212010-04-23 04:16:32 +00004695 const CompoundAssignOperator *E) {
4696 ScalarExprEmitter Scalar(*this);
Craig Topper8a13c412014-05-21 05:09:00 +00004697 Value *Result = nullptr;
Douglas Gregor914af212010-04-23 04:16:32 +00004698 switch (E->getOpcode()) {
4699#define COMPOUND_OP(Op) \
John McCalle3027922010-08-25 11:45:40 +00004700 case BO_##Op##Assign: \
Douglas Gregor914af212010-04-23 04:16:32 +00004701 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004702 Result)
Douglas Gregor914af212010-04-23 04:16:32 +00004703 COMPOUND_OP(Mul);
4704 COMPOUND_OP(Div);
4705 COMPOUND_OP(Rem);
4706 COMPOUND_OP(Add);
4707 COMPOUND_OP(Sub);
4708 COMPOUND_OP(Shl);
4709 COMPOUND_OP(Shr);
4710 COMPOUND_OP(And);
4711 COMPOUND_OP(Xor);
4712 COMPOUND_OP(Or);
4713#undef COMPOUND_OP
Craig Toppera97d7e72013-07-26 06:16:11 +00004714
John McCalle3027922010-08-25 11:45:40 +00004715 case BO_PtrMemD:
4716 case BO_PtrMemI:
4717 case BO_Mul:
4718 case BO_Div:
4719 case BO_Rem:
4720 case BO_Add:
4721 case BO_Sub:
4722 case BO_Shl:
4723 case BO_Shr:
4724 case BO_LT:
4725 case BO_GT:
4726 case BO_LE:
4727 case BO_GE:
4728 case BO_EQ:
4729 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00004730 case BO_Cmp:
John McCalle3027922010-08-25 11:45:40 +00004731 case BO_And:
4732 case BO_Xor:
4733 case BO_Or:
4734 case BO_LAnd:
4735 case BO_LOr:
4736 case BO_Assign:
4737 case BO_Comma:
David Blaikie83d382b2011-09-23 05:06:16 +00004738 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor914af212010-04-23 04:16:32 +00004739 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004740
Douglas Gregor914af212010-04-23 04:16:32 +00004741 llvm_unreachable("Unhandled compound assignment operator");
4742}
Vedant Kumara125eb52017-06-01 19:22:18 +00004743
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004744struct GEPOffsetAndOverflow {
4745 // The total (signed) byte offset for the GEP.
4746 llvm::Value *TotalOffset;
4747 // The offset overflow flag - true if the total offset overflows.
4748 llvm::Value *OffsetOverflows;
4749};
Vedant Kumara125eb52017-06-01 19:22:18 +00004750
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004751/// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004752/// and compute the total offset it applies from it's base pointer BasePtr.
4753/// Returns offset in bytes and a boolean flag whether an overflow happened
4754/// during evaluation.
4755static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
4756 llvm::LLVMContext &VMContext,
4757 CodeGenModule &CGM,
Nikita Popov7c362b22020-02-16 17:57:18 +01004758 CGBuilderTy &Builder) {
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004759 const auto &DL = CGM.getDataLayout();
4760
4761 // The total (signed) byte offset for the GEP.
4762 llvm::Value *TotalOffset = nullptr;
4763
4764 // Was the GEP already reduced to a constant?
4765 if (isa<llvm::Constant>(GEPVal)) {
4766 // Compute the offset by casting both pointers to integers and subtracting:
4767 // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
4768 Value *BasePtr_int =
4769 Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
4770 Value *GEPVal_int =
4771 Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
4772 TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
4773 return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
4774 }
4775
Vedant Kumara125eb52017-06-01 19:22:18 +00004776 auto *GEP = cast<llvm::GEPOperator>(GEPVal);
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004777 assert(GEP->getPointerOperand() == BasePtr &&
4778 "BasePtr must be the the base of the GEP.");
Vedant Kumara125eb52017-06-01 19:22:18 +00004779 assert(GEP->isInBounds() && "Expected inbounds GEP");
4780
Vedant Kumara125eb52017-06-01 19:22:18 +00004781 auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
4782
4783 // Grab references to the signed add/mul overflow intrinsics for intptr_t.
4784 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4785 auto *SAddIntrinsic =
4786 CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
4787 auto *SMulIntrinsic =
4788 CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
4789
Vedant Kumara125eb52017-06-01 19:22:18 +00004790 // The offset overflow flag - true if the total offset overflows.
4791 llvm::Value *OffsetOverflows = Builder.getFalse();
4792
4793 /// Return the result of the given binary operation.
4794 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
4795 llvm::Value *RHS) -> llvm::Value * {
Davide Italiano77378e42017-06-01 23:55:18 +00004796 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
Vedant Kumara125eb52017-06-01 19:22:18 +00004797
4798 // If the operands are constants, return a constant result.
4799 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
4800 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
4801 llvm::APInt N;
4802 bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
4803 /*Signed=*/true, N);
4804 if (HasOverflow)
4805 OffsetOverflows = Builder.getTrue();
4806 return llvm::ConstantInt::get(VMContext, N);
4807 }
4808 }
4809
4810 // Otherwise, compute the result with checked arithmetic.
4811 auto *ResultAndOverflow = Builder.CreateCall(
4812 (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
4813 OffsetOverflows = Builder.CreateOr(
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004814 Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
Vedant Kumara125eb52017-06-01 19:22:18 +00004815 return Builder.CreateExtractValue(ResultAndOverflow, 0);
4816 };
4817
4818 // Determine the total byte offset by looking at each GEP operand.
4819 for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
4820 GTI != GTE; ++GTI) {
4821 llvm::Value *LocalOffset;
4822 auto *Index = GTI.getOperand();
4823 // Compute the local offset contributed by this indexing step:
4824 if (auto *STy = GTI.getStructTypeOrNull()) {
4825 // For struct indexing, the local offset is the byte position of the
4826 // specified field.
4827 unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
4828 LocalOffset = llvm::ConstantInt::get(
4829 IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
4830 } else {
4831 // Otherwise this is array-like indexing. The local offset is the index
4832 // multiplied by the element size.
4833 auto *ElementSize = llvm::ConstantInt::get(
4834 IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
4835 auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
4836 LocalOffset = eval(BO_Mul, ElementSize, IndexS);
4837 }
4838
4839 // If this is the first offset, set it as the total offset. Otherwise, add
4840 // the local offset into the running total.
4841 if (!TotalOffset || TotalOffset == Zero)
4842 TotalOffset = LocalOffset;
4843 else
4844 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
4845 }
4846
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004847 return {TotalOffset, OffsetOverflows};
4848}
4849
4850Value *
4851CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
4852 bool SignedIndices, bool IsSubtraction,
4853 SourceLocation Loc, const Twine &Name) {
4854 Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
4855
4856 // If the pointer overflow sanitizer isn't enabled, do nothing.
4857 if (!SanOpts.has(SanitizerKind::PointerOverflow))
4858 return GEPVal;
4859
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004860 llvm::Type *PtrTy = Ptr->getType();
4861
4862 // Perform nullptr-and-offset check unless the nullptr is defined.
4863 bool PerformNullCheck = !NullPointerIsDefined(
4864 Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
4865 // Check for overflows unless the GEP got constant-folded,
4866 // and only in the default address space
4867 bool PerformOverflowCheck =
4868 !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
4869
4870 if (!(PerformNullCheck || PerformOverflowCheck))
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004871 return GEPVal;
4872
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004873 const auto &DL = CGM.getDataLayout();
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004874
4875 SanitizerScope SanScope(this);
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004876 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004877
4878 GEPOffsetAndOverflow EvaluatedGEP =
4879 EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
4880
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004881 assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
4882 EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
4883 "If the offset got constant-folded, we don't expect that there was an "
4884 "overflow.");
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004885
4886 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4887
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004888 // Common case: if the total offset is zero, and we are using C++ semantics,
4889 // where nullptr+0 is defined, don't emit a check.
4890 if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
Vedant Kumara125eb52017-06-01 19:22:18 +00004891 return GEPVal;
4892
4893 // Now that we've computed the total offset, add it to the base pointer (with
4894 // wrapping semantics).
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004895 auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004896 auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
Vedant Kumara125eb52017-06-01 19:22:18 +00004897
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004898 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
Roman Lebedevf1d33842019-09-06 14:19:04 +00004899
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004900 if (PerformNullCheck) {
4901 // In C++, if the base pointer evaluates to a null pointer value,
4902 // the only valid pointer this inbounds GEP can produce is also
4903 // a null pointer, so the offset must also evaluate to zero.
4904 // Likewise, if we have non-zero base pointer, we can not get null pointer
4905 // as a result, so the offset can not be -intptr_t(BasePtr).
4906 // In other words, both pointers are either null, or both are non-null,
4907 // or the behaviour is undefined.
4908 //
4909 // C, however, is more strict in this regard, and gives more
4910 // optimization opportunities: in C, additionally, nullptr+0 is undefined.
4911 // So both the input to the 'gep inbounds' AND the output must not be null.
4912 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
4913 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
4914 auto *Valid =
4915 CGM.getLangOpts().CPlusPlus
4916 ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
4917 : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
4918 Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004919 }
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004920
4921 if (PerformOverflowCheck) {
4922 // The GEP is valid if:
4923 // 1) The total offset doesn't overflow, and
4924 // 2) The sign of the difference between the computed address and the base
4925 // pointer matches the sign of the total offset.
4926 llvm::Value *ValidGEP;
4927 auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
4928 if (SignedIndices) {
4929 // GEP is computed as `unsigned base + signed offset`, therefore:
4930 // * If offset was positive, then the computed pointer can not be
4931 // [unsigned] less than the base pointer, unless it overflowed.
4932 // * If offset was negative, then the computed pointer can not be
4933 // [unsigned] greater than the bas pointere, unless it overflowed.
4934 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4935 auto *PosOrZeroOffset =
4936 Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
4937 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
4938 ValidGEP =
4939 Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
4940 } else if (!IsSubtraction) {
4941 // GEP is computed as `unsigned base + unsigned offset`, therefore the
4942 // computed pointer can not be [unsigned] less than base pointer,
4943 // unless there was an overflow.
4944 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
4945 ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4946 } else {
4947 // GEP is computed as `unsigned base - unsigned offset`, therefore the
4948 // computed pointer can not be [unsigned] greater than base pointer,
4949 // unless there was an overflow.
4950 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
4951 ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
4952 }
4953 ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
4954 Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
4955 }
Roman Lebedevf1d33842019-09-06 14:19:04 +00004956
4957 assert(!Checks.empty() && "Should have produced some checks.");
Vedant Kumara125eb52017-06-01 19:22:18 +00004958
4959 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
4960 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
4961 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
Roman Lebedevf1d33842019-09-06 14:19:04 +00004962 EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
Vedant Kumara125eb52017-06-01 19:22:18 +00004963
4964 return GEPVal;
4965}