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