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