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