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