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