blob: fa5aa702440e7a3cae053a10150088d98016ad25 [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
Craig Topperf2f1a092016-07-08 02:17:35 +00001312 unsigned NumElements = DstTy->getVectorNumElements();
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.
1330 llvm::Type *SrcElementTy = SrcTy->getVectorElementType();
1331 llvm::Type *DstElementTy = DstTy->getVectorElementType();
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
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001653 SmallVector<llvm::Constant*, 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())
1658 indices.push_back(llvm::UndefValue::get(CGF.Int32Ty));
1659 else
1660 indices.push_back(Builder.getInt32(Idx.getZExtValue()));
Nate Begemana0110022010-06-08 00:16:34 +00001661 }
1662
Chris Lattner91c08ad2011-02-15 00:14:06 +00001663 Value *SV = llvm::ConstantVector::get(indices);
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001664 return Builder.CreateShuffleVector(V1, V2, SV, "shuffle");
1665}
Hal Finkelc4d7c822013-09-18 03:29:45 +00001666
1667Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
1668 QualType SrcType = E->getSrcExpr()->getType(),
1669 DstType = E->getType();
1670
1671 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
1672
1673 SrcType = CGF.getContext().getCanonicalType(SrcType);
1674 DstType = CGF.getContext().getCanonicalType(DstType);
1675 if (SrcType == DstType) return Src;
1676
1677 assert(SrcType->isVectorType() &&
1678 "ConvertVector source type must be a vector");
1679 assert(DstType->isVectorType() &&
1680 "ConvertVector destination type must be a vector");
1681
1682 llvm::Type *SrcTy = Src->getType();
1683 llvm::Type *DstTy = ConvertType(DstType);
1684
1685 // Ignore conversions like int -> uint.
1686 if (SrcTy == DstTy)
1687 return Src;
1688
Simon Pilgrime0712012019-10-02 15:31:25 +00001689 QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
1690 DstEltType = DstType->castAs<VectorType>()->getElementType();
Hal Finkelc4d7c822013-09-18 03:29:45 +00001691
1692 assert(SrcTy->isVectorTy() &&
1693 "ConvertVector source IR type must be a vector");
1694 assert(DstTy->isVectorTy() &&
1695 "ConvertVector destination IR type must be a vector");
1696
1697 llvm::Type *SrcEltTy = SrcTy->getVectorElementType(),
1698 *DstEltTy = DstTy->getVectorElementType();
1699
1700 if (DstEltType->isBooleanType()) {
1701 assert((SrcEltTy->isFloatingPointTy() ||
1702 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
1703
1704 llvm::Value *Zero = llvm::Constant::getNullValue(SrcTy);
1705 if (SrcEltTy->isFloatingPointTy()) {
1706 return Builder.CreateFCmpUNE(Src, Zero, "tobool");
1707 } else {
1708 return Builder.CreateICmpNE(Src, Zero, "tobool");
1709 }
1710 }
1711
1712 // We have the arithmetic types: real int/float.
Craig Topper8a13c412014-05-21 05:09:00 +00001713 Value *Res = nullptr;
Hal Finkelc4d7c822013-09-18 03:29:45 +00001714
1715 if (isa<llvm::IntegerType>(SrcEltTy)) {
1716 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
1717 if (isa<llvm::IntegerType>(DstEltTy))
1718 Res = Builder.CreateIntCast(Src, DstTy, InputSigned, "conv");
1719 else if (InputSigned)
1720 Res = Builder.CreateSIToFP(Src, DstTy, "conv");
1721 else
1722 Res = Builder.CreateUIToFP(Src, DstTy, "conv");
1723 } else if (isa<llvm::IntegerType>(DstEltTy)) {
1724 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
1725 if (DstEltType->isSignedIntegerOrEnumerationType())
1726 Res = Builder.CreateFPToSI(Src, DstTy, "conv");
1727 else
1728 Res = Builder.CreateFPToUI(Src, DstTy, "conv");
1729 } else {
1730 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
1731 "Unknown real conversion");
1732 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
1733 Res = Builder.CreateFPTrunc(Src, DstTy, "conv");
1734 else
1735 Res = Builder.CreateFPExt(Src, DstTy, "conv");
1736 }
1737
1738 return Res;
1739}
1740
Eli Friedmancb422f12009-11-26 03:22:21 +00001741Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
Alex Lorenz6cc83172017-08-25 10:07:00 +00001742 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E)) {
1743 CGF.EmitIgnoredExpr(E->getBase());
Volodymyr Sapsaief1899b2018-11-01 21:57:05 +00001744 return CGF.emitScalarConstant(Constant, E);
Alex Lorenz6cc83172017-08-25 10:07:00 +00001745 } else {
Fangrui Song407659a2018-11-30 23:41:18 +00001746 Expr::EvalResult Result;
1747 if (E->EvaluateAsInt(Result, CGF.getContext(), Expr::SE_AllowSideEffects)) {
1748 llvm::APSInt Value = Result.Val.getInt();
Alex Lorenz6cc83172017-08-25 10:07:00 +00001749 CGF.EmitIgnoredExpr(E->getBase());
1750 return Builder.getInt(Value);
1751 }
Eli Friedmancb422f12009-11-26 03:22:21 +00001752 }
Devang Patel44b8bf02010-10-04 21:46:04 +00001753
Eli Friedmancb422f12009-11-26 03:22:21 +00001754 return EmitLoadOfLValue(E);
1755}
Eli Friedmana1b4ed82008-05-14 19:38:39 +00001756
Chris Lattner2da04b32007-08-24 05:35:26 +00001757Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00001758 TestAndClearIgnoreResultAssign();
1759
Chris Lattner2da04b32007-08-24 05:35:26 +00001760 // Emit subscript expressions in rvalue context's. For most cases, this just
1761 // loads the lvalue formed by the subscript expr. However, we have to be
1762 // careful, because the base of a vector subscript is occasionally an rvalue,
1763 // so we can't get it as an lvalue.
1764 if (!E->getBase()->getType()->isVectorType())
1765 return EmitLoadOfLValue(E);
Mike Stump4a3999f2009-09-09 13:00:44 +00001766
Chris Lattner2da04b32007-08-24 05:35:26 +00001767 // Handle the vector case. The base must be a vector, the index must be an
1768 // integer value.
1769 Value *Base = Visit(E->getBase());
1770 Value *Idx = Visit(E->getIdx());
Richard Smith539e4a72013-02-23 02:53:19 +00001771 QualType IdxTy = E->getIdx()->getType();
1772
Alexey Samsonovedf99a92014-11-07 22:29:38 +00001773 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00001774 CGF.EmitBoundsCheck(E, E->getBase(), Idx, IdxTy, /*Accessed*/true);
1775
Chris Lattner2da04b32007-08-24 05:35:26 +00001776 return Builder.CreateExtractElement(Base, Idx, "vecext");
1777}
1778
Nate Begeman19351632009-10-18 20:10:40 +00001779static llvm::Constant *getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
Chris Lattner2192fe52011-07-18 04:24:23 +00001780 unsigned Off, llvm::Type *I32Ty) {
Nate Begeman19351632009-10-18 20:10:40 +00001781 int MV = SVI->getMaskValue(Idx);
Craig Toppera97d7e72013-07-26 06:16:11 +00001782 if (MV == -1)
Nate Begeman19351632009-10-18 20:10:40 +00001783 return llvm::UndefValue::get(I32Ty);
1784 return llvm::ConstantInt::get(I32Ty, Off+MV);
1785}
1786
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001787static llvm::Constant *getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
1788 if (C->getBitWidth() != 32) {
1789 assert(llvm::ConstantInt::isValueValidForType(I32Ty,
1790 C->getZExtValue()) &&
1791 "Index operand too large for shufflevector mask!");
1792 return llvm::ConstantInt::get(I32Ty, C->getZExtValue());
1793 }
1794 return C;
1795}
1796
Nate Begeman19351632009-10-18 20:10:40 +00001797Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
1798 bool Ignore = TestAndClearIgnoreResultAssign();
1799 (void)Ignore;
1800 assert (Ignore == false && "init list ignored");
1801 unsigned NumInitElements = E->getNumInits();
Craig Toppera97d7e72013-07-26 06:16:11 +00001802
Nate Begeman19351632009-10-18 20:10:40 +00001803 if (E->hadArrayRangeDesignator())
1804 CGF.ErrorUnsupported(E, "GNU array range designator extension");
Craig Toppera97d7e72013-07-26 06:16:11 +00001805
Chris Lattner2192fe52011-07-18 04:24:23 +00001806 llvm::VectorType *VType =
Nate Begeman19351632009-10-18 20:10:40 +00001807 dyn_cast<llvm::VectorType>(ConvertType(E->getType()));
Craig Toppera97d7e72013-07-26 06:16:11 +00001808
Sebastian Redl12757ab2011-09-24 17:48:14 +00001809 if (!VType) {
1810 if (NumInitElements == 0) {
1811 // C++11 value-initialization for the scalar.
1812 return EmitNullValue(E->getType());
1813 }
1814 // We have a scalar in braces. Just use the first element.
Nate Begeman19351632009-10-18 20:10:40 +00001815 return Visit(E->getInit(0));
Sebastian Redl12757ab2011-09-24 17:48:14 +00001816 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001817
Nate Begeman19351632009-10-18 20:10:40 +00001818 unsigned ResElts = VType->getNumElements();
Craig Toppera97d7e72013-07-26 06:16:11 +00001819
1820 // Loop over initializers collecting the Value for each, and remembering
Nate Begeman19351632009-10-18 20:10:40 +00001821 // whether the source was swizzle (ExtVectorElementExpr). This will allow
1822 // us to fold the shuffle for the swizzle into the shuffle for the vector
1823 // initializer, since LLVM optimizers generally do not want to touch
1824 // shuffles.
1825 unsigned CurIdx = 0;
1826 bool VIsUndefShuffle = false;
1827 llvm::Value *V = llvm::UndefValue::get(VType);
1828 for (unsigned i = 0; i != NumInitElements; ++i) {
1829 Expr *IE = E->getInit(i);
1830 Value *Init = Visit(IE);
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001831 SmallVector<llvm::Constant*, 16> Args;
Craig Toppera97d7e72013-07-26 06:16:11 +00001832
Chris Lattner2192fe52011-07-18 04:24:23 +00001833 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Init->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001834
Nate Begeman19351632009-10-18 20:10:40 +00001835 // Handle scalar elements. If the scalar initializer is actually one
Craig Toppera97d7e72013-07-26 06:16:11 +00001836 // element of a different vector of the same width, use shuffle instead of
Nate Begeman19351632009-10-18 20:10:40 +00001837 // extract+insert.
1838 if (!VVT) {
1839 if (isa<ExtVectorElementExpr>(IE)) {
1840 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Init);
1841
1842 if (EI->getVectorOperandType()->getNumElements() == ResElts) {
1843 llvm::ConstantInt *C = cast<llvm::ConstantInt>(EI->getIndexOperand());
Craig Topper8a13c412014-05-21 05:09:00 +00001844 Value *LHS = nullptr, *RHS = nullptr;
Nate Begeman19351632009-10-18 20:10:40 +00001845 if (CurIdx == 0) {
1846 // insert into undef -> shuffle (src, undef)
Simon Pilgrim4034b9f2015-08-02 15:28:10 +00001847 // shufflemask must use an i32
1848 Args.push_back(getAsInt32(C, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001849 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001850
1851 LHS = EI->getVectorOperand();
1852 RHS = V;
1853 VIsUndefShuffle = true;
1854 } else if (VIsUndefShuffle) {
1855 // insert into undefshuffle && size match -> shuffle (v, src)
1856 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(V);
1857 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001858 Args.push_back(getMaskElt(SVV, j, 0, CGF.Int32Ty));
Chris Lattner2531eb42011-04-19 22:55:03 +00001859 Args.push_back(Builder.getInt32(ResElts + C->getZExtValue()));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001860 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
1861
Nate Begeman19351632009-10-18 20:10:40 +00001862 LHS = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1863 RHS = EI->getVectorOperand();
1864 VIsUndefShuffle = false;
1865 }
1866 if (!Args.empty()) {
Chris Lattner91c08ad2011-02-15 00:14:06 +00001867 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001868 V = Builder.CreateShuffleVector(LHS, RHS, Mask);
1869 ++CurIdx;
1870 continue;
1871 }
1872 }
1873 }
Chris Lattner2531eb42011-04-19 22:55:03 +00001874 V = Builder.CreateInsertElement(V, Init, Builder.getInt32(CurIdx),
1875 "vecinit");
Nate Begeman19351632009-10-18 20:10:40 +00001876 VIsUndefShuffle = false;
1877 ++CurIdx;
1878 continue;
1879 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001880
Nate Begeman19351632009-10-18 20:10:40 +00001881 unsigned InitElts = VVT->getNumElements();
1882
Craig Toppera97d7e72013-07-26 06:16:11 +00001883 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
Nate Begeman19351632009-10-18 20:10:40 +00001884 // input is the same width as the vector being constructed, generate an
1885 // optimized shuffle of the swizzle input into the result.
Nate Begemanb8326be2009-10-25 02:26:01 +00001886 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
Nate Begeman19351632009-10-18 20:10:40 +00001887 if (isa<ExtVectorElementExpr>(IE)) {
1888 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Init);
1889 Value *SVOp = SVI->getOperand(0);
Chris Lattner2192fe52011-07-18 04:24:23 +00001890 llvm::VectorType *OpTy = cast<llvm::VectorType>(SVOp->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00001891
Nate Begeman19351632009-10-18 20:10:40 +00001892 if (OpTy->getNumElements() == ResElts) {
Nate Begeman19351632009-10-18 20:10:40 +00001893 for (unsigned j = 0; j != CurIdx; ++j) {
1894 // If the current vector initializer is a shuffle with undef, merge
1895 // this shuffle directly into it.
1896 if (VIsUndefShuffle) {
1897 Args.push_back(getMaskElt(cast<llvm::ShuffleVectorInst>(V), j, 0,
Chris Lattner5e016ae2010-06-27 07:15:29 +00001898 CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001899 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00001900 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001901 }
1902 }
1903 for (unsigned j = 0, je = InitElts; j != je; ++j)
Chris Lattner5e016ae2010-06-27 07:15:29 +00001904 Args.push_back(getMaskElt(SVI, j, Offset, CGF.Int32Ty));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001905 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001906
1907 if (VIsUndefShuffle)
1908 V = cast<llvm::ShuffleVectorInst>(V)->getOperand(0);
1909
1910 Init = SVOp;
1911 }
1912 }
1913
1914 // Extend init to result vector length, and then shuffle its contribution
1915 // to the vector initializer into V.
1916 if (Args.empty()) {
1917 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001918 Args.push_back(Builder.getInt32(j));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001919 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Chris Lattner91c08ad2011-02-15 00:14:06 +00001920 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001921 Init = Builder.CreateShuffleVector(Init, llvm::UndefValue::get(VVT),
Nate Begemanb8326be2009-10-25 02:26:01 +00001922 Mask, "vext");
Nate Begeman19351632009-10-18 20:10:40 +00001923
1924 Args.clear();
1925 for (unsigned j = 0; j != CurIdx; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001926 Args.push_back(Builder.getInt32(j));
Nate Begeman19351632009-10-18 20:10:40 +00001927 for (unsigned j = 0; j != InitElts; ++j)
Chris Lattner2531eb42011-04-19 22:55:03 +00001928 Args.push_back(Builder.getInt32(j+Offset));
Benjamin Kramer8001f742012-02-14 12:06:21 +00001929 Args.resize(ResElts, llvm::UndefValue::get(CGF.Int32Ty));
Nate Begeman19351632009-10-18 20:10:40 +00001930 }
1931
1932 // If V is undef, make sure it ends up on the RHS of the shuffle to aid
1933 // merging subsequent shuffles into this one.
1934 if (CurIdx == 0)
1935 std::swap(V, Init);
Chris Lattner91c08ad2011-02-15 00:14:06 +00001936 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
Nate Begeman19351632009-10-18 20:10:40 +00001937 V = Builder.CreateShuffleVector(V, Init, Mask, "vecinit");
1938 VIsUndefShuffle = isa<llvm::UndefValue>(Init);
1939 CurIdx += InitElts;
1940 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001941
Nate Begeman19351632009-10-18 20:10:40 +00001942 // FIXME: evaluate codegen vs. shuffling against constant null vector.
1943 // Emit remaining default initializers.
Chris Lattner2192fe52011-07-18 04:24:23 +00001944 llvm::Type *EltTy = VType->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00001945
Nate Begeman19351632009-10-18 20:10:40 +00001946 // Emit remaining default initializers
1947 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
Chris Lattner2531eb42011-04-19 22:55:03 +00001948 Value *Idx = Builder.getInt32(CurIdx);
Nate Begeman19351632009-10-18 20:10:40 +00001949 llvm::Value *Init = llvm::Constant::getNullValue(EltTy);
1950 V = Builder.CreateInsertElement(V, Init, Idx, "vecinit");
1951 }
1952 return V;
1953}
1954
John McCall7f416cc2015-09-08 08:05:57 +00001955bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001956 const Expr *E = CE->getSubExpr();
John McCalld9c7c6562010-03-30 23:58:03 +00001957
John McCalle3027922010-08-25 11:45:40 +00001958 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
John McCalld9c7c6562010-03-30 23:58:03 +00001959 return false;
Craig Toppera97d7e72013-07-26 06:16:11 +00001960
John McCall7f416cc2015-09-08 08:05:57 +00001961 if (isa<CXXThisExpr>(E->IgnoreParens())) {
Anders Carlsson8c793172009-11-23 17:57:54 +00001962 // We always assume that 'this' is never null.
1963 return false;
1964 }
Craig Toppera97d7e72013-07-26 06:16:11 +00001965
Anders Carlsson8c793172009-11-23 17:57:54 +00001966 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Sebastian Redlc57d34b2010-07-20 04:20:21 +00001967 // And that glvalue casts are never null.
John McCall2536c6d2010-08-25 10:28:54 +00001968 if (ICE->getValueKind() != VK_RValue)
Anders Carlsson8c793172009-11-23 17:57:54 +00001969 return false;
1970 }
1971
1972 return true;
1973}
1974
Chris Lattner2da04b32007-08-24 05:35:26 +00001975// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
1976// have to handle a more broad range of conversions than explicit casts, as they
1977// handle things like function to ptr-to-function decay etc.
John McCall23c29fe2011-06-24 21:55:10 +00001978Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
Eli Friedmane96f1d32009-11-27 04:41:50 +00001979 Expr *E = CE->getSubExpr();
Anders Carlsson8c978b42009-09-22 22:00:46 +00001980 QualType DestTy = CE->getType();
John McCalle3027922010-08-25 11:45:40 +00001981 CastKind Kind = CE->getCastKind();
Craig Toppera97d7e72013-07-26 06:16:11 +00001982
John McCalle399e5b2016-01-27 18:32:30 +00001983 // These cases are generally not written to ignore the result of
1984 // evaluating their sub-expressions, so we clear this now.
1985 bool Ignored = TestAndClearIgnoreResultAssign();
Mike Stump4a3999f2009-09-09 13:00:44 +00001986
Eli Friedman0dfc6802009-11-27 02:07:44 +00001987 // Since almost all cast kinds apply to scalars, this switch doesn't have
1988 // a default case, so the compiler will warn on a missing case. The cases
1989 // are in the same order as in the CastKind enum.
Anders Carlsson3df53bc2009-08-24 18:26:39 +00001990 switch (Kind) {
John McCall8cb679e2010-11-15 09:13:47 +00001991 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
Eli Friedman34866c72012-08-31 00:14:07 +00001992 case CK_BuiltinFnToFnPtr:
1993 llvm_unreachable("builtin functions are handled elsewhere");
1994
Craig Toppera97d7e72013-07-26 06:16:11 +00001995 case CK_LValueBitCast:
John McCalle3027922010-08-25 11:45:40 +00001996 case CK_ObjCObjectLValueCast: {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08001997 Address Addr = EmitLValue(E).getAddress(CGF);
Alexey Bataevf2440332015-10-07 10:22:08 +00001998 Addr = Builder.CreateElementBitCast(Addr, CGF.ConvertTypeForMem(DestTy));
John McCall7f416cc2015-09-08 08:05:57 +00001999 LValue LV = CGF.MakeAddrLValue(Addr, DestTy);
2000 return EmitLoadOfLValue(LV, CE->getExprLoc());
Douglas Gregor51954272010-07-13 23:17:26 +00002001 }
John McCallcd78e802011-09-10 01:16:55 +00002002
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00002003 case CK_LValueToRValueBitCast: {
2004 LValue SourceLVal = CGF.EmitLValue(E);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002005 Address Addr = Builder.CreateElementBitCast(SourceLVal.getAddress(CGF),
Erik Pilkingtoneee944e2019-07-02 18:28:13 +00002006 CGF.ConvertTypeForMem(DestTy));
2007 LValue DestLV = CGF.MakeAddrLValue(Addr, DestTy);
2008 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2009 return EmitLoadOfLValue(DestLV, CE->getExprLoc());
2010 }
2011
John McCall9320b872011-09-09 05:25:32 +00002012 case CK_CPointerToObjCPointerCast:
2013 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00002014 case CK_AnyPointerToBlockPointerCast:
2015 case CK_BitCast: {
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00002016 Value *Src = Visit(const_cast<Expr*>(E));
David Tweede1468322013-12-11 13:39:46 +00002017 llvm::Type *SrcTy = Src->getType();
2018 llvm::Type *DstTy = ConvertType(DestTy);
Bob Wilson95a27b02014-02-17 19:20:59 +00002019 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
David Tweede1468322013-12-11 13:39:46 +00002020 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00002021 llvm_unreachable("wrong cast for pointers in different address spaces"
2022 "(must be an address space cast)!");
David Tweede1468322013-12-11 13:39:46 +00002023 }
Peter Collingbourned2926c92015-03-14 02:42:25 +00002024
2025 if (CGF.SanOpts.has(SanitizerKind::CFIUnrelatedCast)) {
2026 if (auto PT = DestTy->getAs<PointerType>())
2027 CGF.EmitVTablePtrCheckForCast(PT->getPointeeType(), Src,
Peter Collingbourne6708c4a2015-06-19 01:51:54 +00002028 /*MayBeNull=*/true,
2029 CodeGenFunction::CFITCK_UnrelatedCast,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002030 CE->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00002031 }
2032
Piotr Padlewski07058292018-07-02 19:21:36 +00002033 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2034 const QualType SrcType = E->getType();
2035
2036 if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
2037 // Casting to pointer that could carry dynamic information (provided by
2038 // invariant.group) requires launder.
2039 Src = Builder.CreateLaunderInvariantGroup(Src);
2040 } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
2041 // Casting to pointer that does not carry dynamic information (provided
2042 // by invariant.group) requires stripping it. Note that we don't do it
2043 // if the source could not be dynamic type and destination could be
2044 // dynamic because dynamic information is already laundered. It is
2045 // because launder(strip(src)) == launder(src), so there is no need to
2046 // add extra strip before launder.
2047 Src = Builder.CreateStripInvariantGroup(Src);
2048 }
2049 }
2050
Amy Huang301a5bb2019-05-02 20:07:35 +00002051 // Update heapallocsite metadata when there is an explicit cast.
2052 if (llvm::CallInst *CI = dyn_cast<llvm::CallInst>(Src))
2053 if (CI->getMetadata("heapallocsite") && isa<ExplicitCastExpr>(CE))
2054 CGF.getDebugInfo()->
2055 addHeapAllocSiteMetadata(CI, CE->getType(), CE->getExprLoc());
2056
David Tweede1468322013-12-11 13:39:46 +00002057 return Builder.CreateBitCast(Src, DstTy);
2058 }
2059 case CK_AddressSpaceConversion: {
Yaxun Liu402804b2016-12-15 08:09:08 +00002060 Expr::EvalResult Result;
2061 if (E->EvaluateAsRValue(Result, CGF.getContext()) &&
2062 Result.Val.isNullPointer()) {
2063 // If E has side effect, it is emitted even if its final result is a
2064 // null pointer. In that case, a DCE pass should be able to
2065 // eliminate the useless instructions emitted during translating E.
2066 if (Result.HasSideEffects)
2067 Visit(E);
2068 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(
2069 ConvertType(DestTy)), DestTy);
2070 }
Yaxun Liub7b6d0f2016-04-12 19:03:49 +00002071 // Since target may map different address spaces in AST to the same address
2072 // space, an address space conversion may end up as a bitcast.
Yaxun Liu6d96f1632017-05-18 18:51:09 +00002073 return CGF.CGM.getTargetCodeGenInfo().performAddrSpaceCast(
2074 CGF, Visit(E), E->getType()->getPointeeType().getAddressSpace(),
2075 DestTy->getPointeeType().getAddressSpace(), ConvertType(DestTy));
Anders Carlssonf1ae6d42009-09-01 20:52:42 +00002076 }
David Chisnallfa35df62012-01-16 17:27:18 +00002077 case CK_AtomicToNonAtomic:
2078 case CK_NonAtomicToAtomic:
John McCalle3027922010-08-25 11:45:40 +00002079 case CK_NoOp:
2080 case CK_UserDefinedConversion:
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002081 return Visit(const_cast<Expr*>(E));
Mike Stump4a3999f2009-09-09 13:00:44 +00002082
John McCalle3027922010-08-25 11:45:40 +00002083 case CK_BaseToDerived: {
Jordan Rose7bb26112012-10-03 01:08:28 +00002084 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2085 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2086
John McCall7f416cc2015-09-08 08:05:57 +00002087 Address Base = CGF.EmitPointerWithAlignment(E);
2088 Address Derived =
2089 CGF.GetAddressOfDerivedClass(Base, DerivedClassDecl,
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00002090 CE->path_begin(), CE->path_end(),
John McCall7f416cc2015-09-08 08:05:57 +00002091 CGF.ShouldNullCheckClassCastValue(CE));
Filipe Cabecinhas178a8df2013-08-08 01:08:17 +00002092
Richard Smith2c5868c2013-02-13 21:18:23 +00002093 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2094 // performed and the object is not of the derived type.
Alexey Samsonovac4afe42014-07-07 23:59:57 +00002095 if (CGF.sanitizePerformTypeCheck())
Richard Smith2c5868c2013-02-13 21:18:23 +00002096 CGF.EmitTypeCheck(CodeGenFunction::TCK_DowncastPointer, CE->getExprLoc(),
John McCall7f416cc2015-09-08 08:05:57 +00002097 Derived.getPointer(), DestTy->getPointeeType());
Richard Smith2c5868c2013-02-13 21:18:23 +00002098
Peter Collingbourned2926c92015-03-14 02:42:25 +00002099 if (CGF.SanOpts.has(SanitizerKind::CFIDerivedCast))
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002100 CGF.EmitVTablePtrCheckForCast(
2101 DestTy->getPointeeType(), Derived.getPointer(),
2102 /*MayBeNull=*/true, CodeGenFunction::CFITCK_DerivedCast,
2103 CE->getBeginLoc());
Peter Collingbourned2926c92015-03-14 02:42:25 +00002104
John McCall7f416cc2015-09-08 08:05:57 +00002105 return Derived.getPointer();
Anders Carlsson8c793172009-11-23 17:57:54 +00002106 }
John McCalle3027922010-08-25 11:45:40 +00002107 case CK_UncheckedDerivedToBase:
2108 case CK_DerivedToBase: {
John McCall7f416cc2015-09-08 08:05:57 +00002109 // The EmitPointerWithAlignment path does this fine; just discard
2110 // the alignment.
2111 return CGF.EmitPointerWithAlignment(CE).getPointer();
Anders Carlsson12f5a252009-09-12 04:57:16 +00002112 }
John McCall7f416cc2015-09-08 08:05:57 +00002113
Anders Carlsson8a01a752011-04-11 02:03:26 +00002114 case CK_Dynamic: {
John McCall7f416cc2015-09-08 08:05:57 +00002115 Address V = CGF.EmitPointerWithAlignment(E);
Eli Friedman0dfc6802009-11-27 02:07:44 +00002116 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(CE);
2117 return CGF.EmitDynamicCast(V, DCE);
2118 }
Eli Friedmane96f1d32009-11-27 04:41:50 +00002119
John McCall7f416cc2015-09-08 08:05:57 +00002120 case CK_ArrayToPointerDecay:
2121 return CGF.EmitArrayToPointerDecay(E).getPointer();
John McCalle3027922010-08-25 11:45:40 +00002122 case CK_FunctionToPointerDecay:
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002123 return EmitLValue(E).getPointer(CGF);
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002124
John McCalle84af4e2010-11-13 01:35:44 +00002125 case CK_NullToPointer:
2126 if (MustVisitNullValue(E))
Richard Smith27252a12019-06-14 17:46:38 +00002127 CGF.EmitIgnoredExpr(E);
John McCalle84af4e2010-11-13 01:35:44 +00002128
Yaxun Liu402804b2016-12-15 08:09:08 +00002129 return CGF.CGM.getNullPointer(cast<llvm::PointerType>(ConvertType(DestTy)),
2130 DestTy);
John McCalle84af4e2010-11-13 01:35:44 +00002131
John McCalle3027922010-08-25 11:45:40 +00002132 case CK_NullToMemberPointer: {
John McCalle84af4e2010-11-13 01:35:44 +00002133 if (MustVisitNullValue(E))
Richard Smith27252a12019-06-14 17:46:38 +00002134 CGF.EmitIgnoredExpr(E);
John McCalla1dee5302010-08-22 10:59:02 +00002135
John McCall7a9aac22010-08-23 01:21:21 +00002136 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2137 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2138 }
Anders Carlsson12f5a252009-09-12 04:57:16 +00002139
John McCallc62bb392012-02-15 01:22:51 +00002140 case CK_ReinterpretMemberPointer:
John McCalle3027922010-08-25 11:45:40 +00002141 case CK_BaseToDerivedMemberPointer:
2142 case CK_DerivedToBaseMemberPointer: {
Eli Friedmane96f1d32009-11-27 04:41:50 +00002143 Value *Src = Visit(E);
Craig Toppera97d7e72013-07-26 06:16:11 +00002144
John McCalla1dee5302010-08-22 10:59:02 +00002145 // Note that the AST doesn't distinguish between checked and
2146 // unchecked member pointer conversions, so we always have to
2147 // implement checked conversions here. This is inefficient when
2148 // actual control flow may be required in order to perform the
2149 // check, which it is for data member pointers (but not member
2150 // function pointers on Itanium and ARM).
John McCall7a9aac22010-08-23 01:21:21 +00002151 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, CE, Src);
Eli Friedmane96f1d32009-11-27 04:41:50 +00002152 }
John McCall31168b02011-06-15 23:02:42 +00002153
John McCall2d637d22011-09-10 06:18:15 +00002154 case CK_ARCProduceObject:
John McCall31168b02011-06-15 23:02:42 +00002155 return CGF.EmitARCRetainScalarExpr(E);
John McCall2d637d22011-09-10 06:18:15 +00002156 case CK_ARCConsumeObject:
John McCall31168b02011-06-15 23:02:42 +00002157 return CGF.EmitObjCConsumeObject(E->getType(), Visit(E));
John McCalle399e5b2016-01-27 18:32:30 +00002158 case CK_ARCReclaimReturnedObject:
2159 return CGF.EmitARCReclaimReturnedObject(E, /*allowUnsafe*/ Ignored);
John McCallff613032011-10-04 06:23:45 +00002160 case CK_ARCExtendBlockObject:
2161 return CGF.EmitARCExtendBlockObject(E);
John McCall31168b02011-06-15 23:02:42 +00002162
Douglas Gregored90df32012-02-22 05:02:47 +00002163 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmanec75fec2012-02-28 01:08:45 +00002164 return CGF.EmitBlockCopyAndAutorelease(Visit(E), E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00002165
John McCallc5e62b42010-11-13 09:02:35 +00002166 case CK_FloatingRealToComplex:
2167 case CK_FloatingComplexCast:
2168 case CK_IntegralRealToComplex:
2169 case CK_IntegralComplexCast:
John McCalld7646252010-11-14 08:17:51 +00002170 case CK_IntegralComplexToFloatingComplex:
2171 case CK_FloatingComplexToIntegralComplex:
John McCalle3027922010-08-25 11:45:40 +00002172 case CK_ConstructorConversion:
John McCall3eba6e62010-11-16 06:21:14 +00002173 case CK_ToUnion:
2174 llvm_unreachable("scalar cast to non-scalar value");
John McCall34376a62010-12-04 03:47:34 +00002175
John McCallf3735e02010-12-01 04:43:34 +00002176 case CK_LValueToRValue:
2177 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
John McCall34376a62010-12-04 03:47:34 +00002178 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
John McCallf3735e02010-12-01 04:43:34 +00002179 return Visit(const_cast<Expr*>(E));
Eli Friedman0dfc6802009-11-27 02:07:44 +00002180
John McCalle3027922010-08-25 11:45:40 +00002181 case CK_IntegralToPointer: {
Anders Carlsson7cd39e02009-09-15 04:48:33 +00002182 Value *Src = Visit(const_cast<Expr*>(E));
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002183
Anders Carlsson094c4592009-10-18 18:12:03 +00002184 // First, convert to the correct width so that we control the kind of
2185 // extension.
Yaxun Liu26f75662016-08-19 05:17:25 +00002186 auto DestLLVMTy = ConvertType(DestTy);
2187 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002188 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
Anders Carlsson094c4592009-10-18 18:12:03 +00002189 llvm::Value* IntResult =
2190 Builder.CreateIntCast(Src, MiddleTy, InputSigned, "conv");
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002191
Piotr Padlewski07058292018-07-02 19:21:36 +00002192 auto *IntToPtr = Builder.CreateIntToPtr(IntResult, DestLLVMTy);
Daniel Dunbaread6824c2010-08-25 03:32:38 +00002193
Piotr Padlewski07058292018-07-02 19:21:36 +00002194 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2195 // Going from integer to pointer that could be dynamic requires reloading
2196 // dynamic information from invariant.group.
2197 if (DestTy.mayBeDynamicClass())
2198 IntToPtr = Builder.CreateLaunderInvariantGroup(IntToPtr);
2199 }
2200 return IntToPtr;
2201 }
2202 case CK_PointerToIntegral: {
2203 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
2204 auto *PtrExpr = Visit(E);
2205
2206 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2207 const QualType SrcType = E->getType();
2208
2209 // Casting to integer requires stripping dynamic information as it does
2210 // not carries it.
2211 if (SrcType.mayBeDynamicClass())
2212 PtrExpr = Builder.CreateStripInvariantGroup(PtrExpr);
2213 }
2214
2215 return Builder.CreatePtrToInt(PtrExpr, ConvertType(DestTy));
2216 }
John McCalle3027922010-08-25 11:45:40 +00002217 case CK_ToVoid: {
John McCalla2342eb2010-12-05 02:00:02 +00002218 CGF.EmitIgnoredExpr(E);
Craig Topper8a13c412014-05-21 05:09:00 +00002219 return nullptr;
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002220 }
John McCalle3027922010-08-25 11:45:40 +00002221 case CK_VectorSplat: {
Chris Lattner2192fe52011-07-18 04:24:23 +00002222 llvm::Type *DstTy = ConvertType(DestTy);
George Burgess IVdf1ed002016-01-13 01:52:39 +00002223 Value *Elt = Visit(const_cast<Expr*>(E));
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002224 // Splat the element across to all elements
Craig Topperf2f1a092016-07-08 02:17:35 +00002225 unsigned NumElements = DstTy->getVectorNumElements();
Alp Toker5f072d82014-04-19 23:55:49 +00002226 return Builder.CreateVectorSplat(NumElements, Elt, "splat");
Eli Friedmanc08bdea2009-11-16 21:33:53 +00002227 }
John McCall8cb679e2010-11-15 09:13:47 +00002228
Leonard Chan99bda372018-10-15 16:07:02 +00002229 case CK_FixedPointCast:
Leonard Chanb4ba4672018-10-23 17:55:35 +00002230 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2231 CE->getExprLoc());
2232
2233 case CK_FixedPointToBoolean:
2234 assert(E->getType()->isFixedPointType() &&
2235 "Expected src type to be fixed point type");
2236 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
2237 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2238 CE->getExprLoc());
Leonard Chan99bda372018-10-15 16:07:02 +00002239
Leonard Chan8f7caae2019-03-06 00:28:43 +00002240 case CK_FixedPointToIntegral:
2241 assert(E->getType()->isFixedPointType() &&
2242 "Expected src type to be fixed point type");
2243 assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
2244 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2245 CE->getExprLoc());
2246
2247 case CK_IntegralToFixedPoint:
2248 assert(E->getType()->isIntegerType() &&
2249 "Expected src type to be an integer");
2250 assert(DestTy->isFixedPointType() &&
2251 "Expected dest type to be fixed point type");
2252 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2253 CE->getExprLoc());
2254
Roman Lebedevb69ba222018-07-30 18:58:30 +00002255 case CK_IntegralCast: {
2256 ScalarConversionOpts Opts;
Roman Lebedev62debd802018-10-30 21:58:56 +00002257 if (auto *ICE = dyn_cast<ImplicitCastExpr>(CE)) {
Roman Lebedevd677c3f2018-11-19 19:56:43 +00002258 if (!ICE->isPartOfExplicitCast())
2259 Opts = ScalarConversionOpts(CGF.SanOpts);
Roman Lebedevb69ba222018-07-30 18:58:30 +00002260 }
2261 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2262 CE->getExprLoc(), Opts);
2263 }
John McCalle3027922010-08-25 11:45:40 +00002264 case CK_IntegralToFloating:
2265 case CK_FloatingToIntegral:
2266 case CK_FloatingCast:
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002267 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
2268 CE->getExprLoc());
Roman Lebedevb69ba222018-07-30 18:58:30 +00002269 case CK_BooleanToSignedIntegral: {
2270 ScalarConversionOpts Opts;
2271 Opts.TreatBooleanAsSigned = true;
George Burgess IVdf1ed002016-01-13 01:52:39 +00002272 return EmitScalarConversion(Visit(E), E->getType(), DestTy,
Roman Lebedevb69ba222018-07-30 18:58:30 +00002273 CE->getExprLoc(), Opts);
2274 }
John McCall8cb679e2010-11-15 09:13:47 +00002275 case CK_IntegralToBoolean:
2276 return EmitIntToBoolConversion(Visit(E));
2277 case CK_PointerToBoolean:
Yaxun Liu402804b2016-12-15 08:09:08 +00002278 return EmitPointerToBoolConversion(Visit(E), E->getType());
John McCall8cb679e2010-11-15 09:13:47 +00002279 case CK_FloatingToBoolean:
2280 return EmitFloatToBoolConversion(Visit(E));
John McCalle3027922010-08-25 11:45:40 +00002281 case CK_MemberPointerToBoolean: {
John McCall7a9aac22010-08-23 01:21:21 +00002282 llvm::Value *MemPtr = Visit(E);
2283 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
2284 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
Anders Carlsson3df53bc2009-08-24 18:26:39 +00002285 }
John McCalld7646252010-11-14 08:17:51 +00002286
2287 case CK_FloatingComplexToReal:
2288 case CK_IntegralComplexToReal:
John McCall07bb1962010-11-16 10:08:07 +00002289 return CGF.EmitComplexExpr(E, false, true).first;
John McCalld7646252010-11-14 08:17:51 +00002290
2291 case CK_FloatingComplexToBoolean:
2292 case CK_IntegralComplexToBoolean: {
John McCall07bb1962010-11-16 10:08:07 +00002293 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
John McCalld7646252010-11-14 08:17:51 +00002294
2295 // TODO: kill this function off, inline appropriate case here
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00002296 return EmitComplexToScalarConversion(V, E->getType(), DestTy,
2297 CE->getExprLoc());
John McCalld7646252010-11-14 08:17:51 +00002298 }
2299
Andrew Savonichevb555b762018-10-23 15:19:20 +00002300 case CK_ZeroToOCLOpaqueType: {
Andrew Savonichev3fee3512018-11-08 11:25:41 +00002301 assert((DestTy->isEventT() || DestTy->isQueueT() ||
2302 DestTy->isOCLIntelSubgroupAVCType()) &&
Andrew Savonichevb555b762018-10-23 15:19:20 +00002303 "CK_ZeroToOCLEvent cast on non-event type");
Egor Churaev89831422016-12-23 14:55:49 +00002304 return llvm::Constant::getNullValue(ConvertType(DestTy));
2305 }
2306
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002307 case CK_IntToOCLSampler:
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002308 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00002309
2310 } // end of switch
Mike Stump4a3999f2009-09-09 13:00:44 +00002311
John McCall3eba6e62010-11-16 06:21:14 +00002312 llvm_unreachable("unknown scalar cast");
Chris Lattner2da04b32007-08-24 05:35:26 +00002313}
2314
Chris Lattner04a913b2007-08-31 22:09:40 +00002315Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
John McCallce1de612011-01-26 04:00:11 +00002316 CodeGenFunction::StmtExprEvaluation eval(CGF);
John McCall7f416cc2015-09-08 08:05:57 +00002317 Address RetAlloca = CGF.EmitCompoundStmt(*E->getSubStmt(),
2318 !E->getType()->isVoidType());
2319 if (!RetAlloca.isValid())
Craig Topper8a13c412014-05-21 05:09:00 +00002320 return nullptr;
Nick Lewycky2d84e842013-10-02 02:29:49 +00002321 return CGF.EmitLoadOfScalar(CGF.MakeAddrLValue(RetAlloca, E->getType()),
2322 E->getExprLoc());
Chris Lattner04a913b2007-08-31 22:09:40 +00002323}
2324
Reid Kleckner092d0652017-03-06 22:18:34 +00002325Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
2326 CGF.enterFullExpression(E);
2327 CodeGenFunction::RunCleanupsScope Scope(CGF);
2328 Value *V = Visit(E->getSubExpr());
2329 // Defend against dominance problems caused by jumps out of expression
2330 // evaluation through the shared cleanup block.
2331 Scope.ForceCleanup({&V});
2332 return V;
2333}
2334
Chris Lattner2da04b32007-08-24 05:35:26 +00002335//===----------------------------------------------------------------------===//
2336// Unary Operators
2337//===----------------------------------------------------------------------===//
2338
Alexey Samsonovf6246502015-04-23 01:50:45 +00002339static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
2340 llvm::Value *InVal, bool IsInc) {
2341 BinOpInfo BinOp;
2342 BinOp.LHS = InVal;
2343 BinOp.RHS = llvm::ConstantInt::get(InVal->getType(), 1, false);
2344 BinOp.Ty = E->getType();
2345 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
Adam Nemet484aa452017-03-27 19:17:25 +00002346 // FIXME: once UnaryOperator carries FPFeatures, copy it here.
Alexey Samsonovf6246502015-04-23 01:50:45 +00002347 BinOp.E = E;
2348 return BinOp;
2349}
2350
2351llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
2352 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
2353 llvm::Value *Amount =
2354 llvm::ConstantInt::get(InVal->getType(), IsInc ? 1 : -1, true);
2355 StringRef Name = IsInc ? "inc" : "dec";
Richard Smith9c6890a2012-11-01 22:30:59 +00002356 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Anton Yartsev85129b82011-02-07 02:17:30 +00002357 case LangOptions::SOB_Defined:
Alexey Samsonovf6246502015-04-23 01:50:45 +00002358 return Builder.CreateAdd(InVal, Amount, Name);
Richard Smith3e056de2012-08-25 00:32:28 +00002359 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002360 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002361 return Builder.CreateNSWAdd(InVal, Amount, Name);
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00002362 LLVM_FALLTHROUGH;
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002363 case LangOptions::SOB_Trapping:
2364 if (!E->canOverflow())
2365 return Builder.CreateNSWAdd(InVal, Amount, Name);
2366 return EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, InVal, IsInc));
2367 }
David Blaikie83d382b2011-09-23 05:06:16 +00002368 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
Anton Yartsev85129b82011-02-07 02:17:30 +00002369}
2370
Alexey Bataev7b518dc2020-01-06 16:14:34 -05002371namespace {
2372/// Handles check and update for lastprivate conditional variables.
2373class OMPLastprivateConditionalUpdateRAII {
2374private:
2375 CodeGenFunction &CGF;
2376 const UnaryOperator *E;
2377
2378public:
2379 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
2380 const UnaryOperator *E)
2381 : CGF(CGF), E(E) {}
2382 ~OMPLastprivateConditionalUpdateRAII() {
2383 if (CGF.getLangOpts().OpenMP)
2384 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
2385 CGF, E->getSubExpr());
2386 }
2387};
2388} // namespace
2389
John McCalle3dc1702011-02-15 09:22:45 +00002390llvm::Value *
2391ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
2392 bool isInc, bool isPre) {
Alexey Bataev7b518dc2020-01-06 16:14:34 -05002393 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
John McCalle3dc1702011-02-15 09:22:45 +00002394 QualType type = E->getSubExpr()->getType();
Craig Topper8a13c412014-05-21 05:09:00 +00002395 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00002396 llvm::Value *value;
2397 llvm::Value *input;
Anton Yartsev85129b82011-02-07 02:17:30 +00002398
John McCalle3dc1702011-02-15 09:22:45 +00002399 int amount = (isInc ? 1 : -1);
Vedant Kumar175b6d12017-07-13 20:55:26 +00002400 bool isSubtraction = !isInc;
John McCalle3dc1702011-02-15 09:22:45 +00002401
David Chisnallfa35df62012-01-16 17:27:18 +00002402 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
David Chisnallef78c302013-03-03 16:02:42 +00002403 type = atomicTy->getValueType();
2404 if (isInc && type->isBooleanType()) {
2405 llvm::Value *True = CGF.EmitToMemory(Builder.getTrue(), type);
2406 if (isPre) {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002407 Builder.CreateStore(True, LV.getAddress(CGF), LV.isVolatileQualified())
2408 ->setAtomic(llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002409 return Builder.getTrue();
2410 }
2411 // For atomic bool increment, we just store true and return it for
2412 // preincrement, do an atomic swap with true for postincrement
JF Bastien92f4ef12016-04-06 17:26:42 +00002413 return Builder.CreateAtomicRMW(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002414 llvm::AtomicRMWInst::Xchg, LV.getPointer(CGF), True,
JF Bastien92f4ef12016-04-06 17:26:42 +00002415 llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002416 }
2417 // Special case for atomic increment / decrement on integers, emit
2418 // atomicrmw instructions. We skip this if we want to be doing overflow
Craig Toppera97d7e72013-07-26 06:16:11 +00002419 // checking, and fall into the slow path with the atomic cmpxchg loop.
David Chisnallef78c302013-03-03 16:02:42 +00002420 if (!type->isBooleanType() && type->isIntegerType() &&
2421 !(type->isUnsignedIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002422 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
David Chisnallef78c302013-03-03 16:02:42 +00002423 CGF.getLangOpts().getSignedOverflowBehavior() !=
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002424 LangOptions::SOB_Trapping) {
David Chisnallef78c302013-03-03 16:02:42 +00002425 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
2426 llvm::AtomicRMWInst::Sub;
2427 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
2428 llvm::Instruction::Sub;
2429 llvm::Value *amt = CGF.EmitToMemory(
2430 llvm::ConstantInt::get(ConvertType(type), 1, true), type);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08002431 llvm::Value *old =
2432 Builder.CreateAtomicRMW(aop, LV.getPointer(CGF), amt,
2433 llvm::AtomicOrdering::SequentiallyConsistent);
David Chisnallef78c302013-03-03 16:02:42 +00002434 return isPre ? Builder.CreateBinOp(op, old, amt) : old;
2435 }
Nick Lewycky2d84e842013-10-02 02:29:49 +00002436 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002437 input = value;
2438 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
David Chisnallfa35df62012-01-16 17:27:18 +00002439 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
2440 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
David Chisnallef78c302013-03-03 16:02:42 +00002441 value = CGF.EmitToMemory(value, type);
David Chisnallfa35df62012-01-16 17:27:18 +00002442 Builder.CreateBr(opBB);
2443 Builder.SetInsertPoint(opBB);
2444 atomicPHI = Builder.CreatePHI(value->getType(), 2);
2445 atomicPHI->addIncoming(value, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00002446 value = atomicPHI;
David Chisnallef78c302013-03-03 16:02:42 +00002447 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +00002448 value = EmitLoadOfLValue(LV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00002449 input = value;
David Chisnallfa35df62012-01-16 17:27:18 +00002450 }
2451
John McCalle3dc1702011-02-15 09:22:45 +00002452 // Special case of integer increment that we have to check first: bool++.
2453 // Due to promotion rules, we get:
2454 // bool++ -> bool = bool + 1
2455 // -> bool = (int)bool + 1
2456 // -> bool = ((int)bool + 1 != 0)
2457 // An interesting aspect of this is that increment is always true.
2458 // Decrement does not have this property.
2459 if (isInc && type->isBooleanType()) {
2460 value = Builder.getTrue();
2461
2462 // Most common case by far: integer increment.
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002463 } else if (type->isIntegerType()) {
Roman Lebedevb98a0c72019-11-27 17:07:06 +03002464 QualType promotedType;
2465 bool canPerformLossyDemotionCheck = false;
2466 if (type->isPromotableIntegerType()) {
2467 promotedType = CGF.getContext().getPromotedIntegerType(type);
2468 assert(promotedType != type && "Shouldn't promote to the same type.");
2469 canPerformLossyDemotionCheck = true;
2470 canPerformLossyDemotionCheck &=
2471 CGF.getContext().getCanonicalType(type) !=
2472 CGF.getContext().getCanonicalType(promotedType);
2473 canPerformLossyDemotionCheck &=
2474 PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
2475 type, promotedType);
2476 assert((!canPerformLossyDemotionCheck ||
2477 type->isSignedIntegerOrEnumerationType() ||
2478 promotedType->isSignedIntegerOrEnumerationType() ||
2479 ConvertType(type)->getScalarSizeInBits() ==
2480 ConvertType(promotedType)->getScalarSizeInBits()) &&
2481 "The following check expects that if we do promotion to different "
2482 "underlying canonical type, at least one of the types (either "
2483 "base or promoted) will be signed, or the bitwidths will match.");
2484 }
2485 if (CGF.SanOpts.hasOneOf(
2486 SanitizerKind::ImplicitIntegerArithmeticValueChange) &&
2487 canPerformLossyDemotionCheck) {
2488 // While `x += 1` (for `x` with width less than int) is modeled as
2489 // promotion+arithmetics+demotion, and we can catch lossy demotion with
2490 // ease; inc/dec with width less than int can't overflow because of
2491 // promotion rules, so we omit promotion+demotion, which means that we can
2492 // not catch lossy "demotion". Because we still want to catch these cases
2493 // when the sanitizer is enabled, we perform the promotion, then perform
2494 // the increment/decrement in the wider type, and finally
2495 // perform the demotion. This will catch lossy demotions.
2496
2497 value = EmitScalarConversion(value, type, promotedType, E->getExprLoc());
2498 Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
2499 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
2500 // Do pass non-default ScalarConversionOpts so that sanitizer check is
2501 // emitted.
2502 value = EmitScalarConversion(value, promotedType, type, E->getExprLoc(),
2503 ScalarConversionOpts(CGF.SanOpts));
2504
2505 // Note that signed integer inc/dec with width less than int can't
2506 // overflow because of promotion rules; we're just eliding a few steps
2507 // here.
2508 } else if (E->canOverflow() && type->isSignedIntegerOrEnumerationType()) {
Malcolm Parsonsfab36802018-04-16 08:31:08 +00002509 value = EmitIncDecConsiderOverflowBehavior(E, value, isInc);
2510 } else if (E->canOverflow() && type->isUnsignedIntegerType() &&
2511 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
2512 value =
2513 EmitOverflowCheckedBinOp(createBinOpInfoFromIncDec(E, value, isInc));
Alexey Samsonovf6246502015-04-23 01:50:45 +00002514 } else {
2515 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount, true);
John McCalle3dc1702011-02-15 09:22:45 +00002516 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
Alexey Samsonovf6246502015-04-23 01:50:45 +00002517 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002518
John McCalle3dc1702011-02-15 09:22:45 +00002519 // Next most common: pointer increment.
2520 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
2521 QualType type = ptr->getPointeeType();
2522
2523 // VLA types don't have constant size.
John McCall77527a82011-06-25 01:32:37 +00002524 if (const VariableArrayType *vla
2525 = CGF.getContext().getAsVariableArrayType(type)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +00002526 llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
John McCall23c29fe2011-06-24 21:55:10 +00002527 if (!isInc) numElts = Builder.CreateNSWNeg(numElts, "vla.negsize");
Richard Smith9c6890a2012-11-01 22:30:59 +00002528 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall23c29fe2011-06-24 21:55:10 +00002529 value = Builder.CreateGEP(value, numElts, "vla.inc");
Chris Lattner2e72da942011-03-01 00:03:48 +00002530 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002531 value = CGF.EmitCheckedInBoundsGEP(
2532 value, numElts, /*SignedIndices=*/false, isSubtraction,
2533 E->getExprLoc(), "vla.inc");
Craig Toppera97d7e72013-07-26 06:16:11 +00002534
John McCalle3dc1702011-02-15 09:22:45 +00002535 // Arithmetic on function pointers (!) is just +-1.
2536 } else if (type->isFunctionType()) {
Chris Lattner2531eb42011-04-19 22:55:03 +00002537 llvm::Value *amt = Builder.getInt32(amount);
John McCalle3dc1702011-02-15 09:22:45 +00002538
2539 value = CGF.EmitCastToVoidPtr(value);
Richard Smith9c6890a2012-11-01 22:30:59 +00002540 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002541 value = Builder.CreateGEP(value, amt, "incdec.funcptr");
2542 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002543 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2544 isSubtraction, E->getExprLoc(),
2545 "incdec.funcptr");
John McCalle3dc1702011-02-15 09:22:45 +00002546 value = Builder.CreateBitCast(value, input->getType());
2547
2548 // For everything else, we can just do a simple increment.
Anton Yartsev85129b82011-02-07 02:17:30 +00002549 } else {
Chris Lattner2531eb42011-04-19 22:55:03 +00002550 llvm::Value *amt = Builder.getInt32(amount);
Richard Smith9c6890a2012-11-01 22:30:59 +00002551 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002552 value = Builder.CreateGEP(value, amt, "incdec.ptr");
2553 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002554 value = CGF.EmitCheckedInBoundsGEP(value, amt, /*SignedIndices=*/false,
2555 isSubtraction, E->getExprLoc(),
2556 "incdec.ptr");
John McCalle3dc1702011-02-15 09:22:45 +00002557 }
2558
2559 // Vector increment/decrement.
2560 } else if (type->isVectorType()) {
2561 if (type->hasIntegerRepresentation()) {
2562 llvm::Value *amt = llvm::ConstantInt::get(value->getType(), amount);
2563
Eli Friedman409943e2011-05-06 18:04:18 +00002564 value = Builder.CreateAdd(value, amt, isInc ? "inc" : "dec");
John McCalle3dc1702011-02-15 09:22:45 +00002565 } else {
2566 value = Builder.CreateFAdd(
2567 value,
2568 llvm::ConstantFP::get(value->getType(), amount),
Anton Yartsev85129b82011-02-07 02:17:30 +00002569 isInc ? "inc" : "dec");
2570 }
Anton Yartsev85129b82011-02-07 02:17:30 +00002571
John McCalle3dc1702011-02-15 09:22:45 +00002572 // Floating point.
2573 } else if (type->isRealFloatingType()) {
Chris Lattner05dc78c2010-06-26 22:09:34 +00002574 // Add the inc/dec to the real part.
John McCalle3dc1702011-02-15 09:22:45 +00002575 llvm::Value *amt;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002576
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002577 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002578 // Another special case: half FP increment should be done via float
Akira Hatanaka502775a2017-12-09 00:02:37 +00002579 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002580 value = Builder.CreateCall(
2581 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_from_fp16,
2582 CGF.CGM.FloatTy),
2583 input, "incdec.conv");
2584 } else {
2585 value = Builder.CreateFPExt(input, CGF.CGM.FloatTy, "incdec.conv");
2586 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002587 }
2588
John McCalle3dc1702011-02-15 09:22:45 +00002589 if (value->getType()->isFloatTy())
2590 amt = llvm::ConstantFP::get(VMContext,
2591 llvm::APFloat(static_cast<float>(amount)));
2592 else if (value->getType()->isDoubleTy())
2593 amt = llvm::ConstantFP::get(VMContext,
2594 llvm::APFloat(static_cast<double>(amount)));
Chris Lattner05dc78c2010-06-26 22:09:34 +00002595 else {
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002596 // Remaining types are Half, LongDouble or __float128. Convert from float.
John McCalle3dc1702011-02-15 09:22:45 +00002597 llvm::APFloat F(static_cast<float>(amount));
Chris Lattner05dc78c2010-06-26 22:09:34 +00002598 bool ignored;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002599 const llvm::fltSemantics *FS;
Ahmed Bougacha6ba38312015-03-24 23:44:42 +00002600 // Don't use getFloatTypeSemantics because Half isn't
2601 // necessarily represented using the "half" LLVM type.
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002602 if (value->getType()->isFP128Ty())
2603 FS = &CGF.getTarget().getFloat128Format();
2604 else if (value->getType()->isHalfTy())
2605 FS = &CGF.getTarget().getHalfFormat();
2606 else
2607 FS = &CGF.getTarget().getLongDoubleFormat();
2608 F.convert(*FS, llvm::APFloat::rmTowardZero, &ignored);
John McCalle3dc1702011-02-15 09:22:45 +00002609 amt = llvm::ConstantFP::get(VMContext, F);
Chris Lattner05dc78c2010-06-26 22:09:34 +00002610 }
John McCalle3dc1702011-02-15 09:22:45 +00002611 value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
2612
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002613 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
Akira Hatanaka502775a2017-12-09 00:02:37 +00002614 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
Ahmed Bougachad1801af2015-03-23 17:54:16 +00002615 value = Builder.CreateCall(
2616 CGF.CGM.getIntrinsic(llvm::Intrinsic::convert_to_fp16,
2617 CGF.CGM.FloatTy),
2618 value, "incdec.conv");
2619 } else {
2620 value = Builder.CreateFPTrunc(value, input->getType(), "incdec.conv");
2621 }
2622 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002623
Bevin Hansson39baaab2020-01-08 11:12:55 +01002624 // Fixed-point types.
2625 } else if (type->isFixedPointType()) {
2626 // Fixed-point types are tricky. In some cases, it isn't possible to
2627 // represent a 1 or a -1 in the type at all. Piggyback off of
2628 // EmitFixedPointBinOp to avoid having to reimplement saturation.
2629 BinOpInfo Info;
2630 Info.E = E;
2631 Info.Ty = E->getType();
2632 Info.Opcode = isInc ? BO_Add : BO_Sub;
2633 Info.LHS = value;
2634 Info.RHS = llvm::ConstantInt::get(value->getType(), 1, false);
2635 // If the type is signed, it's better to represent this as +(-1) or -(-1),
2636 // since -1 is guaranteed to be representable.
2637 if (type->isSignedFixedPointType()) {
2638 Info.Opcode = isInc ? BO_Sub : BO_Add;
2639 Info.RHS = Builder.CreateNeg(Info.RHS);
2640 }
2641 // Now, convert from our invented integer literal to the type of the unary
2642 // op. This will upscale and saturate if necessary. This value can become
2643 // undef in some cases.
2644 FixedPointSemantics SrcSema =
2645 FixedPointSemantics::GetIntegerSemantics(value->getType()
2646 ->getScalarSizeInBits(),
2647 /*IsSigned=*/true);
2648 FixedPointSemantics DstSema =
2649 CGF.getContext().getFixedPointSemantics(Info.Ty);
2650 Info.RHS = EmitFixedPointConversion(Info.RHS, SrcSema, DstSema,
2651 E->getExprLoc());
2652 value = EmitFixedPointBinOp(Info);
2653
John McCalle3dc1702011-02-15 09:22:45 +00002654 // Objective-C pointer types.
2655 } else {
2656 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
2657 value = CGF.EmitCastToVoidPtr(value);
2658
2659 CharUnits size = CGF.getContext().getTypeSizeInChars(OPT->getObjectType());
2660 if (!isInc) size = -size;
2661 llvm::Value *sizeValue =
2662 llvm::ConstantInt::get(CGF.SizeTy, size.getQuantity());
2663
Richard Smith9c6890a2012-11-01 22:30:59 +00002664 if (CGF.getLangOpts().isSignedOverflowDefined())
Chris Lattner2e72da942011-03-01 00:03:48 +00002665 value = Builder.CreateGEP(value, sizeValue, "incdec.objptr");
2666 else
Vedant Kumar175b6d12017-07-13 20:55:26 +00002667 value = CGF.EmitCheckedInBoundsGEP(value, sizeValue,
2668 /*SignedIndices=*/false, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00002669 E->getExprLoc(), "incdec.objptr");
John McCalle3dc1702011-02-15 09:22:45 +00002670 value = Builder.CreateBitCast(value, input->getType());
Chris Lattner05dc78c2010-06-26 22:09:34 +00002671 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002672
David Chisnallfa35df62012-01-16 17:27:18 +00002673 if (atomicPHI) {
Erik Pilkington53e43f42019-02-28 00:47:55 +00002674 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
David Chisnallfa35df62012-01-16 17:27:18 +00002675 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00002676 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00002677 LV, RValue::get(atomicPHI), RValue::get(value), E->getExprLoc());
2678 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), type);
2679 llvm::Value *success = Pair.second;
Erik Pilkington53e43f42019-02-28 00:47:55 +00002680 atomicPHI->addIncoming(old, curBlock);
2681 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
David Chisnallfa35df62012-01-16 17:27:18 +00002682 Builder.SetInsertPoint(contBB);
2683 return isPre ? value : input;
2684 }
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002685
Chris Lattner05dc78c2010-06-26 22:09:34 +00002686 // Store the updated result through the lvalue.
2687 if (LV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00002688 CGF.EmitStoreThroughBitfieldLValue(RValue::get(value), LV, &value);
Chris Lattner05dc78c2010-06-26 22:09:34 +00002689 else
John McCall55e1fbc2011-06-25 02:11:03 +00002690 CGF.EmitStoreThroughLValue(RValue::get(value), LV);
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00002691
Chris Lattner05dc78c2010-06-26 22:09:34 +00002692 // If this is a postinc, return the value read from memory, otherwise use the
2693 // updated value.
John McCalle3dc1702011-02-15 09:22:45 +00002694 return isPre ? value : input;
Chris Lattner05dc78c2010-06-26 22:09:34 +00002695}
2696
2697
2698
Chris Lattner2da04b32007-08-24 05:35:26 +00002699Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002700 TestAndClearIgnoreResultAssign();
Cameron McInally20b8ed22019-10-14 15:35:01 +00002701 Value *Op = Visit(E->getSubExpr());
2702
2703 // Generate a unary FNeg for FP ops.
2704 if (Op->getType()->isFPOrFPVectorTy())
2705 return Builder.CreateFNeg(Op, "fneg");
2706
Chris Lattner0bf27622010-06-26 21:48:21 +00002707 // Emit unary minus with EmitSub so we handle overflow cases etc.
2708 BinOpInfo BinOp;
Cameron McInally20b8ed22019-10-14 15:35:01 +00002709 BinOp.RHS = Op;
2710 BinOp.LHS = llvm::Constant::getNullValue(BinOp.RHS->getType());
Chris Lattner0bf27622010-06-26 21:48:21 +00002711 BinOp.Ty = E->getType();
John McCalle3027922010-08-25 11:45:40 +00002712 BinOp.Opcode = BO_Sub;
Adam Nemet484aa452017-03-27 19:17:25 +00002713 // FIXME: once UnaryOperator carries FPFeatures, copy it here.
Chris Lattner0bf27622010-06-26 21:48:21 +00002714 BinOp.E = E;
2715 return EmitSub(BinOp);
Chris Lattner2da04b32007-08-24 05:35:26 +00002716}
2717
2718Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002719 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00002720 Value *Op = Visit(E->getSubExpr());
2721 return Builder.CreateNot(Op, "neg");
2722}
2723
2724Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00002725 // Perform vector logical not on comparison with zero vector.
2726 if (E->getType()->isExtVectorType()) {
2727 Value *Oper = Visit(E->getSubExpr());
2728 Value *Zero = llvm::Constant::getNullValue(Oper->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00002729 Value *Result;
2730 if (Oper->getType()->isFPOrFPVectorTy())
2731 Result = Builder.CreateFCmp(llvm::CmpInst::FCMP_OEQ, Oper, Zero, "cmp");
2732 else
2733 Result = Builder.CreateICmp(llvm::CmpInst::ICMP_EQ, Oper, Zero, "cmp");
Tanya Lattner20248222012-01-16 21:02:28 +00002734 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
2735 }
Craig Toppera97d7e72013-07-26 06:16:11 +00002736
Chris Lattner2da04b32007-08-24 05:35:26 +00002737 // Compare operand to zero.
2738 Value *BoolVal = CGF.EvaluateExprAsBool(E->getSubExpr());
Mike Stump4a3999f2009-09-09 13:00:44 +00002739
Chris Lattner2da04b32007-08-24 05:35:26 +00002740 // Invert value.
2741 // TODO: Could dynamically modify easy computations here. For example, if
2742 // the operand is an icmp ne, turn into icmp eq.
2743 BoolVal = Builder.CreateNot(BoolVal, "lnot");
Mike Stump4a3999f2009-09-09 13:00:44 +00002744
Anders Carlsson775640d2009-05-19 18:44:53 +00002745 // ZExt result to the expr type.
2746 return Builder.CreateZExt(BoolVal, ConvertType(E->getType()), "lnot.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00002747}
2748
Eli Friedmand7c72322010-08-05 09:58:49 +00002749Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
2750 // Try folding the offsetof to a constant.
Fangrui Song407659a2018-11-30 23:41:18 +00002751 Expr::EvalResult EVResult;
2752 if (E->EvaluateAsInt(EVResult, CGF.getContext())) {
2753 llvm::APSInt Value = EVResult.Val.getInt();
Richard Smith5fab0c92011-12-28 19:48:30 +00002754 return Builder.getInt(Value);
Fangrui Song407659a2018-11-30 23:41:18 +00002755 }
Eli Friedmand7c72322010-08-05 09:58:49 +00002756
2757 // Loop over the components of the offsetof to compute the value.
2758 unsigned n = E->getNumComponents();
Chris Lattner2192fe52011-07-18 04:24:23 +00002759 llvm::Type* ResultType = ConvertType(E->getType());
Eli Friedmand7c72322010-08-05 09:58:49 +00002760 llvm::Value* Result = llvm::Constant::getNullValue(ResultType);
2761 QualType CurrentType = E->getTypeSourceInfo()->getType();
2762 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00002763 OffsetOfNode ON = E->getComponent(i);
Craig Topper8a13c412014-05-21 05:09:00 +00002764 llvm::Value *Offset = nullptr;
Eli Friedmand7c72322010-08-05 09:58:49 +00002765 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00002766 case OffsetOfNode::Array: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002767 // Compute the index
2768 Expr *IdxExpr = E->getIndexExpr(ON.getArrayExprIndex());
2769 llvm::Value* Idx = CGF.EmitScalarExpr(IdxExpr);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00002770 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
Eli Friedmand7c72322010-08-05 09:58:49 +00002771 Idx = Builder.CreateIntCast(Idx, ResultType, IdxSigned, "conv");
2772
2773 // Save the element type
2774 CurrentType =
2775 CGF.getContext().getAsArrayType(CurrentType)->getElementType();
2776
2777 // Compute the element size
2778 llvm::Value* ElemSize = llvm::ConstantInt::get(ResultType,
2779 CGF.getContext().getTypeSizeInChars(CurrentType).getQuantity());
2780
2781 // Multiply out to compute the result
2782 Offset = Builder.CreateMul(Idx, ElemSize);
2783 break;
2784 }
2785
James Y Knight7281c352015-12-29 22:31:18 +00002786 case OffsetOfNode::Field: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002787 FieldDecl *MemberDecl = ON.getField();
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002788 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
Eli Friedmand7c72322010-08-05 09:58:49 +00002789 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2790
2791 // Compute the index of the field in its parent.
2792 unsigned i = 0;
2793 // FIXME: It would be nice if we didn't have to loop here!
2794 for (RecordDecl::field_iterator Field = RD->field_begin(),
2795 FieldEnd = RD->field_end();
David Blaikie2d7c57e2012-04-30 02:36:29 +00002796 Field != FieldEnd; ++Field, ++i) {
David Blaikie40ed2972012-06-06 20:45:41 +00002797 if (*Field == MemberDecl)
Eli Friedmand7c72322010-08-05 09:58:49 +00002798 break;
2799 }
2800 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
2801
2802 // Compute the offset to the field
2803 int64_t OffsetInt = RL.getFieldOffset(i) /
2804 CGF.getContext().getCharWidth();
2805 Offset = llvm::ConstantInt::get(ResultType, OffsetInt);
2806
2807 // Save the element type.
2808 CurrentType = MemberDecl->getType();
2809 break;
2810 }
Eli Friedman165301d2010-08-06 16:37:05 +00002811
James Y Knight7281c352015-12-29 22:31:18 +00002812 case OffsetOfNode::Identifier:
Eli Friedmane83d2b762010-08-06 01:17:25 +00002813 llvm_unreachable("dependent __builtin_offsetof");
Eli Friedman165301d2010-08-06 16:37:05 +00002814
James Y Knight7281c352015-12-29 22:31:18 +00002815 case OffsetOfNode::Base: {
Eli Friedmand7c72322010-08-05 09:58:49 +00002816 if (ON.getBase()->isVirtual()) {
2817 CGF.ErrorUnsupported(E, "virtual base in offsetof");
2818 continue;
2819 }
2820
Simon Pilgrim1cd399c2019-10-03 11:22:48 +00002821 RecordDecl *RD = CurrentType->castAs<RecordType>()->getDecl();
Eli Friedmand7c72322010-08-05 09:58:49 +00002822 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(RD);
2823
2824 // Save the element type.
2825 CurrentType = ON.getBase()->getType();
Craig Toppera97d7e72013-07-26 06:16:11 +00002826
Eli Friedmand7c72322010-08-05 09:58:49 +00002827 // Compute the offset to the base.
2828 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
2829 CXXRecordDecl *BaseRD = cast<CXXRecordDecl>(BaseRT->getDecl());
Benjamin Kramer2ef30312012-07-04 18:45:14 +00002830 CharUnits OffsetInt = RL.getBaseClassOffset(BaseRD);
2831 Offset = llvm::ConstantInt::get(ResultType, OffsetInt.getQuantity());
Eli Friedmand7c72322010-08-05 09:58:49 +00002832 break;
2833 }
2834 }
2835 Result = Builder.CreateAdd(Result, Offset);
2836 }
2837 return Result;
Douglas Gregor882211c2010-04-28 22:16:22 +00002838}
2839
Peter Collingbournee190dee2011-03-11 19:24:49 +00002840/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
Sebastian Redl6f282892008-11-11 17:56:53 +00002841/// argument of the sizeof expression as an integer.
2842Value *
Peter Collingbournee190dee2011-03-11 19:24:49 +00002843ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
2844 const UnaryExprOrTypeTraitExpr *E) {
Sebastian Redl6f282892008-11-11 17:56:53 +00002845 QualType TypeToSize = E->getTypeOfArgument();
Peter Collingbournee190dee2011-03-11 19:24:49 +00002846 if (E->getKind() == UETT_SizeOf) {
Mike Stump4a3999f2009-09-09 13:00:44 +00002847 if (const VariableArrayType *VAT =
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002848 CGF.getContext().getAsVariableArrayType(TypeToSize)) {
2849 if (E->isArgumentType()) {
2850 // sizeof(type) - make sure to emit the VLA size.
John McCall23c29fe2011-06-24 21:55:10 +00002851 CGF.EmitVariablyModifiedType(TypeToSize);
Eli Friedman3253e182009-04-20 03:21:44 +00002852 } else {
2853 // C99 6.5.3.4p2: If the argument is an expression of type
2854 // VLA, it is evaluated.
John McCalla2342eb2010-12-05 02:00:02 +00002855 CGF.EmitIgnoredExpr(E->getArgumentExpr());
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002856 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002857
Sander de Smalen891af03a2018-02-03 13:55:59 +00002858 auto VlaSize = CGF.getVLASize(VAT);
2859 llvm::Value *size = VlaSize.NumElts;
John McCall23c29fe2011-06-24 21:55:10 +00002860
2861 // Scale the number of non-VLA elements by the non-VLA element size.
Sander de Smalen891af03a2018-02-03 13:55:59 +00002862 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(VlaSize.Type);
John McCall23c29fe2011-06-24 21:55:10 +00002863 if (!eltSize.isOne())
Sander de Smalen891af03a2018-02-03 13:55:59 +00002864 size = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), size);
John McCall23c29fe2011-06-24 21:55:10 +00002865
2866 return size;
Anders Carlsson76dbc042008-12-21 03:33:21 +00002867 }
Alexey Bataev00396512015-07-02 03:40:19 +00002868 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
2869 auto Alignment =
2870 CGF.getContext()
2871 .toCharUnitsFromBits(CGF.getContext().getOpenMPDefaultSimdAlign(
2872 E->getTypeOfArgument()->getPointeeType()))
2873 .getQuantity();
2874 return llvm::ConstantInt::get(CGF.SizeTy, Alignment);
Anders Carlsson30032882008-12-12 07:38:43 +00002875 }
Eli Friedman2aa38fe2009-01-24 22:19:05 +00002876
Mike Stump4a3999f2009-09-09 13:00:44 +00002877 // If this isn't sizeof(vla), the result must be constant; use the constant
2878 // folding logic so we don't have to duplicate it here.
Richard Smith5fab0c92011-12-28 19:48:30 +00002879 return Builder.getInt(E->EvaluateKnownConstInt(CGF.getContext()));
Chris Lattner2da04b32007-08-24 05:35:26 +00002880}
2881
Chris Lattner9f0ad962007-08-24 21:20:17 +00002882Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E) {
2883 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002884 if (Op->getType()->isAnyComplexType()) {
2885 // If it's an l-value, load through the appropriate subobject l-value.
2886 // Note that we have to ask E because Op might be an l-value that
2887 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002888 if (E->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002889 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2890 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002891
2892 // Otherwise, calculate and project.
2893 return CGF.EmitComplexExpr(Op, false, true).first;
2894 }
2895
Chris Lattner9f0ad962007-08-24 21:20:17 +00002896 return Visit(Op);
2897}
John McCall07bb1962010-11-16 10:08:07 +00002898
Chris Lattner9f0ad962007-08-24 21:20:17 +00002899Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E) {
2900 Expr *Op = E->getSubExpr();
John McCall07bb1962010-11-16 10:08:07 +00002901 if (Op->getType()->isAnyComplexType()) {
2902 // If it's an l-value, load through the appropriate subobject l-value.
2903 // Note that we have to ask E because Op might be an l-value that
2904 // this won't work for, e.g. an Obj-C property.
John McCall086a4642010-11-24 05:12:34 +00002905 if (Op->isGLValue())
Nick Lewycky2d84e842013-10-02 02:29:49 +00002906 return CGF.EmitLoadOfLValue(CGF.EmitLValue(E),
2907 E->getExprLoc()).getScalarVal();
John McCall07bb1962010-11-16 10:08:07 +00002908
2909 // Otherwise, calculate and project.
2910 return CGF.EmitComplexExpr(Op, true, false).second;
2911 }
Mike Stump4a3999f2009-09-09 13:00:44 +00002912
Mike Stumpdf0fe272009-05-29 15:46:01 +00002913 // __imag on a scalar returns zero. Emit the subexpr to ensure side
2914 // effects are evaluated, but not the actual value.
Richard Smith0b6b8e42012-02-18 20:53:32 +00002915 if (Op->isGLValue())
2916 CGF.EmitLValue(Op);
2917 else
2918 CGF.EmitScalarExpr(Op, true);
Owen Anderson0b75f232009-07-31 20:28:54 +00002919 return llvm::Constant::getNullValue(ConvertType(E->getType()));
Chris Lattner9f0ad962007-08-24 21:20:17 +00002920}
2921
Chris Lattner2da04b32007-08-24 05:35:26 +00002922//===----------------------------------------------------------------------===//
2923// Binary Operators
2924//===----------------------------------------------------------------------===//
2925
2926BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00002927 TestAndClearIgnoreResultAssign();
Chris Lattner2da04b32007-08-24 05:35:26 +00002928 BinOpInfo Result;
2929 Result.LHS = Visit(E->getLHS());
2930 Result.RHS = Visit(E->getRHS());
Chris Lattner3d966d62007-08-24 21:00:35 +00002931 Result.Ty = E->getType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002932 Result.Opcode = E->getOpcode();
Adam Nemet484aa452017-03-27 19:17:25 +00002933 Result.FPFeatures = E->getFPFeatures();
Chris Lattner2da04b32007-08-24 05:35:26 +00002934 Result.E = E;
2935 return Result;
2936}
2937
Douglas Gregor914af212010-04-23 04:16:32 +00002938LValue ScalarExprEmitter::EmitCompoundAssignLValue(
2939 const CompoundAssignOperator *E,
2940 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00002941 Value *&Result) {
Benjamin Kramerd20ef752009-12-25 15:43:36 +00002942 QualType LHSTy = E->getLHS()->getType();
Chris Lattner3d966d62007-08-24 21:00:35 +00002943 BinOpInfo OpInfo;
Craig Toppera97d7e72013-07-26 06:16:11 +00002944
Eli Friedmanf0450072013-06-12 01:40:06 +00002945 if (E->getComputationResultType()->isAnyComplexType())
Richard Smith527473d2015-02-12 21:23:20 +00002946 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
Craig Toppera97d7e72013-07-26 06:16:11 +00002947
Mike Stumpc63428b2009-05-22 19:07:20 +00002948 // Emit the RHS first. __block variables need to have the rhs evaluated
2949 // first, plus this should improve codegen a little.
2950 OpInfo.RHS = Visit(E->getRHS());
2951 OpInfo.Ty = E->getComputationResultType();
Chris Lattner0bf27622010-06-26 21:48:21 +00002952 OpInfo.Opcode = E->getOpcode();
Adam Nemet484aa452017-03-27 19:17:25 +00002953 OpInfo.FPFeatures = E->getFPFeatures();
Mike Stumpc63428b2009-05-22 19:07:20 +00002954 OpInfo.E = E;
Eli Friedman8b7b1b12009-03-28 01:22:36 +00002955 // Load/convert the LHS.
Richard Smith4d1458e2012-09-08 02:08:36 +00002956 LValue LHSLV = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
David Chisnallfa35df62012-01-16 17:27:18 +00002957
Craig Topper8a13c412014-05-21 05:09:00 +00002958 llvm::PHINode *atomicPHI = nullptr;
David Chisnallef78c302013-03-03 16:02:42 +00002959 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
2960 QualType type = atomicTy->getValueType();
2961 if (!type->isBooleanType() && type->isIntegerType() &&
Alexey Samsonovedf99a92014-11-07 22:29:38 +00002962 !(type->isUnsignedIntegerType() &&
2963 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
2964 CGF.getLangOpts().getSignedOverflowBehavior() !=
2965 LangOptions::SOB_Trapping) {
Tim Northover10e0d642019-11-07 13:36:03 +00002966 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
2967 llvm::Instruction::BinaryOps Op;
David Chisnallef78c302013-03-03 16:02:42 +00002968 switch (OpInfo.Opcode) {
2969 // We don't have atomicrmw operands for *, %, /, <<, >>
2970 case BO_MulAssign: case BO_DivAssign:
2971 case BO_RemAssign:
2972 case BO_ShlAssign:
2973 case BO_ShrAssign:
2974 break;
2975 case BO_AddAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00002976 AtomicOp = llvm::AtomicRMWInst::Add;
2977 Op = llvm::Instruction::Add;
David Chisnallef78c302013-03-03 16:02:42 +00002978 break;
2979 case BO_SubAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00002980 AtomicOp = llvm::AtomicRMWInst::Sub;
2981 Op = llvm::Instruction::Sub;
David Chisnallef78c302013-03-03 16:02:42 +00002982 break;
2983 case BO_AndAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00002984 AtomicOp = llvm::AtomicRMWInst::And;
2985 Op = llvm::Instruction::And;
David Chisnallef78c302013-03-03 16:02:42 +00002986 break;
2987 case BO_XorAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00002988 AtomicOp = llvm::AtomicRMWInst::Xor;
2989 Op = llvm::Instruction::Xor;
David Chisnallef78c302013-03-03 16:02:42 +00002990 break;
2991 case BO_OrAssign:
Tim Northover10e0d642019-11-07 13:36:03 +00002992 AtomicOp = llvm::AtomicRMWInst::Or;
2993 Op = llvm::Instruction::Or;
David Chisnallef78c302013-03-03 16:02:42 +00002994 break;
2995 default:
2996 llvm_unreachable("Invalid compound assignment type");
2997 }
Tim Northover10e0d642019-11-07 13:36:03 +00002998 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
2999 llvm::Value *Amt = CGF.EmitToMemory(
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003000 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
3001 E->getExprLoc()),
3002 LHSTy);
Tim Northover10e0d642019-11-07 13:36:03 +00003003 Value *OldVal = Builder.CreateAtomicRMW(
Akira Hatanakaf139ae32019-12-03 15:17:01 -08003004 AtomicOp, LHSLV.getPointer(CGF), Amt,
JF Bastien92f4ef12016-04-06 17:26:42 +00003005 llvm::AtomicOrdering::SequentiallyConsistent);
Tim Northover10e0d642019-11-07 13:36:03 +00003006
3007 // Since operation is atomic, the result type is guaranteed to be the
3008 // same as the input in LLVM terms.
3009 Result = Builder.CreateBinOp(Op, OldVal, Amt);
David Chisnallef78c302013-03-03 16:02:42 +00003010 return LHSLV;
3011 }
3012 }
David Chisnallfa35df62012-01-16 17:27:18 +00003013 // FIXME: For floating point types, we should be saving and restoring the
3014 // floating point environment in the loop.
3015 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3016 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
Nick Lewycky2d84e842013-10-02 02:29:49 +00003017 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
David Chisnallef78c302013-03-03 16:02:42 +00003018 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, type);
David Chisnallfa35df62012-01-16 17:27:18 +00003019 Builder.CreateBr(opBB);
3020 Builder.SetInsertPoint(opBB);
3021 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
3022 atomicPHI->addIncoming(OpInfo.LHS, startBB);
David Chisnallfa35df62012-01-16 17:27:18 +00003023 OpInfo.LHS = atomicPHI;
3024 }
David Chisnallef78c302013-03-03 16:02:42 +00003025 else
Nick Lewycky2d84e842013-10-02 02:29:49 +00003026 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003027
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00003028 SourceLocation Loc = E->getExprLoc();
3029 OpInfo.LHS =
3030 EmitScalarConversion(OpInfo.LHS, LHSTy, E->getComputationLHSType(), Loc);
Eli Friedman93ee5ca2012-06-16 02:19:17 +00003031
Chris Lattner3d966d62007-08-24 21:00:35 +00003032 // Expand the binary operator.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003033 Result = (this->*Func)(OpInfo);
Craig Toppera97d7e72013-07-26 06:16:11 +00003034
Roman Lebedevd677c3f2018-11-19 19:56:43 +00003035 // Convert the result back to the LHS type,
3036 // potentially with Implicit Conversion sanitizer check.
3037 Result = EmitScalarConversion(Result, E->getComputationResultType(), LHSTy,
3038 Loc, ScalarConversionOpts(CGF.SanOpts));
David Chisnallfa35df62012-01-16 17:27:18 +00003039
3040 if (atomicPHI) {
Erik Pilkington53e43f42019-02-28 00:47:55 +00003041 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
David Chisnallfa35df62012-01-16 17:27:18 +00003042 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
Alexey Bataev452d8e12014-12-15 05:25:25 +00003043 auto Pair = CGF.EmitAtomicCompareExchange(
Alexey Bataevb4505a72015-03-30 05:20:59 +00003044 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
3045 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
3046 llvm::Value *success = Pair.second;
Erik Pilkington53e43f42019-02-28 00:47:55 +00003047 atomicPHI->addIncoming(old, curBlock);
3048 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
David Chisnallfa35df62012-01-16 17:27:18 +00003049 Builder.SetInsertPoint(contBB);
3050 return LHSLV;
3051 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003052
Mike Stump4a3999f2009-09-09 13:00:44 +00003053 // Store the result value into the LHS lvalue. Bit-fields are handled
3054 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
3055 // 'An assignment expression has the value of the left operand after the
3056 // assignment...'.
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003057 if (LHSLV.isBitField())
John McCall55e1fbc2011-06-25 02:11:03 +00003058 CGF.EmitStoreThroughBitfieldLValue(RValue::get(Result), LHSLV, &Result);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003059 else
John McCall55e1fbc2011-06-25 02:11:03 +00003060 CGF.EmitStoreThroughLValue(RValue::get(Result), LHSLV);
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003061
Alexey Bataeva58da1a2019-12-27 09:44:43 -05003062 if (CGF.getLangOpts().OpenMP)
3063 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
3064 E->getLHS());
Douglas Gregor914af212010-04-23 04:16:32 +00003065 return LHSLV;
3066}
3067
3068Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
3069 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
3070 bool Ignore = TestAndClearIgnoreResultAssign();
Simon Pilgrim30aa42e2019-05-18 12:17:15 +00003071 Value *RHS = nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003072 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
3073
3074 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00003075 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00003076 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003077
John McCall07bb1962010-11-16 10:08:07 +00003078 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00003079 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00003080 return RHS;
3081
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00003082 // If the lvalue is non-volatile, return the computed value of the assignment.
3083 if (!LHS.isVolatileQualified())
3084 return RHS;
3085
3086 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00003087 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner3d966d62007-08-24 21:00:35 +00003088}
3089
Chris Lattner8ee6a412010-09-11 21:47:09 +00003090void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
Richard Smith4d1458e2012-09-08 02:08:36 +00003091 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003092 SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
Chris Lattner8ee6a412010-09-11 21:47:09 +00003093
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00003094 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003095 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
3096 SanitizerKind::IntegerDivideByZero));
Alexey Samsonov4c1a96f2014-11-10 22:27:30 +00003097 }
Richard Smithc86a1142012-11-06 02:30:30 +00003098
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003099 const auto *BO = cast<BinaryOperator>(Ops.E);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003100 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003101 Ops.Ty->hasSignedIntegerRepresentation() &&
Vedant Kumard9191152017-05-02 23:46:56 +00003102 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
3103 Ops.mayHaveIntegerOverflow()) {
Richard Smithc86a1142012-11-06 02:30:30 +00003104 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
3105
Chris Lattner8ee6a412010-09-11 21:47:09 +00003106 llvm::Value *IntMin =
Chris Lattner2531eb42011-04-19 22:55:03 +00003107 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
Chris Lattner8ee6a412010-09-11 21:47:09 +00003108 llvm::Value *NegOne = llvm::ConstantInt::get(Ty, -1ULL);
3109
Richard Smith4d1458e2012-09-08 02:08:36 +00003110 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
3111 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003112 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
3113 Checks.push_back(
3114 std::make_pair(NotOverflow, SanitizerKind::SignedIntegerOverflow));
Chris Lattner8ee6a412010-09-11 21:47:09 +00003115 }
Richard Smithc86a1142012-11-06 02:30:30 +00003116
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003117 if (Checks.size() > 0)
3118 EmitBinOpCheck(Checks, Ops);
Chris Lattner8ee6a412010-09-11 21:47:09 +00003119}
Chris Lattner3d966d62007-08-24 21:00:35 +00003120
Chris Lattner2da04b32007-08-24 05:35:26 +00003121Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003122 {
3123 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003124 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3125 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Vedant Kumard9191152017-05-02 23:46:56 +00003126 Ops.Ty->isIntegerType() &&
3127 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003128 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
3129 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003130 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
Vedant Kumard9191152017-05-02 23:46:56 +00003131 Ops.Ty->isRealFloatingType() &&
3132 Ops.mayHaveFloatDivisionByZero()) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003133 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003134 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
3135 EmitBinOpCheck(std::make_pair(NonZero, SanitizerKind::FloatDivideByZero),
3136 Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00003137 }
Chris Lattner8ee6a412010-09-11 21:47:09 +00003138 }
Will Dietz1897cb32012-11-27 15:01:55 +00003139
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003140 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
3141 llvm::Value *Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
Yaxun Liuffb60902016-08-09 20:10:18 +00003142 if (CGF.getLangOpts().OpenCL &&
3143 !CGF.CGM.getCodeGenOpts().CorrectlyRoundedDivSqrt) {
3144 // OpenCL v1.1 s7.4: minimum accuracy of single precision / is 2.5ulp
3145 // OpenCL v1.2 s5.6.4.2: The -cl-fp32-correctly-rounded-divide-sqrt
3146 // build option allows an application to specify that single precision
3147 // floating-point divide (x/y and 1/x) and sqrt used in the program
3148 // source are correctly rounded.
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003149 llvm::Type *ValTy = Val->getType();
3150 if (ValTy->isFloatTy() ||
3151 (isa<llvm::VectorType>(ValTy) &&
3152 cast<llvm::VectorType>(ValTy)->getElementType()->isFloatTy()))
Duncan Sandse81111c2012-04-10 08:23:07 +00003153 CGF.SetFPAccuracy(Val, 2.5);
Peter Collingbourne95fd2ca2011-10-27 19:19:51 +00003154 }
3155 return Val;
3156 }
Bevin Hansson39baaab2020-01-08 11:12:55 +01003157 else if (Ops.isFixedPointOp())
Bevin Hansson0b9922e2019-11-19 13:15:06 +01003158 return EmitFixedPointBinOp(Ops);
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003159 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003160 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
3161 else
3162 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
3163}
3164
3165Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
3166 // Rem in C can't be a floating point type: C99 6.5.5p2.
Vedant Kumar42de3802017-02-25 00:43:39 +00003167 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
3168 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
Vedant Kumard9191152017-05-02 23:46:56 +00003169 Ops.Ty->isIntegerType() &&
3170 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003171 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattner8ee6a412010-09-11 21:47:09 +00003172 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
Vedant Kumar42de3802017-02-25 00:43:39 +00003173 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
Chris Lattner8ee6a412010-09-11 21:47:09 +00003174 }
3175
Eli Friedman493c34a2011-04-10 04:44:11 +00003176 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003177 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
3178 else
3179 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
3180}
3181
Mike Stump0c61b732009-04-01 20:28:16 +00003182Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
3183 unsigned IID;
3184 unsigned OpID = 0;
Mike Stump40968592009-04-02 01:03:55 +00003185
Will Dietz1897cb32012-11-27 15:01:55 +00003186 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
Chris Lattner0bf27622010-06-26 21:48:21 +00003187 switch (Ops.Opcode) {
John McCalle3027922010-08-25 11:45:40 +00003188 case BO_Add:
3189 case BO_AddAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003190 OpID = 1;
Will Dietz1897cb32012-11-27 15:01:55 +00003191 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
3192 llvm::Intrinsic::uadd_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003193 break;
John McCalle3027922010-08-25 11:45:40 +00003194 case BO_Sub:
3195 case BO_SubAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003196 OpID = 2;
Will Dietz1897cb32012-11-27 15:01:55 +00003197 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
3198 llvm::Intrinsic::usub_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003199 break;
John McCalle3027922010-08-25 11:45:40 +00003200 case BO_Mul:
3201 case BO_MulAssign:
Mike Stumpd3e38852009-04-02 18:15:54 +00003202 OpID = 3;
Will Dietz1897cb32012-11-27 15:01:55 +00003203 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
3204 llvm::Intrinsic::umul_with_overflow;
Mike Stumpd3e38852009-04-02 18:15:54 +00003205 break;
3206 default:
David Blaikie83d382b2011-09-23 05:06:16 +00003207 llvm_unreachable("Unsupported operation for overflow detection");
Mike Stump0c61b732009-04-01 20:28:16 +00003208 }
Mike Stumpd3e38852009-04-02 18:15:54 +00003209 OpID <<= 1;
Will Dietz1897cb32012-11-27 15:01:55 +00003210 if (isSigned)
3211 OpID |= 1;
Mike Stumpd3e38852009-04-02 18:15:54 +00003212
Vedant Kumar4b62b5c2017-05-09 23:34:49 +00003213 CodeGenFunction::SanitizerScope SanScope(&CGF);
Chris Lattnera5f58b02011-07-09 17:41:47 +00003214 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
Mike Stump0c61b732009-04-01 20:28:16 +00003215
Benjamin Kramer8d375ce2011-07-14 17:45:50 +00003216 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
Mike Stump0c61b732009-04-01 20:28:16 +00003217
David Blaikie43f9bb72015-05-18 22:14:03 +00003218 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
Mike Stump0c61b732009-04-01 20:28:16 +00003219 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
3220 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
3221
Richard Smith4d1458e2012-09-08 02:08:36 +00003222 // Handle overflow with llvm.trap if no custom handler has been specified.
3223 const std::string *handlerName =
Richard Smith9c6890a2012-11-01 22:30:59 +00003224 &CGF.getLangOpts().OverflowHandler;
Richard Smith4d1458e2012-09-08 02:08:36 +00003225 if (handlerName->empty()) {
Richard Smithb1b0ab42012-11-05 22:21:05 +00003226 // If the signed-integer-overflow sanitizer is enabled, emit a call to its
Richard Smithde670682012-11-01 22:15:34 +00003227 // runtime. Otherwise, this is a -ftrapv check, so just emit a trap.
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003228 if (!isSigned || CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003229 llvm::Value *NotOverflow = Builder.CreateNot(overflow);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003230 SanitizerMask Kind = isSigned ? SanitizerKind::SignedIntegerOverflow
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003231 : SanitizerKind::UnsignedIntegerOverflow;
3232 EmitBinOpCheck(std::make_pair(NotOverflow, Kind), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00003233 } else
Chad Rosierae229d52013-01-29 23:31:22 +00003234 CGF.EmitTrapCheck(Builder.CreateNot(overflow));
Richard Smith4d1458e2012-09-08 02:08:36 +00003235 return result;
3236 }
3237
Mike Stump0c61b732009-04-01 20:28:16 +00003238 // Branch in case of overflow.
David Chisnalldd84ef12010-09-17 18:29:54 +00003239 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
Duncan P. N. Exon Smith01f574c2016-08-17 03:15:29 +00003240 llvm::BasicBlock *continueBB =
3241 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
Chris Lattner8139c982010-08-07 00:20:46 +00003242 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
Mike Stump0c61b732009-04-01 20:28:16 +00003243
3244 Builder.CreateCondBr(overflow, overflowBB, continueBB);
3245
David Chisnalldd84ef12010-09-17 18:29:54 +00003246 // If an overflow handler is set, then we want to call it and then use its
3247 // result, if it returns.
3248 Builder.SetInsertPoint(overflowBB);
3249
3250 // Get the overflow handler.
Chris Lattnerece04092012-02-07 00:39:47 +00003251 llvm::Type *Int8Ty = CGF.Int8Ty;
Chris Lattnera5f58b02011-07-09 17:41:47 +00003252 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
David Chisnalldd84ef12010-09-17 18:29:54 +00003253 llvm::FunctionType *handlerTy =
3254 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
James Y Knight9871db02019-02-05 16:42:33 +00003255 llvm::FunctionCallee handler =
3256 CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
David Chisnalldd84ef12010-09-17 18:29:54 +00003257
3258 // Sign extend the args to 64-bit, so that we can use the same handler for
3259 // all types of overflow.
3260 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
3261 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
3262
3263 // Call the handler with the two arguments, the operation, and the size of
3264 // the result.
John McCall882987f2013-02-28 19:01:20 +00003265 llvm::Value *handlerArgs[] = {
3266 lhs,
3267 rhs,
3268 Builder.getInt8(OpID),
3269 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
3270 };
3271 llvm::Value *handlerResult =
3272 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
David Chisnalldd84ef12010-09-17 18:29:54 +00003273
3274 // Truncate the result back to the desired size.
3275 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
3276 Builder.CreateBr(continueBB);
3277
Mike Stump0c61b732009-04-01 20:28:16 +00003278 Builder.SetInsertPoint(continueBB);
Jay Foad20c0f022011-03-30 11:28:58 +00003279 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
David Chisnalldd84ef12010-09-17 18:29:54 +00003280 phi->addIncoming(result, initialBB);
3281 phi->addIncoming(handlerResult, overflowBB);
3282
3283 return phi;
Mike Stump0c61b732009-04-01 20:28:16 +00003284}
Chris Lattner2da04b32007-08-24 05:35:26 +00003285
John McCall77527a82011-06-25 01:32:37 +00003286/// Emit pointer + index arithmetic.
3287static Value *emitPointerArithmetic(CodeGenFunction &CGF,
3288 const BinOpInfo &op,
3289 bool isSubtraction) {
3290 // Must have binary (not unary) expr here. Unary pointer
3291 // increment/decrement doesn't use this path.
3292 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
Craig Toppera97d7e72013-07-26 06:16:11 +00003293
John McCall77527a82011-06-25 01:32:37 +00003294 Value *pointer = op.LHS;
3295 Expr *pointerOperand = expr->getLHS();
3296 Value *index = op.RHS;
3297 Expr *indexOperand = expr->getRHS();
3298
3299 // In a subtraction, the LHS is always the pointer.
3300 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
3301 std::swap(pointer, index);
3302 std::swap(pointerOperand, indexOperand);
3303 }
3304
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003305 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003306
John McCall77527a82011-06-25 01:32:37 +00003307 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
Yaxun Liu26f75662016-08-19 05:17:25 +00003308 auto &DL = CGF.CGM.getDataLayout();
3309 auto PtrTy = cast<llvm::PointerType>(pointer->getType());
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00003310
3311 // Some versions of glibc and gcc use idioms (particularly in their malloc
3312 // routines) that add a pointer-sized integer (known to be a pointer value)
3313 // to a null pointer in order to cast the value back to an integer or as
3314 // part of a pointer alignment algorithm. This is undefined behavior, but
3315 // we'd like to be able to compile programs that use it.
3316 //
3317 // Normally, we'd generate a GEP with a null-pointer base here in response
3318 // to that code, but it's also UB to dereference a pointer created that
3319 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
3320 // generate a direct cast of the integer value to a pointer.
3321 //
3322 // The idiom (p = nullptr + N) is not met if any of the following are true:
3323 //
3324 // The operation is subtraction.
3325 // The index is not pointer-sized.
3326 // The pointer type is not byte-sized.
3327 //
3328 if (BinaryOperator::isNullPointerArithmeticExtension(CGF.getContext(),
3329 op.Opcode,
Fangrui Song6907ce22018-07-30 19:24:48 +00003330 expr->getLHS(),
Andrew Kaylor3d0a5402017-09-19 20:26:40 +00003331 expr->getRHS()))
3332 return CGF.Builder.CreateIntToPtr(index, pointer->getType());
3333
Nicola Zaghen97572772019-12-13 09:55:45 +00003334 if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
John McCall77527a82011-06-25 01:32:37 +00003335 // Zero-extend or sign-extend the pointer value according to
3336 // whether the index is signed or not.
Nicola Zaghen97572772019-12-13 09:55:45 +00003337 index = CGF.Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
John McCall77527a82011-06-25 01:32:37 +00003338 "idx.ext");
3339 }
3340
3341 // If this is subtraction, negate the index.
3342 if (isSubtraction)
3343 index = CGF.Builder.CreateNeg(index, "idx.neg");
3344
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003345 if (CGF.SanOpts.has(SanitizerKind::ArrayBounds))
Richard Smith539e4a72013-02-23 02:53:19 +00003346 CGF.EmitBoundsCheck(op.E, pointerOperand, index, indexOperand->getType(),
3347 /*Accessed*/ false);
3348
John McCall77527a82011-06-25 01:32:37 +00003349 const PointerType *pointerType
3350 = pointerOperand->getType()->getAs<PointerType>();
3351 if (!pointerType) {
3352 QualType objectType = pointerOperand->getType()
3353 ->castAs<ObjCObjectPointerType>()
3354 ->getPointeeType();
3355 llvm::Value *objectSize
3356 = CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(objectType));
3357
3358 index = CGF.Builder.CreateMul(index, objectSize);
3359
3360 Value *result = CGF.Builder.CreateBitCast(pointer, CGF.VoidPtrTy);
3361 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3362 return CGF.Builder.CreateBitCast(result, pointer->getType());
3363 }
3364
3365 QualType elementType = pointerType->getPointeeType();
3366 if (const VariableArrayType *vla
3367 = CGF.getContext().getAsVariableArrayType(elementType)) {
3368 // The element count here is the total number of non-VLA elements.
Sander de Smalen891af03a2018-02-03 13:55:59 +00003369 llvm::Value *numElements = CGF.getVLASize(vla).NumElts;
John McCall77527a82011-06-25 01:32:37 +00003370
3371 // Effectively, the multiply by the VLA size is part of the GEP.
3372 // GEP indexes are signed, and scaling an index isn't permitted to
3373 // signed-overflow, so we use the same semantics for our explicit
3374 // multiply. We suppress this if overflow is not undefined behavior.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003375 if (CGF.getLangOpts().isSignedOverflowDefined()) {
John McCall77527a82011-06-25 01:32:37 +00003376 index = CGF.Builder.CreateMul(index, numElements, "vla.index");
3377 pointer = CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3378 } else {
3379 index = CGF.Builder.CreateNSWMul(index, numElements, "vla.index");
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003380 pointer =
Vedant Kumar175b6d12017-07-13 20:55:26 +00003381 CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003382 op.E->getExprLoc(), "add.ptr");
Chris Lattner51924e512010-06-26 21:25:03 +00003383 }
John McCall77527a82011-06-25 01:32:37 +00003384 return pointer;
Mike Stump4a3999f2009-09-09 13:00:44 +00003385 }
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003386
Mike Stump4a3999f2009-09-09 13:00:44 +00003387 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
3388 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
3389 // future proof.
John McCall77527a82011-06-25 01:32:37 +00003390 if (elementType->isVoidType() || elementType->isFunctionType()) {
Matt Arsenaultc6da9ec2019-10-31 08:41:37 -07003391 Value *result = CGF.EmitCastToVoidPtr(pointer);
John McCall77527a82011-06-25 01:32:37 +00003392 result = CGF.Builder.CreateGEP(result, index, "add.ptr");
3393 return CGF.Builder.CreateBitCast(result, pointer->getType());
Mike Stump4a3999f2009-09-09 13:00:44 +00003394 }
3395
David Blaikiebbafb8a2012-03-11 07:00:24 +00003396 if (CGF.getLangOpts().isSignedOverflowDefined())
John McCall77527a82011-06-25 01:32:37 +00003397 return CGF.Builder.CreateGEP(pointer, index, "add.ptr");
3398
Vedant Kumar175b6d12017-07-13 20:55:26 +00003399 return CGF.EmitCheckedInBoundsGEP(pointer, index, isSigned, isSubtraction,
Vedant Kumar6dbf4272017-06-12 18:42:51 +00003400 op.E->getExprLoc(), "add.ptr");
Chris Lattner2da04b32007-08-24 05:35:26 +00003401}
3402
Lang Hames5de91cc2012-10-02 04:45:10 +00003403// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
3404// Addend. Use negMul and negAdd to negate the first operand of the Mul or
3405// the add operand respectively. This allows fmuladd to represent a*b-c, or
3406// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
3407// efficient operations.
Wang, Pengfei3239b502020-01-15 19:08:38 +08003408static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
Lang Hames5de91cc2012-10-02 04:45:10 +00003409 const CodeGenFunction &CGF, CGBuilderTy &Builder,
3410 bool negMul, bool negAdd) {
3411 assert(!(negMul && negAdd) && "Only one of negMul and negAdd should be set.");
Craig Toppera97d7e72013-07-26 06:16:11 +00003412
Lang Hames5de91cc2012-10-02 04:45:10 +00003413 Value *MulOp0 = MulOp->getOperand(0);
3414 Value *MulOp1 = MulOp->getOperand(1);
Craig Topper8b23b2b2019-12-30 13:24:08 -08003415 if (negMul)
3416 MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
3417 if (negAdd)
3418 Addend = Builder.CreateFNeg(Addend, "neg");
Lang Hames5de91cc2012-10-02 04:45:10 +00003419
Wang, Pengfei3239b502020-01-15 19:08:38 +08003420 Value *FMulAdd = nullptr;
3421 if (Builder.getIsFPConstrained()) {
3422 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
3423 "Only constrained operation should be created when Builder is in FP "
3424 "constrained mode");
3425 FMulAdd = Builder.CreateConstrainedFPCall(
3426 CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
3427 Addend->getType()),
3428 {MulOp0, MulOp1, Addend});
3429 } else {
3430 FMulAdd = Builder.CreateCall(
3431 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
3432 {MulOp0, MulOp1, Addend});
3433 }
3434 MulOp->eraseFromParent();
Lang Hames5de91cc2012-10-02 04:45:10 +00003435
Wang, Pengfei3239b502020-01-15 19:08:38 +08003436 return FMulAdd;
Lang Hames5de91cc2012-10-02 04:45:10 +00003437}
3438
3439// Check whether it would be legal to emit an fmuladd intrinsic call to
3440// represent op and if so, build the fmuladd.
3441//
3442// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
3443// Does NOT check the type of the operation - it's assumed that this function
3444// will be called from contexts where it's known that the type is contractable.
Craig Toppera97d7e72013-07-26 06:16:11 +00003445static Value* tryEmitFMulAdd(const BinOpInfo &op,
Lang Hames5de91cc2012-10-02 04:45:10 +00003446 const CodeGenFunction &CGF, CGBuilderTy &Builder,
3447 bool isSub=false) {
3448
3449 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
3450 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
3451 "Only fadd/fsub can be the root of an fmuladd.");
3452
3453 // Check whether this op is marked as fusable.
Adam Nemet049a31d2017-03-29 21:54:24 +00003454 if (!op.FPFeatures.allowFPContractWithinStatement())
Craig Topper8a13c412014-05-21 05:09:00 +00003455 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00003456
3457 // We have a potentially fusable op. Look for a mul on one of the operands.
Sanjay Patela30cee62015-12-03 01:25:12 +00003458 // Also, make sure that the mul result isn't used directly. In that case,
3459 // there's no point creating a muladd operation.
3460 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(op.LHS)) {
3461 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3462 LHSBinOp->use_empty())
Lang Hames5de91cc2012-10-02 04:45:10 +00003463 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
Sanjay Patela30cee62015-12-03 01:25:12 +00003464 }
3465 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(op.RHS)) {
3466 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
3467 RHSBinOp->use_empty())
Lang Hames5de91cc2012-10-02 04:45:10 +00003468 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
Lang Hames5de91cc2012-10-02 04:45:10 +00003469 }
3470
Wang, Pengfei3239b502020-01-15 19:08:38 +08003471 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(op.LHS)) {
3472 if (LHSBinOp->getIntrinsicID() ==
3473 llvm::Intrinsic::experimental_constrained_fmul &&
3474 LHSBinOp->use_empty())
3475 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, false, isSub);
3476 }
3477 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(op.RHS)) {
3478 if (RHSBinOp->getIntrinsicID() ==
3479 llvm::Intrinsic::experimental_constrained_fmul &&
3480 RHSBinOp->use_empty())
3481 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub, false);
3482 }
3483
Craig Topper8a13c412014-05-21 05:09:00 +00003484 return nullptr;
Lang Hames5de91cc2012-10-02 04:45:10 +00003485}
3486
John McCall77527a82011-06-25 01:32:37 +00003487Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
3488 if (op.LHS->getType()->isPointerTy() ||
3489 op.RHS->getType()->isPointerTy())
Vedant Kumar175b6d12017-07-13 20:55:26 +00003490 return emitPointerArithmetic(CGF, op, CodeGenFunction::NotSubtraction);
John McCall77527a82011-06-25 01:32:37 +00003491
3492 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003493 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
John McCall77527a82011-06-25 01:32:37 +00003494 case LangOptions::SOB_Defined:
3495 return Builder.CreateAdd(op.LHS, op.RHS, "add");
Richard Smith3e056de2012-08-25 00:32:28 +00003496 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003497 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00003498 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003499 LLVM_FALLTHROUGH;
John McCall77527a82011-06-25 01:32:37 +00003500 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003501 if (CanElideOverflowCheck(CGF.getContext(), op))
3502 return Builder.CreateNSWAdd(op.LHS, op.RHS, "add");
John McCall77527a82011-06-25 01:32:37 +00003503 return EmitOverflowCheckedBinOp(op);
3504 }
3505 }
Will Dietz1897cb32012-11-27 15:01:55 +00003506
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003507 if (op.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003508 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3509 !CanElideOverflowCheck(CGF.getContext(), op))
Will Dietz1897cb32012-11-27 15:01:55 +00003510 return EmitOverflowCheckedBinOp(op);
3511
Lang Hames5de91cc2012-10-02 04:45:10 +00003512 if (op.LHS->getType()->isFPOrFPVectorTy()) {
3513 // Try to form an fmuladd.
3514 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
3515 return FMulAdd;
3516
Adam Nemet370d0872017-04-04 21:18:30 +00003517 Value *V = Builder.CreateFAdd(op.LHS, op.RHS, "add");
3518 return propagateFMFlags(V, op);
Lang Hames5de91cc2012-10-02 04:45:10 +00003519 }
John McCall77527a82011-06-25 01:32:37 +00003520
Bevin Hansson39baaab2020-01-08 11:12:55 +01003521 if (op.isFixedPointOp())
Leonard Chan837da5d2019-01-16 19:53:50 +00003522 return EmitFixedPointBinOp(op);
Leonard Chan2044ac82019-01-16 18:13:59 +00003523
John McCall77527a82011-06-25 01:32:37 +00003524 return Builder.CreateAdd(op.LHS, op.RHS, "add");
3525}
3526
Leonard Chan2044ac82019-01-16 18:13:59 +00003527/// The resulting value must be calculated with exact precision, so the operands
3528/// may not be the same type.
Leonard Chan837da5d2019-01-16 19:53:50 +00003529Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
Leonard Chan2044ac82019-01-16 18:13:59 +00003530 using llvm::APSInt;
3531 using llvm::ConstantInt;
3532
Bevin Hansson39baaab2020-01-08 11:12:55 +01003533 // This is either a binary operation where at least one of the operands is
3534 // a fixed-point type, or a unary operation where the operand is a fixed-point
3535 // type. The result type of a binary operation is determined by
3536 // Sema::handleFixedPointConversions().
Leonard Chan2044ac82019-01-16 18:13:59 +00003537 QualType ResultTy = op.Ty;
Bevin Hansson39baaab2020-01-08 11:12:55 +01003538 QualType LHSTy, RHSTy;
3539 if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
Bevin Hansson39baaab2020-01-08 11:12:55 +01003540 RHSTy = BinOp->getRHS()->getType();
Bevin Hansson313461f2020-01-08 14:01:30 +01003541 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
3542 // For compound assignment, the effective type of the LHS at this point
3543 // is the computation LHS type, not the actual LHS type, and the final
3544 // result type is not the type of the expression but rather the
3545 // computation result type.
3546 LHSTy = CAO->getComputationLHSType();
3547 ResultTy = CAO->getComputationResultType();
3548 } else
3549 LHSTy = BinOp->getLHS()->getType();
Bevin Hansson39baaab2020-01-08 11:12:55 +01003550 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
3551 LHSTy = UnOp->getSubExpr()->getType();
3552 RHSTy = UnOp->getSubExpr()->getType();
3553 }
Leonard Chan2044ac82019-01-16 18:13:59 +00003554 ASTContext &Ctx = CGF.getContext();
3555 Value *LHS = op.LHS;
3556 Value *RHS = op.RHS;
3557
3558 auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
3559 auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
3560 auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
3561 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
3562
3563 // Convert the operands to the full precision type.
3564 Value *FullLHS = EmitFixedPointConversion(LHS, LHSFixedSema, CommonFixedSema,
Bevin Hansson39baaab2020-01-08 11:12:55 +01003565 op.E->getExprLoc());
Leonard Chan2044ac82019-01-16 18:13:59 +00003566 Value *FullRHS = EmitFixedPointConversion(RHS, RHSFixedSema, CommonFixedSema,
Bevin Hansson39baaab2020-01-08 11:12:55 +01003567 op.E->getExprLoc());
Leonard Chan2044ac82019-01-16 18:13:59 +00003568
Bevin Hansson313461f2020-01-08 14:01:30 +01003569 // Perform the actual operation.
Leonard Chan2044ac82019-01-16 18:13:59 +00003570 Value *Result;
Bevin Hansson39baaab2020-01-08 11:12:55 +01003571 switch (op.Opcode) {
Bevin Hansson313461f2020-01-08 14:01:30 +01003572 case BO_AddAssign:
Leonard Chan837da5d2019-01-16 19:53:50 +00003573 case BO_Add: {
3574 if (ResultFixedSema.isSaturated()) {
3575 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3576 ? llvm::Intrinsic::sadd_sat
3577 : llvm::Intrinsic::uadd_sat;
3578 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3579 } else {
3580 Result = Builder.CreateAdd(FullLHS, FullRHS);
3581 }
3582 break;
3583 }
Bevin Hansson313461f2020-01-08 14:01:30 +01003584 case BO_SubAssign:
Leonard Chan837da5d2019-01-16 19:53:50 +00003585 case BO_Sub: {
3586 if (ResultFixedSema.isSaturated()) {
3587 llvm::Intrinsic::ID IID = ResultFixedSema.isSigned()
3588 ? llvm::Intrinsic::ssub_sat
3589 : llvm::Intrinsic::usub_sat;
3590 Result = Builder.CreateBinaryIntrinsic(IID, FullLHS, FullRHS);
3591 } else {
3592 Result = Builder.CreateSub(FullLHS, FullRHS);
3593 }
3594 break;
3595 }
Bevin Hansson313461f2020-01-08 14:01:30 +01003596 case BO_MulAssign:
Bevin Hansson0b9922e2019-11-19 13:15:06 +01003597 case BO_Mul: {
3598 llvm::Intrinsic::ID IID;
3599 if (ResultFixedSema.isSaturated())
3600 IID = ResultFixedSema.isSigned()
3601 ? llvm::Intrinsic::smul_fix_sat
3602 : llvm::Intrinsic::umul_fix_sat;
3603 else
3604 IID = ResultFixedSema.isSigned()
3605 ? llvm::Intrinsic::smul_fix
3606 : llvm::Intrinsic::umul_fix;
3607 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3608 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3609 break;
3610 }
Bevin Hansson313461f2020-01-08 14:01:30 +01003611 case BO_DivAssign:
Bevin Hansson0b9922e2019-11-19 13:15:06 +01003612 case BO_Div: {
3613 llvm::Intrinsic::ID IID;
3614 if (ResultFixedSema.isSaturated())
3615 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix_sat
3616 : llvm::Intrinsic::udiv_fix_sat;
3617 else
3618 IID = ResultFixedSema.isSigned() ? llvm::Intrinsic::sdiv_fix
3619 : llvm::Intrinsic::udiv_fix;
3620 Result = Builder.CreateIntrinsic(IID, {FullLHS->getType()},
3621 {FullLHS, FullRHS, Builder.getInt32(CommonFixedSema.getScale())});
3622 break;
3623 }
Leonard Chance1d4f12019-02-21 20:50:09 +00003624 case BO_LT:
3625 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLT(FullLHS, FullRHS)
3626 : Builder.CreateICmpULT(FullLHS, FullRHS);
3627 case BO_GT:
3628 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGT(FullLHS, FullRHS)
3629 : Builder.CreateICmpUGT(FullLHS, FullRHS);
3630 case BO_LE:
3631 return CommonFixedSema.isSigned() ? Builder.CreateICmpSLE(FullLHS, FullRHS)
3632 : Builder.CreateICmpULE(FullLHS, FullRHS);
3633 case BO_GE:
3634 return CommonFixedSema.isSigned() ? Builder.CreateICmpSGE(FullLHS, FullRHS)
3635 : Builder.CreateICmpUGE(FullLHS, FullRHS);
3636 case BO_EQ:
3637 // For equality operations, we assume any padding bits on unsigned types are
3638 // zero'd out. They could be overwritten through non-saturating operations
3639 // that cause overflow, but this leads to undefined behavior.
3640 return Builder.CreateICmpEQ(FullLHS, FullRHS);
3641 case BO_NE:
3642 return Builder.CreateICmpNE(FullLHS, FullRHS);
Leonard Chan837da5d2019-01-16 19:53:50 +00003643 case BO_Shl:
3644 case BO_Shr:
3645 case BO_Cmp:
Leonard Chan837da5d2019-01-16 19:53:50 +00003646 case BO_LAnd:
3647 case BO_LOr:
Leonard Chan837da5d2019-01-16 19:53:50 +00003648 case BO_ShlAssign:
3649 case BO_ShrAssign:
3650 llvm_unreachable("Found unimplemented fixed point binary operation");
3651 case BO_PtrMemD:
3652 case BO_PtrMemI:
3653 case BO_Rem:
3654 case BO_Xor:
3655 case BO_And:
3656 case BO_Or:
3657 case BO_Assign:
3658 case BO_RemAssign:
3659 case BO_AndAssign:
3660 case BO_XorAssign:
3661 case BO_OrAssign:
3662 case BO_Comma:
3663 llvm_unreachable("Found unsupported binary operation for fixed point types.");
Leonard Chan2044ac82019-01-16 18:13:59 +00003664 }
3665
3666 // Convert to the result type.
3667 return EmitFixedPointConversion(Result, CommonFixedSema, ResultFixedSema,
Bevin Hansson39baaab2020-01-08 11:12:55 +01003668 op.E->getExprLoc());
Leonard Chan2044ac82019-01-16 18:13:59 +00003669}
3670
John McCall77527a82011-06-25 01:32:37 +00003671Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
3672 // The LHS is always a pointer if either side is.
3673 if (!op.LHS->getType()->isPointerTy()) {
3674 if (op.Ty->isSignedIntegerOrEnumerationType()) {
Richard Smith9c6890a2012-11-01 22:30:59 +00003675 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
Chris Lattner51924e512010-06-26 21:25:03 +00003676 case LangOptions::SOB_Defined:
John McCall77527a82011-06-25 01:32:37 +00003677 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Richard Smith3e056de2012-08-25 00:32:28 +00003678 case LangOptions::SOB_Undefined:
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003679 if (!CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow))
Richard Smith3e056de2012-08-25 00:32:28 +00003680 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
Reid Kleckner4dc0b1a2018-11-01 19:54:45 +00003681 LLVM_FALLTHROUGH;
Chris Lattner51924e512010-06-26 21:25:03 +00003682 case LangOptions::SOB_Trapping:
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003683 if (CanElideOverflowCheck(CGF.getContext(), op))
3684 return Builder.CreateNSWSub(op.LHS, op.RHS, "sub");
John McCall77527a82011-06-25 01:32:37 +00003685 return EmitOverflowCheckedBinOp(op);
Chris Lattner51924e512010-06-26 21:25:03 +00003686 }
3687 }
Will Dietz1897cb32012-11-27 15:01:55 +00003688
Alexey Samsonovedf99a92014-11-07 22:29:38 +00003689 if (op.Ty->isUnsignedIntegerType() &&
Vedant Kumar82ee16b2017-02-25 00:43:36 +00003690 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow) &&
3691 !CanElideOverflowCheck(CGF.getContext(), op))
Will Dietz1897cb32012-11-27 15:01:55 +00003692 return EmitOverflowCheckedBinOp(op);
3693
Lang Hames5de91cc2012-10-02 04:45:10 +00003694 if (op.LHS->getType()->isFPOrFPVectorTy()) {
3695 // Try to form an fmuladd.
3696 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
3697 return FMulAdd;
Adam Nemet370d0872017-04-04 21:18:30 +00003698 Value *V = Builder.CreateFSub(op.LHS, op.RHS, "sub");
3699 return propagateFMFlags(V, op);
Lang Hames5de91cc2012-10-02 04:45:10 +00003700 }
Chris Lattner5902e7b2010-03-29 17:28:16 +00003701
Bevin Hansson39baaab2020-01-08 11:12:55 +01003702 if (op.isFixedPointOp())
Leonard Chan837da5d2019-01-16 19:53:50 +00003703 return EmitFixedPointBinOp(op);
3704
John McCall77527a82011-06-25 01:32:37 +00003705 return Builder.CreateSub(op.LHS, op.RHS, "sub");
Mike Stump0c61b732009-04-01 20:28:16 +00003706 }
Chris Lattner3d966d62007-08-24 21:00:35 +00003707
John McCall77527a82011-06-25 01:32:37 +00003708 // If the RHS is not a pointer, then we have normal pointer
3709 // arithmetic.
3710 if (!op.RHS->getType()->isPointerTy())
Vedant Kumar175b6d12017-07-13 20:55:26 +00003711 return emitPointerArithmetic(CGF, op, CodeGenFunction::IsSubtraction);
Eli Friedmane381f7e2009-03-28 02:45:41 +00003712
John McCall77527a82011-06-25 01:32:37 +00003713 // Otherwise, this is a pointer subtraction.
Daniel Dunbar42a8cd32009-01-23 18:51:09 +00003714
John McCall77527a82011-06-25 01:32:37 +00003715 // Do the raw subtraction part.
3716 llvm::Value *LHS
3717 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
3718 llvm::Value *RHS
3719 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
3720 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
Daniel Dunbaref2ffbc2009-04-25 05:08:32 +00003721
John McCall77527a82011-06-25 01:32:37 +00003722 // Okay, figure out the element size.
3723 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
3724 QualType elementType = expr->getLHS()->getType()->getPointeeType();
Mike Stump4a3999f2009-09-09 13:00:44 +00003725
Craig Topper8a13c412014-05-21 05:09:00 +00003726 llvm::Value *divisor = nullptr;
John McCall77527a82011-06-25 01:32:37 +00003727
3728 // For a variable-length array, this is going to be non-constant.
3729 if (const VariableArrayType *vla
3730 = CGF.getContext().getAsVariableArrayType(elementType)) {
Sander de Smalen891af03a2018-02-03 13:55:59 +00003731 auto VlaSize = CGF.getVLASize(vla);
3732 elementType = VlaSize.Type;
3733 divisor = VlaSize.NumElts;
John McCall77527a82011-06-25 01:32:37 +00003734
3735 // Scale the number of non-VLA elements by the non-VLA element size.
3736 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
3737 if (!eltSize.isOne())
3738 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
3739
3740 // For everything elese, we can just compute it, safe in the
3741 // assumption that Sema won't let anything through that we can't
3742 // safely compute the size of.
3743 } else {
3744 CharUnits elementSize;
3745 // Handle GCC extension for pointer arithmetic on void* and
3746 // function pointer types.
3747 if (elementType->isVoidType() || elementType->isFunctionType())
3748 elementSize = CharUnits::One();
3749 else
3750 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
3751
3752 // Don't even emit the divide for element size of 1.
3753 if (elementSize.isOne())
3754 return diffInChars;
3755
3756 divisor = CGF.CGM.getSize(elementSize);
Chris Lattner2da04b32007-08-24 05:35:26 +00003757 }
Craig Toppera97d7e72013-07-26 06:16:11 +00003758
Chris Lattner2e72da942011-03-01 00:03:48 +00003759 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
3760 // pointer difference in C is only defined in the case where both operands
3761 // are pointing to elements of an array.
John McCall77527a82011-06-25 01:32:37 +00003762 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
Chris Lattner2da04b32007-08-24 05:35:26 +00003763}
3764
David Tweed042e0882013-01-07 16:43:27 +00003765Value *ScalarExprEmitter::GetWidthMinusOneValue(Value* LHS,Value* RHS) {
David Tweed9fb566c2013-01-10 09:11:33 +00003766 llvm::IntegerType *Ty;
3767 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
3768 Ty = cast<llvm::IntegerType>(VT->getElementType());
3769 else
3770 Ty = cast<llvm::IntegerType>(LHS->getType());
3771 return llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth() - 1);
David Tweed042e0882013-01-07 16:43:27 +00003772}
3773
Chris Lattner2da04b32007-08-24 05:35:26 +00003774Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
3775 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3776 // RHS to the same size as the LHS.
3777 Value *RHS = Ops.RHS;
3778 if (Ops.LHS->getType() != RHS->getType())
3779 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00003780
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003781 bool SanitizeBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
James Molloy59802322016-08-16 09:45:36 +00003782 Ops.Ty->hasSignedIntegerRepresentation() &&
Richard Smith7939ba02019-06-25 01:45:26 +00003783 !CGF.getLangOpts().isSignedOverflowDefined() &&
3784 !CGF.getLangOpts().CPlusPlus2a;
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003785 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
3786 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3787 if (CGF.getLangOpts().OpenCL)
3788 RHS =
3789 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shl.mask");
3790 else if ((SanitizeBase || SanitizeExponent) &&
3791 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003792 CodeGenFunction::SanitizerScope SanScope(&CGF);
Peter Collingbourne3eea6772015-05-11 21:39:14 +00003793 SmallVector<std::pair<Value *, SanitizerMask>, 2> Checks;
Vedant Kumard3a601b2017-01-30 23:38:54 +00003794 llvm::Value *WidthMinusOne = GetWidthMinusOneValue(Ops.LHS, Ops.RHS);
3795 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
Richard Smith3e056de2012-08-25 00:32:28 +00003796
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003797 if (SanitizeExponent) {
3798 Checks.push_back(
3799 std::make_pair(ValidExponent, SanitizerKind::ShiftExponent));
3800 }
3801
3802 if (SanitizeBase) {
3803 // Check whether we are shifting any non-zero bits off the top of the
3804 // integer. We only emit this check if exponent is valid - otherwise
3805 // instructions below will have undefined behavior themselves.
Alexey Samsonov48a9db02015-03-05 21:57:35 +00003806 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
3807 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003808 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
3809 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
Vedant Kumard3a601b2017-01-30 23:38:54 +00003810 llvm::Value *PromotedWidthMinusOne =
3811 (RHS == Ops.RHS) ? WidthMinusOne
3812 : GetWidthMinusOneValue(Ops.LHS, RHS);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003813 CGF.EmitBlock(CheckShiftBase);
Vedant Kumard3a601b2017-01-30 23:38:54 +00003814 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
3815 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
3816 /*NUW*/ true, /*NSW*/ true),
3817 "shl.check");
Richard Smith3e056de2012-08-25 00:32:28 +00003818 if (CGF.getLangOpts().CPlusPlus) {
3819 // In C99, we are not permitted to shift a 1 bit into the sign bit.
3820 // Under C++11's rules, shifting a 1 bit into the sign bit is
3821 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
3822 // define signed left shifts, so we use the C99 and C++11 rules there).
3823 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
3824 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
3825 }
3826 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003827 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
Alexey Samsonov48a9db02015-03-05 21:57:35 +00003828 CGF.EmitBlock(Cont);
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003829 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
3830 BaseCheck->addIncoming(Builder.getTrue(), Orig);
3831 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
3832 Checks.push_back(std::make_pair(BaseCheck, SanitizerKind::ShiftBase));
Richard Smith3e056de2012-08-25 00:32:28 +00003833 }
Will Dietz11d0a9f2013-02-25 22:37:49 +00003834
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003835 assert(!Checks.empty());
3836 EmitBinOpCheck(Checks, Ops);
Mike Stumpba6a0c42009-12-14 21:58:14 +00003837 }
3838
Chris Lattner2da04b32007-08-24 05:35:26 +00003839 return Builder.CreateShl(Ops.LHS, RHS, "shl");
3840}
3841
3842Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
3843 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
3844 // RHS to the same size as the LHS.
3845 Value *RHS = Ops.RHS;
3846 if (Ops.LHS->getType() != RHS->getType())
3847 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
Mike Stump4a3999f2009-09-09 13:00:44 +00003848
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003849 // OpenCL 6.3j: shift values are effectively % word size of LHS.
3850 if (CGF.getLangOpts().OpenCL)
3851 RHS =
3852 Builder.CreateAnd(RHS, GetWidthMinusOneValue(Ops.LHS, RHS), "shr.mask");
3853 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
3854 isa<llvm::IntegerType>(Ops.LHS->getType())) {
Alexey Samsonov24cad992014-07-17 18:46:27 +00003855 CodeGenFunction::SanitizerScope SanScope(&CGF);
Alexey Samsonove396bfc2014-11-11 22:03:54 +00003856 llvm::Value *Valid =
3857 Builder.CreateICmpULE(RHS, GetWidthMinusOneValue(Ops.LHS, RHS));
Alexey Samsonov21d2dda2015-03-09 21:50:19 +00003858 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::ShiftExponent), Ops);
Alexey Samsonov24cad992014-07-17 18:46:27 +00003859 }
David Tweed042e0882013-01-07 16:43:27 +00003860
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00003861 if (Ops.Ty->hasUnsignedIntegerRepresentation())
Chris Lattner2da04b32007-08-24 05:35:26 +00003862 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
3863 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
3864}
3865
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003866enum IntrinsicType { VCMPEQ, VCMPGT };
3867// return corresponding comparison intrinsic for given vector type
3868static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
3869 BuiltinType::Kind ElemKind) {
3870 switch (ElemKind) {
David Blaikie83d382b2011-09-23 05:06:16 +00003871 default: llvm_unreachable("unexpected element type");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003872 case BuiltinType::Char_U:
3873 case BuiltinType::UChar:
3874 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3875 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003876 case BuiltinType::Char_S:
3877 case BuiltinType::SChar:
3878 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
3879 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003880 case BuiltinType::UShort:
3881 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3882 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003883 case BuiltinType::Short:
3884 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
3885 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003886 case BuiltinType::UInt:
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003887 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3888 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003889 case BuiltinType::Int:
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003890 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
3891 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
Guozhi Wei769095b2017-10-19 20:11:23 +00003892 case BuiltinType::ULong:
3893 case BuiltinType::ULongLong:
3894 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3895 llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
3896 case BuiltinType::Long:
3897 case BuiltinType::LongLong:
3898 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
3899 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003900 case BuiltinType::Float:
3901 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
3902 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
Guozhi Wei769095b2017-10-19 20:11:23 +00003903 case BuiltinType::Double:
3904 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
3905 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003906 }
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003907}
3908
Craig Topperc82f8962015-12-16 06:24:28 +00003909Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
3910 llvm::CmpInst::Predicate UICmpOpc,
3911 llvm::CmpInst::Predicate SICmpOpc,
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +01003912 llvm::CmpInst::Predicate FCmpOpc,
3913 bool IsSignaling) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00003914 TestAndClearIgnoreResultAssign();
Chris Lattner42e6b812007-08-26 16:34:22 +00003915 Value *Result;
Chris Lattner2da04b32007-08-24 05:35:26 +00003916 QualType LHSTy = E->getLHS()->getType();
Chandler Carruthb29a7432014-10-11 11:03:30 +00003917 QualType RHSTy = E->getRHS()->getType();
John McCall7a9aac22010-08-23 01:21:21 +00003918 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
John McCalle3027922010-08-25 11:45:40 +00003919 assert(E->getOpcode() == BO_EQ ||
3920 E->getOpcode() == BO_NE);
John McCalla1dee5302010-08-22 10:59:02 +00003921 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
3922 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
John McCall7a9aac22010-08-23 01:21:21 +00003923 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
John McCalle3027922010-08-25 11:45:40 +00003924 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
Chandler Carruthb29a7432014-10-11 11:03:30 +00003925 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
Leonard Chance1d4f12019-02-21 20:50:09 +00003926 BinOpInfo BOInfo = EmitBinOps(E);
3927 Value *LHS = BOInfo.LHS;
3928 Value *RHS = BOInfo.RHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00003929
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003930 // If AltiVec, the comparison results in a numeric type, so we use
3931 // intrinsics comparing vectors and giving 0 or 1 as a result
Anton Yartsev93900c72011-03-28 21:00:05 +00003932 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003933 // constants for mapping CR6 register bits to predicate result
3934 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
3935
3936 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
3937
3938 // in several cases vector arguments order will be reversed
3939 Value *FirstVecArg = LHS,
3940 *SecondVecArg = RHS;
3941
Simon Pilgrime0712012019-10-02 15:31:25 +00003942 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
Simon Pilgrim16c53ff2020-01-11 15:33:25 +00003943 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003944
3945 switch(E->getOpcode()) {
David Blaikie83d382b2011-09-23 05:06:16 +00003946 default: llvm_unreachable("is not a comparison operation");
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003947 case BO_EQ:
3948 CR6 = CR6_LT;
3949 ID = GetIntrinsic(VCMPEQ, ElementKind);
3950 break;
3951 case BO_NE:
3952 CR6 = CR6_EQ;
3953 ID = GetIntrinsic(VCMPEQ, ElementKind);
3954 break;
3955 case BO_LT:
3956 CR6 = CR6_LT;
3957 ID = GetIntrinsic(VCMPGT, ElementKind);
3958 std::swap(FirstVecArg, SecondVecArg);
3959 break;
3960 case BO_GT:
3961 CR6 = CR6_LT;
3962 ID = GetIntrinsic(VCMPGT, ElementKind);
3963 break;
3964 case BO_LE:
3965 if (ElementKind == BuiltinType::Float) {
3966 CR6 = CR6_LT;
3967 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3968 std::swap(FirstVecArg, SecondVecArg);
3969 }
3970 else {
3971 CR6 = CR6_EQ;
3972 ID = GetIntrinsic(VCMPGT, ElementKind);
3973 }
3974 break;
3975 case BO_GE:
3976 if (ElementKind == BuiltinType::Float) {
3977 CR6 = CR6_LT;
3978 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
3979 }
3980 else {
3981 CR6 = CR6_EQ;
3982 ID = GetIntrinsic(VCMPGT, ElementKind);
3983 std::swap(FirstVecArg, SecondVecArg);
3984 }
3985 break;
3986 }
3987
Chris Lattner2531eb42011-04-19 22:55:03 +00003988 Value *CR6Param = Builder.getInt32(CR6);
Anton Yartsev3f8f2882010-11-18 03:19:30 +00003989 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
David Blaikie43f9bb72015-05-18 22:14:03 +00003990 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
Guozhi Wei3625f3e2017-10-10 20:31:27 +00003991
3992 // The result type of intrinsic may not be same as E->getType().
3993 // If E->getType() is not BoolTy, EmitScalarConversion will do the
3994 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
3995 // do nothing, if ResultTy is not i1 at the same time, it will cause
3996 // crash later.
3997 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
3998 if (ResultTy->getBitWidth() > 1 &&
3999 E->getType() == CGF.getContext().BoolTy)
4000 Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004001 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4002 E->getExprLoc());
Anton Yartsev3f8f2882010-11-18 03:19:30 +00004003 }
4004
Bevin Hansson39baaab2020-01-08 11:12:55 +01004005 if (BOInfo.isFixedPointOp()) {
Leonard Chance1d4f12019-02-21 20:50:09 +00004006 Result = EmitFixedPointBinOp(BOInfo);
4007 } else if (LHS->getType()->isFPOrFPVectorTy()) {
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +01004008 if (!IsSignaling)
4009 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
4010 else
4011 Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
Douglas Gregor5cc2c8b2010-07-23 15:58:24 +00004012 } else if (LHSTy->hasSignedIntegerRepresentation()) {
Craig Topperc82f8962015-12-16 06:24:28 +00004013 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
Chris Lattner2da04b32007-08-24 05:35:26 +00004014 } else {
Eli Friedman3c285242008-05-29 15:09:15 +00004015 // Unsigned integers and pointers.
Piotr Padlewski07058292018-07-02 19:21:36 +00004016
4017 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
4018 !isa<llvm::ConstantPointerNull>(LHS) &&
4019 !isa<llvm::ConstantPointerNull>(RHS)) {
4020
4021 // Dynamic information is required to be stripped for comparisons,
4022 // because it could leak the dynamic information. Based on comparisons
4023 // of pointers to dynamic objects, the optimizer can replace one pointer
4024 // with another, which might be incorrect in presence of invariant
4025 // groups. Comparison with null is safe because null does not carry any
4026 // dynamic information.
4027 if (LHSTy.mayBeDynamicClass())
4028 LHS = Builder.CreateStripInvariantGroup(LHS);
4029 if (RHSTy.mayBeDynamicClass())
4030 RHS = Builder.CreateStripInvariantGroup(RHS);
4031 }
4032
Craig Topperc82f8962015-12-16 06:24:28 +00004033 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
Chris Lattner2da04b32007-08-24 05:35:26 +00004034 }
Chris Lattner2a7deb62009-07-08 01:08:03 +00004035
4036 // If this is a vector comparison, sign extend the result to the appropriate
4037 // vector integer type and return it (don't convert to bool).
4038 if (LHSTy->isVectorType())
4039 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
Mike Stump4a3999f2009-09-09 13:00:44 +00004040
Chris Lattner2da04b32007-08-24 05:35:26 +00004041 } else {
4042 // Complex Comparison: can only be an equality comparison.
Chandler Carruthb29a7432014-10-11 11:03:30 +00004043 CodeGenFunction::ComplexPairTy LHS, RHS;
4044 QualType CETy;
4045 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
4046 LHS = CGF.EmitComplexExpr(E->getLHS());
4047 CETy = CTy->getElementType();
4048 } else {
4049 LHS.first = Visit(E->getLHS());
4050 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
4051 CETy = LHSTy;
4052 }
4053 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
4054 RHS = CGF.EmitComplexExpr(E->getRHS());
4055 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
4056 CTy->getElementType()) &&
4057 "The element types must always match.");
Chandler Carruth60fdc412014-10-11 11:29:26 +00004058 (void)CTy;
Chandler Carruthb29a7432014-10-11 11:03:30 +00004059 } else {
4060 RHS.first = Visit(E->getRHS());
4061 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
4062 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
4063 "The element types must always match.");
4064 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004065
Chris Lattner42e6b812007-08-26 16:34:22 +00004066 Value *ResultR, *ResultI;
Chris Lattner2da04b32007-08-24 05:35:26 +00004067 if (CETy->isRealFloatingType()) {
Ulrich Weigand76e9c2a2020-01-10 14:29:24 +01004068 // As complex comparisons can only be equality comparisons, they
4069 // are never signaling comparisons.
Craig Topperc82f8962015-12-16 06:24:28 +00004070 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
4071 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
Chris Lattner2da04b32007-08-24 05:35:26 +00004072 } else {
4073 // Complex comparisons can only be equality comparisons. As such, signed
4074 // and unsigned opcodes are the same.
Craig Topperc82f8962015-12-16 06:24:28 +00004075 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
4076 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
Chris Lattner2da04b32007-08-24 05:35:26 +00004077 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004078
John McCalle3027922010-08-25 11:45:40 +00004079 if (E->getOpcode() == BO_EQ) {
Chris Lattner2da04b32007-08-24 05:35:26 +00004080 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
4081 } else {
John McCalle3027922010-08-25 11:45:40 +00004082 assert(E->getOpcode() == BO_NE &&
Chris Lattner2da04b32007-08-24 05:35:26 +00004083 "Complex comparison other than == or != ?");
4084 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
4085 }
4086 }
Nuno Lopesa0abe622009-01-11 23:22:37 +00004087
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004088 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
4089 E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00004090}
4091
4092Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00004093 bool Ignore = TestAndClearIgnoreResultAssign();
4094
John McCall31168b02011-06-15 23:02:42 +00004095 Value *RHS;
4096 LValue LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00004097
John McCall31168b02011-06-15 23:02:42 +00004098 switch (E->getLHS()->getType().getObjCLifetime()) {
4099 case Qualifiers::OCL_Strong:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004100 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
John McCall31168b02011-06-15 23:02:42 +00004101 break;
4102
4103 case Qualifiers::OCL_Autoreleasing:
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00004104 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
John McCall31168b02011-06-15 23:02:42 +00004105 break;
4106
John McCalle399e5b2016-01-27 18:32:30 +00004107 case Qualifiers::OCL_ExplicitNone:
4108 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
4109 break;
4110
John McCall31168b02011-06-15 23:02:42 +00004111 case Qualifiers::OCL_Weak:
4112 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00004113 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004114 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(CGF), RHS, Ignore);
John McCall31168b02011-06-15 23:02:42 +00004115 break;
4116
John McCall31168b02011-06-15 23:02:42 +00004117 case Qualifiers::OCL_None:
John McCall31168b02011-06-15 23:02:42 +00004118 // __block variables need to have the rhs evaluated first, plus
4119 // this should improve codegen just a little.
4120 RHS = Visit(E->getRHS());
Richard Smith4d1458e2012-09-08 02:08:36 +00004121 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
John McCall31168b02011-06-15 23:02:42 +00004122
4123 // Store the value into the LHS. Bit-fields are handled specially
4124 // because the result is altered by the store, i.e., [C99 6.5.16p1]
4125 // 'An assignment expression has the value of the left operand after
4126 // the assignment...'.
Vedant Kumar42c17ec2017-03-14 01:56:34 +00004127 if (LHS.isBitField()) {
John McCall55e1fbc2011-06-25 02:11:03 +00004128 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +00004129 } else {
4130 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
John McCall55e1fbc2011-06-25 02:11:03 +00004131 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
Vedant Kumar42c17ec2017-03-14 01:56:34 +00004132 }
John McCall31168b02011-06-15 23:02:42 +00004133 }
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004134
4135 // If the result is clearly ignored, return now.
Mike Stumpdf0fe272009-05-29 15:46:01 +00004136 if (Ignore)
Craig Topper8a13c412014-05-21 05:09:00 +00004137 return nullptr;
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004138
John McCall07bb1962010-11-16 10:08:07 +00004139 // The result of an assignment in C is the assigned r-value.
Richard Smith9c6890a2012-11-01 22:30:59 +00004140 if (!CGF.getLangOpts().CPlusPlus)
John McCall07bb1962010-11-16 10:08:07 +00004141 return RHS;
4142
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004143 // If the lvalue is non-volatile, return the computed value of the assignment.
4144 if (!LHS.isVolatileQualified())
4145 return RHS;
4146
4147 // Otherwise, reload the value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00004148 return EmitLoadOfLValue(LHS, E->getExprLoc());
Chris Lattner2da04b32007-08-24 05:35:26 +00004149}
4150
4151Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00004152 // Perform vector logical and on comparisons with zero vectors.
4153 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00004154 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004155
Tanya Lattner20248222012-01-16 21:02:28 +00004156 Value *LHS = Visit(E->getLHS());
4157 Value *RHS = Visit(E->getRHS());
4158 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00004159 if (LHS->getType()->isFPOrFPVectorTy()) {
4160 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4161 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4162 } else {
4163 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4164 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4165 }
Tanya Lattner20248222012-01-16 21:02:28 +00004166 Value *And = Builder.CreateAnd(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00004167 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00004168 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004169
Chris Lattner2192fe52011-07-18 04:24:23 +00004170 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00004171
Chris Lattner8b084582008-11-12 08:26:50 +00004172 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
4173 // If we have 1 && X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00004174 bool LHSCondVal;
4175 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4176 if (LHSCondVal) { // If we have 1 && X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00004177 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004178
Chris Lattner5b1964b2008-11-11 07:41:27 +00004179 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00004180 // ZExt result to int or bool.
4181 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00004182 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004183
Chris Lattner671fec82009-10-17 04:24:20 +00004184 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
Chris Lattner8b084582008-11-12 08:26:50 +00004185 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00004186 return llvm::Constant::getNullValue(ResTy);
Chris Lattner5b1964b2008-11-11 07:41:27 +00004187 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004188
Daniel Dunbara612e792008-11-13 01:38:36 +00004189 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
4190 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
Chris Lattner8b084582008-11-12 08:26:50 +00004191
John McCallce1de612011-01-26 04:00:11 +00004192 CodeGenFunction::ConditionalEvaluation eval(CGF);
4193
Chris Lattner35710d182008-11-12 08:38:24 +00004194 // Branch on the LHS first. If it is false, go to the failure (cont) block.
Justin Bogner66242d62015-04-23 23:06:47 +00004195 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, ContBlock,
4196 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00004197
4198 // Any edges into the ContBlock are now from an (indeterminate number of)
4199 // edges from this first condition. All of these values will be false. Start
4200 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00004201 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00004202 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00004203 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4204 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00004205 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
Mike Stump4a3999f2009-09-09 13:00:44 +00004206
John McCallce1de612011-01-26 04:00:11 +00004207 eval.begin(CGF);
Chris Lattner2da04b32007-08-24 05:35:26 +00004208 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004209 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00004210 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
John McCallce1de612011-01-26 04:00:11 +00004211 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004212
Chris Lattner2da04b32007-08-24 05:35:26 +00004213 // Reaquire the RHS block, as there may be subblocks inserted.
4214 RHSBlock = Builder.GetInsertBlock();
Chris Lattner35710d182008-11-12 08:38:24 +00004215
David Blaikie1b5adb82014-07-10 20:42:59 +00004216 // Emit an unconditional branch from this block to ContBlock.
4217 {
Devang Patel4d761272011-03-30 00:08:31 +00004218 // There is no need to emit line number for unconditional branch.
Adrian Prantl95b24e92015-02-03 20:00:54 +00004219 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
David Blaikie1b5adb82014-07-10 20:42:59 +00004220 CGF.EmitBlock(ContBlock);
4221 }
4222 // Insert an entry into the phi node for the edge with the value of RHSCond.
Chris Lattner2da04b32007-08-24 05:35:26 +00004223 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004224
Anastasis Grammenosdfe8fe52018-06-21 16:53:48 +00004225 // Artificial location to preserve the scope information
4226 {
4227 auto NL = ApplyDebugLocation::CreateArtificial(CGF);
4228 PN->setDebugLoc(Builder.getCurrentDebugLocation());
4229 }
4230
Chris Lattner2da04b32007-08-24 05:35:26 +00004231 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00004232 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00004233}
4234
4235Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
Tanya Lattner20248222012-01-16 21:02:28 +00004236 // Perform vector logical or on comparisons with zero vectors.
4237 if (E->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00004238 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004239
Tanya Lattner20248222012-01-16 21:02:28 +00004240 Value *LHS = Visit(E->getLHS());
4241 Value *RHS = Visit(E->getRHS());
4242 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
Joey Gouly7d00f002013-02-21 11:49:56 +00004243 if (LHS->getType()->isFPOrFPVectorTy()) {
4244 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
4245 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
4246 } else {
4247 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
4248 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
4249 }
Tanya Lattner20248222012-01-16 21:02:28 +00004250 Value *Or = Builder.CreateOr(LHS, RHS);
Joey Gouly7d00f002013-02-21 11:49:56 +00004251 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
Tanya Lattner20248222012-01-16 21:02:28 +00004252 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004253
Chris Lattner2192fe52011-07-18 04:24:23 +00004254 llvm::Type *ResTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00004255
Chris Lattner8b084582008-11-12 08:26:50 +00004256 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
4257 // If we have 0 || X, just emit X without inserting the control flow.
Chris Lattner41c6ab52011-02-27 23:02:32 +00004258 bool LHSCondVal;
4259 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
4260 if (!LHSCondVal) { // If we have 0 || X, just emit X.
Justin Bogner66242d62015-04-23 23:06:47 +00004261 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004262
Chris Lattner5b1964b2008-11-11 07:41:27 +00004263 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Chris Lattner671fec82009-10-17 04:24:20 +00004264 // ZExt result to int or bool.
4265 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
Chris Lattner5b1964b2008-11-11 07:41:27 +00004266 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004267
Chris Lattner671fec82009-10-17 04:24:20 +00004268 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
Chris Lattner8b084582008-11-12 08:26:50 +00004269 if (!CGF.ContainsLabel(E->getRHS()))
Chris Lattner671fec82009-10-17 04:24:20 +00004270 return llvm::ConstantInt::get(ResTy, 1);
Chris Lattner5b1964b2008-11-11 07:41:27 +00004271 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004272
Daniel Dunbara612e792008-11-13 01:38:36 +00004273 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
4274 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
Mike Stump4a3999f2009-09-09 13:00:44 +00004275
John McCallce1de612011-01-26 04:00:11 +00004276 CodeGenFunction::ConditionalEvaluation eval(CGF);
4277
Chris Lattner35710d182008-11-12 08:38:24 +00004278 // Branch on the LHS first. If it is true, go to the success (cont) block.
Justin Bogneref512b92014-01-06 22:27:43 +00004279 CGF.EmitBranchOnBoolExpr(E->getLHS(), ContBlock, RHSBlock,
Justin Bogner66242d62015-04-23 23:06:47 +00004280 CGF.getCurrentProfileCount() -
4281 CGF.getProfileCount(E->getRHS()));
Chris Lattner35710d182008-11-12 08:38:24 +00004282
4283 // Any edges into the ContBlock are now from an (indeterminate number of)
4284 // edges from this first condition. All of these values will be true. Start
4285 // setting up the PHI node in the Cont Block for this.
Jay Foad20c0f022011-03-30 11:28:58 +00004286 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
Owen Anderson41a75022009-08-13 21:57:51 +00004287 "", ContBlock);
Chris Lattner35710d182008-11-12 08:38:24 +00004288 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
4289 PI != PE; ++PI)
Owen Andersonfe4e3472009-07-31 17:39:36 +00004290 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
Chris Lattner35710d182008-11-12 08:38:24 +00004291
John McCallce1de612011-01-26 04:00:11 +00004292 eval.begin(CGF);
Anders Carlssonf47a3de2009-06-04 02:53:13 +00004293
Chris Lattner35710d182008-11-12 08:38:24 +00004294 // Emit the RHS condition as a bool value.
Chris Lattner2da04b32007-08-24 05:35:26 +00004295 CGF.EmitBlock(RHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004296 CGF.incrementProfileCounter(E);
Chris Lattner2da04b32007-08-24 05:35:26 +00004297 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
Mike Stump4a3999f2009-09-09 13:00:44 +00004298
John McCallce1de612011-01-26 04:00:11 +00004299 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004300
Chris Lattner2da04b32007-08-24 05:35:26 +00004301 // Reaquire the RHS block, as there may be subblocks inserted.
4302 RHSBlock = Builder.GetInsertBlock();
Mike Stump4a3999f2009-09-09 13:00:44 +00004303
Chris Lattner35710d182008-11-12 08:38:24 +00004304 // Emit an unconditional branch from this block to ContBlock. Insert an entry
4305 // into the phi node for the edge with the value of RHSCond.
4306 CGF.EmitBlock(ContBlock);
Chris Lattner2da04b32007-08-24 05:35:26 +00004307 PN->addIncoming(RHSCond, RHSBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004308
Chris Lattner2da04b32007-08-24 05:35:26 +00004309 // ZExt result to int.
Chris Lattner671fec82009-10-17 04:24:20 +00004310 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
Chris Lattner2da04b32007-08-24 05:35:26 +00004311}
4312
4313Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
John McCalla2342eb2010-12-05 02:00:02 +00004314 CGF.EmitIgnoredExpr(E->getLHS());
Daniel Dunbar5c7e3932008-11-11 23:11:34 +00004315 CGF.EnsureInsertPoint();
Chris Lattner2da04b32007-08-24 05:35:26 +00004316 return Visit(E->getRHS());
4317}
4318
4319//===----------------------------------------------------------------------===//
4320// Other Operators
4321//===----------------------------------------------------------------------===//
4322
Chris Lattner3fd91f832008-11-12 08:55:54 +00004323/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
4324/// expression is cheap enough and side-effect-free enough to evaluate
4325/// unconditionally instead of conditionally. This is used to convert control
4326/// flow into selects in some cases.
Mike Stump53f9ded2009-11-03 23:25:48 +00004327static bool isCheapEnoughToEvaluateUnconditionally(const Expr *E,
4328 CodeGenFunction &CGF) {
Chris Lattner56784f92011-04-16 23:15:35 +00004329 // Anything that is an integer or floating point constant is fine.
Nick Lewycky22e55a02013-11-08 23:00:12 +00004330 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
Mike Stump4a3999f2009-09-09 13:00:44 +00004331
Nick Lewycky22e55a02013-11-08 23:00:12 +00004332 // Even non-volatile automatic variables can't be evaluated unconditionally.
4333 // Referencing a thread_local may cause non-trivial initialization work to
4334 // occur. If we're inside a lambda and one of the variables is from the scope
4335 // outside the lambda, that function may have returned already. Reading its
4336 // locals is a bad idea. Also, these reads may introduce races there didn't
4337 // exist in the source-level program.
Chris Lattner3fd91f832008-11-12 08:55:54 +00004338}
4339
4340
Chris Lattner2da04b32007-08-24 05:35:26 +00004341Value *ScalarExprEmitter::
John McCallc07a0c72011-02-17 10:25:35 +00004342VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
Mike Stumpdf0fe272009-05-29 15:46:01 +00004343 TestAndClearIgnoreResultAssign();
John McCallc07a0c72011-02-17 10:25:35 +00004344
4345 // Bind the common expression if necessary.
Eli Friedman48fd89a2012-01-06 20:42:20 +00004346 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
John McCallc07a0c72011-02-17 10:25:35 +00004347
4348 Expr *condExpr = E->getCond();
4349 Expr *lhsExpr = E->getTrueExpr();
4350 Expr *rhsExpr = E->getFalseExpr();
4351
Chris Lattnercd439292008-11-12 08:04:58 +00004352 // If the condition constant folds and can be elided, try to avoid emitting
4353 // the condition and the dead arm.
Chris Lattner41c6ab52011-02-27 23:02:32 +00004354 bool CondExprBool;
4355 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
John McCallc07a0c72011-02-17 10:25:35 +00004356 Expr *live = lhsExpr, *dead = rhsExpr;
Chris Lattner41c6ab52011-02-27 23:02:32 +00004357 if (!CondExprBool) std::swap(live, dead);
Mike Stump4a3999f2009-09-09 13:00:44 +00004358
Eli Friedman27ef75b2011-10-15 02:10:40 +00004359 // If the dead side doesn't have labels we need, just emit the Live part.
4360 if (!CGF.ContainsLabel(dead)) {
Justin Bogneref512b92014-01-06 22:27:43 +00004361 if (CondExprBool)
Justin Bogner66242d62015-04-23 23:06:47 +00004362 CGF.incrementProfileCounter(E);
Eli Friedman27ef75b2011-10-15 02:10:40 +00004363 Value *Result = Visit(live);
4364
4365 // If the live part is a throw expression, it acts like it has a void
4366 // type, so evaluating it returns a null Value*. However, a conditional
4367 // with non-void type must return a non-null Value*.
4368 if (!Result && !E->getType()->isVoidType())
4369 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
4370
4371 return Result;
4372 }
Chris Lattnerd53e2332008-11-11 18:56:45 +00004373 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004374
Nate Begemanabb5a732010-09-20 22:41:17 +00004375 // OpenCL: If the condition is a vector, we can treat this condition like
4376 // the select function.
Craig Toppera97d7e72013-07-26 06:16:11 +00004377 if (CGF.getLangOpts().OpenCL
John McCallc07a0c72011-02-17 10:25:35 +00004378 && condExpr->getType()->isVectorType()) {
Justin Bogner66242d62015-04-23 23:06:47 +00004379 CGF.incrementProfileCounter(E);
Justin Bogneref512b92014-01-06 22:27:43 +00004380
John McCallc07a0c72011-02-17 10:25:35 +00004381 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4382 llvm::Value *LHS = Visit(lhsExpr);
4383 llvm::Value *RHS = Visit(rhsExpr);
Craig Toppera97d7e72013-07-26 06:16:11 +00004384
Chris Lattner2192fe52011-07-18 04:24:23 +00004385 llvm::Type *condType = ConvertType(condExpr->getType());
4386 llvm::VectorType *vecTy = cast<llvm::VectorType>(condType);
Craig Toppera97d7e72013-07-26 06:16:11 +00004387
4388 unsigned numElem = vecTy->getNumElements();
Chris Lattner2192fe52011-07-18 04:24:23 +00004389 llvm::Type *elemType = vecTy->getElementType();
Craig Toppera97d7e72013-07-26 06:16:11 +00004390
Chris Lattner2d6b7b92012-01-25 05:34:41 +00004391 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
Nate Begemanabb5a732010-09-20 22:41:17 +00004392 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
Craig Toppera97d7e72013-07-26 06:16:11 +00004393 llvm::Value *tmp = Builder.CreateSExt(TestMSB,
Nate Begemanabb5a732010-09-20 22:41:17 +00004394 llvm::VectorType::get(elemType,
Craig Toppera97d7e72013-07-26 06:16:11 +00004395 numElem),
Nate Begemanabb5a732010-09-20 22:41:17 +00004396 "sext");
4397 llvm::Value *tmp2 = Builder.CreateNot(tmp);
Craig Toppera97d7e72013-07-26 06:16:11 +00004398
Nate Begemanabb5a732010-09-20 22:41:17 +00004399 // Cast float to int to perform ANDs if necessary.
4400 llvm::Value *RHSTmp = RHS;
4401 llvm::Value *LHSTmp = LHS;
4402 bool wasCast = false;
Chris Lattner2192fe52011-07-18 04:24:23 +00004403 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
Peter Collingbourneaac265c2012-05-29 00:35:18 +00004404 if (rhsVTy->getElementType()->isFloatingPointTy()) {
Nate Begemanabb5a732010-09-20 22:41:17 +00004405 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
4406 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
4407 wasCast = true;
4408 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004409
Nate Begemanabb5a732010-09-20 22:41:17 +00004410 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
4411 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
4412 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
4413 if (wasCast)
4414 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
4415
4416 return tmp5;
4417 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004418
Erich Keane349636d2019-12-05 06:17:39 -08004419 if (condExpr->getType()->isVectorType()) {
4420 CGF.incrementProfileCounter(E);
4421
4422 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
4423 llvm::Value *LHS = Visit(lhsExpr);
4424 llvm::Value *RHS = Visit(rhsExpr);
4425
4426 llvm::Type *CondType = ConvertType(condExpr->getType());
4427 auto *VecTy = cast<llvm::VectorType>(CondType);
4428 llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
4429
4430 CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
4431 return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
4432 }
4433
Chris Lattner3fd91f832008-11-12 08:55:54 +00004434 // If this is a really simple expression (like x ? 4 : 5), emit this as a
4435 // select instead of as control flow. We can only do this if it is cheap and
Chris Lattner9ce8a532008-11-16 06:16:27 +00004436 // safe to evaluate the LHS and RHS unconditionally.
John McCallc07a0c72011-02-17 10:25:35 +00004437 if (isCheapEnoughToEvaluateUnconditionally(lhsExpr, CGF) &&
4438 isCheapEnoughToEvaluateUnconditionally(rhsExpr, CGF)) {
4439 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
Vedant Kumar502bbfa2017-02-25 06:35:45 +00004440 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
4441
4442 CGF.incrementProfileCounter(E, StepV);
4443
John McCallc07a0c72011-02-17 10:25:35 +00004444 llvm::Value *LHS = Visit(lhsExpr);
4445 llvm::Value *RHS = Visit(rhsExpr);
Eli Friedman516c2ad2011-12-08 22:01:56 +00004446 if (!LHS) {
4447 // If the conditional has void type, make sure we return a null Value*.
4448 assert(!RHS && "LHS and RHS types must match");
Craig Topper8a13c412014-05-21 05:09:00 +00004449 return nullptr;
Eli Friedman516c2ad2011-12-08 22:01:56 +00004450 }
Chris Lattner3fd91f832008-11-12 08:55:54 +00004451 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
4452 }
Mike Stump4a3999f2009-09-09 13:00:44 +00004453
Daniel Dunbard2a53a72008-11-12 10:13:37 +00004454 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
4455 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
Daniel Dunbara612e792008-11-13 01:38:36 +00004456 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
John McCallce1de612011-01-26 04:00:11 +00004457
4458 CodeGenFunction::ConditionalEvaluation eval(CGF);
Justin Bogner66242d62015-04-23 23:06:47 +00004459 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
4460 CGF.getProfileCount(lhsExpr));
Anders Carlsson43c52cd2009-06-04 03:00:32 +00004461
Chris Lattner2da04b32007-08-24 05:35:26 +00004462 CGF.EmitBlock(LHSBlock);
Justin Bogner66242d62015-04-23 23:06:47 +00004463 CGF.incrementProfileCounter(E);
John McCallce1de612011-01-26 04:00:11 +00004464 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00004465 Value *LHS = Visit(lhsExpr);
John McCallce1de612011-01-26 04:00:11 +00004466 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004467
Chris Lattner2da04b32007-08-24 05:35:26 +00004468 LHSBlock = Builder.GetInsertBlock();
John McCallce1de612011-01-26 04:00:11 +00004469 Builder.CreateBr(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004470
Chris Lattner2da04b32007-08-24 05:35:26 +00004471 CGF.EmitBlock(RHSBlock);
John McCallce1de612011-01-26 04:00:11 +00004472 eval.begin(CGF);
John McCallc07a0c72011-02-17 10:25:35 +00004473 Value *RHS = Visit(rhsExpr);
John McCallce1de612011-01-26 04:00:11 +00004474 eval.end(CGF);
Mike Stump4a3999f2009-09-09 13:00:44 +00004475
John McCallce1de612011-01-26 04:00:11 +00004476 RHSBlock = Builder.GetInsertBlock();
Chris Lattner2da04b32007-08-24 05:35:26 +00004477 CGF.EmitBlock(ContBlock);
Mike Stump4a3999f2009-09-09 13:00:44 +00004478
Eli Friedmanf6c175b2009-12-07 20:25:53 +00004479 // If the LHS or RHS is a throw expression, it will be legitimately null.
4480 if (!LHS)
4481 return RHS;
4482 if (!RHS)
4483 return LHS;
Mike Stump4a3999f2009-09-09 13:00:44 +00004484
Chris Lattner2da04b32007-08-24 05:35:26 +00004485 // Create a PHI node for the real part.
Jay Foad20c0f022011-03-30 11:28:58 +00004486 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
Chris Lattner2da04b32007-08-24 05:35:26 +00004487 PN->addIncoming(LHS, LHSBlock);
4488 PN->addIncoming(RHS, RHSBlock);
4489 return PN;
4490}
4491
4492Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
Eli Friedman75807f22013-07-20 00:40:58 +00004493 return Visit(E->getChosenSubExpr());
Chris Lattner2da04b32007-08-24 05:35:26 +00004494}
4495
Chris Lattnerb6a7b582007-11-30 17:56:23 +00004496Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
Richard Smitha1a808c2014-04-14 23:47:48 +00004497 QualType Ty = VE->getType();
Daniel Sanders59229dc2014-11-19 10:01:35 +00004498
Richard Smitha1a808c2014-04-14 23:47:48 +00004499 if (Ty->isVariablyModifiedType())
4500 CGF.EmitVariablyModifiedType(Ty);
4501
Charles Davisc7d5c942015-09-17 20:55:33 +00004502 Address ArgValue = Address::invalid();
4503 Address ArgPtr = CGF.EmitVAArg(VE, ArgValue);
4504
Daniel Sanders59229dc2014-11-19 10:01:35 +00004505 llvm::Type *ArgTy = ConvertType(VE->getType());
Anders Carlsson13abd7e2008-11-04 05:30:00 +00004506
James Y Knight29b5f082016-02-24 02:59:33 +00004507 // If EmitVAArg fails, emit an error.
4508 if (!ArgPtr.isValid()) {
4509 CGF.ErrorUnsupported(VE, "va_arg expression");
4510 return llvm::UndefValue::get(ArgTy);
4511 }
Anders Carlsson13abd7e2008-11-04 05:30:00 +00004512
Mike Stumpdf0fe272009-05-29 15:46:01 +00004513 // FIXME Volatility.
Daniel Sanders59229dc2014-11-19 10:01:35 +00004514 llvm::Value *Val = Builder.CreateLoad(ArgPtr);
4515
4516 // If EmitVAArg promoted the type, we must truncate it.
Daniel Sanderscdcb5802015-01-13 10:47:00 +00004517 if (ArgTy != Val->getType()) {
4518 if (ArgTy->isPointerTy() && !Val->getType()->isPointerTy())
4519 Val = Builder.CreateIntToPtr(Val, ArgTy);
4520 else
4521 Val = Builder.CreateTrunc(Val, ArgTy);
4522 }
Daniel Sanders59229dc2014-11-19 10:01:35 +00004523
4524 return Val;
Anders Carlsson7e13ab82007-10-15 20:28:48 +00004525}
4526
John McCall351762c2011-02-07 10:33:21 +00004527Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
4528 return CGF.EmitBlockLiteral(block);
Mike Stumpab3afd82009-02-12 18:29:15 +00004529}
4530
Yaxun Liuc5647012016-06-08 15:11:21 +00004531// Convert a vec3 to vec4, or vice versa.
4532static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
4533 Value *Src, unsigned NumElementsDst) {
4534 llvm::Value *UnV = llvm::UndefValue::get(Src->getType());
4535 SmallVector<llvm::Constant*, 4> Args;
4536 Args.push_back(Builder.getInt32(0));
4537 Args.push_back(Builder.getInt32(1));
4538 Args.push_back(Builder.getInt32(2));
4539 if (NumElementsDst == 4)
4540 Args.push_back(llvm::UndefValue::get(CGF.Int32Ty));
4541 llvm::Constant *Mask = llvm::ConstantVector::get(Args);
4542 return Builder.CreateShuffleVector(Src, UnV, Mask);
4543}
4544
Yaxun Liuea6b7962016-10-03 14:41:50 +00004545// Create cast instructions for converting LLVM value \p Src to LLVM type \p
4546// DstTy. \p Src has the same size as \p DstTy. Both are single value types
4547// but could be scalar or vectors of different lengths, and either can be
4548// pointer.
4549// There are 4 cases:
4550// 1. non-pointer -> non-pointer : needs 1 bitcast
4551// 2. pointer -> pointer : needs 1 bitcast or addrspacecast
4552// 3. pointer -> non-pointer
4553// a) pointer -> intptr_t : needs 1 ptrtoint
4554// b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
4555// 4. non-pointer -> pointer
4556// a) intptr_t -> pointer : needs 1 inttoptr
4557// b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
4558// Note: for cases 3b and 4b two casts are required since LLVM casts do not
4559// allow casting directly between pointer types and non-integer non-pointer
4560// types.
4561static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
4562 const llvm::DataLayout &DL,
4563 Value *Src, llvm::Type *DstTy,
4564 StringRef Name = "") {
4565 auto SrcTy = Src->getType();
4566
4567 // Case 1.
4568 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
4569 return Builder.CreateBitCast(Src, DstTy, Name);
4570
4571 // Case 2.
4572 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
4573 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
4574
4575 // Case 3.
4576 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
4577 // Case 3b.
4578 if (!DstTy->isIntegerTy())
4579 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
4580 // Cases 3a and 3b.
4581 return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
4582 }
4583
4584 // Case 4b.
4585 if (!SrcTy->isIntegerTy())
4586 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
4587 // Cases 4a and 4b.
4588 return Builder.CreateIntToPtr(Src, DstTy, Name);
4589}
4590
Tanya Lattner55808c12011-06-04 00:47:47 +00004591Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
4592 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
Chris Lattner2192fe52011-07-18 04:24:23 +00004593 llvm::Type *DstTy = ConvertType(E->getType());
Craig Toppera97d7e72013-07-26 06:16:11 +00004594
Chris Lattner2192fe52011-07-18 04:24:23 +00004595 llvm::Type *SrcTy = Src->getType();
Yaxun Liuc5647012016-06-08 15:11:21 +00004596 unsigned NumElementsSrc = isa<llvm::VectorType>(SrcTy) ?
4597 cast<llvm::VectorType>(SrcTy)->getNumElements() : 0;
4598 unsigned NumElementsDst = isa<llvm::VectorType>(DstTy) ?
4599 cast<llvm::VectorType>(DstTy)->getNumElements() : 0;
Craig Toppera97d7e72013-07-26 06:16:11 +00004600
Yaxun Liuc5647012016-06-08 15:11:21 +00004601 // Going from vec3 to non-vec3 is a special case and requires a shuffle
4602 // vector to get a vec4, then a bitcast if the target type is different.
4603 if (NumElementsSrc == 3 && NumElementsDst != 3) {
4604 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00004605
4606 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4607 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4608 DstTy);
4609 }
4610
Yaxun Liuc5647012016-06-08 15:11:21 +00004611 Src->setName("astype");
4612 return Src;
4613 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004614
Yaxun Liuc5647012016-06-08 15:11:21 +00004615 // Going from non-vec3 to vec3 is a special case and requires a bitcast
4616 // to vec4 if the original type is not vec4, then a shuffle vector to
4617 // get a vec3.
4618 if (NumElementsSrc != 3 && NumElementsDst == 3) {
Jin-Gu Kange7cdcde2017-04-04 16:40:25 +00004619 if (!CGF.CGM.getCodeGenOpts().PreserveVec3Type) {
4620 auto Vec4Ty = llvm::VectorType::get(DstTy->getVectorElementType(), 4);
4621 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
4622 Vec4Ty);
4623 }
4624
Yaxun Liuc5647012016-06-08 15:11:21 +00004625 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
4626 Src->setName("astype");
4627 return Src;
Tanya Lattner55808c12011-06-04 00:47:47 +00004628 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004629
Sylvestre Ledru4644e9a2019-10-12 15:24:00 +00004630 return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
4631 Src, DstTy, "astype");
Tanya Lattner55808c12011-06-04 00:47:47 +00004632}
4633
Eli Friedmandf14b3a2011-10-11 02:20:01 +00004634Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
4635 return CGF.EmitAtomicExpr(E).getScalarVal();
4636}
4637
Chris Lattner2da04b32007-08-24 05:35:26 +00004638//===----------------------------------------------------------------------===//
4639// Entry Point into this File
4640//===----------------------------------------------------------------------===//
4641
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004642/// Emit the computation of the specified expression of scalar type, ignoring
4643/// the result.
Mike Stumpdf0fe272009-05-29 15:46:01 +00004644Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
John McCall47fb9502013-03-07 21:37:08 +00004645 assert(E && hasScalarEvaluationKind(E->getType()) &&
Chris Lattner2da04b32007-08-24 05:35:26 +00004646 "Invalid scalar expression to emit");
Mike Stump4a3999f2009-09-09 13:00:44 +00004647
David Blaikie38b25912015-02-09 19:13:51 +00004648 return ScalarExprEmitter(*this, IgnoreResultAssign)
4649 .Visit(const_cast<Expr *>(E));
Chris Lattner2da04b32007-08-24 05:35:26 +00004650}
Chris Lattner3474c202007-08-26 06:48:56 +00004651
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004652/// Emit a conversion from the specified type to the specified destination type,
4653/// both of which are LLVM scalar types.
Chris Lattner42e6b812007-08-26 16:34:22 +00004654Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004655 QualType DstTy,
4656 SourceLocation Loc) {
John McCall47fb9502013-03-07 21:37:08 +00004657 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
Chris Lattner3474c202007-08-26 06:48:56 +00004658 "Invalid scalar expression to emit");
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004659 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
Chris Lattner3474c202007-08-26 06:48:56 +00004660}
Chris Lattner42e6b812007-08-26 16:34:22 +00004661
Filipe Cabecinhas650d7f72015-08-05 06:19:26 +00004662/// Emit a conversion from the specified complex type to the specified
4663/// destination type, where the destination type is an LLVM scalar type.
Chris Lattner42e6b812007-08-26 16:34:22 +00004664Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
4665 QualType SrcTy,
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004666 QualType DstTy,
4667 SourceLocation Loc) {
John McCall47fb9502013-03-07 21:37:08 +00004668 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
Chris Lattner42e6b812007-08-26 16:34:22 +00004669 "Invalid complex -> scalar conversion");
Filipe Cabecinhas7af183d2015-08-11 04:19:28 +00004670 return ScalarExprEmitter(*this)
4671 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
Chris Lattner42e6b812007-08-26 16:34:22 +00004672}
Anders Carlssonb9eb82c2007-12-10 19:35:18 +00004673
Chris Lattner05dc78c2010-06-26 22:09:34 +00004674
4675llvm::Value *CodeGenFunction::
4676EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
4677 bool isInc, bool isPre) {
4678 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
4679}
4680
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004681LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004682 // object->isa or (*object).isa
4683 // Generate code as for: *(Class*)object
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00004684
4685 Expr *BaseExpr = E->getBase();
John McCall7f416cc2015-09-08 08:05:57 +00004686 Address Addr = Address::invalid();
John McCall086a4642010-11-24 05:12:34 +00004687 if (BaseExpr->isRValue()) {
John McCall7f416cc2015-09-08 08:05:57 +00004688 Addr = Address(EmitScalarExpr(BaseExpr), getPointerAlign());
Daniel Dunbarf6fb7e22010-08-21 03:08:16 +00004689 } else {
Akira Hatanakaf139ae32019-12-03 15:17:01 -08004690 Addr = EmitLValue(BaseExpr).getAddress(*this);
Fariborz Jahaniandf506b92010-02-05 19:18:30 +00004691 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004692
John McCall7f416cc2015-09-08 08:05:57 +00004693 // Cast the address to Class*.
4694 Addr = Builder.CreateElementBitCast(Addr, ConvertType(E->getType()));
4695 return MakeAddrLValue(Addr, E->getType());
Fariborz Jahanian531c16f2009-12-09 23:35:29 +00004696}
4697
Douglas Gregor914af212010-04-23 04:16:32 +00004698
John McCalla2342eb2010-12-05 02:00:02 +00004699LValue CodeGenFunction::EmitCompoundAssignmentLValue(
Douglas Gregor914af212010-04-23 04:16:32 +00004700 const CompoundAssignOperator *E) {
4701 ScalarExprEmitter Scalar(*this);
Craig Topper8a13c412014-05-21 05:09:00 +00004702 Value *Result = nullptr;
Douglas Gregor914af212010-04-23 04:16:32 +00004703 switch (E->getOpcode()) {
4704#define COMPOUND_OP(Op) \
John McCalle3027922010-08-25 11:45:40 +00004705 case BO_##Op##Assign: \
Douglas Gregor914af212010-04-23 04:16:32 +00004706 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
Daniel Dunbarc85ea8e2010-06-29 22:00:45 +00004707 Result)
Douglas Gregor914af212010-04-23 04:16:32 +00004708 COMPOUND_OP(Mul);
4709 COMPOUND_OP(Div);
4710 COMPOUND_OP(Rem);
4711 COMPOUND_OP(Add);
4712 COMPOUND_OP(Sub);
4713 COMPOUND_OP(Shl);
4714 COMPOUND_OP(Shr);
4715 COMPOUND_OP(And);
4716 COMPOUND_OP(Xor);
4717 COMPOUND_OP(Or);
4718#undef COMPOUND_OP
Craig Toppera97d7e72013-07-26 06:16:11 +00004719
John McCalle3027922010-08-25 11:45:40 +00004720 case BO_PtrMemD:
4721 case BO_PtrMemI:
4722 case BO_Mul:
4723 case BO_Div:
4724 case BO_Rem:
4725 case BO_Add:
4726 case BO_Sub:
4727 case BO_Shl:
4728 case BO_Shr:
4729 case BO_LT:
4730 case BO_GT:
4731 case BO_LE:
4732 case BO_GE:
4733 case BO_EQ:
4734 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +00004735 case BO_Cmp:
John McCalle3027922010-08-25 11:45:40 +00004736 case BO_And:
4737 case BO_Xor:
4738 case BO_Or:
4739 case BO_LAnd:
4740 case BO_LOr:
4741 case BO_Assign:
4742 case BO_Comma:
David Blaikie83d382b2011-09-23 05:06:16 +00004743 llvm_unreachable("Not valid compound assignment operators");
Douglas Gregor914af212010-04-23 04:16:32 +00004744 }
Craig Toppera97d7e72013-07-26 06:16:11 +00004745
Douglas Gregor914af212010-04-23 04:16:32 +00004746 llvm_unreachable("Unhandled compound assignment operator");
4747}
Vedant Kumara125eb52017-06-01 19:22:18 +00004748
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004749struct GEPOffsetAndOverflow {
4750 // The total (signed) byte offset for the GEP.
4751 llvm::Value *TotalOffset;
4752 // The offset overflow flag - true if the total offset overflows.
4753 llvm::Value *OffsetOverflows;
4754};
Vedant Kumara125eb52017-06-01 19:22:18 +00004755
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004756/// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004757/// and compute the total offset it applies from it's base pointer BasePtr.
4758/// Returns offset in bytes and a boolean flag whether an overflow happened
4759/// during evaluation.
4760static GEPOffsetAndOverflow EmitGEPOffsetInBytes(Value *BasePtr, Value *GEPVal,
4761 llvm::LLVMContext &VMContext,
4762 CodeGenModule &CGM,
Nikita Popov7c362b22020-02-16 17:57:18 +01004763 CGBuilderTy &Builder) {
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004764 const auto &DL = CGM.getDataLayout();
4765
4766 // The total (signed) byte offset for the GEP.
4767 llvm::Value *TotalOffset = nullptr;
4768
4769 // Was the GEP already reduced to a constant?
4770 if (isa<llvm::Constant>(GEPVal)) {
4771 // Compute the offset by casting both pointers to integers and subtracting:
4772 // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
4773 Value *BasePtr_int =
4774 Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
4775 Value *GEPVal_int =
4776 Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
4777 TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
4778 return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
4779 }
4780
Vedant Kumara125eb52017-06-01 19:22:18 +00004781 auto *GEP = cast<llvm::GEPOperator>(GEPVal);
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004782 assert(GEP->getPointerOperand() == BasePtr &&
4783 "BasePtr must be the the base of the GEP.");
Vedant Kumara125eb52017-06-01 19:22:18 +00004784 assert(GEP->isInBounds() && "Expected inbounds GEP");
4785
Vedant Kumara125eb52017-06-01 19:22:18 +00004786 auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
4787
4788 // Grab references to the signed add/mul overflow intrinsics for intptr_t.
4789 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4790 auto *SAddIntrinsic =
4791 CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
4792 auto *SMulIntrinsic =
4793 CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
4794
Vedant Kumara125eb52017-06-01 19:22:18 +00004795 // The offset overflow flag - true if the total offset overflows.
4796 llvm::Value *OffsetOverflows = Builder.getFalse();
4797
4798 /// Return the result of the given binary operation.
4799 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
4800 llvm::Value *RHS) -> llvm::Value * {
Davide Italiano77378e42017-06-01 23:55:18 +00004801 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
Vedant Kumara125eb52017-06-01 19:22:18 +00004802
4803 // If the operands are constants, return a constant result.
4804 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
4805 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
4806 llvm::APInt N;
4807 bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
4808 /*Signed=*/true, N);
4809 if (HasOverflow)
4810 OffsetOverflows = Builder.getTrue();
4811 return llvm::ConstantInt::get(VMContext, N);
4812 }
4813 }
4814
4815 // Otherwise, compute the result with checked arithmetic.
4816 auto *ResultAndOverflow = Builder.CreateCall(
4817 (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
4818 OffsetOverflows = Builder.CreateOr(
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004819 Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
Vedant Kumara125eb52017-06-01 19:22:18 +00004820 return Builder.CreateExtractValue(ResultAndOverflow, 0);
4821 };
4822
4823 // Determine the total byte offset by looking at each GEP operand.
4824 for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
4825 GTI != GTE; ++GTI) {
4826 llvm::Value *LocalOffset;
4827 auto *Index = GTI.getOperand();
4828 // Compute the local offset contributed by this indexing step:
4829 if (auto *STy = GTI.getStructTypeOrNull()) {
4830 // For struct indexing, the local offset is the byte position of the
4831 // specified field.
4832 unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
4833 LocalOffset = llvm::ConstantInt::get(
4834 IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
4835 } else {
4836 // Otherwise this is array-like indexing. The local offset is the index
4837 // multiplied by the element size.
4838 auto *ElementSize = llvm::ConstantInt::get(
4839 IntPtrTy, DL.getTypeAllocSize(GTI.getIndexedType()));
4840 auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
4841 LocalOffset = eval(BO_Mul, ElementSize, IndexS);
4842 }
4843
4844 // If this is the first offset, set it as the total offset. Otherwise, add
4845 // the local offset into the running total.
4846 if (!TotalOffset || TotalOffset == Zero)
4847 TotalOffset = LocalOffset;
4848 else
4849 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
4850 }
4851
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004852 return {TotalOffset, OffsetOverflows};
4853}
4854
4855Value *
4856CodeGenFunction::EmitCheckedInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
4857 bool SignedIndices, bool IsSubtraction,
4858 SourceLocation Loc, const Twine &Name) {
4859 Value *GEPVal = Builder.CreateInBoundsGEP(Ptr, IdxList, Name);
4860
4861 // If the pointer overflow sanitizer isn't enabled, do nothing.
4862 if (!SanOpts.has(SanitizerKind::PointerOverflow))
4863 return GEPVal;
4864
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004865 llvm::Type *PtrTy = Ptr->getType();
4866
4867 // Perform nullptr-and-offset check unless the nullptr is defined.
4868 bool PerformNullCheck = !NullPointerIsDefined(
4869 Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
4870 // Check for overflows unless the GEP got constant-folded,
4871 // and only in the default address space
4872 bool PerformOverflowCheck =
4873 !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
4874
4875 if (!(PerformNullCheck || PerformOverflowCheck))
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004876 return GEPVal;
4877
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004878 const auto &DL = CGM.getDataLayout();
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004879
4880 SanitizerScope SanScope(this);
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004881 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004882
4883 GEPOffsetAndOverflow EvaluatedGEP =
4884 EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
4885
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004886 assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
4887 EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
4888 "If the offset got constant-folded, we don't expect that there was an "
4889 "overflow.");
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004890
4891 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
4892
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004893 // Common case: if the total offset is zero, and we are using C++ semantics,
4894 // where nullptr+0 is defined, don't emit a check.
4895 if (EvaluatedGEP.TotalOffset == Zero && CGM.getLangOpts().CPlusPlus)
Vedant Kumara125eb52017-06-01 19:22:18 +00004896 return GEPVal;
4897
4898 // Now that we've computed the total offset, add it to the base pointer (with
4899 // wrapping semantics).
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004900 auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
Roman Lebedev8f03dcd2019-09-06 14:18:57 +00004901 auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
Vedant Kumara125eb52017-06-01 19:22:18 +00004902
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004903 llvm::SmallVector<std::pair<llvm::Value *, SanitizerMask>, 2> Checks;
Roman Lebedevf1d33842019-09-06 14:19:04 +00004904
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004905 if (PerformNullCheck) {
4906 // In C++, if the base pointer evaluates to a null pointer value,
4907 // the only valid pointer this inbounds GEP can produce is also
4908 // a null pointer, so the offset must also evaluate to zero.
4909 // Likewise, if we have non-zero base pointer, we can not get null pointer
4910 // as a result, so the offset can not be -intptr_t(BasePtr).
4911 // In other words, both pointers are either null, or both are non-null,
4912 // or the behaviour is undefined.
4913 //
4914 // C, however, is more strict in this regard, and gives more
4915 // optimization opportunities: in C, additionally, nullptr+0 is undefined.
4916 // So both the input to the 'gep inbounds' AND the output must not be null.
4917 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
4918 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
4919 auto *Valid =
4920 CGM.getLangOpts().CPlusPlus
4921 ? Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr)
4922 : Builder.CreateAnd(BaseIsNotNullptr, ResultIsNotNullptr);
4923 Checks.emplace_back(Valid, SanitizerKind::PointerOverflow);
Vedant Kumar6dbf4272017-06-12 18:42:51 +00004924 }
Roman Lebedev536b0ee2019-10-10 09:25:02 +00004925
4926 if (PerformOverflowCheck) {
4927 // The GEP is valid if:
4928 // 1) The total offset doesn't overflow, and
4929 // 2) The sign of the difference between the computed address and the base
4930 // pointer matches the sign of the total offset.
4931 llvm::Value *ValidGEP;
4932 auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
4933 if (SignedIndices) {
4934 // GEP is computed as `unsigned base + signed offset`, therefore:
4935 // * If offset was positive, then the computed pointer can not be
4936 // [unsigned] less than the base pointer, unless it overflowed.
4937 // * If offset was negative, then the computed pointer can not be
4938 // [unsigned] greater than the bas pointere, unless it overflowed.
4939 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4940 auto *PosOrZeroOffset =
4941 Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
4942 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
4943 ValidGEP =
4944 Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
4945 } else if (!IsSubtraction) {
4946 // GEP is computed as `unsigned base + unsigned offset`, therefore the
4947 // computed pointer can not be [unsigned] less than base pointer,
4948 // unless there was an overflow.
4949 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
4950 ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
4951 } else {
4952 // GEP is computed as `unsigned base - unsigned offset`, therefore the
4953 // computed pointer can not be [unsigned] greater than base pointer,
4954 // unless there was an overflow.
4955 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
4956 ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
4957 }
4958 ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
4959 Checks.emplace_back(ValidGEP, SanitizerKind::PointerOverflow);
4960 }
Roman Lebedevf1d33842019-09-06 14:19:04 +00004961
4962 assert(!Checks.empty() && "Should have produced some checks.");
Vedant Kumara125eb52017-06-01 19:22:18 +00004963
4964 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
4965 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
4966 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
Roman Lebedevf1d33842019-09-06 14:19:04 +00004967 EmitCheck(Checks, SanitizerHandler::PointerOverflow, StaticArgs, DynamicArgs);
Vedant Kumara125eb52017-06-01 19:22:18 +00004968
4969 return GEPVal;
4970}