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