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