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