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 Value *V = CGF.EmitCallExpr(E).getScalarVal();
686
687 EmitLValueAlignmentAssumption(E, V);
688 return V;
689 }
690
691 Value *VisitStmtExpr(const StmtExpr *E);
692
693 // Unary Operators.
694 Value *VisitUnaryPostDec(const UnaryOperator *E) {
695 LValue LV = EmitLValue(E: E->getSubExpr());
696 return EmitScalarPrePostIncDec(E, LV, isInc: false, isPre: false);
697 }
698 Value *VisitUnaryPostInc(const UnaryOperator *E) {
699 LValue LV = EmitLValue(E: E->getSubExpr());
700 return EmitScalarPrePostIncDec(E, LV, isInc: true, isPre: false);
701 }
702 Value *VisitUnaryPreDec(const UnaryOperator *E) {
703 LValue LV = EmitLValue(E: E->getSubExpr());
704 return EmitScalarPrePostIncDec(E, LV, isInc: false, isPre: true);
705 }
706 Value *VisitUnaryPreInc(const UnaryOperator *E) {
707 LValue LV = EmitLValue(E: E->getSubExpr());
708 return EmitScalarPrePostIncDec(E, LV, isInc: true, isPre: true);
709 }
710
711 llvm::Value *EmitIncDecConsiderOverflowBehavior(const UnaryOperator *E,
712 llvm::Value *InVal,
713 bool IsInc);
714
715 llvm::Value *EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
716 bool isInc, bool isPre);
717
718
719 Value *VisitUnaryAddrOf(const UnaryOperator *E) {
720 if (isa<MemberPointerType>(Val: E->getType())) // never sugared
721 return CGF.CGM.getMemberPointerConstant(e: E);
722
723 return EmitLValue(E: E->getSubExpr()).getPointer(CGF);
724 }
725 Value *VisitUnaryDeref(const UnaryOperator *E) {
726 if (E->getType()->isVoidType())
727 return Visit(E: E->getSubExpr()); // the actual value should be unused
728 return EmitLoadOfLValue(E);
729 }
730
731 Value *VisitUnaryPlus(const UnaryOperator *E,
732 QualType PromotionType = QualType());
733 Value *VisitPlus(const UnaryOperator *E, QualType PromotionType);
734 Value *VisitUnaryMinus(const UnaryOperator *E,
735 QualType PromotionType = QualType());
736 Value *VisitMinus(const UnaryOperator *E, QualType PromotionType);
737
738 Value *VisitUnaryNot (const UnaryOperator *E);
739 Value *VisitUnaryLNot (const UnaryOperator *E);
740 Value *VisitUnaryReal(const UnaryOperator *E,
741 QualType PromotionType = QualType());
742 Value *VisitReal(const UnaryOperator *E, QualType PromotionType);
743 Value *VisitUnaryImag(const UnaryOperator *E,
744 QualType PromotionType = QualType());
745 Value *VisitImag(const UnaryOperator *E, QualType PromotionType);
746 Value *VisitUnaryExtension(const UnaryOperator *E) {
747 return Visit(E: E->getSubExpr());
748 }
749
750 // C++
751 Value *VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E) {
752 return EmitLoadOfLValue(E);
753 }
754 Value *VisitSourceLocExpr(SourceLocExpr *SLE) {
755 auto &Ctx = CGF.getContext();
756 APValue Evaluated =
757 SLE->EvaluateInContext(Ctx, DefaultExpr: CGF.CurSourceLocExprScope.getDefaultExpr());
758 return ConstantEmitter(CGF).emitAbstract(loc: SLE->getLocation(), value: Evaluated,
759 T: SLE->getType());
760 }
761
762 Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
763 CodeGenFunction::CXXDefaultArgExprScope Scope(CGF, DAE);
764 return Visit(E: DAE->getExpr());
765 }
766 Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
767 CodeGenFunction::CXXDefaultInitExprScope Scope(CGF, DIE);
768 return Visit(E: DIE->getExpr());
769 }
770 Value *VisitCXXThisExpr(CXXThisExpr *TE) {
771 return CGF.LoadCXXThis();
772 }
773
774 Value *VisitExprWithCleanups(ExprWithCleanups *E);
775 Value *VisitCXXNewExpr(const CXXNewExpr *E) {
776 return CGF.EmitCXXNewExpr(E);
777 }
778 Value *VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
779 CGF.EmitCXXDeleteExpr(E);
780 return nullptr;
781 }
782
783 Value *VisitTypeTraitExpr(const TypeTraitExpr *E) {
784 if (E->isStoredAsBoolean())
785 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()),
786 V: E->getBoolValue());
787 assert(E->getAPValue().isInt() && "APValue type not supported");
788 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()),
789 V: E->getAPValue().getInt());
790 }
791
792 Value *VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E) {
793 return Builder.getInt1(V: E->isSatisfied());
794 }
795
796 Value *VisitRequiresExpr(const RequiresExpr *E) {
797 return Builder.getInt1(V: E->isSatisfied());
798 }
799
800 Value *VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
801 return llvm::ConstantInt::get(Ty: ConvertType(T: E->getType()), V: E->getValue());
802 }
803
804 Value *VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
805 return llvm::ConstantInt::get(Ty: Builder.getInt1Ty(), V: E->getValue());
806 }
807
808 Value *VisitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *E) {
809 // C++ [expr.pseudo]p1:
810 // The result shall only be used as the operand for the function call
811 // operator (), and the result of such a call has type void. The only
812 // effect is the evaluation of the postfix-expression before the dot or
813 // arrow.
814 CGF.EmitScalarExpr(E: E->getBase());
815 return nullptr;
816 }
817
818 Value *VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
819 return EmitNullValue(Ty: E->getType());
820 }
821
822 Value *VisitCXXThrowExpr(const CXXThrowExpr *E) {
823 CGF.EmitCXXThrowExpr(E);
824 return nullptr;
825 }
826
827 Value *VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
828 return Builder.getInt1(V: E->getValue());
829 }
830
831 // Binary Operators.
832 Value *EmitMul(const BinOpInfo &Ops) {
833 if (Ops.Ty->isSignedIntegerOrEnumerationType() ||
834 Ops.Ty->isUnsignedIntegerType()) {
835 const bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
836 const bool hasSan =
837 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
838 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
839 switch (getOverflowBehaviorConsideringType(CGF, Ty: Ops.Ty)) {
840 case LangOptions::OB_Wrap:
841 return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
842 case LangOptions::OB_SignedAndDefined:
843 if (!hasSan)
844 return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
845 [[fallthrough]];
846 case LangOptions::OB_Unset:
847 if (!hasSan)
848 return isSigned ? Builder.CreateNSWMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul")
849 : Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
850 [[fallthrough]];
851 case LangOptions::OB_Trap:
852 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: Ops))
853 return isSigned ? Builder.CreateNSWMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul")
854 : Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
855 return EmitOverflowCheckedBinOp(Ops);
856 }
857 }
858
859 if (Ops.Ty->isConstantMatrixType()) {
860 llvm::MatrixBuilder MB(Builder);
861 // We need to check the types of the operands of the operator to get the
862 // correct matrix dimensions.
863 auto *BO = cast<BinaryOperator>(Val: Ops.E);
864 auto *LHSMatTy = dyn_cast<ConstantMatrixType>(
865 Val: BO->getLHS()->getType().getCanonicalType());
866 auto *RHSMatTy = dyn_cast<ConstantMatrixType>(
867 Val: BO->getRHS()->getType().getCanonicalType());
868 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
869 if (LHSMatTy && RHSMatTy)
870 return MB.CreateMatrixMultiply(LHS: Ops.LHS, RHS: Ops.RHS, LHSRows: LHSMatTy->getNumRows(),
871 LHSColumns: LHSMatTy->getNumColumns(),
872 RHSColumns: RHSMatTy->getNumColumns());
873 return MB.CreateScalarMultiply(LHS: Ops.LHS, RHS: Ops.RHS);
874 }
875
876 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
877 // Preserve the old values
878 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
879 return Builder.CreateFMul(L: Ops.LHS, R: Ops.RHS, Name: "mul");
880 }
881 if (Ops.isFixedPointOp())
882 return EmitFixedPointBinOp(Ops);
883 return Builder.CreateMul(LHS: Ops.LHS, RHS: Ops.RHS, Name: "mul");
884 }
885 /// Create a binary op that checks for overflow.
886 /// Currently only supports +, - and *.
887 Value *EmitOverflowCheckedBinOp(const BinOpInfo &Ops);
888
889 // Check for undefined division and modulus behaviors.
890 void EmitUndefinedBehaviorIntegerDivAndRemCheck(const BinOpInfo &Ops,
891 llvm::Value *Zero,bool isDiv);
892 // Common helper for getting how wide LHS of shift is.
893 static Value *GetMaximumShiftAmount(Value *LHS, Value *RHS, bool RHSIsSigned);
894
895 // Used for shifting constraints for OpenCL, do mask for powers of 2, URem for
896 // non powers of two.
897 Value *ConstrainShiftValue(Value *LHS, Value *RHS, const Twine &Name);
898
899 Value *EmitDiv(const BinOpInfo &Ops);
900 Value *EmitRem(const BinOpInfo &Ops);
901 Value *EmitAdd(const BinOpInfo &Ops);
902 Value *EmitSub(const BinOpInfo &Ops);
903 Value *EmitShl(const BinOpInfo &Ops);
904 Value *EmitShr(const BinOpInfo &Ops);
905 Value *EmitAnd(const BinOpInfo &Ops) {
906 return Builder.CreateAnd(LHS: Ops.LHS, RHS: Ops.RHS, Name: "and");
907 }
908 Value *EmitXor(const BinOpInfo &Ops) {
909 return Builder.CreateXor(LHS: Ops.LHS, RHS: Ops.RHS, Name: "xor");
910 }
911 Value *EmitOr (const BinOpInfo &Ops) {
912 return Builder.CreateOr(LHS: Ops.LHS, RHS: Ops.RHS, Name: "or");
913 }
914
915 // Helper functions for fixed point binary operations.
916 Value *EmitFixedPointBinOp(const BinOpInfo &Ops);
917
918 BinOpInfo EmitBinOps(const BinaryOperator *E,
919 QualType PromotionTy = QualType());
920
921 Value *EmitPromotedValue(Value *result, QualType PromotionType);
922 Value *EmitUnPromotedValue(Value *result, QualType ExprType);
923 Value *EmitPromoted(const Expr *E, QualType PromotionType);
924
925 LValue EmitCompoundAssignLValue(const CompoundAssignOperator *E,
926 Value *(ScalarExprEmitter::*F)(const BinOpInfo &),
927 Value *&Result);
928
929 Value *EmitCompoundAssign(const CompoundAssignOperator *E,
930 Value *(ScalarExprEmitter::*F)(const BinOpInfo &));
931
932 QualType getPromotionType(QualType Ty) {
933 const auto &Ctx = CGF.getContext();
934 if (auto *CT = Ty->getAs<ComplexType>()) {
935 QualType ElementType = CT->getElementType();
936 if (ElementType.UseExcessPrecision(Ctx))
937 return Ctx.getComplexType(T: Ctx.FloatTy);
938 }
939
940 if (Ty.UseExcessPrecision(Ctx)) {
941 if (auto *VT = Ty->getAs<VectorType>()) {
942 unsigned NumElements = VT->getNumElements();
943 return Ctx.getVectorType(VectorType: Ctx.FloatTy, NumElts: NumElements, VecKind: VT->getVectorKind());
944 }
945 return Ctx.FloatTy;
946 }
947
948 return QualType();
949 }
950
951 // Binary operators and binary compound assignment operators.
952#define HANDLEBINOP(OP) \
953 Value *VisitBin##OP(const BinaryOperator *E) { \
954 QualType promotionTy = getPromotionType(E->getType()); \
955 auto result = Emit##OP(EmitBinOps(E, promotionTy)); \
956 if (result && !promotionTy.isNull()) \
957 result = EmitUnPromotedValue(result, E->getType()); \
958 return result; \
959 } \
960 Value *VisitBin##OP##Assign(const CompoundAssignOperator *E) { \
961 ApplyAtomGroup Grp(CGF.getDebugInfo()); \
962 return EmitCompoundAssign(E, &ScalarExprEmitter::Emit##OP); \
963 }
964 HANDLEBINOP(Mul)
965 HANDLEBINOP(Div)
966 HANDLEBINOP(Rem)
967 HANDLEBINOP(Add)
968 HANDLEBINOP(Sub)
969 HANDLEBINOP(Shl)
970 HANDLEBINOP(Shr)
971 HANDLEBINOP(And)
972 HANDLEBINOP(Xor)
973 HANDLEBINOP(Or)
974#undef HANDLEBINOP
975
976 // Comparisons.
977 Value *EmitCompare(const BinaryOperator *E, llvm::CmpInst::Predicate UICmpOpc,
978 llvm::CmpInst::Predicate SICmpOpc,
979 llvm::CmpInst::Predicate FCmpOpc, bool IsSignaling);
980#define VISITCOMP(CODE, UI, SI, FP, SIG) \
981 Value *VisitBin##CODE(const BinaryOperator *E) { \
982 return EmitCompare(E, llvm::ICmpInst::UI, llvm::ICmpInst::SI, \
983 llvm::FCmpInst::FP, SIG); }
984 VISITCOMP(LT, ICMP_ULT, ICMP_SLT, FCMP_OLT, true)
985 VISITCOMP(GT, ICMP_UGT, ICMP_SGT, FCMP_OGT, true)
986 VISITCOMP(LE, ICMP_ULE, ICMP_SLE, FCMP_OLE, true)
987 VISITCOMP(GE, ICMP_UGE, ICMP_SGE, FCMP_OGE, true)
988 VISITCOMP(EQ, ICMP_EQ , ICMP_EQ , FCMP_OEQ, false)
989 VISITCOMP(NE, ICMP_NE , ICMP_NE , FCMP_UNE, false)
990#undef VISITCOMP
991
992 Value *VisitBinAssign (const BinaryOperator *E);
993
994 Value *VisitBinLAnd (const BinaryOperator *E);
995 Value *VisitBinLOr (const BinaryOperator *E);
996 Value *VisitBinComma (const BinaryOperator *E);
997
998 Value *VisitBinPtrMemD(const Expr *E) { return EmitLoadOfLValue(E); }
999 Value *VisitBinPtrMemI(const Expr *E) { return EmitLoadOfLValue(E); }
1000
1001 Value *VisitCXXRewrittenBinaryOperator(CXXRewrittenBinaryOperator *E) {
1002 return Visit(E: E->getSemanticForm());
1003 }
1004
1005 // Other Operators.
1006 Value *VisitBlockExpr(const BlockExpr *BE);
1007 Value *VisitAbstractConditionalOperator(const AbstractConditionalOperator *);
1008 Value *VisitChooseExpr(ChooseExpr *CE);
1009 Value *VisitVAArgExpr(VAArgExpr *VE);
1010 Value *VisitObjCStringLiteral(const ObjCStringLiteral *E) {
1011 return CGF.EmitObjCStringLiteral(E);
1012 }
1013 Value *VisitObjCBoxedExpr(ObjCBoxedExpr *E) {
1014 return CGF.EmitObjCBoxedExpr(E);
1015 }
1016 Value *VisitObjCArrayLiteral(ObjCArrayLiteral *E) {
1017 return CGF.EmitObjCArrayLiteral(E);
1018 }
1019 Value *VisitObjCDictionaryLiteral(ObjCDictionaryLiteral *E) {
1020 return CGF.EmitObjCDictionaryLiteral(E);
1021 }
1022 Value *VisitAsTypeExpr(AsTypeExpr *CE);
1023 Value *VisitAtomicExpr(AtomicExpr *AE);
1024 Value *VisitPackIndexingExpr(PackIndexingExpr *E) {
1025 return Visit(E: E->getSelectedExpr());
1026 }
1027};
1028} // end anonymous namespace.
1029
1030//===----------------------------------------------------------------------===//
1031// Utilities
1032//===----------------------------------------------------------------------===//
1033
1034/// EmitConversionToBool - Convert the specified expression value to a
1035/// boolean (i1) truth value. This is equivalent to "Val != 0".
1036Value *ScalarExprEmitter::EmitConversionToBool(Value *Src, QualType SrcType) {
1037 assert(SrcType.isCanonical() && "EmitScalarConversion strips typedefs");
1038
1039 if (SrcType->isRealFloatingType())
1040 return EmitFloatToBoolConversion(V: Src);
1041
1042 if (const MemberPointerType *MPT = dyn_cast<MemberPointerType>(Val&: SrcType))
1043 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr: Src, MPT);
1044
1045 // The conversion is a NOP, and will be done when CodeGening the builtin.
1046 if (SrcType == CGF.getContext().AMDGPUFeaturePredicateTy)
1047 return Src;
1048
1049 assert((SrcType->isIntegerType() || isa<llvm::PointerType>(Src->getType())) &&
1050 "Unknown scalar type to convert");
1051
1052 if (isa<llvm::IntegerType>(Val: Src->getType()))
1053 return EmitIntToBoolConversion(V: Src);
1054
1055 assert(isa<llvm::PointerType>(Src->getType()));
1056 return EmitPointerToBoolConversion(V: Src, QT: SrcType);
1057}
1058
1059void ScalarExprEmitter::EmitFloatConversionCheck(
1060 Value *OrigSrc, QualType OrigSrcType, Value *Src, QualType SrcType,
1061 QualType DstType, llvm::Type *DstTy, SourceLocation Loc) {
1062 assert(SrcType->isFloatingType() && "not a conversion from floating point");
1063 if (!isa<llvm::IntegerType>(Val: DstTy))
1064 return;
1065
1066 auto CheckOrdinal = SanitizerKind::SO_FloatCastOverflow;
1067 auto CheckHandler = SanitizerHandler::FloatCastOverflow;
1068 SanitizerDebugLocation SanScope(&CGF, {CheckOrdinal}, CheckHandler);
1069 using llvm::APFloat;
1070 using llvm::APSInt;
1071
1072 llvm::Value *Check = nullptr;
1073 const llvm::fltSemantics &SrcSema =
1074 CGF.getContext().getFloatTypeSemantics(T: OrigSrcType);
1075
1076 // Floating-point to integer. This has undefined behavior if the source is
1077 // +-Inf, NaN, or doesn't fit into the destination type (after truncation
1078 // to an integer).
1079 unsigned Width = CGF.getContext().getIntWidth(T: DstType);
1080 bool Unsigned = DstType->isUnsignedIntegerOrEnumerationType();
1081
1082 APSInt Min = APSInt::getMinValue(numBits: Width, Unsigned);
1083 APFloat MinSrc(SrcSema, APFloat::uninitialized);
1084 if (MinSrc.convertFromAPInt(Input: Min, IsSigned: !Unsigned, RM: APFloat::rmTowardZero) &
1085 APFloat::opOverflow)
1086 // Don't need an overflow check for lower bound. Just check for
1087 // -Inf/NaN.
1088 MinSrc = APFloat::getInf(Sem: SrcSema, Negative: true);
1089 else
1090 // Find the largest value which is too small to represent (before
1091 // truncation toward zero).
1092 MinSrc.subtract(RHS: APFloat(SrcSema, 1), RM: APFloat::rmTowardNegative);
1093
1094 APSInt Max = APSInt::getMaxValue(numBits: Width, Unsigned);
1095 APFloat MaxSrc(SrcSema, APFloat::uninitialized);
1096 if (MaxSrc.convertFromAPInt(Input: Max, IsSigned: !Unsigned, RM: APFloat::rmTowardZero) &
1097 APFloat::opOverflow)
1098 // Don't need an overflow check for upper bound. Just check for
1099 // +Inf/NaN.
1100 MaxSrc = APFloat::getInf(Sem: SrcSema, Negative: false);
1101 else
1102 // Find the smallest value which is too large to represent (before
1103 // truncation toward zero).
1104 MaxSrc.add(RHS: APFloat(SrcSema, 1), RM: APFloat::rmTowardPositive);
1105
1106 // If we're converting from __half, convert the range to float to match
1107 // the type of src.
1108 if (OrigSrcType->isHalfType()) {
1109 const llvm::fltSemantics &Sema =
1110 CGF.getContext().getFloatTypeSemantics(T: SrcType);
1111 bool IsInexact;
1112 MinSrc.convert(ToSemantics: Sema, RM: APFloat::rmTowardZero, losesInfo: &IsInexact);
1113 MaxSrc.convert(ToSemantics: Sema, RM: APFloat::rmTowardZero, losesInfo: &IsInexact);
1114 }
1115
1116 llvm::Value *GE =
1117 Builder.CreateFCmpOGT(LHS: Src, RHS: llvm::ConstantFP::get(Context&: VMContext, V: MinSrc));
1118 llvm::Value *LE =
1119 Builder.CreateFCmpOLT(LHS: Src, RHS: llvm::ConstantFP::get(Context&: VMContext, V: MaxSrc));
1120 Check = Builder.CreateAnd(LHS: GE, RHS: LE);
1121
1122 llvm::Constant *StaticArgs[] = {CGF.EmitCheckSourceLocation(Loc),
1123 CGF.EmitCheckTypeDescriptor(T: OrigSrcType),
1124 CGF.EmitCheckTypeDescriptor(T: DstType)};
1125 CGF.EmitCheck(Checked: std::make_pair(x&: Check, y&: CheckOrdinal), Check: CheckHandler, StaticArgs,
1126 DynamicArgs: OrigSrc);
1127}
1128
1129// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1130// Returns 'i1 false' when the truncation Src -> Dst was lossy.
1131static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1132 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1133EmitIntegerTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1134 QualType DstType, CGBuilderTy &Builder) {
1135 llvm::Type *SrcTy = Src->getType();
1136 llvm::Type *DstTy = Dst->getType();
1137 (void)DstTy; // Only used in assert()
1138
1139 // This should be truncation of integral types.
1140 assert(Src != Dst);
1141 assert(SrcTy->getScalarSizeInBits() > Dst->getType()->getScalarSizeInBits());
1142 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1143 "non-integer llvm type");
1144
1145 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1146 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1147
1148 // If both (src and dst) types are unsigned, then it's an unsigned truncation.
1149 // Else, it is a signed truncation.
1150 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
1151 SanitizerKind::SanitizerOrdinal Ordinal;
1152 if (!SrcSigned && !DstSigned) {
1153 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1154 Ordinal = SanitizerKind::SO_ImplicitUnsignedIntegerTruncation;
1155 } else {
1156 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1157 Ordinal = SanitizerKind::SO_ImplicitSignedIntegerTruncation;
1158 }
1159
1160 llvm::Value *Check = nullptr;
1161 // 1. Extend the truncated value back to the same width as the Src.
1162 Check = Builder.CreateIntCast(V: Dst, DestTy: SrcTy, isSigned: DstSigned, Name: "anyext");
1163 // 2. Equality-compare with the original source value
1164 Check = Builder.CreateICmpEQ(LHS: Check, RHS: Src, Name: "truncheck");
1165 // If the comparison result is 'i1 false', then the truncation was lossy.
1166 return std::make_pair(x&: Kind, y: std::make_pair(x&: Check, y&: Ordinal));
1167}
1168
1169static bool PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
1170 QualType SrcType, QualType DstType) {
1171 return SrcType->isIntegerType() && DstType->isIntegerType();
1172}
1173
1174void ScalarExprEmitter::EmitIntegerTruncationCheck(Value *Src, QualType SrcType,
1175 Value *Dst, QualType DstType,
1176 SourceLocation Loc,
1177 bool OBTrapInvolved) {
1178 if (!CGF.SanOpts.hasOneOf(K: SanitizerKind::ImplicitIntegerTruncation) &&
1179 !OBTrapInvolved)
1180 return;
1181
1182 // We only care about int->int conversions here.
1183 // We ignore conversions to/from pointer and/or bool.
1184 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1185 DstType))
1186 return;
1187
1188 unsigned SrcBits = Src->getType()->getScalarSizeInBits();
1189 unsigned DstBits = Dst->getType()->getScalarSizeInBits();
1190 // This must be truncation. Else we do not care.
1191 if (SrcBits <= DstBits)
1192 return;
1193
1194 assert(!DstType->isBooleanType() && "we should not get here with booleans.");
1195
1196 // If the integer sign change sanitizer is enabled,
1197 // and we are truncating from larger unsigned type to smaller signed type,
1198 // let that next sanitizer deal with it.
1199 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1200 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1201 if (CGF.SanOpts.has(K: SanitizerKind::ImplicitIntegerSignChange) &&
1202 (!SrcSigned && DstSigned))
1203 return;
1204
1205 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1206 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1207 Check;
1208
1209 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1210 {
1211 // We don't know the check kind until we call
1212 // EmitIntegerTruncationCheckHelper, but we want to annotate
1213 // EmitIntegerTruncationCheckHelper's instructions too.
1214 SanitizerDebugLocation SanScope(
1215 &CGF,
1216 {SanitizerKind::SO_ImplicitUnsignedIntegerTruncation,
1217 SanitizerKind::SO_ImplicitSignedIntegerTruncation},
1218 CheckHandler);
1219 Check =
1220 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1221 // If the comparison result is 'i1 false', then the truncation was lossy.
1222 }
1223
1224 // Do we care about this type of truncation?
1225 if (!CGF.SanOpts.has(O: Check.second.second)) {
1226 // Just emit a trap check if an __ob_trap was involved but appropriate
1227 // sanitizer isn't enabled.
1228 if (OBTrapInvolved)
1229 CGF.EmitTrapCheck(Checked: Check.second.first, CheckHandlerID: CheckHandler);
1230 return;
1231 }
1232
1233 SanitizerDebugLocation SanScope(&CGF, {Check.second.second}, CheckHandler);
1234
1235 // Does some SSCL ignore this type?
1236 const bool ignoredBySanitizer = CGF.getContext().isTypeIgnoredBySanitizer(
1237 Mask: SanitizerMask::bitPosToMask(Pos: Check.second.second), Ty: DstType);
1238
1239 // Consider OverflowBehaviorTypes which override SSCL type entries for
1240 // truncation sanitizers.
1241 if (const auto *OBT = DstType->getAs<OverflowBehaviorType>()) {
1242 if (OBT->isWrapKind())
1243 return;
1244 }
1245 if (ignoredBySanitizer && !OBTrapInvolved)
1246 return;
1247
1248 llvm::Constant *StaticArgs[] = {
1249 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(T: SrcType),
1250 CGF.EmitCheckTypeDescriptor(T: DstType),
1251 llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: Check.first),
1252 llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: 0)};
1253
1254 CGF.EmitCheck(Checked: Check.second, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst});
1255}
1256
1257static llvm::Value *EmitIsNegativeTestHelper(Value *V, QualType VType,
1258 const char *Name,
1259 CGBuilderTy &Builder) {
1260 bool VSigned = VType->isSignedIntegerOrEnumerationType();
1261 llvm::Type *VTy = V->getType();
1262 if (!VSigned) {
1263 // If the value is unsigned, then it is never negative.
1264 return llvm::ConstantInt::getFalse(Context&: VTy->getContext());
1265 }
1266 llvm::Constant *Zero = llvm::ConstantInt::get(Ty: VTy, V: 0);
1267 return Builder.CreateICmp(P: llvm::ICmpInst::ICMP_SLT, LHS: V, RHS: Zero,
1268 Name: llvm::Twine(Name) + "." + V->getName() +
1269 ".negativitycheck");
1270}
1271
1272// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1273// Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1274static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1275 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1276EmitIntegerSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1277 QualType DstType, CGBuilderTy &Builder) {
1278 llvm::Type *SrcTy = Src->getType();
1279 llvm::Type *DstTy = Dst->getType();
1280
1281 assert(isa<llvm::IntegerType>(SrcTy) && isa<llvm::IntegerType>(DstTy) &&
1282 "non-integer llvm type");
1283
1284 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1285 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1286 (void)SrcSigned; // Only used in assert()
1287 (void)DstSigned; // Only used in assert()
1288 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1289 unsigned DstBits = DstTy->getScalarSizeInBits();
1290 (void)SrcBits; // Only used in assert()
1291 (void)DstBits; // Only used in assert()
1292
1293 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1294 "either the widths should be different, or the signednesses.");
1295
1296 // 1. Was the old Value negative?
1297 llvm::Value *SrcIsNegative =
1298 EmitIsNegativeTestHelper(V: Src, VType: SrcType, Name: "src", Builder);
1299 // 2. Is the new Value negative?
1300 llvm::Value *DstIsNegative =
1301 EmitIsNegativeTestHelper(V: Dst, VType: DstType, Name: "dst", Builder);
1302 // 3. Now, was the 'negativity status' preserved during the conversion?
1303 // NOTE: conversion from negative to zero is considered to change the sign.
1304 // (We want to get 'false' when the conversion changed the sign)
1305 // So we should just equality-compare the negativity statuses.
1306 llvm::Value *Check = nullptr;
1307 Check = Builder.CreateICmpEQ(LHS: SrcIsNegative, RHS: DstIsNegative, Name: "signchangecheck");
1308 // If the comparison result is 'false', then the conversion changed the sign.
1309 return std::make_pair(
1310 x: ScalarExprEmitter::ICCK_IntegerSignChange,
1311 y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitIntegerSignChange));
1312}
1313
1314void ScalarExprEmitter::EmitIntegerSignChangeCheck(Value *Src, QualType SrcType,
1315 Value *Dst, QualType DstType,
1316 SourceLocation Loc,
1317 bool OBTrapInvolved) {
1318 if (!CGF.SanOpts.has(O: SanitizerKind::SO_ImplicitIntegerSignChange) &&
1319 !OBTrapInvolved)
1320 return;
1321
1322 llvm::Type *SrcTy = Src->getType();
1323 llvm::Type *DstTy = Dst->getType();
1324
1325 // We only care about int->int conversions here.
1326 // We ignore conversions to/from pointer and/or bool.
1327 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1328 DstType))
1329 return;
1330
1331 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1332 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1333 unsigned SrcBits = SrcTy->getScalarSizeInBits();
1334 unsigned DstBits = DstTy->getScalarSizeInBits();
1335
1336 // Now, we do not need to emit the check in *all* of the cases.
1337 // We can avoid emitting it in some obvious cases where it would have been
1338 // dropped by the opt passes (instcombine) always anyways.
1339 // If it's a cast between effectively the same type, no check.
1340 // NOTE: this is *not* equivalent to checking the canonical types.
1341 if (SrcSigned == DstSigned && SrcBits == DstBits)
1342 return;
1343 // At least one of the values needs to have signed type.
1344 // If both are unsigned, then obviously, neither of them can be negative.
1345 if (!SrcSigned && !DstSigned)
1346 return;
1347 // If the conversion is to *larger* *signed* type, then no check is needed.
1348 // Because either sign-extension happens (so the sign will remain),
1349 // or zero-extension will happen (the sign bit will be zero.)
1350 if ((DstBits > SrcBits) && DstSigned)
1351 return;
1352 if (CGF.SanOpts.has(K: SanitizerKind::ImplicitSignedIntegerTruncation) &&
1353 (SrcBits > DstBits) && SrcSigned) {
1354 // If the signed integer truncation sanitizer is enabled,
1355 // and this is a truncation from signed type, then no check is needed.
1356 // Because here sign change check is interchangeable with truncation check.
1357 return;
1358 }
1359 // Does an SSCL have an entry for the DstType under its respective sanitizer
1360 // section? Don't check this if an __ob_trap type is involved as it has
1361 // priority to emit checks regardless of sanitizer case lists.
1362 if (!OBTrapInvolved) {
1363 if (DstSigned &&
1364 CGF.getContext().isTypeIgnoredBySanitizer(
1365 Mask: SanitizerKind::ImplicitSignedIntegerTruncation, Ty: DstType))
1366 return;
1367 if (!DstSigned &&
1368 CGF.getContext().isTypeIgnoredBySanitizer(
1369 Mask: SanitizerKind::ImplicitUnsignedIntegerTruncation, Ty: DstType))
1370 return;
1371 }
1372 // That's it. We can't rule out any more cases with the data we have.
1373
1374 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1375 SanitizerDebugLocation SanScope(
1376 &CGF,
1377 {SanitizerKind::SO_ImplicitIntegerSignChange,
1378 SanitizerKind::SO_ImplicitUnsignedIntegerTruncation,
1379 SanitizerKind::SO_ImplicitSignedIntegerTruncation},
1380 CheckHandler);
1381
1382 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1383 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1384 Check;
1385
1386 // Each of these checks needs to return 'false' when an issue was detected.
1387 ImplicitConversionCheckKind CheckKind;
1388 llvm::SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>,
1389 2>
1390 Checks;
1391 // So we can 'and' all the checks together, and still get 'false',
1392 // if at least one of the checks detected an issue.
1393
1394 Check = EmitIntegerSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1395 CheckKind = Check.first;
1396 Checks.emplace_back(Args&: Check.second);
1397
1398 if (CGF.SanOpts.has(K: SanitizerKind::ImplicitSignedIntegerTruncation) &&
1399 (SrcBits > DstBits) && !SrcSigned && DstSigned) {
1400 // If the signed integer truncation sanitizer was enabled,
1401 // and we are truncating from larger unsigned type to smaller signed type,
1402 // let's handle the case we skipped in that check.
1403 Check =
1404 EmitIntegerTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1405 CheckKind = ICCK_SignedIntegerTruncationOrSignChange;
1406 Checks.emplace_back(Args&: Check.second);
1407 // If the comparison result is 'i1 false', then the truncation was lossy.
1408 }
1409
1410 if (!CGF.SanOpts.has(O: SanitizerKind::SO_ImplicitIntegerSignChange)) {
1411 if (OBTrapInvolved) {
1412 llvm::Value *Combined = Check.second.first;
1413 for (const auto &C : Checks)
1414 Combined = Builder.CreateAnd(LHS: Combined, RHS: C.first);
1415 CGF.EmitTrapCheck(Checked: Combined, CheckHandlerID: CheckHandler);
1416 }
1417 return;
1418 }
1419
1420 llvm::Constant *StaticArgs[] = {
1421 CGF.EmitCheckSourceLocation(Loc), CGF.EmitCheckTypeDescriptor(T: SrcType),
1422 CGF.EmitCheckTypeDescriptor(T: DstType),
1423 llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: CheckKind),
1424 llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: 0)};
1425 // EmitCheck() will 'and' all the checks together.
1426 CGF.EmitCheck(Checked: Checks, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst});
1427}
1428
1429// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1430// Returns 'i1 false' when the truncation Src -> Dst was lossy.
1431static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1432 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1433EmitBitfieldTruncationCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1434 QualType DstType, CGBuilderTy &Builder) {
1435 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1436 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1437
1438 ScalarExprEmitter::ImplicitConversionCheckKind Kind;
1439 if (!SrcSigned && !DstSigned)
1440 Kind = ScalarExprEmitter::ICCK_UnsignedIntegerTruncation;
1441 else
1442 Kind = ScalarExprEmitter::ICCK_SignedIntegerTruncation;
1443
1444 llvm::Value *Check = nullptr;
1445 // 1. Extend the truncated value back to the same width as the Src.
1446 Check = Builder.CreateIntCast(V: Dst, DestTy: Src->getType(), isSigned: DstSigned, Name: "bf.anyext");
1447 // 2. Equality-compare with the original source value
1448 Check = Builder.CreateICmpEQ(LHS: Check, RHS: Src, Name: "bf.truncheck");
1449 // If the comparison result is 'i1 false', then the truncation was lossy.
1450
1451 return std::make_pair(
1452 x&: Kind,
1453 y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitBitfieldConversion));
1454}
1455
1456// Should be called within CodeGenFunction::SanitizerScope RAII scope.
1457// Returns 'i1 false' when the conversion Src -> Dst changed the sign.
1458static std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1459 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1460EmitBitfieldSignChangeCheckHelper(Value *Src, QualType SrcType, Value *Dst,
1461 QualType DstType, CGBuilderTy &Builder) {
1462 // 1. Was the old Value negative?
1463 llvm::Value *SrcIsNegative =
1464 EmitIsNegativeTestHelper(V: Src, VType: SrcType, Name: "bf.src", Builder);
1465 // 2. Is the new Value negative?
1466 llvm::Value *DstIsNegative =
1467 EmitIsNegativeTestHelper(V: Dst, VType: DstType, Name: "bf.dst", Builder);
1468 // 3. Now, was the 'negativity status' preserved during the conversion?
1469 // NOTE: conversion from negative to zero is considered to change the sign.
1470 // (We want to get 'false' when the conversion changed the sign)
1471 // So we should just equality-compare the negativity statuses.
1472 llvm::Value *Check = nullptr;
1473 Check =
1474 Builder.CreateICmpEQ(LHS: SrcIsNegative, RHS: DstIsNegative, Name: "bf.signchangecheck");
1475 // If the comparison result is 'false', then the conversion changed the sign.
1476 return std::make_pair(
1477 x: ScalarExprEmitter::ICCK_IntegerSignChange,
1478 y: std::make_pair(x&: Check, y: SanitizerKind::SO_ImplicitBitfieldConversion));
1479}
1480
1481void CodeGenFunction::EmitBitfieldConversionCheck(Value *Src, QualType SrcType,
1482 Value *Dst, QualType DstType,
1483 const CGBitFieldInfo &Info,
1484 SourceLocation Loc) {
1485
1486 if (!SanOpts.has(K: SanitizerKind::ImplicitBitfieldConversion))
1487 return;
1488
1489 // We only care about int->int conversions here.
1490 // We ignore conversions to/from pointer and/or bool.
1491 if (!PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(SrcType,
1492 DstType))
1493 return;
1494
1495 if (DstType->isBooleanType() || SrcType->isBooleanType())
1496 return;
1497
1498 // This should be truncation of integral types.
1499 assert(isa<llvm::IntegerType>(Src->getType()) &&
1500 isa<llvm::IntegerType>(Dst->getType()) && "non-integer llvm type");
1501
1502 // TODO: Calculate src width to avoid emitting code
1503 // for unecessary cases.
1504 unsigned SrcBits = ConvertType(T: SrcType)->getScalarSizeInBits();
1505 unsigned DstBits = Info.Size;
1506
1507 bool SrcSigned = SrcType->isSignedIntegerOrEnumerationType();
1508 bool DstSigned = DstType->isSignedIntegerOrEnumerationType();
1509
1510 auto CheckHandler = SanitizerHandler::ImplicitConversion;
1511 SanitizerDebugLocation SanScope(
1512 this, {SanitizerKind::SO_ImplicitBitfieldConversion}, CheckHandler);
1513
1514 std::pair<ScalarExprEmitter::ImplicitConversionCheckKind,
1515 std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>>
1516 Check;
1517
1518 // Truncation
1519 bool EmitTruncation = DstBits < SrcBits;
1520 // If Dst is signed and Src unsigned, we want to be more specific
1521 // about the CheckKind we emit, in this case we want to emit
1522 // ICCK_SignedIntegerTruncationOrSignChange.
1523 bool EmitTruncationFromUnsignedToSigned =
1524 EmitTruncation && DstSigned && !SrcSigned;
1525 // Sign change
1526 bool SameTypeSameSize = SrcSigned == DstSigned && SrcBits == DstBits;
1527 bool BothUnsigned = !SrcSigned && !DstSigned;
1528 bool LargerSigned = (DstBits > SrcBits) && DstSigned;
1529 // We can avoid emitting sign change checks in some obvious cases
1530 // 1. If Src and Dst have the same signedness and size
1531 // 2. If both are unsigned sign check is unecessary!
1532 // 3. If Dst is signed and bigger than Src, either
1533 // sign-extension or zero-extension will make sure
1534 // the sign remains.
1535 bool EmitSignChange = !SameTypeSameSize && !BothUnsigned && !LargerSigned;
1536
1537 if (EmitTruncation)
1538 Check =
1539 EmitBitfieldTruncationCheckHelper(Src, SrcType, Dst, DstType, Builder);
1540 else if (EmitSignChange) {
1541 assert(((SrcBits != DstBits) || (SrcSigned != DstSigned)) &&
1542 "either the widths should be different, or the signednesses.");
1543 Check =
1544 EmitBitfieldSignChangeCheckHelper(Src, SrcType, Dst, DstType, Builder);
1545 } else
1546 return;
1547
1548 ScalarExprEmitter::ImplicitConversionCheckKind CheckKind = Check.first;
1549 if (EmitTruncationFromUnsignedToSigned)
1550 CheckKind = ScalarExprEmitter::ICCK_SignedIntegerTruncationOrSignChange;
1551
1552 llvm::Constant *StaticArgs[] = {
1553 EmitCheckSourceLocation(Loc), EmitCheckTypeDescriptor(T: SrcType),
1554 EmitCheckTypeDescriptor(T: DstType),
1555 llvm::ConstantInt::get(Ty: Builder.getInt8Ty(), V: CheckKind),
1556 llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: Info.Size)};
1557
1558 EmitCheck(Checked: Check.second, Check: CheckHandler, StaticArgs, DynamicArgs: {Src, Dst});
1559}
1560
1561Value *ScalarExprEmitter::EmitScalarCast(Value *Src, QualType SrcType,
1562 QualType DstType, llvm::Type *SrcTy,
1563 llvm::Type *DstTy,
1564 ScalarConversionOpts Opts) {
1565 // The Element types determine the type of cast to perform.
1566 llvm::Type *SrcElementTy;
1567 llvm::Type *DstElementTy;
1568 QualType SrcElementType;
1569 QualType DstElementType;
1570 if (SrcType->isMatrixType() && DstType->isMatrixType()) {
1571 SrcElementTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType();
1572 DstElementTy = cast<llvm::VectorType>(Val: DstTy)->getElementType();
1573 SrcElementType = SrcType->castAs<MatrixType>()->getElementType();
1574 DstElementType = DstType->castAs<MatrixType>()->getElementType();
1575 } else {
1576 assert(!SrcType->isMatrixType() && !DstType->isMatrixType() &&
1577 "cannot cast between matrix and non-matrix types");
1578 SrcElementTy = SrcTy;
1579 DstElementTy = DstTy;
1580 SrcElementType = SrcType;
1581 DstElementType = DstType;
1582 }
1583
1584 if (isa<llvm::IntegerType>(Val: SrcElementTy)) {
1585 bool InputSigned = SrcElementType->isSignedIntegerOrEnumerationType();
1586 if (SrcElementType->isBooleanType() && Opts.TreatBooleanAsSigned) {
1587 InputSigned = true;
1588 }
1589
1590 if (isa<llvm::IntegerType>(Val: DstElementTy))
1591 return Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: InputSigned, Name: "conv");
1592 if (InputSigned)
1593 return Builder.CreateSIToFP(V: Src, DestTy: DstTy, Name: "conv");
1594 return Builder.CreateUIToFP(V: Src, DestTy: DstTy, Name: "conv");
1595 }
1596
1597 if (isa<llvm::IntegerType>(Val: DstElementTy)) {
1598 assert(SrcElementTy->isFloatingPointTy() && "Unknown real conversion");
1599 bool IsSigned = DstElementType->isSignedIntegerOrEnumerationType();
1600
1601 // If we can't recognize overflow as undefined behavior, assume that
1602 // overflow saturates. This protects against normal optimizations if we are
1603 // compiling with non-standard FP semantics.
1604 if (!CGF.CGM.getCodeGenOpts().StrictFloatCastOverflow) {
1605 llvm::Intrinsic::ID IID =
1606 IsSigned ? llvm::Intrinsic::fptosi_sat : llvm::Intrinsic::fptoui_sat;
1607 return Builder.CreateCall(Callee: CGF.CGM.getIntrinsic(IID, Tys: {DstTy, SrcTy}), Args: Src);
1608 }
1609
1610 if (IsSigned)
1611 return Builder.CreateFPToSI(V: Src, DestTy: DstTy, Name: "conv");
1612 return Builder.CreateFPToUI(V: Src, DestTy: DstTy, Name: "conv");
1613 }
1614
1615 if ((DstElementTy->is16bitFPTy() && SrcElementTy->is16bitFPTy())) {
1616 Value *FloatVal = Builder.CreateFPExt(V: Src, DestTy: Builder.getFloatTy(), Name: "fpext");
1617 return Builder.CreateFPTrunc(V: FloatVal, DestTy: DstTy, Name: "fptrunc");
1618 }
1619 if (DstElementTy->getTypeID() < SrcElementTy->getTypeID())
1620 return Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv");
1621 return Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv");
1622}
1623
1624/// Emit a conversion from the specified type to the specified destination type,
1625/// both of which are LLVM scalar types.
1626Value *ScalarExprEmitter::EmitScalarConversion(Value *Src, QualType SrcType,
1627 QualType DstType,
1628 SourceLocation Loc,
1629 ScalarConversionOpts Opts) {
1630 // All conversions involving fixed point types should be handled by the
1631 // EmitFixedPoint family functions. This is done to prevent bloating up this
1632 // function more, and although fixed point numbers are represented by
1633 // integers, we do not want to follow any logic that assumes they should be
1634 // treated as integers.
1635 // TODO(leonardchan): When necessary, add another if statement checking for
1636 // conversions to fixed point types from other types.
1637 if (SrcType->isFixedPointType()) {
1638 if (DstType->isBooleanType())
1639 // It is important that we check this before checking if the dest type is
1640 // an integer because booleans are technically integer types.
1641 // We do not need to check the padding bit on unsigned types if unsigned
1642 // padding is enabled because overflow into this bit is undefined
1643 // behavior.
1644 return Builder.CreateIsNotNull(Arg: Src, Name: "tobool");
1645 if (DstType->isFixedPointType() || DstType->isIntegerType() ||
1646 DstType->isRealFloatingType())
1647 return EmitFixedPointConversion(Src, SrcTy: SrcType, DstTy: DstType, Loc);
1648
1649 llvm_unreachable(
1650 "Unhandled scalar conversion from a fixed point type to another type.");
1651 } else if (DstType->isFixedPointType()) {
1652 if (SrcType->isIntegerType() || SrcType->isRealFloatingType())
1653 // This also includes converting booleans and enums to fixed point types.
1654 return EmitFixedPointConversion(Src, SrcTy: SrcType, DstTy: DstType, Loc);
1655
1656 llvm_unreachable(
1657 "Unhandled scalar conversion to a fixed point type from another type.");
1658 }
1659
1660 QualType NoncanonicalSrcType = SrcType;
1661 QualType NoncanonicalDstType = DstType;
1662
1663 SrcType = CGF.getContext().getCanonicalType(T: SrcType);
1664 DstType = CGF.getContext().getCanonicalType(T: DstType);
1665 if (SrcType == DstType) return Src;
1666
1667 if (DstType->isVoidType()) return nullptr;
1668
1669 llvm::Value *OrigSrc = Src;
1670 QualType OrigSrcType = SrcType;
1671 llvm::Type *SrcTy = Src->getType();
1672
1673 // Handle conversions to bool first, they are special: comparisons against 0.
1674 if (DstType->isBooleanType())
1675 return EmitConversionToBool(Src, SrcType);
1676
1677 llvm::Type *DstTy = ConvertType(T: DstType);
1678
1679 // Determine whether an overflow behavior of 'trap' has been specified for
1680 // either the destination or the source types. If so, we can elide sanitizer
1681 // capability checks as this overflow behavior kind is also capable of
1682 // emitting traps without runtime sanitizer support.
1683 // Also skip instrumentation if either source or destination has 'wrap'
1684 // behavior - the user has explicitly indicated they accept wrapping
1685 // semantics. Use non-canonical types to preserve OBT annotations.
1686 const auto *DstOBT = NoncanonicalDstType->getAs<OverflowBehaviorType>();
1687 const auto *SrcOBT = NoncanonicalSrcType->getAs<OverflowBehaviorType>();
1688 bool OBTrapInvolved =
1689 (DstOBT && DstOBT->isTrapKind()) || (SrcOBT && SrcOBT->isTrapKind());
1690 bool OBWrapInvolved =
1691 (DstOBT && DstOBT->isWrapKind()) || (SrcOBT && SrcOBT->isWrapKind());
1692
1693 // Cast from half through float if half isn't a native type.
1694 if (SrcType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1695 // Cast to FP using the intrinsic if the half type itself isn't supported.
1696 if (DstTy->isFloatingPointTy()) {
1697 if (CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics()) {
1698 Value *BitCast = Builder.CreateBitCast(V: Src, DestTy: CGF.CGM.HalfTy);
1699 return Builder.CreateFPExt(V: BitCast, DestTy: DstTy, Name: "conv");
1700 }
1701 } else {
1702 // Cast to other types through float, using either the intrinsic or FPExt,
1703 // depending on whether the half type itself is supported
1704 // (as opposed to operations on half, available with NativeHalfType).
1705
1706 if (Src->getType() != CGF.CGM.HalfTy) {
1707 assert(CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics());
1708 Src = Builder.CreateBitCast(V: Src, DestTy: CGF.CGM.HalfTy);
1709 }
1710
1711 Src = Builder.CreateFPExt(V: Src, DestTy: CGF.CGM.FloatTy, Name: "conv");
1712 SrcType = CGF.getContext().FloatTy;
1713 SrcTy = CGF.FloatTy;
1714 }
1715 }
1716
1717 // Ignore conversions like int -> uint.
1718 if (SrcTy == DstTy) {
1719 if (Opts.EmitImplicitIntegerSignChangeChecks ||
1720 (OBTrapInvolved && !OBWrapInvolved))
1721 EmitIntegerSignChangeCheck(Src, SrcType: NoncanonicalSrcType, Dst: Src,
1722 DstType: NoncanonicalDstType, Loc, OBTrapInvolved);
1723
1724 return Src;
1725 }
1726
1727 // Handle pointer conversions next: pointers can only be converted to/from
1728 // other pointers and integers. Check for pointer types in terms of LLVM, as
1729 // some native types (like Obj-C id) may map to a pointer type.
1730 if (auto DstPT = dyn_cast<llvm::PointerType>(Val: DstTy)) {
1731 // The source value may be an integer, or a pointer.
1732 if (isa<llvm::PointerType>(Val: SrcTy))
1733 return Src;
1734
1735 assert(SrcType->isIntegerType() && "Not ptr->ptr or int->ptr conversion?");
1736 // First, convert to the correct width so that we control the kind of
1737 // extension.
1738 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DstPT);
1739 bool InputSigned = SrcType->isSignedIntegerOrEnumerationType();
1740 llvm::Value* IntResult =
1741 Builder.CreateIntCast(V: Src, DestTy: MiddleTy, isSigned: InputSigned, Name: "conv");
1742 // Then, cast to pointer.
1743 return Builder.CreateIntToPtr(V: IntResult, DestTy: DstTy, Name: "conv");
1744 }
1745
1746 if (isa<llvm::PointerType>(Val: SrcTy)) {
1747 // Must be an ptr to int cast.
1748 assert(isa<llvm::IntegerType>(DstTy) && "not ptr->int?");
1749 return Builder.CreatePtrToInt(V: Src, DestTy: DstTy, Name: "conv");
1750 }
1751
1752 // A scalar can be splatted to an extended vector of the same element type
1753 if (DstType->isExtVectorType() && !SrcType->isVectorType()) {
1754 // Sema should add casts to make sure that the source expression's type is
1755 // the same as the vector's element type (sans qualifiers)
1756 assert(DstType->castAs<ExtVectorType>()->getElementType().getTypePtr() ==
1757 SrcType.getTypePtr() &&
1758 "Splatted expr doesn't match with vector element type?");
1759
1760 // Splat the element across to all elements
1761 unsigned NumElements = cast<llvm::FixedVectorType>(Val: DstTy)->getNumElements();
1762 return Builder.CreateVectorSplat(NumElts: NumElements, V: Src, Name: "splat");
1763 }
1764
1765 if (SrcType->isMatrixType() && DstType->isMatrixType())
1766 return EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1767
1768 if (isa<llvm::VectorType>(Val: SrcTy) || isa<llvm::VectorType>(Val: DstTy)) {
1769 // Allow bitcast from vector to integer/fp of the same size.
1770 llvm::TypeSize SrcSize = SrcTy->getPrimitiveSizeInBits();
1771 llvm::TypeSize DstSize = DstTy->getPrimitiveSizeInBits();
1772 if (SrcSize == DstSize)
1773 return Builder.CreateBitCast(V: Src, DestTy: DstTy, Name: "conv");
1774
1775 // Conversions between vectors of different sizes are not allowed except
1776 // when vectors of half are involved. Operations on storage-only half
1777 // vectors require promoting half vector operands to float vectors and
1778 // truncating the result, which is either an int or float vector, to a
1779 // short or half vector.
1780
1781 // Source and destination are both expected to be vectors.
1782 llvm::Type *SrcElementTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType();
1783 llvm::Type *DstElementTy = cast<llvm::VectorType>(Val: DstTy)->getElementType();
1784 (void)DstElementTy;
1785
1786 assert(((SrcElementTy->isIntegerTy() &&
1787 DstElementTy->isIntegerTy()) ||
1788 (SrcElementTy->isFloatingPointTy() &&
1789 DstElementTy->isFloatingPointTy())) &&
1790 "unexpected conversion between a floating-point vector and an "
1791 "integer vector");
1792
1793 // Truncate an i32 vector to an i16 vector.
1794 if (SrcElementTy->isIntegerTy())
1795 return Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: false, Name: "conv");
1796
1797 // Truncate a float vector to a half vector.
1798 if (SrcSize > DstSize)
1799 return Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv");
1800
1801 // Promote a half vector to a float vector.
1802 return Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv");
1803 }
1804
1805 // Finally, we have the arithmetic types: real int/float.
1806 Value *Res = nullptr;
1807 llvm::Type *ResTy = DstTy;
1808
1809 // An overflowing conversion has undefined behavior if either the source type
1810 // or the destination type is a floating-point type. However, we consider the
1811 // range of representable values for all floating-point types to be
1812 // [-inf,+inf], so no overflow can ever happen when the destination type is a
1813 // floating-point type.
1814 if (CGF.SanOpts.has(K: SanitizerKind::FloatCastOverflow) &&
1815 OrigSrcType->isFloatingType())
1816 EmitFloatConversionCheck(OrigSrc, OrigSrcType, Src, SrcType, DstType, DstTy,
1817 Loc);
1818
1819 // Cast to half through float if half isn't a native type.
1820 if (DstType->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
1821 // Make sure we cast in a single step if from another FP type.
1822 if (SrcTy->isFloatingPointTy()) {
1823 // Handle the case where the half type is represented as an integer (as
1824 // opposed to operations on half, available with NativeHalfType).
1825
1826 // If the half type is supported, just use an fptrunc.
1827 Value *Res = Builder.CreateFPTrunc(V: Src, DestTy: CGF.CGM.HalfTy, Name: "conv");
1828 if (DstTy == CGF.CGM.HalfTy)
1829 return Res;
1830
1831 assert(DstTy->isIntegerTy(16) &&
1832 CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics() &&
1833 "Only half FP requires extra conversion");
1834 return Builder.CreateBitCast(V: Res, DestTy: DstTy);
1835 }
1836
1837 DstTy = CGF.FloatTy;
1838 }
1839
1840 Res = EmitScalarCast(Src, SrcType, DstType, SrcTy, DstTy, Opts);
1841
1842 if (DstTy != ResTy) {
1843 Res = Builder.CreateFPTrunc(V: Res, DestTy: CGF.CGM.HalfTy, Name: "conv");
1844
1845 if (ResTy != CGF.CGM.HalfTy) {
1846 assert(ResTy->isIntegerTy(16) &&
1847 CGF.getContext().getTargetInfo().useFP16ConversionIntrinsics() &&
1848 "Only half FP requires extra conversion");
1849 Res = Builder.CreateBitCast(V: Res, DestTy: ResTy);
1850 }
1851 }
1852
1853 if ((Opts.EmitImplicitIntegerTruncationChecks || OBTrapInvolved) &&
1854 !OBWrapInvolved && !Opts.PatternExcluded)
1855 EmitIntegerTruncationCheck(Src, SrcType: NoncanonicalSrcType, Dst: Res,
1856 DstType: NoncanonicalDstType, Loc, OBTrapInvolved);
1857
1858 if (Opts.EmitImplicitIntegerSignChangeChecks ||
1859 (OBTrapInvolved && !OBWrapInvolved))
1860 EmitIntegerSignChangeCheck(Src, SrcType: NoncanonicalSrcType, Dst: Res,
1861 DstType: NoncanonicalDstType, Loc, OBTrapInvolved);
1862
1863 return Res;
1864}
1865
1866Value *ScalarExprEmitter::EmitFixedPointConversion(Value *Src, QualType SrcTy,
1867 QualType DstTy,
1868 SourceLocation Loc) {
1869 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
1870 llvm::Value *Result;
1871 if (SrcTy->isRealFloatingType())
1872 Result = FPBuilder.CreateFloatingToFixed(Src,
1873 DstSema: CGF.getContext().getFixedPointSemantics(Ty: DstTy));
1874 else if (DstTy->isRealFloatingType())
1875 Result = FPBuilder.CreateFixedToFloating(Src,
1876 SrcSema: CGF.getContext().getFixedPointSemantics(Ty: SrcTy),
1877 DstTy: ConvertType(T: DstTy));
1878 else {
1879 auto SrcFPSema = CGF.getContext().getFixedPointSemantics(Ty: SrcTy);
1880 auto DstFPSema = CGF.getContext().getFixedPointSemantics(Ty: DstTy);
1881
1882 if (DstTy->isIntegerType())
1883 Result = FPBuilder.CreateFixedToInteger(Src, SrcSema: SrcFPSema,
1884 DstWidth: DstFPSema.getWidth(),
1885 DstIsSigned: DstFPSema.isSigned());
1886 else if (SrcTy->isIntegerType())
1887 Result = FPBuilder.CreateIntegerToFixed(Src, SrcIsSigned: SrcFPSema.isSigned(),
1888 DstSema: DstFPSema);
1889 else
1890 Result = FPBuilder.CreateFixedToFixed(Src, SrcSema: SrcFPSema, DstSema: DstFPSema);
1891 }
1892 return Result;
1893}
1894
1895/// Emit a conversion from the specified complex type to the specified
1896/// destination type, where the destination type is an LLVM scalar type.
1897Value *ScalarExprEmitter::EmitComplexToScalarConversion(
1898 CodeGenFunction::ComplexPairTy Src, QualType SrcTy, QualType DstTy,
1899 SourceLocation Loc) {
1900 // Get the source element type.
1901 SrcTy = SrcTy->castAs<ComplexType>()->getElementType();
1902
1903 // Handle conversions to bool first, they are special: comparisons against 0.
1904 if (DstTy->isBooleanType()) {
1905 // Complex != 0 -> (Real != 0) | (Imag != 0)
1906 Src.first = EmitScalarConversion(Src: Src.first, SrcType: SrcTy, DstType: DstTy, Loc);
1907 Src.second = EmitScalarConversion(Src: Src.second, SrcType: SrcTy, DstType: DstTy, Loc);
1908 return Builder.CreateOr(LHS: Src.first, RHS: Src.second, Name: "tobool");
1909 }
1910
1911 // C99 6.3.1.7p2: "When a value of complex type is converted to a real type,
1912 // the imaginary part of the complex value is discarded and the value of the
1913 // real part is converted according to the conversion rules for the
1914 // corresponding real type.
1915 return EmitScalarConversion(Src: Src.first, SrcType: SrcTy, DstType: DstTy, Loc);
1916}
1917
1918Value *ScalarExprEmitter::EmitNullValue(QualType Ty) {
1919 return CGF.EmitFromMemory(Value: CGF.CGM.EmitNullConstant(T: Ty), Ty);
1920}
1921
1922/// Emit a sanitization check for the given "binary" operation (which
1923/// might actually be a unary increment which has been lowered to a binary
1924/// operation). The check passes if all values in \p Checks (which are \c i1),
1925/// are \c true.
1926void ScalarExprEmitter::EmitBinOpCheck(
1927 ArrayRef<std::pair<Value *, SanitizerKind::SanitizerOrdinal>> Checks,
1928 const BinOpInfo &Info) {
1929 assert(CGF.IsSanitizerScope);
1930 SanitizerHandler Check;
1931 SmallVector<llvm::Constant *, 4> StaticData;
1932 SmallVector<llvm::Value *, 2> DynamicData;
1933 TrapReason TR;
1934
1935 BinaryOperatorKind Opcode = Info.Opcode;
1936 if (BinaryOperator::isCompoundAssignmentOp(Opc: Opcode))
1937 Opcode = BinaryOperator::getOpForCompoundAssignment(Opc: Opcode);
1938
1939 StaticData.push_back(Elt: CGF.EmitCheckSourceLocation(Loc: Info.E->getExprLoc()));
1940 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Val: Info.E);
1941 if (UO && UO->getOpcode() == UO_Minus) {
1942 Check = SanitizerHandler::NegateOverflow;
1943 StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: UO->getType()));
1944 DynamicData.push_back(Elt: Info.RHS);
1945 } else {
1946 if (BinaryOperator::isShiftOp(Opc: Opcode)) {
1947 // Shift LHS negative or too large, or RHS out of bounds.
1948 Check = SanitizerHandler::ShiftOutOfBounds;
1949 const BinaryOperator *BO = cast<BinaryOperator>(Val: Info.E);
1950 StaticData.push_back(
1951 Elt: CGF.EmitCheckTypeDescriptor(T: BO->getLHS()->getType()));
1952 StaticData.push_back(
1953 Elt: CGF.EmitCheckTypeDescriptor(T: BO->getRHS()->getType()));
1954 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
1955 // Divide or modulo by zero, or signed overflow (eg INT_MAX / -1).
1956 Check = SanitizerHandler::DivremOverflow;
1957 StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: Info.Ty));
1958 } else {
1959 // Arithmetic overflow (+, -, *).
1960 int ArithOverflowKind = 0;
1961 switch (Opcode) {
1962 case BO_Add: {
1963 Check = SanitizerHandler::AddOverflow;
1964 ArithOverflowKind = diag::UBSanArithKind::Add;
1965 break;
1966 }
1967 case BO_Sub: {
1968 Check = SanitizerHandler::SubOverflow;
1969 ArithOverflowKind = diag::UBSanArithKind::Sub;
1970 break;
1971 }
1972 case BO_Mul: {
1973 Check = SanitizerHandler::MulOverflow;
1974 ArithOverflowKind = diag::UBSanArithKind::Mul;
1975 break;
1976 }
1977 default:
1978 llvm_unreachable("unexpected opcode for bin op check");
1979 }
1980 StaticData.push_back(Elt: CGF.EmitCheckTypeDescriptor(T: Info.Ty));
1981 if (CGF.CGM.getCodeGenOpts().SanitizeTrap.has(
1982 K: SanitizerKind::UnsignedIntegerOverflow) ||
1983 CGF.CGM.getCodeGenOpts().SanitizeTrap.has(
1984 K: SanitizerKind::SignedIntegerOverflow)) {
1985 // Only pay the cost for constructing the trap diagnostic if they are
1986 // going to be used.
1987 CGF.CGM.BuildTrapReason(DiagID: diag::trap_ubsan_arith_overflow, TR)
1988 << Info.Ty->isSignedIntegerOrEnumerationType() << ArithOverflowKind
1989 << Info.E;
1990 }
1991 }
1992 DynamicData.push_back(Elt: Info.LHS);
1993 DynamicData.push_back(Elt: Info.RHS);
1994 }
1995
1996 CGF.EmitCheck(Checked: Checks, Check, StaticArgs: StaticData, DynamicArgs: DynamicData, TR: &TR);
1997}
1998
1999//===----------------------------------------------------------------------===//
2000// Visitor Methods
2001//===----------------------------------------------------------------------===//
2002
2003Value *ScalarExprEmitter::VisitExpr(Expr *E) {
2004 CGF.ErrorUnsupported(S: E, Type: "scalar expression");
2005 if (E->getType()->isVoidType())
2006 return nullptr;
2007 return llvm::PoisonValue::get(T: CGF.ConvertType(T: E->getType()));
2008}
2009
2010Value *
2011ScalarExprEmitter::VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E) {
2012 ASTContext &Context = CGF.getContext();
2013 unsigned AddrSpace =
2014 Context.getTargetAddressSpace(AS: CGF.CGM.GetGlobalConstantAddressSpace());
2015 llvm::Constant *GlobalConstStr = Builder.CreateGlobalString(
2016 Str: E->ComputeName(Context), Name: "__usn_str", AddressSpace: AddrSpace);
2017
2018 llvm::Type *ExprTy = ConvertType(T: E->getType());
2019 return Builder.CreatePointerBitCastOrAddrSpaceCast(V: GlobalConstStr, DestTy: ExprTy,
2020 Name: "usn_addr_cast");
2021}
2022
2023Value *ScalarExprEmitter::VisitEmbedExpr(EmbedExpr *E) {
2024 assert(E->getDataElementCount() == 1);
2025 auto It = E->begin();
2026 return Builder.getInt(AI: (*It)->getValue());
2027}
2028
2029Value *ScalarExprEmitter::VisitShuffleVectorExpr(ShuffleVectorExpr *E) {
2030 // Vector Mask Case
2031 if (E->getNumSubExprs() == 2) {
2032 Value *LHS = CGF.EmitScalarExpr(E: E->getExpr(Index: 0));
2033 Value *RHS = CGF.EmitScalarExpr(E: E->getExpr(Index: 1));
2034 Value *Mask;
2035
2036 auto *LTy = cast<llvm::FixedVectorType>(Val: LHS->getType());
2037 unsigned LHSElts = LTy->getNumElements();
2038
2039 Mask = RHS;
2040
2041 auto *MTy = cast<llvm::FixedVectorType>(Val: Mask->getType());
2042
2043 // Mask off the high bits of each shuffle index.
2044 Value *MaskBits =
2045 llvm::ConstantInt::get(Ty: MTy, V: llvm::NextPowerOf2(A: LHSElts - 1) - 1);
2046 Mask = Builder.CreateAnd(LHS: Mask, RHS: MaskBits, Name: "mask");
2047
2048 // newv = undef
2049 // mask = mask & maskbits
2050 // for each elt
2051 // n = extract mask i
2052 // x = extract val n
2053 // newv = insert newv, x, i
2054 auto *RTy = llvm::FixedVectorType::get(ElementType: LTy->getElementType(),
2055 NumElts: MTy->getNumElements());
2056 Value* NewV = llvm::PoisonValue::get(T: RTy);
2057 for (unsigned i = 0, e = MTy->getNumElements(); i != e; ++i) {
2058 Value *IIndx = llvm::ConstantInt::get(Ty: CGF.SizeTy, V: i);
2059 Value *Indx = Builder.CreateExtractElement(Vec: Mask, Idx: IIndx, Name: "shuf_idx");
2060
2061 Value *VExt = Builder.CreateExtractElement(Vec: LHS, Idx: Indx, Name: "shuf_elt");
2062 NewV = Builder.CreateInsertElement(Vec: NewV, NewElt: VExt, Idx: IIndx, Name: "shuf_ins");
2063 }
2064 return NewV;
2065 }
2066
2067 Value* V1 = CGF.EmitScalarExpr(E: E->getExpr(Index: 0));
2068 Value* V2 = CGF.EmitScalarExpr(E: E->getExpr(Index: 1));
2069
2070 SmallVector<int, 32> Indices;
2071 for (unsigned i = 2; i < E->getNumSubExprs(); ++i) {
2072 llvm::APSInt Idx = E->getShuffleMaskIdx(N: i - 2);
2073 // Check for -1 and output it as undef in the IR.
2074 if (Idx.isSigned() && Idx.isAllOnes())
2075 Indices.push_back(Elt: -1);
2076 else
2077 Indices.push_back(Elt: Idx.getZExtValue());
2078 }
2079
2080 return Builder.CreateShuffleVector(V1, V2, Mask: Indices, Name: "shuffle");
2081}
2082
2083Value *ScalarExprEmitter::VisitConvertVectorExpr(ConvertVectorExpr *E) {
2084 QualType SrcType = E->getSrcExpr()->getType(),
2085 DstType = E->getType();
2086
2087 Value *Src = CGF.EmitScalarExpr(E: E->getSrcExpr());
2088
2089 SrcType = CGF.getContext().getCanonicalType(T: SrcType);
2090 DstType = CGF.getContext().getCanonicalType(T: DstType);
2091 if (SrcType == DstType) return Src;
2092
2093 assert(SrcType->isVectorType() &&
2094 "ConvertVector source type must be a vector");
2095 assert(DstType->isVectorType() &&
2096 "ConvertVector destination type must be a vector");
2097
2098 llvm::Type *SrcTy = Src->getType();
2099 llvm::Type *DstTy = ConvertType(T: DstType);
2100
2101 // Ignore conversions like int -> uint.
2102 if (SrcTy == DstTy)
2103 return Src;
2104
2105 QualType SrcEltType = SrcType->castAs<VectorType>()->getElementType(),
2106 DstEltType = DstType->castAs<VectorType>()->getElementType();
2107
2108 assert(SrcTy->isVectorTy() &&
2109 "ConvertVector source IR type must be a vector");
2110 assert(DstTy->isVectorTy() &&
2111 "ConvertVector destination IR type must be a vector");
2112
2113 llvm::Type *SrcEltTy = cast<llvm::VectorType>(Val: SrcTy)->getElementType(),
2114 *DstEltTy = cast<llvm::VectorType>(Val: DstTy)->getElementType();
2115
2116 if (DstEltType->isBooleanType()) {
2117 assert((SrcEltTy->isFloatingPointTy() ||
2118 isa<llvm::IntegerType>(SrcEltTy)) && "Unknown boolean conversion");
2119
2120 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: SrcTy);
2121 if (SrcEltTy->isFloatingPointTy()) {
2122 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2123 return Builder.CreateFCmpUNE(LHS: Src, RHS: Zero, Name: "tobool");
2124 } else {
2125 return Builder.CreateICmpNE(LHS: Src, RHS: Zero, Name: "tobool");
2126 }
2127 }
2128
2129 // We have the arithmetic types: real int/float.
2130 Value *Res = nullptr;
2131
2132 if (isa<llvm::IntegerType>(Val: SrcEltTy)) {
2133 bool InputSigned = SrcEltType->isSignedIntegerOrEnumerationType();
2134 if (isa<llvm::IntegerType>(Val: DstEltTy))
2135 Res = Builder.CreateIntCast(V: Src, DestTy: DstTy, isSigned: InputSigned, Name: "conv");
2136 else {
2137 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2138 if (InputSigned)
2139 Res = Builder.CreateSIToFP(V: Src, DestTy: DstTy, Name: "conv");
2140 else
2141 Res = Builder.CreateUIToFP(V: Src, DestTy: DstTy, Name: "conv");
2142 }
2143 } else if (isa<llvm::IntegerType>(Val: DstEltTy)) {
2144 assert(SrcEltTy->isFloatingPointTy() && "Unknown real conversion");
2145 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2146 if (DstEltType->isSignedIntegerOrEnumerationType())
2147 Res = Builder.CreateFPToSI(V: Src, DestTy: DstTy, Name: "conv");
2148 else
2149 Res = Builder.CreateFPToUI(V: Src, DestTy: DstTy, Name: "conv");
2150 } else {
2151 assert(SrcEltTy->isFloatingPointTy() && DstEltTy->isFloatingPointTy() &&
2152 "Unknown real conversion");
2153 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, E);
2154 if (DstEltTy->getTypeID() < SrcEltTy->getTypeID())
2155 Res = Builder.CreateFPTrunc(V: Src, DestTy: DstTy, Name: "conv");
2156 else
2157 Res = Builder.CreateFPExt(V: Src, DestTy: DstTy, Name: "conv");
2158 }
2159
2160 return Res;
2161}
2162
2163Value *ScalarExprEmitter::VisitMemberExpr(MemberExpr *E) {
2164 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(ME: E)) {
2165 CGF.EmitIgnoredExpr(E: E->getBase());
2166 return CGF.emitScalarConstant(Constant, E);
2167 } else {
2168 Expr::EvalResult Result;
2169 if (E->EvaluateAsInt(Result, Ctx: CGF.getContext(), AllowSideEffects: Expr::SE_AllowSideEffects)) {
2170 llvm::APSInt Value = Result.Val.getInt();
2171 CGF.EmitIgnoredExpr(E: E->getBase());
2172 return Builder.getInt(AI: Value);
2173 }
2174 }
2175
2176 llvm::Value *Result = EmitLoadOfLValue(E);
2177
2178 // If -fdebug-info-for-profiling is specified, emit a pseudo variable and its
2179 // debug info for the pointer, even if there is no variable associated with
2180 // the pointer's expression.
2181 if (CGF.CGM.getCodeGenOpts().DebugInfoForProfiling && CGF.getDebugInfo()) {
2182 if (llvm::LoadInst *Load = dyn_cast<llvm::LoadInst>(Val: Result)) {
2183 if (llvm::GetElementPtrInst *GEP =
2184 dyn_cast<llvm::GetElementPtrInst>(Val: Load->getPointerOperand())) {
2185 if (llvm::Instruction *Pointer =
2186 dyn_cast<llvm::Instruction>(Val: GEP->getPointerOperand())) {
2187 QualType Ty = E->getBase()->getType();
2188 if (!E->isArrow())
2189 Ty = CGF.getContext().getPointerType(T: Ty);
2190 CGF.getDebugInfo()->EmitPseudoVariable(Builder, Value: Pointer, Ty);
2191 }
2192 }
2193 }
2194 }
2195 return Result;
2196}
2197
2198Value *ScalarExprEmitter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) {
2199 TestAndClearIgnoreResultAssign();
2200
2201 // Emit subscript expressions in rvalue context's. For most cases, this just
2202 // loads the lvalue formed by the subscript expr. However, we have to be
2203 // careful, because the base of a vector subscript is occasionally an rvalue,
2204 // so we can't get it as an lvalue.
2205 if (!E->getBase()->getType()->isVectorType() &&
2206 !E->getBase()->getType()->isSveVLSBuiltinType())
2207 return EmitLoadOfLValue(E);
2208
2209 // Handle the vector case. The base must be a vector, the index must be an
2210 // integer value.
2211 Value *Base = Visit(E: E->getBase());
2212 Value *Idx = Visit(E: E->getIdx());
2213 QualType IdxTy = E->getIdx()->getType();
2214
2215 if (CGF.SanOpts.has(K: SanitizerKind::ArrayBounds))
2216 CGF.EmitBoundsCheck(ArrayExpr: E, ArrayExprBase: E->getBase(), Index: Idx, IndexType: IdxTy, /*Accessed*/true);
2217
2218 Value *Ret = Builder.CreateExtractElement(Vec: Base, Idx, Name: "vecext");
2219
2220 // Even being a scalar the `__mfp8` type corresponds to `<1 x i8>` in LLVM IR.
2221 if (E->getType()->isMFloat8Type())
2222 Ret = Builder.CreateInsertElement(
2223 Vec: llvm::PoisonValue::get(T: llvm::FixedVectorType::get(ElementType: CGF.Int8Ty, NumElts: 1)), NewElt: Ret,
2224 Idx: uint64_t(0), Name: "mfp8ext");
2225
2226 return Ret;
2227}
2228
2229Value *ScalarExprEmitter::VisitMatrixSingleSubscriptExpr(
2230 MatrixSingleSubscriptExpr *E) {
2231 TestAndClearIgnoreResultAssign();
2232
2233 auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
2234 unsigned NumRows = MatrixTy->getNumRows();
2235 unsigned NumColumns = MatrixTy->getNumColumns();
2236
2237 // Row index
2238 Value *RowIdx = CGF.EmitMatrixIndexExpr(E: E->getRowIdx());
2239 llvm::MatrixBuilder MB(Builder);
2240
2241 // The row index must be in [0, NumRows)
2242 if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0)
2243 MB.CreateIndexAssumption(Idx: RowIdx, NumElements: NumRows);
2244
2245 Value *FlatMatrix = Visit(E: E->getBase());
2246 llvm::Type *ElemTy = CGF.ConvertTypeForMem(T: MatrixTy->getElementType());
2247 auto *ResultTy = llvm::FixedVectorType::get(ElementType: ElemTy, NumElts: NumColumns);
2248 Value *RowVec = llvm::PoisonValue::get(T: ResultTy);
2249
2250 bool IsMatrixRowMajor =
2251 isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: E->getBase()->getType());
2252
2253 for (unsigned Col = 0; Col != NumColumns; ++Col) {
2254 Value *ColVal = llvm::ConstantInt::get(Ty: RowIdx->getType(), V: Col);
2255 Value *EltIdx = MB.CreateIndex(RowIdx, ColumnIdx: ColVal, NumRows, NumCols: NumColumns,
2256 IsMatrixRowMajor, Name: "matrix_row_idx");
2257 Value *Elt =
2258 Builder.CreateExtractElement(Vec: FlatMatrix, Idx: EltIdx, Name: "matrix_elem");
2259 Value *Lane = llvm::ConstantInt::get(Ty: Builder.getInt32Ty(), V: Col);
2260 RowVec = Builder.CreateInsertElement(Vec: RowVec, NewElt: Elt, Idx: Lane, Name: "matrix_row_ins");
2261 }
2262
2263 return CGF.EmitFromMemory(Value: RowVec, Ty: E->getType());
2264}
2265
2266Value *ScalarExprEmitter::VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
2267 TestAndClearIgnoreResultAssign();
2268
2269 // Handle the vector case. The base must be a vector, the index must be an
2270 // integer value.
2271 Value *RowIdx = CGF.EmitMatrixIndexExpr(E: E->getRowIdx());
2272 Value *ColumnIdx = CGF.EmitMatrixIndexExpr(E: E->getColumnIdx());
2273
2274 const auto *MatrixTy = E->getBase()->getType()->castAs<ConstantMatrixType>();
2275 llvm::MatrixBuilder MB(Builder);
2276
2277 Value *Idx;
2278 unsigned NumCols = MatrixTy->getNumColumns();
2279 unsigned NumRows = MatrixTy->getNumRows();
2280 bool IsMatrixRowMajor =
2281 isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: E->getBase()->getType());
2282 Idx = MB.CreateIndex(RowIdx, ColumnIdx, NumRows, NumCols, IsMatrixRowMajor);
2283
2284 if (CGF.CGM.getCodeGenOpts().OptimizationLevel > 0)
2285 MB.CreateIndexAssumption(Idx, NumElements: MatrixTy->getNumElementsFlattened());
2286
2287 Value *Matrix = Visit(E: E->getBase());
2288
2289 // TODO: Should we emit bounds checks with SanitizerKind::ArrayBounds?
2290 return Builder.CreateExtractElement(Vec: Matrix, Idx, Name: "matrixext");
2291}
2292
2293static int getMaskElt(llvm::ShuffleVectorInst *SVI, unsigned Idx,
2294 unsigned Off) {
2295 int MV = SVI->getMaskValue(Elt: Idx);
2296 if (MV == -1)
2297 return -1;
2298 return Off + MV;
2299}
2300
2301static int getAsInt32(llvm::ConstantInt *C, llvm::Type *I32Ty) {
2302 assert(llvm::ConstantInt::isValueValidForType(I32Ty, C->getZExtValue()) &&
2303 "Index operand too large for shufflevector mask!");
2304 return C->getZExtValue();
2305}
2306
2307Value *ScalarExprEmitter::VisitInitListExpr(InitListExpr *E) {
2308 bool Ignore = TestAndClearIgnoreResultAssign();
2309 (void)Ignore;
2310 unsigned NumInitElements = E->getNumInits();
2311 assert((Ignore == false ||
2312 (NumInitElements == 0 && E->getType()->isVoidType())) &&
2313 "init list ignored");
2314
2315 // HLSL initialization lists in the AST are an expansion which can contain
2316 // side-effecting expressions wrapped in opaque value expressions. To properly
2317 // emit these we need to emit the opaque values before we emit the argument
2318 // expressions themselves. This is a little hacky, but it prevents us needing
2319 // to do a bigger AST-level change for a language feature that we need
2320 // deprecate in the near future. See related HLSL language proposals in the
2321 // proposals (https://github.com/microsoft/hlsl-specs/blob/main/proposals):
2322 // * 0005-strict-initializer-lists.md
2323 // * 0032-constructors.md
2324 if (CGF.getLangOpts().HLSL)
2325 CGF.CGM.getHLSLRuntime().emitInitListOpaqueValues(CGF, E);
2326
2327 if (E->hadArrayRangeDesignator())
2328 CGF.ErrorUnsupported(S: E, Type: "GNU array range designator extension");
2329
2330 llvm::VectorType *VType =
2331 dyn_cast<llvm::VectorType>(Val: ConvertType(T: E->getType()));
2332
2333 if (!VType) {
2334 if (NumInitElements == 0) {
2335 // C++11 value-initialization for the scalar.
2336 return EmitNullValue(Ty: E->getType());
2337 }
2338 // We have a scalar in braces. Just use the first element.
2339 return Visit(E: E->getInit(Init: 0));
2340 }
2341
2342 if (isa<llvm::ScalableVectorType>(Val: VType)) {
2343 if (NumInitElements == 0) {
2344 // C++11 value-initialization for the vector.
2345 return EmitNullValue(Ty: E->getType());
2346 }
2347
2348 if (NumInitElements == 1) {
2349 Expr *InitVector = E->getInit(Init: 0);
2350
2351 // Initialize from another scalable vector of the same type.
2352 if (InitVector->getType().getCanonicalType() ==
2353 E->getType().getCanonicalType())
2354 return Visit(E: InitVector);
2355 }
2356
2357 llvm_unreachable("Unexpected initialization of a scalable vector!");
2358 }
2359
2360 unsigned ResElts = cast<llvm::FixedVectorType>(Val: VType)->getNumElements();
2361
2362 // For column-major matrix types, we insert elements directly at their
2363 // column-major positions rather than inserting sequentially and shuffling.
2364 const ConstantMatrixType *ColMajorMT = nullptr;
2365 if (const auto *MT = E->getType()->getAs<ConstantMatrixType>();
2366 MT && !isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: E->getType()))
2367 ColMajorMT = MT;
2368
2369 // Loop over initializers collecting the Value for each, and remembering
2370 // whether the source was swizzle (ExtVectorElementExpr). This will allow
2371 // us to fold the shuffle for the swizzle into the shuffle for the vector
2372 // initializer, since LLVM optimizers generally do not want to touch
2373 // shuffles.
2374 unsigned CurIdx = 0;
2375 bool VIsPoisonShuffle = false;
2376 llvm::Value *V = llvm::PoisonValue::get(T: VType);
2377 for (unsigned i = 0; i != NumInitElements; ++i) {
2378 Expr *IE = E->getInit(Init: i);
2379 Value *Init = Visit(E: IE);
2380 SmallVector<int, 16> Args;
2381
2382 llvm::VectorType *VVT = dyn_cast<llvm::VectorType>(Val: Init->getType());
2383
2384 // Handle scalar elements. If the scalar initializer is actually one
2385 // element of a different vector of the same width, use shuffle instead of
2386 // extract+insert.
2387 if (!VVT) {
2388 if (isa<ExtVectorElementExpr>(Val: IE)) {
2389 llvm::ExtractElementInst *EI = cast<llvm::ExtractElementInst>(Val: Init);
2390
2391 if (cast<llvm::FixedVectorType>(Val: EI->getVectorOperandType())
2392 ->getNumElements() == ResElts) {
2393 llvm::ConstantInt *C = cast<llvm::ConstantInt>(Val: EI->getIndexOperand());
2394 Value *LHS = nullptr, *RHS = nullptr;
2395 if (CurIdx == 0) {
2396 // insert into poison -> shuffle (src, poison)
2397 // shufflemask must use an i32
2398 Args.push_back(Elt: getAsInt32(C, I32Ty: CGF.Int32Ty));
2399 Args.resize(N: ResElts, NV: -1);
2400
2401 LHS = EI->getVectorOperand();
2402 RHS = V;
2403 VIsPoisonShuffle = true;
2404 } else if (VIsPoisonShuffle) {
2405 // insert into poison shuffle && size match -> shuffle (v, src)
2406 llvm::ShuffleVectorInst *SVV = cast<llvm::ShuffleVectorInst>(Val: V);
2407 for (unsigned j = 0; j != CurIdx; ++j)
2408 Args.push_back(Elt: getMaskElt(SVI: SVV, Idx: j, Off: 0));
2409 Args.push_back(Elt: ResElts + C->getZExtValue());
2410 Args.resize(N: ResElts, NV: -1);
2411
2412 LHS = cast<llvm::ShuffleVectorInst>(Val: V)->getOperand(i_nocapture: 0);
2413 RHS = EI->getVectorOperand();
2414 VIsPoisonShuffle = false;
2415 }
2416 if (!Args.empty()) {
2417 V = Builder.CreateShuffleVector(V1: LHS, V2: RHS, Mask: Args);
2418 ++CurIdx;
2419 continue;
2420 }
2421 }
2422 }
2423 unsigned InsertIdx =
2424 ColMajorMT
2425 ? ColMajorMT->mapRowMajorToColumnMajorFlattenedIndex(RowMajorIdx: CurIdx)
2426 : CurIdx;
2427 V = Builder.CreateInsertElement(Vec: V, NewElt: Init, Idx: Builder.getInt32(C: InsertIdx),
2428 Name: "vecinit");
2429 VIsPoisonShuffle = false;
2430 ++CurIdx;
2431 continue;
2432 }
2433
2434 unsigned InitElts = cast<llvm::FixedVectorType>(Val: VVT)->getNumElements();
2435
2436 // If the initializer is an ExtVecEltExpr (a swizzle), and the swizzle's
2437 // input is the same width as the vector being constructed, generate an
2438 // optimized shuffle of the swizzle input into the result.
2439 unsigned Offset = (CurIdx == 0) ? 0 : ResElts;
2440 if (isa<ExtVectorElementExpr>(Val: IE)) {
2441 llvm::ShuffleVectorInst *SVI = cast<llvm::ShuffleVectorInst>(Val: Init);
2442 Value *SVOp = SVI->getOperand(i_nocapture: 0);
2443 auto *OpTy = cast<llvm::FixedVectorType>(Val: SVOp->getType());
2444
2445 if (OpTy->getNumElements() == ResElts) {
2446 for (unsigned j = 0; j != CurIdx; ++j) {
2447 // If the current vector initializer is a shuffle with poison, merge
2448 // this shuffle directly into it.
2449 if (VIsPoisonShuffle) {
2450 Args.push_back(Elt: getMaskElt(SVI: cast<llvm::ShuffleVectorInst>(Val: V), Idx: j, Off: 0));
2451 } else {
2452 Args.push_back(Elt: j);
2453 }
2454 }
2455 for (unsigned j = 0, je = InitElts; j != je; ++j)
2456 Args.push_back(Elt: getMaskElt(SVI, Idx: j, Off: Offset));
2457 Args.resize(N: ResElts, NV: -1);
2458
2459 if (VIsPoisonShuffle)
2460 V = cast<llvm::ShuffleVectorInst>(Val: V)->getOperand(i_nocapture: 0);
2461
2462 Init = SVOp;
2463 }
2464 }
2465
2466 // Extend init to result vector length, and then shuffle its contribution
2467 // to the vector initializer into V.
2468 if (Args.empty()) {
2469 for (unsigned j = 0; j != InitElts; ++j)
2470 Args.push_back(Elt: j);
2471 Args.resize(N: ResElts, NV: -1);
2472 Init = Builder.CreateShuffleVector(V: Init, Mask: Args, Name: "vext");
2473
2474 Args.clear();
2475 for (unsigned j = 0; j != CurIdx; ++j)
2476 Args.push_back(Elt: j);
2477 for (unsigned j = 0; j != InitElts; ++j)
2478 Args.push_back(Elt: j + Offset);
2479 Args.resize(N: ResElts, NV: -1);
2480 }
2481
2482 // If V is poison, make sure it ends up on the RHS of the shuffle to aid
2483 // merging subsequent shuffles into this one.
2484 if (CurIdx == 0)
2485 std::swap(a&: V, b&: Init);
2486 V = Builder.CreateShuffleVector(V1: V, V2: Init, Mask: Args, Name: "vecinit");
2487 VIsPoisonShuffle = isa<llvm::PoisonValue>(Val: Init);
2488 CurIdx += InitElts;
2489 }
2490
2491 // FIXME: evaluate codegen vs. shuffling against constant null vector.
2492 // Emit remaining default initializers.
2493 llvm::Type *EltTy = VType->getElementType();
2494
2495 // Emit remaining default initializers
2496 for (/* Do not initialize i*/; CurIdx < ResElts; ++CurIdx) {
2497 unsigned InsertIdx =
2498 ColMajorMT ? ColMajorMT->mapRowMajorToColumnMajorFlattenedIndex(RowMajorIdx: CurIdx)
2499 : CurIdx;
2500 Value *Idx = Builder.getInt32(C: InsertIdx);
2501 llvm::Value *Init = llvm::Constant::getNullValue(Ty: EltTy);
2502 V = Builder.CreateInsertElement(Vec: V, NewElt: Init, Idx, Name: "vecinit");
2503 }
2504
2505 return V;
2506}
2507
2508static bool isDeclRefKnownNonNull(CodeGenFunction &CGF, const ValueDecl *D) {
2509 return !D->isWeak();
2510}
2511
2512static bool isLValueKnownNonNull(CodeGenFunction &CGF, const Expr *E) {
2513 E = E->IgnoreParens();
2514
2515 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E))
2516 if (UO->getOpcode() == UO_Deref)
2517 return CGF.isPointerKnownNonNull(E: UO->getSubExpr());
2518
2519 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: E))
2520 return isDeclRefKnownNonNull(CGF, D: DRE->getDecl());
2521
2522 if (const auto *ME = dyn_cast<MemberExpr>(Val: E)) {
2523 if (isa<FieldDecl>(Val: ME->getMemberDecl()))
2524 return true;
2525 return isDeclRefKnownNonNull(CGF, D: ME->getMemberDecl());
2526 }
2527
2528 // Array subscripts? Anything else?
2529
2530 return false;
2531}
2532
2533bool CodeGenFunction::isPointerKnownNonNull(const Expr *E) {
2534 assert(E->getType()->isSignableType(getContext()));
2535
2536 E = E->IgnoreParens();
2537
2538 if (isa<CXXThisExpr>(Val: E))
2539 return true;
2540
2541 if (const auto *UO = dyn_cast<UnaryOperator>(Val: E))
2542 if (UO->getOpcode() == UO_AddrOf)
2543 return isLValueKnownNonNull(CGF&: *this, E: UO->getSubExpr());
2544
2545 if (const auto *CE = dyn_cast<CastExpr>(Val: E))
2546 if (CE->getCastKind() == CK_FunctionToPointerDecay ||
2547 CE->getCastKind() == CK_ArrayToPointerDecay)
2548 return isLValueKnownNonNull(CGF&: *this, E: CE->getSubExpr());
2549
2550 // Maybe honor __nonnull?
2551
2552 return false;
2553}
2554
2555bool CodeGenFunction::ShouldNullCheckClassCastValue(const CastExpr *CE) {
2556 const Expr *E = CE->getSubExpr();
2557
2558 if (CE->getCastKind() == CK_UncheckedDerivedToBase)
2559 return false;
2560
2561 if (isa<CXXThisExpr>(Val: E->IgnoreParens())) {
2562 // We always assume that 'this' is never null.
2563 return false;
2564 }
2565
2566 if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: CE)) {
2567 // And that glvalue casts are never null.
2568 if (ICE->isGLValue())
2569 return false;
2570 }
2571
2572 return true;
2573}
2574
2575// RHS is an aggregate type
2576static Value *EmitHLSLElementwiseCast(CodeGenFunction &CGF, LValue SrcVal,
2577 QualType DestTy, SourceLocation Loc) {
2578 SmallVector<LValue, 16> LoadList;
2579 CGF.FlattenAccessAndTypeLValue(LVal: SrcVal, AccessList&: LoadList);
2580 // Dest is either a vector, constant matrix, or a builtin
2581 // if its a vector create a temp alloca to store into and return that
2582 if (auto *VecTy = DestTy->getAs<VectorType>()) {
2583 assert(LoadList.size() >= VecTy->getNumElements() &&
2584 "Flattened type on RHS must have the same number or more elements "
2585 "than vector on LHS.");
2586 llvm::Value *V = CGF.Builder.CreateLoad(
2587 Addr: CGF.CreateIRTempWithoutCast(T: DestTy, Name: "flatcast.tmp"));
2588 // write to V.
2589 for (unsigned I = 0, E = VecTy->getNumElements(); I < E; I++) {
2590 RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[I], Loc);
2591 assert(RVal.isScalar() &&
2592 "All flattened source values should be scalars.");
2593 llvm::Value *Cast =
2594 CGF.EmitScalarConversion(Src: RVal.getScalarVal(), SrcTy: LoadList[I].getType(),
2595 DstTy: VecTy->getElementType(), Loc);
2596 V = CGF.Builder.CreateInsertElement(Vec: V, NewElt: Cast, Idx: I);
2597 }
2598 return V;
2599 }
2600 if (auto *MatTy = DestTy->getAs<ConstantMatrixType>()) {
2601 assert(LoadList.size() >= MatTy->getNumElementsFlattened() &&
2602 "Flattened type on RHS must have the same number or more elements "
2603 "than vector on LHS.");
2604
2605 bool IsRowMajor = isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: DestTy);
2606
2607 llvm::Value *V = CGF.Builder.CreateLoad(
2608 Addr: CGF.CreateIRTempWithoutCast(T: DestTy, Name: "flatcast.tmp"));
2609 // V is an allocated temporary for constructing the matrix.
2610 for (unsigned Row = 0, RE = MatTy->getNumRows(); Row < RE; Row++) {
2611 for (unsigned Col = 0, CE = MatTy->getNumColumns(); Col < CE; Col++) {
2612 // When interpreted as a matrix, \p LoadList is *always* row-major order
2613 // regardless of the default matrix memory layout.
2614 unsigned LoadIdx = MatTy->getRowMajorFlattenedIndex(Row, Column: Col);
2615 RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[LoadIdx], Loc);
2616 assert(RVal.isScalar() &&
2617 "All flattened source values should be scalars.");
2618 llvm::Value *Cast = CGF.EmitScalarConversion(
2619 Src: RVal.getScalarVal(), SrcTy: LoadList[LoadIdx].getType(),
2620 DstTy: MatTy->getElementType(), Loc);
2621 unsigned MatrixIdx = MatTy->getFlattenedIndex(Row, Column: Col, IsRowMajor);
2622 V = CGF.Builder.CreateInsertElement(Vec: V, NewElt: Cast, Idx: MatrixIdx);
2623 }
2624 }
2625 return V;
2626 }
2627 // if its a builtin just do an extract element or load.
2628 assert(DestTy->isBuiltinType() &&
2629 "Destination type must be a vector, matrix, or builtin type.");
2630 RValue RVal = CGF.EmitLoadOfLValue(V: LoadList[0], Loc);
2631 assert(RVal.isScalar() && "All flattened source values should be scalars.");
2632 return CGF.EmitScalarConversion(Src: RVal.getScalarVal(), SrcTy: LoadList[0].getType(),
2633 DstTy: DestTy, Loc);
2634}
2635
2636// VisitCastExpr - Emit code for an explicit or implicit cast. Implicit casts
2637// have to handle a more broad range of conversions than explicit casts, as they
2638// handle things like function to ptr-to-function decay etc.
2639Value *ScalarExprEmitter::VisitCastExpr(CastExpr *CE) {
2640 llvm::scope_exit RestoreCurCast(
2641 [this, Prev = CGF.CurCast] { CGF.CurCast = Prev; });
2642 CGF.CurCast = CE;
2643
2644 Expr *E = CE->getSubExpr();
2645 QualType DestTy = CE->getType();
2646 CastKind Kind = CE->getCastKind();
2647 CodeGenFunction::CGFPOptionsRAII FPOptions(CGF, CE);
2648
2649 // These cases are generally not written to ignore the result of
2650 // evaluating their sub-expressions, so we clear this now.
2651 bool Ignored = TestAndClearIgnoreResultAssign();
2652
2653 // Since almost all cast kinds apply to scalars, this switch doesn't have
2654 // a default case, so the compiler will warn on a missing case. The cases
2655 // are in the same order as in the CastKind enum.
2656 switch (Kind) {
2657 case CK_Dependent: llvm_unreachable("dependent cast kind in IR gen!");
2658 case CK_BuiltinFnToFnPtr:
2659 llvm_unreachable("builtin functions are handled elsewhere");
2660
2661 case CK_LValueBitCast:
2662 case CK_ObjCObjectLValueCast: {
2663 Address Addr = EmitLValue(E).getAddress();
2664 Addr = Addr.withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy));
2665 LValue LV = CGF.MakeAddrLValue(Addr, T: DestTy);
2666 return EmitLoadOfLValue(LV, Loc: CE->getExprLoc());
2667 }
2668
2669 case CK_LValueToRValueBitCast: {
2670 LValue SourceLVal = CGF.EmitLValue(E);
2671 Address Addr =
2672 SourceLVal.getAddress().withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy));
2673 LValue DestLV = CGF.MakeAddrLValue(Addr, T: DestTy);
2674 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2675 return EmitLoadOfLValue(LV: DestLV, Loc: CE->getExprLoc());
2676 }
2677
2678 case CK_CPointerToObjCPointerCast:
2679 case CK_BlockPointerToObjCPointerCast:
2680 case CK_AnyPointerToBlockPointerCast:
2681 case CK_BitCast: {
2682 Value *Src = Visit(E);
2683 llvm::Type *SrcTy = Src->getType();
2684 llvm::Type *DstTy = ConvertType(T: DestTy);
2685
2686 // FIXME: this is a gross but seemingly necessary workaround for an issue
2687 // manifesting when a target uses a non-default AS for indirect sret args,
2688 // but the source HLL is generic, wherein a valid C-cast or reinterpret_cast
2689 // on the address of a local struct that gets returned by value yields an
2690 // invalid bitcast from the a pointer to the IndirectAS to a pointer to the
2691 // DefaultAS. We can only do this subversive thing because sret args are
2692 // manufactured and them residing in the IndirectAS is a target specific
2693 // detail, and doing an AS cast here still retains the semantics the user
2694 // expects. It is desirable to remove this iff a better solution is found.
2695 if (auto A = dyn_cast<llvm::Argument>(Val: Src); A && A->hasStructRetAttr())
2696 return CGF.performAddrSpaceCast(Src, DestTy: DstTy);
2697
2698 // FIXME: Similarly to the sret case above, we need to handle BitCasts that
2699 // involve implicit address space conversions. This arises when the source
2700 // language lacks explicit address spaces, but the target's data layout
2701 // assigns different address spaces (e.g., program address space for
2702 // function pointers). Since Sema operates on Clang types (which don't carry
2703 // this information) and selects CK_BitCast, we must detect the address
2704 // space mismatch here in CodeGen when lowering to LLVM types. The most
2705 // common case is casting function pointers (which get the program AS from
2706 // the data layout) to/from object pointers (which use the default AS).
2707 // Ideally, this would be resolved at a higher level, but that would require
2708 // exposing data layout details to Sema.
2709 if (SrcTy->isPtrOrPtrVectorTy() && DstTy->isPtrOrPtrVectorTy() &&
2710 SrcTy->getPointerAddressSpace() != DstTy->getPointerAddressSpace()) {
2711 return CGF.performAddrSpaceCast(Src, DestTy: DstTy);
2712 }
2713
2714 assert(
2715 (!SrcTy->isPtrOrPtrVectorTy() || !DstTy->isPtrOrPtrVectorTy() ||
2716 SrcTy->getPointerAddressSpace() == DstTy->getPointerAddressSpace()) &&
2717 "Address-space cast must be used to convert address spaces");
2718
2719 if (CGF.SanOpts.has(K: SanitizerKind::CFIUnrelatedCast)) {
2720 if (auto *PT = DestTy->getAs<PointerType>()) {
2721 CGF.EmitVTablePtrCheckForCast(
2722 T: PT->getPointeeType(),
2723 Derived: Address(Src,
2724 CGF.ConvertTypeForMem(
2725 T: E->getType()->castAs<PointerType>()->getPointeeType()),
2726 CGF.getPointerAlign()),
2727 /*MayBeNull=*/true, TCK: CodeGenFunction::CFITCK_UnrelatedCast,
2728 Loc: CE->getBeginLoc());
2729 }
2730 }
2731
2732 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
2733 const QualType SrcType = E->getType();
2734
2735 if (SrcType.mayBeNotDynamicClass() && DestTy.mayBeDynamicClass()) {
2736 // Casting to pointer that could carry dynamic information (provided by
2737 // invariant.group) requires launder.
2738 Src = Builder.CreateLaunderInvariantGroup(Ptr: Src);
2739 } else if (SrcType.mayBeDynamicClass() && DestTy.mayBeNotDynamicClass()) {
2740 // Casting to pointer that does not carry dynamic information (provided
2741 // by invariant.group) requires stripping it. Note that we don't do it
2742 // if the source could not be dynamic type and destination could be
2743 // dynamic because dynamic information is already laundered. It is
2744 // because launder(strip(src)) == launder(src), so there is no need to
2745 // add extra strip before launder.
2746 Src = Builder.CreateStripInvariantGroup(Ptr: Src);
2747 }
2748 }
2749
2750 // Update heapallocsite metadata when there is an explicit pointer cast.
2751 if (auto *CI = dyn_cast<llvm::CallBase>(Val: Src)) {
2752 if (CI->getMetadata(Kind: "heapallocsite") && isa<ExplicitCastExpr>(Val: CE) &&
2753 !isa<CastExpr>(Val: E)) {
2754 QualType PointeeType = DestTy->getPointeeType();
2755 if (!PointeeType.isNull())
2756 CGF.getDebugInfo()->addHeapAllocSiteMetadata(CallSite: CI, AllocatedTy: PointeeType,
2757 Loc: CE->getExprLoc());
2758 }
2759 }
2760
2761 // If Src is a fixed vector and Dst is a scalable vector, and both have the
2762 // same element type, use the llvm.vector.insert intrinsic to perform the
2763 // bitcast.
2764 if (auto *FixedSrcTy = dyn_cast<llvm::FixedVectorType>(Val: SrcTy)) {
2765 if (auto *ScalableDstTy = dyn_cast<llvm::ScalableVectorType>(Val: DstTy)) {
2766 // If we are casting a fixed i8 vector to a scalable i1 predicate
2767 // vector, use a vector insert and bitcast the result.
2768 if (ScalableDstTy->getElementType()->isIntegerTy(BitWidth: 1) &&
2769 FixedSrcTy->getElementType()->isIntegerTy(BitWidth: 8)) {
2770 ScalableDstTy = llvm::ScalableVectorType::get(
2771 ElementType: FixedSrcTy->getElementType(),
2772 MinNumElts: llvm::divideCeil(
2773 Numerator: ScalableDstTy->getElementCount().getKnownMinValue(), Denominator: 8));
2774 }
2775 if (FixedSrcTy->getElementType() == ScalableDstTy->getElementType()) {
2776 llvm::Value *PoisonVec = llvm::PoisonValue::get(T: ScalableDstTy);
2777 llvm::Value *Result = Builder.CreateInsertVector(
2778 DstType: ScalableDstTy, SrcVec: PoisonVec, SubVec: Src, Idx: uint64_t(0), Name: "cast.scalable");
2779 ScalableDstTy = cast<llvm::ScalableVectorType>(
2780 Val: llvm::VectorType::getWithSizeAndScalar(SizeTy: ScalableDstTy, EltTy: DstTy));
2781 if (Result->getType() != ScalableDstTy)
2782 Result = Builder.CreateBitCast(V: Result, DestTy: ScalableDstTy);
2783 if (Result->getType() != DstTy)
2784 Result = Builder.CreateExtractVector(DstType: DstTy, SrcVec: Result, Idx: uint64_t(0));
2785 return Result;
2786 }
2787 }
2788 }
2789
2790 // If Src is a scalable vector and Dst is a fixed vector, and both have the
2791 // same element type, use the llvm.vector.extract intrinsic to perform the
2792 // bitcast.
2793 if (auto *ScalableSrcTy = dyn_cast<llvm::ScalableVectorType>(Val: SrcTy)) {
2794 if (auto *FixedDstTy = dyn_cast<llvm::FixedVectorType>(Val: DstTy)) {
2795 // If we are casting a scalable i1 predicate vector to a fixed i8
2796 // vector, bitcast the source and use a vector extract.
2797 if (ScalableSrcTy->getElementType()->isIntegerTy(BitWidth: 1) &&
2798 FixedDstTy->getElementType()->isIntegerTy(BitWidth: 8)) {
2799 if (!ScalableSrcTy->getElementCount().isKnownMultipleOf(RHS: 8)) {
2800 ScalableSrcTy = llvm::ScalableVectorType::get(
2801 ElementType: ScalableSrcTy->getElementType(),
2802 MinNumElts: llvm::alignTo<8>(
2803 Value: ScalableSrcTy->getElementCount().getKnownMinValue()));
2804 llvm::Value *ZeroVec = llvm::Constant::getNullValue(Ty: ScalableSrcTy);
2805 Src = Builder.CreateInsertVector(DstType: ScalableSrcTy, SrcVec: ZeroVec, SubVec: Src,
2806 Idx: uint64_t(0));
2807 }
2808
2809 ScalableSrcTy = llvm::ScalableVectorType::get(
2810 ElementType: FixedDstTy->getElementType(),
2811 MinNumElts: ScalableSrcTy->getElementCount().getKnownMinValue() / 8);
2812 Src = Builder.CreateBitCast(V: Src, DestTy: ScalableSrcTy);
2813 }
2814 if (ScalableSrcTy->getElementType() == FixedDstTy->getElementType())
2815 return Builder.CreateExtractVector(DstType: DstTy, SrcVec: Src, Idx: uint64_t(0),
2816 Name: "cast.fixed");
2817 }
2818 }
2819
2820 // Perform VLAT <-> VLST bitcast through memory.
2821 // TODO: since the llvm.vector.{insert,extract} intrinsics
2822 // require the element types of the vectors to be the same, we
2823 // need to keep this around for bitcasts between VLAT <-> VLST where
2824 // the element types of the vectors are not the same, until we figure
2825 // out a better way of doing these casts.
2826 if ((isa<llvm::FixedVectorType>(Val: SrcTy) &&
2827 isa<llvm::ScalableVectorType>(Val: DstTy)) ||
2828 (isa<llvm::ScalableVectorType>(Val: SrcTy) &&
2829 isa<llvm::FixedVectorType>(Val: DstTy))) {
2830 Address Addr = CGF.CreateDefaultAlignTempAlloca(Ty: SrcTy, Name: "saved-value");
2831 LValue LV = CGF.MakeAddrLValue(Addr, T: E->getType());
2832 CGF.EmitStoreOfScalar(value: Src, lvalue: LV);
2833 Addr = Addr.withElementType(ElemTy: CGF.ConvertTypeForMem(T: DestTy));
2834 LValue DestLV = CGF.MakeAddrLValue(Addr, T: DestTy);
2835 DestLV.setTBAAInfo(TBAAAccessInfo::getMayAliasInfo());
2836 return EmitLoadOfLValue(LV: DestLV, Loc: CE->getExprLoc());
2837 }
2838
2839 llvm::Value *Result = Builder.CreateBitCast(V: Src, DestTy: DstTy);
2840 return CGF.authPointerToPointerCast(ResultPtr: Result, SourceType: E->getType(), DestType: DestTy);
2841 }
2842 case CK_AddressSpaceConversion: {
2843 llvm::Type *DestLTy = ConvertType(T: DestTy);
2844 // WebAssembly reference types are opaque target extension types so an
2845 // "address space conversion" involving them is not a real pointer cast.
2846 auto IsWasmFuncref = [](llvm::Type *T) {
2847 auto *TET = dyn_cast<llvm::TargetExtType>(Val: T);
2848 return TET && TET->getName() == "wasm.funcref";
2849 };
2850 bool SrcIsFuncref = IsWasmFuncref(ConvertType(T: E->getType()));
2851 bool DestIsFuncref = IsWasmFuncref(DestLTy);
2852 if (SrcIsFuncref && DestIsFuncref) {
2853 // funcref -> funcref (e.g. between differently-typed funcrefs) is the
2854 // identity on the opaque reference value.
2855 return Visit(E);
2856 }
2857 if (SrcIsFuncref && !DestIsFuncref) {
2858 // funcref -> pointer: use wasm_funcref_to_ptr. This will probably crash
2859 // later in codegen since we haven't implemented a way to actually get a
2860 // function pointer from a funcref.
2861 llvm::Function *ToPtr =
2862 CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::wasm_funcref_to_ptr);
2863 return CGF.Builder.CreateCall(Callee: ToPtr, Args: {Visit(E)});
2864 }
2865 if (!SrcIsFuncref && DestIsFuncref) {
2866 // A null function pointer converts to a null funcref (ref.null func),
2867 // rather than a table lookup at index 0.
2868 Expr::EvalResult NullResult;
2869 if (E->EvaluateAsRValue(Result&: NullResult, Ctx: CGF.getContext()) &&
2870 NullResult.Val.isNullPointer()) {
2871 if (NullResult.HasSideEffects)
2872 Visit(E);
2873 return llvm::Constant::getNullValue(Ty: DestLTy);
2874 }
2875 // pointer -> funcref: do a table.get from the indirect function table.
2876 llvm::Function *ToFuncref =
2877 CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::wasm_ptr_to_funcref);
2878 return CGF.Builder.CreateCall(Callee: ToFuncref, Args: {Visit(E)});
2879 }
2880 Expr::EvalResult Result;
2881 if (E->EvaluateAsRValue(Result, Ctx: CGF.getContext()) &&
2882 Result.Val.isNullPointer()) {
2883 // If E has side effect, it is emitted even if its final result is a
2884 // null pointer. In that case, a DCE pass should be able to
2885 // eliminate the useless instructions emitted during translating E.
2886 if (Result.HasSideEffects)
2887 Visit(E);
2888 return CGF.CGM.getNullPointer(T: cast<llvm::PointerType>(Val: DestLTy), QT: DestTy);
2889 }
2890 // Since target may map different address spaces in AST to the same address
2891 // space, an address space conversion may end up as a bitcast.
2892 return CGF.performAddrSpaceCast(Src: Visit(E), DestTy: DestLTy);
2893 }
2894 case CK_AtomicToNonAtomic:
2895 case CK_NonAtomicToAtomic:
2896 case CK_UserDefinedConversion:
2897 return Visit(E);
2898
2899 case CK_NoOp: {
2900 return CE->changesVolatileQualification() ? EmitLoadOfLValue(E: CE) : Visit(E);
2901 }
2902
2903 case CK_BaseToDerived: {
2904 const CXXRecordDecl *DerivedClassDecl = DestTy->getPointeeCXXRecordDecl();
2905 assert(DerivedClassDecl && "BaseToDerived arg isn't a C++ object pointer!");
2906
2907 Address Base = CGF.EmitPointerWithAlignment(Addr: E);
2908 Address Derived =
2909 CGF.GetAddressOfDerivedClass(Value: Base, Derived: DerivedClassDecl,
2910 PathBegin: CE->path_begin(), PathEnd: CE->path_end(),
2911 NullCheckValue: CGF.ShouldNullCheckClassCastValue(CE));
2912
2913 // C++11 [expr.static.cast]p11: Behavior is undefined if a downcast is
2914 // performed and the object is not of the derived type.
2915 if (CGF.sanitizePerformTypeCheck())
2916 CGF.EmitTypeCheck(TCK: CodeGenFunction::TCK_DowncastPointer, Loc: CE->getExprLoc(),
2917 Addr: Derived, Type: DestTy->getPointeeType());
2918
2919 if (CGF.SanOpts.has(K: SanitizerKind::CFIDerivedCast))
2920 CGF.EmitVTablePtrCheckForCast(T: DestTy->getPointeeType(), Derived,
2921 /*MayBeNull=*/true,
2922 TCK: CodeGenFunction::CFITCK_DerivedCast,
2923 Loc: CE->getBeginLoc());
2924
2925 return CGF.getAsNaturalPointerTo(Addr: Derived, PointeeType: CE->getType()->getPointeeType());
2926 }
2927 case CK_UncheckedDerivedToBase:
2928 case CK_DerivedToBase: {
2929 // The EmitPointerWithAlignment path does this fine; just discard
2930 // the alignment.
2931 return CGF.getAsNaturalPointerTo(Addr: CGF.EmitPointerWithAlignment(Addr: CE),
2932 PointeeType: CE->getType()->getPointeeType());
2933 }
2934
2935 case CK_Dynamic: {
2936 Address V = CGF.EmitPointerWithAlignment(Addr: E);
2937 const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(Val: CE);
2938 return CGF.EmitDynamicCast(V, DCE);
2939 }
2940
2941 case CK_ArrayToPointerDecay:
2942 return CGF.getAsNaturalPointerTo(Addr: CGF.EmitArrayToPointerDecay(Array: E),
2943 PointeeType: CE->getType()->getPointeeType());
2944 case CK_FunctionToPointerDecay:
2945 return EmitLValue(E).getPointer(CGF);
2946
2947 case CK_NullToPointer:
2948 if (MustVisitNullValue(E))
2949 CGF.EmitIgnoredExpr(E);
2950
2951 return CGF.CGM.getNullPointer(T: cast<llvm::PointerType>(Val: ConvertType(T: DestTy)),
2952 QT: DestTy);
2953
2954 case CK_NullToMemberPointer: {
2955 if (MustVisitNullValue(E))
2956 CGF.EmitIgnoredExpr(E);
2957
2958 const MemberPointerType *MPT = CE->getType()->getAs<MemberPointerType>();
2959 return CGF.CGM.getCXXABI().EmitNullMemberPointer(MPT);
2960 }
2961
2962 case CK_ReinterpretMemberPointer:
2963 case CK_BaseToDerivedMemberPointer:
2964 case CK_DerivedToBaseMemberPointer: {
2965 Value *Src = Visit(E);
2966
2967 // Note that the AST doesn't distinguish between checked and
2968 // unchecked member pointer conversions, so we always have to
2969 // implement checked conversions here. This is inefficient when
2970 // actual control flow may be required in order to perform the
2971 // check, which it is for data member pointers (but not member
2972 // function pointers on Itanium and ARM).
2973 return CGF.CGM.getCXXABI().EmitMemberPointerConversion(CGF, E: CE, Src);
2974 }
2975
2976 case CK_ARCProduceObject:
2977 return CGF.EmitARCRetainScalarExpr(expr: E);
2978 case CK_ARCConsumeObject:
2979 return CGF.EmitObjCConsumeObject(T: E->getType(), Ptr: Visit(E));
2980 case CK_ARCReclaimReturnedObject:
2981 return CGF.EmitARCReclaimReturnedObject(e: E, /*allowUnsafe*/ allowUnsafeClaim: Ignored);
2982 case CK_ARCExtendBlockObject:
2983 return CGF.EmitARCExtendBlockObject(expr: E);
2984
2985 case CK_CopyAndAutoreleaseBlockObject:
2986 return CGF.EmitBlockCopyAndAutorelease(Block: Visit(E), Ty: E->getType());
2987
2988 case CK_FloatingRealToComplex:
2989 case CK_FloatingComplexCast:
2990 case CK_IntegralRealToComplex:
2991 case CK_IntegralComplexCast:
2992 case CK_IntegralComplexToFloatingComplex:
2993 case CK_FloatingComplexToIntegralComplex:
2994 case CK_ConstructorConversion:
2995 case CK_ToUnion:
2996 case CK_HLSLArrayRValue:
2997 llvm_unreachable("scalar cast to non-scalar value");
2998
2999 case CK_LValueToRValue:
3000 assert(CGF.getContext().hasSameUnqualifiedType(E->getType(), DestTy));
3001 assert(E->isGLValue() && "lvalue-to-rvalue applied to r-value!");
3002 return Visit(E);
3003
3004 case CK_IntegralToPointer: {
3005 Value *Src = Visit(E);
3006
3007 // First, convert to the correct width so that we control the kind of
3008 // extension.
3009 auto DestLLVMTy = ConvertType(T: DestTy);
3010 llvm::Type *MiddleTy = CGF.CGM.getDataLayout().getIntPtrType(DestLLVMTy);
3011 bool InputSigned = E->getType()->isSignedIntegerOrEnumerationType();
3012 llvm::Value* IntResult =
3013 Builder.CreateIntCast(V: Src, DestTy: MiddleTy, isSigned: InputSigned, Name: "conv");
3014
3015 auto *IntToPtr = Builder.CreateIntToPtr(V: IntResult, DestTy: DestLLVMTy);
3016
3017 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
3018 // Going from integer to pointer that could be dynamic requires reloading
3019 // dynamic information from invariant.group.
3020 if (DestTy.mayBeDynamicClass())
3021 IntToPtr = Builder.CreateLaunderInvariantGroup(Ptr: IntToPtr);
3022 }
3023
3024 IntToPtr = CGF.authPointerToPointerCast(ResultPtr: IntToPtr, SourceType: E->getType(), DestType: DestTy);
3025 return IntToPtr;
3026 }
3027 case CK_PointerToIntegral: {
3028 assert(!DestTy->isBooleanType() && "bool should use PointerToBool");
3029 auto *PtrExpr = Visit(E);
3030
3031 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers) {
3032 const QualType SrcType = E->getType();
3033
3034 // Casting to integer requires stripping dynamic information as it does
3035 // not carries it.
3036 if (SrcType.mayBeDynamicClass())
3037 PtrExpr = Builder.CreateStripInvariantGroup(Ptr: PtrExpr);
3038 }
3039
3040 PtrExpr = CGF.authPointerToPointerCast(ResultPtr: PtrExpr, SourceType: E->getType(), DestType: DestTy);
3041 return Builder.CreatePtrToInt(V: PtrExpr, DestTy: ConvertType(T: DestTy));
3042 }
3043 case CK_ToVoid: {
3044 CGF.EmitIgnoredExpr(E);
3045 return nullptr;
3046 }
3047 case CK_MatrixCast: {
3048 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3049 Loc: CE->getExprLoc());
3050 }
3051 // CK_HLSLAggregateSplatCast only handles splatting to vectors from a vec1
3052 // Casts were inserted in Sema to Cast the Src Expr to a Scalar and
3053 // To perform any necessary Scalar Cast, so this Cast can be handled
3054 // by the regular Vector Splat cast code.
3055 case CK_HLSLAggregateSplatCast:
3056 case CK_VectorSplat: {
3057 llvm::Type *DstTy = ConvertType(T: DestTy);
3058 Value *Elt = Visit(E);
3059 // Splat the element across to all elements
3060 llvm::ElementCount NumElements =
3061 cast<llvm::VectorType>(Val: DstTy)->getElementCount();
3062 return Builder.CreateVectorSplat(EC: NumElements, V: Elt, Name: "splat");
3063 }
3064
3065 case CK_FixedPointCast:
3066 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3067 Loc: CE->getExprLoc());
3068
3069 case CK_FixedPointToBoolean:
3070 assert(E->getType()->isFixedPointType() &&
3071 "Expected src type to be fixed point type");
3072 assert(DestTy->isBooleanType() && "Expected dest type to be boolean type");
3073 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3074 Loc: CE->getExprLoc());
3075
3076 case CK_FixedPointToIntegral:
3077 assert(E->getType()->isFixedPointType() &&
3078 "Expected src type to be fixed point type");
3079 assert(DestTy->isIntegerType() && "Expected dest type to be an integer");
3080 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3081 Loc: CE->getExprLoc());
3082
3083 case CK_IntegralToFixedPoint:
3084 assert(E->getType()->isIntegerType() &&
3085 "Expected src type to be an integer");
3086 assert(DestTy->isFixedPointType() &&
3087 "Expected dest type to be fixed point type");
3088 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3089 Loc: CE->getExprLoc());
3090
3091 case CK_IntegralCast: {
3092 if (E->getType()->isExtVectorType() && DestTy->isExtVectorType()) {
3093 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
3094 return Builder.CreateIntCast(V: Visit(E), DestTy: ConvertType(T: DestTy),
3095 isSigned: SrcElTy->isSignedIntegerOrEnumerationType(),
3096 Name: "conv");
3097 }
3098 ScalarConversionOpts Opts;
3099 if (auto *ICE = dyn_cast<ImplicitCastExpr>(Val: CE)) {
3100 if (!ICE->isPartOfExplicitCast())
3101 Opts = ScalarConversionOpts(CGF.SanOpts);
3102 }
3103 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3104 Loc: CE->getExprLoc(), Opts);
3105 }
3106 case CK_IntegralToFloating: {
3107 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
3108 // TODO: Support constrained FP intrinsics.
3109 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
3110 if (SrcElTy->isSignedIntegerOrEnumerationType())
3111 return Builder.CreateSIToFP(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3112 return Builder.CreateUIToFP(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3113 }
3114 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3115 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3116 Loc: CE->getExprLoc());
3117 }
3118 case CK_FloatingToIntegral: {
3119 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
3120 // TODO: Support constrained FP intrinsics.
3121 QualType DstElTy = DestTy->castAs<VectorType>()->getElementType();
3122 if (DstElTy->isSignedIntegerOrEnumerationType())
3123 return Builder.CreateFPToSI(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3124 return Builder.CreateFPToUI(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3125 }
3126 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3127 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3128 Loc: CE->getExprLoc());
3129 }
3130 case CK_FloatingCast: {
3131 if (E->getType()->isVectorType() && DestTy->isVectorType()) {
3132 // TODO: Support constrained FP intrinsics.
3133 QualType SrcElTy = E->getType()->castAs<VectorType>()->getElementType();
3134 QualType DstElTy = DestTy->castAs<VectorType>()->getElementType();
3135 if (DstElTy->castAs<BuiltinType>()->getKind() <
3136 SrcElTy->castAs<BuiltinType>()->getKind())
3137 return Builder.CreateFPTrunc(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3138 return Builder.CreateFPExt(V: Visit(E), DestTy: ConvertType(T: DestTy), Name: "conv");
3139 }
3140 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3141 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3142 Loc: CE->getExprLoc());
3143 }
3144 case CK_FixedPointToFloating:
3145 case CK_FloatingToFixedPoint: {
3146 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3147 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3148 Loc: CE->getExprLoc());
3149 }
3150 case CK_BooleanToSignedIntegral: {
3151 ScalarConversionOpts Opts;
3152 Opts.TreatBooleanAsSigned = true;
3153 return EmitScalarConversion(Src: Visit(E), SrcType: E->getType(), DstType: DestTy,
3154 Loc: CE->getExprLoc(), Opts);
3155 }
3156 case CK_IntegralToBoolean:
3157 return EmitIntToBoolConversion(V: Visit(E));
3158 case CK_PointerToBoolean:
3159 return EmitPointerToBoolConversion(V: Visit(E), QT: E->getType());
3160 case CK_FloatingToBoolean: {
3161 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, CE);
3162 return EmitFloatToBoolConversion(V: Visit(E));
3163 }
3164 case CK_MemberPointerToBoolean: {
3165 llvm::Value *MemPtr = Visit(E);
3166 const MemberPointerType *MPT = E->getType()->getAs<MemberPointerType>();
3167 return CGF.CGM.getCXXABI().EmitMemberPointerIsNotNull(CGF, MemPtr, MPT);
3168 }
3169
3170 case CK_FloatingComplexToReal:
3171 case CK_IntegralComplexToReal:
3172 return CGF.EmitComplexExpr(E, IgnoreReal: false, IgnoreImag: true).first;
3173
3174 case CK_FloatingComplexToBoolean:
3175 case CK_IntegralComplexToBoolean: {
3176 CodeGenFunction::ComplexPairTy V = CGF.EmitComplexExpr(E);
3177
3178 // TODO: kill this function off, inline appropriate case here
3179 return EmitComplexToScalarConversion(Src: V, SrcTy: E->getType(), DstTy: DestTy,
3180 Loc: CE->getExprLoc());
3181 }
3182
3183 case CK_ZeroToOCLOpaqueType: {
3184 assert((DestTy->isEventT() || DestTy->isQueueT() ||
3185 DestTy->isOCLIntelSubgroupAVCType()) &&
3186 "CK_ZeroToOCLEvent cast on non-event type");
3187 return llvm::Constant::getNullValue(Ty: ConvertType(T: DestTy));
3188 }
3189
3190 case CK_IntToOCLSampler:
3191 return CGF.CGM.createOpenCLIntToSamplerConversion(E, CGF);
3192
3193 case CK_HLSLVectorTruncation: {
3194 assert((DestTy->isVectorType() || DestTy->isBuiltinType()) &&
3195 "Destination type must be a vector or builtin type.");
3196 Value *Vec = Visit(E);
3197 if (auto *VecTy = DestTy->getAs<VectorType>()) {
3198 SmallVector<int> Mask;
3199 unsigned NumElts = VecTy->getNumElements();
3200 for (unsigned I = 0; I != NumElts; ++I)
3201 Mask.push_back(Elt: I);
3202
3203 return Builder.CreateShuffleVector(V: Vec, Mask, Name: "trunc");
3204 }
3205 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: CGF.SizeTy);
3206 return Builder.CreateExtractElement(Vec, Idx: Zero, Name: "cast.vtrunc");
3207 }
3208 case CK_HLSLMatrixTruncation: {
3209 assert((DestTy->isMatrixType() || DestTy->isBuiltinType()) &&
3210 "Destination type must be a matrix or builtin type.");
3211 Value *Mat = Visit(E);
3212 if (auto *MatTy = DestTy->getAs<ConstantMatrixType>()) {
3213 SmallVector<int> Mask(MatTy->getNumElementsFlattened());
3214 unsigned NumCols = MatTy->getNumColumns();
3215 unsigned NumRows = MatTy->getNumRows();
3216 auto *SrcMatTy = E->getType()->getAs<ConstantMatrixType>();
3217 assert(SrcMatTy && "Source type must be a matrix type.");
3218 assert(NumRows <= SrcMatTy->getNumRows());
3219 assert(NumCols <= SrcMatTy->getNumColumns());
3220
3221 // isMatrix[Src|Dst]RowMajor needs the full sugared QualType to find
3222 // matrix layout attrs. So use E->getType() & DestTy rather than SrcMatTy
3223 // & MatTy b/c getAs<ConstantMatrixType>() strips the sugar.
3224 bool IsSrcRowMajor = isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: E->getType());
3225 bool IsDstRowMajor = isMatrixRowMajor(LangOpts: CGF.getLangOpts(), T: DestTy);
3226 for (unsigned R = 0; R < NumRows; R++)
3227 for (unsigned C = 0; C < NumCols; C++)
3228 Mask[MatTy->getFlattenedIndex(Row: R, Column: C, IsRowMajor: IsDstRowMajor)] =
3229 SrcMatTy->getFlattenedIndex(Row: R, Column: C, IsRowMajor: IsSrcRowMajor);
3230
3231 return Builder.CreateShuffleVector(V: Mat, Mask, Name: "trunc");
3232 }
3233 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: CGF.SizeTy);
3234 return Builder.CreateExtractElement(Vec: Mat, Idx: Zero, Name: "cast.mtrunc");
3235 }
3236 case CK_HLSLElementwiseCast: {
3237 RValue RV = CGF.EmitAnyExpr(E);
3238 SourceLocation Loc = CE->getExprLoc();
3239
3240 Address SrcAddr = Address::invalid();
3241
3242 if (RV.isAggregate()) {
3243 SrcAddr = RV.getAggregateAddress();
3244 } else {
3245 SrcAddr = CGF.CreateMemTemp(T: E->getType(), Name: "hlsl.ewcast.src");
3246 LValue TmpLV = CGF.MakeAddrLValue(Addr: SrcAddr, T: E->getType());
3247 CGF.EmitStoreThroughLValue(Src: RV, Dst: TmpLV);
3248 }
3249
3250 LValue SrcVal = CGF.MakeAddrLValue(Addr: SrcAddr, T: E->getType());
3251 return EmitHLSLElementwiseCast(CGF, SrcVal, DestTy, Loc);
3252 }
3253
3254 } // end of switch
3255
3256 llvm_unreachable("unknown scalar cast");
3257}
3258
3259Value *ScalarExprEmitter::VisitStmtExpr(const StmtExpr *E) {
3260 CodeGenFunction::StmtExprEvaluation eval(CGF);
3261 Address RetAlloca = CGF.EmitCompoundStmt(S: *E->getSubStmt(),
3262 GetLast: !E->getType()->isVoidType());
3263 if (!RetAlloca.isValid())
3264 return nullptr;
3265 return CGF.EmitLoadOfScalar(lvalue: CGF.MakeAddrLValue(Addr: RetAlloca, T: E->getType()),
3266 Loc: E->getExprLoc());
3267}
3268
3269Value *ScalarExprEmitter::VisitExprWithCleanups(ExprWithCleanups *E) {
3270 CodeGenFunction::RunCleanupsScope Scope(CGF);
3271 Value *V = Visit(E: E->getSubExpr());
3272 // Defend against dominance problems caused by jumps out of expression
3273 // evaluation through the shared cleanup block.
3274 Scope.ForceCleanup(ValuesToReload: {&V});
3275 return V;
3276}
3277
3278//===----------------------------------------------------------------------===//
3279// Unary Operators
3280//===----------------------------------------------------------------------===//
3281
3282static BinOpInfo createBinOpInfoFromIncDec(const UnaryOperator *E,
3283 llvm::Value *InVal, bool IsInc,
3284 FPOptions FPFeatures) {
3285 BinOpInfo BinOp;
3286 BinOp.LHS = InVal;
3287 BinOp.RHS = llvm::ConstantInt::get(Ty: InVal->getType(), V: 1, IsSigned: false);
3288 BinOp.Ty = E->getType();
3289 BinOp.Opcode = IsInc ? BO_Add : BO_Sub;
3290 BinOp.FPFeatures = FPFeatures;
3291 BinOp.E = E;
3292 return BinOp;
3293}
3294
3295llvm::Value *ScalarExprEmitter::EmitIncDecConsiderOverflowBehavior(
3296 const UnaryOperator *E, llvm::Value *InVal, bool IsInc) {
3297 // Treat positive amount as unsigned to support inc of i1 (needed for
3298 // unsigned _BitInt(1)).
3299 llvm::Value *Amount =
3300 llvm::ConstantInt::get(Ty: InVal->getType(), V: IsInc ? 1 : -1, IsSigned: !IsInc);
3301 StringRef Name = IsInc ? "inc" : "dec";
3302 QualType Ty = E->getType();
3303 const bool isSigned = Ty->isSignedIntegerOrEnumerationType();
3304 const bool hasSan =
3305 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
3306 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
3307
3308 switch (getOverflowBehaviorConsideringType(CGF, Ty)) {
3309 case LangOptions::OB_Wrap:
3310 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3311 case LangOptions::OB_SignedAndDefined:
3312 if (!hasSan)
3313 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3314 [[fallthrough]];
3315 case LangOptions::OB_Unset:
3316 if (!E->canOverflow())
3317 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3318 if (!hasSan)
3319 return isSigned ? Builder.CreateNSWAdd(LHS: InVal, RHS: Amount, Name)
3320 : Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3321 [[fallthrough]];
3322 case LangOptions::OB_Trap:
3323 if (!Ty->getAs<OverflowBehaviorType>() && !E->canOverflow())
3324 return Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3325 BinOpInfo Info = createBinOpInfoFromIncDec(
3326 E, InVal, IsInc, FPFeatures: E->getFPFeaturesInEffect(LO: CGF.getLangOpts()));
3327 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: Info))
3328 return isSigned ? Builder.CreateNSWAdd(LHS: InVal, RHS: Amount, Name)
3329 : Builder.CreateAdd(LHS: InVal, RHS: Amount, Name);
3330 return EmitOverflowCheckedBinOp(Ops: Info);
3331 }
3332 llvm_unreachable("Unknown OverflowBehaviorKind");
3333}
3334
3335namespace {
3336/// Handles check and update for lastprivate conditional variables.
3337class OMPLastprivateConditionalUpdateRAII {
3338private:
3339 CodeGenFunction &CGF;
3340 const UnaryOperator *E;
3341
3342public:
3343 OMPLastprivateConditionalUpdateRAII(CodeGenFunction &CGF,
3344 const UnaryOperator *E)
3345 : CGF(CGF), E(E) {}
3346 ~OMPLastprivateConditionalUpdateRAII() {
3347 if (CGF.getLangOpts().OpenMP)
3348 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(
3349 CGF, LHS: E->getSubExpr());
3350 }
3351};
3352} // namespace
3353
3354llvm::Value *
3355ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
3356 bool isInc, bool isPre) {
3357 ApplyAtomGroup Grp(CGF.getDebugInfo());
3358 OMPLastprivateConditionalUpdateRAII OMPRegion(CGF, E);
3359 QualType type = E->getSubExpr()->getType();
3360 llvm::PHINode *atomicPHI = nullptr;
3361 llvm::Value *value;
3362 llvm::Value *input;
3363 llvm::Value *Previous = nullptr;
3364 QualType SrcType = E->getType();
3365
3366 int amount = (isInc ? 1 : -1);
3367 bool isSubtraction = !isInc;
3368
3369 if (const AtomicType *atomicTy = type->getAs<AtomicType>()) {
3370 type = atomicTy->getValueType();
3371 if (isInc && type->isBooleanType()) {
3372 llvm::Value *True = CGF.EmitToMemory(Value: Builder.getTrue(), Ty: type);
3373 if (isPre) {
3374 Builder.CreateStore(Val: True, Addr: LV.getAddress(), IsVolatile: LV.isVolatileQualified())
3375 ->setAtomic(Ordering: llvm::AtomicOrdering::SequentiallyConsistent);
3376 return Builder.getTrue();
3377 }
3378 // For atomic bool increment, we just store true and return it for
3379 // preincrement, do an atomic swap with true for postincrement
3380 return Builder.CreateAtomicRMW(
3381 Op: llvm::AtomicRMWInst::Xchg, Addr: LV.getAddress(), Val: True,
3382 Ordering: llvm::AtomicOrdering::SequentiallyConsistent);
3383 }
3384 // Special case for atomic increment / decrement on integers, emit
3385 // atomicrmw instructions. We skip this if we want to be doing overflow
3386 // checking, and fall into the slow path with the atomic cmpxchg loop.
3387 if (!type->isBooleanType() && type->isIntegerType() &&
3388 !(type->isUnsignedIntegerType() &&
3389 CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) &&
3390 CGF.getLangOpts().getSignedOverflowBehavior() !=
3391 LangOptions::SOB_Trapping) {
3392 llvm::AtomicRMWInst::BinOp aop = isInc ? llvm::AtomicRMWInst::Add :
3393 llvm::AtomicRMWInst::Sub;
3394 llvm::Instruction::BinaryOps op = isInc ? llvm::Instruction::Add :
3395 llvm::Instruction::Sub;
3396 llvm::Value *amt = CGF.EmitToMemory(
3397 Value: llvm::ConstantInt::get(Ty: ConvertType(T: type), V: 1, IsSigned: true), Ty: type);
3398 llvm::Value *old =
3399 Builder.CreateAtomicRMW(Op: aop, Addr: LV.getAddress(), Val: amt,
3400 Ordering: llvm::AtomicOrdering::SequentiallyConsistent);
3401 return isPre ? Builder.CreateBinOp(Opc: op, LHS: old, RHS: amt) : old;
3402 }
3403 // Special case for atomic increment/decrement on floats.
3404 // Bail out non-power-of-2-sized floating point types (e.g., x86_fp80).
3405 if (type->isFloatingType()) {
3406 llvm::Type *Ty = ConvertType(T: type);
3407 if (llvm::has_single_bit(Value: Ty->getScalarSizeInBits())) {
3408 llvm::AtomicRMWInst::BinOp aop =
3409 isInc ? llvm::AtomicRMWInst::FAdd : llvm::AtomicRMWInst::FSub;
3410 llvm::Instruction::BinaryOps op =
3411 isInc ? llvm::Instruction::FAdd : llvm::Instruction::FSub;
3412 llvm::Value *amt = llvm::ConstantFP::get(Ty, V: 1.0);
3413 llvm::AtomicRMWInst *old =
3414 CGF.emitAtomicRMWInst(Op: aop, Addr: LV.getAddress(), Val: amt,
3415 Order: llvm::AtomicOrdering::SequentiallyConsistent);
3416
3417 return isPre ? Builder.CreateBinOp(Opc: op, LHS: old, RHS: amt) : old;
3418 }
3419 }
3420 value = EmitLoadOfLValue(LV, Loc: E->getExprLoc());
3421 input = value;
3422 // For every other atomic operation, we need to emit a load-op-cmpxchg loop
3423 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
3424 llvm::BasicBlock *opBB = CGF.createBasicBlock(name: "atomic_op", parent: CGF.CurFn);
3425 value = CGF.EmitToMemory(Value: value, Ty: type);
3426 Builder.CreateBr(Dest: opBB);
3427 Builder.SetInsertPoint(opBB);
3428 atomicPHI = Builder.CreatePHI(Ty: value->getType(), NumReservedValues: 2);
3429 atomicPHI->addIncoming(V: value, BB: startBB);
3430 value = atomicPHI;
3431 } else {
3432 value = EmitLoadOfLValue(LV, Loc: E->getExprLoc());
3433 input = value;
3434 }
3435
3436 // Special case of integer increment that we have to check first: bool++.
3437 // Due to promotion rules, we get:
3438 // bool++ -> bool = bool + 1
3439 // -> bool = (int)bool + 1
3440 // -> bool = ((int)bool + 1 != 0)
3441 // An interesting aspect of this is that increment is always true.
3442 // Decrement does not have this property.
3443 if (isInc && type->isBooleanType()) {
3444 value = Builder.getTrue();
3445
3446 // Most common case by far: integer increment.
3447 } else if (type->isIntegerType()) {
3448 QualType promotedType;
3449 bool canPerformLossyDemotionCheck = false;
3450
3451 if (CGF.getContext().isPromotableIntegerType(T: type)) {
3452 promotedType = CGF.getContext().getPromotedIntegerType(PromotableType: type);
3453 assert(promotedType != type && "Shouldn't promote to the same type.");
3454 canPerformLossyDemotionCheck = true;
3455 canPerformLossyDemotionCheck &=
3456 CGF.getContext().getCanonicalType(T: type) !=
3457 CGF.getContext().getCanonicalType(T: promotedType);
3458 canPerformLossyDemotionCheck &=
3459 PromotionIsPotentiallyEligibleForImplicitIntegerConversionCheck(
3460 SrcType: type, DstType: promotedType);
3461 assert((!canPerformLossyDemotionCheck ||
3462 type->isSignedIntegerOrEnumerationType() ||
3463 promotedType->isSignedIntegerOrEnumerationType() ||
3464 ConvertType(type)->getScalarSizeInBits() ==
3465 ConvertType(promotedType)->getScalarSizeInBits()) &&
3466 "The following check expects that if we do promotion to different "
3467 "underlying canonical type, at least one of the types (either "
3468 "base or promoted) will be signed, or the bitwidths will match.");
3469 }
3470 if (CGF.SanOpts.hasOneOf(
3471 K: SanitizerKind::ImplicitIntegerArithmeticValueChange |
3472 SanitizerKind::ImplicitBitfieldConversion) &&
3473 canPerformLossyDemotionCheck) {
3474 // While `x += 1` (for `x` with width less than int) is modeled as
3475 // promotion+arithmetics+demotion, and we can catch lossy demotion with
3476 // ease; inc/dec with width less than int can't overflow because of
3477 // promotion rules, so we omit promotion+demotion, which means that we can
3478 // not catch lossy "demotion". Because we still want to catch these cases
3479 // when the sanitizer is enabled, we perform the promotion, then perform
3480 // the increment/decrement in the wider type, and finally
3481 // perform the demotion. This will catch lossy demotions.
3482
3483 // We have a special case for bitfields defined using all the bits of the
3484 // type. In this case we need to do the same trick as for the integer
3485 // sanitizer checks, i.e., promotion -> increment/decrement -> demotion.
3486
3487 value = EmitScalarConversion(Src: value, SrcType: type, DstType: promotedType, Loc: E->getExprLoc());
3488 Value *amt = llvm::ConstantInt::get(Ty: value->getType(), V: amount, IsSigned: true);
3489 value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec");
3490 // Do pass non-default ScalarConversionOpts so that sanitizer check is
3491 // emitted if LV is not a bitfield, otherwise the bitfield sanitizer
3492 // checks will take care of the conversion.
3493 ScalarConversionOpts Opts;
3494 if (!LV.isBitField())
3495 Opts = ScalarConversionOpts(CGF.SanOpts);
3496 else if (CGF.SanOpts.has(K: SanitizerKind::ImplicitBitfieldConversion)) {
3497 Previous = value;
3498 SrcType = promotedType;
3499 }
3500
3501 Opts.PatternExcluded = CGF.getContext().isUnaryOverflowPatternExcluded(UO: E);
3502 value = EmitScalarConversion(Src: value, SrcType: promotedType, DstType: type, Loc: E->getExprLoc(),
3503 Opts);
3504
3505 // Note that signed integer inc/dec with width less than int can't
3506 // overflow because of promotion rules; we're just eliding a few steps
3507 // here.
3508 } else if (type->isSignedIntegerOrEnumerationType() ||
3509 type->isUnsignedIntegerType()) {
3510 value = EmitIncDecConsiderOverflowBehavior(E, InVal: value, IsInc: isInc);
3511 } else {
3512 // Treat positive amount as unsigned to support inc of i1 (needed for
3513 // unsigned _BitInt(1)).
3514 llvm::Value *amt =
3515 llvm::ConstantInt::get(Ty: value->getType(), V: amount, IsSigned: !isInc);
3516 value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec");
3517 }
3518
3519 // Next most common: pointer increment.
3520 } else if (const PointerType *ptr = type->getAs<PointerType>()) {
3521 QualType type = ptr->getPointeeType();
3522
3523 // VLA types don't have constant size.
3524 if (const VariableArrayType *vla
3525 = CGF.getContext().getAsVariableArrayType(T: type)) {
3526 llvm::Value *numElts = CGF.getVLASize(vla).NumElts;
3527 if (!isInc) numElts = Builder.CreateNSWNeg(V: numElts, Name: "vla.negsize");
3528 llvm::Type *elemTy = CGF.ConvertTypeForMem(T: vla->getElementType());
3529 if (CGF.getLangOpts().PointerOverflowDefined)
3530 value = Builder.CreateGEP(Ty: elemTy, Ptr: value, IdxList: numElts, Name: "vla.inc");
3531 else
3532 value = CGF.EmitCheckedInBoundsGEP(
3533 ElemTy: elemTy, Ptr: value, IdxList: numElts, /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3534 Loc: E->getExprLoc(), Name: "vla.inc");
3535
3536 // Arithmetic on function pointers (!) is just +-1.
3537 } else if (type->isFunctionType()) {
3538 llvm::Value *amt = Builder.getInt32(C: amount);
3539
3540 if (CGF.getLangOpts().PointerOverflowDefined)
3541 value = Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: value, IdxList: amt, Name: "incdec.funcptr");
3542 else
3543 value =
3544 CGF.EmitCheckedInBoundsGEP(ElemTy: CGF.Int8Ty, Ptr: value, IdxList: amt,
3545 /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3546 Loc: E->getExprLoc(), Name: "incdec.funcptr");
3547
3548 // For everything else, we can just do a simple increment.
3549 } else {
3550 llvm::Value *amt = Builder.getInt32(C: amount);
3551 llvm::Type *elemTy = CGF.ConvertTypeForMem(T: type);
3552 if (CGF.getLangOpts().PointerOverflowDefined)
3553 value = Builder.CreateGEP(Ty: elemTy, Ptr: value, IdxList: amt, Name: "incdec.ptr");
3554 else
3555 value = CGF.EmitCheckedInBoundsGEP(
3556 ElemTy: elemTy, Ptr: value, IdxList: amt, /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3557 Loc: E->getExprLoc(), Name: "incdec.ptr");
3558 }
3559
3560 // Vector increment/decrement.
3561 } else if (type->isVectorType()) {
3562 if (type->hasIntegerRepresentation()) {
3563 llvm::Value *amt = llvm::ConstantInt::getSigned(Ty: value->getType(), V: amount);
3564
3565 value = Builder.CreateAdd(LHS: value, RHS: amt, Name: isInc ? "inc" : "dec");
3566 } else {
3567 value = Builder.CreateFAdd(
3568 L: value,
3569 R: llvm::ConstantFP::get(Ty: value->getType(), V: amount),
3570 Name: isInc ? "inc" : "dec");
3571 }
3572
3573 // Floating point.
3574 } else if (type->isRealFloatingType()) {
3575 // Add the inc/dec to the real part.
3576 llvm::Value *amt;
3577 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, E);
3578
3579 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
3580 // Another special case: half FP increment should be done via float. If
3581 // the input isn't already half, it may be i16.
3582 Value *bitcast = Builder.CreateBitCast(V: input, DestTy: CGF.CGM.HalfTy);
3583 value = Builder.CreateFPExt(V: bitcast, DestTy: CGF.CGM.FloatTy, Name: "incdec.conv");
3584 }
3585
3586 if (value->getType()->isFloatTy())
3587 amt = llvm::ConstantFP::get(Context&: VMContext,
3588 V: llvm::APFloat(static_cast<float>(amount)));
3589 else if (value->getType()->isDoubleTy())
3590 amt = llvm::ConstantFP::get(Context&: VMContext,
3591 V: llvm::APFloat(static_cast<double>(amount)));
3592 else {
3593 // Remaining types are Half, Bfloat16, LongDouble, __ibm128 or __float128.
3594 // Convert from float.
3595 llvm::APFloat F(static_cast<float>(amount));
3596 bool ignored;
3597 const llvm::fltSemantics *FS;
3598 // Don't use getFloatTypeSemantics because Half isn't
3599 // necessarily represented using the "half" LLVM type.
3600 if (value->getType()->isFP128Ty())
3601 FS = &CGF.getTarget().getFloat128Format();
3602 else if (value->getType()->isHalfTy())
3603 FS = &CGF.getTarget().getHalfFormat();
3604 else if (value->getType()->isBFloatTy())
3605 FS = &CGF.getTarget().getBFloat16Format();
3606 else if (value->getType()->isPPC_FP128Ty())
3607 FS = &CGF.getTarget().getIbm128Format();
3608 else
3609 FS = &CGF.getTarget().getLongDoubleFormat();
3610 F.convert(ToSemantics: *FS, RM: llvm::APFloat::rmTowardZero, losesInfo: &ignored);
3611 amt = llvm::ConstantFP::get(Context&: VMContext, V: F);
3612 }
3613 value = Builder.CreateFAdd(L: value, R: amt, Name: isInc ? "inc" : "dec");
3614
3615 if (type->isHalfType() && !CGF.getContext().getLangOpts().NativeHalfType) {
3616 value = Builder.CreateFPTrunc(V: value, DestTy: CGF.CGM.HalfTy, Name: "incdec.conv");
3617 value = Builder.CreateBitCast(V: value, DestTy: input->getType());
3618 }
3619
3620 // Fixed-point types.
3621 } else if (type->isFixedPointType()) {
3622 // Fixed-point types are tricky. In some cases, it isn't possible to
3623 // represent a 1 or a -1 in the type at all. Piggyback off of
3624 // EmitFixedPointBinOp to avoid having to reimplement saturation.
3625 BinOpInfo Info;
3626 Info.E = E;
3627 Info.Ty = E->getType();
3628 Info.Opcode = isInc ? BO_Add : BO_Sub;
3629 Info.LHS = value;
3630 Info.RHS = llvm::ConstantInt::get(Ty: value->getType(), V: 1, IsSigned: false);
3631 // If the type is signed, it's better to represent this as +(-1) or -(-1),
3632 // since -1 is guaranteed to be representable.
3633 if (type->isSignedFixedPointType()) {
3634 Info.Opcode = isInc ? BO_Sub : BO_Add;
3635 Info.RHS = Builder.CreateNeg(V: Info.RHS);
3636 }
3637 // Now, convert from our invented integer literal to the type of the unary
3638 // op. This will upscale and saturate if necessary. This value can become
3639 // undef in some cases.
3640 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
3641 auto DstSema = CGF.getContext().getFixedPointSemantics(Ty: Info.Ty);
3642 Info.RHS = FPBuilder.CreateIntegerToFixed(Src: Info.RHS, SrcIsSigned: true, DstSema);
3643 value = EmitFixedPointBinOp(Ops: Info);
3644
3645 // Objective-C pointer types.
3646 } else {
3647 const ObjCObjectPointerType *OPT = type->castAs<ObjCObjectPointerType>();
3648
3649 CharUnits size = CGF.getContext().getTypeSizeInChars(T: OPT->getObjectType());
3650 if (!isInc) size = -size;
3651 llvm::Value *sizeValue =
3652 llvm::ConstantInt::getSigned(Ty: CGF.SizeTy, V: size.getQuantity());
3653
3654 if (CGF.getLangOpts().PointerOverflowDefined)
3655 value = Builder.CreateGEP(Ty: CGF.Int8Ty, Ptr: value, IdxList: sizeValue, Name: "incdec.objptr");
3656 else
3657 value = CGF.EmitCheckedInBoundsGEP(
3658 ElemTy: CGF.Int8Ty, Ptr: value, IdxList: sizeValue, /*SignedIndices=*/false, IsSubtraction: isSubtraction,
3659 Loc: E->getExprLoc(), Name: "incdec.objptr");
3660 value = Builder.CreateBitCast(V: value, DestTy: input->getType());
3661 }
3662
3663 if (atomicPHI) {
3664 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
3665 llvm::BasicBlock *contBB = CGF.createBasicBlock(name: "atomic_cont", parent: CGF.CurFn);
3666 auto Pair = CGF.EmitAtomicCompareExchange(
3667 Obj: LV, Expected: RValue::get(V: atomicPHI), Desired: RValue::get(V: value), Loc: E->getExprLoc());
3668 llvm::Value *old = CGF.EmitToMemory(Value: Pair.first.getScalarVal(), Ty: type);
3669 llvm::Value *success = Pair.second;
3670 atomicPHI->addIncoming(V: old, BB: curBlock);
3671 Builder.CreateCondBr(Cond: success, True: contBB, False: atomicPHI->getParent());
3672 Builder.SetInsertPoint(contBB);
3673 return isPre ? value : input;
3674 }
3675
3676 // Store the updated result through the lvalue.
3677 if (LV.isBitField()) {
3678 Value *Src = Previous ? Previous : value;
3679 CGF.EmitStoreThroughBitfieldLValue(Src: RValue::get(V: value), Dst: LV, Result: &value);
3680 CGF.EmitBitfieldConversionCheck(Src, SrcType, Dst: value, DstType: E->getType(),
3681 Info: LV.getBitFieldInfo(), Loc: E->getExprLoc());
3682 } else
3683 CGF.EmitStoreThroughLValue(Src: RValue::get(V: value), Dst: LV);
3684
3685 // If this is a postinc, return the value read from memory, otherwise use the
3686 // updated value.
3687 return isPre ? value : input;
3688}
3689
3690
3691Value *ScalarExprEmitter::VisitUnaryPlus(const UnaryOperator *E,
3692 QualType PromotionType) {
3693 QualType promotionTy = PromotionType.isNull()
3694 ? getPromotionType(Ty: E->getSubExpr()->getType())
3695 : PromotionType;
3696 Value *result = VisitPlus(E, PromotionType: promotionTy);
3697 if (result && !promotionTy.isNull())
3698 result = EmitUnPromotedValue(result, ExprType: E->getType());
3699 return result;
3700}
3701
3702Value *ScalarExprEmitter::VisitPlus(const UnaryOperator *E,
3703 QualType PromotionType) {
3704 // This differs from gcc, though, most likely due to a bug in gcc.
3705 TestAndClearIgnoreResultAssign();
3706 if (!PromotionType.isNull())
3707 return CGF.EmitPromotedScalarExpr(E: E->getSubExpr(), PromotionType);
3708 return Visit(E: E->getSubExpr());
3709}
3710
3711Value *ScalarExprEmitter::VisitUnaryMinus(const UnaryOperator *E,
3712 QualType PromotionType) {
3713 QualType promotionTy = PromotionType.isNull()
3714 ? getPromotionType(Ty: E->getSubExpr()->getType())
3715 : PromotionType;
3716 Value *result = VisitMinus(E, PromotionType: promotionTy);
3717 if (result && !promotionTy.isNull())
3718 result = EmitUnPromotedValue(result, ExprType: E->getType());
3719 return result;
3720}
3721
3722Value *ScalarExprEmitter::VisitMinus(const UnaryOperator *E,
3723 QualType PromotionType) {
3724 TestAndClearIgnoreResultAssign();
3725 Value *Op;
3726 if (!PromotionType.isNull())
3727 Op = CGF.EmitPromotedScalarExpr(E: E->getSubExpr(), PromotionType);
3728 else
3729 Op = Visit(E: E->getSubExpr());
3730
3731 // Generate a unary FNeg for FP ops.
3732 if (Op->getType()->isFPOrFPVectorTy())
3733 return Builder.CreateFNeg(V: Op, Name: "fneg");
3734
3735 // Emit unary minus with EmitSub so we handle overflow cases etc.
3736 BinOpInfo BinOp;
3737 BinOp.RHS = Op;
3738 BinOp.LHS = llvm::Constant::getNullValue(Ty: BinOp.RHS->getType());
3739 BinOp.Ty = E->getType();
3740 BinOp.Opcode = BO_Sub;
3741 BinOp.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts());
3742 BinOp.E = E;
3743 return EmitSub(Ops: BinOp);
3744}
3745
3746Value *ScalarExprEmitter::VisitUnaryNot(const UnaryOperator *E) {
3747 TestAndClearIgnoreResultAssign();
3748 Value *Op = Visit(E: E->getSubExpr());
3749 return Builder.CreateNot(V: Op, Name: "not");
3750}
3751
3752Value *ScalarExprEmitter::VisitUnaryLNot(const UnaryOperator *E) {
3753 // Perform vector logical not on comparison with zero vector.
3754 if (E->getType()->isVectorType() &&
3755 E->getType()->castAs<VectorType>()->getVectorKind() ==
3756 VectorKind::Generic) {
3757 Value *Oper = Visit(E: E->getSubExpr());
3758 Value *Zero = llvm::Constant::getNullValue(Ty: Oper->getType());
3759 Value *Result;
3760 if (Oper->getType()->isFPOrFPVectorTy()) {
3761 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
3762 CGF, E->getFPFeaturesInEffect(LO: CGF.getLangOpts()));
3763 Result = Builder.CreateFCmp(P: llvm::CmpInst::FCMP_OEQ, LHS: Oper, RHS: Zero, Name: "cmp");
3764 } else
3765 Result = Builder.CreateICmp(P: llvm::CmpInst::ICMP_EQ, LHS: Oper, RHS: Zero, Name: "cmp");
3766 return Builder.CreateSExt(V: Result, DestTy: ConvertType(T: E->getType()), Name: "sext");
3767 }
3768
3769 // Compare operand to zero.
3770 Value *BoolVal = CGF.EvaluateExprAsBool(E: E->getSubExpr());
3771
3772 // Invert value.
3773 // TODO: Could dynamically modify easy computations here. For example, if
3774 // the operand is an icmp ne, turn into icmp eq.
3775 BoolVal = Builder.CreateNot(V: BoolVal, Name: "lnot");
3776
3777 // ZExt result to the expr type.
3778 return Builder.CreateZExt(V: BoolVal, DestTy: ConvertType(T: E->getType()), Name: "lnot.ext");
3779}
3780
3781Value *ScalarExprEmitter::VisitOffsetOfExpr(OffsetOfExpr *E) {
3782 // Try folding the offsetof to a constant.
3783 Expr::EvalResult EVResult;
3784 if (E->EvaluateAsInt(Result&: EVResult, Ctx: CGF.getContext())) {
3785 llvm::APSInt Value = EVResult.Val.getInt();
3786 return Builder.getInt(AI: Value);
3787 }
3788
3789 // Loop over the components of the offsetof to compute the value.
3790 unsigned n = E->getNumComponents();
3791 llvm::Type* ResultType = ConvertType(T: E->getType());
3792 llvm::Value* Result = llvm::Constant::getNullValue(Ty: ResultType);
3793 QualType CurrentType = E->getTypeSourceInfo()->getType();
3794 for (unsigned i = 0; i != n; ++i) {
3795 OffsetOfNode ON = E->getComponent(Idx: i);
3796 llvm::Value *Offset = nullptr;
3797 switch (ON.getKind()) {
3798 case OffsetOfNode::Array: {
3799 // Compute the index
3800 Expr *IdxExpr = E->getIndexExpr(Idx: ON.getArrayExprIndex());
3801 llvm::Value* Idx = CGF.EmitScalarExpr(E: IdxExpr);
3802 bool IdxSigned = IdxExpr->getType()->isSignedIntegerOrEnumerationType();
3803 Idx = Builder.CreateIntCast(V: Idx, DestTy: ResultType, isSigned: IdxSigned, Name: "conv");
3804
3805 // Save the element type
3806 CurrentType =
3807 CGF.getContext().getAsArrayType(T: CurrentType)->getElementType();
3808
3809 // Compute the element size
3810 llvm::Value* ElemSize = llvm::ConstantInt::get(Ty: ResultType,
3811 V: CGF.getContext().getTypeSizeInChars(T: CurrentType).getQuantity());
3812
3813 // Multiply out to compute the result
3814 Offset = Builder.CreateMul(LHS: Idx, RHS: ElemSize);
3815 break;
3816 }
3817
3818 case OffsetOfNode::Field: {
3819 FieldDecl *MemberDecl = ON.getField();
3820 auto *RD = CurrentType->castAsRecordDecl();
3821 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(D: RD);
3822
3823 // Get the index of the field in its parent.
3824 unsigned FieldIndex = MemberDecl->getFieldIndex();
3825
3826 // Compute the offset to the field
3827 int64_t OffsetInt =
3828 RL.getFieldOffset(FieldNo: FieldIndex) / CGF.getContext().getCharWidth();
3829 Offset = llvm::ConstantInt::get(Ty: ResultType, V: OffsetInt);
3830
3831 // Save the element type.
3832 CurrentType = MemberDecl->getType();
3833 break;
3834 }
3835
3836 case OffsetOfNode::Identifier:
3837 llvm_unreachable("dependent __builtin_offsetof");
3838
3839 case OffsetOfNode::Base: {
3840 if (ON.getBase()->isVirtual()) {
3841 CGF.ErrorUnsupported(S: E, Type: "virtual base in offsetof");
3842 continue;
3843 }
3844
3845 const ASTRecordLayout &RL = CGF.getContext().getASTRecordLayout(
3846 D: CurrentType->castAsCanonical<RecordType>()->getDecl());
3847
3848 // Save the element type.
3849 CurrentType = ON.getBase()->getType();
3850
3851 // Compute the offset to the base.
3852 auto *BaseRD = CurrentType->castAsCXXRecordDecl();
3853 CharUnits OffsetInt = RL.getBaseClassOffset(Base: BaseRD);
3854 Offset = llvm::ConstantInt::get(Ty: ResultType, V: OffsetInt.getQuantity());
3855 break;
3856 }
3857 }
3858 Result = Builder.CreateAdd(LHS: Result, RHS: Offset);
3859 }
3860 return Result;
3861}
3862
3863/// VisitUnaryExprOrTypeTraitExpr - Return the size or alignment of the type of
3864/// argument of the sizeof expression as an integer.
3865Value *
3866ScalarExprEmitter::VisitUnaryExprOrTypeTraitExpr(
3867 const UnaryExprOrTypeTraitExpr *E) {
3868 QualType TypeToSize = E->getTypeOfArgument();
3869 if (auto Kind = E->getKind();
3870 Kind == UETT_SizeOf || Kind == UETT_DataSizeOf || Kind == UETT_CountOf) {
3871 if (const VariableArrayType *VAT =
3872 CGF.getContext().getAsVariableArrayType(T: TypeToSize)) {
3873 // For _Countof, we only want to evaluate if the extent is actually
3874 // variable as opposed to a multi-dimensional array whose extent is
3875 // constant but whose element type is variable.
3876 bool EvaluateExtent = true;
3877 if (Kind == UETT_CountOf && VAT->getElementType()->isArrayType()) {
3878 EvaluateExtent =
3879 !VAT->getSizeExpr()->isIntegerConstantExpr(Ctx: CGF.getContext());
3880 }
3881 if (EvaluateExtent) {
3882 if (E->isArgumentType()) {
3883 // sizeof(type) - make sure to emit the VLA size.
3884 CGF.EmitVariablyModifiedType(Ty: TypeToSize);
3885 } else {
3886 // C99 6.5.3.4p2: If the argument is an expression of type
3887 // VLA, it is evaluated.
3888 CGF.EmitIgnoredExpr(E: E->getArgumentExpr());
3889 }
3890
3891 // For _Countof, we just want to return the size of a single dimension.
3892 if (Kind == UETT_CountOf)
3893 return CGF.getVLAElements1D(vla: VAT).NumElts;
3894
3895 // For sizeof and __datasizeof, we need to scale the number of elements
3896 // by the size of the array element type.
3897 auto VlaSize = CGF.getVLASize(vla: VAT);
3898
3899 // Scale the number of non-VLA elements by the non-VLA element size.
3900 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(T: VlaSize.Type);
3901 if (!eltSize.isOne())
3902 return CGF.Builder.CreateNUWMul(LHS: CGF.CGM.getSize(numChars: eltSize),
3903 RHS: VlaSize.NumElts);
3904 return VlaSize.NumElts;
3905 }
3906 }
3907 } else if (E->getKind() == UETT_OpenMPRequiredSimdAlign) {
3908 auto Alignment =
3909 CGF.getContext()
3910 .toCharUnitsFromBits(BitSize: CGF.getContext().getOpenMPDefaultSimdAlign(
3911 T: E->getTypeOfArgument()->getPointeeType()))
3912 .getQuantity();
3913 return llvm::ConstantInt::get(Ty: CGF.SizeTy, V: Alignment);
3914 } else if (E->getKind() == UETT_VectorElements) {
3915 auto *VecTy = cast<llvm::VectorType>(Val: ConvertType(T: E->getTypeOfArgument()));
3916 return Builder.CreateElementCount(Ty: CGF.SizeTy, EC: VecTy->getElementCount());
3917 }
3918
3919 // If this isn't sizeof(vla), the result must be constant; use the constant
3920 // folding logic so we don't have to duplicate it here.
3921 return Builder.getInt(AI: E->EvaluateKnownConstInt(Ctx: CGF.getContext()));
3922}
3923
3924Value *ScalarExprEmitter::VisitUnaryReal(const UnaryOperator *E,
3925 QualType PromotionType) {
3926 QualType promotionTy = PromotionType.isNull()
3927 ? getPromotionType(Ty: E->getSubExpr()->getType())
3928 : PromotionType;
3929 Value *result = VisitReal(E, PromotionType: promotionTy);
3930 if (result && !promotionTy.isNull())
3931 result = EmitUnPromotedValue(result, ExprType: E->getType());
3932 return result;
3933}
3934
3935Value *ScalarExprEmitter::VisitReal(const UnaryOperator *E,
3936 QualType PromotionType) {
3937 Expr *Op = E->getSubExpr();
3938 if (Op->getType()->isAnyComplexType()) {
3939 // If it's an l-value, load through the appropriate subobject l-value.
3940 // Note that we have to ask E because Op might be an l-value that
3941 // this won't work for, e.g. an Obj-C property.
3942 if (E->isGLValue()) {
3943 if (!PromotionType.isNull()) {
3944 CodeGenFunction::ComplexPairTy result = CGF.EmitComplexExpr(
3945 E: Op, /*IgnoreReal*/ IgnoreResultAssign, /*IgnoreImag*/ true);
3946 PromotionType = PromotionType->isAnyComplexType()
3947 ? PromotionType
3948 : CGF.getContext().getComplexType(T: PromotionType);
3949 return result.first ? CGF.EmitPromotedValue(result, PromotionType).first
3950 : result.first;
3951 }
3952
3953 return CGF.EmitLoadOfLValue(V: CGF.EmitLValue(E), Loc: E->getExprLoc())
3954 .getScalarVal();
3955 }
3956 // Otherwise, calculate and project.
3957 return CGF.EmitComplexExpr(E: Op, IgnoreReal: false, IgnoreImag: true).first;
3958 }
3959
3960 if (!PromotionType.isNull())
3961 return CGF.EmitPromotedScalarExpr(E: Op, PromotionType);
3962 return Visit(E: Op);
3963}
3964
3965Value *ScalarExprEmitter::VisitUnaryImag(const UnaryOperator *E,
3966 QualType PromotionType) {
3967 QualType promotionTy = PromotionType.isNull()
3968 ? getPromotionType(Ty: E->getSubExpr()->getType())
3969 : PromotionType;
3970 Value *result = VisitImag(E, PromotionType: promotionTy);
3971 if (result && !promotionTy.isNull())
3972 result = EmitUnPromotedValue(result, ExprType: E->getType());
3973 return result;
3974}
3975
3976Value *ScalarExprEmitter::VisitImag(const UnaryOperator *E,
3977 QualType PromotionType) {
3978 Expr *Op = E->getSubExpr();
3979 if (Op->getType()->isAnyComplexType()) {
3980 // If it's an l-value, load through the appropriate subobject l-value.
3981 // Note that we have to ask E because Op might be an l-value that
3982 // this won't work for, e.g. an Obj-C property.
3983 if (Op->isGLValue()) {
3984 if (!PromotionType.isNull()) {
3985 CodeGenFunction::ComplexPairTy result = CGF.EmitComplexExpr(
3986 E: Op, /*IgnoreReal*/ true, /*IgnoreImag*/ IgnoreResultAssign);
3987 PromotionType = PromotionType->isAnyComplexType()
3988 ? PromotionType
3989 : CGF.getContext().getComplexType(T: PromotionType);
3990 return result.second
3991 ? CGF.EmitPromotedValue(result, PromotionType).second
3992 : result.second;
3993 }
3994
3995 return CGF.EmitLoadOfLValue(V: CGF.EmitLValue(E), Loc: E->getExprLoc())
3996 .getScalarVal();
3997 }
3998 // Otherwise, calculate and project.
3999 return CGF.EmitComplexExpr(E: Op, IgnoreReal: true, IgnoreImag: false).second;
4000 }
4001
4002 // __imag on a scalar returns zero. Emit the subexpr to ensure side
4003 // effects are evaluated, but not the actual value.
4004 if (Op->isGLValue())
4005 CGF.EmitLValue(E: Op);
4006 else if (!PromotionType.isNull())
4007 CGF.EmitPromotedScalarExpr(E: Op, PromotionType);
4008 else
4009 CGF.EmitScalarExpr(E: Op, IgnoreResultAssign: true);
4010 if (!PromotionType.isNull())
4011 return llvm::Constant::getNullValue(Ty: ConvertType(T: PromotionType));
4012 return llvm::Constant::getNullValue(Ty: ConvertType(T: E->getType()));
4013}
4014
4015//===----------------------------------------------------------------------===//
4016// Binary Operators
4017//===----------------------------------------------------------------------===//
4018
4019Value *ScalarExprEmitter::EmitPromotedValue(Value *result,
4020 QualType PromotionType) {
4021 return CGF.Builder.CreateFPExt(V: result, DestTy: ConvertType(T: PromotionType), Name: "ext");
4022}
4023
4024Value *ScalarExprEmitter::EmitUnPromotedValue(Value *result,
4025 QualType ExprType) {
4026 return CGF.Builder.CreateFPTrunc(V: result, DestTy: ConvertType(T: ExprType), Name: "unpromotion");
4027}
4028
4029Value *ScalarExprEmitter::EmitPromoted(const Expr *E, QualType PromotionType) {
4030 E = E->IgnoreParens();
4031 if (auto BO = dyn_cast<BinaryOperator>(Val: E)) {
4032 switch (BO->getOpcode()) {
4033#define HANDLE_BINOP(OP) \
4034 case BO_##OP: \
4035 return Emit##OP(EmitBinOps(BO, PromotionType));
4036 HANDLE_BINOP(Add)
4037 HANDLE_BINOP(Sub)
4038 HANDLE_BINOP(Mul)
4039 HANDLE_BINOP(Div)
4040#undef HANDLE_BINOP
4041 default:
4042 break;
4043 }
4044 } else if (auto UO = dyn_cast<UnaryOperator>(Val: E)) {
4045 switch (UO->getOpcode()) {
4046 case UO_Imag:
4047 return VisitImag(E: UO, PromotionType);
4048 case UO_Real:
4049 return VisitReal(E: UO, PromotionType);
4050 case UO_Minus:
4051 return VisitMinus(E: UO, PromotionType);
4052 case UO_Plus:
4053 return VisitPlus(E: UO, PromotionType);
4054 default:
4055 break;
4056 }
4057 }
4058 auto result = Visit(E: const_cast<Expr *>(E));
4059 if (result) {
4060 if (!PromotionType.isNull())
4061 return EmitPromotedValue(result, PromotionType);
4062 else
4063 return EmitUnPromotedValue(result, ExprType: E->getType());
4064 }
4065 return result;
4066}
4067
4068BinOpInfo ScalarExprEmitter::EmitBinOps(const BinaryOperator *E,
4069 QualType PromotionType) {
4070 TestAndClearIgnoreResultAssign();
4071 BinOpInfo Result;
4072 Result.LHS = CGF.EmitPromotedScalarExpr(E: E->getLHS(), PromotionType);
4073 Result.RHS = CGF.EmitPromotedScalarExpr(E: E->getRHS(), PromotionType);
4074 if (!PromotionType.isNull())
4075 Result.Ty = PromotionType;
4076 else
4077 Result.Ty = E->getType();
4078 Result.Opcode = E->getOpcode();
4079 Result.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts());
4080 Result.E = E;
4081 return Result;
4082}
4083
4084LValue ScalarExprEmitter::EmitCompoundAssignLValue(
4085 const CompoundAssignOperator *E,
4086 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &),
4087 Value *&Result) {
4088 QualType LHSTy = E->getLHS()->getType();
4089 BinOpInfo OpInfo;
4090
4091 if (E->getComputationResultType()->isAnyComplexType())
4092 return CGF.EmitScalarCompoundAssignWithComplex(E, Result);
4093
4094 // Emit the RHS first. __block variables need to have the rhs evaluated
4095 // first, plus this should improve codegen a little.
4096
4097 QualType PromotionTypeCR;
4098 PromotionTypeCR = getPromotionType(Ty: E->getComputationResultType());
4099 if (PromotionTypeCR.isNull())
4100 PromotionTypeCR = E->getComputationResultType();
4101 QualType PromotionTypeLHS = getPromotionType(Ty: E->getComputationLHSType());
4102 QualType PromotionTypeRHS = getPromotionType(Ty: E->getRHS()->getType());
4103 if (!PromotionTypeRHS.isNull())
4104 OpInfo.RHS = CGF.EmitPromotedScalarExpr(E: E->getRHS(), PromotionType: PromotionTypeRHS);
4105 else
4106 OpInfo.RHS = Visit(E: E->getRHS());
4107 OpInfo.Ty = PromotionTypeCR;
4108 OpInfo.Opcode = E->getOpcode();
4109 OpInfo.FPFeatures = E->getFPFeaturesInEffect(LO: CGF.getLangOpts());
4110 OpInfo.E = E;
4111 // Load/convert the LHS.
4112 LValue LHSLV = EmitCheckedLValue(E: E->getLHS(), TCK: CodeGenFunction::TCK_Store);
4113
4114 llvm::PHINode *atomicPHI = nullptr;
4115 if (const AtomicType *atomicTy = LHSTy->getAs<AtomicType>()) {
4116 QualType type = atomicTy->getValueType();
4117 if (!type->isBooleanType() && type->isIntegerType() &&
4118 !(type->isUnsignedIntegerType() &&
4119 CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) &&
4120 CGF.getLangOpts().getSignedOverflowBehavior() !=
4121 LangOptions::SOB_Trapping) {
4122 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
4123 llvm::Instruction::BinaryOps Op;
4124 switch (OpInfo.Opcode) {
4125 // We don't have atomicrmw operands for *, %, /, <<, >>
4126 case BO_MulAssign: case BO_DivAssign:
4127 case BO_RemAssign:
4128 case BO_ShlAssign:
4129 case BO_ShrAssign:
4130 break;
4131 case BO_AddAssign:
4132 AtomicOp = llvm::AtomicRMWInst::Add;
4133 Op = llvm::Instruction::Add;
4134 break;
4135 case BO_SubAssign:
4136 AtomicOp = llvm::AtomicRMWInst::Sub;
4137 Op = llvm::Instruction::Sub;
4138 break;
4139 case BO_AndAssign:
4140 AtomicOp = llvm::AtomicRMWInst::And;
4141 Op = llvm::Instruction::And;
4142 break;
4143 case BO_XorAssign:
4144 AtomicOp = llvm::AtomicRMWInst::Xor;
4145 Op = llvm::Instruction::Xor;
4146 break;
4147 case BO_OrAssign:
4148 AtomicOp = llvm::AtomicRMWInst::Or;
4149 Op = llvm::Instruction::Or;
4150 break;
4151 default:
4152 llvm_unreachable("Invalid compound assignment type");
4153 }
4154 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
4155 llvm::Value *Amt = CGF.EmitToMemory(
4156 Value: EmitScalarConversion(Src: OpInfo.RHS, SrcType: E->getRHS()->getType(), DstType: LHSTy,
4157 Loc: E->getExprLoc()),
4158 Ty: LHSTy);
4159
4160 llvm::AtomicRMWInst *OldVal =
4161 CGF.emitAtomicRMWInst(Op: AtomicOp, Addr: LHSLV.getAddress(), Val: Amt);
4162
4163 // Since operation is atomic, the result type is guaranteed to be the
4164 // same as the input in LLVM terms.
4165 Result = Builder.CreateBinOp(Opc: Op, LHS: OldVal, RHS: Amt);
4166 return LHSLV;
4167 }
4168 }
4169 // FIXME: For floating point types, we should be saving and restoring the
4170 // floating point environment in the loop.
4171 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
4172 llvm::BasicBlock *opBB = CGF.createBasicBlock(name: "atomic_op", parent: CGF.CurFn);
4173 OpInfo.LHS = EmitLoadOfLValue(LV: LHSLV, Loc: E->getExprLoc());
4174 OpInfo.LHS = CGF.EmitToMemory(Value: OpInfo.LHS, Ty: type);
4175 Builder.CreateBr(Dest: opBB);
4176 Builder.SetInsertPoint(opBB);
4177 atomicPHI = Builder.CreatePHI(Ty: OpInfo.LHS->getType(), NumReservedValues: 2);
4178 atomicPHI->addIncoming(V: OpInfo.LHS, BB: startBB);
4179 OpInfo.LHS = atomicPHI;
4180 }
4181 else
4182 OpInfo.LHS = EmitLoadOfLValue(LV: LHSLV, Loc: E->getExprLoc());
4183
4184 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
4185 SourceLocation Loc = E->getExprLoc();
4186 if (!PromotionTypeLHS.isNull())
4187 OpInfo.LHS = EmitScalarConversion(Src: OpInfo.LHS, SrcType: LHSTy, DstType: PromotionTypeLHS,
4188 Loc: E->getExprLoc());
4189 else
4190 OpInfo.LHS = EmitScalarConversion(Src: OpInfo.LHS, SrcType: LHSTy,
4191 DstType: E->getComputationLHSType(), Loc);
4192
4193 // Expand the binary operator.
4194 Result = (this->*Func)(OpInfo);
4195
4196 // Convert the result back to the LHS type,
4197 // potentially with Implicit Conversion sanitizer check.
4198 // If LHSLV is a bitfield, use default ScalarConversionOpts
4199 // to avoid emit any implicit integer checks.
4200 Value *Previous = nullptr;
4201 if (LHSLV.isBitField()) {
4202 Previous = Result;
4203 Result = EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: LHSTy, Loc);
4204 } else if (const auto *atomicTy = LHSTy->getAs<AtomicType>()) {
4205 Result =
4206 EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: atomicTy->getValueType(),
4207 Loc, Opts: ScalarConversionOpts(CGF.SanOpts));
4208 } else {
4209 Result = EmitScalarConversion(Src: Result, SrcType: PromotionTypeCR, DstType: LHSTy, Loc,
4210 Opts: ScalarConversionOpts(CGF.SanOpts));
4211 }
4212
4213 if (atomicPHI) {
4214 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
4215 llvm::BasicBlock *contBB = CGF.createBasicBlock(name: "atomic_cont", parent: CGF.CurFn);
4216 auto Pair = CGF.EmitAtomicCompareExchange(
4217 Obj: LHSLV, Expected: RValue::get(V: atomicPHI), Desired: RValue::get(V: Result), Loc: E->getExprLoc());
4218 llvm::Value *old = CGF.EmitToMemory(Value: Pair.first.getScalarVal(), Ty: LHSTy);
4219 llvm::Value *success = Pair.second;
4220 atomicPHI->addIncoming(V: old, BB: curBlock);
4221 Builder.CreateCondBr(Cond: success, True: contBB, False: atomicPHI->getParent());
4222 Builder.SetInsertPoint(contBB);
4223 return LHSLV;
4224 }
4225
4226 // Store the result value into the LHS lvalue. Bit-fields are handled
4227 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
4228 // 'An assignment expression has the value of the left operand after the
4229 // assignment...'.
4230 if (LHSLV.isBitField()) {
4231 Value *Src = Previous ? Previous : Result;
4232 QualType SrcType = E->getRHS()->getType();
4233 QualType DstType = E->getLHS()->getType();
4234 CGF.EmitStoreThroughBitfieldLValue(Src: RValue::get(V: Result), Dst: LHSLV, Result: &Result);
4235 CGF.EmitBitfieldConversionCheck(Src, SrcType, Dst: Result, DstType,
4236 Info: LHSLV.getBitFieldInfo(), Loc: E->getExprLoc());
4237 } else
4238 CGF.EmitStoreThroughLValue(Src: RValue::get(V: Result), Dst: LHSLV);
4239
4240 if (CGF.getLangOpts().OpenMP)
4241 CGF.CGM.getOpenMPRuntime().checkAndEmitLastprivateConditional(CGF,
4242 LHS: E->getLHS());
4243 return LHSLV;
4244}
4245
4246Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
4247 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
4248 bool Ignore = TestAndClearIgnoreResultAssign();
4249 Value *RHS = nullptr;
4250 LValue LHS = EmitCompoundAssignLValue(E, Func, Result&: RHS);
4251
4252 // If the result is clearly ignored, return now.
4253 if (Ignore)
4254 return nullptr;
4255
4256 // The result of an assignment in C is the assigned r-value.
4257 if (!CGF.getLangOpts().CPlusPlus)
4258 return RHS;
4259
4260 // If the lvalue is non-volatile, return the computed value of the assignment.
4261 if (!LHS.isVolatileQualified())
4262 return RHS;
4263
4264 // Otherwise, reload the value.
4265 return EmitLoadOfLValue(LV: LHS, Loc: E->getExprLoc());
4266}
4267
4268void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
4269 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
4270 SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>, 2>
4271 Checks;
4272
4273 if (CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero)) {
4274 Checks.push_back(Elt: std::make_pair(x: Builder.CreateICmpNE(LHS: Ops.RHS, RHS: Zero),
4275 y: SanitizerKind::SO_IntegerDivideByZero));
4276 }
4277
4278 const auto *BO = cast<BinaryOperator>(Val: Ops.E);
4279 if (CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow) &&
4280 Ops.Ty->hasSignedIntegerRepresentation() &&
4281 !IsWidenedIntegerOp(Ctx: CGF.getContext(), E: BO->getLHS()) &&
4282 Ops.mayHaveIntegerOverflow() &&
4283 !CGF.getContext().isTypeIgnoredBySanitizer(
4284 Mask: SanitizerKind::SignedIntegerOverflow, Ty: Ops.Ty)) {
4285 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Val: Zero->getType());
4286
4287 llvm::Value *IntMin =
4288 Builder.getInt(AI: llvm::APInt::getSignedMinValue(numBits: Ty->getBitWidth()));
4289 llvm::Value *NegOne = llvm::Constant::getAllOnesValue(Ty);
4290
4291 llvm::Value *LHSCmp = Builder.CreateICmpNE(LHS: Ops.LHS, RHS: IntMin);
4292 llvm::Value *RHSCmp = Builder.CreateICmpNE(LHS: Ops.RHS, RHS: NegOne);
4293 llvm::Value *NotOverflow = Builder.CreateOr(LHS: LHSCmp, RHS: RHSCmp, Name: "or");
4294 Checks.push_back(
4295 Elt: std::make_pair(x&: NotOverflow, y: SanitizerKind::SO_SignedIntegerOverflow));
4296 }
4297
4298 if (Checks.size() > 0)
4299 EmitBinOpCheck(Checks, Info: Ops);
4300}
4301
4302Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
4303 {
4304 SanitizerDebugLocation SanScope(&CGF,
4305 {SanitizerKind::SO_IntegerDivideByZero,
4306 SanitizerKind::SO_SignedIntegerOverflow,
4307 SanitizerKind::SO_FloatDivideByZero},
4308 SanitizerHandler::DivremOverflow);
4309 if ((CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero) ||
4310 CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) &&
4311 Ops.Ty->isIntegerType() &&
4312 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
4313 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty));
4314 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, isDiv: true);
4315 } else if (CGF.SanOpts.has(K: SanitizerKind::FloatDivideByZero) &&
4316 Ops.Ty->isRealFloatingType() &&
4317 Ops.mayHaveFloatDivisionByZero()) {
4318 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty));
4319 llvm::Value *NonZero = Builder.CreateFCmpUNE(LHS: Ops.RHS, RHS: Zero);
4320 EmitBinOpCheck(
4321 Checks: std::make_pair(x&: NonZero, y: SanitizerKind::SO_FloatDivideByZero), Info: Ops);
4322 }
4323 }
4324
4325 if (Ops.Ty->isConstantMatrixType()) {
4326 llvm::MatrixBuilder MB(Builder);
4327 // We need to check the types of the operands of the operator to get the
4328 // correct matrix dimensions.
4329 auto *BO = cast<BinaryOperator>(Val: Ops.E);
4330 (void)BO;
4331 assert(
4332 isa<ConstantMatrixType>(BO->getLHS()->getType().getCanonicalType()) &&
4333 "first operand must be a matrix");
4334 assert(BO->getRHS()->getType().getCanonicalType()->isArithmeticType() &&
4335 "second operand must be an arithmetic type");
4336 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
4337 return MB.CreateScalarDiv(LHS: Ops.LHS, RHS: Ops.RHS,
4338 IsUnsigned: Ops.Ty->hasUnsignedIntegerRepresentation());
4339 }
4340
4341 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
4342 llvm::Value *Val;
4343 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
4344 Val = Builder.CreateFDiv(L: Ops.LHS, R: Ops.RHS, Name: "div");
4345 CGF.SetDivFPAccuracy(Val);
4346 return Val;
4347 }
4348 else if (Ops.isFixedPointOp())
4349 return EmitFixedPointBinOp(Ops);
4350 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
4351 return Builder.CreateUDiv(LHS: Ops.LHS, RHS: Ops.RHS, Name: "div");
4352 else
4353 return Builder.CreateSDiv(LHS: Ops.LHS, RHS: Ops.RHS, Name: "div");
4354}
4355
4356Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
4357 // Rem in C can't be a floating point type: C99 6.5.5p2.
4358 if ((CGF.SanOpts.has(K: SanitizerKind::IntegerDivideByZero) ||
4359 CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) &&
4360 Ops.Ty->isIntegerType() &&
4361 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
4362 SanitizerDebugLocation SanScope(&CGF,
4363 {SanitizerKind::SO_IntegerDivideByZero,
4364 SanitizerKind::SO_SignedIntegerOverflow},
4365 SanitizerHandler::DivremOverflow);
4366 llvm::Value *Zero = llvm::Constant::getNullValue(Ty: ConvertType(T: Ops.Ty));
4367 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, isDiv: false);
4368 }
4369
4370 if (Ops.Ty->hasUnsignedIntegerRepresentation())
4371 return Builder.CreateURem(LHS: Ops.LHS, RHS: Ops.RHS, Name: "rem");
4372
4373 if (CGF.getLangOpts().HLSL && Ops.Ty->hasFloatingRepresentation())
4374 return Builder.CreateFRem(L: Ops.LHS, R: Ops.RHS, Name: "rem");
4375
4376 return Builder.CreateSRem(LHS: Ops.LHS, RHS: Ops.RHS, Name: "rem");
4377}
4378
4379Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
4380 unsigned IID;
4381 unsigned OpID = 0;
4382 SanitizerHandler OverflowKind;
4383
4384 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
4385 switch (Ops.Opcode) {
4386 case BO_Add:
4387 case BO_AddAssign:
4388 OpID = 1;
4389 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
4390 llvm::Intrinsic::uadd_with_overflow;
4391 OverflowKind = SanitizerHandler::AddOverflow;
4392 break;
4393 case BO_Sub:
4394 case BO_SubAssign:
4395 OpID = 2;
4396 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
4397 llvm::Intrinsic::usub_with_overflow;
4398 OverflowKind = SanitizerHandler::SubOverflow;
4399 break;
4400 case BO_Mul:
4401 case BO_MulAssign:
4402 OpID = 3;
4403 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
4404 llvm::Intrinsic::umul_with_overflow;
4405 OverflowKind = SanitizerHandler::MulOverflow;
4406 break;
4407 default:
4408 llvm_unreachable("Unsupported operation for overflow detection");
4409 }
4410 OpID <<= 1;
4411 if (isSigned)
4412 OpID |= 1;
4413
4414 SanitizerDebugLocation SanScope(&CGF,
4415 {SanitizerKind::SO_SignedIntegerOverflow,
4416 SanitizerKind::SO_UnsignedIntegerOverflow},
4417 OverflowKind);
4418 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(T: Ops.Ty);
4419
4420 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, Tys: opTy);
4421
4422 Value *resultAndOverflow = Builder.CreateCall(Callee: intrinsic, Args: {Ops.LHS, Ops.RHS});
4423 Value *result = Builder.CreateExtractValue(Agg: resultAndOverflow, Idxs: 0);
4424 Value *overflow = Builder.CreateExtractValue(Agg: resultAndOverflow, Idxs: 1);
4425
4426 // Handle overflow with llvm.trap if no custom handler has been specified.
4427 const std::string *handlerName =
4428 &CGF.getLangOpts().OverflowHandler;
4429 if (handlerName->empty()) {
4430 // If no -ftrapv handler has been specified, try to use sanitizer runtimes
4431 // if available otherwise just emit a trap. It is possible for unsigned
4432 // arithmetic to result in a trap due to the OverflowBehaviorType attribute
4433 // which describes overflow behavior on a per-type basis.
4434 if (isSigned) {
4435 if (CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)) {
4436 llvm::Value *NotOf = Builder.CreateNot(V: overflow);
4437 EmitBinOpCheck(
4438 Checks: std::make_pair(x&: NotOf, y: SanitizerKind::SO_SignedIntegerOverflow),
4439 Info: Ops);
4440 } else
4441 CGF.EmitTrapCheck(Checked: Builder.CreateNot(V: overflow), CheckHandlerID: OverflowKind);
4442 return result;
4443 }
4444 if (CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow)) {
4445 llvm::Value *NotOf = Builder.CreateNot(V: overflow);
4446 EmitBinOpCheck(
4447 Checks: std::make_pair(x&: NotOf, y: SanitizerKind::SO_UnsignedIntegerOverflow),
4448 Info: Ops);
4449 } else
4450 CGF.EmitTrapCheck(Checked: Builder.CreateNot(V: overflow), CheckHandlerID: OverflowKind);
4451 return result;
4452 }
4453
4454 // Branch in case of overflow.
4455 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
4456 llvm::BasicBlock *continueBB =
4457 CGF.createBasicBlock(name: "nooverflow", parent: CGF.CurFn, before: initialBB->getNextNode());
4458 llvm::BasicBlock *overflowBB = CGF.createBasicBlock(name: "overflow", parent: CGF.CurFn);
4459
4460 Builder.CreateCondBr(Cond: overflow, True: overflowBB, False: continueBB);
4461
4462 // If an overflow handler is set, then we want to call it and then use its
4463 // result, if it returns.
4464 Builder.SetInsertPoint(overflowBB);
4465
4466 // Get the overflow handler.
4467 llvm::Type *Int8Ty = CGF.Int8Ty;
4468 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
4469 llvm::FunctionType *handlerTy =
4470 llvm::FunctionType::get(Result: CGF.Int64Ty, Params: argTypes, isVarArg: true);
4471 llvm::FunctionCallee handler =
4472 CGF.CGM.CreateRuntimeFunction(Ty: handlerTy, Name: *handlerName);
4473
4474 // Sign extend the args to 64-bit, so that we can use the same handler for
4475 // all types of overflow.
4476 llvm::Value *lhs = Builder.CreateSExt(V: Ops.LHS, DestTy: CGF.Int64Ty);
4477 llvm::Value *rhs = Builder.CreateSExt(V: Ops.RHS, DestTy: CGF.Int64Ty);
4478
4479 // Call the handler with the two arguments, the operation, and the size of
4480 // the result.
4481 llvm::Value *handlerArgs[] = {
4482 lhs,
4483 rhs,
4484 Builder.getInt8(C: OpID),
4485 Builder.getInt8(C: cast<llvm::IntegerType>(Val: opTy)->getBitWidth())
4486 };
4487 llvm::Value *handlerResult =
4488 CGF.EmitNounwindRuntimeCall(callee: handler, args: handlerArgs);
4489
4490 // Truncate the result back to the desired size.
4491 handlerResult = Builder.CreateTrunc(V: handlerResult, DestTy: opTy);
4492 Builder.CreateBr(Dest: continueBB);
4493
4494 Builder.SetInsertPoint(continueBB);
4495 llvm::PHINode *phi = Builder.CreatePHI(Ty: opTy, NumReservedValues: 2);
4496 phi->addIncoming(V: result, BB: initialBB);
4497 phi->addIncoming(V: handlerResult, BB: overflowBB);
4498
4499 return phi;
4500}
4501
4502/// BO_Add/BO_Sub are handled by EmitPointerWithAlignment to preserve alignment
4503/// information.
4504/// This function is used for BO_AddAssign/BO_SubAssign.
4505static Value *emitPointerArithmetic(CodeGenFunction &CGF, const BinOpInfo &op,
4506 bool isSubtraction) {
4507 // Must have binary (not unary) expr here. Unary pointer
4508 // increment/decrement doesn't use this path.
4509 const BinaryOperator *expr = cast<BinaryOperator>(Val: op.E);
4510
4511 Value *pointer = op.LHS;
4512 Expr *pointerOperand = expr->getLHS();
4513 Value *index = op.RHS;
4514 Expr *indexOperand = expr->getRHS();
4515
4516 // In a subtraction, the LHS is always the pointer.
4517 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
4518 std::swap(a&: pointer, b&: index);
4519 std::swap(a&: pointerOperand, b&: indexOperand);
4520 }
4521
4522 return CGF.EmitPointerArithmetic(BO: expr, pointerOperand, pointer, indexOperand,
4523 index, isSubtraction);
4524}
4525
4526/// Emit pointer + index arithmetic.
4527llvm::Value *CodeGenFunction::EmitPointerArithmetic(
4528 const BinaryOperator *BO, Expr *pointerOperand, llvm::Value *pointer,
4529 Expr *indexOperand, llvm::Value *index, bool isSubtraction) {
4530 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
4531
4532 unsigned width = cast<llvm::IntegerType>(Val: index->getType())->getBitWidth();
4533 auto &DL = CGM.getDataLayout();
4534 auto *PtrTy = cast<llvm::PointerType>(Val: pointer->getType());
4535
4536 // Some versions of glibc and gcc use idioms (particularly in their malloc
4537 // routines) that add a pointer-sized integer (known to be a pointer value)
4538 // to a null pointer in order to cast the value back to an integer or as
4539 // part of a pointer alignment algorithm. This is undefined behavior, but
4540 // we'd like to be able to compile programs that use it.
4541 //
4542 // Normally, we'd generate a GEP with a null-pointer base here in response
4543 // to that code, but it's also UB to dereference a pointer created that
4544 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
4545 // generate a direct cast of the integer value to a pointer.
4546 //
4547 // The idiom (p = nullptr + N) is not met if any of the following are true:
4548 //
4549 // The operation is subtraction.
4550 // The index is not pointer-sized.
4551 // The pointer type is not byte-sized.
4552 //
4553 // Note that we do not suppress the pointer overflow check in this case.
4554 if (BinaryOperator::isNullPointerArithmeticExtension(
4555 Ctx&: getContext(), Opc: BO->getOpcode(), LHS: pointerOperand, RHS: indexOperand)) {
4556 llvm::Value *Ptr = Builder.CreateIntToPtr(V: index, DestTy: pointer->getType());
4557 if (getLangOpts().PointerOverflowDefined ||
4558 !SanOpts.has(K: SanitizerKind::PointerOverflow) ||
4559 NullPointerIsDefined(F: Builder.GetInsertBlock()->getParent(),
4560 AS: PtrTy->getPointerAddressSpace()))
4561 return Ptr;
4562 // The inbounds GEP of null is valid iff the index is zero.
4563 auto CheckOrdinal = SanitizerKind::SO_PointerOverflow;
4564 auto CheckHandler = SanitizerHandler::PointerOverflow;
4565 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
4566 llvm::Value *IsZeroIndex = Builder.CreateIsNull(Arg: index);
4567 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc: BO->getExprLoc())};
4568 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
4569 llvm::Value *IntPtr = llvm::Constant::getNullValue(Ty: IntPtrTy);
4570 llvm::Value *ComputedGEP = Builder.CreateZExtOrTrunc(V: index, DestTy: IntPtrTy);
4571 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
4572 EmitCheck(Checked: {{IsZeroIndex, CheckOrdinal}}, Check: CheckHandler, StaticArgs,
4573 DynamicArgs);
4574 return Ptr;
4575 }
4576
4577 if (width != DL.getIndexTypeSizeInBits(Ty: PtrTy)) {
4578 // Zero-extend or sign-extend the pointer value according to
4579 // whether the index is signed or not.
4580 index = Builder.CreateIntCast(V: index, DestTy: DL.getIndexType(PtrTy), isSigned,
4581 Name: "idx.ext");
4582 }
4583
4584 // If this is subtraction, negate the index.
4585 if (isSubtraction)
4586 index = Builder.CreateNeg(V: index, Name: "idx.neg");
4587
4588 if (SanOpts.has(K: SanitizerKind::ArrayBounds))
4589 EmitBoundsCheck(ArrayExpr: BO, ArrayExprBase: pointerOperand, Index: index, IndexType: indexOperand->getType(),
4590 /*Accessed*/ false);
4591
4592 const PointerType *pointerType =
4593 pointerOperand->getType()->getAs<PointerType>();
4594 if (!pointerType) {
4595 QualType objectType = pointerOperand->getType()
4596 ->castAs<ObjCObjectPointerType>()
4597 ->getPointeeType();
4598 llvm::Value *objectSize =
4599 CGM.getSize(numChars: getContext().getTypeSizeInChars(T: objectType));
4600
4601 index = Builder.CreateMul(LHS: index, RHS: objectSize);
4602
4603 llvm::Value *result = Builder.CreateGEP(Ty: Int8Ty, Ptr: pointer, IdxList: index, Name: "add.ptr");
4604 return Builder.CreateBitCast(V: result, DestTy: pointer->getType());
4605 }
4606
4607 QualType elementType = pointerType->getPointeeType();
4608 if (const VariableArrayType *vla =
4609 getContext().getAsVariableArrayType(T: elementType)) {
4610 // The element count here is the total number of non-VLA elements.
4611 llvm::Value *numElements = getVLASize(vla).NumElts;
4612
4613 // Effectively, the multiply by the VLA size is part of the GEP.
4614 // GEP indexes are signed, and scaling an index isn't permitted to
4615 // signed-overflow, so we use the same semantics for our explicit
4616 // multiply. We suppress this if overflow is not undefined behavior.
4617 llvm::Type *elemTy = ConvertTypeForMem(T: vla->getElementType());
4618 if (getLangOpts().PointerOverflowDefined) {
4619 index = Builder.CreateMul(LHS: index, RHS: numElements, Name: "vla.index");
4620 pointer = Builder.CreateGEP(Ty: elemTy, Ptr: pointer, IdxList: index, Name: "add.ptr");
4621 } else {
4622 index = Builder.CreateNSWMul(LHS: index, RHS: numElements, Name: "vla.index");
4623 pointer =
4624 EmitCheckedInBoundsGEP(ElemTy: elemTy, Ptr: pointer, IdxList: index, SignedIndices: isSigned,
4625 IsSubtraction: isSubtraction, Loc: BO->getExprLoc(), Name: "add.ptr");
4626 }
4627 return pointer;
4628 }
4629
4630 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
4631 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
4632 // future proof.
4633 llvm::Type *elemTy;
4634 if (elementType->isVoidType() || elementType->isFunctionType())
4635 elemTy = Int8Ty;
4636 else
4637 elemTy = ConvertTypeForMem(T: elementType);
4638
4639 if (getLangOpts().PointerOverflowDefined)
4640 return Builder.CreateGEP(Ty: elemTy, Ptr: pointer, IdxList: index, Name: "add.ptr");
4641
4642 return EmitCheckedInBoundsGEP(ElemTy: elemTy, Ptr: pointer, IdxList: index, SignedIndices: isSigned, IsSubtraction: isSubtraction,
4643 Loc: BO->getExprLoc(), Name: "add.ptr");
4644}
4645
4646// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
4647// Addend. Use negMul and negAdd to negate the first operand of the Mul or
4648// the add operand respectively. This allows fmuladd to represent a*b-c, or
4649// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
4650// efficient operations.
4651static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
4652 const CodeGenFunction &CGF, CGBuilderTy &Builder,
4653 bool negMul, bool negAdd) {
4654 Value *MulOp0 = MulOp->getOperand(i: 0);
4655 Value *MulOp1 = MulOp->getOperand(i: 1);
4656 if (negMul)
4657 MulOp0 = Builder.CreateFNeg(V: MulOp0, Name: "neg");
4658 if (negAdd)
4659 Addend = Builder.CreateFNeg(V: Addend, Name: "neg");
4660
4661 Value *FMulAdd = nullptr;
4662 if (Builder.getIsFPConstrained()) {
4663 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
4664 "Only constrained operation should be created when Builder is in FP "
4665 "constrained mode");
4666 FMulAdd = Builder.CreateConstrainedFPCall(
4667 Callee: CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::experimental_constrained_fmuladd,
4668 Tys: Addend->getType()),
4669 Args: {MulOp0, MulOp1, Addend});
4670 } else {
4671 FMulAdd = Builder.CreateCall(
4672 Callee: CGF.CGM.getIntrinsic(IID: llvm::Intrinsic::fmuladd, Tys: Addend->getType()),
4673 Args: {MulOp0, MulOp1, Addend});
4674 }
4675 MulOp->eraseFromParent();
4676
4677 return FMulAdd;
4678}
4679
4680// Check whether it would be legal to emit an fmuladd intrinsic call to
4681// represent op and if so, build the fmuladd.
4682//
4683// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
4684// Does NOT check the type of the operation - it's assumed that this function
4685// will be called from contexts where it's known that the type is contractable.
4686static Value* tryEmitFMulAdd(const BinOpInfo &op,
4687 const CodeGenFunction &CGF, CGBuilderTy &Builder,
4688 bool isSub=false) {
4689
4690 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
4691 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
4692 "Only fadd/fsub can be the root of an fmuladd.");
4693
4694 // Check whether this op is marked as fusable.
4695 if (!op.FPFeatures.allowFPContractWithinStatement())
4696 return nullptr;
4697
4698 Value *LHS = op.LHS;
4699 Value *RHS = op.RHS;
4700
4701 // Peek through fneg to look for fmul. Make sure fneg has no users, and that
4702 // it is the only use of its operand.
4703 bool NegLHS = false;
4704 if (auto *LHSUnOp = dyn_cast<llvm::UnaryOperator>(Val: LHS)) {
4705 if (LHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4706 LHSUnOp->use_empty() && LHSUnOp->getOperand(i_nocapture: 0)->hasOneUse()) {
4707 LHS = LHSUnOp->getOperand(i_nocapture: 0);
4708 NegLHS = true;
4709 }
4710 }
4711
4712 bool NegRHS = false;
4713 if (auto *RHSUnOp = dyn_cast<llvm::UnaryOperator>(Val: RHS)) {
4714 if (RHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4715 RHSUnOp->use_empty() && RHSUnOp->getOperand(i_nocapture: 0)->hasOneUse()) {
4716 RHS = RHSUnOp->getOperand(i_nocapture: 0);
4717 NegRHS = true;
4718 }
4719 }
4720
4721 // We have a potentially fusable op. Look for a mul on one of the operands.
4722 // Also, make sure that the mul result isn't used directly. In that case,
4723 // there's no point creating a muladd operation.
4724 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(Val: LHS)) {
4725 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4726 (LHSBinOp->use_empty() || NegLHS)) {
4727 // If we looked through fneg, erase it.
4728 if (NegLHS)
4729 cast<llvm::Instruction>(Val: op.LHS)->eraseFromParent();
4730 return buildFMulAdd(MulOp: LHSBinOp, Addend: op.RHS, CGF, Builder, negMul: NegLHS, negAdd: isSub);
4731 }
4732 }
4733 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(Val: RHS)) {
4734 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4735 (RHSBinOp->use_empty() || NegRHS)) {
4736 // If we looked through fneg, erase it.
4737 if (NegRHS)
4738 cast<llvm::Instruction>(Val: op.RHS)->eraseFromParent();
4739 return buildFMulAdd(MulOp: RHSBinOp, Addend: op.LHS, CGF, Builder, negMul: isSub ^ NegRHS, negAdd: false);
4740 }
4741 }
4742
4743 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(Val: LHS)) {
4744 if (LHSBinOp->getIntrinsicID() ==
4745 llvm::Intrinsic::experimental_constrained_fmul &&
4746 (LHSBinOp->use_empty() || NegLHS)) {
4747 // If we looked through fneg, erase it.
4748 if (NegLHS)
4749 cast<llvm::Instruction>(Val: op.LHS)->eraseFromParent();
4750 return buildFMulAdd(MulOp: LHSBinOp, Addend: op.RHS, CGF, Builder, negMul: NegLHS, negAdd: isSub);
4751 }
4752 }
4753 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(Val: RHS)) {
4754 if (RHSBinOp->getIntrinsicID() ==
4755 llvm::Intrinsic::experimental_constrained_fmul &&
4756 (RHSBinOp->use_empty() || NegRHS)) {
4757 // If we looked through fneg, erase it.
4758 if (NegRHS)
4759 cast<llvm::Instruction>(Val: op.RHS)->eraseFromParent();
4760 return buildFMulAdd(MulOp: RHSBinOp, Addend: op.LHS, CGF, Builder, negMul: isSub ^ NegRHS, negAdd: false);
4761 }
4762 }
4763
4764 return nullptr;
4765}
4766
4767Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
4768 if (op.LHS->getType()->isPointerTy() ||
4769 op.RHS->getType()->isPointerTy())
4770 return emitPointerArithmetic(CGF, op, isSubtraction: CodeGenFunction::NotSubtraction);
4771
4772 if (op.Ty->isSignedIntegerOrEnumerationType() ||
4773 op.Ty->isUnsignedIntegerType()) {
4774 const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType();
4775 const bool hasSan =
4776 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
4777 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
4778 switch (getOverflowBehaviorConsideringType(CGF, Ty: op.Ty)) {
4779 case LangOptions::OB_Wrap:
4780 return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4781 case LangOptions::OB_SignedAndDefined:
4782 if (!hasSan)
4783 return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4784 [[fallthrough]];
4785 case LangOptions::OB_Unset:
4786 if (!hasSan)
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 [[fallthrough]];
4790 case LangOptions::OB_Trap:
4791 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: op))
4792 return isSigned ? Builder.CreateNSWAdd(LHS: op.LHS, RHS: op.RHS, Name: "add")
4793 : Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4794 return EmitOverflowCheckedBinOp(Ops: op);
4795 }
4796 }
4797
4798 // For vector and matrix adds, try to fold into a fmuladd.
4799 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4800 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4801 // Try to form an fmuladd.
4802 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
4803 return FMulAdd;
4804 }
4805
4806 if (op.Ty->isConstantMatrixType()) {
4807 llvm::MatrixBuilder MB(Builder);
4808 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4809 return MB.CreateAdd(LHS: op.LHS, RHS: op.RHS);
4810 }
4811
4812 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4813 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4814 return Builder.CreateFAdd(L: op.LHS, R: op.RHS, Name: "add");
4815 }
4816
4817 if (op.isFixedPointOp())
4818 return EmitFixedPointBinOp(Ops: op);
4819
4820 return Builder.CreateAdd(LHS: op.LHS, RHS: op.RHS, Name: "add");
4821}
4822
4823/// The resulting value must be calculated with exact precision, so the operands
4824/// may not be the same type.
4825Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
4826 using llvm::APSInt;
4827 using llvm::ConstantInt;
4828
4829 // This is either a binary operation where at least one of the operands is
4830 // a fixed-point type, or a unary operation where the operand is a fixed-point
4831 // type. The result type of a binary operation is determined by
4832 // Sema::handleFixedPointConversions().
4833 QualType ResultTy = op.Ty;
4834 QualType LHSTy, RHSTy;
4835 if (const auto *BinOp = dyn_cast<BinaryOperator>(Val: op.E)) {
4836 RHSTy = BinOp->getRHS()->getType();
4837 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(Val: BinOp)) {
4838 // For compound assignment, the effective type of the LHS at this point
4839 // is the computation LHS type, not the actual LHS type, and the final
4840 // result type is not the type of the expression but rather the
4841 // computation result type.
4842 LHSTy = CAO->getComputationLHSType();
4843 ResultTy = CAO->getComputationResultType();
4844 } else
4845 LHSTy = BinOp->getLHS()->getType();
4846 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(Val: op.E)) {
4847 LHSTy = UnOp->getSubExpr()->getType();
4848 RHSTy = UnOp->getSubExpr()->getType();
4849 }
4850 ASTContext &Ctx = CGF.getContext();
4851 Value *LHS = op.LHS;
4852 Value *RHS = op.RHS;
4853
4854 auto LHSFixedSema = Ctx.getFixedPointSemantics(Ty: LHSTy);
4855 auto RHSFixedSema = Ctx.getFixedPointSemantics(Ty: RHSTy);
4856 auto ResultFixedSema = Ctx.getFixedPointSemantics(Ty: ResultTy);
4857 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(Other: RHSFixedSema);
4858
4859 // Perform the actual operation.
4860 Value *Result;
4861 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
4862 switch (op.Opcode) {
4863 case BO_AddAssign:
4864 case BO_Add:
4865 Result = FPBuilder.CreateAdd(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4866 break;
4867 case BO_SubAssign:
4868 case BO_Sub:
4869 Result = FPBuilder.CreateSub(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4870 break;
4871 case BO_MulAssign:
4872 case BO_Mul:
4873 Result = FPBuilder.CreateMul(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4874 break;
4875 case BO_DivAssign:
4876 case BO_Div:
4877 Result = FPBuilder.CreateDiv(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4878 break;
4879 case BO_ShlAssign:
4880 case BO_Shl:
4881 Result = FPBuilder.CreateShl(LHS, LHSSema: LHSFixedSema, RHS);
4882 break;
4883 case BO_ShrAssign:
4884 case BO_Shr:
4885 Result = FPBuilder.CreateShr(LHS, LHSSema: LHSFixedSema, RHS);
4886 break;
4887 case BO_LT:
4888 return FPBuilder.CreateLT(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4889 case BO_GT:
4890 return FPBuilder.CreateGT(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4891 case BO_LE:
4892 return FPBuilder.CreateLE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4893 case BO_GE:
4894 return FPBuilder.CreateGE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4895 case BO_EQ:
4896 // For equality operations, we assume any padding bits on unsigned types are
4897 // zero'd out. They could be overwritten through non-saturating operations
4898 // that cause overflow, but this leads to undefined behavior.
4899 return FPBuilder.CreateEQ(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4900 case BO_NE:
4901 return FPBuilder.CreateNE(LHS, LHSSema: LHSFixedSema, RHS, RHSSema: RHSFixedSema);
4902 case BO_Cmp:
4903 case BO_LAnd:
4904 case BO_LOr:
4905 llvm_unreachable("Found unimplemented fixed point binary operation");
4906 case BO_PtrMemD:
4907 case BO_PtrMemI:
4908 case BO_Rem:
4909 case BO_Xor:
4910 case BO_And:
4911 case BO_Or:
4912 case BO_Assign:
4913 case BO_RemAssign:
4914 case BO_AndAssign:
4915 case BO_XorAssign:
4916 case BO_OrAssign:
4917 case BO_Comma:
4918 llvm_unreachable("Found unsupported binary operation for fixed point types.");
4919 }
4920
4921 bool IsShift = BinaryOperator::isShiftOp(Opc: op.Opcode) ||
4922 BinaryOperator::isShiftAssignOp(Opc: op.Opcode);
4923 // Convert to the result type.
4924 return FPBuilder.CreateFixedToFixed(Src: Result, SrcSema: IsShift ? LHSFixedSema
4925 : CommonFixedSema,
4926 DstSema: ResultFixedSema);
4927}
4928
4929Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
4930 // The LHS is always a pointer if either side is.
4931 if (!op.LHS->getType()->isPointerTy()) {
4932 if (op.Ty->isSignedIntegerOrEnumerationType() ||
4933 op.Ty->isUnsignedIntegerType()) {
4934 const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType();
4935 const bool hasSan =
4936 isSigned ? CGF.SanOpts.has(K: SanitizerKind::SignedIntegerOverflow)
4937 : CGF.SanOpts.has(K: SanitizerKind::UnsignedIntegerOverflow);
4938 switch (getOverflowBehaviorConsideringType(CGF, Ty: op.Ty)) {
4939 case LangOptions::OB_Wrap:
4940 return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4941 case LangOptions::OB_SignedAndDefined:
4942 if (!hasSan)
4943 return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4944 [[fallthrough]];
4945 case LangOptions::OB_Unset:
4946 if (!hasSan)
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 [[fallthrough]];
4950 case LangOptions::OB_Trap:
4951 if (CanElideOverflowCheck(Ctx&: CGF.getContext(), Op: op))
4952 return isSigned ? Builder.CreateNSWSub(LHS: op.LHS, RHS: op.RHS, Name: "sub")
4953 : Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4954 return EmitOverflowCheckedBinOp(Ops: op);
4955 }
4956 }
4957
4958 // For vector and matrix subs, try to fold into a fmuladd.
4959 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4960 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4961 // Try to form an fmuladd.
4962 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, isSub: true))
4963 return FMulAdd;
4964 }
4965
4966 if (op.Ty->isConstantMatrixType()) {
4967 llvm::MatrixBuilder MB(Builder);
4968 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4969 return MB.CreateSub(LHS: op.LHS, RHS: op.RHS);
4970 }
4971
4972 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4973 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4974 return Builder.CreateFSub(L: op.LHS, R: op.RHS, Name: "sub");
4975 }
4976
4977 if (op.isFixedPointOp())
4978 return EmitFixedPointBinOp(op);
4979
4980 return Builder.CreateSub(LHS: op.LHS, RHS: op.RHS, Name: "sub");
4981 }
4982
4983 // If the RHS is not a pointer, then we have normal pointer
4984 // arithmetic.
4985 if (!op.RHS->getType()->isPointerTy())
4986 return emitPointerArithmetic(CGF, op, isSubtraction: CodeGenFunction::IsSubtraction);
4987
4988 // Otherwise, this is a pointer subtraction.
4989
4990 // Do the raw subtraction part.
4991 llvm::Value *LHS
4992 = Builder.CreatePtrToInt(V: op.LHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.lhs.cast");
4993 llvm::Value *RHS
4994 = Builder.CreatePtrToInt(V: op.RHS, DestTy: CGF.PtrDiffTy, Name: "sub.ptr.rhs.cast");
4995 Value *diffInChars = Builder.CreateSub(LHS, RHS, Name: "sub.ptr.sub");
4996
4997 // Okay, figure out the element size.
4998 const BinaryOperator *expr = cast<BinaryOperator>(Val: op.E);
4999 QualType elementType = expr->getLHS()->getType()->getPointeeType();
5000
5001 llvm::Value *divisor = nullptr;
5002
5003 // For a variable-length array, this is going to be non-constant.
5004 if (const VariableArrayType *vla
5005 = CGF.getContext().getAsVariableArrayType(T: elementType)) {
5006 auto VlaSize = CGF.getVLASize(vla);
5007 elementType = VlaSize.Type;
5008 divisor = VlaSize.NumElts;
5009
5010 // Scale the number of non-VLA elements by the non-VLA element size.
5011 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(T: elementType);
5012 if (!eltSize.isOne())
5013 divisor = CGF.Builder.CreateNUWMul(LHS: CGF.CGM.getSize(numChars: eltSize), RHS: divisor);
5014
5015 // For everything elese, we can just compute it, safe in the
5016 // assumption that Sema won't let anything through that we can't
5017 // safely compute the size of.
5018 } else {
5019 CharUnits elementSize;
5020 // Handle GCC extension for pointer arithmetic on void* and
5021 // function pointer types.
5022 if (elementType->isVoidType() || elementType->isFunctionType())
5023 elementSize = CharUnits::One();
5024 else
5025 elementSize = CGF.getContext().getTypeSizeInChars(T: elementType);
5026
5027 // Don't even emit the divide for element size of 1.
5028 if (elementSize.isOne())
5029 return diffInChars;
5030
5031 divisor = CGF.CGM.getSize(numChars: elementSize);
5032 }
5033
5034 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
5035 // pointer difference in C is only defined in the case where both operands
5036 // are pointing to elements of an array.
5037 return Builder.CreateExactSDiv(LHS: diffInChars, RHS: divisor, Name: "sub.ptr.div");
5038}
5039
5040Value *ScalarExprEmitter::GetMaximumShiftAmount(Value *LHS, Value *RHS,
5041 bool RHSIsSigned) {
5042 llvm::IntegerType *Ty;
5043 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Val: LHS->getType()))
5044 Ty = cast<llvm::IntegerType>(Val: VT->getElementType());
5045 else
5046 Ty = cast<llvm::IntegerType>(Val: LHS->getType());
5047 // For a given type of LHS the maximum shift amount is width(LHS)-1, however
5048 // it can occur that width(LHS)-1 > range(RHS). Since there is no check for
5049 // this in ConstantInt::get, this results in the value getting truncated.
5050 // Constrain the return value to be max(RHS) in this case.
5051 llvm::Type *RHSTy = RHS->getType();
5052 llvm::APInt RHSMax =
5053 RHSIsSigned ? llvm::APInt::getSignedMaxValue(numBits: RHSTy->getScalarSizeInBits())
5054 : llvm::APInt::getMaxValue(numBits: RHSTy->getScalarSizeInBits());
5055 if (RHSMax.ult(RHS: Ty->getBitWidth()))
5056 return llvm::ConstantInt::get(Ty: RHSTy, V: RHSMax);
5057 return llvm::ConstantInt::get(Ty: RHSTy, V: Ty->getBitWidth() - 1);
5058}
5059
5060Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
5061 const Twine &Name) {
5062 llvm::IntegerType *Ty;
5063 if (auto *VT = dyn_cast<llvm::VectorType>(Val: LHS->getType()))
5064 Ty = cast<llvm::IntegerType>(Val: VT->getElementType());
5065 else
5066 Ty = cast<llvm::IntegerType>(Val: LHS->getType());
5067
5068 if (llvm::isPowerOf2_64(Value: Ty->getBitWidth()))
5069 return Builder.CreateAnd(LHS: RHS, RHS: GetMaximumShiftAmount(LHS, RHS, RHSIsSigned: false), Name);
5070
5071 return Builder.CreateURem(
5072 LHS: RHS, RHS: llvm::ConstantInt::get(Ty: RHS->getType(), V: Ty->getBitWidth()), Name);
5073}
5074
5075Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
5076 // TODO: This misses out on the sanitizer check below.
5077 if (Ops.isFixedPointOp())
5078 return EmitFixedPointBinOp(op: Ops);
5079
5080 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
5081 // RHS to the same size as the LHS.
5082 Value *RHS = Ops.RHS;
5083 if (Ops.LHS->getType() != RHS->getType())
5084 RHS = Builder.CreateIntCast(V: RHS, DestTy: Ops.LHS->getType(), isSigned: false, Name: "sh_prom");
5085
5086 bool SanitizeSignedBase = CGF.SanOpts.has(K: SanitizerKind::ShiftBase) &&
5087 Ops.Ty->hasSignedIntegerRepresentation() &&
5088 !CGF.getLangOpts().isSignedOverflowDefined() &&
5089 !CGF.getLangOpts().CPlusPlus20;
5090 bool SanitizeUnsignedBase =
5091 CGF.SanOpts.has(K: SanitizerKind::UnsignedShiftBase) &&
5092 Ops.Ty->hasUnsignedIntegerRepresentation();
5093 bool SanitizeBase = SanitizeSignedBase || SanitizeUnsignedBase;
5094 bool SanitizeExponent = CGF.SanOpts.has(K: SanitizerKind::ShiftExponent);
5095 // OpenCL 6.3j: shift values are effectively % word size of LHS.
5096 if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL)
5097 RHS = ConstrainShiftValue(LHS: Ops.LHS, RHS, Name: "shl.mask");
5098 else if ((SanitizeBase || SanitizeExponent) &&
5099 isa<llvm::IntegerType>(Val: Ops.LHS->getType())) {
5100 SmallVector<SanitizerKind::SanitizerOrdinal, 3> Ordinals;
5101 if (SanitizeSignedBase)
5102 Ordinals.push_back(Elt: SanitizerKind::SO_ShiftBase);
5103 if (SanitizeUnsignedBase)
5104 Ordinals.push_back(Elt: SanitizerKind::SO_UnsignedShiftBase);
5105 if (SanitizeExponent)
5106 Ordinals.push_back(Elt: SanitizerKind::SO_ShiftExponent);
5107
5108 SanitizerDebugLocation SanScope(&CGF, Ordinals,
5109 SanitizerHandler::ShiftOutOfBounds);
5110 SmallVector<std::pair<Value *, SanitizerKind::SanitizerOrdinal>, 2> Checks;
5111 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
5112 llvm::Value *WidthMinusOne =
5113 GetMaximumShiftAmount(LHS: Ops.LHS, RHS: Ops.RHS, RHSIsSigned);
5114 llvm::Value *ValidExponent = Builder.CreateICmpULE(LHS: Ops.RHS, RHS: WidthMinusOne);
5115
5116 if (SanitizeExponent) {
5117 Checks.push_back(
5118 Elt: std::make_pair(x&: ValidExponent, y: SanitizerKind::SO_ShiftExponent));
5119 }
5120
5121 if (SanitizeBase) {
5122 // Check whether we are shifting any non-zero bits off the top of the
5123 // integer. We only emit this check if exponent is valid - otherwise
5124 // instructions below will have undefined behavior themselves.
5125 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
5126 llvm::BasicBlock *Cont = CGF.createBasicBlock(name: "cont");
5127 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock(name: "check");
5128 Builder.CreateCondBr(Cond: ValidExponent, True: CheckShiftBase, False: Cont);
5129 llvm::Value *PromotedWidthMinusOne =
5130 (RHS == Ops.RHS) ? WidthMinusOne
5131 : GetMaximumShiftAmount(LHS: Ops.LHS, RHS, RHSIsSigned);
5132 CGF.EmitBlock(BB: CheckShiftBase);
5133 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
5134 LHS: Ops.LHS, RHS: Builder.CreateSub(LHS: PromotedWidthMinusOne, RHS, Name: "shl.zeros",
5135 /*NUW*/ HasNUW: true, /*NSW*/ HasNSW: true),
5136 Name: "shl.check");
5137 if (SanitizeUnsignedBase || CGF.getLangOpts().CPlusPlus) {
5138 // In C99, we are not permitted to shift a 1 bit into the sign bit.
5139 // Under C++11's rules, shifting a 1 bit into the sign bit is
5140 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
5141 // define signed left shifts, so we use the C99 and C++11 rules there).
5142 // Unsigned shifts can always shift into the top bit.
5143 llvm::Value *One = llvm::ConstantInt::get(Ty: BitsShiftedOff->getType(), V: 1);
5144 BitsShiftedOff = Builder.CreateLShr(LHS: BitsShiftedOff, RHS: One);
5145 }
5146 llvm::Value *Zero = llvm::ConstantInt::get(Ty: BitsShiftedOff->getType(), V: 0);
5147 llvm::Value *ValidBase = Builder.CreateICmpEQ(LHS: BitsShiftedOff, RHS: Zero);
5148 CGF.EmitBlock(BB: Cont);
5149 llvm::PHINode *BaseCheck = Builder.CreatePHI(Ty: ValidBase->getType(), NumReservedValues: 2);
5150 BaseCheck->addIncoming(V: Builder.getTrue(), BB: Orig);
5151 BaseCheck->addIncoming(V: ValidBase, BB: CheckShiftBase);
5152 Checks.push_back(Elt: std::make_pair(
5153 x&: BaseCheck, y: SanitizeSignedBase ? SanitizerKind::SO_ShiftBase
5154 : SanitizerKind::SO_UnsignedShiftBase));
5155 }
5156
5157 assert(!Checks.empty());
5158 EmitBinOpCheck(Checks, Info: Ops);
5159 }
5160
5161 return Builder.CreateShl(LHS: Ops.LHS, RHS, Name: "shl");
5162}
5163
5164Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
5165 // TODO: This misses out on the sanitizer check below.
5166 if (Ops.isFixedPointOp())
5167 return EmitFixedPointBinOp(op: Ops);
5168
5169 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
5170 // RHS to the same size as the LHS.
5171 Value *RHS = Ops.RHS;
5172 if (Ops.LHS->getType() != RHS->getType())
5173 RHS = Builder.CreateIntCast(V: RHS, DestTy: Ops.LHS->getType(), isSigned: false, Name: "sh_prom");
5174
5175 // OpenCL 6.3j: shift values are effectively % word size of LHS.
5176 if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL)
5177 RHS = ConstrainShiftValue(LHS: Ops.LHS, RHS, Name: "shr.mask");
5178 else if (CGF.SanOpts.has(K: SanitizerKind::ShiftExponent) &&
5179 isa<llvm::IntegerType>(Val: Ops.LHS->getType())) {
5180 SanitizerDebugLocation SanScope(&CGF, {SanitizerKind::SO_ShiftExponent},
5181 SanitizerHandler::ShiftOutOfBounds);
5182 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
5183 llvm::Value *Valid = Builder.CreateICmpULE(
5184 LHS: Ops.RHS, RHS: GetMaximumShiftAmount(LHS: Ops.LHS, RHS: Ops.RHS, RHSIsSigned));
5185 EmitBinOpCheck(Checks: std::make_pair(x&: Valid, y: SanitizerKind::SO_ShiftExponent), Info: Ops);
5186 }
5187
5188 if (Ops.Ty->hasUnsignedIntegerRepresentation())
5189 return Builder.CreateLShr(LHS: Ops.LHS, RHS, Name: "shr");
5190 return Builder.CreateAShr(LHS: Ops.LHS, RHS, Name: "shr");
5191}
5192
5193enum IntrinsicType { VCMPEQ, VCMPGT };
5194// return corresponding comparison intrinsic for given vector type
5195static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
5196 BuiltinType::Kind ElemKind) {
5197 switch (ElemKind) {
5198 default: llvm_unreachable("unexpected element type");
5199 case BuiltinType::Char_U:
5200 case BuiltinType::UChar:
5201 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
5202 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
5203 case BuiltinType::Char_S:
5204 case BuiltinType::SChar:
5205 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
5206 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
5207 case BuiltinType::UShort:
5208 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
5209 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
5210 case BuiltinType::Short:
5211 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
5212 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
5213 case BuiltinType::UInt:
5214 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
5215 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
5216 case BuiltinType::Int:
5217 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
5218 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
5219 case BuiltinType::ULong:
5220 case BuiltinType::ULongLong:
5221 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
5222 llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
5223 case BuiltinType::Long:
5224 case BuiltinType::LongLong:
5225 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
5226 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
5227 case BuiltinType::Float:
5228 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
5229 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
5230 case BuiltinType::Double:
5231 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
5232 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
5233 case BuiltinType::UInt128:
5234 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
5235 : llvm::Intrinsic::ppc_altivec_vcmpgtuq_p;
5236 case BuiltinType::Int128:
5237 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
5238 : llvm::Intrinsic::ppc_altivec_vcmpgtsq_p;
5239 }
5240}
5241
5242Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
5243 llvm::CmpInst::Predicate UICmpOpc,
5244 llvm::CmpInst::Predicate SICmpOpc,
5245 llvm::CmpInst::Predicate FCmpOpc,
5246 bool IsSignaling) {
5247 TestAndClearIgnoreResultAssign();
5248 Value *Result;
5249 QualType LHSTy = E->getLHS()->getType();
5250 QualType RHSTy = E->getRHS()->getType();
5251 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
5252 assert(E->getOpcode() == BO_EQ ||
5253 E->getOpcode() == BO_NE);
5254 Value *LHS = CGF.EmitScalarExpr(E: E->getLHS());
5255 Value *RHS = CGF.EmitScalarExpr(E: E->getRHS());
5256 Result = CGF.CGM.getCXXABI().EmitMemberPointerComparison(
5257 CGF, L: LHS, R: RHS, MPT, Inequality: E->getOpcode() == BO_NE);
5258 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
5259 BinOpInfo BOInfo = EmitBinOps(E);
5260 Value *LHS = BOInfo.LHS;
5261 Value *RHS = BOInfo.RHS;
5262
5263 // If AltiVec, the comparison results in a numeric type, so we use
5264 // intrinsics comparing vectors and giving 0 or 1 as a result
5265 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
5266 // constants for mapping CR6 register bits to predicate result
5267 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
5268
5269 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
5270
5271 // in several cases vector arguments order will be reversed
5272 Value *FirstVecArg = LHS,
5273 *SecondVecArg = RHS;
5274
5275 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
5276 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
5277
5278 switch(E->getOpcode()) {
5279 default: llvm_unreachable("is not a comparison operation");
5280 case BO_EQ:
5281 CR6 = CR6_LT;
5282 ID = GetIntrinsic(IT: VCMPEQ, ElemKind: ElementKind);
5283 break;
5284 case BO_NE:
5285 CR6 = CR6_EQ;
5286 ID = GetIntrinsic(IT: VCMPEQ, ElemKind: ElementKind);
5287 break;
5288 case BO_LT:
5289 CR6 = CR6_LT;
5290 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5291 std::swap(a&: FirstVecArg, b&: SecondVecArg);
5292 break;
5293 case BO_GT:
5294 CR6 = CR6_LT;
5295 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5296 break;
5297 case BO_LE:
5298 if (ElementKind == BuiltinType::Float) {
5299 CR6 = CR6_LT;
5300 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
5301 std::swap(a&: FirstVecArg, b&: SecondVecArg);
5302 }
5303 else {
5304 CR6 = CR6_EQ;
5305 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5306 }
5307 break;
5308 case BO_GE:
5309 if (ElementKind == BuiltinType::Float) {
5310 CR6 = CR6_LT;
5311 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
5312 }
5313 else {
5314 CR6 = CR6_EQ;
5315 ID = GetIntrinsic(IT: VCMPGT, ElemKind: ElementKind);
5316 std::swap(a&: FirstVecArg, b&: SecondVecArg);
5317 }
5318 break;
5319 }
5320
5321 Value *CR6Param = Builder.getInt32(C: CR6);
5322 llvm::Function *F = CGF.CGM.getIntrinsic(IID: ID);
5323 Result = Builder.CreateCall(Callee: F, Args: {CR6Param, FirstVecArg, SecondVecArg});
5324
5325 // The result type of intrinsic may not be same as E->getType().
5326 // If E->getType() is not BoolTy, EmitScalarConversion will do the
5327 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
5328 // do nothing, if ResultTy is not i1 at the same time, it will cause
5329 // crash later.
5330 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Val: Result->getType());
5331 if (ResultTy->getBitWidth() > 1 &&
5332 E->getType() == CGF.getContext().BoolTy)
5333 Result = Builder.CreateTrunc(V: Result, DestTy: Builder.getInt1Ty());
5334 return EmitScalarConversion(Src: Result, SrcType: CGF.getContext().BoolTy, DstType: E->getType(),
5335 Loc: E->getExprLoc());
5336 }
5337
5338 if (BOInfo.isFixedPointOp()) {
5339 Result = EmitFixedPointBinOp(op: BOInfo);
5340 } else if (LHS->getType()->isFPOrFPVectorTy()) {
5341 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures);
5342 if (!IsSignaling)
5343 Result = Builder.CreateFCmp(P: FCmpOpc, LHS, RHS, Name: "cmp");
5344 else
5345 Result = Builder.CreateFCmpS(P: FCmpOpc, LHS, RHS, Name: "cmp");
5346 } else if (LHSTy->hasSignedIntegerRepresentation()) {
5347 Result = Builder.CreateICmp(P: SICmpOpc, LHS, RHS, Name: "cmp");
5348 } else {
5349 // Unsigned integers and pointers.
5350
5351 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
5352 !isa<llvm::ConstantPointerNull>(Val: LHS) &&
5353 !isa<llvm::ConstantPointerNull>(Val: RHS)) {
5354
5355 // Dynamic information is required to be stripped for comparisons,
5356 // because it could leak the dynamic information. Based on comparisons
5357 // of pointers to dynamic objects, the optimizer can replace one pointer
5358 // with another, which might be incorrect in presence of invariant
5359 // groups. Comparison with null is safe because null does not carry any
5360 // dynamic information.
5361 if (LHSTy.mayBeDynamicClass())
5362 LHS = Builder.CreateStripInvariantGroup(Ptr: LHS);
5363 if (RHSTy.mayBeDynamicClass())
5364 RHS = Builder.CreateStripInvariantGroup(Ptr: RHS);
5365 }
5366
5367 Result = Builder.CreateICmp(P: UICmpOpc, LHS, RHS, Name: "cmp");
5368 }
5369
5370 // If this is a vector comparison, sign extend the result to the appropriate
5371 // vector integer type and return it (don't convert to bool).
5372 if (LHSTy->isVectorType() || LHSTy->isSveVLSBuiltinType())
5373 return Builder.CreateSExt(V: Result, DestTy: ConvertType(T: E->getType()), Name: "sext");
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 assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
6466 EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
6467 "If the offset got constant-folded, we don't expect that there was an "
6468 "overflow.");
6469
6470 auto *Zero = llvm::ConstantInt::getNullValue(Ty: IntPtrTy);
6471
6472 // Common case: if the total offset is zero, don't emit a check.
6473 if (EvaluatedGEP.TotalOffset == Zero)
6474 return GEPVal;
6475
6476 // Now that we've computed the total offset, add it to the base pointer (with
6477 // wrapping semantics).
6478 auto *IntPtr = Builder.CreatePtrToInt(V: Ptr, DestTy: IntPtrTy);
6479 auto *ComputedGEP = Builder.CreateAdd(LHS: IntPtr, RHS: EvaluatedGEP.TotalOffset);
6480
6481 llvm::SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>,
6482 2>
6483 Checks;
6484
6485 if (PerformNullCheck) {
6486 // If the base pointer evaluates to a null pointer value,
6487 // the only valid pointer this inbounds GEP can produce is also
6488 // a null pointer, so the offset must also evaluate to zero.
6489 // Likewise, if we have non-zero base pointer, we can not get null pointer
6490 // as a result, so the offset can not be -intptr_t(BasePtr).
6491 // In other words, both pointers are either null, or both are non-null,
6492 // or the behaviour is undefined.
6493 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Arg: Ptr);
6494 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(Arg: ComputedGEP);
6495 auto *Valid = Builder.CreateICmpEQ(LHS: BaseIsNotNullptr, RHS: ResultIsNotNullptr);
6496 Checks.emplace_back(Args&: Valid, Args&: CheckOrdinal);
6497 }
6498
6499 if (PerformOverflowCheck) {
6500 // The GEP is valid if:
6501 // 1) The total offset doesn't overflow, and
6502 // 2) The sign of the difference between the computed address and the base
6503 // pointer matches the sign of the total offset.
6504 llvm::Value *ValidGEP;
6505 auto *NoOffsetOverflow = Builder.CreateNot(V: EvaluatedGEP.OffsetOverflows);
6506 if (SignedIndices) {
6507 // GEP is computed as `unsigned base + signed offset`, therefore:
6508 // * If offset was positive, then the computed pointer can not be
6509 // [unsigned] less than the base pointer, unless it overflowed.
6510 // * If offset was negative, then the computed pointer can not be
6511 // [unsigned] greater than the bas pointere, unless it overflowed.
6512 auto *PosOrZeroValid = Builder.CreateICmpUGE(LHS: ComputedGEP, RHS: IntPtr);
6513 auto *PosOrZeroOffset =
6514 Builder.CreateICmpSGE(LHS: EvaluatedGEP.TotalOffset, RHS: Zero);
6515 llvm::Value *NegValid = Builder.CreateICmpULT(LHS: ComputedGEP, RHS: IntPtr);
6516 ValidGEP =
6517 Builder.CreateSelect(C: PosOrZeroOffset, True: PosOrZeroValid, False: NegValid);
6518 } else if (!IsSubtraction) {
6519 // GEP is computed as `unsigned base + unsigned offset`, therefore the
6520 // computed pointer can not be [unsigned] less than base pointer,
6521 // unless there was an overflow.
6522 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
6523 ValidGEP = Builder.CreateICmpUGE(LHS: ComputedGEP, RHS: IntPtr);
6524 } else {
6525 // GEP is computed as `unsigned base - unsigned offset`, therefore the
6526 // computed pointer can not be [unsigned] greater than base pointer,
6527 // unless there was an overflow.
6528 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
6529 ValidGEP = Builder.CreateICmpULE(LHS: ComputedGEP, RHS: IntPtr);
6530 }
6531 ValidGEP = Builder.CreateAnd(LHS: ValidGEP, RHS: NoOffsetOverflow);
6532 Checks.emplace_back(Args&: ValidGEP, Args&: CheckOrdinal);
6533 }
6534
6535 assert(!Checks.empty() && "Should have produced some checks.");
6536
6537 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
6538 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
6539 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
6540 EmitCheck(Checked: Checks, Check: CheckHandler, StaticArgs, DynamicArgs);
6541
6542 return GEPVal;
6543}
6544
6545Address CodeGenFunction::EmitCheckedInBoundsGEP(
6546 Address Addr, ArrayRef<Value *> IdxList, llvm::Type *elementType,
6547 bool SignedIndices, bool IsSubtraction, SourceLocation Loc, CharUnits Align,
6548 const Twine &Name) {
6549 if (!SanOpts.has(K: SanitizerKind::PointerOverflow)) {
6550 llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::inBounds();
6551 if (!SignedIndices && !IsSubtraction)
6552 NWFlags |= llvm::GEPNoWrapFlags::noUnsignedWrap();
6553
6554 return Builder.CreateGEP(Addr, IdxList, ElementType: elementType, Align, Name, NW: NWFlags);
6555 }
6556
6557 return RawAddress(
6558 EmitCheckedInBoundsGEP(ElemTy: Addr.getElementType(), Ptr: Addr.emitRawPointer(CGF&: *this),
6559 IdxList, SignedIndices, IsSubtraction, Loc, Name),
6560 elementType, Align);
6561}
6562