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