1//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// 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
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCXXABI.h"
14#include "CGCleanup.h"
15#include "CGDebugInfo.h"
16#include "CGHLSLRuntime.h"
17#include "CGObjCRuntime.h"
18#include "CGOpenMPRuntime.h"
19#include "CGRecordLayout.h"
20#include "CodeGenFunction.h"
21#include "CodeGenModule.h"
22#include "ConstantEmitter.h"
23#include "TargetInfo.h"
24#include "TrapReasonBuilder.h"
25#include "clang/AST/ASTContext.h"
26#include "clang/AST/Attr.h"
27#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
29#include "clang/AST/MatrixUtils.h"
30#include "clang/AST/ParentMapContext.h"
31#include "clang/AST/RecordLayout.h"
32#include "clang/AST/StmtVisitor.h"
33#include "clang/Basic/CodeGenOptions.h"
34#include "clang/Basic/DiagnosticTrap.h"
35#include "clang/Basic/TargetInfo.h"
36#include "clang/CodeGenUtils/ExprUtils.h"
37#include "llvm/ADT/APFixedPoint.h"
38#include "llvm/ADT/ScopeExit.h"
39#include "llvm/Analysis/ValueTracking.h"
40#include "llvm/IR/Argument.h"
41#include "llvm/IR/CFG.h"
42#include "llvm/IR/Constants.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/DerivedTypes.h"
45#include "llvm/IR/FixedPointBuilder.h"
46#include "llvm/IR/Function.h"
47#include "llvm/IR/GEPNoWrapFlags.h"
48#include "llvm/IR/GetElementPtrTypeIterator.h"
49#include "llvm/IR/GlobalVariable.h"
50#include "llvm/IR/Intrinsics.h"
51#include "llvm/IR/IntrinsicsPowerPC.h"
52#include "llvm/IR/IntrinsicsWebAssembly.h"
53#include "llvm/IR/MatrixBuilder.h"
54#include "llvm/IR/Module.h"
55#include "llvm/Support/TypeSize.h"
56#include <cstdarg>
57#include <optional>
58
59using namespace clang;
60using namespace CodeGen;
61using llvm::Value;
62
63//===----------------------------------------------------------------------===//
64// Scalar Expression Emitter
65//===----------------------------------------------------------------------===//
66
67namespace llvm {
68extern cl::opt<bool> EnableSingleByteCoverage;
69} // namespace llvm
70
71namespace {
72
73/// Determine whether the given binary operation may overflow.
74/// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
75/// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
76/// the returned overflow check is precise. The returned value is 'true' for
77/// all other opcodes, to be conservative.
78bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
79 BinaryOperator::Opcode Opcode, bool Signed,
80 llvm::APInt &Result) {
81 // Assume overflow is possible, unless we can prove otherwise.
82 bool Overflow = true;
83 const auto &LHSAP = LHS->getValue();
84 const auto &RHSAP = RHS->getValue();
85 if (Opcode == BO_Add) {
86 Result = Signed ? LHSAP.sadd_ov(RHS: RHSAP, Overflow)
87 : LHSAP.uadd_ov(RHS: RHSAP, Overflow);
88 } else if (Opcode == BO_Sub) {
89 Result = Signed ? LHSAP.ssub_ov(RHS: RHSAP, Overflow)
90 : LHSAP.usub_ov(RHS: RHSAP, Overflow);
91 } else if (Opcode == BO_Mul) {
92 Result = Signed ? LHSAP.smul_ov(RHS: RHSAP, Overflow)
93 : LHSAP.umul_ov(RHS: RHSAP, Overflow);
94 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
95 if (Signed && !RHS->isZero())
96 Result = LHSAP.sdiv_ov(RHS: RHSAP, Overflow);
97 else
98 return false;
99 }
100 return Overflow;
101}
102
103struct BinOpInfo {
104 Value *LHS;
105 Value *RHS;
106 QualType Ty; // Computation Type.
107 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
108 FPOptions FPFeatures;
109 const Expr *E; // Entire expr, for error unsupported. May not be binop.
110
111 /// Check if the binop can result in integer overflow.
112 bool mayHaveIntegerOverflow() const {
113 // Without constant input, we can't rule out overflow.
114 auto *LHSCI = dyn_cast<llvm::ConstantInt>(Val: LHS);
115 auto *RHSCI = dyn_cast<llvm::ConstantInt>(Val: RHS);
116 if (!LHSCI || !RHSCI)
117 return true;
118
119 llvm::APInt Result;
120 return ::mayHaveIntegerOverflow(
121 LHS: LHSCI, RHS: RHSCI, Opcode, Signed: Ty->hasSignedIntegerRepresentation(), Result);
122 }
123
124 /// Check if the binop computes a division or a remainder.
125 bool isDivremOp() const {
126 return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
127 Opcode == BO_RemAssign;
128 }
129
130 /// Check if the binop can result in an integer division by zero.
131 bool mayHaveIntegerDivisionByZero() const {
132 if (isDivremOp())
133 if (auto *CI = dyn_cast<llvm::ConstantInt>(Val: RHS))
134 return CI->isZero();
135 return true;
136 }
137
138 /// Check if the binop can result in a float division by zero.
139 bool mayHaveFloatDivisionByZero() const {
140 if (isDivremOp())
141 if (auto *CFP = dyn_cast<llvm::ConstantFP>(Val: RHS))
142 return CFP->isZero();
143 return true;
144 }
145
146 /// Check if at least one operand is a fixed point type. In such cases, this
147 /// operation did not follow usual arithmetic conversion and both operands
148 /// might not be of the same type.
149 bool isFixedPointOp() const {
150 // We cannot simply check the result type since comparison operations return
151 // an int.
152 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
153 QualType LHSType = BinOp->getLHS()->getType();
154 QualType RHSType = BinOp->getRHS()->getType();
155 return LHSType->isFixedPointType() || RHSType->isFixedPointType();
156 }
157 if (const auto *UnOp = dyn_cast<UnaryOperator>(Val: E))
158 return UnOp->getSubExpr()->getType()->isFixedPointType();
159 return false;
160 }
161
162 /// Check if the RHS has a signed integer representation.
163 bool rhsHasSignedIntegerRepresentation() const {
164 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: E)) {
165 QualType RHSType = BinOp->getRHS()->getType();
166 return RHSType->hasSignedIntegerRepresentation();
167 }
168 return false;
169 }
170};
171
172static bool MustVisitNullValue(const Expr *E) {
173 // If a null pointer expression's type is the C++0x nullptr_t, then
174 // it's not necessarily a simple constant and it must be evaluated
175 // for its potential side effects.
176 return E->getType()->isNullPtrType();
177}
178
179/// If \p E is a widened promoted integer, get its base (unpromoted) type.
180static std::optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
181 const Expr *E) {
182 const Expr *Base = E->IgnoreImpCasts();
183 if (E == Base)
184 return std::nullopt;
185
186 QualType BaseTy = Base->getType();
187 if (!Ctx.isPromotableIntegerType(T: BaseTy) ||
188 Ctx.getTypeSize(T: BaseTy) >= Ctx.getTypeSize(T: E->getType()))
189 return std::nullopt;
190
191 return BaseTy;
192}
193
194/// Check if \p E is a widened promoted integer.
195static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
196 return getUnwidenedIntegerType(Ctx, E).has_value();
197}
198
199/// Consider OverflowBehaviorType and language options to calculate the final
200/// overflow behavior for an expression. There are no language options for
201/// unsigned overflow semantics so there is nothing to consider there.
202static LangOptions::OverflowBehaviorKind
203getOverflowBehaviorConsideringType(const CodeGenFunction &CGF,
204 const QualType Ty) {
205 const OverflowBehaviorType *OBT = Ty->getAs<OverflowBehaviorType>();
206 /// FIXME: Having two enums named `OverflowBehaviorKind` is not ideal, these
207 /// should be unified into one coherent enum that supports both unsigned and
208 /// signed overflow behavior semantics.
209 if (OBT) {
210 switch (OBT->getBehaviorKind()) {
211 case OverflowBehaviorType::OverflowBehaviorKind::Wrap:
212 return LangOptions::OverflowBehaviorKind::OB_Wrap;
213 case OverflowBehaviorType::OverflowBehaviorKind::Trap:
214 return LangOptions::OverflowBehaviorKind::OB_Trap;
215 }
216 llvm_unreachable("Unknown OverflowBehaviorKind");
217 }
218
219 if (Ty->isUnsignedIntegerType()) {
220 return LangOptions::OverflowBehaviorKind::OB_Unset;
221 }
222
223 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
224 case LangOptions::SignedOverflowBehaviorTy::SOB_Defined:
225 return LangOptions::OverflowBehaviorKind::OB_SignedAndDefined;
226 case LangOptions::SignedOverflowBehaviorTy::SOB_Undefined:
227 return LangOptions::OverflowBehaviorKind::OB_Unset;
228 case LangOptions::SignedOverflowBehaviorTy::SOB_Trapping:
229 return LangOptions::OverflowBehaviorKind::OB_Trap;
230 }
231 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
232}
233
234/// Check if we can skip the overflow check for \p Op.
235static bool CanElideOverflowCheck(ASTContext &Ctx, const BinOpInfo &Op) {
236 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
237 "Expected a unary or binary operator");
238
239 // If the binop has constant inputs and we can prove there is no overflow,
240 // we can elide the overflow check.
241 if (!Op.mayHaveIntegerOverflow())
242 return true;
243
244 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: Op.E);
245 if (UO && Ctx.isUnaryOverflowPatternExcluded(UO))
246 return true;
247
248 const auto *BO = dyn_cast<BinaryOperator>(Val: Op.E);
249 if (BO && BO->hasExcludedOverflowPattern())
250 return true;
251
252 if (Op.Ty.isWrapType())
253 return true;
254 if (Op.Ty.isTrapType())
255 return false;
256
257 if (Op.Ty->isSignedIntegerType() &&
258 Ctx.isTypeIgnoredBySanitizer(Mask: SanitizerKind::SignedIntegerOverflow,
259 Ty: Op.Ty)) {
260 return true;
261 }
262
263 if (Op.Ty->isUnsignedIntegerType() &&
264 Ctx.isTypeIgnoredBySanitizer(Mask: SanitizerKind::UnsignedIntegerOverflow,
265 Ty: Op.Ty)) {
266 return true;
267 }
268
269 // If a unary op has a widened operand, the op cannot overflow.
270 if (UO)
271 return !UO->canOverflow();
272
273 // We usually don't need overflow checks for binops with widened operands.
274 // Multiplication with promoted unsigned operands is a special case.
275 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, E: BO->getLHS());
276 if (!OptionalLHSTy)
277 return false;
278
279 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, E: BO->getRHS());
280 if (!OptionalRHSTy)
281 return false;
282
283 QualType LHSTy = *OptionalLHSTy;
284 QualType RHSTy = *OptionalRHSTy;
285
286 // This is the simple case: binops without unsigned multiplication, and with
287 // widened operands. No overflow check is needed here.
288 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
289 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
290 return true;
291
292 // For unsigned multiplication the overflow check can be elided if either one
293 // of the unpromoted types are less than half the size of the promoted type.
294 unsigned PromotedSize = Ctx.getTypeSize(T: Op.E->getType());
295 return (2 * Ctx.getTypeSize(T: LHSTy)) < PromotedSize ||
296 (2 * Ctx.getTypeSize(T: RHSTy)) < PromotedSize;
297}
298
299class ScalarExprEmitter
300 : public StmtVisitor<ScalarExprEmitter, Value*> {
301 CodeGenFunction &CGF;
302 CGBuilderTy &Builder;
303 bool IgnoreResultAssign;
304 llvm::LLVMContext &VMContext;
305public:
306
307 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
308 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
309 VMContext(cgf.getLLVMContext()) {
310 }
311
312 //===--------------------------------------------------------------------===//
313 // Utilities
314 //===--------------------------------------------------------------------===//
315
316 bool TestAndClearIgnoreResultAssign() {
317 bool I = IgnoreResultAssign;
318 IgnoreResultAssign = false;
319 return I;
320 }
321
322 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
323 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
324 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
325 return CGF.EmitCheckedLValue(E, TCK);
326 }
327
328 void EmitBinOpCheck(
329 ArrayRef<std::pair<Value *, SanitizerKind::SanitizerOrdinal>> Checks,
330 const BinOpInfo &Info);
331
332 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
333 return CGF.EmitLoadOfLValue(V: LV, Loc).getScalarVal();
334 }
335
336 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
337 const AlignValueAttr *AVAttr = nullptr;
338 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
339 const ValueDecl *VD = DRE->getDecl();
340
341 if (VD->getType()->isReferenceType()) {
342 if (const auto *TTy =
343 VD->getType().getNonReferenceType()->getAs<TypedefType>())
344 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
345 } else {
346 // Assumptions for function parameters are emitted at the start of the
347 // function, so there is no need to repeat that here,
348 // unless the alignment-assumption sanitizer is enabled,
349 // then we prefer the assumption over alignment attribute
350 // on IR function param.
351 if (isa<ParmVarDecl>(Val: VD) && !CGF.SanOpts.has(K: SanitizerKind::Alignment))
352 return;
353
354 AVAttr = VD->getAttr<AlignValueAttr>();
355 }
356 }
357
358 if (!AVAttr)
359 if (const auto *TTy = E->getType()->getAs<TypedefType>())
360 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
361
362 if (!AVAttr)
363 return;
364
365 Value *AlignmentValue = CGF.EmitScalarExpr(E: AVAttr->getAlignment());
366 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Val: AlignmentValue);
367 CGF.emitAlignmentAssumption(PtrValue: V, E, AssumptionLoc: AVAttr->getLocation(), Alignment: AlignmentCI);
368 }
369
370 /// EmitLoadOfLValue - Given an expression with complex type that represents a
371 /// value l-value, this method emits the address of the l-value, then loads
372 /// and returns the result.
373 Value *EmitLoadOfLValue(const Expr *E) {
374 LValue LV = EmitCheckedLValue(E, TCK: CodeGenFunction::TCK_Load);
375 if (CGF.CurLoadedLValueCapture && CGF.CurLoadedLValueCapture->E == E)
376 CGF.CurLoadedLValueCapture->LV = LV;
377
378 Value *V = EmitLoadOfLValue(LV, Loc: E->getExprLoc());
379
380 EmitLValueAlignmentAssumption(E, V);
381 return V;
382 }
383
384 /// EmitConversionToBool - Convert the specified expression value to a
385 /// boolean (i1) truth value. This is equivalent to "Val != 0".
386 Value *EmitConversionToBool(Value *Src, QualType DstTy);
387
388 /// Emit a check that a conversion from a floating-point type does not
389 /// overflow.
390 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
391 Value *Src, QualType SrcType, QualType DstType,
392 llvm::Type *DstTy, SourceLocation Loc);
393
394 /// Known implicit conversion check kinds.
395 /// This is used for bitfield conversion checks as well.
396 /// Keep in sync with the enum of the same name in ubsan_handlers.h
397 enum ImplicitConversionCheckKind : unsigned char {
398 ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
399 ICCK_UnsignedIntegerTruncation = 1,
400 ICCK_SignedIntegerTruncation = 2,
401 ICCK_IntegerSignChange = 3,
402 ICCK_SignedIntegerTruncationOrSignChange = 4,
403 };
404
405 /// Emit a check that an [implicit] truncation of an integer does not
406 /// discard any bits. It is not UB, so we use the value after truncation.
407 void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
408 QualType DstType, SourceLocation Loc,
409 bool OBTrapInvolved = false);
410
411 /// Emit a check that an [implicit] conversion of an integer does not change
412 /// the sign of the value. It is not UB, so we use the value after conversion.
413 /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
414 void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
415 QualType DstType, SourceLocation Loc,
416 bool OBTrapInvolved = false);
417
418 /// Emit a conversion from the specified type to the specified destination
419 /// type, both of which are LLVM scalar types.
420 struct ScalarConversionOpts {
421 bool TreatBooleanAsSigned;
422 bool EmitImplicitIntegerTruncationChecks;
423 bool EmitImplicitIntegerSignChangeChecks;
424 /* Potential -fsanitize-undefined-ignore-overflow-pattern= */
425 bool PatternExcluded;
426
427 ScalarConversionOpts()
428 : TreatBooleanAsSigned(false),
429 EmitImplicitIntegerTruncationChecks(false),
430 EmitImplicitIntegerSignChangeChecks(false), PatternExcluded(false) {}
431
432 ScalarConversionOpts(clang::SanitizerSet SanOpts)
433 : TreatBooleanAsSigned(false),
434 EmitImplicitIntegerTruncationChecks(
435 SanOpts.hasOneOf(K: SanitizerKind::ImplicitIntegerTruncation)),
436 EmitImplicitIntegerSignChangeChecks(
437 SanOpts.has(K: SanitizerKind::ImplicitIntegerSignChange)),
438 PatternExcluded(false) {}
439 };
440 Value *EmitScalarCast(Value *Src, QualType SrcType, QualType DstType,
441 llvm::Type *SrcTy, llvm::Type *DstTy,
442 ScalarConversionOpts Opts);
443 Value *
444 EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
445 SourceLocation Loc,
446 ScalarConversionOpts Opts = ScalarConversionOpts());
447
448 /// Convert between either a fixed point and other fixed point or fixed point
449 /// and an integer.
450 Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
451 SourceLocation Loc);
452
453 /// Emit a conversion from the specified complex type to the specified
454 /// destination type, where the destination type is an LLVM scalar type.
455 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
456 QualType SrcTy, QualType DstTy,
457 SourceLocation Loc);
458
459 /// EmitNullValue - Emit a value that corresponds to null for the given type.
460 Value *EmitNullValue(QualType Ty);
461
462 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
463 Value *EmitFloatToBoolConversion(Value *V) {
464 // Compare against 0.0 for fp scalars.
465 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: V->getType());
466 return Builder.CreateFCmpUNE(LHS: V, RHS: Zero, Name: "tobool");
467 }
468
469 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
470 Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
471 Value *Zero = CGF.CGM.getNullPointer(T: cast<llvm::PointerType>(Val: V->getType()), QT);
472
473 return Builder.CreateICmpNE(LHS: V, RHS: Zero, Name: "tobool");
474 }
475
476 Value *EmitIntToBoolConversion(Value *V) {
477 // Because of the type rules of C, we often end up computing a
478 // logical value, then zero extending it to int, then wanting it
479 // as a logical value again. Optimize this common case.
480 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(Val: V)) {
481 if (ZI->getOperand(i_nocapture: 0)->getType() == Builder.getInt1Ty()) {
482 Value *Result = ZI->getOperand(i_nocapture: 0);
483 // If there aren't any more uses, zap the instruction to save space.
484 // Note that there can be more uses, for example if this
485 // is the result of an assignment.
486 if (ZI->use_empty())
487 ZI->eraseFromParent();
488 return Result;
489 }
490 }
491
492 return Builder.CreateIsNotNull(Arg: V, Name: "tobool");
493 }
494
495 //===--------------------------------------------------------------------===//
496 // Visitor Methods
497 //===--------------------------------------------------------------------===//
498
499 Value *Visit(Expr *E) {
500 ApplyDebugLocation DL(CGF, E);
501 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(S: E);
502 }
503
504 Value *VisitStmt(Stmt *S) {
505 S->dump(OS&: llvm::errs(), Context: CGF.getContext());
506 llvm_unreachable("Stmt can't have complex result type!");
507 }
508 Value *VisitExpr(Expr *S);
509
510 Value *VisitConstantExpr(ConstantExpr *E) {
511 // A constant expression of type 'void' generates no code and produces no
512 // value.
513 if (E->getType()->isVoidType())
514 return nullptr;
515
516 if (Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(CE: E)) {
517 if (E->isGLValue()) {
518 // This was already converted to an rvalue when it was constant
519 // evaluated.
520 if (E->hasAPValueResult() && !E->getAPValueResult().isLValue())
521 return Result;
522 return CGF.EmitLoadOfScalar(
523 Addr: Address(Result, CGF.convertTypeForLoadStore(ASTTy: E->getType()),
524 CGF.getContext().getTypeAlignInChars(T: E->getType())),
525 /*Volatile*/ false, Ty: E->getType(), Loc: E->getExprLoc());
526 }
527 return Result;
528 }
529 return Visit(E: E->getSubExpr());
530 }
531 Value *VisitParenExpr(ParenExpr *PE) {
532 return Visit(E: PE->getSubExpr());
533 }
534 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
535 return Visit(E: E->getReplacement());
536 }
537 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
538 return Visit(E: GE->getResultExpr());
539 }
540 Value *VisitCoawaitExpr(CoawaitExpr *S) {
541 return CGF.EmitCoawaitExpr(E: *S).getScalarVal();
542 }
543 Value *VisitCoyieldExpr(CoyieldExpr *S) {
544 return CGF.EmitCoyieldExpr(E: *S).getScalarVal();
545 }
546 Value *VisitUnaryCoawait(const UnaryOperator *E) {
547 return Visit(E: E->getSubExpr());
548 }
549
550 // Leaves.
551 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
552 return Builder.getInt(AI: E->getValue());
553 }
554 Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
555 return Builder.getInt(AI: E->getValue());
556 }
557 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
558 return llvm::ConstantFP::get(Context&: VMContext, V: E->getValue());
559 }
560 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
561 // Character literals are always stored in an unsigned (even for signed
562 // char), so allow implicit truncation here.
563 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue(),
564 /*IsSigned=*/false, /*ImplicitTrunc=*/true);
565 }
566 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
567 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue());
568 }
569 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
570 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue());
571 }
572 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
573 if (E->getType()->isVoidType())
574 return nullptr;
575
576 return EmitNullValue(Ty: E->getType());
577 }
578 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
579 return EmitNullValue(Ty: E->getType());
580 }
581 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
582 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
583 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
584 llvm::Value *V = CGF.GetAddrOfLabel(L: E->getLabel());
585 return Builder.CreateBitCast(V, DestTy: ConvertType(T: E->getType()));
586 }
587
588 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
589 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()),V: E->getPackLength());
590 }
591
592 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
593 return CGF.EmitPseudoObjectRValue(e: E).getScalarVal();
594 }
595
596 Value *VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E);
597 Value *VisitEmbedExpr(EmbedExpr *E);
598
599 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
600 if (E->isGLValue())
601 return EmitLoadOfLValue(LV: CGF.getOrCreateOpaqueLValueMapping(e: E),
602 Loc: E->getExprLoc());
603
604 // Otherwise, assume the mapping is the scalar directly.
605 return CGF.getOrCreateOpaqueRValueMapping(e: E).getScalarVal();
606 }
607
608 Value *VisitOpenACCAsteriskSizeExpr(OpenACCAsteriskSizeExpr *E) {
609 llvm_unreachable("Codegen for this isn't defined/implemented");
610 }
611
612 // l-values.
613 Value *VisitDeclRefExpr(DeclRefExpr *E) {
614 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(RefExpr: E))
615 return CGF.emitScalarConstant(Constant, E);
616 return EmitLoadOfLValue(E);
617 }
618
619 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
620 return CGF.EmitObjCSelectorExpr(E);
621 }
622 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
623 return CGF.EmitObjCProtocolExpr(E);
624 }
625 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
626 return EmitLoadOfLValue(E);
627 }
628 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
629 if (E->getMethodDecl() &&
630 E->getMethodDecl()->getReturnType()->isReferenceType())
631 return EmitLoadOfLValue(E);
632 return CGF.EmitObjCMessageExpr(E).getScalarVal();
633 }
634
635 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
636 LValue LV = CGF.EmitObjCIsaExpr(E);
637 Value *V = CGF.EmitLoadOfLValue(V: LV, Loc: E->getExprLoc()).getScalarVal();
638 return V;
639 }
640
641 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
642 VersionTuple Version = E->getVersion();
643
644 // If we're checking for a platform older than our minimum deployment
645 // target, we can fold the check away.
646 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
647 return llvm::ConstantInt::get(Ty: Builder.getInt1Ty(), V: 1);
648
649 return CGF.EmitBuiltinAvailable(Version);
650 }
651
652 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
653 Value *VisitMatrixSingleSubscriptExpr(MatrixSingleSubscriptExpr *E);
654 Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E);
655 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
656 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
657 Value *VisitMemberExpr(MemberExpr *E);
658 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
659 Value *VisitMatrixElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
660 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
661 // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which
662 // transitively calls EmitCompoundLiteralLValue, here in C++ since compound
663 // literals aren't l-values in C++. We do so simply because that's the
664 // cleanest way to handle compound literals in C++.
665 // See the discussion here: https://reviews.llvm.org/D64464
666 return EmitLoadOfLValue(E);
667 }
668
669 Value *VisitInitListExpr(InitListExpr *E);
670
671 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
672 assert(CGF.getArrayInitIndex() &&
673 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
674 return CGF.getArrayInitIndex();
675 }
676
677 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
678 return EmitNullValue(Ty: E->getType());
679 }
680 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
681 CGF.CGM.EmitExplicitCastExprType(E, CGF: &CGF);
682 return VisitCastExpr(E);
683 }
684 Value *VisitCastExpr(CastExpr *E);
685
686 Value *VisitCallExpr(const CallExpr *E) {
687 if (E->getCallReturnType(Ctx: CGF.getContext())->isReferenceType())
688 return EmitLoadOfLValue(E);
689
690 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
691
692 Value *V = CGF.EmitCallExpr(E).getScalarVal();
693
694 EmitLValueAlignmentAssumption(E, V);
695 return V;
696 }
697
698 Value *VisitStmtExpr(const StmtExpr *E);
699
700 // Unary Operators.
701 Value *VisitUnaryPostDec(const UnaryOperator *E) {
702 LValue LV = EmitLValue(E: E->getSubExpr());
703 return EmitScalarPrePostIncDec(E, LV, isInc: false, isPre: false);
704 }
705 Value *VisitUnaryPostInc(const UnaryOperator *E) {
706 LValue LV = EmitLValue(E: E->getSubExpr());
707 return EmitScalarPrePostIncDec(E, LV, isInc: true, isPre: false);
708 }
709 Value *VisitUnaryPreDec(const UnaryOperator *E) {
710 LValue LV = EmitLValue(E: E->getSubExpr());
711 return EmitScalarPrePostIncDec(E, LV, isInc: false, isPre: true);
712 }
713 Value *VisitUnaryPreInc(const UnaryOperator *E) {
714 LValue LV = EmitLValue(E: E->getSubExpr());
715 return EmitScalarPrePostIncDec(E, LV, isInc: true, isPre: true);
716 }
717
718 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
719 llvm::Value *InVal,
720 bool IsInc);
721
722 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
723 bool isInc, bool isPre);
724
725
726 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
727 if (isa<MemberPointerType>(Val: E->getType())) // never sugared
728 return CGF.CGM.getMemberPointerConstant(e: E);
729
730 return EmitLValue(E: E->getSubExpr()).getPointer(CGF);
731 }
732 Value *VisitUnaryDeref(const UnaryOperator *E) {
733 if (E->getType()->isVoidType())
734 return Visit(E: E->getSubExpr()); // the actual value should be unused
735 return EmitLoadOfLValue(E);
736 }
737
738 Value *VisitUnaryPlus(const UnaryOperator *E,
739 QualType PromotionType = QualType());
740 Value *VisitPlus(const UnaryOperator *E, QualType PromotionType);
741 Value *VisitUnaryMinus(const UnaryOperator *E,
742 QualType PromotionType = QualType());
743 Value *VisitMinus(const UnaryOperator *E, QualType PromotionType);
744
745 Value *VisitUnaryNot (const UnaryOperator *E);
746 Value *VisitUnaryLNot (const UnaryOperator *E);
747 Value *VisitUnaryReal(const UnaryOperator *E,
748 QualType PromotionType = QualType());
749 Value *VisitReal(const UnaryOperator *E, QualType PromotionType);
750 Value *VisitUnaryImag(const UnaryOperator *E,
751 QualType PromotionType = QualType());
752 Value *VisitImag(const UnaryOperator *E, QualType PromotionType);
753 Value *VisitUnaryExtension(const UnaryOperator *E) {
754 return Visit(E: E->getSubExpr());
755 }
756
757 // C++
758 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
759 return EmitLoadOfLValue(E);
760 }
761 Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
762 auto &Ctx = CGF.getContext();
763 APValue Evaluated =
764 SLE->EvaluateInContext(Ctx, DefaultExpr: CGF.CurSourceLocExprScope.getDefaultExpr());
765 return ConstantEmitter(CGF).emitAbstract(loc: SLE->getLocation(), value: Evaluated,
766 T: SLE->getType());
767 }
768
769 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
770 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
771 return Visit(E: DAE->getExpr());
772 }
773 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
774 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
775 return Visit(E: DIE->getExpr());
776 }
777 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
778 return CGF.LoadCXXThis();
779 }
780
781 Value *VisitExprWithCleanups(ExprWithCleanups *E);
782 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
783 return CGF.EmitCXXNewExpr(E);
784 }
785 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
786 CGF.EmitCXXDeleteExpr(E);
787 return nullptr;
788 }
789
790 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
791 if (E->isStoredAsBoolean())
792 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()),
793 V: E->getBoolValue());
794 assert(E->getType()->isIntegerType() && "not a scalar type trait");
795 assert(E->getAPValue().isInt() && "APValue type not supported");
796 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()),
797 V: E->getAPValue().getInt());
798 }
799
800 Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
801 return Builder.getInt1(V: E->isSatisfied());
802 }
803
804 Value *VisitRequiresExpr(const RequiresExpr *E) {
805 return Builder.getInt1(V: E->isSatisfied());
806 }
807
808 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
809 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue());
810 }
811
812 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
813 return llvm::ConstantInt::get(Ty: Builder.getInt1Ty(), V: E->getValue());
814 }
815
816 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
817 // C++ [expr.pseudo]p1:
818 // The result shall only be used as the operand for the function call
819 // operator (), and the result of such a call has type void. The only
820 // effect is the evaluation of the postfix-expression before the dot or
821 // arrow.
822 CGF.EmitScalarExpr(E: E->getBase());
823 return nullptr;
824 }
825
826 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
827 return EmitNullValue(Ty: E->getType());
828 }
829
830 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
831 CGF.EmitCXXThrowExpr(E);
832 return nullptr;
833 }
834
835 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
836 return Builder.getInt1(V: E->getValue());
837 }
838
839 // Binary Operators.
840 Value *EmitMul(const BinOpInfo &Ops) {
841 if (Ops.Ty->isSignedIntegerOrEnumerationType() ||
842 Ops.Ty->isUnsignedIntegerType()) {
843 const bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
844 const bool hasSan =
845 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
846 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
847 switch (getOverflowBehaviorConsideringType(CGF, Ty: Ops.Ty)) {
848 case LangOptions::OB_Wrap:
849 return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
850 case LangOptions::OB_SignedAndDefined:
851 if (!hasSan)
852 return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
853 [[fallthrough]];
854 case LangOptions::OB_Unset:
855 if (!hasSan)
856 return isSigned ? Builder.CreateNSWMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul")
857 : Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
858 [[fallthrough]];
859 case LangOptions::OB_Trap:
860 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: Ops))
861 return isSigned ? Builder.CreateNSWMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul")
862 : Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
863 return EmitOverflowCheckedBinOp(Ops);
864 }
865 }
866
867 if (Ops.Ty->isConstantMatrixType()) {
868 llvm::MatrixBuilder MB(Builder);
869 // We need to check the types of the operands of the operator to get the
870 // correct matrix dimensions.
871 auto *BO = cast<BinaryOperator>(Val: Ops.E);
872 auto *LHSMatTy = dyn_cast<ConstantMatrixType>(
873 Val: BO->getLHS()->getType().getCanonicalType());
874 auto *RHSMatTy = dyn_cast<ConstantMatrixType>(
875 Val: BO->getRHS()->getType().getCanonicalType());
876 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
877 // In HLSL, matrix * matrix is element-wise, so skip this block.
878 if (LHSMatTy && RHSMatTy && !CGF.getLangOpts().HLSL)
879 return MB.CreateMatrixMultiply(LHS: Ops.LHS, RHS: Ops.RHS, LHSRows: LHSMatTy->getNumRows(),
880 LHSColumns: LHSMatTy->getNumColumns(),
881 RHSColumns: RHSMatTy->getNumColumns());
882 return MB.CreateScalarMultiply(LHS: Ops.LHS, RHS: Ops.RHS);
883 }
884
885 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
886 // Preserve the old values
887 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
888 return Builder.CreateFMul(L: Ops.LHS, R: Ops.RHS, Name: "mul");
889 }
890 if (Ops.isFixedPointOp())
891 return EmitFixedPointBinOp(Ops);
892 return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
893 }
894 /// Create a binary op that checks for overflow.
895 /// Currently only supports +, - and *.
896 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
897
898 // Check for undefined division and modulus behaviors.
899 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
900 llvm::Value *Zero,bool isDiv);
901 // Common helper for getting how wide LHS of shift is.
902 static Value *GetMaximumShiftAmount(Value *LHS, Value *RHS, bool RHSIsSigned);
903
904 // Used for shifting constraints for OpenCL, do mask for powers of 2, URem for
905 // non powers of two.
906 Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name);
907
908 Value *EmitDiv(const BinOpInfo &Ops);
909 Value *EmitRem(const BinOpInfo &Ops);
910 Value *EmitAdd(const BinOpInfo &Ops);
911 Value *EmitSub(const BinOpInfo &Ops);
912 Value *EmitShl(const BinOpInfo &Ops);
913 Value *EmitShr(const BinOpInfo &Ops);
914 Value *EmitAnd(const BinOpInfo &Ops) {
915 return Builder.CreateAnd(LHS: Ops.LHS, RHS: Ops.RHS, Name: "and");
916 }
917 Value *EmitXor(const BinOpInfo &Ops) {
918 return Builder.CreateXor(LHS: Ops.LHS, RHS: Ops.RHS, Name: "xor");
919 }
920 Value *EmitOr (const BinOpInfo &Ops) {
921 return Builder.CreateOr(LHS: Ops.LHS, RHS: Ops.RHS, Name: "or");
922 }
923
924 // Helper functions for fixed point binary operations.
925 Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
926
927 BinOpInfo EmitBinOps(const BinaryOperator *E,
928 QualType PromotionTy = QualType());
929
930 Value *EmitPromotedValue(Value *result, QualType PromotionType);
931 Value *EmitUnPromotedValue(Value *result, QualType ExprType);
932 Value *EmitPromoted(const Expr *E, QualType PromotionType);
933
934 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
935 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
936 Value *&Result);
937
938 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
939 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
940
941 QualType getPromotionType(QualType Ty) {
942 const auto &Ctx = CGF.getContext();
943 if (auto *CT = Ty->getAs<ComplexType>()) {
944 QualType ElementType = CT->getElementType();
945 if (ElementType.UseExcessPrecision(Ctx))
946 return Ctx.getComplexType(T: Ctx.FloatTy);
947 }
948
949 if (Ty.UseExcessPrecision(Ctx)) {
950 if (auto *VT = Ty->getAs<VectorType>()) {
951 unsigned NumElements = VT->getNumElements();
952 return Ctx.getVectorType(VectorType: Ctx.FloatTy, NumElts: NumElements, VecKind: VT->getVectorKind());
953 }
954 return Ctx.FloatTy;
955 }
956
957 return QualType();
958 }
959
960 // Binary operators and binary compound assignment operators.
961#define HANDLEBINOP(OP) \
962 Value *VisitBin##OP(const BinaryOperator *E) { \
963 QualType promotionTy = getPromotionType(E->getType()); \
964 auto result = Emit##OP(EmitBinOps(E, promotionTy)); \
965 if (result && !promotionTy.isNull()) \
966 result = EmitUnPromotedValue(result, E->getType()); \
967 return result; \
968 } \
969 Value *VisitBin##OP##Assign(const CompoundAssignOperator *E) { \
970 ApplyAtomGroup Grp(CGF.getDebugInfo()); \
971 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit##OP); \
972 }
973 HANDLEBINOP(Mul)
974 HANDLEBINOP(Div)
975 HANDLEBINOP(Rem)
976 HANDLEBINOP(Add)
977 HANDLEBINOP(Sub)
978 HANDLEBINOP(Shl)
979 HANDLEBINOP(Shr)
980 HANDLEBINOP(And)
981 HANDLEBINOP(Xor)
982 HANDLEBINOP(Or)
983#undef HANDLEBINOP
984
985 // Comparisons.
986 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
987 llvm::CmpInst::Predicate SICmpOpc,
988 llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
989#define VISITCOMP(CODE, UI, SI, FP, SIG) \
990 Value *VisitBin##CODE(const BinaryOperator *E) { \
991 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
992 llvm::FCmpInst::FP, SIG); }
993 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true)
994 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true)
995 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true)
996 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true)
997 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false)
998 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false)
999#undef VISITCOMP
1000
1001 Value *VisitBinAssign (const BinaryOperator *E);
1002
1003 Value *VisitBinLAnd (const BinaryOperator *E);
1004 Value *VisitBinLOr (const BinaryOperator *E);
1005 Value *VisitBinComma (const BinaryOperator *E);
1006
1007 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
1008 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
1009
1010 Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
1011 return Visit(E: E->getSemanticForm());
1012 }
1013
1014 // Other Operators.
1015 Value *VisitBlockExpr(const BlockExpr *BE);
1016 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
1017 Value *VisitChooseExpr(ChooseExpr *CE);
1018 Value *VisitVAArgExpr(VAArgExpr *VE);
1019 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1020 return CGF.EmitObjCStringLiteral(E);
1021 }
1022 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
1023 return CGF.EmitObjCBoxedExpr(E);
1024 }
1025 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
1026 return CGF.EmitObjCArrayLiteral(E);
1027 }
1028 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
1029 return CGF.EmitObjCDictionaryLiteral(E);
1030 }
1031 Value *VisitAsTypeExpr(AsTypeExpr *CE);
1032 Value *VisitAtomicExpr(AtomicExpr *AE);
1033 Value *VisitPackIndexingExpr(PackIndexingExpr *E) {
1034 return Visit(E: E->getSelectedExpr());
1035 }
1036};
1037} // end anonymous namespace.
1038
1039//===----------------------------------------------------------------------===//
1040// Utilities
1041//===----------------------------------------------------------------------===//
1042
1043/// EmitConversionToBool - Convert the specified expression value to a
1044/// boolean (i1) truth value. This is equivalent to "Val != 0".
1045Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
1046 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
1047
1048 if (SrcType->isRealFloatingType())
1049 return EmitFloatToBoolConversion(V: Src);
1050
1051 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(Val&: SrcType))
1052 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr: Src, MPT);
1053
1054 // The conversion is a NOP, and will be done when CodeGening the builtin.
1055 if (SrcType == CGF.getContext().AMDGPUFeaturePredicateTy)
1056 return Src;
1057
1058 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
1059 "Unknown scalar type to convert");
1060
1061 if (isa<llvm::IntegerType>(Val: Src->getType()))
1062 return EmitIntToBoolConversion(V: Src);
1063
1064 assert(isa<llvm::PointerType>(Src->getType()));
1065 return EmitPointerToBoolConversion(V: Src, QT: SrcType);
1066}
1067
1068void ScalarExprEmitter::EmitFloatConversionCheck(
1069 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
1070 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
1071 assert(SrcType->isFloatingType() && "not a conversion from floating point");
1072 if (!isa<llvm::IntegerType>(Val: DstTy))
1073 return;
1074
1075 auto CheckOrdinal = SanitizerKind::SO_FloatCastOverflow;
1076 auto CheckHandler = SanitizerHandler::FloatCastOverflow;
1077 SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler);
1078 using llvm::APFloat;
1079 using llvm::APSInt;
1080
1081 llvm::Value *Check = nullptr;
1082 const llvm::fltSemantics &SrcSema =
1083 CGF.getContext().getFloatTypeSemantics(T: OrigSrcType);
1084
1085 // Floating-point to integer. This has undefined behavior if the source is
1086 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
1087 // to an integer).
1088 unsigned Width = CGF.getContext().getIntWidth(T: DstType);
1089 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
1090
1091 APSInt Min = APSInt::getMinValue(numBits: Width, Unsigned);
1092 APFloat MinSrc(SrcSema, APFloat::uninitialized);
1093 if (MinSrc.convertFromAPInt(Input: Min, IsSigned: !Unsigned, RM: APFloat::rmTowardZero) &
1094 APFloat::opOverflow)
1095 // Don't need an overflow check for lower bound. Just check for
1096 // -Inf/NaN.
1097 MinSrc = APFloat::getInf(Sem: SrcSema, Negative: true);
1098 else
1099 // Find the largest value which is too small to represent (before
1100 // truncation toward zero).
1101 MinSrc.subtract(RHS: APFloat(SrcSema, 1), RM: APFloat::rmTowardNegative);
1102
1103 APSInt Max = APSInt::getMaxValue(numBits: Width, Unsigned);
1104 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
1105 if (MaxSrc.convertFromAPInt(Input: Max, IsSigned: !Unsigned, RM: APFloat::rmTowardZero) &
1106 APFloat::opOverflow)
1107 // Don't need an overflow check for upper bound. Just check for
1108 // +Inf/NaN.
1109 MaxSrc = APFloat::getInf(Sem: SrcSema, Negative: false);
1110 else
1111 // Find the smallest value which is too large to represent (before
1112 // truncation toward zero).
1113 MaxSrc.add(RHS: APFloat(SrcSema, 1), RM: APFloat::rmTowardPositive);
1114
1115 // If we're converting from __half, convert the range to float to match
1116 // the type of src.
1117 if (OrigSrcType->isHalfType()) {
1118 const llvm::fltSemantics &Sema =
1119 CGF.getContext().getFloatTypeSemantics(T: SrcType);
1120 bool IsInexact;
1121 MinSrc.convert(ToSemantics: Sema, RM: APFloat::rmTowardZero, losesInfo: &IsInexact);
1122 MaxSrc.convert(ToSemantics: Sema, RM: APFloat::rmTowardZero, losesInfo: &IsInexact);
1123 }
1124
1125 llvm::Value *GE =
1126 Builder.CreateFCmpOGT(LHS: Src, RHS: llvm::ConstantFP::get(Context&: VMContext, V: MinSrc));
1127 llvm::Value *LE =
1128 Builder.CreateFCmpOLT(LHS: Src, RHS: llvm::ConstantFP::get(Context&: VMContext, V: MaxSrc));
1129 Check = Builder.CreateAnd(LHS: GE, RHS: LE);
1130
1131 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
1132 CGF.EmitCheckTypeDescriptor(T: OrigSrcType),
1133 CGF.EmitCheckTypeDescriptor(T: DstType)};
1134 CGF.EmitCheck(Checked: std::make_pair(x&: Check, y&: CheckOrdinal), Check: CheckHandler, StaticArgs,
1135 DynamicArgs: OrigSrc);
1136}
1137
1138// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1139// Returns 'i1 false' when the truncation Src -> Dst was lossy.
1140static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1141 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1142EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1143 QualType DstType, CGBuilderTy &Builder) {
1144 llvm::Type *SrcTy = Src->getType();
1145 llvm::Type *DstTy = Dst->getType();
1146 (void)DstTy; // Only used in assert()
1147
1148 // This should be truncation of integral types.
1149 assert(Src != Dst);
1150 assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
1151 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1152 "non-integer llvm type");
1153
1154 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1155 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1156
1157 // If both (src and dst) types are unsigned, then it's an unsigned truncation.
1158 // Else, it is a signed truncation.
1159 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
1160 SanitizerKind::SanitizerOrdinal Ordinal;
1161 if (!SrcSigned && !DstSigned) {
1162 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1163 Ordinal = SanitizerKind::SO_ImplicitUnsignedIntegerTruncation;
1164 } else {
1165 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1166 Ordinal = SanitizerKind::SO_ImplicitSignedIntegerTruncation;
1167 }
1168
1169 llvm::Value *Check = nullptr;
1170 // 1. Extend the truncated value back to the same width as the Src.
1171 Check = Builder.CreateIntCast(V: Dst, DestTy: SrcTy, isSigned: DstSigned, Name: "anyext");
1172 // 2. Equality-compare with the original source value
1173 Check = Builder.CreateICmpEQ(LHS: Check, RHS: Src, Name: "truncheck");
1174 // If the comparison result is 'i1 false', then the truncation was lossy.
1175 return std::make_pair(x&: Kind, y: std::make_pair(x&: Check, y&: Ordinal));
1176}
1177
1178static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
1179 QualType SrcType, QualType DstType) {
1180 return SrcType->isIntegerType() && DstType->isIntegerType();
1181}
1182
1183void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
1184 Value *Dst, QualType DstType,
1185 SourceLocation Loc,
1186 bool OBTrapInvolved) {
1187 if (!CGF.SanOpts.hasOneOf(K: SanitizerKind::ImplicitIntegerTruncation) &&
1188 !OBTrapInvolved)
1189 return;
1190
1191 // We only care about int->int conversions here.
1192 // We ignore conversions to/from pointer and/or bool.
1193 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1194 DstType))
1195 return;
1196
1197 unsigned SrcBits = Src->getType()->getScalarSizeInBits();
1198 unsigned DstBits = Dst->getType()->getScalarSizeInBits();
1199 // This must be truncation. Else we do not care.
1200 if (SrcBits <= DstBits)
1201 return;
1202
1203 assert(!DstType->isBooleanType() && "we should not get here with booleans.");
1204
1205 // If the integer sign change sanitizer is enabled,
1206 // and we are truncating from larger unsigned type to smaller signed type,
1207 // let that next sanitizer deal with it.
1208 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1209 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1210 if (CGF.SanOpts.has(K: SanitizerKind::ImplicitIntegerSignChange) &&
1211 (!SrcSigned && DstSigned))
1212 return;
1213
1214 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1215 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1216 Check;
1217
1218 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1219 {
1220 // We don't know the check kind until we call
1221 // EmitIntegerTruncationCheckHelper, but we want to annotate
1222 // EmitIntegerTruncationCheckHelper's instructions too.
1223 SanitizerDebugLocation SanScope(
1224 &CGF,
1225 {SanitizerKind::SO_ImplicitUnsignedIntegerTruncation,
1226 SanitizerKind::SO_ImplicitSignedIntegerTruncation},
1227 CheckHandler);
1228 Check =
1229 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1230 // If the comparison result is 'i1 false', then the truncation was lossy.
1231 }
1232
1233 // Do we care about this type of truncation?
1234 if (!CGF.SanOpts.has(O: Check.second.second)) {
1235 // Just emit a trap check if an __ob_trap was involved but appropriate
1236 // sanitizer isn't enabled.
1237 if (OBTrapInvolved)
1238 CGF.EmitTrapCheck(Checked: Check.second.first, CheckHandlerID: CheckHandler);
1239 return;
1240 }
1241
1242 SanitizerDebugLocation SanScope(&CGF, {Check.second.second}, CheckHandler);
1243
1244 // Does some SSCL ignore this type?
1245 const bool ignoredBySanitizer = CGF.getContext().isTypeIgnoredBySanitizer(
1246 Mask: SanitizerMask::bitPosToMask(Pos: Check.second.second), Ty: DstType);
1247
1248 // Consider OverflowBehaviorTypes which override SSCL type entries for
1249 // truncation sanitizers.
1250 if (const auto *OBT = DstType->getAs<OverflowBehaviorType>()) {
1251 if (OBT->isWrapKind())
1252 return;
1253 }
1254 if (ignoredBySanitizer && !OBTrapInvolved)
1255 return;
1256
1257 llvm::Constant *StaticArgs[] = {
1258 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(T: SrcType),
1259 CGF.EmitCheckTypeDescriptor(T: DstType),
1260 llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: Check.first),
1261 llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: 0)};
1262
1263 CGF.EmitCheck(Checked: Check.second, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst});
1264}
1265
1266static llvm::Value *EmitIsNegativeTestHelper(Value *V, QualType VType,
1267 const char *Name,
1268 CGBuilderTy &Builder) {
1269 bool VSigned = VType->isSignedIntegerOrEnumerationType();
1270 llvm::Type *VTy = V->getType();
1271 if (!VSigned) {
1272 // If the value is unsigned, then it is never negative.
1273 return llvm::ConstantInt::getFalse(Context&: VTy->getContext());
1274 }
1275 llvm::Constant *Zero = llvm::ConstantInt::get(Ty: VTy, V: 0);
1276 return Builder.CreateICmp(P: llvm::ICmpInst::ICMP_SLT, LHS: V, RHS: Zero,
1277 Name: llvm::Twine(Name) + "." + V->getName() +
1278 ".negativitycheck");
1279}
1280
1281// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1282// Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1283static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1284 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1285EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1286 QualType DstType, CGBuilderTy &Builder) {
1287 llvm::Type *SrcTy = Src->getType();
1288 llvm::Type *DstTy = Dst->getType();
1289
1290 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1291 "non-integer llvm type");
1292
1293 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1294 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1295 (void)SrcSigned; // Only used in assert()
1296 (void)DstSigned; // Only used in assert()
1297 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1298 unsigned DstBits = DstTy->getScalarSizeInBits();
1299 (void)SrcBits; // Only used in assert()
1300 (void)DstBits; // Only used in assert()
1301
1302 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1303 "either the widths should be different, or the signednesses.");
1304
1305 // 1. Was the old Value negative?
1306 llvm::Value *SrcIsNegative =
1307 EmitIsNegativeTestHelper(V: Src, VType: SrcType, Name: "src", Builder);
1308 // 2. Is the new Value negative?
1309 llvm::Value *DstIsNegative =
1310 EmitIsNegativeTestHelper(V: Dst, VType: DstType, Name: "dst", Builder);
1311 // 3. Now, was the 'negativity status' preserved during the conversion?
1312 // NOTE: conversion from negative to zero is considered to change the sign.
1313 // (We want to get 'false' when the conversion changed the sign)
1314 // So we should just equality-compare the negativity statuses.
1315 llvm::Value *Check = nullptr;
1316 Check = Builder.CreateICmpEQ(LHS: SrcIsNegative, RHS: DstIsNegative, Name: "signchangecheck");
1317 // If the comparison result is 'false', then the conversion changed the sign.
1318 return std::make_pair(
1319 x: ScalarExprEmitter::ICCK_IntegerSignChange,
1320 y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitIntegerSignChange));
1321}
1322
1323void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1324 Value *Dst, QualType DstType,
1325 SourceLocation Loc,
1326 bool OBTrapInvolved) {
1327 if (!CGF.SanOpts.has(O: SanitizerKind::SO_ImplicitIntegerSignChange) &&
1328 !OBTrapInvolved)
1329 return;
1330
1331 llvm::Type *SrcTy = Src->getType();
1332 llvm::Type *DstTy = Dst->getType();
1333
1334 // We only care about int->int conversions here.
1335 // We ignore conversions to/from pointer and/or bool.
1336 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1337 DstType))
1338 return;
1339
1340 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1341 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1342 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1343 unsigned DstBits = DstTy->getScalarSizeInBits();
1344
1345 // Now, we do not need to emit the check in *all* of the cases.
1346 // We can avoid emitting it in some obvious cases where it would have been
1347 // dropped by the opt passes (instcombine) always anyways.
1348 // If it's a cast between effectively the same type, no check.
1349 // NOTE: this is *not* equivalent to checking the canonical types.
1350 if (SrcSigned == DstSigned && SrcBits == DstBits)
1351 return;
1352 // At least one of the values needs to have signed type.
1353 // If both are unsigned, then obviously, neither of them can be negative.
1354 if (!SrcSigned && !DstSigned)
1355 return;
1356 // If the conversion is to *larger* *signed* type, then no check is needed.
1357 // Because either sign-extension happens (so the sign will remain),
1358 // or zero-extension will happen (the sign bit will be zero.)
1359 if ((DstBits > SrcBits) && DstSigned)
1360 return;
1361 if (CGF.SanOpts.has(K: SanitizerKind::ImplicitSignedIntegerTruncation) &&
1362 (SrcBits > DstBits) && SrcSigned) {
1363 // If the signed integer truncation sanitizer is enabled,
1364 // and this is a truncation from signed type, then no check is needed.
1365 // Because here sign change check is interchangeable with truncation check.
1366 return;
1367 }
1368 // Does an SSCL have an entry for the DstType under its respective sanitizer
1369 // section? Don't check this if an __ob_trap type is involved as it has
1370 // priority to emit checks regardless of sanitizer case lists.
1371 if (!OBTrapInvolved) {
1372 if (DstSigned &&
1373 CGF.getContext().isTypeIgnoredBySanitizer(
1374 Mask: SanitizerKind::ImplicitSignedIntegerTruncation, Ty: DstType))
1375 return;
1376 if (!DstSigned &&
1377 CGF.getContext().isTypeIgnoredBySanitizer(
1378 Mask: SanitizerKind::ImplicitUnsignedIntegerTruncation, Ty: DstType))
1379 return;
1380 }
1381 // That's it. We can't rule out any more cases with the data we have.
1382
1383 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1384 SanitizerDebugLocation SanScope(
1385 &CGF,
1386 {SanitizerKind::SO_ImplicitIntegerSignChange,
1387 SanitizerKind::SO_ImplicitUnsignedIntegerTruncation,
1388 SanitizerKind::SO_ImplicitSignedIntegerTruncation},
1389 CheckHandler);
1390
1391 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1392 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1393 Check;
1394
1395 // Each of these checks needs to return 'false' when an issue was detected.
1396 ImplicitConversionCheckKind CheckKind;
1397 llvm::SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>,
1398 2>
1399 Checks;
1400 // So we can 'and' all the checks together, and still get 'false',
1401 // if at least one of the checks detected an issue.
1402
1403 Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1404 CheckKind = Check.first;
1405 Checks.emplace_back(Args&: Check.second);
1406
1407 if (CGF.SanOpts.has(K: SanitizerKind::ImplicitSignedIntegerTruncation) &&
1408 (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1409 // If the signed integer truncation sanitizer was enabled,
1410 // and we are truncating from larger unsigned type to smaller signed type,
1411 // let's handle the case we skipped in that check.
1412 Check =
1413 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1414 CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1415 Checks.emplace_back(Args&: Check.second);
1416 // If the comparison result is 'i1 false', then the truncation was lossy.
1417 }
1418
1419 if (!CGF.SanOpts.has(O: SanitizerKind::SO_ImplicitIntegerSignChange)) {
1420 if (OBTrapInvolved) {
1421 llvm::Value *Combined = Check.second.first;
1422 for (const auto &C : Checks)
1423 Combined = Builder.CreateAnd(LHS: Combined, RHS: C.first);
1424 CGF.EmitTrapCheck(Checked: Combined, CheckHandlerID: CheckHandler);
1425 }
1426 return;
1427 }
1428
1429 llvm::Constant *StaticArgs[] = {
1430 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(T: SrcType),
1431 CGF.EmitCheckTypeDescriptor(T: DstType),
1432 llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: CheckKind),
1433 llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: 0)};
1434 // EmitCheck() will 'and' all the checks together.
1435 CGF.EmitCheck(Checked: Checks, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst});
1436}
1437
1438// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1439// Returns 'i1 false' when the truncation Src -> Dst was lossy.
1440static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1441 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1442EmitBitfieldTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1443 QualType DstType, CGBuilderTy &Builder) {
1444 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1445 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1446
1447 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
1448 if (!SrcSigned && !DstSigned)
1449 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1450 else
1451 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1452
1453 llvm::Value *Check = nullptr;
1454 // 1. Extend the truncated value back to the same width as the Src.
1455 Check = Builder.CreateIntCast(V: Dst, DestTy: Src->getType(), isSigned: DstSigned, Name: "bf.anyext");
1456 // 2. Equality-compare with the original source value
1457 Check = Builder.CreateICmpEQ(LHS: Check, RHS: Src, Name: "bf.truncheck");
1458 // If the comparison result is 'i1 false', then the truncation was lossy.
1459
1460 return std::make_pair(
1461 x&: Kind,
1462 y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitBitfieldConversion));
1463}
1464
1465// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1466// Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1467static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1468 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1469EmitBitfieldSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1470 QualType DstType, CGBuilderTy &Builder) {
1471 // 1. Was the old Value negative?
1472 llvm::Value *SrcIsNegative =
1473 EmitIsNegativeTestHelper(V: Src, VType: SrcType, Name: "bf.src", Builder);
1474 // 2. Is the new Value negative?
1475 llvm::Value *DstIsNegative =
1476 EmitIsNegativeTestHelper(V: Dst, VType: DstType, Name: "bf.dst", Builder);
1477 // 3. Now, was the 'negativity status' preserved during the conversion?
1478 // NOTE: conversion from negative to zero is considered to change the sign.
1479 // (We want to get 'false' when the conversion changed the sign)
1480 // So we should just equality-compare the negativity statuses.
1481 llvm::Value *Check = nullptr;
1482 Check =
1483 Builder.CreateICmpEQ(LHS: SrcIsNegative, RHS: DstIsNegative, Name: "bf.signchangecheck");
1484 // If the comparison result is 'false', then the conversion changed the sign.
1485 return std::make_pair(
1486 x: ScalarExprEmitter::ICCK_IntegerSignChange,
1487 y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitBitfieldConversion));
1488}
1489
1490void CodeGenFunction::EmitBitfieldConversionCheck(Value *Src, QualType SrcType,
1491 Value *Dst, QualType DstType,
1492 const CGBitFieldInfo &Info,
1493 SourceLocation Loc) {
1494
1495 if (!SanOpts.has(K: SanitizerKind::ImplicitBitfieldConversion))
1496 return;
1497
1498 // We only care about int->int conversions here.
1499 // We ignore conversions to/from pointer and/or bool.
1500 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1501 DstType))
1502 return;
1503
1504 if (DstType->isBooleanType() || SrcType->isBooleanType())
1505 return;
1506
1507 // This should be truncation of integral types.
1508 assert(isa<llvm::IntegerType>(Src->getType()) &&
1509 isa<llvm::IntegerType>(Dst->getType()) && "non-integer llvm type");
1510
1511 // TODO: Calculate src width to avoid emitting code
1512 // for unecessary cases.
1513 unsigned SrcBits = ConvertType(T: SrcType)->getScalarSizeInBits();
1514 unsigned DstBits = Info.Size;
1515
1516 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1517 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1518
1519 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1520 SanitizerDebugLocation SanScope(
1521 this, {SanitizerKind::SO_ImplicitBitfieldConversion}, CheckHandler);
1522
1523 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1524 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1525 Check;
1526
1527 // Truncation
1528 bool EmitTruncation = DstBits < SrcBits;
1529 // If Dst is signed and Src unsigned, we want to be more specific
1530 // about the CheckKind we emit, in this case we want to emit
1531 // ICCK_SignedIntegerTruncationOrSignChange.
1532 bool EmitTruncationFromUnsignedToSigned =
1533 EmitTruncation && DstSigned && !SrcSigned;
1534 // Sign change
1535 bool SameTypeSameSize = SrcSigned == DstSigned && SrcBits == DstBits;
1536 bool BothUnsigned = !SrcSigned && !DstSigned;
1537 bool LargerSigned = (DstBits > SrcBits) && DstSigned;
1538 // We can avoid emitting sign change checks in some obvious cases
1539 // 1. If Src and Dst have the same signedness and size
1540 // 2. If both are unsigned sign check is unecessary!
1541 // 3. If Dst is signed and bigger than Src, either
1542 // sign-extension or zero-extension will make sure
1543 // the sign remains.
1544 bool EmitSignChange = !SameTypeSameSize && !BothUnsigned && !LargerSigned;
1545
1546 if (EmitTruncation)
1547 Check =
1548 EmitBitfieldTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1549 else if (EmitSignChange) {
1550 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1551 "either the widths should be different, or the signednesses.");
1552 Check =
1553 EmitBitfieldSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1554 } else
1555 return;
1556
1557 ScalarExprEmitter::ImplicitConversionCheckKind CheckKind = Check.first;
1558 if (EmitTruncationFromUnsignedToSigned)
1559 CheckKind = ScalarExprEmitter::ICCK_SignedIntegerTruncationOrSignChange;
1560
1561 llvm::Constant *StaticArgs[] = {
1562 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(T: SrcType),
1563 EmitCheckTypeDescriptor(T: DstType),
1564 llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: CheckKind),
1565 llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: Info.Size)};
1566
1567 EmitCheck(Checked: Check.second, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst});
1568}
1569
1570Value *ScalarExprEmitter::EmitScalarCast(Value *Src, QualType SrcType,
1571 QualType DstType, llvm::Type *SrcTy,
1572 llvm::Type *DstTy,
1573 ScalarConversionOpts Opts) {
1574 // The Element types determine the type of cast to perform.
1575 llvm::Type *SrcElementTy;
1576 llvm::Type *DstElementTy;
1577 QualType SrcElementType;
1578 QualType DstElementType;
1579 if (SrcType->isMatrixType() && DstType->isMatrixType()) {
1580 SrcElementTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType();
1581 DstElementTy = cast<llvm::VectorType>(Val: DstTy)->getElementType();
1582 SrcElementType = SrcType->castAs<MatrixType>()->getElementType();
1583 DstElementType = DstType->castAs<MatrixType>()->getElementType();
1584 } else {
1585 assert(!SrcType->isMatrixType() && !DstType->isMatrixType() &&
1586 "cannot cast between matrix and non-matrix types");
1587 SrcElementTy = SrcTy;
1588 DstElementTy = DstTy;
1589 SrcElementType = SrcType;
1590 DstElementType = DstType;
1591 }
1592
1593 if (isa<llvm::IntegerType>(Val: SrcElementTy)) {
1594 bool InputSigned = SrcElementType->isSignedIntegerOrEnumerationType();
1595 if (SrcElementType->isBooleanType() && Opts.TreatBooleanAsSigned) {
1596 InputSigned = true;
1597 }
1598
1599 if (isa<llvm::IntegerType>(Val: DstElementTy))
1600 return Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: InputSigned, Name: "conv");
1601 if (InputSigned)
1602 return Builder.CreateSIToFP(V: Src, DestTy: DstTy, Name: "conv");
1603 return Builder.CreateUIToFP(V: Src, DestTy: DstTy, Name: "conv");
1604 }
1605
1606 if (isa<llvm::IntegerType>(Val: DstElementTy)) {
1607 assert(SrcElementTy->isFloatingPointTy() && "Unknown real conversion");
1608 bool IsSigned = DstElementType->isSignedIntegerOrEnumerationType();
1609
1610 // If we can't recognize overflow as undefined behavior, assume that
1611 // overflow saturates. This protects against normal optimizations if we are
1612 // compiling with non-standard FP semantics.
1613 if (!CGF.CGM.getCodeGenOpts().StrictFloatCastOverflow) {
1614 llvm::Intrinsic::ID IID =
1615 IsSigned ? llvm::Intrinsic::fptosi_sat : llvm::Intrinsic::fptoui_sat;
1616 return Builder.CreateCall(Callee: CGF.CGM.getIntrinsic(IID, Tys: {DstTy, SrcTy}), Args: Src);
1617 }
1618
1619 if (IsSigned)
1620 return Builder.CreateFPToSI(V: Src, DestTy: DstTy, Name: "conv");
1621 return Builder.CreateFPToUI(V: Src, DestTy: DstTy, Name: "conv");
1622 }
1623
1624 if ((DstElementTy->is16bitFPTy() && SrcElementTy->is16bitFPTy())) {
1625 Value *FloatVal = Builder.CreateFPExt(V: Src, DestTy: Builder.getFloatTy(), Name: "fpext");
1626 return Builder.CreateFPTrunc(V: FloatVal, DestTy: DstTy, Name: "fptrunc");
1627 }
1628 if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
1629 return Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv");
1630 return Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv");
1631}
1632
1633/// Emit a conversion from the specified type to the specified destination type,
1634/// both of which are LLVM scalar types.
1635Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
1636 QualType DstType,
1637 SourceLocation Loc,
1638 ScalarConversionOpts Opts) {
1639 // All conversions involving fixed point types should be handled by the
1640 // EmitFixedPoint family functions. This is done to prevent bloating up this
1641 // function more, and although fixed point numbers are represented by
1642 // integers, we do not want to follow any logic that assumes they should be
1643 // treated as integers.
1644 // TODO(leonardchan): When necessary, add another if statement checking for
1645 // conversions to fixed point types from other types.
1646 if (SrcType->isFixedPointType()) {
1647 if (DstType->isBooleanType())
1648 // It is important that we check this before checking if the dest type is
1649 // an integer because booleans are technically integer types.
1650 // We do not need to check the padding bit on unsigned types if unsigned
1651 // padding is enabled because overflow into this bit is undefined
1652 // behavior.
1653 return Builder.CreateIsNotNull(Arg: Src, Name: "tobool");
1654 if (DstType->isFixedPointType() || DstType->isIntegerType() ||
1655 DstType->isRealFloatingType())
1656 return EmitFixedPointConversion(Src, SrcTy: SrcType, DstTy: DstType, Loc);
1657
1658 llvm_unreachable(
1659 "Unhandled scalar conversion from a fixed point type to another type.");
1660 } else if (DstType->isFixedPointType()) {
1661 if (SrcType->isIntegerType() || SrcType->isRealFloatingType())
1662 // This also includes converting booleans and enums to fixed point types.
1663 return EmitFixedPointConversion(Src, SrcTy: SrcType, DstTy: DstType, Loc);
1664
1665 llvm_unreachable(
1666 "Unhandled scalar conversion to a fixed point type from another type.");
1667 }
1668
1669 QualType NoncanonicalSrcType = SrcType;
1670 QualType NoncanonicalDstType = DstType;
1671
1672 SrcType = CGF.getContext().getCanonicalType(T: SrcType);
1673 DstType = CGF.getContext().getCanonicalType(T: DstType);
1674 if (SrcType == DstType) return Src;
1675
1676 if (DstType->isVoidType()) return nullptr;
1677
1678 llvm::Value *OrigSrc = Src;
1679 QualType OrigSrcType = SrcType;
1680 llvm::Type *SrcTy = Src->getType();
1681
1682 // Handle conversions to bool first, they are special: comparisons against 0.
1683 if (DstType->isBooleanType())
1684 return EmitConversionToBool(Src, SrcType);
1685
1686 llvm::Type *DstTy = ConvertType(T: DstType);
1687
1688 // Determine whether an overflow behavior of 'trap' has been specified for
1689 // either the destination or the source types. If so, we can elide sanitizer
1690 // capability checks as this overflow behavior kind is also capable of
1691 // emitting traps without runtime sanitizer support.
1692 // Also skip instrumentation if either source or destination has 'wrap'
1693 // behavior - the user has explicitly indicated they accept wrapping
1694 // semantics. Use non-canonical types to preserve OBT annotations.
1695 const auto *DstOBT = NoncanonicalDstType->getAs<OverflowBehaviorType>();
1696 const auto *SrcOBT = NoncanonicalSrcType->getAs<OverflowBehaviorType>();
1697 bool OBTrapInvolved =
1698 (DstOBT && DstOBT->isTrapKind()) || (SrcOBT && SrcOBT->isTrapKind());
1699 bool OBWrapInvolved =
1700 (DstOBT && DstOBT->isWrapKind()) || (SrcOBT && SrcOBT->isWrapKind());
1701
1702 // If half isn't a native type, cast to float for evaluation.
1703 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1704 SrcTy == CGF.CGM.HalfTy && DstTy != CGF.CGM.HalfTy) {
1705 if (DstTy->isFloatingPointTy())
1706 return Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv");
1707
1708 // Cast to other types through float (as opposed to operations on half,
1709 // available with NativeHalfType).
1710 Src = Builder.CreateFPExt(V: Src, DestTy: CGF.CGM.FloatTy, Name: "conv");
1711 SrcType = CGF.getContext().FloatTy;
1712 SrcTy = CGF.FloatTy;
1713 }
1714
1715 // Ignore conversions like int -> uint.
1716 if (SrcTy == DstTy) {
1717 if (Opts.EmitImplicitIntegerSignChangeChecks ||
1718 (OBTrapInvolved && !OBWrapInvolved))
1719 EmitIntegerSignChangeCheck(Src, SrcType: NoncanonicalSrcType, Dst: Src,
1720 DstType: NoncanonicalDstType, Loc, OBTrapInvolved);
1721
1722 return Src;
1723 }
1724
1725 // Handle pointer conversions next: pointers can only be converted to/from
1726 // other pointers and integers. Check for pointer types in terms of LLVM, as
1727 // some native types (like Obj-C id) may map to a pointer type.
1728 if (auto DstPT = dyn_cast<llvm::PointerType>(Val: DstTy)) {
1729 // The source value may be an integer, or a pointer.
1730 if (isa<llvm::PointerType>(Val: SrcTy))
1731 return Src;
1732
1733 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
1734 // First, convert to the correct width so that we control the kind of
1735 // extension.
1736 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
1737 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1738 llvm::Value* IntResult =
1739 Builder.CreateIntCast(V: Src, DestTy: MiddleTy, isSigned: InputSigned, Name: "conv");
1740 // Then, cast to pointer.
1741 return Builder.CreateIntToPtr(V: IntResult, DestTy: DstTy, Name: "conv");
1742 }
1743
1744 if (isa<llvm::PointerType>(Val: SrcTy)) {
1745 // Must be an ptr to int cast.
1746 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
1747 return Builder.CreatePtrToInt(V: Src, DestTy: DstTy, Name: "conv");
1748 }
1749
1750 // A scalar can be splatted to an extended vector of the same element type
1751 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
1752 // Sema should add casts to make sure that the source expression's type is
1753 // the same as the vector's element type (sans qualifiers)
1754 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1755 SrcType.getTypePtr() &&
1756 "Splatted expr doesn't match with vector element type?");
1757
1758 // Splat the element across to all elements
1759 unsigned NumElements = cast<llvm::FixedVectorType>(Val: DstTy)->getNumElements();
1760 return Builder.CreateVectorSplat(NumElts: NumElements, V: Src, Name: "splat");
1761 }
1762
1763 if (SrcType->isMatrixType() && DstType->isMatrixType())
1764 return EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1765
1766 if (isa<llvm::VectorType>(Val: SrcTy) || isa<llvm::VectorType>(Val: DstTy)) {
1767 // Allow bitcast from vector to integer/fp of the same size.
1768 llvm::TypeSize SrcSize = SrcTy->getPrimitiveSizeInBits();
1769 llvm::TypeSize DstSize = DstTy->getPrimitiveSizeInBits();
1770 if (SrcSize == DstSize)
1771 return Builder.CreateBitCast(V: Src, DestTy: DstTy, Name: "conv");
1772
1773 // Conversions between vectors of different sizes are not allowed except
1774 // when vectors of half are involved. Operations on storage-only half
1775 // vectors require promoting half vector operands to float vectors and
1776 // truncating the result, which is either an int or float vector, to a
1777 // short or half vector.
1778
1779 // Source and destination are both expected to be vectors.
1780 llvm::Type *SrcElementTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType();
1781 llvm::Type *DstElementTy = cast<llvm::VectorType>(Val: DstTy)->getElementType();
1782 (void)DstElementTy;
1783
1784 assert(((SrcElementTy->isIntegerTy() &&
1785 DstElementTy->isIntegerTy()) ||
1786 (SrcElementTy->isFloatingPointTy() &&
1787 DstElementTy->isFloatingPointTy())) &&
1788 "unexpected conversion between a floating-point vector and an "
1789 "integer vector");
1790
1791 // Truncate an i32 vector to an i16 vector.
1792 if (SrcElementTy->isIntegerTy())
1793 return Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: false, Name: "conv");
1794
1795 // Truncate a float vector to a half vector.
1796 if (SrcSize > DstSize)
1797 return Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv");
1798
1799 // Promote a half vector to a float vector.
1800 return Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv");
1801 }
1802
1803 // Finally, we have the arithmetic types: real int/float.
1804 Value *Res = nullptr;
1805 llvm::Type *ResTy = DstTy;
1806
1807 // An overflowing conversion has undefined behavior if either the source type
1808 // or the destination type is a floating-point type. However, we consider the
1809 // range of representable values for all floating-point types to be
1810 // [-inf,+inf], so no overflow can ever happen when the destination type is a
1811 // floating-point type.
1812 if (CGF.SanOpts.has(K: SanitizerKind::FloatCastOverflow) &&
1813 OrigSrcType->isFloatingType())
1814 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1815 Loc);
1816
1817 // Cast to half from float if half isn't a native type. When __fp16 isn't
1818 // native, arithmetic is evaluated as float.
1819 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType &&
1820 DstTy == CGF.CGM.HalfTy) {
1821 // Make sure we cast in a single step if from another FP type.
1822 if (SrcTy->isFloatingPointTy())
1823 return Builder.CreateFPTrunc(V: Src, DestTy: CGF.CGM.HalfTy, Name: "conv");
1824
1825 DstTy = CGF.FloatTy;
1826 }
1827
1828 Res = EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1829
1830 if (DstTy != ResTy) {
1831 Res = Builder.CreateFPTrunc(V: Res, DestTy: CGF.CGM.HalfTy, Name: "conv");
1832
1833 if (ResTy != CGF.CGM.HalfTy) {
1834 assert(ResTy->isIntegerTy(16) &&
1835 "Only half FP requires extra conversion");
1836 Res = Builder.CreateBitCast(V: Res, DestTy: ResTy);
1837 }
1838 }
1839
1840 if ((Opts.EmitImplicitIntegerTruncationChecks || OBTrapInvolved) &&
1841 !OBWrapInvolved && !Opts.PatternExcluded)
1842 EmitIntegerTruncationCheck(Src, SrcType: NoncanonicalSrcType, Dst: Res,
1843 DstType: NoncanonicalDstType, Loc, OBTrapInvolved);
1844
1845 if (Opts.EmitImplicitIntegerSignChangeChecks ||
1846 (OBTrapInvolved && !OBWrapInvolved))
1847 EmitIntegerSignChangeCheck(Src, SrcType: NoncanonicalSrcType, Dst: Res,
1848 DstType: NoncanonicalDstType, Loc, OBTrapInvolved);
1849
1850 return Res;
1851}
1852
1853Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1854 QualType DstTy,
1855 SourceLocation Loc) {
1856 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
1857 llvm::Value *Result;
1858 if (SrcTy->isRealFloatingType())
1859 Result = FPBuilder.CreateFloatingToFixed(Src,
1860 DstSema: CGF.getContext().getFixedPointSemantics(Ty: DstTy));
1861 else if (DstTy->isRealFloatingType())
1862 Result = FPBuilder.CreateFixedToFloating(Src,
1863 SrcSema: CGF.getContext().getFixedPointSemantics(Ty: SrcTy),
1864 DstTy: ConvertType(T: DstTy));
1865 else {
1866 auto SrcFPSema = CGF.getContext().getFixedPointSemantics(Ty: SrcTy);
1867 auto DstFPSema = CGF.getContext().getFixedPointSemantics(Ty: DstTy);
1868
1869 if (DstTy->isIntegerType())
1870 Result = FPBuilder.CreateFixedToInteger(Src, SrcSema: SrcFPSema,
1871 DstWidth: DstFPSema.getWidth(),
1872 DstIsSigned: DstFPSema.isSigned());
1873 else if (SrcTy->isIntegerType())
1874 Result = FPBuilder.CreateIntegerToFixed(Src, SrcIsSigned: SrcFPSema.isSigned(),
1875 DstSema: DstFPSema);
1876 else
1877 Result = FPBuilder.CreateFixedToFixed(Src, SrcSema: SrcFPSema, DstSema: DstFPSema);
1878 }
1879 return Result;
1880}
1881
1882/// Emit a conversion from the specified complex type to the specified
1883/// destination type, where the destination type is an LLVM scalar type.
1884Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1885 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1886 SourceLocation Loc) {
1887 // Get the source element type.
1888 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
1889
1890 // Handle conversions to bool first, they are special: comparisons against 0.
1891 if (DstTy->isBooleanType()) {
1892 // Complex != 0 -> (Real != 0) | (Imag != 0)
1893 Src.first = EmitScalarConversion(Src: Src.first, SrcType: SrcTy, DstType: DstTy, Loc);
1894 Src.second = EmitScalarConversion(Src: Src.second, SrcType: SrcTy, DstType: DstTy, Loc);
1895 return Builder.CreateOr(LHS: Src.first, RHS: Src.second, Name: "tobool");
1896 }
1897
1898 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1899 // the imaginary part of the complex value is discarded and the value of the
1900 // real part is converted according to the conversion rules for the
1901 // corresponding real type.
1902 return EmitScalarConversion(Src: Src.first, SrcType: SrcTy, DstType: DstTy, Loc);
1903}
1904
1905Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
1906 return CGF.EmitFromMemory(Value: CGF.CGM.EmitNullConstant(T: Ty), Ty);
1907}
1908
1909/// Emit a sanitization check for the given "binary" operation (which
1910/// might actually be a unary increment which has been lowered to a binary
1911/// operation). The check passes if all values in \p Checks (which are \c i1),
1912/// are \c true.
1913void ScalarExprEmitter::EmitBinOpCheck(
1914 ArrayRef<std::pair<Value *, SanitizerKind::SanitizerOrdinal>> Checks,
1915 const BinOpInfo &Info) {
1916 assert(CGF.IsSanitizerScope);
1917 SanitizerHandler Check;
1918 SmallVector<llvm::Constant *, 4> StaticData;
1919 SmallVector<llvm::Value *, 2> DynamicData;
1920 TrapReason TR;
1921
1922 BinaryOperatorKind Opcode = Info.Opcode;
1923 if (BinaryOperator::isCompoundAssignmentOp(Opc: Opcode))
1924 Opcode = BinaryOperator::getOpForCompoundAssignment(Opc: Opcode);
1925
1926 StaticData.push_back(Elt: CGF.EmitCheckSourceLocation(Loc: Info.E->getExprLoc()));
1927 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: Info.E);
1928 if (UO && UO->getOpcode() == UO_Minus) {
1929 Check = SanitizerHandler::NegateOverflow;
1930 StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: UO->getType()));
1931 DynamicData.push_back(Elt: Info.RHS);
1932 } else {
1933 if (BinaryOperator::isShiftOp(Opc: Opcode)) {
1934 // Shift LHS negative or too large, or RHS out of bounds.
1935 Check = SanitizerHandler::ShiftOutOfBounds;
1936 const BinaryOperator *BO = cast<BinaryOperator>(Val: Info.E);
1937 StaticData.push_back(
1938 Elt: CGF.EmitCheckTypeDescriptor(T: BO->getLHS()->getType()));
1939 StaticData.push_back(
1940 Elt: CGF.EmitCheckTypeDescriptor(T: BO->getRHS()->getType()));
1941 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1942 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
1943 Check = SanitizerHandler::DivremOverflow;
1944 StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: Info.Ty));
1945 } else {
1946 // Arithmetic overflow (+, -, *).
1947 int ArithOverflowKind = 0;
1948 switch (Opcode) {
1949 case BO_Add: {
1950 Check = SanitizerHandler::AddOverflow;
1951 ArithOverflowKind = diag::UBSanArithKind::Add;
1952 break;
1953 }
1954 case BO_Sub: {
1955 Check = SanitizerHandler::SubOverflow;
1956 ArithOverflowKind = diag::UBSanArithKind::Sub;
1957 break;
1958 }
1959 case BO_Mul: {
1960 Check = SanitizerHandler::MulOverflow;
1961 ArithOverflowKind = diag::UBSanArithKind::Mul;
1962 break;
1963 }
1964 default:
1965 llvm_unreachable("unexpected opcode for bin op check");
1966 }
1967 StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: Info.Ty));
1968 if (CGF.CGM.getCodeGenOpts().SanitizeTrap.has(
1969 K: SanitizerKind::UnsignedIntegerOverflow) ||
1970 CGF.CGM.getCodeGenOpts().SanitizeTrap.has(
1971 K: SanitizerKind::SignedIntegerOverflow)) {
1972 // Only pay the cost for constructing the trap diagnostic if they are
1973 // going to be used.
1974 CGF.CGM.BuildTrapReason(DiagID: diag::trap_ubsan_arith_overflow, TR)
1975 << Info.Ty->isSignedIntegerOrEnumerationType() << ArithOverflowKind
1976 << Info.E;
1977 }
1978 }
1979 DynamicData.push_back(Elt: Info.LHS);
1980 DynamicData.push_back(Elt: Info.RHS);
1981 }
1982
1983 CGF.EmitCheck(Checked: Checks, Check, StaticArgs: StaticData, DynamicArgs: DynamicData, TR: &TR);
1984}
1985
1986//===----------------------------------------------------------------------===//
1987// Visitor Methods
1988//===----------------------------------------------------------------------===//
1989
1990Value *ScalarExprEmitter::VisitExpr(Expr *E) {
1991 CGF.ErrorUnsupported(S: E, Type: "scalar expression");
1992 if (E->getType()->isVoidType())
1993 return nullptr;
1994 return llvm::PoisonValue::get(T: CGF.ConvertType(T: E->getType()));
1995}
1996
1997Value *
1998ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E) {
1999 ASTContext &Context = CGF.getContext();
2000 unsigned AddrSpace =
2001 Context.getTargetAddressSpace(AS: CGF.CGM.GetGlobalConstantAddressSpace());
2002 llvm::Constant *GlobalConstStr = Builder.CreateGlobalString(
2003 Str: E->ComputeName(Context), Name: "__usn_str", AddressSpace: AddrSpace);
2004
2005 llvm::Type *ExprTy = ConvertType(T: E->getType());
2006 return Builder.CreatePointerBitCastOrAddrSpaceCast(V: GlobalConstStr, DestTy: ExprTy,
2007 Name: "usn_addr_cast");
2008}
2009
2010Value *ScalarExprEmitter::VisitEmbedExpr(EmbedExpr *E) {
2011 assert(E->getDataElementCount() == 1);
2012 auto It = E->begin();
2013 return Builder.getInt(AI: (*It)->getValue());
2014}
2015
2016Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
2017 // Vector Mask Case
2018 if (E->getNumSubExprs() == 2) {
2019 Value *LHS = CGF.EmitScalarExpr(E: E->getExpr(Index: 0));
2020 Value *RHS = CGF.EmitScalarExpr(E: E->getExpr(Index: 1));
2021 Value *Mask;
2022
2023 auto *LTy = cast<llvm::FixedVectorType>(Val: LHS->getType());
2024 unsigned LHSElts = LTy->getNumElements();
2025
2026 Mask = RHS;
2027
2028 auto *MTy = cast<llvm::FixedVectorType>(Val: Mask->getType());
2029
2030 // Mask off the high bits of each shuffle index.
2031 Value *MaskBits =
2032 llvm::ConstantInt::get(Ty: MTy, V: llvm::NextPowerOf2(A: LHSElts - 1) - 1);
2033 Mask = Builder.CreateAnd(LHS: Mask, RHS: MaskBits, Name: "mask");
2034
2035 // newv = undef
2036 // mask = mask & maskbits
2037 // for each elt
2038 // n = extract mask i
2039 // x = extract val n
2040 // newv = insert newv, x, i
2041 auto *RTy = llvm::FixedVectorType::get(ElementType: LTy->getElementType(),
2042 NumElts: MTy->getNumElements());
2043 Value* NewV = llvm::PoisonValue::get(T: RTy);
2044 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
2045 Value *IIndx = llvm::ConstantInt::get(Ty: CGF.SizeTy, V: i);
2046 Value *Indx = Builder.CreateExtractElement(Vec: Mask, Idx: IIndx, Name: "shuf_idx");
2047
2048 Value *VExt = Builder.CreateExtractElement(Vec: LHS, Idx: Indx, Name: "shuf_elt");
2049 NewV = Builder.CreateInsertElement(Vec: NewV, NewElt: VExt, Idx: IIndx, Name: "shuf_ins");
2050 }
2051 return NewV;
2052 }
2053
2054 Value* V1 = CGF.EmitScalarExpr(E: E->getExpr(Index: 0));
2055 Value* V2 = CGF.EmitScalarExpr(E: E->getExpr(Index: 1));
2056
2057 SmallVector<int, 32> Indices;
2058 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
2059 llvm::APSInt Idx = E->getShuffleMaskIdx(N: i - 2);
2060 // Check for -1 and output it as undef in the IR.
2061 if (Idx.isSigned() && Idx.isAllOnes())
2062 Indices.push_back(Elt: -1);
2063 else
2064 Indices.push_back(Elt: Idx.getZExtValue());
2065 }
2066
2067 return Builder.CreateShuffleVector(V1, V2, Mask: Indices, Name: "shuffle");
2068}
2069
2070Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
2071 QualType SrcType = E->getSrcExpr()->getType(),
2072 DstType = E->getType();
2073
2074 Value *Src = CGF.EmitScalarExpr(E: E->getSrcExpr());
2075
2076 SrcType = CGF.getContext().getCanonicalType(T: SrcType);
2077 DstType = CGF.getContext().getCanonicalType(T: DstType);
2078 if (SrcType == DstType) return Src;
2079
2080 assert(SrcType->isVectorType() &&
2081 "ConvertVector source type must be a vector");
2082 assert(DstType->isVectorType() &&
2083 "ConvertVector destination type must be a vector");
2084
2085 llvm::Type *SrcTy = Src->getType();
2086 llvm::Type *DstTy = ConvertType(T: DstType);
2087
2088 // Ignore conversions like int -> uint.
2089 if (SrcTy == DstTy)
2090 return Src;
2091
2092 QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
2093 DstEltType = DstType->castAs<VectorType>()->getElementType();
2094
2095 assert(SrcTy->isVectorTy() &&
2096 "ConvertVector source IR type must be a vector");
2097 assert(DstTy->isVectorTy() &&
2098 "ConvertVector destination IR type must be a vector");
2099
2100 llvm::Type *SrcEltTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType(),
2101 *DstEltTy = cast<llvm::VectorType>(Val: DstTy)->getElementType();
2102
2103 if (DstEltType->isBooleanType()) {
2104 assert((SrcEltTy->isFloatingPointTy() ||
2105 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
2106
2107 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: SrcTy);
2108 if (SrcEltTy->isFloatingPointTy()) {
2109 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2110 return Builder.CreateFCmpUNE(LHS: Src, RHS: Zero, Name: "tobool");
2111 } else {
2112 return Builder.CreateICmpNE(LHS: Src, RHS: Zero, Name: "tobool");
2113 }
2114 }
2115
2116 // We have the arithmetic types: real int/float.
2117 Value *Res = nullptr;
2118
2119 if (isa<llvm::IntegerType>(Val: SrcEltTy)) {
2120 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
2121 if (isa<llvm::IntegerType>(Val: DstEltTy))
2122 Res = Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: InputSigned, Name: "conv");
2123 else {
2124 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2125 if (InputSigned)
2126 Res = Builder.CreateSIToFP(V: Src, DestTy: DstTy, Name: "conv");
2127 else
2128 Res = Builder.CreateUIToFP(V: Src, DestTy: DstTy, Name: "conv");
2129 }
2130 } else if (isa<llvm::IntegerType>(Val: DstEltTy)) {
2131 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
2132 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2133 if (DstEltType->isSignedIntegerOrEnumerationType())
2134 Res = Builder.CreateFPToSI(V: Src, DestTy: DstTy, Name: "conv");
2135 else
2136 Res = Builder.CreateFPToUI(V: Src, DestTy: DstTy, Name: "conv");
2137 } else {
2138 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
2139 "Unknown real conversion");
2140 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2141 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
2142 Res = Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv");
2143 else
2144 Res = Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv");
2145 }
2146
2147 return Res;
2148}
2149
2150Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
2151 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(ME: E)) {
2152 CGF.EmitIgnoredExpr(E: E->getBase());
2153 return CGF.emitScalarConstant(Constant, E);
2154 } else {
2155 Expr::EvalResult Result;
2156 if (E->EvaluateAsInt(Result, Ctx: CGF.getContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
2157 llvm::APSInt Value = Result.Val.getInt();
2158 CGF.EmitIgnoredExpr(E: E->getBase());
2159 return Builder.getInt(AI: Value);
2160 }
2161 }
2162
2163 llvm::Value *Result = EmitLoadOfLValue(E);
2164
2165 // If -fdebug-info-for-profiling is specified, emit a pseudo variable and its
2166 // debug info for the pointer, even if there is no variable associated with
2167 // the pointer's expression.
2168 if (CGF.CGM.getCodeGenOpts().DebugInfoForProfiling && CGF.getDebugInfo()) {
2169 if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Val: Result)) {
2170 if (llvm::GetElementPtrInst *GEP =
2171 dyn_cast<llvm::GetElementPtrInst>(Val: Load->getPointerOperand())) {
2172 if (llvm::Instruction *Pointer =
2173 dyn_cast<llvm::Instruction>(Val: GEP->getPointerOperand())) {
2174 QualType Ty = E->getBase()->getType();
2175 if (!E->isArrow())
2176 Ty = CGF.getContext().getPointerType(T: Ty);
2177 CGF.getDebugInfo()->EmitPseudoVariable(Builder, Value: Pointer, Ty);
2178 }
2179 }
2180 }
2181 }
2182 return Result;
2183}
2184
2185Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
2186 TestAndClearIgnoreResultAssign();
2187
2188 // Emit subscript expressions in rvalue context's. For most cases, this just
2189 // loads the lvalue formed by the subscript expr. However, we have to be
2190 // careful, because the base of a vector subscript is occasionally an rvalue,
2191 // so we can't get it as an lvalue.
2192 if (!E->getBase()->getType()->isVectorType() &&
2193 !E->getBase()->getType()->isSveVLSBuiltinType())
2194 return EmitLoadOfLValue(E);
2195
2196 // Handle the vector case. The base must be a vector, the index must be an
2197 // integer value.
2198 Value *Base = Visit(E: E->getBase());
2199 Value *Idx = Visit(E: E->getIdx());
2200 QualType IdxTy = E->getIdx()->getType();
2201
2202 if (CGF.SanOpts.has(K: SanitizerKind::ArrayBounds))
2203 CGF.EmitBoundsCheck(ArrayExpr: E, ArrayExprBase: E->getBase(), Index: Idx, IndexType: IdxTy, /*Accessed*/true);
2204
2205 Value *Ret = Builder.CreateExtractElement(Vec: Base, Idx, Name: "vecext");
2206
2207 // Even being a scalar the `__mfp8` type corresponds to `<1 x i8>` in LLVM IR.
2208 if (E->getType()->isMFloat8Type())
2209 Ret = Builder.CreateInsertElement(
2210 Vec: llvm::PoisonValue::get(T: llvm::FixedVectorType::get(ElementType: CGF.Int8Ty, NumElts: 1)), NewElt: Ret,
2211 Idx: uint64_t(0), Name: "mfp8ext");
2212
2213 return Ret;
2214}
2215
2216Value *ScalarExprEmitter::VisitMatrixSingleSubscriptExpr(
2217 MatrixSingleSubscriptExpr *E) {
2218 TestAndClearIgnoreResultAssign();
2219
2220 auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
2221 unsigned NumRows = MatrixTy->getNumRows();
2222 unsigned NumColumns = MatrixTy->getNumColumns();
2223
2224 // Row index
2225 Value *RowIdx = CGF.EmitMatrixIndexExpr(E: E->getRowIdx());
2226 llvm::MatrixBuilder MB(Builder);
2227
2228 // The row index must be in [0, NumRows)
2229 if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0)
2230 MB.CreateIndexAssumption(Idx: RowIdx, NumElements: NumRows);
2231
2232 Value *FlatMatrix = Visit(E: E->getBase());
2233 llvm::Type *ElemTy = CGF.ConvertType(T: MatrixTy->getElementType());
2234 auto *ResultTy = llvm::FixedVectorType::get(ElementType: ElemTy, NumElts: NumColumns);
2235 Value *RowVec = llvm::PoisonValue::get(T: ResultTy);
2236
2237 for (unsigned Col = 0; Col != NumColumns; ++Col) {
2238 Value *ColVal = llvm::ConstantInt::get(Ty: RowIdx->getType(), V: Col);
2239 Value *EltIdx = MB.CreateIndex(RowIdx, ColumnIdx: ColVal, NumRows, NumCols: NumColumns,
2240 /*IsRowMajor=*/IsMatrixRowMajor: false, Name: "matrix_row_idx");
2241 Value *Elt =
2242 Builder.CreateExtractElement(Vec: FlatMatrix, Idx: EltIdx, Name: "matrix_elem");
2243 Value *Lane = llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: Col);
2244 RowVec = Builder.CreateInsertElement(Vec: RowVec, NewElt: Elt, Idx: Lane, Name: "matrix_row_ins");
2245 }
2246
2247 return RowVec;
2248}
2249
2250Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
2251 TestAndClearIgnoreResultAssign();
2252
2253 // HLSL matrix loads are normalized to column-major register values, but
2254 // non-HLSL matrix values retain the selected memory layout.
2255 Value *RowIdx = CGF.EmitMatrixIndexExpr(E: E->getRowIdx());
2256 Value *ColumnIdx = CGF.EmitMatrixIndexExpr(E: E->getColumnIdx());
2257
2258 const auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
2259 llvm::MatrixBuilder MB(Builder);
2260
2261 unsigned NumCols = MatrixTy->getNumColumns();
2262 unsigned NumRows = MatrixTy->getNumRows();
2263 bool IsMatrixRowMajor =
2264 !CGF.getLangOpts().HLSL &&
2265 isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: E->getBase()->getType());
2266 Value *Idx =
2267 MB.CreateIndex(RowIdx, ColumnIdx, NumRows, NumCols, IsMatrixRowMajor);
2268
2269 if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0)
2270 MB.CreateIndexAssumption(Idx, NumElements: MatrixTy->getNumElementsFlattened());
2271
2272 Value *Matrix = Visit(E: E->getBase());
2273
2274 // TODO: Should we emit bounds checks with SanitizerKind::ArrayBounds?
2275 return Builder.CreateExtractElement(Vec: Matrix, Idx, Name: "matrixext");
2276}
2277
2278static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
2279 unsigned Off) {
2280 int MV = SVI->getMaskValue(Elt: Idx);
2281 if (MV == -1)
2282 return -1;
2283 return Off + MV;
2284}
2285
2286static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
2287 assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) &&
2288 "Index operand too large for shufflevector mask!");
2289 return C->getZExtValue();
2290}
2291
2292Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
2293 bool Ignore = TestAndClearIgnoreResultAssign();
2294 (void)Ignore;
2295 unsigned NumInitElements = E->getNumInits();
2296 assert((Ignore == false ||
2297 (NumInitElements == 0 && E->getType()->isVoidType())) &&
2298 "init list ignored");
2299
2300 // HLSL initialization lists in the AST are an expansion which can contain
2301 // side-effecting expressions wrapped in opaque value expressions. To properly
2302 // emit these we need to emit the opaque values before we emit the argument
2303 // expressions themselves. This is a little hacky, but it prevents us needing
2304 // to do a bigger AST-level change for a language feature that we need
2305 // deprecate in the near future. See related HLSL language proposals in the
2306 // proposals (https://github.com/microsoft/hlsl-specs/blob/main/proposals):
2307 // * 0005-strict-initializer-lists.md
2308 // * 0032-constructors.md
2309 if (CGF.getLangOpts().HLSL)
2310 CGF.CGM.getHLSLRuntime().emitInitListOpaqueValues(CGF, E);
2311
2312 if (E->hadArrayRangeDesignator())
2313 CGF.ErrorUnsupported(S: E, Type: "GNU array range designator extension");
2314
2315 llvm::VectorType *VType =
2316 dyn_cast<llvm::VectorType>(Val: ConvertType(T: E->getType()));
2317
2318 if (!VType) {
2319 if (NumInitElements == 0) {
2320 // C++11 value-initialization for the scalar.
2321 return EmitNullValue(Ty: E->getType());
2322 }
2323 // We have a scalar in braces. Just use the first element.
2324 return Visit(E: E->getInit(Init: 0));
2325 }
2326
2327 if (isa<llvm::ScalableVectorType>(Val: VType)) {
2328 if (NumInitElements == 0) {
2329 // C++11 value-initialization for the vector.
2330 return EmitNullValue(Ty: E->getType());
2331 }
2332
2333 if (NumInitElements == 1) {
2334 Expr *InitVector = E->getInit(Init: 0);
2335
2336 // Initialize from another scalable vector of the same type.
2337 if (InitVector->getType().getCanonicalType() ==
2338 E->getType().getCanonicalType())
2339 return Visit(E: InitVector);
2340 }
2341
2342 llvm_unreachable("Unexpected initialization of a scalable vector!");
2343 }
2344
2345 unsigned ResElts = cast<llvm::FixedVectorType>(Val: VType)->getNumElements();
2346
2347 // For column-major matrix types, we insert elements directly at their
2348 // column-major positions rather than inserting sequentially and shuffling.
2349 const ConstantMatrixType *ColMajorMT =
2350 E->getType()->getAs<ConstantMatrixType>();
2351
2352 // Loop over initializers collecting the Value for each, and remembering
2353 // whether the source was swizzle (ExtVectorElementExpr). This will allow
2354 // us to fold the shuffle for the swizzle into the shuffle for the vector
2355 // initializer, since LLVM optimizers generally do not want to touch
2356 // shuffles.
2357 unsigned CurIdx = 0;
2358 bool VIsPoisonShuffle = false;
2359 llvm::Value *V = llvm::PoisonValue::get(T: VType);
2360 for (unsigned i = 0; i != NumInitElements; ++i) {
2361 Expr *IE = E->getInit(Init: i);
2362 Value *Init = Visit(E: IE);
2363 SmallVector<int, 16> Args;
2364
2365 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Val: Init->getType());
2366
2367 // Handle scalar elements. If the scalar initializer is actually one
2368 // element of a different vector of the same width, use shuffle instead of
2369 // extract+insert.
2370 if (!VVT) {
2371 if (isa<ExtVectorElementExpr>(Val: IE)) {
2372 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Val: Init);
2373
2374 if (cast<llvm::FixedVectorType>(Val: EI->getVectorOperandType())
2375 ->getNumElements() == ResElts) {
2376 llvm::ConstantInt *C = cast<llvm::ConstantInt>(Val: EI->getIndexOperand());
2377 Value *LHS = nullptr, *RHS = nullptr;
2378 if (CurIdx == 0) {
2379 // insert into poison -> shuffle (src, poison)
2380 // shufflemask must use an i32
2381 Args.push_back(Elt: getAsInt32(C, I32Ty: CGF.Int32Ty));
2382 Args.resize(N: ResElts, NV: -1);
2383
2384 LHS = EI->getVectorOperand();
2385 RHS = V;
2386 VIsPoisonShuffle = true;
2387 } else if (VIsPoisonShuffle) {
2388 // insert into poison shuffle && size match -> shuffle (v, src)
2389 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(Val: V);
2390 for (unsigned j = 0; j != CurIdx; ++j)
2391 Args.push_back(Elt: getMaskElt(SVI: SVV, Idx: j, Off: 0));
2392 Args.push_back(Elt: ResElts + C->getZExtValue());
2393 Args.resize(N: ResElts, NV: -1);
2394
2395 LHS = cast<llvm::ShuffleVectorInst>(Val: V)->getOperand(i_nocapture: 0);
2396 RHS = EI->getVectorOperand();
2397 VIsPoisonShuffle = false;
2398 }
2399 if (!Args.empty()) {
2400 V = Builder.CreateShuffleVector(V1: LHS, V2: RHS, Mask: Args);
2401 ++CurIdx;
2402 continue;
2403 }
2404 }
2405 }
2406 unsigned InsertIdx =
2407 ColMajorMT
2408 ? ColMajorMT->mapRowMajorToColumnMajorFlattenedIndex(RowMajorIdx: CurIdx)
2409 : CurIdx;
2410 V = Builder.CreateInsertElement(Vec: V, NewElt: Init, Idx: Builder.getInt32(C: InsertIdx),
2411 Name: "vecinit");
2412 VIsPoisonShuffle = false;
2413 ++CurIdx;
2414 continue;
2415 }
2416
2417 unsigned InitElts = cast<llvm::FixedVectorType>(Val: VVT)->getNumElements();
2418
2419 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
2420 // input is the same width as the vector being constructed, generate an
2421 // optimized shuffle of the swizzle input into the result.
2422 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
2423 if (isa<ExtVectorElementExpr>(Val: IE)) {
2424 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Val: Init);
2425 Value *SVOp = SVI->getOperand(i_nocapture: 0);
2426 auto *OpTy = cast<llvm::FixedVectorType>(Val: SVOp->getType());
2427
2428 if (OpTy->getNumElements() == ResElts) {
2429 for (unsigned j = 0; j != CurIdx; ++j) {
2430 // If the current vector initializer is a shuffle with poison, merge
2431 // this shuffle directly into it.
2432 if (VIsPoisonShuffle) {
2433 Args.push_back(Elt: getMaskElt(SVI: cast<llvm::ShuffleVectorInst>(Val: V), Idx: j, Off: 0));
2434 } else {
2435 Args.push_back(Elt: j);
2436 }
2437 }
2438 for (unsigned j = 0, je = InitElts; j != je; ++j)
2439 Args.push_back(Elt: getMaskElt(SVI, Idx: j, Off: Offset));
2440 Args.resize(N: ResElts, NV: -1);
2441
2442 if (VIsPoisonShuffle)
2443 V = cast<llvm::ShuffleVectorInst>(Val: V)->getOperand(i_nocapture: 0);
2444
2445 Init = SVOp;
2446 }
2447 }
2448
2449 // Extend init to result vector length, and then shuffle its contribution
2450 // to the vector initializer into V.
2451 if (Args.empty()) {
2452 for (unsigned j = 0; j != InitElts; ++j)
2453 Args.push_back(Elt: j);
2454 Args.resize(N: ResElts, NV: -1);
2455 Init = Builder.CreateShuffleVector(V: Init, Mask: Args, Name: "vext");
2456
2457 Args.clear();
2458 for (unsigned j = 0; j != CurIdx; ++j)
2459 Args.push_back(Elt: j);
2460 for (unsigned j = 0; j != InitElts; ++j)
2461 Args.push_back(Elt: j + Offset);
2462 Args.resize(N: ResElts, NV: -1);
2463 }
2464
2465 // If V is poison, make sure it ends up on the RHS of the shuffle to aid
2466 // merging subsequent shuffles into this one.
2467 if (CurIdx == 0)
2468 std::swap(a&: V, b&: Init);
2469 V = Builder.CreateShuffleVector(V1: V, V2: Init, Mask: Args, Name: "vecinit");
2470 VIsPoisonShuffle = isa<llvm::PoisonValue>(Val: Init);
2471 CurIdx += InitElts;
2472 }
2473
2474 // FIXME: evaluate codegen vs. shuffling against constant null vector.
2475 // Emit remaining default initializers.
2476 llvm::Type *EltTy = VType->getElementType();
2477
2478 // Emit remaining default initializers
2479 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
2480 unsigned InsertIdx =
2481 ColMajorMT ? ColMajorMT->mapRowMajorToColumnMajorFlattenedIndex(RowMajorIdx: CurIdx)
2482 : CurIdx;
2483 Value *Idx = Builder.getInt32(C: InsertIdx);
2484 llvm::Value *Init = llvm::Constant::getNullValue(Ty: EltTy);
2485 V = Builder.CreateInsertElement(Vec: V, NewElt: Init, Idx, Name: "vecinit");
2486 }
2487
2488 return V;
2489}
2490
2491static bool isDeclRefKnownNonNull(CodeGenFunction &CGF, const ValueDecl *D) {
2492 return !D->isWeak();
2493}
2494
2495static bool isLValueKnownNonNull(CodeGenFunction &CGF, const Expr *E) {
2496 E = E->IgnoreParens();
2497
2498 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E))
2499 if (UO->getOpcode() == UO_Deref)
2500 return CGF.isPointerKnownNonNull(E: UO->getSubExpr());
2501
2502 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E))
2503 return isDeclRefKnownNonNull(CGF, D: DRE->getDecl());
2504
2505 if (const auto *ME = dyn_cast<MemberExpr>(Val: E)) {
2506 if (isa<FieldDecl>(Val: ME->getMemberDecl()))
2507 return true;
2508 return isDeclRefKnownNonNull(CGF, D: ME->getMemberDecl());
2509 }
2510
2511 // Array subscripts? Anything else?
2512
2513 return false;
2514}
2515
2516bool CodeGenFunction::isPointerKnownNonNull(const Expr *E) {
2517 assert(E->getType().getAtomicUnqualifiedType()->isSignableType(getContext()));
2518
2519 E = E->IgnoreParens();
2520
2521 if (isa<CXXThisExpr>(Val: E))
2522 return true;
2523
2524 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E))
2525 if (UO->getOpcode() == UO_AddrOf)
2526 return isLValueKnownNonNull(CGF&: *this, E: UO->getSubExpr());
2527
2528 if (const auto *CE = dyn_cast<CastExpr>(Val: E))
2529 if (CE->getCastKind() == CK_FunctionToPointerDecay ||
2530 CE->getCastKind() == CK_ArrayToPointerDecay)
2531 return isLValueKnownNonNull(CGF&: *this, E: CE->getSubExpr());
2532
2533 // Maybe honor __nonnull?
2534
2535 return false;
2536}
2537
2538bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
2539 const Expr *E = CE->getSubExpr();
2540
2541 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
2542 return false;
2543
2544 if (isa<CXXThisExpr>(Val: E->IgnoreParens())) {
2545 // We always assume that 'this' is never null.
2546 return false;
2547 }
2548
2549 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: CE)) {
2550 // And that glvalue casts are never null.
2551 if (ICE->isGLValue())
2552 return false;
2553 }
2554
2555 return true;
2556}
2557
2558template <typename GetElementTy>
2559static Value *
2560EmitHLSLElementwiseCastToVector(CodeGenFunction &CGF, QualType DestTy,
2561 unsigned NumSrcElements,
2562 GetElementTy GetElement, SourceLocation Loc) {
2563 const auto *VecTy = DestTy->castAs<VectorType>();
2564 assert(NumSrcElements >= VecTy->getNumElements() &&
2565 "Flattened type on RHS must have the same number or more elements "
2566 "than vector on LHS.");
2567 Value *V = llvm::PoisonValue::get(T: CGF.ConvertType(T: DestTy));
2568 for (unsigned I = 0, E = VecTy->getNumElements(); I < E; ++I) {
2569 auto [Element, ElementTy] = GetElement(I);
2570 Value *Cast = CGF.EmitScalarConversion(Src: Element, SrcTy: ElementTy,
2571 DstTy: VecTy->getElementType(), Loc);
2572 V = CGF.Builder.CreateInsertElement(Vec: V, NewElt: Cast, Idx: I);
2573 }
2574 return V;
2575}
2576
2577// RHS is an aggregate type
2578static Value *EmitHLSLElementwiseCast(CodeGenFunction &CGF, LValue SrcVal,
2579 QualType DestTy, SourceLocation Loc) {
2580 SmallVector<LValue, 16> LoadList;
2581 CGF.FlattenAccessAndTypeLValue(LVal: SrcVal, AccessList&: LoadList);
2582 // Dest is either a vector, constant matrix, or a builtin
2583 if (DestTy->isVectorType())
2584 return EmitHLSLElementwiseCastToVector(
2585 CGF, DestTy, NumSrcElements: LoadList.size(),
2586 GetElement: [&](unsigned I) {
2587 RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[I], Loc);
2588 assert(RVal.isScalar() &&
2589 "All flattened source values should be scalars.");
2590 return std::pair(RVal.getScalarVal(), LoadList[I].getType());
2591 },
2592 Loc);
2593
2594 if (auto *MatTy = DestTy->getAs<ConstantMatrixType>()) {
2595 assert(LoadList.size() >= MatTy->getNumElementsFlattened() &&
2596 "Flattened type on RHS must have the same number or more elements "
2597 "than vector on LHS.");
2598
2599 llvm::Value *V = llvm::PoisonValue::get(T: CGF.ConvertType(T: DestTy));
2600 // V is an allocated temporary for constructing the matrix.
2601 for (unsigned Row = 0, RE = MatTy->getNumRows(); Row < RE; Row++) {
2602 for (unsigned Col = 0, CE = MatTy->getNumColumns(); Col < CE; Col++) {
2603 // When interpreted as a matrix, \p LoadList is *always* row-major order
2604 // regardless of the default matrix memory layout.
2605 unsigned LoadIdx = MatTy->getRowMajorFlattenedIndex(Row, Column: Col);
2606 RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[LoadIdx], Loc);
2607 assert(RVal.isScalar() &&
2608 "All flattened source values should be scalars.");
2609 llvm::Value *Cast = CGF.EmitScalarConversion(
2610 Src: RVal.getScalarVal(), SrcTy: LoadList[LoadIdx].getType(),
2611 DstTy: MatTy->getElementType(), Loc);
2612 unsigned MatrixIdx = MatTy->getColumnMajorFlattenedIndex(Row, Column: Col);
2613 V = CGF.Builder.CreateInsertElement(Vec: V, NewElt: Cast, Idx: MatrixIdx);
2614 }
2615 }
2616 return V;
2617 }
2618 // if its a builtin just do an extract element or load.
2619 assert(DestTy->isBuiltinType() &&
2620 "Destination type must be a vector, matrix, or builtin type.");
2621 RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[0], Loc);
2622 assert(RVal.isScalar() && "All flattened source values should be scalars.");
2623 return CGF.EmitScalarConversion(Src: RVal.getScalarVal(), SrcTy: LoadList[0].getType(),
2624 DstTy: DestTy, Loc);
2625}
2626
2627// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
2628// have to handle a more broad range of conversions than explicit casts, as they
2629// handle things like function to ptr-to-function decay etc.
2630Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
2631 llvm::scope_exit RestoreCurCast(
2632 [this, Prev = CGF.CurCast] { CGF.CurCast = Prev; });
2633 CGF.CurCast = CE;
2634
2635 Expr *E = CE->getSubExpr();
2636 QualType DestTy = CE->getType();
2637 CastKind Kind = CE->getCastKind();
2638 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, CE);
2639
2640 // These cases are generally not written to ignore the result of
2641 // evaluating their sub-expressions, so we clear this now.
2642 bool Ignored = TestAndClearIgnoreResultAssign();
2643
2644 // Since almost all cast kinds apply to scalars, this switch doesn't have
2645 // a default case, so the compiler will warn on a missing case. The cases
2646 // are in the same order as in the CastKind enum.
2647 switch (Kind) {
2648 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
2649 case CK_BuiltinFnToFnPtr:
2650 llvm_unreachable("builtin functions are handled elsewhere");
2651
2652 case CK_LValueBitCast:
2653 case CK_ObjCObjectLValueCast: {
2654 Address Addr = EmitLValue(E).getAddress();
2655 Addr = Addr.withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy));
2656 LValue LV = CGF.MakeAddrLValue(Addr, T: DestTy);
2657 return EmitLoadOfLValue(LV, Loc: CE->getExprLoc());
2658 }
2659
2660 case CK_LValueToRValueBitCast: {
2661 LValue SourceLVal = CGF.EmitLValue(E);
2662 Address Addr =
2663 SourceLVal.getAddress().withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy));
2664 LValue DestLV = CGF.MakeAddrLValue(Addr, T: DestTy);
2665 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2666 return EmitLoadOfLValue(LV: DestLV, Loc: CE->getExprLoc());
2667 }
2668
2669 case CK_CPointerToObjCPointerCast:
2670 case CK_BlockPointerToObjCPointerCast:
2671 case CK_AnyPointerToBlockPointerCast:
2672 case CK_BitCast: {
2673 Value *Src = Visit(E);
2674 llvm::Type *SrcTy = Src->getType();
2675 llvm::Type *DstTy = ConvertType(T: DestTy);
2676
2677 // FIXME: this is a gross but seemingly necessary workaround for an issue
2678 // manifesting when a target uses a non-default AS for indirect sret args,
2679 // but the source HLL is generic, wherein a valid C-cast or reinterpret_cast
2680 // on the address of a local struct that gets returned by value yields an
2681 // invalid bitcast from the a pointer to the IndirectAS to a pointer to the
2682 // DefaultAS. We can only do this subversive thing because sret args are
2683 // manufactured and them residing in the IndirectAS is a target specific
2684 // detail, and doing an AS cast here still retains the semantics the user
2685 // expects. It is desirable to remove this iff a better solution is found.
2686 if (auto A = dyn_cast<llvm::Argument>(Val: Src); A && A->hasStructRetAttr())
2687 return CGF.performAddrSpaceCast(Src, DestTy: DstTy);
2688
2689 // FIXME: Similarly to the sret case above, we need to handle BitCasts that
2690 // involve implicit address space conversions. This arises when the source
2691 // language lacks explicit address spaces, but the target's data layout
2692 // assigns different address spaces (e.g., program address space for
2693 // function pointers). Since Sema operates on Clang types (which don't carry
2694 // this information) and selects CK_BitCast, we must detect the address
2695 // space mismatch here in CodeGen when lowering to LLVM types. The most
2696 // common case is casting function pointers (which get the program AS from
2697 // the data layout) to/from object pointers (which use the default AS).
2698 // Ideally, this would be resolved at a higher level, but that would require
2699 // exposing data layout details to Sema.
2700 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
2701 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
2702 return CGF.performAddrSpaceCast(Src, DestTy: DstTy);
2703 }
2704
2705 assert(
2706 (!SrcTy->isPtrOrPtrVectorTy() || !DstTy->isPtrOrPtrVectorTy() ||
2707 SrcTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace()) &&
2708 "Address-space cast must be used to convert address spaces");
2709
2710 if (CGF.SanOpts.has(K: SanitizerKind::CFIUnrelatedCast)) {
2711 if (auto *PT = DestTy->getAs<PointerType>()) {
2712 CGF.EmitVTablePtrCheckForCast(
2713 T: PT->getPointeeType(),
2714 Derived: Address(Src,
2715 CGF.ConvertTypeForMem(
2716 T: E->getType()->castAs<PointerType>()->getPointeeType()),
2717 CGF.getPointerAlign()),
2718 /*MayBeNull=*/true, TCK: CodeGenFunction::CFITCK_UnrelatedCast,
2719 Loc: CE->getBeginLoc());
2720 }
2721 }
2722
2723 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2724 const QualType SrcType = E->getType();
2725
2726 if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
2727 // Casting to pointer that could carry dynamic information (provided by
2728 // invariant.group) requires launder.
2729 Src = Builder.CreateLaunderInvariantGroup(Ptr: Src);
2730 }
2731 }
2732
2733 // Update heapallocsite metadata when there is an explicit pointer cast.
2734 if (auto *CI = dyn_cast<llvm::CallBase>(Val: Src)) {
2735 if (CI->getMetadata(Kind: "heapallocsite") && isa<ExplicitCastExpr>(Val: CE) &&
2736 !isa<CastExpr>(Val: E)) {
2737 QualType PointeeType = DestTy->getPointeeType();
2738 if (!PointeeType.isNull())
2739 CGF.getDebugInfo()->addHeapAllocSiteMetadata(CallSite: CI, AllocatedTy: PointeeType,
2740 Loc: CE->getExprLoc());
2741 }
2742 }
2743
2744 // If Src is a fixed vector and Dst is a scalable vector, and both have the
2745 // same element type, use the llvm.vector.insert intrinsic to perform the
2746 // bitcast.
2747 if (auto *FixedSrcTy = dyn_cast<llvm::FixedVectorType>(Val: SrcTy)) {
2748 if (auto *ScalableDstTy = dyn_cast<llvm::ScalableVectorType>(Val: DstTy)) {
2749 // If we are casting a fixed i8 vector to a scalable i1 predicate
2750 // vector, use a vector insert and bitcast the result.
2751 if (ScalableDstTy->getElementType()->isIntegerTy(BitWidth: 1) &&
2752 FixedSrcTy->getElementType()->isIntegerTy(BitWidth: 8)) {
2753 ScalableDstTy = llvm::ScalableVectorType::get(
2754 ElementType: FixedSrcTy->getElementType(),
2755 MinNumElts: llvm::divideCeil(
2756 Numerator: ScalableDstTy->getElementCount().getKnownMinValue(), Denominator: 8));
2757 }
2758 if (FixedSrcTy->getElementType() == ScalableDstTy->getElementType()) {
2759 llvm::Value *PoisonVec = llvm::PoisonValue::get(T: ScalableDstTy);
2760 llvm::Value *Result = Builder.CreateInsertVector(
2761 DstType: ScalableDstTy, SrcVec: PoisonVec, SubVec: Src, Idx: uint64_t(0), Name: "cast.scalable");
2762 ScalableDstTy = cast<llvm::ScalableVectorType>(
2763 Val: llvm::VectorType::getWithSizeAndScalar(SizeTy: ScalableDstTy, EltTy: DstTy));
2764 if (Result->getType() != ScalableDstTy)
2765 Result = Builder.CreateBitCast(V: Result, DestTy: ScalableDstTy);
2766 if (Result->getType() != DstTy)
2767 Result = Builder.CreateExtractVector(DstType: DstTy, SrcVec: Result, Idx: uint64_t(0));
2768 return Result;
2769 }
2770 }
2771 }
2772
2773 // If Src is a scalable vector and Dst is a fixed vector, and both have the
2774 // same element type, use the llvm.vector.extract intrinsic to perform the
2775 // bitcast.
2776 if (auto *ScalableSrcTy = dyn_cast<llvm::ScalableVectorType>(Val: SrcTy)) {
2777 if (auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(Val: DstTy)) {
2778 // If we are casting a scalable i1 predicate vector to a fixed i8
2779 // vector, bitcast the source and use a vector extract.
2780 if (ScalableSrcTy->getElementType()->isIntegerTy(BitWidth: 1) &&
2781 FixedDstTy->getElementType()->isIntegerTy(BitWidth: 8)) {
2782 if (!ScalableSrcTy->getElementCount().isKnownMultipleOf(RHS: 8)) {
2783 ScalableSrcTy = llvm::ScalableVectorType::get(
2784 ElementType: ScalableSrcTy->getElementType(),
2785 MinNumElts: llvm::alignTo<8>(
2786 Value: ScalableSrcTy->getElementCount().getKnownMinValue()));
2787 llvm::Value *ZeroVec = llvm::Constant::getNullValue(Ty: ScalableSrcTy);
2788 Src = Builder.CreateInsertVector(DstType: ScalableSrcTy, SrcVec: ZeroVec, SubVec: Src,
2789 Idx: uint64_t(0));
2790 }
2791
2792 ScalableSrcTy = llvm::ScalableVectorType::get(
2793 ElementType: FixedDstTy->getElementType(),
2794 MinNumElts: ScalableSrcTy->getElementCount().getKnownMinValue() / 8);
2795 Src = Builder.CreateBitCast(V: Src, DestTy: ScalableSrcTy);
2796 }
2797 if (ScalableSrcTy->getElementType() == FixedDstTy->getElementType())
2798 return Builder.CreateExtractVector(DstType: DstTy, SrcVec: Src, Idx: uint64_t(0),
2799 Name: "cast.fixed");
2800 }
2801 }
2802
2803 // Perform VLAT <-> VLST bitcast through memory.
2804 // TODO: since the llvm.vector.{insert,extract} intrinsics
2805 // require the element types of the vectors to be the same, we
2806 // need to keep this around for bitcasts between VLAT <-> VLST where
2807 // the element types of the vectors are not the same, until we figure
2808 // out a better way of doing these casts.
2809 if ((isa<llvm::FixedVectorType>(Val: SrcTy) &&
2810 isa<llvm::ScalableVectorType>(Val: DstTy)) ||
2811 (isa<llvm::ScalableVectorType>(Val: SrcTy) &&
2812 isa<llvm::FixedVectorType>(Val: DstTy))) {
2813 Address Addr = CGF.CreateDefaultAlignTempAlloca(Ty: SrcTy, Name: "saved-value");
2814 LValue LV = CGF.MakeAddrLValue(Addr, T: E->getType());
2815 CGF.EmitStoreOfScalar(value: Src, lvalue: LV);
2816 Addr = Addr.withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy));
2817 LValue DestLV = CGF.MakeAddrLValue(Addr, T: DestTy);
2818 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2819 return EmitLoadOfLValue(LV: DestLV, Loc: CE->getExprLoc());
2820 }
2821
2822 llvm::Value *Result = Builder.CreateBitCast(V: Src, DestTy: DstTy);
2823 return CGF.authPointerToPointerCast(ResultPtr: Result, SourceType: E->getType(), DestType: DestTy);
2824 }
2825 case CK_AddressSpaceConversion: {
2826 llvm::Type *DestLTy = ConvertType(T: DestTy);
2827 // WebAssembly reference types are opaque target extension types so an
2828 // "address space conversion" involving them is not a real pointer cast.
2829 auto IsWasmFuncref = [](llvm::Type *T) {
2830 auto *TET = dyn_cast<llvm::TargetExtType>(Val: T);
2831 return TET && TET->getName() == "wasm.funcref";
2832 };
2833 bool SrcIsFuncref = IsWasmFuncref(ConvertType(T: E->getType()));
2834 bool DestIsFuncref = IsWasmFuncref(DestLTy);
2835 if (SrcIsFuncref && DestIsFuncref) {
2836 // funcref -> funcref (e.g. between differently-typed funcrefs) is the
2837 // identity on the opaque reference value.
2838 return Visit(E);
2839 }
2840 if (SrcIsFuncref && !DestIsFuncref) {
2841 // funcref -> pointer: use wasm_funcref_to_ptr. This will probably crash
2842 // later in codegen since we haven't implemented a way to actually get a
2843 // function pointer from a funcref.
2844 llvm::Function *ToPtr =
2845 CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::wasm_funcref_to_ptr);
2846 return CGF.Builder.CreateCall(Callee: ToPtr, Args: {Visit(E)});
2847 }
2848 if (!SrcIsFuncref && DestIsFuncref) {
2849 // A null function pointer converts to a null funcref (ref.null func),
2850 // rather than a table lookup at index 0.
2851 Expr::EvalResult NullResult;
2852 if (E->EvaluateAsRValue(Result&: NullResult, Ctx: CGF.getContext()) &&
2853 NullResult.Val.isNullPointer()) {
2854 if (NullResult.HasSideEffects)
2855 Visit(E);
2856 return llvm::Constant::getNullValue(Ty: DestLTy);
2857 }
2858 // pointer -> funcref: do a table.get from the indirect function table.
2859 llvm::Function *ToFuncref =
2860 CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::wasm_ptr_to_funcref);
2861 return CGF.Builder.CreateCall(Callee: ToFuncref, Args: {Visit(E)});
2862 }
2863 Expr::EvalResult Result;
2864 if (E->EvaluateAsRValue(Result, Ctx: CGF.getContext()) &&
2865 Result.Val.isNullPointer()) {
2866 // If E has side effect, it is emitted even if its final result is a
2867 // null pointer. In that case, a DCE pass should be able to
2868 // eliminate the useless instructions emitted during translating E.
2869 if (Result.HasSideEffects)
2870 Visit(E);
2871 return CGF.CGM.getNullPointer(T: cast<llvm::PointerType>(Val: DestLTy), QT: DestTy);
2872 }
2873 // Since target may map different address spaces in AST to the same address
2874 // space, an address space conversion may end up as a bitcast.
2875 return CGF.performAddrSpaceCast(Src: Visit(E), DestTy: DestLTy);
2876 }
2877 case CK_AtomicToNonAtomic:
2878 case CK_NonAtomicToAtomic:
2879 case CK_UserDefinedConversion:
2880 return Visit(E);
2881
2882 case CK_NoOp: {
2883 return CE->changesVolatileQualification() ? EmitLoadOfLValue(E: CE) : Visit(E);
2884 }
2885
2886 case CK_BaseToDerived: {
2887 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2888 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2889
2890 Address Base = CGF.EmitPointerWithAlignment(Addr: E);
2891 Address Derived =
2892 CGF.GetAddressOfDerivedClass(Value: Base, Derived: DerivedClassDecl,
2893 PathBegin: CE->path_begin(), PathEnd: CE->path_end(),
2894 NullCheckValue: CGF.ShouldNullCheckClassCastValue(CE));
2895
2896 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2897 // performed and the object is not of the derived type.
2898 if (CGF.sanitizePerformTypeCheck())
2899 CGF.EmitTypeCheck(TCK: CodeGenFunction::TCK_DowncastPointer, Loc: CE->getExprLoc(),
2900 Addr: Derived, Type: DestTy->getPointeeType());
2901
2902 if (CGF.SanOpts.has(K: SanitizerKind::CFIDerivedCast))
2903 CGF.EmitVTablePtrCheckForCast(T: DestTy->getPointeeType(), Derived,
2904 /*MayBeNull=*/true,
2905 TCK: CodeGenFunction::CFITCK_DerivedCast,
2906 Loc: CE->getBeginLoc());
2907
2908 return CGF.getAsNaturalPointerTo(Addr: Derived, PointeeType: CE->getType()->getPointeeType());
2909 }
2910 case CK_UncheckedDerivedToBase:
2911 case CK_DerivedToBase: {
2912 // The EmitPointerWithAlignment path does this fine; just discard
2913 // the alignment.
2914 return CGF.getAsNaturalPointerTo(Addr: CGF.EmitPointerWithAlignment(Addr: CE),
2915 PointeeType: CE->getType()->getPointeeType());
2916 }
2917
2918 case CK_Dynamic: {
2919 Address V = CGF.EmitPointerWithAlignment(Addr: E);
2920 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(Val: CE);
2921 return CGF.EmitDynamicCast(V, DCE);
2922 }
2923
2924 case CK_ArrayToPointerDecay:
2925 return CGF.getAsNaturalPointerTo(Addr: CGF.EmitArrayToPointerDecay(Array: E),
2926 PointeeType: CE->getType()->getPointeeType());
2927 case CK_FunctionToPointerDecay:
2928 return EmitLValue(E).getPointer(CGF);
2929
2930 case CK_NullToPointer:
2931 if (MustVisitNullValue(E))
2932 CGF.EmitIgnoredExpr(E);
2933
2934 return CGF.CGM.getNullPointer(T: cast<llvm::PointerType>(Val: ConvertType(T: DestTy)),
2935 QT: DestTy);
2936
2937 case CK_NullToMemberPointer: {
2938 if (MustVisitNullValue(E))
2939 CGF.EmitIgnoredExpr(E);
2940
2941 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2942 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2943 }
2944
2945 case CK_ReinterpretMemberPointer:
2946 case CK_BaseToDerivedMemberPointer:
2947 case CK_DerivedToBaseMemberPointer: {
2948 Value *Src = Visit(E);
2949
2950 // Note that the AST doesn't distinguish between checked and
2951 // unchecked member pointer conversions, so we always have to
2952 // implement checked conversions here. This is inefficient when
2953 // actual control flow may be required in order to perform the
2954 // check, which it is for data member pointers (but not member
2955 // function pointers on Itanium and ARM).
2956 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, E: CE, Src);
2957 }
2958
2959 case CK_ARCProduceObject:
2960 return CGF.EmitARCRetainScalarExpr(expr: E);
2961 case CK_ARCConsumeObject:
2962 return CGF.EmitObjCConsumeObject(T: E->getType(), Ptr: Visit(E));
2963 case CK_ARCReclaimReturnedObject:
2964 return CGF.EmitARCReclaimReturnedObject(e: E, /*allowUnsafe*/ allowUnsafeClaim: Ignored);
2965 case CK_ARCExtendBlockObject:
2966 return CGF.EmitARCExtendBlockObject(expr: E);
2967
2968 case CK_CopyAndAutoreleaseBlockObject:
2969 return CGF.EmitBlockCopyAndAutorelease(Block: Visit(E), Ty: E->getType());
2970
2971 case CK_FloatingRealToComplex:
2972 case CK_FloatingComplexCast:
2973 case CK_IntegralRealToComplex:
2974 case CK_IntegralComplexCast:
2975 case CK_IntegralComplexToFloatingComplex:
2976 case CK_FloatingComplexToIntegralComplex:
2977 case CK_ConstructorConversion:
2978 case CK_ToUnion:
2979 case CK_HLSLArrayRValue:
2980 llvm_unreachable("scalar cast to non-scalar value");
2981
2982 case CK_LValueToRValue:
2983 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
2984 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
2985 return Visit(E);
2986
2987 case CK_IntegralToPointer: {
2988 Value *Src = Visit(E);
2989
2990 // First, convert to the correct width so that we control the kind of
2991 // extension.
2992 auto DestLLVMTy = ConvertType(T: DestTy);
2993 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
2994 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
2995 llvm::Value* IntResult =
2996 Builder.CreateIntCast(V: Src, DestTy: MiddleTy, isSigned: InputSigned, Name: "conv");
2997
2998 auto *IntToPtr = Builder.CreateIntToPtr(V: IntResult, DestTy: DestLLVMTy);
2999
3000 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
3001 // Going from integer to pointer that could be dynamic requires reloading
3002 // dynamic information from invariant.group.
3003 if (DestTy.mayBeDynamicClass())
3004 IntToPtr = Builder.CreateLaunderInvariantGroup(Ptr: IntToPtr);
3005 }
3006
3007 IntToPtr = CGF.authPointerToPointerCast(ResultPtr: IntToPtr, SourceType: E->getType(), DestType: DestTy);
3008 return IntToPtr;
3009 }
3010 case CK_PointerToIntegral: {
3011 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
3012 auto *PtrExpr =
3013 CGF.authPointerToPointerCast(ResultPtr: Visit(E), SourceType: E->getType(), DestType: DestTy);
3014 return Builder.CreatePtrToInt(V: PtrExpr, DestTy: ConvertType(T: DestTy));
3015 }
3016 case CK_ToVoid: {
3017 CGF.EmitIgnoredExpr(E);
3018 return nullptr;
3019 }
3020 case CK_MatrixCast: {
3021 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3022 Loc: CE->getExprLoc());
3023 }
3024 // CK_HLSLAggregateSplatCast only handles splatting to vectors from a vec1
3025 // Casts were inserted in Sema to Cast the Src Expr to a Scalar and
3026 // To perform any necessary Scalar Cast, so this Cast can be handled
3027 // by the regular Vector Splat cast code.
3028 case CK_HLSLAggregateSplatCast:
3029 case CK_VectorSplat: {
3030 llvm::Type *DstTy = ConvertType(T: DestTy);
3031 Value *Elt = Visit(E);
3032 // Splat the element across to all elements
3033 llvm::ElementCount NumElements =
3034 cast<llvm::VectorType>(Val: DstTy)->getElementCount();
3035 return Builder.CreateVectorSplat(EC: NumElements, V: Elt, Name: "splat");
3036 }
3037
3038 case CK_FixedPointCast:
3039 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3040 Loc: CE->getExprLoc());
3041
3042 case CK_FixedPointToBoolean:
3043 assert(E->getType()->isFixedPointType() &&
3044 "Expected src type to be fixed point type");
3045 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
3046 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3047 Loc: CE->getExprLoc());
3048
3049 case CK_FixedPointToIntegral:
3050 assert(E->getType()->isFixedPointType() &&
3051 "Expected src type to be fixed point type");
3052 assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
3053 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3054 Loc: CE->getExprLoc());
3055
3056 case CK_IntegralToFixedPoint:
3057 assert(E->getType()->isIntegerType() &&
3058 "Expected src type to be an integer");
3059 assert(DestTy->isFixedPointType() &&
3060 "Expected dest type to be fixed point type");
3061 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3062 Loc: CE->getExprLoc());
3063
3064 case CK_IntegralCast: {
3065 if (E->getType()->isExtVectorType() && DestTy->isExtVectorType()) {
3066 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
3067 return Builder.CreateIntCast(V: Visit(E), DestTy: ConvertType(T: DestTy),
3068 isSigned: SrcElTy->isSignedIntegerOrEnumerationType(),
3069 Name: "conv");
3070 }
3071 ScalarConversionOpts Opts;
3072 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: CE)) {
3073 if (!ICE->isPartOfExplicitCast())
3074 Opts = ScalarConversionOpts(CGF.SanOpts);
3075 }
3076 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3077 Loc: CE->getExprLoc(), Opts);
3078 }
3079 case CK_IntegralToFloating: {
3080 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
3081 // TODO: Support constrained FP intrinsics.
3082 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
3083 if (SrcElTy->isSignedIntegerOrEnumerationType())
3084 return Builder.CreateSIToFP(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3085 return Builder.CreateUIToFP(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3086 }
3087 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3088 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3089 Loc: CE->getExprLoc());
3090 }
3091 case CK_FloatingToIntegral: {
3092 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
3093 // TODO: Support constrained FP intrinsics.
3094 QualType DstElTy = DestTy->castAs<VectorType>()->getElementType();
3095 if (DstElTy->isSignedIntegerOrEnumerationType())
3096 return Builder.CreateFPToSI(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3097 return Builder.CreateFPToUI(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3098 }
3099 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3100 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3101 Loc: CE->getExprLoc());
3102 }
3103 case CK_FloatingCast: {
3104 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
3105 // TODO: Support constrained FP intrinsics.
3106 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
3107 QualType DstElTy = DestTy->castAs<VectorType>()->getElementType();
3108 if (DstElTy->castAs<BuiltinType>()->getKind() <
3109 SrcElTy->castAs<BuiltinType>()->getKind())
3110 return Builder.CreateFPTrunc(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3111 return Builder.CreateFPExt(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3112 }
3113 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3114 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3115 Loc: CE->getExprLoc());
3116 }
3117 case CK_FixedPointToFloating:
3118 case CK_FloatingToFixedPoint: {
3119 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3120 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3121 Loc: CE->getExprLoc());
3122 }
3123 case CK_BooleanToSignedIntegral: {
3124 ScalarConversionOpts Opts;
3125 Opts.TreatBooleanAsSigned = true;
3126 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3127 Loc: CE->getExprLoc(), Opts);
3128 }
3129 case CK_IntegralToBoolean:
3130 return EmitIntToBoolConversion(V: Visit(E));
3131 case CK_PointerToBoolean:
3132 return EmitPointerToBoolConversion(V: Visit(E), QT: E->getType());
3133 case CK_FloatingToBoolean: {
3134 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3135 return EmitFloatToBoolConversion(V: Visit(E));
3136 }
3137 case CK_MemberPointerToBoolean: {
3138 llvm::Value *MemPtr = Visit(E);
3139 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
3140 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
3141 }
3142
3143 case CK_FloatingComplexToReal:
3144 case CK_IntegralComplexToReal:
3145 return CGF.EmitComplexExpr(E, IgnoreReal: false, IgnoreImag: true).first;
3146
3147 case CK_FloatingComplexToBoolean:
3148 case CK_IntegralComplexToBoolean: {
3149 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
3150
3151 // TODO: kill this function off, inline appropriate case here
3152 return EmitComplexToScalarConversion(Src: V, SrcTy: E->getType(), DstTy: DestTy,
3153 Loc: CE->getExprLoc());
3154 }
3155
3156 case CK_ZeroToOCLOpaqueType: {
3157 assert((DestTy->isEventT() || DestTy->isQueueT() ||
3158 DestTy->isOCLIntelSubgroupAVCType()) &&
3159 "CK_ZeroToOCLEvent cast on non-event type");
3160 return llvm::Constant::getNullValue(Ty: ConvertType(T: DestTy));
3161 }
3162
3163 case CK_IntToOCLSampler:
3164 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
3165
3166 case CK_HLSLVectorTruncation: {
3167 assert((DestTy->isVectorType() || DestTy->isBuiltinType()) &&
3168 "Destination type must be a vector or builtin type.");
3169 Value *Vec = Visit(E);
3170 if (auto *VecTy = DestTy->getAs<VectorType>()) {
3171 SmallVector<int> Mask;
3172 unsigned NumElts = VecTy->getNumElements();
3173 for (unsigned I = 0; I != NumElts; ++I)
3174 Mask.push_back(Elt: I);
3175
3176 return Builder.CreateShuffleVector(V: Vec, Mask, Name: "trunc");
3177 }
3178 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: CGF.SizeTy);
3179 return Builder.CreateExtractElement(Vec, Idx: Zero, Name: "cast.vtrunc");
3180 }
3181 case CK_HLSLMatrixTruncation: {
3182 assert((DestTy->isMatrixType() || DestTy->isBuiltinType()) &&
3183 "Destination type must be a matrix or builtin type.");
3184 Value *Mat = Visit(E);
3185 if (auto *MatTy = DestTy->getAs<ConstantMatrixType>()) {
3186 SmallVector<int> Mask(MatTy->getNumElementsFlattened());
3187 unsigned NumCols = MatTy->getNumColumns();
3188 unsigned NumRows = MatTy->getNumRows();
3189 auto *SrcMatTy = E->getType()->getAs<ConstantMatrixType>();
3190 assert(SrcMatTy && "Source type must be a matrix type.");
3191 assert(NumRows <= SrcMatTy->getNumRows());
3192 assert(NumCols <= SrcMatTy->getNumColumns());
3193
3194 for (unsigned R = 0; R < NumRows; R++)
3195 for (unsigned C = 0; C < NumCols; C++)
3196 Mask[MatTy->getColumnMajorFlattenedIndex(Row: R, Column: C)] =
3197 SrcMatTy->getColumnMajorFlattenedIndex(Row: R, Column: C);
3198
3199 return Builder.CreateShuffleVector(V: Mat, Mask, Name: "trunc");
3200 }
3201 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: CGF.SizeTy);
3202 return Builder.CreateExtractElement(Vec: Mat, Idx: Zero, Name: "cast.mtrunc");
3203 }
3204 case CK_HLSLElementwiseCast: {
3205 RValue RV = CGF.EmitAnyExpr(E);
3206 SourceLocation Loc = CE->getExprLoc();
3207
3208 if (const auto *SrcMatTy = E->getType()->getAs<ConstantMatrixType>()) {
3209 assert(DestTy->isVectorType() &&
3210 "Matrix elementwise cast destination must be a vector");
3211 assert(RV.isScalar() && "Matrix rvalue must have scalar representation");
3212 Value *SrcVal = RV.getScalarVal();
3213 return EmitHLSLElementwiseCastToVector(
3214 CGF, DestTy, NumSrcElements: SrcMatTy->getNumElementsFlattened(),
3215 GetElement: [&](unsigned I) {
3216 unsigned Row = I / SrcMatTy->getNumColumns();
3217 unsigned Col = I % SrcMatTy->getNumColumns();
3218 unsigned Idx = SrcMatTy->getColumnMajorFlattenedIndex(Row, Column: Col);
3219 Value *Element =
3220 Builder.CreateExtractElement(Vec: SrcVal, Idx, Name: "matrixext");
3221 return std::pair(Element, SrcMatTy->getElementType());
3222 },
3223 Loc);
3224 }
3225
3226 Address SrcAddr = Address::invalid();
3227
3228 if (RV.isAggregate()) {
3229 SrcAddr = RV.getAggregateAddress();
3230 } else {
3231 SrcAddr = CGF.CreateMemTemp(T: E->getType(), Name: "hlsl.ewcast.src");
3232 LValue TmpLV = CGF.MakeAddrLValue(Addr: SrcAddr, T: E->getType());
3233 CGF.EmitStoreThroughLValue(Src: RV, Dst: TmpLV);
3234 }
3235
3236 LValue SrcVal = CGF.MakeAddrLValue(Addr: SrcAddr, T: E->getType());
3237 return EmitHLSLElementwiseCast(CGF, SrcVal, DestTy, Loc);
3238 }
3239
3240 } // end of switch
3241
3242 llvm_unreachable("unknown scalar cast");
3243}
3244
3245Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
3246 CodeGenFunction::StmtExprEvaluation eval(CGF);
3247 Address RetAlloca = CGF.EmitCompoundStmt(S: *E->getSubStmt(),
3248 GetLast: !E->getType()->isVoidType());
3249 if (!RetAlloca.isValid())
3250 return nullptr;
3251 return CGF.EmitLoadOfScalar(lvalue: CGF.MakeAddrLValue(Addr: RetAlloca, T: E->getType()),
3252 Loc: E->getExprLoc());
3253}
3254
3255Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
3256 CodeGenFunction::RunCleanupsScope Scope(CGF);
3257 Value *V = Visit(E: E->getSubExpr());
3258 // Defend against dominance problems caused by jumps out of expression
3259 // evaluation through the shared cleanup block.
3260 Scope.ForceCleanup(ValuesToReload: {&V});
3261 return V;
3262}
3263
3264//===----------------------------------------------------------------------===//
3265// Unary Operators
3266//===----------------------------------------------------------------------===//
3267
3268static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
3269 llvm::Value *InVal, bool IsInc,
3270 FPOptions FPFeatures) {
3271 BinOpInfo BinOp;
3272 BinOp.LHS = InVal;
3273 BinOp.RHS = llvm::ConstantInt::get(Ty: InVal->getType(), V: 1, IsSigned: false);
3274 BinOp.Ty = E->getType();
3275 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
3276 BinOp.FPFeatures = FPFeatures;
3277 BinOp.E = E;
3278 return BinOp;
3279}
3280
3281llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
3282 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
3283 // Treat positive amount as unsigned to support inc of i1 (needed for
3284 // unsigned _BitInt(1)).
3285 llvm::Value *Amount =
3286 llvm::ConstantInt::get(Ty: InVal->getType(), V: IsInc ? 1 : -1, IsSigned: !IsInc);
3287 StringRef Name = IsInc ? "inc" : "dec";
3288 QualType Ty = E->getType();
3289 const bool isSigned = Ty->isSignedIntegerOrEnumerationType();
3290 const bool hasSan =
3291 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
3292 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
3293
3294 switch (getOverflowBehaviorConsideringType(CGF, Ty)) {
3295 case LangOptions::OB_Wrap:
3296 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3297 case LangOptions::OB_SignedAndDefined:
3298 if (!hasSan)
3299 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3300 [[fallthrough]];
3301 case LangOptions::OB_Unset:
3302 if (!E->canOverflow())
3303 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3304 if (!hasSan)
3305 return isSigned ? Builder.CreateNSWAdd(LHS: InVal, RHS: Amount, Name)
3306 : Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3307 [[fallthrough]];
3308 case LangOptions::OB_Trap:
3309 if (!Ty->getAs<OverflowBehaviorType>() && !E->canOverflow())
3310 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3311 BinOpInfo Info = createBinOpInfoFromIncDec(
3312 E, InVal, IsInc, FPFeatures: E->getFPFeaturesInEffect(LO: CGF.getLangOpts()));
3313 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: Info))
3314 return isSigned ? Builder.CreateNSWAdd(LHS: InVal, RHS: Amount, Name)
3315 : Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3316 return EmitOverflowCheckedBinOp(Ops: Info);
3317 }
3318 llvm_unreachable("Unknown OverflowBehaviorKind");
3319}
3320
3321namespace {
3322/// Handles check and update for lastprivate conditional variables.
3323class OMPLastprivateConditionalUpdateRAII {
3324private:
3325 CodeGenFunction &CGF;
3326 const UnaryOperator *E;
3327
3328public:
3329 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
3330 const UnaryOperator *E)
3331 : CGF(CGF), E(E) {}
3332 ~OMPLastprivateConditionalUpdateRAII() {
3333 if (CGF.getLangOpts().OpenMP)
3334 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
3335 CGF, LHS: E->getSubExpr());
3336 }
3337};
3338} // namespace
3339
3340llvm::Value *
3341ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3342 bool isInc, bool isPre) {
3343 ApplyAtomGroup Grp(CGF.getDebugInfo());
3344 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
3345 QualType type = E->getSubExpr()->getType();
3346 llvm::PHINode *atomicPHI = nullptr;
3347 llvm::Value *value;
3348 llvm::Value *input;
3349 llvm::Value *Previous = nullptr;
3350 QualType SrcType = E->getType();
3351
3352 int amount = (isInc ? 1 : -1);
3353 bool isSubtraction = !isInc;
3354
3355 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
3356 type = atomicTy->getValueType();
3357 if (isInc && type->isBooleanType()) {
3358 llvm::Value *True = CGF.EmitToMemory(Value: Builder.getTrue(), Ty: type);
3359 if (isPre) {
3360 Builder.CreateStore(Val: True, Addr: LV.getAddress(), IsVolatile: LV.isVolatileQualified())
3361 ->setAtomic(Ordering: llvm::AtomicOrdering::SequentiallyConsistent);
3362 return Builder.getTrue();
3363 }
3364 // For atomic bool increment, we just store true and return it for
3365 // preincrement, do an atomic swap with true for postincrement
3366 return Builder.CreateAtomicRMW(
3367 Op: llvm::AtomicRMWInst::Xchg, Addr: LV.getAddress(), Val: True,
3368 Ordering: llvm::AtomicOrdering::SequentiallyConsistent);
3369 }
3370 // Special case for atomic increment / decrement on integers, emit
3371 // atomicrmw instructions. We skip this if we want to be doing overflow
3372 // checking, and fall into the slow path with the atomic cmpxchg loop.
3373 if (!type->isBooleanType() && type->isIntegerType() &&
3374 !(type->isUnsignedIntegerType() &&
3375 CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) &&
3376 CGF.getLangOpts().getSignedOverflowBehavior() !=
3377 LangOptions::SOB_Trapping) {
3378 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
3379 llvm::AtomicRMWInst::Sub;
3380 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
3381 llvm::Instruction::Sub;
3382 llvm::Value *amt = CGF.EmitToMemory(
3383 Value: llvm::ConstantInt::get(Ty: ConvertType(T: type), V: 1, IsSigned: true), Ty: type);
3384 llvm::Value *old =
3385 Builder.CreateAtomicRMW(Op: aop, Addr: LV.getAddress(), Val: amt,
3386 Ordering: llvm::AtomicOrdering::SequentiallyConsistent);
3387 return isPre ? Builder.CreateBinOp(Opc: op, LHS: old, RHS: amt) : old;
3388 }
3389 // Special case for atomic increment/decrement on floats.
3390 // Bail out non-power-of-2-sized floating point types (e.g., x86_fp80).
3391 if (type->isFloatingType()) {
3392 llvm::Type *Ty = ConvertType(T: type);
3393 if (llvm::has_single_bit(Value: Ty->getScalarSizeInBits())) {
3394 llvm::AtomicRMWInst::BinOp aop =
3395 isInc ? llvm::AtomicRMWInst::FAdd : llvm::AtomicRMWInst::FSub;
3396 llvm::Instruction::BinaryOps op =
3397 isInc ? llvm::Instruction::FAdd : llvm::Instruction::FSub;
3398 llvm::Value *amt = llvm::ConstantFP::get(Ty, V: 1.0);
3399 llvm::AtomicRMWInst *old =
3400 CGF.emitAtomicRMWInst(Op: aop, Addr: LV.getAddress(), Val: amt,
3401 Order: llvm::AtomicOrdering::SequentiallyConsistent);
3402
3403 return isPre ? Builder.CreateBinOp(Opc: op, LHS: old, RHS: amt) : old;
3404 }
3405 }
3406 value = EmitLoadOfLValue(LV, Loc: E->getExprLoc());
3407 input = value;
3408 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
3409 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3410 llvm::BasicBlock *opBB = CGF.createBasicBlock(name: "atomic_op", parent: CGF.CurFn);
3411 value = CGF.EmitToMemory(Value: value, Ty: type);
3412 Builder.CreateBr(Dest: opBB);
3413 Builder.SetInsertPoint(opBB);
3414 atomicPHI = Builder.CreatePHI(Ty: value->getType(), NumReservedValues: 2);
3415 atomicPHI->addIncoming(V: value, BB: startBB);
3416 value = atomicPHI;
3417 } else {
3418 value = EmitLoadOfLValue(LV, Loc: E->getExprLoc());
3419 input = value;
3420 }
3421
3422 // Special case of integer increment that we have to check first: bool++.
3423 // Due to promotion rules, we get:
3424 // bool++ -> bool = bool + 1
3425 // -> bool = (int)bool + 1
3426 // -> bool = ((int)bool + 1 != 0)
3427 // An interesting aspect of this is that increment is always true.
3428 // Decrement does not have this property.
3429 if (isInc && type->isBooleanType()) {
3430 value = Builder.getTrue();
3431
3432 // Most common case by far: integer increment.
3433 } else if (type->isIntegerType()) {
3434 QualType promotedType;
3435 bool canPerformLossyDemotionCheck = false;
3436
3437 if (CGF.getContext().isPromotableIntegerType(T: type)) {
3438 promotedType = CGF.getContext().getPromotedIntegerType(PromotableType: type);
3439 assert(promotedType != type && "Shouldn't promote to the same type.");
3440 canPerformLossyDemotionCheck = true;
3441 canPerformLossyDemotionCheck &=
3442 CGF.getContext().getCanonicalType(T: type) !=
3443 CGF.getContext().getCanonicalType(T: promotedType);
3444 canPerformLossyDemotionCheck &=
3445 PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
3446 SrcType: type, DstType: promotedType);
3447 assert((!canPerformLossyDemotionCheck ||
3448 type->isSignedIntegerOrEnumerationType() ||
3449 promotedType->isSignedIntegerOrEnumerationType() ||
3450 ConvertType(type)->getScalarSizeInBits() ==
3451 ConvertType(promotedType)->getScalarSizeInBits()) &&
3452 "The following check expects that if we do promotion to different "
3453 "underlying canonical type, at least one of the types (either "
3454 "base or promoted) will be signed, or the bitwidths will match.");
3455 }
3456 if (CGF.SanOpts.hasOneOf(
3457 K: SanitizerKind::ImplicitIntegerArithmeticValueChange |
3458 SanitizerKind::ImplicitBitfieldConversion) &&
3459 canPerformLossyDemotionCheck) {
3460 // While `x += 1` (for `x` with width less than int) is modeled as
3461 // promotion+arithmetics+demotion, and we can catch lossy demotion with
3462 // ease; inc/dec with width less than int can't overflow because of
3463 // promotion rules, so we omit promotion+demotion, which means that we can
3464 // not catch lossy "demotion". Because we still want to catch these cases
3465 // when the sanitizer is enabled, we perform the promotion, then perform
3466 // the increment/decrement in the wider type, and finally
3467 // perform the demotion. This will catch lossy demotions.
3468
3469 // We have a special case for bitfields defined using all the bits of the
3470 // type. In this case we need to do the same trick as for the integer
3471 // sanitizer checks, i.e., promotion -> increment/decrement -> demotion.
3472
3473 value = EmitScalarConversion(Src: value, SrcType: type, DstType: promotedType, Loc: E->getExprLoc());
3474 Value *amt = llvm::ConstantInt::get(Ty: value->getType(), V: amount, IsSigned: true);
3475 value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec");
3476 // Do pass non-default ScalarConversionOpts so that sanitizer check is
3477 // emitted if LV is not a bitfield, otherwise the bitfield sanitizer
3478 // checks will take care of the conversion.
3479 ScalarConversionOpts Opts;
3480 if (!LV.isBitField())
3481 Opts = ScalarConversionOpts(CGF.SanOpts);
3482 else if (CGF.SanOpts.has(K: SanitizerKind::ImplicitBitfieldConversion)) {
3483 Previous = value;
3484 SrcType = promotedType;
3485 }
3486
3487 Opts.PatternExcluded = CGF.getContext().isUnaryOverflowPatternExcluded(UO: E);
3488 value = EmitScalarConversion(Src: value, SrcType: promotedType, DstType: type, Loc: E->getExprLoc(),
3489 Opts);
3490
3491 // Note that signed integer inc/dec with width less than int can't
3492 // overflow because of promotion rules; we're just eliding a few steps
3493 // here.
3494 } else if (type->isSignedIntegerOrEnumerationType() ||
3495 type->isUnsignedIntegerType()) {
3496 value = EmitIncDecConsiderOverflowBehavior(E, InVal: value, IsInc: isInc);
3497 } else {
3498 // Treat positive amount as unsigned to support inc of i1 (needed for
3499 // unsigned _BitInt(1)).
3500 llvm::Value *amt =
3501 llvm::ConstantInt::get(Ty: value->getType(), V: amount, IsSigned: !isInc);
3502 value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec");
3503 }
3504
3505 // Next most common: pointer increment.
3506 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
3507 QualType type = ptr->getPointeeType();
3508
3509 // VLA types don't have constant size.
3510 if (const VariableArrayType *vla
3511 = CGF.getContext().getAsVariableArrayType(T: type)) {
3512 llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
3513 if (!isInc) numElts = Builder.CreateNSWNeg(V: numElts, Name: "vla.negsize");
3514 llvm::Type *elemTy = CGF.ConvertTypeForMem(T: vla->getElementType());
3515 if (CGF.getLangOpts().PointerOverflowDefined)
3516 value = Builder.CreateGEP(Ty: elemTy, Ptr: value, IdxList: numElts, Name: "vla.inc");
3517 else
3518 value = CGF.EmitCheckedInBoundsGEP(
3519 ElemTy: elemTy, Ptr: value, IdxList: numElts, /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3520 Loc: E->getExprLoc(), Name: "vla.inc");
3521
3522 // Arithmetic on function pointers (!) is just +-1.
3523 } else if (type->isFunctionType()) {
3524 llvm::Value *amt = Builder.getInt32(C: amount);
3525
3526 if (CGF.getLangOpts().PointerOverflowDefined)
3527 value = Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: value, IdxList: amt, Name: "incdec.funcptr");
3528 else
3529 value =
3530 CGF.EmitCheckedInBoundsGEP(ElemTy: CGF.Int8Ty, Ptr: value, IdxList: amt,
3531 /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3532 Loc: E->getExprLoc(), Name: "incdec.funcptr");
3533
3534 // For everything else, we can just do a simple increment.
3535 } else {
3536 llvm::Value *amt = Builder.getInt32(C: amount);
3537 llvm::Type *elemTy = CGF.ConvertTypeForMem(T: type);
3538 if (CGF.getLangOpts().PointerOverflowDefined)
3539 value = Builder.CreateGEP(Ty: elemTy, Ptr: value, IdxList: amt, Name: "incdec.ptr");
3540 else
3541 value = CGF.EmitCheckedInBoundsGEP(
3542 ElemTy: elemTy, Ptr: value, IdxList: amt, /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3543 Loc: E->getExprLoc(), Name: "incdec.ptr");
3544 }
3545
3546 // Vector increment/decrement.
3547 } else if (type->isVectorType()) {
3548 if (type->hasIntegerRepresentation()) {
3549 llvm::Value *amt = llvm::ConstantInt::getSigned(Ty: value->getType(), V: amount);
3550
3551 value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec");
3552 } else {
3553 value = Builder.CreateFAdd(
3554 L: value,
3555 R: llvm::ConstantFP::get(Ty: value->getType(), V: amount),
3556 Name: isInc ? "inc" : "dec");
3557 }
3558
3559 // Floating point.
3560 } else if (type->isRealFloatingType()) {
3561 // Add the inc/dec to the real part.
3562 llvm::Value *amt;
3563 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
3564
3565 // Another special case: half FP increment should be done via float.
3566 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType)
3567 value = Builder.CreateFPExt(V: value, DestTy: CGF.CGM.FloatTy, Name: "incdec.conv");
3568
3569 if (value->getType()->isFloatTy())
3570 amt = llvm::ConstantFP::get(Context&: VMContext,
3571 V: llvm::APFloat(static_cast<float>(amount)));
3572 else if (value->getType()->isDoubleTy())
3573 amt = llvm::ConstantFP::get(Context&: VMContext,
3574 V: llvm::APFloat(static_cast<double>(amount)));
3575 else {
3576 // Remaining types are Half, Bfloat16, LongDouble, __ibm128 or __float128.
3577 // Convert from float.
3578 llvm::APFloat F(static_cast<float>(amount));
3579 bool ignored;
3580 const llvm::fltSemantics *FS;
3581 // Don't use getFloatTypeSemantics because Half isn't
3582 // necessarily represented using the "half" LLVM type.
3583 if (value->getType()->isFP128Ty())
3584 FS = &CGF.getTarget().getFloat128Format();
3585 else if (value->getType()->isHalfTy())
3586 FS = &CGF.getTarget().getHalfFormat();
3587 else if (value->getType()->isBFloatTy())
3588 FS = &CGF.getTarget().getBFloat16Format();
3589 else if (value->getType()->isPPC_FP128Ty())
3590 FS = &CGF.getTarget().getIbm128Format();
3591 else
3592 FS = &CGF.getTarget().getLongDoubleFormat();
3593 F.convert(ToSemantics: *FS, RM: llvm::APFloat::rmTowardZero, losesInfo: &ignored);
3594 amt = llvm::ConstantFP::get(Context&: VMContext, V: F);
3595 }
3596 value = Builder.CreateFAdd(L: value, R: amt, Name: isInc ? "inc" : "dec");
3597
3598 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType)
3599 value = Builder.CreateFPTrunc(V: value, DestTy: CGF.CGM.HalfTy, Name: "incdec.conv");
3600
3601 // Fixed-point types.
3602 } else if (type->isFixedPointType()) {
3603 // Fixed-point types are tricky. In some cases, it isn't possible to
3604 // represent a 1 or a -1 in the type at all. Piggyback off of
3605 // EmitFixedPointBinOp to avoid having to reimplement saturation.
3606 BinOpInfo Info;
3607 Info.E = E;
3608 Info.Ty = E->getType();
3609 Info.Opcode = isInc ? BO_Add : BO_Sub;
3610 Info.LHS = value;
3611 Info.RHS = llvm::ConstantInt::get(Ty: value->getType(), V: 1, IsSigned: false);
3612 // If the type is signed, it's better to represent this as +(-1) or -(-1),
3613 // since -1 is guaranteed to be representable.
3614 if (type->isSignedFixedPointType()) {
3615 Info.Opcode = isInc ? BO_Sub : BO_Add;
3616 Info.RHS = Builder.CreateNeg(V: Info.RHS);
3617 }
3618 // Now, convert from our invented integer literal to the type of the unary
3619 // op. This will upscale and saturate if necessary. This value can become
3620 // undef in some cases.
3621 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
3622 auto DstSema = CGF.getContext().getFixedPointSemantics(Ty: Info.Ty);
3623 Info.RHS = FPBuilder.CreateIntegerToFixed(Src: Info.RHS, SrcIsSigned: true, DstSema);
3624 value = EmitFixedPointBinOp(Ops: Info);
3625
3626 // Objective-C pointer types.
3627 } else {
3628 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
3629
3630 CharUnits size = CGF.getContext().getTypeSizeInChars(T: OPT->getObjectType());
3631 if (!isInc) size = -size;
3632 llvm::Value *sizeValue =
3633 llvm::ConstantInt::getSigned(Ty: CGF.SizeTy, V: size.getQuantity());
3634
3635 if (CGF.getLangOpts().PointerOverflowDefined)
3636 value = Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: value, IdxList: sizeValue, Name: "incdec.objptr");
3637 else
3638 value = CGF.EmitCheckedInBoundsGEP(
3639 ElemTy: CGF.Int8Ty, Ptr: value, IdxList: sizeValue, /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3640 Loc: E->getExprLoc(), Name: "incdec.objptr");
3641 value = Builder.CreateBitCast(V: value, DestTy: input->getType());
3642 }
3643
3644 if (atomicPHI) {
3645 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
3646 llvm::BasicBlock *contBB = CGF.createBasicBlock(name: "atomic_cont", parent: CGF.CurFn);
3647 auto Pair = CGF.EmitAtomicCompareExchange(
3648 Obj: LV, Expected: RValue::get(V: atomicPHI), Desired: RValue::get(V: value), Loc: E->getExprLoc());
3649 llvm::Value *old = CGF.EmitToMemory(Value: Pair.first.getScalarVal(), Ty: type);
3650 llvm::Value *success = Pair.second;
3651 atomicPHI->addIncoming(V: old, BB: curBlock);
3652 Builder.CreateCondBr(Cond: success, True: contBB, False: atomicPHI->getParent());
3653 Builder.SetInsertPoint(contBB);
3654 return isPre ? value : input;
3655 }
3656
3657 // Store the updated result through the lvalue.
3658 if (LV.isBitField()) {
3659 Value *Src = Previous ? Previous : value;
3660 CGF.EmitStoreThroughBitfieldLValue(Src: RValue::get(V: value), Dst: LV, Result: &value);
3661 CGF.EmitBitfieldConversionCheck(Src, SrcType, Dst: value, DstType: E->getType(),
3662 Info: LV.getBitFieldInfo(), Loc: E->getExprLoc());
3663 } else
3664 CGF.EmitStoreThroughLValue(Src: RValue::get(V: value), Dst: LV);
3665
3666 // If this is a postinc, return the value read from memory, otherwise use the
3667 // updated value.
3668 return isPre ? value : input;
3669}
3670
3671
3672Value *ScalarExprEmitter::VisitUnaryPlus(const UnaryOperator *E,
3673 QualType PromotionType) {
3674 QualType promotionTy = PromotionType.isNull()
3675 ? getPromotionType(Ty: E->getSubExpr()->getType())
3676 : PromotionType;
3677 Value *result = VisitPlus(E, PromotionType: promotionTy);
3678 if (result && !promotionTy.isNull())
3679 result = EmitUnPromotedValue(result, ExprType: E->getType());
3680 return result;
3681}
3682
3683Value *ScalarExprEmitter::VisitPlus(const UnaryOperator *E,
3684 QualType PromotionType) {
3685 // This differs from gcc, though, most likely due to a bug in gcc.
3686 TestAndClearIgnoreResultAssign();
3687 if (!PromotionType.isNull())
3688 return CGF.EmitPromotedScalarExpr(E: E->getSubExpr(), PromotionType);
3689 return Visit(E: E->getSubExpr());
3690}
3691
3692Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E,
3693 QualType PromotionType) {
3694 QualType promotionTy = PromotionType.isNull()
3695 ? getPromotionType(Ty: E->getSubExpr()->getType())
3696 : PromotionType;
3697 Value *result = VisitMinus(E, PromotionType: promotionTy);
3698 if (result && !promotionTy.isNull())
3699 result = EmitUnPromotedValue(result, ExprType: E->getType());
3700 return result;
3701}
3702
3703Value *ScalarExprEmitter::VisitMinus(const UnaryOperator *E,
3704 QualType PromotionType) {
3705 TestAndClearIgnoreResultAssign();
3706 Value *Op;
3707 if (!PromotionType.isNull())
3708 Op = CGF.EmitPromotedScalarExpr(E: E->getSubExpr(), PromotionType);
3709 else
3710 Op = Visit(E: E->getSubExpr());
3711
3712 // Generate a unary FNeg for FP ops.
3713 if (Op->getType()->isFPOrFPVectorTy()) {
3714 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
3715 return Builder.CreateFNeg(V: Op, Name: "fneg");
3716 }
3717
3718 // Emit unary minus with EmitSub so we handle overflow cases etc.
3719 BinOpInfo BinOp;
3720 BinOp.RHS = Op;
3721 BinOp.LHS = llvm::Constant::getNullValue(Ty: BinOp.RHS->getType());
3722 BinOp.Ty = E->getType();
3723 BinOp.Opcode = BO_Sub;
3724 BinOp.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts());
3725 BinOp.E = E;
3726 return EmitSub(Ops: BinOp);
3727}
3728
3729Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
3730 TestAndClearIgnoreResultAssign();
3731 Value *Op = Visit(E: E->getSubExpr());
3732 return Builder.CreateNot(V: Op, Name: "not");
3733}
3734
3735Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
3736 // Perform vector logical not on comparison with zero vector.
3737 if (E->getType()->isVectorType() &&
3738 E->getType()->castAs<VectorType>()->getVectorKind() ==
3739 VectorKind::Generic) {
3740 Value *Oper = Visit(E: E->getSubExpr());
3741 Value *Zero = llvm::Constant::getNullValue(Ty: Oper->getType());
3742 Value *Result;
3743 if (Oper->getType()->isFPOrFPVectorTy()) {
3744 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
3745 CGF, E->getFPFeaturesInEffect(LO: CGF.getLangOpts()));
3746 Result = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_OEQ, LHS: Oper, RHS: Zero, Name: "cmp");
3747 } else
3748 Result = Builder.CreateICmp(P: llvm::CmpInst::ICMP_EQ, LHS: Oper, RHS: Zero, Name: "cmp");
3749 return Builder.CreateSExt(V: Result, DestTy: ConvertType(T: E->getType()), Name: "sext");
3750 }
3751
3752 // Compare operand to zero.
3753 Value *BoolVal = CGF.EvaluateExprAsBool(E: E->getSubExpr());
3754
3755 // Invert value.
3756 // TODO: Could dynamically modify easy computations here. For example, if
3757 // the operand is an icmp ne, turn into icmp eq.
3758 BoolVal = Builder.CreateNot(V: BoolVal, Name: "lnot");
3759
3760 // ZExt result to the expr type.
3761 return Builder.CreateZExt(V: BoolVal, DestTy: ConvertType(T: E->getType()), Name: "lnot.ext");
3762}
3763
3764Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
3765 // Try folding the offsetof to a constant.
3766 Expr::EvalResult EVResult;
3767 if (E->EvaluateAsInt(Result&: EVResult, Ctx: CGF.getContext())) {
3768 llvm::APSInt Value = EVResult.Val.getInt();
3769 return Builder.getInt(AI: Value);
3770 }
3771
3772 // Loop over the components of the offsetof to compute the value.
3773 unsigned n = E->getNumComponents();
3774 llvm::Type* ResultType = ConvertType(T: E->getType());
3775 llvm::Value* Result = llvm::Constant::getNullValue(Ty: ResultType);
3776 QualType CurrentType = E->getTypeSourceInfo()->getType();
3777 for (unsigned i = 0; i != n; ++i) {
3778 OffsetOfNode ON = E->getComponent(Idx: i);
3779 llvm::Value *Offset = nullptr;
3780 switch (ON.getKind()) {
3781 case OffsetOfNode::Array: {
3782 // Compute the index
3783 Expr *IdxExpr = E->getIndexExpr(Idx: ON.getArrayExprIndex());
3784 llvm::Value* Idx = CGF.EmitScalarExpr(E: IdxExpr);
3785 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
3786 Idx = Builder.CreateIntCast(V: Idx, DestTy: ResultType, isSigned: IdxSigned, Name: "conv");
3787
3788 // Save the element type
3789 CurrentType =
3790 CGF.getContext().getAsArrayType(T: CurrentType)->getElementType();
3791
3792 // Compute the element size
3793 llvm::Value* ElemSize = llvm::ConstantInt::get(Ty: ResultType,
3794 V: CGF.getContext().getTypeSizeInChars(T: CurrentType).getQuantity());
3795
3796 // Multiply out to compute the result
3797 Offset = Builder.CreateMul(LHS: Idx, RHS: ElemSize);
3798 break;
3799 }
3800
3801 case OffsetOfNode::Field: {
3802 FieldDecl *MemberDecl = ON.getField();
3803 auto *RD = CurrentType->castAsRecordDecl();
3804 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(D: RD);
3805
3806 // Get the index of the field in its parent.
3807 unsigned FieldIndex = MemberDecl->getFieldIndex();
3808
3809 // Compute the offset to the field
3810 int64_t OffsetInt =
3811 RL.getFieldOffset(FieldNo: FieldIndex) / CGF.getContext().getCharWidth();
3812 Offset = llvm::ConstantInt::get(Ty: ResultType, V: OffsetInt);
3813
3814 // Save the element type.
3815 CurrentType = MemberDecl->getType();
3816 break;
3817 }
3818
3819 case OffsetOfNode::Identifier:
3820 llvm_unreachable("dependent __builtin_offsetof");
3821
3822 case OffsetOfNode::Base: {
3823 if (ON.getBase()->isVirtual()) {
3824 CGF.ErrorUnsupported(S: E, Type: "virtual base in offsetof");
3825 continue;
3826 }
3827
3828 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(
3829 D: CurrentType->castAsCanonical<RecordType>()->getDecl());
3830
3831 // Save the element type.
3832 CurrentType = ON.getBase()->getType();
3833
3834 // Compute the offset to the base.
3835 auto *BaseRD = CurrentType->castAsCXXRecordDecl();
3836 CharUnits OffsetInt = RL.getBaseClassOffset(Base: BaseRD);
3837 Offset = llvm::ConstantInt::get(Ty: ResultType, V: OffsetInt.getQuantity());
3838 break;
3839 }
3840 }
3841 Result = Builder.CreateAdd(LHS: Result, RHS: Offset);
3842 }
3843 return Result;
3844}
3845
3846/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
3847/// argument of the sizeof expression as an integer.
3848Value *
3849ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
3850 const UnaryExprOrTypeTraitExpr *E) {
3851 QualType TypeToSize = E->getTypeOfArgument();
3852 if (auto Kind = E->getKind();
3853 Kind == UETT_SizeOf || Kind == UETT_DataSizeOf || Kind == UETT_CountOf) {
3854 if (const VariableArrayType *VAT =
3855 CGF.getContext().getAsVariableArrayType(T: TypeToSize)) {
3856 // For _Countof, we only want to evaluate if the extent is actually
3857 // variable as opposed to a multi-dimensional array whose extent is
3858 // constant but whose element type is variable.
3859 bool EvaluateExtent = true;
3860 if (Kind == UETT_CountOf && VAT->getElementType()->isArrayType()) {
3861 EvaluateExtent =
3862 !VAT->getSizeExpr()->isIntegerConstantExpr(Ctx: CGF.getContext());
3863 }
3864 if (EvaluateExtent) {
3865 if (E->isArgumentType()) {
3866 // sizeof(type) - make sure to emit the VLA size.
3867 CGF.EmitVariablyModifiedType(Ty: TypeToSize);
3868 } else {
3869 // C99 6.5.3.4p2: If the argument is an expression of type
3870 // VLA, it is evaluated.
3871 CGF.EmitIgnoredExpr(E: E->getArgumentExpr());
3872 }
3873
3874 // For _Countof, we just want to return the size of a single dimension.
3875 if (Kind == UETT_CountOf)
3876 return CGF.getVLAElements1D(vla: VAT).NumElts;
3877
3878 // For sizeof and __datasizeof, we need to scale the number of elements
3879 // by the size of the array element type.
3880 auto VlaSize = CGF.getVLASize(vla: VAT);
3881
3882 // Scale the number of non-VLA elements by the non-VLA element size.
3883 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(T: VlaSize.Type);
3884 if (!eltSize.isOne())
3885 return CGF.Builder.CreateNUWMul(LHS: CGF.CGM.getSize(numChars: eltSize),
3886 RHS: VlaSize.NumElts);
3887 return VlaSize.NumElts;
3888 }
3889 }
3890 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
3891 auto Alignment =
3892 CGF.getContext()
3893 .toCharUnitsFromBits(BitSize: CGF.getContext().getOpenMPDefaultSimdAlign(
3894 T: E->getTypeOfArgument()->getPointeeType()))
3895 .getQuantity();
3896 return llvm::ConstantInt::get(Ty: CGF.SizeTy, V: Alignment);
3897 } else if (E->getKind() == UETT_VectorElements) {
3898 auto *VecTy = cast<llvm::VectorType>(Val: ConvertType(T: E->getTypeOfArgument()));
3899 return Builder.CreateElementCount(Ty: CGF.SizeTy, EC: VecTy->getElementCount());
3900 }
3901
3902 // If this isn't sizeof(vla), the result must be constant; use the constant
3903 // folding logic so we don't have to duplicate it here.
3904 return Builder.getInt(AI: E->EvaluateKnownConstInt(Ctx: CGF.getContext()));
3905}
3906
3907Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E,
3908 QualType PromotionType) {
3909 QualType promotionTy = PromotionType.isNull()
3910 ? getPromotionType(Ty: E->getSubExpr()->getType())
3911 : PromotionType;
3912 Value *result = VisitReal(E, PromotionType: promotionTy);
3913 if (result && !promotionTy.isNull())
3914 result = EmitUnPromotedValue(result, ExprType: E->getType());
3915 return result;
3916}
3917
3918Value *ScalarExprEmitter::VisitReal(const UnaryOperator *E,
3919 QualType PromotionType) {
3920 Expr *Op = E->getSubExpr();
3921 if (Op->getType()->isAnyComplexType()) {
3922 // If it's an l-value, load through the appropriate subobject l-value.
3923 // Note that we have to ask E because Op might be an l-value that
3924 // this won't work for, e.g. an Obj-C property.
3925 if (E->isGLValue()) {
3926 if (!PromotionType.isNull()) {
3927 CodeGenFunction::ComplexPairTy result = CGF.EmitComplexExpr(
3928 E: Op, /*IgnoreReal*/ IgnoreResultAssign, /*IgnoreImag*/ true);
3929 PromotionType = PromotionType->isAnyComplexType()
3930 ? PromotionType
3931 : CGF.getContext().getComplexType(T: PromotionType);
3932 return result.first ? CGF.EmitPromotedValue(result, PromotionType).first
3933 : result.first;
3934 }
3935
3936 return CGF.EmitLoadOfLValue(V: CGF.EmitLValue(E), Loc: E->getExprLoc())
3937 .getScalarVal();
3938 }
3939 // Otherwise, calculate and project.
3940 return CGF.EmitComplexExpr(E: Op, IgnoreReal: false, IgnoreImag: true).first;
3941 }
3942
3943 if (!PromotionType.isNull())
3944 return CGF.EmitPromotedScalarExpr(E: Op, PromotionType);
3945 return Visit(E: Op);
3946}
3947
3948Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E,
3949 QualType PromotionType) {
3950 QualType promotionTy = PromotionType.isNull()
3951 ? getPromotionType(Ty: E->getSubExpr()->getType())
3952 : PromotionType;
3953 Value *result = VisitImag(E, PromotionType: promotionTy);
3954 if (result && !promotionTy.isNull())
3955 result = EmitUnPromotedValue(result, ExprType: E->getType());
3956 return result;
3957}
3958
3959Value *ScalarExprEmitter::VisitImag(const UnaryOperator *E,
3960 QualType PromotionType) {
3961 Expr *Op = E->getSubExpr();
3962 if (Op->getType()->isAnyComplexType()) {
3963 // If it's an l-value, load through the appropriate subobject l-value.
3964 // Note that we have to ask E because Op might be an l-value that
3965 // this won't work for, e.g. an Obj-C property.
3966 if (Op->isGLValue()) {
3967 if (!PromotionType.isNull()) {
3968 CodeGenFunction::ComplexPairTy result = CGF.EmitComplexExpr(
3969 E: Op, /*IgnoreReal*/ true, /*IgnoreImag*/ IgnoreResultAssign);
3970 PromotionType = PromotionType->isAnyComplexType()
3971 ? PromotionType
3972 : CGF.getContext().getComplexType(T: PromotionType);
3973 return result.second
3974 ? CGF.EmitPromotedValue(result, PromotionType).second
3975 : result.second;
3976 }
3977
3978 return CGF.EmitLoadOfLValue(V: CGF.EmitLValue(E), Loc: E->getExprLoc())
3979 .getScalarVal();
3980 }
3981 // Otherwise, calculate and project.
3982 return CGF.EmitComplexExpr(E: Op, IgnoreReal: true, IgnoreImag: false).second;
3983 }
3984
3985 // __imag on a scalar returns zero. Emit the subexpr to ensure side
3986 // effects are evaluated, but not the actual value.
3987 if (Op->isGLValue())
3988 CGF.EmitLValue(E: Op);
3989 else if (!PromotionType.isNull())
3990 CGF.EmitPromotedScalarExpr(E: Op, PromotionType);
3991 else
3992 CGF.EmitScalarExpr(E: Op, IgnoreResultAssign: true);
3993 if (!PromotionType.isNull())
3994 return llvm::Constant::getNullValue(Ty: ConvertType(T: PromotionType));
3995 return llvm::Constant::getNullValue(Ty: ConvertType(T: E->getType()));
3996}
3997
3998//===----------------------------------------------------------------------===//
3999// Binary Operators
4000//===----------------------------------------------------------------------===//
4001
4002Value *ScalarExprEmitter::EmitPromotedValue(Value *result,
4003 QualType PromotionType) {
4004 return CGF.Builder.CreateFPExt(V: result, DestTy: ConvertType(T: PromotionType), Name: "ext");
4005}
4006
4007Value *ScalarExprEmitter::EmitUnPromotedValue(Value *result,
4008 QualType ExprType) {
4009 return CGF.Builder.CreateFPTrunc(V: result, DestTy: ConvertType(T: ExprType), Name: "unpromotion");
4010}
4011
4012Value *ScalarExprEmitter::EmitPromoted(const Expr *E, QualType PromotionType) {
4013 E = E->IgnoreParens();
4014 if (auto BO = dyn_cast<BinaryOperator>(Val: E)) {
4015 switch (BO->getOpcode()) {
4016#define HANDLE_BINOP(OP) \
4017 case BO_##OP: \
4018 return Emit##OP(EmitBinOps(BO, PromotionType));
4019 HANDLE_BINOP(Add)
4020 HANDLE_BINOP(Sub)
4021 HANDLE_BINOP(Mul)
4022 HANDLE_BINOP(Div)
4023#undef HANDLE_BINOP
4024 default:
4025 break;
4026 }
4027 } else if (auto UO = dyn_cast<UnaryOperator>(Val: E)) {
4028 switch (UO->getOpcode()) {
4029 case UO_Imag:
4030 return VisitImag(E: UO, PromotionType);
4031 case UO_Real:
4032 return VisitReal(E: UO, PromotionType);
4033 case UO_Minus:
4034 return VisitMinus(E: UO, PromotionType);
4035 case UO_Plus:
4036 return VisitPlus(E: UO, PromotionType);
4037 default:
4038 break;
4039 }
4040 }
4041 auto result = Visit(E: const_cast<Expr *>(E));
4042 if (result) {
4043 if (!PromotionType.isNull())
4044 return EmitPromotedValue(result, PromotionType);
4045 else
4046 return EmitUnPromotedValue(result, ExprType: E->getType());
4047 }
4048 return result;
4049}
4050
4051BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E,
4052 QualType PromotionType) {
4053 TestAndClearIgnoreResultAssign();
4054 BinOpInfo Result;
4055 Result.LHS = CGF.EmitPromotedScalarExpr(E: E->getLHS(), PromotionType);
4056 Result.RHS = CGF.EmitPromotedScalarExpr(E: E->getRHS(), PromotionType);
4057 if (!PromotionType.isNull())
4058 Result.Ty = PromotionType;
4059 else
4060 Result.Ty = E->getType();
4061 Result.Opcode = E->getOpcode();
4062 Result.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts());
4063 Result.E = E;
4064 return Result;
4065}
4066
4067LValue ScalarExprEmitter::EmitCompoundAssignLValue(
4068 const CompoundAssignOperator *E,
4069 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
4070 Value *&Result) {
4071 QualType LHSTy = E->getLHS()->getType();
4072 BinOpInfo OpInfo;
4073
4074 if (E->getComputationResultType()->isAnyComplexType())
4075 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
4076
4077 // Emit the RHS first. __block variables need to have the rhs evaluated
4078 // first, plus this should improve codegen a little.
4079
4080 QualType PromotionTypeCR;
4081 PromotionTypeCR = getPromotionType(Ty: E->getComputationResultType());
4082 if (PromotionTypeCR.isNull())
4083 PromotionTypeCR = E->getComputationResultType();
4084 QualType PromotionTypeLHS = getPromotionType(Ty: E->getComputationLHSType());
4085 QualType PromotionTypeRHS = getPromotionType(Ty: E->getRHS()->getType());
4086 if (!PromotionTypeRHS.isNull())
4087 OpInfo.RHS = CGF.EmitPromotedScalarExpr(E: E->getRHS(), PromotionType: PromotionTypeRHS);
4088 else
4089 OpInfo.RHS = Visit(E: E->getRHS());
4090 OpInfo.Ty = PromotionTypeCR;
4091 OpInfo.Opcode = E->getOpcode();
4092 OpInfo.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts());
4093 OpInfo.E = E;
4094 // Load/convert the LHS.
4095 LValue LHSLV = EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store);
4096
4097 llvm::PHINode *atomicPHI = nullptr;
4098 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
4099 // Type wrapped by _Atomic.
4100 QualType AtomicValueTy = atomicTy->getValueType();
4101 // Type resulting from FP conversion / integer promotion of the compound
4102 // assignment operands.
4103 QualType ResultTy = E->getComputationResultType();
4104 // Do not try the atomicrmw op fast-path when the compound assignment may
4105 // involve FP conversions, as the correct semantics would require promoting
4106 // the loaded integer to double, performing FP arithmetics, and truncation
4107 // back as a single atomic operation. Integer promotion is still
4108 // semantically safe.
4109 bool CanEmitAtomicRMW;
4110 if (AtomicValueTy->isFloatingType()) {
4111 llvm::Type *IRTy = CGF.ConvertType(T: AtomicValueTy);
4112 uint64_t StoreBits = CGF.CGM.getDataLayout().getTypeStoreSizeInBits(Ty: IRTy);
4113 // Floating atomicrmw operations cannot model constrained FP semantics.
4114 CanEmitAtomicRMW =
4115 !OpInfo.FPFeatures.isFPConstrained() &&
4116 CGF.getContext().hasSameUnqualifiedType(T1: AtomicValueTy, T2: ResultTy) &&
4117 llvm::isPowerOf2_64(Value: StoreBits);
4118 } else {
4119 CanEmitAtomicRMW =
4120 !AtomicValueTy->isBooleanType() && AtomicValueTy->isIntegerType() &&
4121 ResultTy->isIntegerType() &&
4122 !(AtomicValueTy->isUnsignedIntegerType() &&
4123 CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) &&
4124 CGF.getLangOpts().getSignedOverflowBehavior() !=
4125 LangOptions::SOB_Trapping;
4126 }
4127 if (CanEmitAtomicRMW) {
4128 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
4129 llvm::Instruction::BinaryOps Op;
4130 if (AtomicValueTy->isFloatingType()) {
4131 switch (OpInfo.Opcode) {
4132 case BO_AddAssign:
4133 AtomicOp = llvm::AtomicRMWInst::FAdd;
4134 Op = llvm::Instruction::FAdd;
4135 break;
4136 case BO_SubAssign:
4137 AtomicOp = llvm::AtomicRMWInst::FSub;
4138 Op = llvm::Instruction::FSub;
4139 break;
4140 default:
4141 break;
4142 }
4143 } else {
4144 switch (OpInfo.Opcode) {
4145 // We don't have atomicrmw operands for *, %, /, <<, >>
4146 case BO_MulAssign: case BO_DivAssign:
4147 case BO_RemAssign:
4148 case BO_ShlAssign:
4149 case BO_ShrAssign:
4150 break;
4151 case BO_AddAssign:
4152 AtomicOp = llvm::AtomicRMWInst::Add;
4153 Op = llvm::Instruction::Add;
4154 break;
4155 case BO_SubAssign:
4156 AtomicOp = llvm::AtomicRMWInst::Sub;
4157 Op = llvm::Instruction::Sub;
4158 break;
4159 case BO_AndAssign:
4160 AtomicOp = llvm::AtomicRMWInst::And;
4161 Op = llvm::Instruction::And;
4162 break;
4163 case BO_XorAssign:
4164 AtomicOp = llvm::AtomicRMWInst::Xor;
4165 Op = llvm::Instruction::Xor;
4166 break;
4167 case BO_OrAssign:
4168 AtomicOp = llvm::AtomicRMWInst::Or;
4169 Op = llvm::Instruction::Or;
4170 break;
4171 default:
4172 llvm_unreachable("Invalid compound assignment type");
4173 }
4174 }
4175 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
4176 llvm::Value *Amt = CGF.EmitToMemory(
4177 Value: EmitScalarConversion(Src: OpInfo.RHS, SrcType: E->getRHS()->getType(), DstType: LHSTy,
4178 Loc: E->getExprLoc()),
4179 Ty: LHSTy);
4180
4181 llvm::AtomicRMWInst *OldVal =
4182 CGF.emitAtomicRMWInst(Op: AtomicOp, Addr: LHSLV.getAddress(), Val: Amt);
4183
4184 // Since operation is atomic, the result type is guaranteed to be the
4185 // same as the input in LLVM terms.
4186 Result = Builder.CreateBinOp(Opc: Op, LHS: OldVal, RHS: Amt);
4187 return LHSLV;
4188 }
4189 }
4190 // FIXME: For floating point types, we should be saving and restoring the
4191 // floating point environment in the loop.
4192 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
4193 llvm::BasicBlock *opBB = CGF.createBasicBlock(name: "atomic_op", parent: CGF.CurFn);
4194 OpInfo.LHS = EmitLoadOfLValue(LV: LHSLV, Loc: E->getExprLoc());
4195 OpInfo.LHS = CGF.EmitToMemory(Value: OpInfo.LHS, Ty: AtomicValueTy);
4196 Builder.CreateBr(Dest: opBB);
4197 Builder.SetInsertPoint(opBB);
4198 atomicPHI = Builder.CreatePHI(Ty: OpInfo.LHS->getType(), NumReservedValues: 2);
4199 atomicPHI->addIncoming(V: OpInfo.LHS, BB: startBB);
4200 OpInfo.LHS = atomicPHI;
4201 }
4202 else
4203 OpInfo.LHS = EmitLoadOfLValue(LV: LHSLV, Loc: E->getExprLoc());
4204
4205 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
4206 SourceLocation Loc = E->getExprLoc();
4207 if (!PromotionTypeLHS.isNull())
4208 OpInfo.LHS = EmitScalarConversion(Src: OpInfo.LHS, SrcType: LHSTy, DstType: PromotionTypeLHS,
4209 Loc: E->getExprLoc());
4210 else
4211 OpInfo.LHS = EmitScalarConversion(Src: OpInfo.LHS, SrcType: LHSTy,
4212 DstType: E->getComputationLHSType(), Loc);
4213
4214 // Expand the binary operator.
4215 Result = (this->*Func)(OpInfo);
4216
4217 // Convert the result back to the LHS type,
4218 // potentially with Implicit Conversion sanitizer check.
4219 // If LHSLV is a bitfield, use default ScalarConversionOpts
4220 // to avoid emit any implicit integer checks.
4221 Value *Previous = nullptr;
4222 if (LHSLV.isBitField()) {
4223 Previous = Result;
4224 Result = EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: LHSTy, Loc);
4225 } else if (const auto *atomicTy = LHSTy->getAs<AtomicType>()) {
4226 Result =
4227 EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: atomicTy->getValueType(),
4228 Loc, Opts: ScalarConversionOpts(CGF.SanOpts));
4229 } else {
4230 Result = EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: LHSTy, Loc,
4231 Opts: ScalarConversionOpts(CGF.SanOpts));
4232 }
4233
4234 if (atomicPHI) {
4235 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
4236 llvm::BasicBlock *contBB = CGF.createBasicBlock(name: "atomic_cont", parent: CGF.CurFn);
4237 auto Pair = CGF.EmitAtomicCompareExchange(
4238 Obj: LHSLV, Expected: RValue::get(V: atomicPHI), Desired: RValue::get(V: Result), Loc: E->getExprLoc());
4239 llvm::Value *old = CGF.EmitToMemory(Value: Pair.first.getScalarVal(), Ty: LHSTy);
4240 llvm::Value *success = Pair.second;
4241 atomicPHI->addIncoming(V: old, BB: curBlock);
4242 Builder.CreateCondBr(Cond: success, True: contBB, False: atomicPHI->getParent());
4243 Builder.SetInsertPoint(contBB);
4244 return LHSLV;
4245 }
4246
4247 // Store the result value into the LHS lvalue. Bit-fields are handled
4248 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
4249 // 'An assignment expression has the value of the left operand after the
4250 // assignment...'.
4251 if (LHSLV.isBitField()) {
4252 Value *Src = Previous ? Previous : Result;
4253 QualType SrcType = E->getRHS()->getType();
4254 QualType DstType = E->getLHS()->getType();
4255 CGF.EmitStoreThroughBitfieldLValue(Src: RValue::get(V: Result), Dst: LHSLV, Result: &Result);
4256 CGF.EmitBitfieldConversionCheck(Src, SrcType, Dst: Result, DstType,
4257 Info: LHSLV.getBitFieldInfo(), Loc: E->getExprLoc());
4258 } else
4259 CGF.EmitStoreThroughLValue(Src: RValue::get(V: Result), Dst: LHSLV);
4260
4261 if (CGF.getLangOpts().OpenMP)
4262 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
4263 LHS: E->getLHS());
4264 return LHSLV;
4265}
4266
4267Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
4268 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
4269 bool Ignore = TestAndClearIgnoreResultAssign();
4270 Value *RHS = nullptr;
4271 LValue LHS = EmitCompoundAssignLValue(E, Func, Result&: RHS);
4272
4273 // If the result is clearly ignored, return now.
4274 if (Ignore)
4275 return nullptr;
4276
4277 // The result of an assignment in C is the assigned r-value.
4278 if (!CGF.getLangOpts().CPlusPlus)
4279 return RHS;
4280
4281 // If the lvalue is non-volatile, return the computed value of the assignment.
4282 if (!LHS.isVolatileQualified())
4283 return RHS;
4284
4285 // Otherwise, reload the value.
4286 return EmitLoadOfLValue(LV: LHS, Loc: E->getExprLoc());
4287}
4288
4289void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
4290 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
4291 SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>, 2>
4292 Checks;
4293
4294 if (CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero)) {
4295 Checks.push_back(Elt: std::make_pair(x: Builder.CreateICmpNE(LHS: Ops.RHS, RHS: Zero),
4296 y: SanitizerKind::SO_IntegerDivideByZero));
4297 }
4298
4299 const auto *BO = cast<BinaryOperator>(Val: Ops.E);
4300 if (CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow) &&
4301 Ops.Ty->hasSignedIntegerRepresentation() &&
4302 !IsWidenedIntegerOp(Ctx: CGF.getContext(), E: BO->getLHS()) &&
4303 Ops.mayHaveIntegerOverflow() &&
4304 !CGF.getContext().isTypeIgnoredBySanitizer(
4305 Mask: SanitizerKind::SignedIntegerOverflow, Ty: Ops.Ty)) {
4306 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Val: Zero->getType());
4307
4308 llvm::Value *IntMin =
4309 Builder.getInt(AI: llvm::APInt::getSignedMinValue(numBits: Ty->getBitWidth()));
4310 llvm::Value *NegOne = llvm::Constant::getAllOnesValue(Ty);
4311
4312 llvm::Value *LHSCmp = Builder.CreateICmpNE(LHS: Ops.LHS, RHS: IntMin);
4313 llvm::Value *RHSCmp = Builder.CreateICmpNE(LHS: Ops.RHS, RHS: NegOne);
4314 llvm::Value *NotOverflow = Builder.CreateOr(LHS: LHSCmp, RHS: RHSCmp, Name: "or");
4315 Checks.push_back(
4316 Elt: std::make_pair(x&: NotOverflow, y: SanitizerKind::SO_SignedIntegerOverflow));
4317 }
4318
4319 if (Checks.size() > 0)
4320 EmitBinOpCheck(Checks, Info: Ops);
4321}
4322
4323Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
4324 {
4325 SanitizerDebugLocation SanScope(&CGF,
4326 {SanitizerKind::SO_IntegerDivideByZero,
4327 SanitizerKind::SO_SignedIntegerOverflow,
4328 SanitizerKind::SO_FloatDivideByZero},
4329 SanitizerHandler::DivremOverflow);
4330 if ((CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero) ||
4331 CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) &&
4332 Ops.Ty->isIntegerType() &&
4333 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
4334 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty));
4335 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, isDiv: true);
4336 } else if (CGF.SanOpts.has(K: SanitizerKind::FloatDivideByZero) &&
4337 Ops.Ty->isRealFloatingType() &&
4338 Ops.mayHaveFloatDivisionByZero()) {
4339 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty));
4340 llvm::Value *NonZero = Builder.CreateFCmpUNE(LHS: Ops.RHS, RHS: Zero);
4341 EmitBinOpCheck(
4342 Checks: std::make_pair(x&: NonZero, y: SanitizerKind::SO_FloatDivideByZero), Info: Ops);
4343 }
4344 }
4345
4346 // In HLSL, matrix / matrix is element-wise, so skip this block.
4347 if (Ops.Ty->isConstantMatrixType() && !Ops.RHS->getType()->isVectorTy()) {
4348 llvm::MatrixBuilder MB(Builder);
4349 // We need to check the types of the operands of the operator to get the
4350 // correct matrix dimensions.
4351 auto *BO = cast<BinaryOperator>(Val: Ops.E);
4352 (void)BO;
4353 assert(
4354 isa<ConstantMatrixType>(BO->getLHS()->getType().getCanonicalType()) &&
4355 "first operand must be a matrix");
4356 assert(BO->getRHS()->getType().getCanonicalType()->isArithmeticType() &&
4357 "second operand must be an arithmetic type");
4358 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
4359 return MB.CreateScalarDiv(LHS: Ops.LHS, RHS: Ops.RHS,
4360 IsUnsigned: Ops.Ty->hasUnsignedIntegerRepresentation());
4361 }
4362
4363 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
4364 llvm::Value *Val;
4365 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
4366 Val = Builder.CreateFDiv(L: Ops.LHS, R: Ops.RHS, Name: "div");
4367 CGF.SetDivFPAccuracy(Val);
4368 return Val;
4369 }
4370 else if (Ops.isFixedPointOp())
4371 return EmitFixedPointBinOp(Ops);
4372 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
4373 return Builder.CreateUDiv(LHS: Ops.LHS, RHS: Ops.RHS, Name: "div");
4374 else
4375 return Builder.CreateSDiv(LHS: Ops.LHS, RHS: Ops.RHS, Name: "div");
4376}
4377
4378Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
4379 // Rem in C can't be a floating point type: C99 6.5.5p2.
4380 if ((CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero) ||
4381 CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) &&
4382 Ops.Ty->isIntegerType() &&
4383 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
4384 SanitizerDebugLocation SanScope(&CGF,
4385 {SanitizerKind::SO_IntegerDivideByZero,
4386 SanitizerKind::SO_SignedIntegerOverflow},
4387 SanitizerHandler::DivremOverflow);
4388 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty));
4389 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, isDiv: false);
4390 }
4391
4392 if (Ops.Ty->hasUnsignedIntegerRepresentation())
4393 return Builder.CreateURem(LHS: Ops.LHS, RHS: Ops.RHS, Name: "rem");
4394
4395 if (CGF.getLangOpts().HLSL && Ops.Ty->hasFloatingRepresentation())
4396 return Builder.CreateFRem(L: Ops.LHS, R: Ops.RHS, Name: "rem");
4397
4398 return Builder.CreateSRem(LHS: Ops.LHS, RHS: Ops.RHS, Name: "rem");
4399}
4400
4401Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
4402 unsigned IID;
4403 unsigned OpID = 0;
4404 SanitizerHandler OverflowKind;
4405
4406 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
4407 switch (Ops.Opcode) {
4408 case BO_Add:
4409 case BO_AddAssign:
4410 OpID = 1;
4411 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
4412 llvm::Intrinsic::uadd_with_overflow;
4413 OverflowKind = SanitizerHandler::AddOverflow;
4414 break;
4415 case BO_Sub:
4416 case BO_SubAssign:
4417 OpID = 2;
4418 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
4419 llvm::Intrinsic::usub_with_overflow;
4420 OverflowKind = SanitizerHandler::SubOverflow;
4421 break;
4422 case BO_Mul:
4423 case BO_MulAssign:
4424 OpID = 3;
4425 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
4426 llvm::Intrinsic::umul_with_overflow;
4427 OverflowKind = SanitizerHandler::MulOverflow;
4428 break;
4429 default:
4430 llvm_unreachable("Unsupported operation for overflow detection");
4431 }
4432 OpID <<= 1;
4433 if (isSigned)
4434 OpID |= 1;
4435
4436 SanitizerDebugLocation SanScope(&CGF,
4437 {SanitizerKind::SO_SignedIntegerOverflow,
4438 SanitizerKind::SO_UnsignedIntegerOverflow},
4439 OverflowKind);
4440 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(T: Ops.Ty);
4441
4442 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, Tys: opTy);
4443
4444 Value *resultAndOverflow = Builder.CreateCall(Callee: intrinsic, Args: {Ops.LHS, Ops.RHS});
4445 Value *result = Builder.CreateExtractValue(Agg: resultAndOverflow, Idxs: 0);
4446 Value *overflow = Builder.CreateExtractValue(Agg: resultAndOverflow, Idxs: 1);
4447
4448 // Handle overflow with llvm.trap if no custom handler has been specified.
4449 const std::string *handlerName =
4450 &CGF.getLangOpts().OverflowHandler;
4451 if (handlerName->empty()) {
4452 // If no -ftrapv handler has been specified, try to use sanitizer runtimes
4453 // if available otherwise just emit a trap. It is possible for unsigned
4454 // arithmetic to result in a trap due to the OverflowBehaviorType attribute
4455 // which describes overflow behavior on a per-type basis.
4456 if (isSigned) {
4457 if (CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) {
4458 llvm::Value *NotOf = Builder.CreateNot(V: overflow);
4459 EmitBinOpCheck(
4460 Checks: std::make_pair(x&: NotOf, y: SanitizerKind::SO_SignedIntegerOverflow),
4461 Info: Ops);
4462 } else
4463 CGF.EmitTrapCheck(Checked: Builder.CreateNot(V: overflow), CheckHandlerID: OverflowKind);
4464 return result;
4465 }
4466 if (CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) {
4467 llvm::Value *NotOf = Builder.CreateNot(V: overflow);
4468 EmitBinOpCheck(
4469 Checks: std::make_pair(x&: NotOf, y: SanitizerKind::SO_UnsignedIntegerOverflow),
4470 Info: Ops);
4471 } else
4472 CGF.EmitTrapCheck(Checked: Builder.CreateNot(V: overflow), CheckHandlerID: OverflowKind);
4473 return result;
4474 }
4475
4476 // Branch in case of overflow.
4477 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
4478 llvm::BasicBlock *continueBB =
4479 CGF.createBasicBlock(name: "nooverflow", parent: CGF.CurFn, before: initialBB->getNextNode());
4480 llvm::BasicBlock *overflowBB = CGF.createBasicBlock(name: "overflow", parent: CGF.CurFn);
4481
4482 Builder.CreateCondBr(Cond: overflow, True: overflowBB, False: continueBB);
4483
4484 // If an overflow handler is set, then we want to call it and then use its
4485 // result, if it returns.
4486 Builder.SetInsertPoint(overflowBB);
4487
4488 // Get the overflow handler.
4489 ASTContext &Ctx = CGF.getContext();
4490 QualType ArgTys[] = {Ctx.LongLongTy, Ctx.LongLongTy, Ctx.UnsignedCharTy,
4491 Ctx.UnsignedCharTy};
4492 llvm::FunctionCallee handler =
4493 CGF.CGM.CreateRuntimeFunction(ReturnTy: Ctx.LongLongTy, ArgTys, Name: *handlerName);
4494
4495 // Sign extend the args to 64-bit, so that we can use the same handler for
4496 // all types of overflow.
4497 llvm::Value *lhs = Builder.CreateSExt(V: Ops.LHS, DestTy: CGF.Int64Ty);
4498 llvm::Value *rhs = Builder.CreateSExt(V: Ops.RHS, DestTy: CGF.Int64Ty);
4499
4500 // Call the handler with the two arguments, the operation, and the size of
4501 // the result.
4502 llvm::Value *handlerArgs[] = {
4503 lhs,
4504 rhs,
4505 Builder.getInt8(C: OpID),
4506 Builder.getInt8(C: cast<llvm::IntegerType>(Val: opTy)->getBitWidth())
4507 };
4508 llvm::Value *handlerResult =
4509 CGF.EmitNounwindRuntimeCall(callee: handler, args: handlerArgs);
4510
4511 // Truncate the result back to the desired size.
4512 handlerResult = Builder.CreateTrunc(V: handlerResult, DestTy: opTy);
4513 Builder.CreateBr(Dest: continueBB);
4514
4515 Builder.SetInsertPoint(continueBB);
4516 llvm::PHINode *phi = Builder.CreatePHI(Ty: opTy, NumReservedValues: 2);
4517 phi->addIncoming(V: result, BB: initialBB);
4518 phi->addIncoming(V: handlerResult, BB: overflowBB);
4519
4520 return phi;
4521}
4522
4523/// BO_Add/BO_Sub are handled by EmitPointerWithAlignment to preserve alignment
4524/// information.
4525/// This function is used for BO_AddAssign/BO_SubAssign.
4526static Value *emitPointerArithmetic(CodeGenFunction &CGF, const BinOpInfo &op,
4527 bool isSubtraction) {
4528 // Must have binary (not unary) expr here. Unary pointer
4529 // increment/decrement doesn't use this path.
4530 const BinaryOperator *expr = cast<BinaryOperator>(Val: op.E);
4531
4532 Value *pointer = op.LHS;
4533 Expr *pointerOperand = expr->getLHS();
4534 Value *index = op.RHS;
4535 Expr *indexOperand = expr->getRHS();
4536
4537 // In a subtraction, the LHS is always the pointer.
4538 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
4539 std::swap(a&: pointer, b&: index);
4540 std::swap(a&: pointerOperand, b&: indexOperand);
4541 }
4542
4543 return CGF.EmitPointerArithmetic(BO: expr, pointerOperand, pointer, indexOperand,
4544 index, isSubtraction);
4545}
4546
4547/// Emit pointer + index arithmetic.
4548llvm::Value *CodeGenFunction::EmitPointerArithmetic(
4549 const BinaryOperator *BO, Expr *pointerOperand, llvm::Value *pointer,
4550 Expr *indexOperand, llvm::Value *index, bool isSubtraction) {
4551 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
4552
4553 unsigned width = cast<llvm::IntegerType>(Val: index->getType())->getBitWidth();
4554 auto &DL = CGM.getDataLayout();
4555 auto *PtrTy = cast<llvm::PointerType>(Val: pointer->getType());
4556
4557 // Some versions of glibc and gcc use idioms (particularly in their malloc
4558 // routines) that add a pointer-sized integer (known to be a pointer value)
4559 // to a null pointer in order to cast the value back to an integer or as
4560 // part of a pointer alignment algorithm. This is undefined behavior, but
4561 // we'd like to be able to compile programs that use it.
4562 //
4563 // Normally, we'd generate a GEP with a null-pointer base here in response
4564 // to that code, but it's also UB to dereference a pointer created that
4565 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
4566 // generate a direct cast of the integer value to a pointer.
4567 //
4568 // The idiom (p = nullptr + N) is not met if any of the following are true:
4569 //
4570 // The operation is subtraction.
4571 // The index is not pointer-sized.
4572 // The pointer type is not byte-sized.
4573 //
4574 // Note that we do not suppress the pointer overflow check in this case.
4575 if (BinaryOperator::isNullPointerArithmeticExtension(
4576 Ctx&: getContext(), Opc: BO->getOpcode(), LHS: pointerOperand, RHS: indexOperand)) {
4577 llvm::Value *Ptr = Builder.CreateIntToPtr(V: index, DestTy: pointer->getType());
4578 if (getLangOpts().PointerOverflowDefined ||
4579 !SanOpts.has(K: SanitizerKind::PointerOverflow) ||
4580 NullPointerIsDefined(F: Builder.GetInsertBlock()->getParent(),
4581 AS: PtrTy->getPointerAddressSpace()))
4582 return Ptr;
4583 // The inbounds GEP of null is valid iff the index is zero.
4584 auto CheckOrdinal = SanitizerKind::SO_PointerOverflow;
4585 auto CheckHandler = SanitizerHandler::PointerOverflow;
4586 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
4587 llvm::Value *IsZeroIndex = Builder.CreateIsNull(Arg: index);
4588 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc: BO->getExprLoc())};
4589 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
4590 llvm::Value *IntPtr = llvm::Constant::getNullValue(Ty: IntPtrTy);
4591 llvm::Value *ComputedGEP = Builder.CreateZExtOrTrunc(V: index, DestTy: IntPtrTy);
4592 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
4593 EmitCheck(Checked: {{IsZeroIndex, CheckOrdinal}}, Check: CheckHandler, StaticArgs,
4594 DynamicArgs);
4595 return Ptr;
4596 }
4597
4598 if (width != DL.getIndexTypeSizeInBits(Ty: PtrTy)) {
4599 // Zero-extend or sign-extend the pointer value according to
4600 // whether the index is signed or not.
4601 index = Builder.CreateIntCast(V: index, DestTy: DL.getIndexType(PtrTy), isSigned,
4602 Name: "idx.ext");
4603 }
4604
4605 // If this is subtraction, negate the index.
4606 if (isSubtraction)
4607 index = Builder.CreateNeg(V: index, Name: "idx.neg");
4608
4609 if (SanOpts.has(K: SanitizerKind::ArrayBounds))
4610 EmitBoundsCheck(ArrayExpr: BO, ArrayExprBase: pointerOperand, Index: index, IndexType: indexOperand->getType(),
4611 /*Accessed*/ false);
4612
4613 const PointerType *pointerType =
4614 pointerOperand->getType()->getAs<PointerType>();
4615 if (!pointerType) {
4616 QualType objectType = pointerOperand->getType()
4617 ->castAs<ObjCObjectPointerType>()
4618 ->getPointeeType();
4619 llvm::Value *objectSize =
4620 CGM.getSize(numChars: getContext().getTypeSizeInChars(T: objectType));
4621
4622 index = Builder.CreateMul(LHS: index, RHS: objectSize);
4623
4624 llvm::Value *result = Builder.CreateGEP(Ty: Int8Ty, Ptr: pointer, IdxList: index, Name: "add.ptr");
4625 return Builder.CreateBitCast(V: result, DestTy: pointer->getType());
4626 }
4627
4628 QualType elementType = pointerType->getPointeeType();
4629 if (const VariableArrayType *vla =
4630 getContext().getAsVariableArrayType(T: elementType)) {
4631 // The element count here is the total number of non-VLA elements.
4632 llvm::Value *numElements = getVLASize(vla).NumElts;
4633
4634 // Effectively, the multiply by the VLA size is part of the GEP.
4635 // GEP indexes are signed, and scaling an index isn't permitted to
4636 // signed-overflow, so we use the same semantics for our explicit
4637 // multiply. We suppress this if overflow is not undefined behavior.
4638 llvm::Type *elemTy = ConvertTypeForMem(T: vla->getElementType());
4639 if (getLangOpts().PointerOverflowDefined) {
4640 index = Builder.CreateMul(LHS: index, RHS: numElements, Name: "vla.index");
4641 pointer = Builder.CreateGEP(Ty: elemTy, Ptr: pointer, IdxList: index, Name: "add.ptr");
4642 } else {
4643 index = Builder.CreateNSWMul(LHS: index, RHS: numElements, Name: "vla.index");
4644 pointer =
4645 EmitCheckedInBoundsGEP(ElemTy: elemTy, Ptr: pointer, IdxList: index, SignedIndices: isSigned,
4646 IsSubtraction: isSubtraction, Loc: BO->getExprLoc(), Name: "add.ptr");
4647 }
4648 return pointer;
4649 }
4650
4651 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
4652 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
4653 // future proof.
4654 llvm::Type *elemTy;
4655 if (elementType->isVoidType() || elementType->isFunctionType())
4656 elemTy = Int8Ty;
4657 else
4658 elemTy = ConvertTypeForMem(T: elementType);
4659
4660 if (getLangOpts().PointerOverflowDefined)
4661 return Builder.CreateGEP(Ty: elemTy, Ptr: pointer, IdxList: index, Name: "add.ptr");
4662
4663 return EmitCheckedInBoundsGEP(ElemTy: elemTy, Ptr: pointer, IdxList: index, SignedIndices: isSigned, IsSubtraction: isSubtraction,
4664 Loc: BO->getExprLoc(), Name: "add.ptr");
4665}
4666
4667// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
4668// Addend. Use negMul and negAdd to negate the first operand of the Mul or
4669// the add operand respectively. This allows fmuladd to represent a*b-c, or
4670// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
4671// efficient operations.
4672static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
4673 const CodeGenFunction &CGF, CGBuilderTy &Builder,
4674 bool negMul, bool negAdd) {
4675 Value *MulOp0 = MulOp->getOperand(i: 0);
4676 Value *MulOp1 = MulOp->getOperand(i: 1);
4677 if (negMul)
4678 MulOp0 = Builder.CreateFNeg(V: MulOp0, Name: "neg");
4679 if (negAdd)
4680 Addend = Builder.CreateFNeg(V: Addend, Name: "neg");
4681
4682 Value *FMulAdd = nullptr;
4683 if (Builder.getIsFPConstrained()) {
4684 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
4685 "Only constrained operation should be created when Builder is in FP "
4686 "constrained mode");
4687 FMulAdd = Builder.CreateConstrainedFPCall(
4688 Callee: CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::experimental_constrained_fmuladd,
4689 Tys: Addend->getType()),
4690 Args: {MulOp0, MulOp1, Addend});
4691 } else {
4692 FMulAdd = Builder.CreateCall(
4693 Callee: CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::fmuladd, Tys: Addend->getType()),
4694 Args: {MulOp0, MulOp1, Addend});
4695 }
4696 MulOp->eraseFromParent();
4697
4698 return FMulAdd;
4699}
4700
4701// Check whether it would be legal to emit an fmuladd intrinsic call to
4702// represent op and if so, build the fmuladd.
4703//
4704// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
4705// Does NOT check the type of the operation - it's assumed that this function
4706// will be called from contexts where it's known that the type is contractable.
4707static Value* tryEmitFMulAdd(const BinOpInfo &op,
4708 const CodeGenFunction &CGF, CGBuilderTy &Builder,
4709 bool isSub=false) {
4710
4711 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
4712 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
4713 "Only fadd/fsub can be the root of an fmuladd.");
4714
4715 // Check whether this op is marked as fusable.
4716 if (!op.FPFeatures.allowFPContractWithinStatement())
4717 return nullptr;
4718
4719 Value *LHS = op.LHS;
4720 Value *RHS = op.RHS;
4721
4722 // Peek through fneg to look for fmul. Make sure fneg has no users, and that
4723 // it is the only use of its operand.
4724 bool NegLHS = false;
4725 if (auto *LHSUnOp = dyn_cast<llvm::UnaryOperator>(Val: LHS)) {
4726 if (LHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4727 LHSUnOp->use_empty() && LHSUnOp->getOperand(i_nocapture: 0)->hasOneUse()) {
4728 LHS = LHSUnOp->getOperand(i_nocapture: 0);
4729 NegLHS = true;
4730 }
4731 }
4732
4733 bool NegRHS = false;
4734 if (auto *RHSUnOp = dyn_cast<llvm::UnaryOperator>(Val: RHS)) {
4735 if (RHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4736 RHSUnOp->use_empty() && RHSUnOp->getOperand(i_nocapture: 0)->hasOneUse()) {
4737 RHS = RHSUnOp->getOperand(i_nocapture: 0);
4738 NegRHS = true;
4739 }
4740 }
4741
4742 // We have a potentially fusable op. Look for a mul on one of the operands.
4743 // Also, make sure that the mul result isn't used directly. In that case,
4744 // there's no point creating a muladd operation.
4745 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(Val: LHS)) {
4746 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4747 (LHSBinOp->use_empty() || NegLHS)) {
4748 // If we looked through fneg, erase it.
4749 if (NegLHS)
4750 cast<llvm::Instruction>(Val: op.LHS)->eraseFromParent();
4751 return buildFMulAdd(MulOp: LHSBinOp, Addend: op.RHS, CGF, Builder, negMul: NegLHS, negAdd: isSub);
4752 }
4753 }
4754 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(Val: RHS)) {
4755 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4756 (RHSBinOp->use_empty() || NegRHS)) {
4757 // If we looked through fneg, erase it.
4758 if (NegRHS)
4759 cast<llvm::Instruction>(Val: op.RHS)->eraseFromParent();
4760 return buildFMulAdd(MulOp: RHSBinOp, Addend: op.LHS, CGF, Builder, negMul: isSub ^ NegRHS, negAdd: false);
4761 }
4762 }
4763
4764 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(Val: LHS)) {
4765 if (LHSBinOp->getIntrinsicID() ==
4766 llvm::Intrinsic::experimental_constrained_fmul &&
4767 (LHSBinOp->use_empty() || NegLHS)) {
4768 // If we looked through fneg, erase it.
4769 if (NegLHS)
4770 cast<llvm::Instruction>(Val: op.LHS)->eraseFromParent();
4771 return buildFMulAdd(MulOp: LHSBinOp, Addend: op.RHS, CGF, Builder, negMul: NegLHS, negAdd: isSub);
4772 }
4773 }
4774 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(Val: RHS)) {
4775 if (RHSBinOp->getIntrinsicID() ==
4776 llvm::Intrinsic::experimental_constrained_fmul &&
4777 (RHSBinOp->use_empty() || NegRHS)) {
4778 // If we looked through fneg, erase it.
4779 if (NegRHS)
4780 cast<llvm::Instruction>(Val: op.RHS)->eraseFromParent();
4781 return buildFMulAdd(MulOp: RHSBinOp, Addend: op.LHS, CGF, Builder, negMul: isSub ^ NegRHS, negAdd: false);
4782 }
4783 }
4784
4785 return nullptr;
4786}
4787
4788Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
4789 if (op.LHS->getType()->isPointerTy() ||
4790 op.RHS->getType()->isPointerTy())
4791 return emitPointerArithmetic(CGF, op, isSubtraction: CodeGenFunction::NotSubtraction);
4792
4793 if (op.Ty->isSignedIntegerOrEnumerationType() ||
4794 op.Ty->isUnsignedIntegerType()) {
4795 const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType();
4796 const bool hasSan =
4797 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
4798 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
4799 switch (getOverflowBehaviorConsideringType(CGF, Ty: op.Ty)) {
4800 case LangOptions::OB_Wrap:
4801 return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4802 case LangOptions::OB_SignedAndDefined:
4803 if (!hasSan)
4804 return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4805 [[fallthrough]];
4806 case LangOptions::OB_Unset:
4807 if (!hasSan)
4808 return isSigned ? Builder.CreateNSWAdd(LHS: op.LHS, RHS: op.RHS, Name: "add")
4809 : Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4810 [[fallthrough]];
4811 case LangOptions::OB_Trap:
4812 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: op))
4813 return isSigned ? Builder.CreateNSWAdd(LHS: op.LHS, RHS: op.RHS, Name: "add")
4814 : Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4815 return EmitOverflowCheckedBinOp(Ops: op);
4816 }
4817 }
4818
4819 // For vector and matrix adds, try to fold into a fmuladd.
4820 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4821 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4822 // Try to form an fmuladd.
4823 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
4824 return FMulAdd;
4825 }
4826
4827 if (op.Ty->isConstantMatrixType()) {
4828 llvm::MatrixBuilder MB(Builder);
4829 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4830 return MB.CreateAdd(LHS: op.LHS, RHS: op.RHS);
4831 }
4832
4833 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4834 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4835 return Builder.CreateFAdd(L: op.LHS, R: op.RHS, Name: "add");
4836 }
4837
4838 if (op.isFixedPointOp())
4839 return EmitFixedPointBinOp(Ops: op);
4840
4841 return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4842}
4843
4844/// The resulting value must be calculated with exact precision, so the operands
4845/// may not be the same type.
4846Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
4847 using llvm::APSInt;
4848 using llvm::ConstantInt;
4849
4850 // This is either a binary operation where at least one of the operands is
4851 // a fixed-point type, or a unary operation where the operand is a fixed-point
4852 // type. The result type of a binary operation is determined by
4853 // Sema::handleFixedPointConversions().
4854 QualType ResultTy = op.Ty;
4855 QualType LHSTy, RHSTy;
4856 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: op.E)) {
4857 RHSTy = BinOp->getRHS()->getType();
4858 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(Val: BinOp)) {
4859 // For compound assignment, the effective type of the LHS at this point
4860 // is the computation LHS type, not the actual LHS type, and the final
4861 // result type is not the type of the expression but rather the
4862 // computation result type.
4863 LHSTy = CAO->getComputationLHSType();
4864 ResultTy = CAO->getComputationResultType();
4865 } else
4866 LHSTy = BinOp->getLHS()->getType();
4867 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(Val: op.E)) {
4868 LHSTy = UnOp->getSubExpr()->getType();
4869 RHSTy = UnOp->getSubExpr()->getType();
4870 }
4871 ASTContext &Ctx = CGF.getContext();
4872 Value *LHS = op.LHS;
4873 Value *RHS = op.RHS;
4874
4875 auto LHSFixedSema = Ctx.getFixedPointSemantics(Ty: LHSTy);
4876 auto RHSFixedSema = Ctx.getFixedPointSemantics(Ty: RHSTy);
4877 auto ResultFixedSema = Ctx.getFixedPointSemantics(Ty: ResultTy);
4878 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(Other: RHSFixedSema);
4879
4880 // Perform the actual operation.
4881 Value *Result;
4882 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
4883 switch (op.Opcode) {
4884 case BO_AddAssign:
4885 case BO_Add:
4886 Result = FPBuilder.CreateAdd(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4887 break;
4888 case BO_SubAssign:
4889 case BO_Sub:
4890 Result = FPBuilder.CreateSub(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4891 break;
4892 case BO_MulAssign:
4893 case BO_Mul:
4894 Result = FPBuilder.CreateMul(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4895 break;
4896 case BO_DivAssign:
4897 case BO_Div:
4898 Result = FPBuilder.CreateDiv(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4899 break;
4900 case BO_ShlAssign:
4901 case BO_Shl:
4902 Result = FPBuilder.CreateShl(LHS, LHSSema: LHSFixedSema, RHS);
4903 break;
4904 case BO_ShrAssign:
4905 case BO_Shr:
4906 Result = FPBuilder.CreateShr(LHS, LHSSema: LHSFixedSema, RHS);
4907 break;
4908 case BO_LT:
4909 return FPBuilder.CreateLT(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4910 case BO_GT:
4911 return FPBuilder.CreateGT(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4912 case BO_LE:
4913 return FPBuilder.CreateLE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4914 case BO_GE:
4915 return FPBuilder.CreateGE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4916 case BO_EQ:
4917 // For equality operations, we assume any padding bits on unsigned types are
4918 // zero'd out. They could be overwritten through non-saturating operations
4919 // that cause overflow, but this leads to undefined behavior.
4920 return FPBuilder.CreateEQ(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4921 case BO_NE:
4922 return FPBuilder.CreateNE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4923 case BO_Cmp:
4924 case BO_LAnd:
4925 case BO_LOr:
4926 llvm_unreachable("Found unimplemented fixed point binary operation");
4927 case BO_PtrMemD:
4928 case BO_PtrMemI:
4929 case BO_Rem:
4930 case BO_Xor:
4931 case BO_And:
4932 case BO_Or:
4933 case BO_Assign:
4934 case BO_RemAssign:
4935 case BO_AndAssign:
4936 case BO_XorAssign:
4937 case BO_OrAssign:
4938 case BO_Comma:
4939 llvm_unreachable("Found unsupported binary operation for fixed point types.");
4940 }
4941
4942 bool IsShift = BinaryOperator::isShiftOp(Opc: op.Opcode) ||
4943 BinaryOperator::isShiftAssignOp(Opc: op.Opcode);
4944 // Convert to the result type.
4945 return FPBuilder.CreateFixedToFixed(Src: Result, SrcSema: IsShift ? LHSFixedSema
4946 : CommonFixedSema,
4947 DstSema: ResultFixedSema);
4948}
4949
4950Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
4951 // The LHS is always a pointer if either side is.
4952 if (!op.LHS->getType()->isPointerTy()) {
4953 if (op.Ty->isSignedIntegerOrEnumerationType() ||
4954 op.Ty->isUnsignedIntegerType()) {
4955 const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType();
4956 const bool hasSan =
4957 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
4958 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
4959 switch (getOverflowBehaviorConsideringType(CGF, Ty: op.Ty)) {
4960 case LangOptions::OB_Wrap:
4961 return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4962 case LangOptions::OB_SignedAndDefined:
4963 if (!hasSan)
4964 return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4965 [[fallthrough]];
4966 case LangOptions::OB_Unset:
4967 if (!hasSan)
4968 return isSigned ? Builder.CreateNSWSub(LHS: op.LHS, RHS: op.RHS, Name: "sub")
4969 : Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4970 [[fallthrough]];
4971 case LangOptions::OB_Trap:
4972 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: op))
4973 return isSigned ? Builder.CreateNSWSub(LHS: op.LHS, RHS: op.RHS, Name: "sub")
4974 : Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4975 return EmitOverflowCheckedBinOp(Ops: op);
4976 }
4977 }
4978
4979 // For vector and matrix subs, try to fold into a fmuladd.
4980 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4981 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4982 // Try to form an fmuladd.
4983 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, isSub: true))
4984 return FMulAdd;
4985 }
4986
4987 if (op.Ty->isConstantMatrixType()) {
4988 llvm::MatrixBuilder MB(Builder);
4989 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4990 return MB.CreateSub(LHS: op.LHS, RHS: op.RHS);
4991 }
4992
4993 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4994 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4995 return Builder.CreateFSub(L: op.LHS, R: op.RHS, Name: "sub");
4996 }
4997
4998 if (op.isFixedPointOp())
4999 return EmitFixedPointBinOp(op);
5000
5001 return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
5002 }
5003
5004 // If the RHS is not a pointer, then we have normal pointer
5005 // arithmetic.
5006 if (!op.RHS->getType()->isPointerTy())
5007 return emitPointerArithmetic(CGF, op, isSubtraction: CodeGenFunction::IsSubtraction);
5008
5009 // Otherwise, this is a pointer subtraction.
5010
5011 // Do the raw subtraction part. When pointer overflow is defined, use ptrtoint
5012 // as the pointer difference can be used to obtain the pointer without basing
5013 // it on one of the pointers (e.g. via -(nullptr - ptr)).
5014 Value *LHS, *RHS;
5015 if (CGF.getLangOpts().PointerOverflowDefined) {
5016 LHS = Builder.CreatePtrToInt(V: op.LHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.lhs.cast");
5017 RHS = Builder.CreatePtrToInt(V: op.RHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.rhs.cast");
5018 } else {
5019 LHS = Builder.CreatePtrToAddr(V: op.LHS, Name: "sub.ptr.lhs.cast");
5020 RHS = Builder.CreatePtrToAddr(V: op.RHS, Name: "sub.ptr.rhs.cast");
5021 if (LHS->getType() != CGF.PtrDiffTy)
5022 LHS = Builder.CreateZExtOrTrunc(V: LHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.lhs.ext");
5023 if (RHS->getType() != CGF.PtrDiffTy)
5024 RHS = Builder.CreateZExtOrTrunc(V: RHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.lhs.ext");
5025 }
5026 Value *diffInChars = Builder.CreateSub(LHS, RHS, Name: "sub.ptr.sub");
5027
5028 // Okay, figure out the element size.
5029 const BinaryOperator *expr = cast<BinaryOperator>(Val: op.E);
5030 QualType elementType = expr->getLHS()->getType()->getPointeeType();
5031
5032 llvm::Value *divisor = nullptr;
5033
5034 // For a variable-length array, this is going to be non-constant.
5035 if (const VariableArrayType *vla
5036 = CGF.getContext().getAsVariableArrayType(T: elementType)) {
5037 auto VlaSize = CGF.getVLASize(vla);
5038 elementType = VlaSize.Type;
5039 divisor = VlaSize.NumElts;
5040
5041 // Scale the number of non-VLA elements by the non-VLA element size.
5042 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(T: elementType);
5043 if (!eltSize.isOne())
5044 divisor = CGF.Builder.CreateNUWMul(LHS: CGF.CGM.getSize(numChars: eltSize), RHS: divisor);
5045
5046 // For everything elese, we can just compute it, safe in the
5047 // assumption that Sema won't let anything through that we can't
5048 // safely compute the size of.
5049 } else {
5050 CharUnits elementSize;
5051 // Handle GCC extension for pointer arithmetic on void* and
5052 // function pointer types.
5053 if (elementType->isVoidType() || elementType->isFunctionType())
5054 elementSize = CharUnits::One();
5055 else
5056 elementSize = CGF.getContext().getTypeSizeInChars(T: elementType);
5057
5058 // Don't even emit the divide for element size of 1.
5059 if (elementSize.isOne())
5060 return diffInChars;
5061
5062 divisor = CGF.CGM.getSize(numChars: elementSize);
5063 }
5064
5065 if (CGF.getLangOpts().StablePointerSubtraction)
5066 return Builder.CreateSDiv(LHS: diffInChars, RHS: divisor, Name: "sub.ptr.div");
5067 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
5068 // pointer difference in C is only defined in the case where both operands
5069 // are pointing to elements of an array.
5070 return Builder.CreateExactSDiv(LHS: diffInChars, RHS: divisor, Name: "sub.ptr.div");
5071}
5072
5073Value *ScalarExprEmitter::GetMaximumShiftAmount(Value *LHS, Value *RHS,
5074 bool RHSIsSigned) {
5075 llvm::IntegerType *Ty;
5076 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Val: LHS->getType()))
5077 Ty = cast<llvm::IntegerType>(Val: VT->getElementType());
5078 else
5079 Ty = cast<llvm::IntegerType>(Val: LHS->getType());
5080 // For a given type of LHS the maximum shift amount is width(LHS)-1, however
5081 // it can occur that width(LHS)-1 > range(RHS). Since there is no check for
5082 // this in ConstantInt::get, this results in the value getting truncated.
5083 // Constrain the return value to be max(RHS) in this case.
5084 llvm::Type *RHSTy = RHS->getType();
5085 llvm::APInt RHSMax =
5086 RHSIsSigned ? llvm::APInt::getSignedMaxValue(numBits: RHSTy->getScalarSizeInBits())
5087 : llvm::APInt::getMaxValue(numBits: RHSTy->getScalarSizeInBits());
5088 if (RHSMax.ult(RHS: Ty->getBitWidth()))
5089 return llvm::ConstantInt::get(Ty: RHSTy, V: RHSMax);
5090 return llvm::ConstantInt::get(Ty: RHSTy, V: Ty->getBitWidth() - 1);
5091}
5092
5093Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
5094 const Twine &Name) {
5095 llvm::IntegerType *Ty;
5096 if (auto *VT = dyn_cast<llvm::VectorType>(Val: LHS->getType()))
5097 Ty = cast<llvm::IntegerType>(Val: VT->getElementType());
5098 else
5099 Ty = cast<llvm::IntegerType>(Val: LHS->getType());
5100
5101 if (llvm::isPowerOf2_64(Value: Ty->getBitWidth()))
5102 return Builder.CreateAnd(LHS: RHS, RHS: GetMaximumShiftAmount(LHS, RHS, RHSIsSigned: false), Name);
5103
5104 return Builder.CreateURem(
5105 LHS: RHS, RHS: llvm::ConstantInt::get(Ty: RHS->getType(), V: Ty->getBitWidth()), Name);
5106}
5107
5108Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
5109 // TODO: This misses out on the sanitizer check below.
5110 if (Ops.isFixedPointOp())
5111 return EmitFixedPointBinOp(op: Ops);
5112
5113 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
5114 // RHS to the same size as the LHS.
5115 Value *RHS = Ops.RHS;
5116 if (Ops.LHS->getType() != RHS->getType())
5117 RHS = Builder.CreateIntCast(V: RHS, DestTy: Ops.LHS->getType(), isSigned: false, Name: "sh_prom");
5118
5119 bool SanitizeSignedBase = CGF.SanOpts.has(K: SanitizerKind::ShiftBase) &&
5120 Ops.Ty->hasSignedIntegerRepresentation() &&
5121 !CGF.getLangOpts().isSignedOverflowDefined() &&
5122 !CGF.getLangOpts().CPlusPlus20;
5123 bool SanitizeUnsignedBase =
5124 CGF.SanOpts.has(K: SanitizerKind::UnsignedShiftBase) &&
5125 Ops.Ty->hasUnsignedIntegerRepresentation();
5126 bool SanitizeBase = SanitizeSignedBase || SanitizeUnsignedBase;
5127 bool SanitizeExponent = CGF.SanOpts.has(K: SanitizerKind::ShiftExponent);
5128 // OpenCL 6.3j: shift values are effectively % word size of LHS.
5129 if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL)
5130 RHS = ConstrainShiftValue(LHS: Ops.LHS, RHS, Name: "shl.mask");
5131 else if ((SanitizeBase || SanitizeExponent) &&
5132 isa<llvm::IntegerType>(Val: Ops.LHS->getType())) {
5133 SmallVector<SanitizerKind::SanitizerOrdinal, 3> Ordinals;
5134 if (SanitizeSignedBase)
5135 Ordinals.push_back(Elt: SanitizerKind::SO_ShiftBase);
5136 if (SanitizeUnsignedBase)
5137 Ordinals.push_back(Elt: SanitizerKind::SO_UnsignedShiftBase);
5138 if (SanitizeExponent)
5139 Ordinals.push_back(Elt: SanitizerKind::SO_ShiftExponent);
5140
5141 SanitizerDebugLocation SanScope(&CGF, Ordinals,
5142 SanitizerHandler::ShiftOutOfBounds);
5143 SmallVector<std::pair<Value *, SanitizerKind::SanitizerOrdinal>, 2> Checks;
5144 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
5145 llvm::Value *WidthMinusOne =
5146 GetMaximumShiftAmount(LHS: Ops.LHS, RHS: Ops.RHS, RHSIsSigned);
5147 llvm::Value *ValidExponent = Builder.CreateICmpULE(LHS: Ops.RHS, RHS: WidthMinusOne);
5148
5149 if (SanitizeExponent) {
5150 Checks.push_back(
5151 Elt: std::make_pair(x&: ValidExponent, y: SanitizerKind::SO_ShiftExponent));
5152 }
5153
5154 if (SanitizeBase) {
5155 // Check whether we are shifting any non-zero bits off the top of the
5156 // integer. We only emit this check if exponent is valid - otherwise
5157 // instructions below will have undefined behavior themselves.
5158 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
5159 llvm::BasicBlock *Cont = CGF.createBasicBlock(name: "cont");
5160 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock(name: "check");
5161 Builder.CreateCondBr(Cond: ValidExponent, True: CheckShiftBase, False: Cont);
5162 llvm::Value *PromotedWidthMinusOne =
5163 (RHS == Ops.RHS) ? WidthMinusOne
5164 : GetMaximumShiftAmount(LHS: Ops.LHS, RHS, RHSIsSigned);
5165 CGF.EmitBlock(BB: CheckShiftBase);
5166 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
5167 LHS: Ops.LHS, RHS: Builder.CreateSub(LHS: PromotedWidthMinusOne, RHS, Name: "shl.zeros",
5168 /*NUW*/ HasNUW: true, /*NSW*/ HasNSW: true),
5169 Name: "shl.check");
5170 if (SanitizeUnsignedBase || CGF.getLangOpts().CPlusPlus) {
5171 // In C99, we are not permitted to shift a 1 bit into the sign bit.
5172 // Under C++11's rules, shifting a 1 bit into the sign bit is
5173 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
5174 // define signed left shifts, so we use the C99 and C++11 rules there).
5175 // Unsigned shifts can always shift into the top bit.
5176 llvm::Value *One = llvm::ConstantInt::get(Ty: BitsShiftedOff->getType(), V: 1);
5177 BitsShiftedOff = Builder.CreateLShr(LHS: BitsShiftedOff, RHS: One);
5178 }
5179 llvm::Value *Zero = llvm::ConstantInt::get(Ty: BitsShiftedOff->getType(), V: 0);
5180 llvm::Value *ValidBase = Builder.CreateICmpEQ(LHS: BitsShiftedOff, RHS: Zero);
5181 CGF.EmitBlock(BB: Cont);
5182 llvm::PHINode *BaseCheck = Builder.CreatePHI(Ty: ValidBase->getType(), NumReservedValues: 2);
5183 BaseCheck->addIncoming(V: Builder.getTrue(), BB: Orig);
5184 BaseCheck->addIncoming(V: ValidBase, BB: CheckShiftBase);
5185 Checks.push_back(Elt: std::make_pair(
5186 x&: BaseCheck, y: SanitizeSignedBase ? SanitizerKind::SO_ShiftBase
5187 : SanitizerKind::SO_UnsignedShiftBase));
5188 }
5189
5190 assert(!Checks.empty());
5191 EmitBinOpCheck(Checks, Info: Ops);
5192 }
5193
5194 return Builder.CreateShl(LHS: Ops.LHS, RHS, Name: "shl");
5195}
5196
5197Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
5198 // TODO: This misses out on the sanitizer check below.
5199 if (Ops.isFixedPointOp())
5200 return EmitFixedPointBinOp(op: Ops);
5201
5202 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
5203 // RHS to the same size as the LHS.
5204 Value *RHS = Ops.RHS;
5205 if (Ops.LHS->getType() != RHS->getType())
5206 RHS = Builder.CreateIntCast(V: RHS, DestTy: Ops.LHS->getType(), isSigned: false, Name: "sh_prom");
5207
5208 // OpenCL 6.3j: shift values are effectively % word size of LHS.
5209 if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL)
5210 RHS = ConstrainShiftValue(LHS: Ops.LHS, RHS, Name: "shr.mask");
5211 else if (CGF.SanOpts.has(K: SanitizerKind::ShiftExponent) &&
5212 isa<llvm::IntegerType>(Val: Ops.LHS->getType())) {
5213 SanitizerDebugLocation SanScope(&CGF, {SanitizerKind::SO_ShiftExponent},
5214 SanitizerHandler::ShiftOutOfBounds);
5215 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
5216 llvm::Value *Valid = Builder.CreateICmpULE(
5217 LHS: Ops.RHS, RHS: GetMaximumShiftAmount(LHS: Ops.LHS, RHS: Ops.RHS, RHSIsSigned));
5218 EmitBinOpCheck(Checks: std::make_pair(x&: Valid, y: SanitizerKind::SO_ShiftExponent), Info: Ops);
5219 }
5220
5221 if (Ops.Ty->hasUnsignedIntegerRepresentation())
5222 return Builder.CreateLShr(LHS: Ops.LHS, RHS, Name: "shr");
5223 return Builder.CreateAShr(LHS: Ops.LHS, RHS, Name: "shr");
5224}
5225
5226enum IntrinsicType { VCMPEQ, VCMPGT };
5227// return corresponding comparison intrinsic for given vector type
5228static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
5229 BuiltinType::Kind ElemKind) {
5230 switch (ElemKind) {
5231 default: llvm_unreachable("unexpected element type");
5232 case BuiltinType::Char_U:
5233 case BuiltinType::UChar:
5234 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
5235 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
5236 case BuiltinType::Char_S:
5237 case BuiltinType::SChar:
5238 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
5239 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
5240 case BuiltinType::UShort:
5241 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
5242 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
5243 case BuiltinType::Short:
5244 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
5245 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
5246 case BuiltinType::UInt:
5247 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
5248 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
5249 case BuiltinType::Int:
5250 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
5251 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
5252 case BuiltinType::ULong:
5253 case BuiltinType::ULongLong:
5254 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
5255 llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
5256 case BuiltinType::Long:
5257 case BuiltinType::LongLong:
5258 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
5259 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
5260 case BuiltinType::Float:
5261 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
5262 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
5263 case BuiltinType::Double:
5264 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
5265 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
5266 case BuiltinType::UInt128:
5267 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
5268 : llvm::Intrinsic::ppc_altivec_vcmpgtuq_p;
5269 case BuiltinType::Int128:
5270 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
5271 : llvm::Intrinsic::ppc_altivec_vcmpgtsq_p;
5272 }
5273}
5274
5275Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
5276 llvm::CmpInst::Predicate UICmpOpc,
5277 llvm::CmpInst::Predicate SICmpOpc,
5278 llvm::CmpInst::Predicate FCmpOpc,
5279 bool IsSignaling) {
5280 TestAndClearIgnoreResultAssign();
5281 Value *Result;
5282 QualType LHSTy = E->getLHS()->getType();
5283 QualType RHSTy = E->getRHS()->getType();
5284 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
5285 assert(E->getOpcode() == BO_EQ ||
5286 E->getOpcode() == BO_NE);
5287 Value *LHS = CGF.EmitScalarExpr(E: E->getLHS());
5288 Value *RHS = CGF.EmitScalarExpr(E: E->getRHS());
5289 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
5290 CGF, L: LHS, R: RHS, MPT, Inequality: E->getOpcode() == BO_NE);
5291 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
5292 BinOpInfo BOInfo = EmitBinOps(E);
5293 Value *LHS = BOInfo.LHS;
5294 Value *RHS = BOInfo.RHS;
5295
5296 // If AltiVec, the comparison results in a numeric type, so we use
5297 // intrinsics comparing vectors and giving 0 or 1 as a result
5298 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
5299 // constants for mapping CR6 register bits to predicate result
5300 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
5301
5302 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
5303
5304 // in several cases vector arguments order will be reversed
5305 Value *FirstVecArg = LHS,
5306 *SecondVecArg = RHS;
5307
5308 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
5309 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
5310
5311 switch(E->getOpcode()) {
5312 default: llvm_unreachable("is not a comparison operation");
5313 case BO_EQ:
5314 CR6 = CR6_LT;
5315 ID = GetIntrinsic(IT: VCMPEQ, ElemKind: ElementKind);
5316 break;
5317 case BO_NE:
5318 CR6 = CR6_EQ;
5319 ID = GetIntrinsic(IT: VCMPEQ, ElemKind: ElementKind);
5320 break;
5321 case BO_LT:
5322 CR6 = CR6_LT;
5323 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5324 std::swap(a&: FirstVecArg, b&: SecondVecArg);
5325 break;
5326 case BO_GT:
5327 CR6 = CR6_LT;
5328 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5329 break;
5330 case BO_LE:
5331 if (ElementKind == BuiltinType::Float) {
5332 CR6 = CR6_LT;
5333 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
5334 std::swap(a&: FirstVecArg, b&: SecondVecArg);
5335 }
5336 else {
5337 CR6 = CR6_EQ;
5338 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5339 }
5340 break;
5341 case BO_GE:
5342 if (ElementKind == BuiltinType::Float) {
5343 CR6 = CR6_LT;
5344 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
5345 }
5346 else {
5347 CR6 = CR6_EQ;
5348 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5349 std::swap(a&: FirstVecArg, b&: SecondVecArg);
5350 }
5351 break;
5352 }
5353
5354 Value *CR6Param = Builder.getInt32(C: CR6);
5355 llvm::Function *F = CGF.CGM.getIntrinsic(IID: ID);
5356 Result = Builder.CreateCall(Callee: F, Args: {CR6Param, FirstVecArg, SecondVecArg});
5357
5358 // The result type of intrinsic may not be same as E->getType().
5359 // If E->getType() is not BoolTy, EmitScalarConversion will do the
5360 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
5361 // do nothing, if ResultTy is not i1 at the same time, it will cause
5362 // crash later.
5363 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Val: Result->getType());
5364 if (ResultTy->getBitWidth() > 1 &&
5365 E->getType() == CGF.getContext().BoolTy)
5366 Result = Builder.CreateTrunc(V: Result, DestTy: Builder.getInt1Ty());
5367 return EmitScalarConversion(Src: Result, SrcType: CGF.getContext().BoolTy, DstType: E->getType(),
5368 Loc: E->getExprLoc());
5369 }
5370
5371 if (BOInfo.isFixedPointOp()) {
5372 Result = EmitFixedPointBinOp(op: BOInfo);
5373 } else if (LHS->getType()->isFPOrFPVectorTy()) {
5374 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures);
5375 if (!IsSignaling)
5376 Result = Builder.CreateFCmp(P: FCmpOpc, LHS, RHS, Name: "cmp");
5377 else
5378 Result = Builder.CreateFCmpS(P: FCmpOpc, LHS, RHS, Name: "cmp");
5379 } else if (LHSTy->hasSignedIntegerRepresentation()) {
5380 Result = Builder.CreateICmp(P: SICmpOpc, LHS, RHS, Name: "cmp");
5381 } else {
5382 // Unsigned integers and pointers.
5383 Result = Builder.CreateICmp(P: UICmpOpc, LHS, RHS, Name: "cmp");
5384 }
5385
5386 // If this is a vector comparison, sign extend the result to the appropriate
5387 // vector integer type and return it (don't convert to bool).
5388 if (LHSTy->isVectorType() || LHSTy->isSveVLSBuiltinType())
5389 return Builder.CreateSExt(V: Result, DestTy: ConvertType(T: E->getType()), Name: "sext");
5390
5391 if (LHSTy->isMatrixType())
5392 return Result;
5393
5394 } else {
5395 // Complex Comparison: can only be an equality comparison.
5396 CodeGenFunction::ComplexPairTy LHS, RHS;
5397 QualType CETy;
5398 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
5399 LHS = CGF.EmitComplexExpr(E: E->getLHS());
5400 CETy = CTy->getElementType();
5401 } else {
5402 LHS.first = Visit(E: E->getLHS());
5403 LHS.second = llvm::Constant::getNullValue(Ty: LHS.first->getType());
5404 CETy = LHSTy;
5405 }
5406 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
5407 RHS = CGF.EmitComplexExpr(E: E->getRHS());
5408 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
5409 CTy->getElementType()) &&
5410 "The element types must always match.");
5411 (void)CTy;
5412 } else {
5413 RHS.first = Visit(E: E->getRHS());
5414 RHS.second = llvm::Constant::getNullValue(Ty: RHS.first->getType());
5415 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
5416 "The element types must always match.");
5417 }
5418
5419 Value *ResultR, *ResultI;
5420 if (CETy->isRealFloatingType()) {
5421 // As complex comparisons can only be equality comparisons, they
5422 // are never signaling comparisons.
5423 ResultR = Builder.CreateFCmp(P: FCmpOpc, LHS: LHS.first, RHS: RHS.first, Name: "cmp.r");
5424 ResultI = Builder.CreateFCmp(P: FCmpOpc, LHS: LHS.second, RHS: RHS.second, Name: "cmp.i");
5425 } else {
5426 // Complex comparisons can only be equality comparisons. As such, signed
5427 // and unsigned opcodes are the same.
5428 ResultR = Builder.CreateICmp(P: UICmpOpc, LHS: LHS.first, RHS: RHS.first, Name: "cmp.r");
5429 ResultI = Builder.CreateICmp(P: UICmpOpc, LHS: LHS.second, RHS: RHS.second, Name: "cmp.i");
5430 }
5431
5432 if (E->getOpcode() == BO_EQ) {
5433 Result = Builder.CreateAnd(LHS: ResultR, RHS: ResultI, Name: "and.ri");
5434 } else {
5435 assert(E->getOpcode() == BO_NE &&
5436 "Complex comparison other than == or != ?");
5437 Result = Builder.CreateOr(LHS: ResultR, RHS: ResultI, Name: "or.ri");
5438 }
5439 }
5440
5441 return EmitScalarConversion(Src: Result, SrcType: CGF.getContext().BoolTy, DstType: E->getType(),
5442 Loc: E->getExprLoc());
5443}
5444
5445llvm::Value *CodeGenFunction::EmitWithOriginalRHSBitfieldAssignment(
5446 const BinaryOperator *E, Value **Previous, QualType *SrcType) {
5447 // In case we have the integer or bitfield sanitizer checks enabled
5448 // we want to get the expression before scalar conversion.
5449 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: E->getRHS())) {
5450 CastKind Kind = ICE->getCastKind();
5451 if (Kind == CK_IntegralCast || Kind == CK_LValueToRValue) {
5452 *SrcType = ICE->getSubExpr()->getType();
5453 *Previous = EmitScalarExpr(E: ICE->getSubExpr());
5454 // Pass default ScalarConversionOpts to avoid emitting
5455 // integer sanitizer checks as E refers to bitfield.
5456 return EmitScalarConversion(Src: *Previous, SrcTy: *SrcType, DstTy: ICE->getType(),
5457 Loc: ICE->getExprLoc());
5458 }
5459 }
5460 return EmitScalarExpr(E: E->getRHS());
5461}
5462
5463Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
5464 ApplyAtomGroup Grp(CGF.getDebugInfo());
5465 bool Ignore = TestAndClearIgnoreResultAssign();
5466
5467 Value *RHS;
5468 LValue LHS;
5469
5470 if (PointerAuthQualifier PtrAuth = E->getLHS()->getType().getPointerAuth()) {
5471 LValue LV = CGF.EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store);
5472 LV.getQuals().removePointerAuth();
5473 llvm::Value *RV =
5474 CGF.EmitPointerAuthQualify(Qualifier: PtrAuth, PointerExpr: E->getRHS(), StorageAddress: LV.getAddress());
5475 CGF.EmitNullabilityCheck(LHS: LV, RHS: RV, Loc: E->getExprLoc());
5476 CGF.EmitStoreThroughLValue(Src: RValue::get(V: RV), Dst: LV);
5477
5478 if (Ignore)
5479 return nullptr;
5480 RV = CGF.EmitPointerAuthUnqualify(Qualifier: PtrAuth, Pointer: RV, PointerType: LV.getType(),
5481 StorageAddress: LV.getAddress(), /*nonnull*/ IsKnownNonNull: false);
5482 return RV;
5483 }
5484
5485 switch (E->getLHS()->getType().getObjCLifetime()) {
5486 case Qualifiers::OCL_Strong:
5487 std::tie(args&: LHS, args&: RHS) = CGF.EmitARCStoreStrong(e: E, ignored: Ignore);
5488 break;
5489
5490 case Qualifiers::OCL_Autoreleasing:
5491 std::tie(args&: LHS, args&: RHS) = CGF.EmitARCStoreAutoreleasing(e: E);
5492 break;
5493
5494 case Qualifiers::OCL_ExplicitNone:
5495 std::tie(args&: LHS, args&: RHS) = CGF.EmitARCStoreUnsafeUnretained(e: E, ignored: Ignore);
5496 break;
5497
5498 case Qualifiers::OCL_Weak:
5499 RHS = Visit(E: E->getRHS());
5500 LHS = EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store);
5501 RHS = CGF.EmitARCStoreWeak(addr: LHS.getAddress(), value: RHS, ignored: Ignore);
5502 break;
5503
5504 case Qualifiers::OCL_None:
5505 // __block variables need to have the rhs evaluated first, plus
5506 // this should improve codegen just a little.
5507 Value *Previous = nullptr;
5508 QualType SrcType = E->getRHS()->getType();
5509 // Check if LHS is a bitfield, if RHS contains an implicit cast expression
5510 // we want to extract that value and potentially (if the bitfield sanitizer
5511 // is enabled) use it to check for an implicit conversion.
5512 if (E->getLHS()->refersToBitField())
5513 RHS = CGF.EmitWithOriginalRHSBitfieldAssignment(E, Previous: &Previous, SrcType: &SrcType);
5514 else
5515 RHS = Visit(E: E->getRHS());
5516
5517 LHS = EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store);
5518
5519 // Store the value into the LHS. Bit-fields are handled specially
5520 // because the result is altered by the store, i.e., [C99 6.5.16p1]
5521 // 'An assignment expression has the value of the left operand after
5522 // the assignment...'.
5523 if (LHS.isBitField()) {
5524 CGF.EmitStoreThroughBitfieldLValue(Src: RValue::get(V: RHS), Dst: LHS, Result: &RHS);
5525 // If the expression contained an implicit conversion, make sure
5526 // to use the value before the scalar conversion.
5527 Value *Src = Previous ? Previous : RHS;
5528 QualType DstType = E->getLHS()->getType();
5529 CGF.EmitBitfieldConversionCheck(Src, SrcType, Dst: RHS, DstType,
5530 Info: LHS.getBitFieldInfo(), Loc: E->getExprLoc());
5531 } else {
5532 CGF.EmitNullabilityCheck(LHS, RHS, Loc: E->getExprLoc());
5533 CGF.EmitStoreThroughLValue(Src: RValue::get(V: RHS), Dst: LHS);
5534 }
5535 }
5536 // OpenMP: Handle lastprivate(condition:) in scalar assignment
5537 if (CGF.getLangOpts().OpenMP) {
5538 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
5539 LHS: E->getLHS());
5540 }
5541
5542 // If the result is clearly ignored, return now.
5543 if (Ignore)
5544 return nullptr;
5545
5546 // The result of an assignment in C is the assigned r-value.
5547 if (!CGF.getLangOpts().CPlusPlus)
5548 return RHS;
5549
5550 // If the lvalue is non-volatile, return the computed value of the assignment.
5551 if (!LHS.isVolatileQualified())
5552 return RHS;
5553
5554 // Otherwise, reload the value.
5555 return EmitLoadOfLValue(LV: LHS, Loc: E->getExprLoc());
5556}
5557
5558Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
5559 auto HasLHSSkip = CGF.hasSkipCounter(S: E);
5560 auto HasRHSSkip = CGF.hasSkipCounter(S: E->getRHS());
5561
5562 // Perform vector logical and on comparisons with zero vectors.
5563 if (E->getType()->isVectorType()) {
5564 CGF.incrementProfileCounter(S: E);
5565
5566 Value *LHS = Visit(E: E->getLHS());
5567 Value *RHS = Visit(E: E->getRHS());
5568 Value *Zero = llvm::ConstantAggregateZero::get(Ty: LHS->getType());
5569 if (LHS->getType()->isFPOrFPVectorTy()) {
5570 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
5571 CGF, E->getFPFeaturesInEffect(LO: CGF.getLangOpts()));
5572 LHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS, RHS: Zero, Name: "cmp");
5573 RHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS: RHS, RHS: Zero, Name: "cmp");
5574 } else {
5575 LHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS, RHS: Zero, Name: "cmp");
5576 RHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS: RHS, RHS: Zero, Name: "cmp");
5577 }
5578 Value *And = Builder.CreateAnd(LHS, RHS);
5579 return Builder.CreateSExt(V: And, DestTy: ConvertType(T: E->getType()), Name: "sext");
5580 }
5581
5582 bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
5583 llvm::Type *ResTy = ConvertType(T: E->getType());
5584
5585 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
5586 // If we have 1 && X, just emit X without inserting the control flow.
5587 bool LHSCondVal;
5588 if (CGF.ConstantFoldsToSimpleInteger(Cond: E->getLHS(), Result&: LHSCondVal)) {
5589 if (LHSCondVal) { // If we have 1 && X, just emit X.
5590 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E, /*UseBoth=*/true);
5591
5592 // If the top of the logical operator nest, reset the MCDC temp to 0.
5593 if (CGF.isMCDCDecisionExpr(E))
5594 CGF.maybeResetMCDCCondBitmap(E);
5595
5596 Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS());
5597
5598 // If we're generating for profiling or coverage, generate a branch to a
5599 // block that increments the RHS counter needed to track branch condition
5600 // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
5601 // "FalseBlock" after the increment is done.
5602 if (InstrumentRegions &&
5603 CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) {
5604 CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond);
5605 llvm::BasicBlock *FBlock = CGF.createBasicBlock(name: "land.end");
5606 llvm::BasicBlock *RHSSkip =
5607 (HasRHSSkip ? CGF.createBasicBlock(name: "land.rhsskip") : FBlock);
5608 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "land.rhscnt");
5609 Builder.CreateCondBr(Cond: RHSCond, True: RHSBlockCnt, False: RHSSkip);
5610 CGF.EmitBlock(BB: RHSBlockCnt);
5611 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS());
5612 CGF.EmitBranch(Block: FBlock);
5613 if (HasRHSSkip) {
5614 CGF.EmitBlock(BB: RHSSkip);
5615 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS());
5616 }
5617 CGF.EmitBlock(BB: FBlock);
5618 } else
5619 CGF.markStmtMaybeUsed(S: E->getRHS());
5620
5621 // If the top of the logical operator nest, update the MCDC bitmap.
5622 if (CGF.isMCDCDecisionExpr(E))
5623 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5624
5625 // ZExt result to int or bool.
5626 return Builder.CreateZExtOrBitCast(V: RHSCond, DestTy: ResTy, Name: "land.ext");
5627 }
5628
5629 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
5630 if (!CGF.ContainsLabel(S: E->getRHS())) {
5631 CGF.markStmtAsUsed(Skipped: false, S: E);
5632 if (HasLHSSkip)
5633 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E);
5634
5635 CGF.markStmtMaybeUsed(S: E->getRHS());
5636
5637 return llvm::Constant::getNullValue(Ty: ResTy);
5638 }
5639 }
5640
5641 // If the top of the logical operator nest, reset the MCDC temp to 0.
5642 if (CGF.isMCDCDecisionExpr(E))
5643 CGF.maybeResetMCDCCondBitmap(E);
5644
5645 llvm::BasicBlock *ContBlock = CGF.createBasicBlock(name: "land.end");
5646 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock(name: "land.rhs");
5647
5648 llvm::BasicBlock *LHSFalseBlock =
5649 (HasLHSSkip ? CGF.createBasicBlock(name: "land.lhsskip") : ContBlock);
5650
5651 CodeGenFunction::ConditionalEvaluation eval(CGF);
5652
5653 // Branch on the LHS first. If it is false, go to the failure (cont) block.
5654 CGF.EmitBranchOnBoolExpr(Cond: E->getLHS(), TrueBlock: RHSBlock, FalseBlock: LHSFalseBlock,
5655 TrueCount: CGF.getProfileCount(S: E->getRHS()));
5656
5657 if (HasLHSSkip) {
5658 CGF.EmitBlock(BB: LHSFalseBlock);
5659 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E);
5660 CGF.EmitBranch(Block: ContBlock);
5661 }
5662
5663 // Any edges into the ContBlock are now from an (indeterminate number of)
5664 // edges from this first condition. All of these values will be false. Start
5665 // setting up the PHI node in the Cont Block for this.
5666 llvm::PHINode *PN = llvm::PHINode::Create(Ty: llvm::Type::getInt1Ty(C&: VMContext), NumReservedValues: 2,
5667 NameStr: "", InsertBefore: ContBlock);
5668 for (llvm::pred_iterator PI = pred_begin(BB: ContBlock), PE = pred_end(BB: ContBlock);
5669 PI != PE; ++PI)
5670 PN->addIncoming(V: llvm::ConstantInt::getFalse(Context&: VMContext), BB: *PI);
5671
5672 eval.begin(CGF);
5673 CGF.EmitBlock(BB: RHSBlock);
5674 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E);
5675 Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS());
5676 eval.end(CGF);
5677
5678 // Reaquire the RHS block, as there may be subblocks inserted.
5679 RHSBlock = Builder.GetInsertBlock();
5680
5681 // If we're generating for profiling or coverage, generate a branch on the
5682 // RHS to a block that increments the RHS true counter needed to track branch
5683 // condition coverage.
5684 llvm::BasicBlock *ContIncoming = RHSBlock;
5685 if (InstrumentRegions &&
5686 CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) {
5687 CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond);
5688 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "land.rhscnt");
5689 llvm::BasicBlock *RHSBlockSkip =
5690 (HasRHSSkip ? CGF.createBasicBlock(name: "land.rhsskip") : ContBlock);
5691 Builder.CreateCondBr(Cond: RHSCond, True: RHSBlockCnt, False: RHSBlockSkip);
5692 CGF.EmitBlock(BB: RHSBlockCnt);
5693 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS());
5694 CGF.EmitBranch(Block: ContBlock);
5695 PN->addIncoming(V: RHSCond, BB: RHSBlockCnt);
5696 if (HasRHSSkip) {
5697 CGF.EmitBlock(BB: RHSBlockSkip);
5698 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS());
5699 CGF.EmitBranch(Block: ContBlock);
5700 ContIncoming = RHSBlockSkip;
5701 }
5702 }
5703
5704 // Emit an unconditional branch from this block to ContBlock.
5705 {
5706 // There is no need to emit line number for unconditional branch.
5707 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
5708 CGF.EmitBlock(BB: ContBlock);
5709 }
5710 // Insert an entry into the phi node for the edge with the value of RHSCond.
5711 PN->addIncoming(V: RHSCond, BB: ContIncoming);
5712
5713 // If the top of the logical operator nest, update the MCDC bitmap.
5714 if (CGF.isMCDCDecisionExpr(E))
5715 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5716
5717 // Artificial location to preserve the scope information
5718 {
5719 auto NL = ApplyDebugLocation::CreateArtificial(CGF);
5720 PN->setDebugLoc(Builder.getCurrentDebugLocation());
5721 }
5722
5723 // ZExt result to int.
5724 return Builder.CreateZExtOrBitCast(V: PN, DestTy: ResTy, Name: "land.ext");
5725}
5726
5727Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
5728 auto HasLHSSkip = CGF.hasSkipCounter(S: E);
5729 auto HasRHSSkip = CGF.hasSkipCounter(S: E->getRHS());
5730
5731 // Perform vector logical or on comparisons with zero vectors.
5732 if (E->getType()->isVectorType()) {
5733 CGF.incrementProfileCounter(S: E);
5734
5735 Value *LHS = Visit(E: E->getLHS());
5736 Value *RHS = Visit(E: E->getRHS());
5737 Value *Zero = llvm::ConstantAggregateZero::get(Ty: LHS->getType());
5738 if (LHS->getType()->isFPOrFPVectorTy()) {
5739 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
5740 CGF, E->getFPFeaturesInEffect(LO: CGF.getLangOpts()));
5741 LHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS, RHS: Zero, Name: "cmp");
5742 RHS = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_UNE, LHS: RHS, RHS: Zero, Name: "cmp");
5743 } else {
5744 LHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS, RHS: Zero, Name: "cmp");
5745 RHS = Builder.CreateICmp(P: llvm::CmpInst::ICMP_NE, LHS: RHS, RHS: Zero, Name: "cmp");
5746 }
5747 Value *Or = Builder.CreateOr(LHS, RHS);
5748 return Builder.CreateSExt(V: Or, DestTy: ConvertType(T: E->getType()), Name: "sext");
5749 }
5750
5751 bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
5752 llvm::Type *ResTy = ConvertType(T: E->getType());
5753
5754 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
5755 // If we have 0 || X, just emit X without inserting the control flow.
5756 bool LHSCondVal;
5757 if (CGF.ConstantFoldsToSimpleInteger(Cond: E->getLHS(), Result&: LHSCondVal)) {
5758 if (!LHSCondVal) { // If we have 0 || X, just emit X.
5759 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E, /*UseBoth=*/true);
5760
5761 // If the top of the logical operator nest, reset the MCDC temp to 0.
5762 if (CGF.isMCDCDecisionExpr(E))
5763 CGF.maybeResetMCDCCondBitmap(E);
5764
5765 Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS());
5766
5767 // If we're generating for profiling or coverage, generate a branch to a
5768 // block that increments the RHS counter need to track branch condition
5769 // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
5770 // "FalseBlock" after the increment is done.
5771 if (InstrumentRegions &&
5772 CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) {
5773 CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond);
5774 llvm::BasicBlock *FBlock = CGF.createBasicBlock(name: "lor.end");
5775 llvm::BasicBlock *RHSSkip =
5776 (HasRHSSkip ? CGF.createBasicBlock(name: "lor.rhsskip") : FBlock);
5777 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "lor.rhscnt");
5778 Builder.CreateCondBr(Cond: RHSCond, True: RHSSkip, False: RHSBlockCnt);
5779 CGF.EmitBlock(BB: RHSBlockCnt);
5780 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS());
5781 CGF.EmitBranch(Block: FBlock);
5782 if (HasRHSSkip) {
5783 CGF.EmitBlock(BB: RHSSkip);
5784 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS());
5785 }
5786 CGF.EmitBlock(BB: FBlock);
5787 } else
5788 CGF.markStmtMaybeUsed(S: E->getRHS());
5789
5790 // If the top of the logical operator nest, update the MCDC bitmap.
5791 if (CGF.isMCDCDecisionExpr(E))
5792 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5793
5794 // ZExt result to int or bool.
5795 return Builder.CreateZExtOrBitCast(V: RHSCond, DestTy: ResTy, Name: "lor.ext");
5796 }
5797
5798 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
5799 if (!CGF.ContainsLabel(S: E->getRHS())) {
5800 CGF.markStmtAsUsed(Skipped: false, S: E);
5801 if (HasLHSSkip)
5802 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E);
5803
5804 CGF.markStmtMaybeUsed(S: E->getRHS());
5805
5806 return llvm::ConstantInt::get(Ty: ResTy, V: 1);
5807 }
5808 }
5809
5810 // If the top of the logical operator nest, reset the MCDC temp to 0.
5811 if (CGF.isMCDCDecisionExpr(E))
5812 CGF.maybeResetMCDCCondBitmap(E);
5813
5814 llvm::BasicBlock *ContBlock = CGF.createBasicBlock(name: "lor.end");
5815 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock(name: "lor.rhs");
5816 llvm::BasicBlock *LHSTrueBlock =
5817 (HasLHSSkip ? CGF.createBasicBlock(name: "lor.lhsskip") : ContBlock);
5818
5819 CodeGenFunction::ConditionalEvaluation eval(CGF);
5820
5821 // Branch on the LHS first. If it is true, go to the success (cont) block.
5822 CGF.EmitBranchOnBoolExpr(Cond: E->getLHS(), TrueBlock: LHSTrueBlock, FalseBlock: RHSBlock,
5823 TrueCount: CGF.getCurrentProfileCount() -
5824 CGF.getProfileCount(S: E->getRHS()));
5825
5826 if (HasLHSSkip) {
5827 CGF.EmitBlock(BB: LHSTrueBlock);
5828 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E);
5829 CGF.EmitBranch(Block: ContBlock);
5830 }
5831
5832 // Any edges into the ContBlock are now from an (indeterminate number of)
5833 // edges from this first condition. All of these values will be true. Start
5834 // setting up the PHI node in the Cont Block for this.
5835 llvm::PHINode *PN = llvm::PHINode::Create(Ty: llvm::Type::getInt1Ty(C&: VMContext), NumReservedValues: 2,
5836 NameStr: "", InsertBefore: ContBlock);
5837 for (llvm::pred_iterator PI = pred_begin(BB: ContBlock), PE = pred_end(BB: ContBlock);
5838 PI != PE; ++PI)
5839 PN->addIncoming(V: llvm::ConstantInt::getTrue(Context&: VMContext), BB: *PI);
5840
5841 eval.begin(CGF);
5842
5843 // Emit the RHS condition as a bool value.
5844 CGF.EmitBlock(BB: RHSBlock);
5845 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E);
5846 Value *RHSCond = CGF.EvaluateExprAsBool(E: E->getRHS());
5847
5848 eval.end(CGF);
5849
5850 // Reaquire the RHS block, as there may be subblocks inserted.
5851 RHSBlock = Builder.GetInsertBlock();
5852
5853 // If we're generating for profiling or coverage, generate a branch on the
5854 // RHS to a block that increments the RHS true counter needed to track branch
5855 // condition coverage.
5856 llvm::BasicBlock *ContIncoming = RHSBlock;
5857 if (InstrumentRegions &&
5858 CodeGenFunction::isInstrumentedCondition(C: E->getRHS())) {
5859 CGF.maybeUpdateMCDCCondBitmap(E: E->getRHS(), Val: RHSCond);
5860 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock(name: "lor.rhscnt");
5861 llvm::BasicBlock *RHSTrueBlock =
5862 (HasRHSSkip ? CGF.createBasicBlock(name: "lor.rhsskip") : ContBlock);
5863 Builder.CreateCondBr(Cond: RHSCond, True: RHSTrueBlock, False: RHSBlockCnt);
5864 CGF.EmitBlock(BB: RHSBlockCnt);
5865 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E->getRHS());
5866 CGF.EmitBranch(Block: ContBlock);
5867 PN->addIncoming(V: RHSCond, BB: RHSBlockCnt);
5868 if (HasRHSSkip) {
5869 CGF.EmitBlock(BB: RHSTrueBlock);
5870 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E->getRHS());
5871 CGF.EmitBranch(Block: ContBlock);
5872 ContIncoming = RHSTrueBlock;
5873 }
5874 }
5875
5876 // Emit an unconditional branch from this block to ContBlock. Insert an entry
5877 // into the phi node for the edge with the value of RHSCond.
5878 CGF.EmitBlock(BB: ContBlock);
5879 PN->addIncoming(V: RHSCond, BB: ContIncoming);
5880
5881 // If the top of the logical operator nest, update the MCDC bitmap.
5882 if (CGF.isMCDCDecisionExpr(E))
5883 CGF.maybeUpdateMCDCTestVectorBitmap(E);
5884
5885 // ZExt result to int.
5886 return Builder.CreateZExtOrBitCast(V: PN, DestTy: ResTy, Name: "lor.ext");
5887}
5888
5889Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
5890 CGF.EmitIgnoredExpr(E: E->getLHS());
5891 CGF.EnsureInsertPoint();
5892 return Visit(E: E->getRHS());
5893}
5894
5895//===----------------------------------------------------------------------===//
5896// Other Operators
5897//===----------------------------------------------------------------------===//
5898
5899Value *ScalarExprEmitter::
5900VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
5901 TestAndClearIgnoreResultAssign();
5902
5903 // Bind the common expression if necessary.
5904 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
5905
5906 Expr *condExpr = E->getCond();
5907 Expr *lhsExpr = E->getTrueExpr();
5908 Expr *rhsExpr = E->getFalseExpr();
5909
5910 // If the condition constant folds and can be elided, try to avoid emitting
5911 // the condition and the dead arm.
5912 bool CondExprBool;
5913 if (CGF.ConstantFoldsToSimpleInteger(Cond: condExpr, Result&: CondExprBool)) {
5914 Expr *live = lhsExpr, *dead = rhsExpr;
5915 if (!CondExprBool) std::swap(a&: live, b&: dead);
5916
5917 // If the dead side doesn't have labels we need, just emit the Live part.
5918 if (!CGF.ContainsLabel(S: dead)) {
5919 CGF.incrementProfileCounter(ExecSkip: CondExprBool ? CGF.UseExecPath
5920 : CGF.UseSkipPath,
5921 S: E, /*UseBoth=*/true);
5922 Value *Result = Visit(E: live);
5923 CGF.markStmtMaybeUsed(S: dead);
5924
5925 // If the live part is a throw expression, it acts like it has a void
5926 // type, so evaluating it returns a null Value*. However, a conditional
5927 // with non-void type must return a non-null Value*.
5928 if (!Result && !E->getType()->isVoidType())
5929 Result = llvm::UndefValue::get(T: CGF.ConvertType(T: E->getType()));
5930
5931 return Result;
5932 }
5933 }
5934
5935 // OpenCL: If the condition is a vector, we can treat this condition like
5936 // the select function.
5937 if (CGF.getLangOpts().OpenCL && (condExpr->getType()->isVectorType() ||
5938 condExpr->getType()->isExtVectorType())) {
5939 CGF.incrementProfileCounter(S: E);
5940
5941 llvm::Value *CondV = CGF.EmitScalarExpr(E: condExpr);
5942 llvm::Value *LHS = Visit(E: lhsExpr);
5943 llvm::Value *RHS = Visit(E: rhsExpr);
5944
5945 llvm::Type *condType = ConvertType(T: condExpr->getType());
5946 auto *vecTy = cast<llvm::FixedVectorType>(Val: condType);
5947
5948 unsigned numElem = vecTy->getNumElements();
5949 llvm::Type *elemType = vecTy->getElementType();
5950
5951 llvm::Value *zeroVec = llvm::Constant::getNullValue(Ty: vecTy);
5952 llvm::Value *TestMSB = Builder.CreateICmpSLT(LHS: CondV, RHS: zeroVec);
5953 llvm::Value *tmp = Builder.CreateSExt(
5954 V: TestMSB, DestTy: llvm::FixedVectorType::get(ElementType: elemType, NumElts: numElem), Name: "sext");
5955 llvm::Value *tmp2 = Builder.CreateNot(V: tmp);
5956
5957 // Cast float to int to perform ANDs if necessary.
5958 llvm::Value *RHSTmp = RHS;
5959 llvm::Value *LHSTmp = LHS;
5960 bool wasCast = false;
5961 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(Val: RHS->getType());
5962 if (rhsVTy->getElementType()->isFloatingPointTy()) {
5963 RHSTmp = Builder.CreateBitCast(V: RHS, DestTy: tmp2->getType());
5964 LHSTmp = Builder.CreateBitCast(V: LHS, DestTy: tmp->getType());
5965 wasCast = true;
5966 }
5967
5968 llvm::Value *tmp3 = Builder.CreateAnd(LHS: RHSTmp, RHS: tmp2);
5969 llvm::Value *tmp4 = Builder.CreateAnd(LHS: LHSTmp, RHS: tmp);
5970 llvm::Value *tmp5 = Builder.CreateOr(LHS: tmp3, RHS: tmp4, Name: "cond");
5971 if (wasCast)
5972 tmp5 = Builder.CreateBitCast(V: tmp5, DestTy: RHS->getType());
5973
5974 return tmp5;
5975 }
5976
5977 if (condExpr->getType()->isVectorType() ||
5978 condExpr->getType()->isSveVLSBuiltinType()) {
5979 CGF.incrementProfileCounter(S: E);
5980
5981 llvm::Value *CondV = CGF.EmitScalarExpr(E: condExpr);
5982 llvm::Value *LHS = Visit(E: lhsExpr);
5983 llvm::Value *RHS = Visit(E: rhsExpr);
5984
5985 llvm::Type *CondType = ConvertType(T: condExpr->getType());
5986 auto *VecTy = cast<llvm::VectorType>(Val: CondType);
5987
5988 if (VecTy->getElementType()->isIntegerTy(BitWidth: 1))
5989 return Builder.CreateSelect(C: CondV, True: LHS, False: RHS, Name: "vector_select");
5990
5991 // OpenCL uses the MSB of the mask vector.
5992 llvm::Value *ZeroVec = llvm::Constant::getNullValue(Ty: VecTy);
5993 if (condExpr->getType()->isExtVectorType())
5994 CondV = Builder.CreateICmpSLT(LHS: CondV, RHS: ZeroVec, Name: "vector_cond");
5995 else
5996 CondV = Builder.CreateICmpNE(LHS: CondV, RHS: ZeroVec, Name: "vector_cond");
5997 return Builder.CreateSelect(C: CondV, True: LHS, False: RHS, Name: "vector_select");
5998 }
5999
6000 // If this is a really simple expression (like x ? 4 : 5), emit this as a
6001 // select instead of as control flow. We can only do this if it is cheap and
6002 // safe to evaluate the LHS and RHS unconditionally.
6003 if (!llvm::EnableSingleByteCoverage &&
6004 CodeGenUtils::isCheapEnoughToEvaluateUnconditionally(E: lhsExpr,
6005 Ctx: CGF.getContext()) &&
6006 CodeGenUtils::isCheapEnoughToEvaluateUnconditionally(E: rhsExpr,
6007 Ctx: CGF.getContext())) {
6008 llvm::Value *CondV = CGF.EvaluateExprAsBool(E: condExpr);
6009 llvm::Value *StepV = Builder.CreateZExtOrBitCast(V: CondV, DestTy: CGF.Int64Ty);
6010
6011 CGF.incrementProfileCounter(S: E, StepV);
6012
6013 llvm::Value *LHS = Visit(E: lhsExpr);
6014 llvm::Value *RHS = Visit(E: rhsExpr);
6015 if (!LHS) {
6016 // If the conditional has void type, make sure we return a null Value*.
6017 assert(!RHS && "LHS and RHS types must match");
6018 return nullptr;
6019 }
6020 return Builder.CreateSelect(C: CondV, True: LHS, False: RHS, Name: "cond");
6021 }
6022
6023 // If the top of the logical operator nest, reset the MCDC temp to 0.
6024 if (auto E = CGF.stripCond(C: condExpr); CGF.isMCDCDecisionExpr(E))
6025 CGF.maybeResetMCDCCondBitmap(E);
6026
6027 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock(name: "cond.true");
6028 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock(name: "cond.false");
6029 llvm::BasicBlock *ContBlock = CGF.createBasicBlock(name: "cond.end");
6030
6031 CodeGenFunction::ConditionalEvaluation eval(CGF);
6032 CGF.EmitBranchOnBoolExpr(Cond: condExpr, TrueBlock: LHSBlock, FalseBlock: RHSBlock,
6033 TrueCount: CGF.getProfileCount(S: lhsExpr));
6034
6035 CGF.EmitBlock(BB: LHSBlock);
6036
6037 // If the top of the logical operator nest, update the MCDC bitmap for the
6038 // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
6039 // may also contain a boolean expression.
6040 if (auto E = CGF.stripCond(C: condExpr); CGF.isMCDCDecisionExpr(E))
6041 CGF.maybeUpdateMCDCTestVectorBitmap(E);
6042
6043 CGF.incrementProfileCounter(ExecSkip: CGF.UseExecPath, S: E);
6044 eval.begin(CGF);
6045 Value *LHS = Visit(E: lhsExpr);
6046 eval.end(CGF);
6047
6048 LHSBlock = Builder.GetInsertBlock();
6049 Builder.CreateBr(Dest: ContBlock);
6050
6051 CGF.EmitBlock(BB: RHSBlock);
6052
6053 // If the top of the logical operator nest, update the MCDC bitmap for the
6054 // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
6055 // may also contain a boolean expression.
6056 if (auto E = CGF.stripCond(C: condExpr); CGF.isMCDCDecisionExpr(E))
6057 CGF.maybeUpdateMCDCTestVectorBitmap(E);
6058
6059 CGF.incrementProfileCounter(ExecSkip: CGF.UseSkipPath, S: E);
6060 eval.begin(CGF);
6061 Value *RHS = Visit(E: rhsExpr);
6062 eval.end(CGF);
6063
6064 RHSBlock = Builder.GetInsertBlock();
6065 CGF.EmitBlock(BB: ContBlock);
6066
6067 // If the LHS or RHS is a throw expression, it will be legitimately null.
6068 if (!LHS)
6069 return RHS;
6070 if (!RHS)
6071 return LHS;
6072
6073 // Create a PHI node for the real part.
6074 llvm::PHINode *PN = Builder.CreatePHI(Ty: LHS->getType(), NumReservedValues: 2, Name: "cond");
6075 PN->addIncoming(V: LHS, BB: LHSBlock);
6076 PN->addIncoming(V: RHS, BB: RHSBlock);
6077
6078 return PN;
6079}
6080
6081Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
6082 return Visit(E: E->getChosenSubExpr());
6083}
6084
6085Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
6086 Address ArgValue = Address::invalid();
6087 RValue ArgPtr = CGF.EmitVAArg(VE, VAListAddr&: ArgValue);
6088
6089 return ArgPtr.getScalarVal();
6090}
6091
6092Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
6093 return CGF.EmitBlockLiteral(block);
6094}
6095
6096// Convert a vec3 to vec4, or vice versa.
6097static Value *ConvertVec3AndVec4(CGBuilderTy &Builder, CodeGenFunction &CGF,
6098 Value *Src, unsigned NumElementsDst) {
6099 static constexpr int Mask[] = {0, 1, 2, -1};
6100 return Builder.CreateShuffleVector(V: Src, Mask: llvm::ArrayRef(Mask, NumElementsDst));
6101}
6102
6103// Create cast instructions for converting LLVM value \p Src to LLVM type \p
6104// DstTy. \p Src has the same size as \p DstTy. Both are single value types
6105// but could be scalar or vectors of different lengths, and either can be
6106// pointer.
6107// There are 4 cases:
6108// 1. non-pointer -> non-pointer : needs 1 bitcast
6109// 2. pointer -> pointer : needs 1 bitcast or addrspacecast
6110// 3. pointer -> non-pointer
6111// a) pointer -> intptr_t : needs 1 ptrtoint
6112// b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
6113// 4. non-pointer -> pointer
6114// a) intptr_t -> pointer : needs 1 inttoptr
6115// b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
6116// Note: for cases 3b and 4b two casts are required since LLVM casts do not
6117// allow casting directly between pointer types and non-integer non-pointer
6118// types.
6119static Value *createCastsForTypeOfSameSize(CGBuilderTy &Builder,
6120 const llvm::DataLayout &DL,
6121 Value *Src, llvm::Type *DstTy,
6122 StringRef Name = "") {
6123 auto SrcTy = Src->getType();
6124
6125 // Case 1.
6126 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
6127 return Builder.CreateBitCast(V: Src, DestTy: DstTy, Name);
6128
6129 // Case 2.
6130 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
6131 return Builder.CreatePointerBitCastOrAddrSpaceCast(V: Src, DestTy: DstTy, Name);
6132
6133 // Case 3.
6134 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
6135 // Case 3b.
6136 if (!DstTy->isIntegerTy())
6137 Src = Builder.CreatePtrToInt(V: Src, DestTy: DL.getIntPtrType(SrcTy));
6138 // Cases 3a and 3b.
6139 return Builder.CreateBitOrPointerCast(V: Src, DestTy: DstTy, Name);
6140 }
6141
6142 // Case 4b.
6143 if (!SrcTy->isIntegerTy())
6144 Src = Builder.CreateBitCast(V: Src, DestTy: DL.getIntPtrType(DstTy));
6145 // Cases 4a and 4b.
6146 return Builder.CreateIntToPtr(V: Src, DestTy: DstTy, Name);
6147}
6148
6149Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
6150 Value *Src = CGF.EmitScalarExpr(E: E->getSrcExpr());
6151 llvm::Type *DstTy = ConvertType(T: E->getType());
6152
6153 llvm::Type *SrcTy = Src->getType();
6154 unsigned NumElementsSrc =
6155 isa<llvm::VectorType>(Val: SrcTy)
6156 ? cast<llvm::FixedVectorType>(Val: SrcTy)->getNumElements()
6157 : 0;
6158 unsigned NumElementsDst =
6159 isa<llvm::VectorType>(Val: DstTy)
6160 ? cast<llvm::FixedVectorType>(Val: DstTy)->getNumElements()
6161 : 0;
6162
6163 // Use bit vector expansion for ext_vector_type boolean vectors.
6164 if (E->getType()->isExtVectorBoolType())
6165 return CGF.emitBoolVecConversion(SrcVec: Src, NumElementsDst, Name: "astype");
6166
6167 // Going from vec3 to non-vec3 is a special case and requires a shuffle
6168 // vector to get a vec4, then a bitcast if the target type is different.
6169 if (NumElementsSrc == 3 && NumElementsDst != 3) {
6170 Src = ConvertVec3AndVec4(Builder, CGF, Src, NumElementsDst: 4);
6171 Src = createCastsForTypeOfSameSize(Builder, DL: CGF.CGM.getDataLayout(), Src,
6172 DstTy);
6173
6174 Src->setName("astype");
6175 return Src;
6176 }
6177
6178 // Going from non-vec3 to vec3 is a special case and requires a bitcast
6179 // to vec4 if the original type is not vec4, then a shuffle vector to
6180 // get a vec3.
6181 if (NumElementsSrc != 3 && NumElementsDst == 3) {
6182 auto *Vec4Ty = llvm::FixedVectorType::get(
6183 ElementType: cast<llvm::VectorType>(Val: DstTy)->getElementType(), NumElts: 4);
6184 Src = createCastsForTypeOfSameSize(Builder, DL: CGF.CGM.getDataLayout(), Src,
6185 DstTy: Vec4Ty);
6186
6187 Src = ConvertVec3AndVec4(Builder, CGF, Src, NumElementsDst: 3);
6188 Src->setName("astype");
6189 return Src;
6190 }
6191
6192 return createCastsForTypeOfSameSize(Builder, DL: CGF.CGM.getDataLayout(),
6193 Src, DstTy, Name: "astype");
6194}
6195
6196Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
6197 return CGF.EmitAtomicExpr(E).getScalarVal();
6198}
6199
6200//===----------------------------------------------------------------------===//
6201// Entry Point into this File
6202//===----------------------------------------------------------------------===//
6203
6204/// Emit the computation of the specified expression of scalar type, ignoring
6205/// the result.
6206Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
6207 assert(E && hasScalarEvaluationKind(E->getType()) &&
6208 "Invalid scalar expression to emit");
6209
6210 return ScalarExprEmitter(*this, IgnoreResultAssign)
6211 .Visit(E: const_cast<Expr *>(E));
6212}
6213
6214/// Emit a conversion from the specified type to the specified destination type,
6215/// both of which are LLVM scalar types.
6216Value *CodeGenFunction::EmitScalarConversion(Value *Src, QualType SrcTy,
6217 QualType DstTy,
6218 SourceLocation Loc) {
6219 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
6220 "Invalid scalar expression to emit");
6221 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcType: SrcTy, DstType: DstTy, Loc);
6222}
6223
6224/// Emit a conversion from the specified complex type to the specified
6225/// destination type, where the destination type is an LLVM scalar type.
6226Value *CodeGenFunction::EmitComplexToScalarConversion(ComplexPairTy Src,
6227 QualType SrcTy,
6228 QualType DstTy,
6229 SourceLocation Loc) {
6230 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
6231 "Invalid complex -> scalar conversion");
6232 return ScalarExprEmitter(*this)
6233 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
6234}
6235
6236
6237Value *
6238CodeGenFunction::EmitPromotedScalarExpr(const Expr *E,
6239 QualType PromotionType) {
6240 if (!PromotionType.isNull())
6241 return ScalarExprEmitter(*this).EmitPromoted(E, PromotionType);
6242 else
6243 return ScalarExprEmitter(*this).Visit(E: const_cast<Expr *>(E));
6244}
6245
6246
6247llvm::Value *CodeGenFunction::
6248EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
6249 bool isInc, bool isPre) {
6250 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
6251}
6252
6253LValue CodeGenFunction::EmitObjCIsaExpr(const ObjCIsaExpr *E) {
6254 // object->isa or (*object).isa
6255 // Generate code as for: *(Class*)object
6256
6257 Expr *BaseExpr = E->getBase();
6258 Address Addr = Address::invalid();
6259 if (BaseExpr->isPRValue()) {
6260 llvm::Type *BaseTy =
6261 ConvertTypeForMem(T: BaseExpr->getType()->getPointeeType());
6262 Addr = Address(EmitScalarExpr(E: BaseExpr), BaseTy, getPointerAlign());
6263 } else {
6264 Addr = EmitLValue(E: BaseExpr).getAddress();
6265 }
6266
6267 // Cast the address to Class*.
6268 Addr = Addr.withElementType(ElemTy: ConvertType(T: E->getType()));
6269 return MakeAddrLValue(Addr, T: E->getType());
6270}
6271
6272
6273LValue CodeGenFunction::EmitCompoundAssignmentLValue(
6274 const CompoundAssignOperator *E) {
6275 ApplyAtomGroup Grp(getDebugInfo());
6276 ScalarExprEmitter Scalar(*this);
6277 Value *Result = nullptr;
6278 switch (E->getOpcode()) {
6279#define COMPOUND_OP(Op) \
6280 case BO_##Op##Assign: \
6281 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
6282 Result)
6283 COMPOUND_OP(Mul);
6284 COMPOUND_OP(Div);
6285 COMPOUND_OP(Rem);
6286 COMPOUND_OP(Add);
6287 COMPOUND_OP(Sub);
6288 COMPOUND_OP(Shl);
6289 COMPOUND_OP(Shr);
6290 COMPOUND_OP(And);
6291 COMPOUND_OP(Xor);
6292 COMPOUND_OP(Or);
6293#undef COMPOUND_OP
6294
6295 case BO_PtrMemD:
6296 case BO_PtrMemI:
6297 case BO_Mul:
6298 case BO_Div:
6299 case BO_Rem:
6300 case BO_Add:
6301 case BO_Sub:
6302 case BO_Shl:
6303 case BO_Shr:
6304 case BO_LT:
6305 case BO_GT:
6306 case BO_LE:
6307 case BO_GE:
6308 case BO_EQ:
6309 case BO_NE:
6310 case BO_Cmp:
6311 case BO_And:
6312 case BO_Xor:
6313 case BO_Or:
6314 case BO_LAnd:
6315 case BO_LOr:
6316 case BO_Assign:
6317 case BO_Comma:
6318 llvm_unreachable("Not valid compound assignment operators");
6319 }
6320
6321 llvm_unreachable("Unhandled compound assignment operator");
6322}
6323
6324struct GEPOffsetAndOverflow {
6325 // The total (signed) byte offset for the GEP.
6326 llvm::Value *TotalOffset;
6327 // The offset overflow flag - true if the total offset overflows.
6328 llvm::Value *OffsetOverflows;
6329};
6330
6331/// Compute the total offset in bytes that indexing BasePtr with ElemTy and
6332/// IdxList applies, using checked arithmetic.
6333/// Returns offset in bytes and a boolean flag whether an overflow happened
6334/// during evaluation.
6335static GEPOffsetAndOverflow
6336EmitGEPOffsetInBytes(Value *BasePtr, llvm::Type *ElemTy,
6337 ArrayRef<Value *> IdxList, llvm::LLVMContext &VMContext,
6338 CodeGenModule &CGM, CGBuilderTy &Builder) {
6339 const auto &DL = CGM.getDataLayout();
6340
6341 // The total (signed) byte offset for the GEP.
6342 llvm::Value *TotalOffset = nullptr;
6343
6344 auto *IntPtrTy = DL.getAddressType(PtrTy: BasePtr->getType());
6345
6346 // Grab references to the signed add/mul overflow intrinsics for intptr_t.
6347 auto *Zero = llvm::ConstantInt::getNullValue(Ty: IntPtrTy);
6348 auto *SAddIntrinsic =
6349 CGM.getIntrinsic(IID: llvm::Intrinsic::sadd_with_overflow, Tys: IntPtrTy);
6350 auto *SMulIntrinsic =
6351 CGM.getIntrinsic(IID: llvm::Intrinsic::smul_with_overflow, Tys: IntPtrTy);
6352
6353 // The offset overflow flag - true if the total offset overflows.
6354 llvm::Value *OffsetOverflows = Builder.getFalse();
6355
6356 /// Return the result of the given binary operation.
6357 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
6358 llvm::Value *RHS) -> llvm::Value * {
6359 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
6360
6361 // If the operands are constants, return a constant result.
6362 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(Val: LHS)) {
6363 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(Val: RHS)) {
6364 llvm::APInt N;
6365 bool HasOverflow = mayHaveIntegerOverflow(LHS: LHSCI, RHS: RHSCI, Opcode,
6366 /*Signed=*/true, Result&: N);
6367 if (HasOverflow)
6368 OffsetOverflows = Builder.getTrue();
6369 return llvm::ConstantInt::get(Context&: VMContext, V: N);
6370 }
6371 }
6372
6373 // Otherwise, compute the result with checked arithmetic.
6374 auto *ResultAndOverflow = Builder.CreateCall(
6375 Callee: (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, Args: {LHS, RHS});
6376 OffsetOverflows = Builder.CreateOr(
6377 LHS: Builder.CreateExtractValue(Agg: ResultAndOverflow, Idxs: 1), RHS: OffsetOverflows);
6378 return Builder.CreateExtractValue(Agg: ResultAndOverflow, Idxs: 0);
6379 };
6380
6381 // Determine the total byte offset by looking at each GEP operand.
6382 for (auto GTI = llvm::gep_type_begin(Op0: ElemTy, A: IdxList),
6383 GTE = llvm::gep_type_end(ElemTy, A: IdxList);
6384 GTI != GTE; ++GTI) {
6385 llvm::Value *LocalOffset;
6386 auto *Index = GTI.getOperand();
6387 // Compute the local offset contributed by this indexing step:
6388 if (auto *STy = GTI.getStructTypeOrNull()) {
6389 // For struct indexing, the local offset is the byte position of the
6390 // specified field.
6391 unsigned FieldNo = cast<llvm::ConstantInt>(Val: Index)->getZExtValue();
6392 LocalOffset = llvm::ConstantInt::get(
6393 Ty: IntPtrTy, V: DL.getStructLayout(Ty: STy)->getElementOffset(Idx: FieldNo));
6394 } else {
6395 // Otherwise this is array-like indexing. The local offset is the index
6396 // multiplied by the element size.
6397 auto *ElementSize =
6398 llvm::ConstantInt::get(Ty: IntPtrTy, V: GTI.getSequentialElementStride(DL));
6399 auto *IndexS = Builder.CreateIntCast(V: Index, DestTy: IntPtrTy, /*isSigned=*/true);
6400 LocalOffset = eval(BO_Mul, ElementSize, IndexS);
6401 }
6402
6403 // If this is the first offset, set it as the total offset. Otherwise, add
6404 // the local offset into the running total.
6405 if (!TotalOffset || TotalOffset == Zero)
6406 TotalOffset = LocalOffset;
6407 else
6408 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
6409 }
6410
6411 return {.TotalOffset: TotalOffset, .OffsetOverflows: OffsetOverflows};
6412}
6413
6414// OpenMP section maps pass `section - host_offset`. A GEP of an array-of-arrays
6415// from that pointer is not inbounds of the allocation.
6416static llvm::GEPNoWrapFlags
6417inBoundsGEPFlags(const CodeGenFunction &CGF, const llvm::Value *Ptr,
6418 llvm::Type *SrcTy, bool SignedIndices, bool IsSubtraction) {
6419 llvm::GEPNoWrapFlags NW;
6420 bool SectionGEP = CGF.getLangOpts().OpenMPIsTargetDevice &&
6421 SrcTy->isArrayTy() &&
6422 SrcTy->getArrayElementType()->isArrayTy() &&
6423 !isa<llvm::AllocaInst>(Val: llvm::getUnderlyingObject(V: Ptr));
6424 if (!SectionGEP)
6425 NW = llvm::GEPNoWrapFlags::inBounds();
6426 if (!SignedIndices && !IsSubtraction)
6427 NW |= llvm::GEPNoWrapFlags::noUnsignedWrap();
6428 return NW;
6429}
6430
6431Value *
6432CodeGenFunction::EmitCheckedInBoundsGEP(llvm::Type *ElemTy, Value *Ptr,
6433 ArrayRef<Value *> IdxList,
6434 bool SignedIndices, bool IsSubtraction,
6435 SourceLocation Loc, const Twine &Name) {
6436 llvm::Type *PtrTy = Ptr->getType();
6437
6438 llvm::GEPNoWrapFlags NWFlags =
6439 inBoundsGEPFlags(CGF: *this, Ptr, SrcTy: ElemTy, SignedIndices, IsSubtraction);
6440
6441 Value *GEPVal = Builder.CreateGEP(Ty: ElemTy, Ptr, IdxList, Name, NW: NWFlags);
6442
6443 // If the pointer overflow sanitizer isn't enabled, do nothing.
6444 if (!SanOpts.has(K: SanitizerKind::PointerOverflow))
6445 return GEPVal;
6446
6447 // Perform nullptr-and-offset check unless the nullptr is defined.
6448 bool PerformNullCheck = !NullPointerIsDefined(
6449 F: Builder.GetInsertBlock()->getParent(), AS: PtrTy->getPointerAddressSpace());
6450 // Check for overflows unless the GEP got constant-folded,
6451 // and only in the default address space
6452 bool PerformOverflowCheck =
6453 !isa<llvm::Constant>(Val: GEPVal) && PtrTy->getPointerAddressSpace() == 0;
6454
6455 if (!(PerformNullCheck || PerformOverflowCheck))
6456 return GEPVal;
6457
6458 const auto &DL = CGM.getDataLayout();
6459
6460 auto CheckOrdinal = SanitizerKind::SO_PointerOverflow;
6461 auto CheckHandler = SanitizerHandler::PointerOverflow;
6462 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
6463 llvm::Type *IntPtrTy = DL.getAddressType(PtrTy);
6464
6465 GEPOffsetAndOverflow EvaluatedGEP = EmitGEPOffsetInBytes(
6466 BasePtr: Ptr, ElemTy, IdxList, VMContext&: getLLVMContext(), CGM, Builder);
6467
6468 auto *Zero = llvm::ConstantInt::getNullValue(Ty: IntPtrTy);
6469
6470 // Common case: if the total offset is zero and has not overflowed, don't emit
6471 // a check.
6472 if (EvaluatedGEP.TotalOffset == Zero &&
6473 EvaluatedGEP.OffsetOverflows == Builder.getFalse())
6474 return GEPVal;
6475
6476 // Now that we've computed the total offset, add it to the base pointer (with
6477 // wrapping semantics).
6478 auto *IntPtr = Builder.CreatePtrToAddr(V: Ptr);
6479 auto *ComputedGEP = Builder.CreateAdd(LHS: IntPtr, RHS: EvaluatedGEP.TotalOffset);
6480
6481 llvm::SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>,
6482 2>
6483 Checks;
6484
6485 if (PerformNullCheck) {
6486 // If the base pointer evaluates to a null pointer value,
6487 // the only valid pointer this inbounds GEP can produce is also
6488 // a null pointer, so the offset must also evaluate to zero.
6489 // Likewise, if we have non-zero base pointer, we can not get null pointer
6490 // as a result, so the offset can not be -intptr_t(BasePtr).
6491 // In other words, both pointers are either null, or both are non-null,
6492 // or the behaviour is undefined.
6493 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Arg: Ptr);
6494 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(Arg: ComputedGEP);
6495 auto *Valid = Builder.CreateICmpEQ(LHS: BaseIsNotNullptr, RHS: ResultIsNotNullptr);
6496 Checks.emplace_back(Args&: Valid, Args&: CheckOrdinal);
6497 }
6498
6499 if (PerformOverflowCheck) {
6500 // The GEP is valid if:
6501 // 1) The total offset doesn't overflow, and
6502 // 2) The sign of the difference between the computed address and the base
6503 // pointer matches the sign of the total offset.
6504 llvm::Value *ValidGEP;
6505 auto *NoOffsetOverflow = Builder.CreateNot(V: EvaluatedGEP.OffsetOverflows);
6506 if (SignedIndices) {
6507 // GEP is computed as `unsigned base + signed offset`, therefore:
6508 // * If offset was positive, then the computed pointer can not be
6509 // [unsigned] less than the base pointer, unless it overflowed.
6510 // * If offset was negative, then the computed pointer can not be
6511 // [unsigned] greater than the bas pointere, unless it overflowed.
6512 auto *PosOrZeroValid = Builder.CreateICmpUGE(LHS: ComputedGEP, RHS: IntPtr);
6513 auto *PosOrZeroOffset =
6514 Builder.CreateICmpSGE(LHS: EvaluatedGEP.TotalOffset, RHS: Zero);
6515 llvm::Value *NegValid = Builder.CreateICmpULT(LHS: ComputedGEP, RHS: IntPtr);
6516 ValidGEP =
6517 Builder.CreateSelect(C: PosOrZeroOffset, True: PosOrZeroValid, False: NegValid);
6518 } else if (!IsSubtraction) {
6519 // GEP is computed as `unsigned base + unsigned offset`, therefore the
6520 // computed pointer can not be [unsigned] less than base pointer,
6521 // unless there was an overflow.
6522 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
6523 ValidGEP = Builder.CreateICmpUGE(LHS: ComputedGEP, RHS: IntPtr);
6524 } else {
6525 // GEP is computed as `unsigned base - unsigned offset`, therefore the
6526 // computed pointer can not be [unsigned] greater than base pointer,
6527 // unless there was an overflow.
6528 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
6529 ValidGEP = Builder.CreateICmpULE(LHS: ComputedGEP, RHS: IntPtr);
6530 }
6531 ValidGEP = Builder.CreateAnd(LHS: ValidGEP, RHS: NoOffsetOverflow);
6532 Checks.emplace_back(Args&: ValidGEP, Args&: CheckOrdinal);
6533 }
6534
6535 assert(!Checks.empty() && "Should have produced some checks.");
6536
6537 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
6538 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
6539 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
6540 EmitCheck(Checked: Checks, Check: CheckHandler, StaticArgs, DynamicArgs);
6541
6542 return GEPVal;
6543}
6544
6545Address CodeGenFunction::EmitCheckedInBoundsGEP(
6546 Address Addr, ArrayRef<Value *> IdxList, llvm::Type *elementType,
6547 bool SignedIndices, bool IsSubtraction, SourceLocation Loc, CharUnits Align,
6548 const Twine &Name) {
6549 if (!SanOpts.has(K: SanitizerKind::PointerOverflow)) {
6550 llvm::GEPNoWrapFlags NWFlags =
6551 inBoundsGEPFlags(CGF: *this, Ptr: Addr.getBasePointer(), SrcTy: Addr.getElementType(),
6552 SignedIndices, IsSubtraction);
6553 return Builder.CreateGEP(Addr, IdxList, ElementType: elementType, Align, Name, NW: NWFlags);
6554 }
6555
6556 return RawAddress(
6557 EmitCheckedInBoundsGEP(ElemTy: Addr.getElementType(), Ptr: Addr.emitRawPointer(CGF&: *this),
6558 IdxList, SignedIndices, IsSubtraction, Loc, Name),
6559 elementType, Align);
6560}
6561