clang 24.0.0git
CGExprScalar.cpp
Go to the documentation of this file.
1//===--- CGExprScalar.cpp - Emit LLVM Code for Scalar Exprs ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code to emit Expr nodes with scalar LLVM types as LLVM code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCXXABI.h"
14#include "CGCleanup.h"
15#include "CGDebugInfo.h"
16#include "CGHLSLRuntime.h"
17#include "CGObjCRuntime.h"
18#include "CGOpenMPRuntime.h"
19#include "CGRecordLayout.h"
20#include "CodeGenFunction.h"
21#include "CodeGenModule.h"
22#include "ConstantEmitter.h"
23#include "TargetInfo.h"
24#include "TrapReasonBuilder.h"
26#include "clang/AST/Attr.h"
27#include "clang/AST/DeclObjC.h"
28#include "clang/AST/Expr.h"
36#include "llvm/ADT/APFixedPoint.h"
37#include "llvm/ADT/ScopeExit.h"
38#include "llvm/IR/Argument.h"
39#include "llvm/IR/CFG.h"
40#include "llvm/IR/Constants.h"
41#include "llvm/IR/DataLayout.h"
42#include "llvm/IR/DerivedTypes.h"
43#include "llvm/IR/FixedPointBuilder.h"
44#include "llvm/IR/Function.h"
45#include "llvm/IR/GEPNoWrapFlags.h"
46#include "llvm/IR/GetElementPtrTypeIterator.h"
47#include "llvm/IR/GlobalVariable.h"
48#include "llvm/IR/Intrinsics.h"
49#include "llvm/IR/IntrinsicsPowerPC.h"
50#include "llvm/IR/IntrinsicsWebAssembly.h"
51#include "llvm/IR/MatrixBuilder.h"
52#include "llvm/IR/Module.h"
53#include "llvm/Support/TypeSize.h"
54#include <cstdarg>
55#include <optional>
56
57using namespace clang;
58using namespace CodeGen;
59using llvm::Value;
60
61//===----------------------------------------------------------------------===//
62// Scalar Expression Emitter
63//===----------------------------------------------------------------------===//
64
65namespace llvm {
66extern cl::opt<bool> EnableSingleByteCoverage;
67} // namespace llvm
68
69namespace {
70
71/// Determine whether the given binary operation may overflow.
72/// Sets \p Result to the value of the operation for BO_Add, BO_Sub, BO_Mul,
73/// and signed BO_{Div,Rem}. For these opcodes, and for unsigned BO_{Div,Rem},
74/// the returned overflow check is precise. The returned value is 'true' for
75/// all other opcodes, to be conservative.
76bool mayHaveIntegerOverflow(llvm::ConstantInt *LHS, llvm::ConstantInt *RHS,
77 BinaryOperator::Opcode Opcode, bool Signed,
78 llvm::APInt &Result) {
79 // Assume overflow is possible, unless we can prove otherwise.
80 bool Overflow = true;
81 const auto &LHSAP = LHS->getValue();
82 const auto &RHSAP = RHS->getValue();
83 if (Opcode == BO_Add) {
84 Result = Signed ? LHSAP.sadd_ov(RHSAP, Overflow)
85 : LHSAP.uadd_ov(RHSAP, Overflow);
86 } else if (Opcode == BO_Sub) {
87 Result = Signed ? LHSAP.ssub_ov(RHSAP, Overflow)
88 : LHSAP.usub_ov(RHSAP, Overflow);
89 } else if (Opcode == BO_Mul) {
90 Result = Signed ? LHSAP.smul_ov(RHSAP, Overflow)
91 : LHSAP.umul_ov(RHSAP, Overflow);
92 } else if (Opcode == BO_Div || Opcode == BO_Rem) {
93 if (Signed && !RHS->isZero())
94 Result = LHSAP.sdiv_ov(RHSAP, Overflow);
95 else
96 return false;
97 }
98 return Overflow;
99}
100
101struct BinOpInfo {
102 Value *LHS;
103 Value *RHS;
104 QualType Ty; // Computation Type.
105 BinaryOperator::Opcode Opcode; // Opcode of BinOp to perform
106 FPOptions FPFeatures;
107 const Expr *E; // Entire expr, for error unsupported. May not be binop.
108
109 /// Check if the binop can result in integer overflow.
110 bool mayHaveIntegerOverflow() const {
111 // Without constant input, we can't rule out overflow.
112 auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS);
113 auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS);
114 if (!LHSCI || !RHSCI)
115 return true;
116
117 llvm::APInt Result;
118 return ::mayHaveIntegerOverflow(
119 LHSCI, RHSCI, Opcode, Ty->hasSignedIntegerRepresentation(), Result);
120 }
121
122 /// Check if the binop computes a division or a remainder.
123 bool isDivremOp() const {
124 return Opcode == BO_Div || Opcode == BO_Rem || Opcode == BO_DivAssign ||
125 Opcode == BO_RemAssign;
126 }
127
128 /// Check if the binop can result in an integer division by zero.
129 bool mayHaveIntegerDivisionByZero() const {
130 if (isDivremOp())
131 if (auto *CI = dyn_cast<llvm::ConstantInt>(RHS))
132 return CI->isZero();
133 return true;
134 }
135
136 /// Check if the binop can result in a float division by zero.
137 bool mayHaveFloatDivisionByZero() const {
138 if (isDivremOp())
139 if (auto *CFP = dyn_cast<llvm::ConstantFP>(RHS))
140 return CFP->isZero();
141 return true;
142 }
143
144 /// Check if at least one operand is a fixed point type. In such cases, this
145 /// operation did not follow usual arithmetic conversion and both operands
146 /// might not be of the same type.
147 bool isFixedPointOp() const {
148 // We cannot simply check the result type since comparison operations return
149 // an int.
150 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
151 QualType LHSType = BinOp->getLHS()->getType();
152 QualType RHSType = BinOp->getRHS()->getType();
153 return LHSType->isFixedPointType() || RHSType->isFixedPointType();
154 }
155 if (const auto *UnOp = dyn_cast<UnaryOperator>(E))
156 return UnOp->getSubExpr()->getType()->isFixedPointType();
157 return false;
158 }
159
160 /// Check if the RHS has a signed integer representation.
161 bool rhsHasSignedIntegerRepresentation() const {
162 if (const auto *BinOp = dyn_cast<BinaryOperator>(E)) {
163 QualType RHSType = BinOp->getRHS()->getType();
164 return RHSType->hasSignedIntegerRepresentation();
165 }
166 return false;
167 }
168};
169
170static bool MustVisitNullValue(const Expr *E) {
171 // If a null pointer expression's type is the C++0x nullptr_t, then
172 // it's not necessarily a simple constant and it must be evaluated
173 // for its potential side effects.
174 return E->getType()->isNullPtrType();
175}
176
177/// If \p E is a widened promoted integer, get its base (unpromoted) type.
178static std::optional<QualType> getUnwidenedIntegerType(const ASTContext &Ctx,
179 const Expr *E) {
180 const Expr *Base = E->IgnoreImpCasts();
181 if (E == Base)
182 return std::nullopt;
183
184 QualType BaseTy = Base->getType();
185 if (!Ctx.isPromotableIntegerType(BaseTy) ||
186 Ctx.getTypeSize(BaseTy) >= Ctx.getTypeSize(E->getType()))
187 return std::nullopt;
188
189 return BaseTy;
190}
191
192/// Check if \p E is a widened promoted integer.
193static bool IsWidenedIntegerOp(const ASTContext &Ctx, const Expr *E) {
194 return getUnwidenedIntegerType(Ctx, E).has_value();
195}
196
197/// Consider OverflowBehaviorType and language options to calculate the final
198/// overflow behavior for an expression. There are no language options for
199/// unsigned overflow semantics so there is nothing to consider there.
201getOverflowBehaviorConsideringType(const CodeGenFunction &CGF,
202 const QualType Ty) {
203 const OverflowBehaviorType *OBT = Ty->getAs<OverflowBehaviorType>();
204 /// FIXME: Having two enums named `OverflowBehaviorKind` is not ideal, these
205 /// should be unified into one coherent enum that supports both unsigned and
206 /// signed overflow behavior semantics.
207 if (OBT) {
208 switch (OBT->getBehaviorKind()) {
209 case OverflowBehaviorType::OverflowBehaviorKind::Wrap:
211 case OverflowBehaviorType::OverflowBehaviorKind::Trap:
213 }
214 llvm_unreachable("Unknown OverflowBehaviorKind");
215 }
216
217 if (Ty->isUnsignedIntegerType()) {
219 }
220
221 switch (CGF.getLangOpts().getSignedOverflowBehavior()) {
228 }
229 llvm_unreachable("Unknown SignedOverflowBehaviorTy");
230}
231
232/// Check if we can skip the overflow check for \p Op.
233static bool CanElideOverflowCheck(ASTContext &Ctx, const BinOpInfo &Op) {
234 assert((isa<UnaryOperator>(Op.E) || isa<BinaryOperator>(Op.E)) &&
235 "Expected a unary or binary operator");
236
237 // If the binop has constant inputs and we can prove there is no overflow,
238 // we can elide the overflow check.
239 if (!Op.mayHaveIntegerOverflow())
240 return true;
241
242 const UnaryOperator *UO = dyn_cast<UnaryOperator>(Op.E);
243 if (UO && Ctx.isUnaryOverflowPatternExcluded(UO))
244 return true;
245
246 const auto *BO = dyn_cast<BinaryOperator>(Op.E);
247 if (BO && BO->hasExcludedOverflowPattern())
248 return true;
249
250 if (Op.Ty.isWrapType())
251 return true;
252 if (Op.Ty.isTrapType())
253 return false;
254
255 if (Op.Ty->isSignedIntegerType() &&
256 Ctx.isTypeIgnoredBySanitizer(SanitizerKind::SignedIntegerOverflow,
257 Op.Ty)) {
258 return true;
259 }
260
261 if (Op.Ty->isUnsignedIntegerType() &&
262 Ctx.isTypeIgnoredBySanitizer(SanitizerKind::UnsignedIntegerOverflow,
263 Op.Ty)) {
264 return true;
265 }
266
267 // If a unary op has a widened operand, the op cannot overflow.
268 if (UO)
269 return !UO->canOverflow();
270
271 // We usually don't need overflow checks for binops with widened operands.
272 // Multiplication with promoted unsigned operands is a special case.
273 auto OptionalLHSTy = getUnwidenedIntegerType(Ctx, BO->getLHS());
274 if (!OptionalLHSTy)
275 return false;
276
277 auto OptionalRHSTy = getUnwidenedIntegerType(Ctx, BO->getRHS());
278 if (!OptionalRHSTy)
279 return false;
280
281 QualType LHSTy = *OptionalLHSTy;
282 QualType RHSTy = *OptionalRHSTy;
283
284 // This is the simple case: binops without unsigned multiplication, and with
285 // widened operands. No overflow check is needed here.
286 if ((Op.Opcode != BO_Mul && Op.Opcode != BO_MulAssign) ||
287 !LHSTy->isUnsignedIntegerType() || !RHSTy->isUnsignedIntegerType())
288 return true;
289
290 // For unsigned multiplication the overflow check can be elided if either one
291 // of the unpromoted types are less than half the size of the promoted type.
292 unsigned PromotedSize = Ctx.getTypeSize(Op.E->getType());
293 return (2 * Ctx.getTypeSize(LHSTy)) < PromotedSize ||
294 (2 * Ctx.getTypeSize(RHSTy)) < PromotedSize;
295}
296
297class ScalarExprEmitter
298 : public StmtVisitor<ScalarExprEmitter, Value*> {
299 CodeGenFunction &CGF;
300 CGBuilderTy &Builder;
301 bool IgnoreResultAssign;
302 llvm::LLVMContext &VMContext;
303public:
304
305 ScalarExprEmitter(CodeGenFunction &cgf, bool ira=false)
306 : CGF(cgf), Builder(CGF.Builder), IgnoreResultAssign(ira),
307 VMContext(cgf.getLLVMContext()) {
308 }
309
310 //===--------------------------------------------------------------------===//
311 // Utilities
312 //===--------------------------------------------------------------------===//
313
314 bool TestAndClearIgnoreResultAssign() {
315 bool I = IgnoreResultAssign;
316 IgnoreResultAssign = false;
317 return I;
318 }
319
320 llvm::Type *ConvertType(QualType T) { return CGF.ConvertType(T); }
321 LValue EmitLValue(const Expr *E) { return CGF.EmitLValue(E); }
322 LValue EmitCheckedLValue(const Expr *E, CodeGenFunction::TypeCheckKind TCK) {
323 return CGF.EmitCheckedLValue(E, TCK);
324 }
325
326 void EmitBinOpCheck(
327 ArrayRef<std::pair<Value *, SanitizerKind::SanitizerOrdinal>> Checks,
328 const BinOpInfo &Info);
329
330 Value *EmitLoadOfLValue(LValue LV, SourceLocation Loc) {
331 return CGF.EmitLoadOfLValue(LV, Loc).getScalarVal();
332 }
333
334 void EmitLValueAlignmentAssumption(const Expr *E, Value *V) {
335 const AlignValueAttr *AVAttr = nullptr;
336 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) {
337 const ValueDecl *VD = DRE->getDecl();
338
339 if (VD->getType()->isReferenceType()) {
340 if (const auto *TTy =
341 VD->getType().getNonReferenceType()->getAs<TypedefType>())
342 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
343 } else {
344 // Assumptions for function parameters are emitted at the start of the
345 // function, so there is no need to repeat that here,
346 // unless the alignment-assumption sanitizer is enabled,
347 // then we prefer the assumption over alignment attribute
348 // on IR function param.
349 if (isa<ParmVarDecl>(VD) && !CGF.SanOpts.has(SanitizerKind::Alignment))
350 return;
351
352 AVAttr = VD->getAttr<AlignValueAttr>();
353 }
354 }
355
356 if (!AVAttr)
357 if (const auto *TTy = E->getType()->getAs<TypedefType>())
358 AVAttr = TTy->getDecl()->getAttr<AlignValueAttr>();
359
360 if (!AVAttr)
361 return;
362
363 Value *AlignmentValue = CGF.EmitScalarExpr(AVAttr->getAlignment());
364 llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(AlignmentValue);
365 CGF.emitAlignmentAssumption(V, E, AVAttr->getLocation(), AlignmentCI);
366 }
367
368 /// EmitLoadOfLValue - Given an expression with complex type that represents a
369 /// value l-value, this method emits the address of the l-value, then loads
370 /// and returns the result.
371 Value *EmitLoadOfLValue(const Expr *E) {
372 Value *V = EmitLoadOfLValue(EmitCheckedLValue(E, CodeGenFunction::TCK_Load),
373 E->getExprLoc());
374
375 EmitLValueAlignmentAssumption(E, V);
376 return V;
377 }
378
379 /// EmitConversionToBool - Convert the specified expression value to a
380 /// boolean (i1) truth value. This is equivalent to "Val != 0".
381 Value *EmitConversionToBool(Value *Src, QualType DstTy);
382
383 /// Emit a check that a conversion from a floating-point type does not
384 /// overflow.
385 void EmitFloatConversionCheck(Value *OrigSrc, QualType OrigSrcType,
386 Value *Src, QualType SrcType, QualType DstType,
387 llvm::Type *DstTy, SourceLocation Loc);
388
389 /// Known implicit conversion check kinds.
390 /// This is used for bitfield conversion checks as well.
391 /// Keep in sync with the enum of the same name in ubsan_handlers.h
392 enum ImplicitConversionCheckKind : unsigned char {
393 ICCK_IntegerTruncation = 0, // Legacy, was only used by clang 7.
394 ICCK_UnsignedIntegerTruncation = 1,
395 ICCK_SignedIntegerTruncation = 2,
396 ICCK_IntegerSignChange = 3,
397 ICCK_SignedIntegerTruncationOrSignChange = 4,
398 };
399
400 /// Emit a check that an [implicit] truncation of an integer does not
401 /// discard any bits. It is not UB, so we use the value after truncation.
402 void EmitIntegerTruncationCheck(Value *Src, QualType SrcType, Value *Dst,
403 QualType DstType, SourceLocation Loc,
404 bool OBTrapInvolved = false);
405
406 /// Emit a check that an [implicit] conversion of an integer does not change
407 /// the sign of the value. It is not UB, so we use the value after conversion.
408 /// NOTE: Src and Dst may be the exact same value! (point to the same thing)
409 void EmitIntegerSignChangeCheck(Value *Src, QualType SrcType, Value *Dst,
410 QualType DstType, SourceLocation Loc,
411 bool OBTrapInvolved = false);
412
413 /// Emit a conversion from the specified type to the specified destination
414 /// type, both of which are LLVM scalar types.
415 struct ScalarConversionOpts {
416 bool TreatBooleanAsSigned;
417 bool EmitImplicitIntegerTruncationChecks;
418 bool EmitImplicitIntegerSignChangeChecks;
419 /* Potential -fsanitize-undefined-ignore-overflow-pattern= */
420 bool PatternExcluded;
421
422 ScalarConversionOpts()
423 : TreatBooleanAsSigned(false),
424 EmitImplicitIntegerTruncationChecks(false),
425 EmitImplicitIntegerSignChangeChecks(false), PatternExcluded(false) {}
426
427 ScalarConversionOpts(clang::SanitizerSet SanOpts)
428 : TreatBooleanAsSigned(false),
429 EmitImplicitIntegerTruncationChecks(
430 SanOpts.hasOneOf(SanitizerKind::ImplicitIntegerTruncation)),
431 EmitImplicitIntegerSignChangeChecks(
432 SanOpts.has(SanitizerKind::ImplicitIntegerSignChange)),
433 PatternExcluded(false) {}
434 };
435 Value *EmitScalarCast(Value *Src, QualType SrcType, QualType DstType,
436 llvm::Type *SrcTy, llvm::Type *DstTy,
437 ScalarConversionOpts Opts);
438 Value *
439 EmitScalarConversion(Value *Src, QualType SrcTy, QualType DstTy,
440 SourceLocation Loc,
441 ScalarConversionOpts Opts = ScalarConversionOpts());
442
443 /// Convert between either a fixed point and other fixed point or fixed point
444 /// and an integer.
445 Value *EmitFixedPointConversion(Value *Src, QualType SrcTy, QualType DstTy,
446 SourceLocation Loc);
447
448 /// Emit a conversion from the specified complex type to the specified
449 /// destination type, where the destination type is an LLVM scalar type.
450 Value *EmitComplexToScalarConversion(CodeGenFunction::ComplexPairTy Src,
451 QualType SrcTy, QualType DstTy,
452 SourceLocation Loc);
453
454 /// EmitNullValue - Emit a value that corresponds to null for the given type.
455 Value *EmitNullValue(QualType Ty);
456
457 /// EmitFloatToBoolConversion - Perform an FP to boolean conversion.
458 Value *EmitFloatToBoolConversion(Value *V) {
459 // Compare against 0.0 for fp scalars.
460 llvm::Value *Zero = llvm::Constant::getNullValue(V->getType());
461 return Builder.CreateFCmpUNE(V, Zero, "tobool");
462 }
463
464 /// EmitPointerToBoolConversion - Perform a pointer to boolean conversion.
465 Value *EmitPointerToBoolConversion(Value *V, QualType QT) {
466 Value *Zero = CGF.CGM.getNullPointer(cast<llvm::PointerType>(V->getType()), QT);
467
468 return Builder.CreateICmpNE(V, Zero, "tobool");
469 }
470
471 Value *EmitIntToBoolConversion(Value *V) {
472 // Because of the type rules of C, we often end up computing a
473 // logical value, then zero extending it to int, then wanting it
474 // as a logical value again. Optimize this common case.
475 if (llvm::ZExtInst *ZI = dyn_cast<llvm::ZExtInst>(V)) {
476 if (ZI->getOperand(0)->getType() == Builder.getInt1Ty()) {
477 Value *Result = ZI->getOperand(0);
478 // If there aren't any more uses, zap the instruction to save space.
479 // Note that there can be more uses, for example if this
480 // is the result of an assignment.
481 if (ZI->use_empty())
482 ZI->eraseFromParent();
483 return Result;
484 }
485 }
486
487 return Builder.CreateIsNotNull(V, "tobool");
488 }
489
490 //===--------------------------------------------------------------------===//
491 // Visitor Methods
492 //===--------------------------------------------------------------------===//
493
494 Value *Visit(Expr *E) {
495 ApplyDebugLocation DL(CGF, E);
496 return StmtVisitor<ScalarExprEmitter, Value*>::Visit(E);
497 }
498
499 Value *VisitStmt(Stmt *S) {
500 S->dump(llvm::errs(), CGF.getContext());
501 llvm_unreachable("Stmt can't have complex result type!");
502 }
503 Value *VisitExpr(Expr *S);
504
505 Value *VisitConstantExpr(ConstantExpr *E) {
506 // A constant expression of type 'void' generates no code and produces no
507 // value.
508 if (E->getType()->isVoidType())
509 return nullptr;
510
511 if (Value *Result = ConstantEmitter(CGF).tryEmitConstantExpr(E)) {
512 if (E->isGLValue()) {
513 // This was already converted to an rvalue when it was constant
514 // evaluated.
515 if (E->hasAPValueResult() && !E->getAPValueResult().isLValue())
516 return Result;
517 return CGF.EmitLoadOfScalar(
520 /*Volatile*/ false, E->getType(), E->getExprLoc());
521 }
522 return Result;
523 }
524 return Visit(E->getSubExpr());
525 }
526 Value *VisitParenExpr(ParenExpr *PE) {
527 return Visit(PE->getSubExpr());
528 }
529 Value *VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E) {
530 return Visit(E->getReplacement());
531 }
532 Value *VisitGenericSelectionExpr(GenericSelectionExpr *GE) {
533 return Visit(GE->getResultExpr());
534 }
535 Value *VisitCoawaitExpr(CoawaitExpr *S) {
536 return CGF.EmitCoawaitExpr(*S).getScalarVal();
537 }
538 Value *VisitCoyieldExpr(CoyieldExpr *S) {
539 return CGF.EmitCoyieldExpr(*S).getScalarVal();
540 }
541 Value *VisitUnaryCoawait(const UnaryOperator *E) {
542 return Visit(E->getSubExpr());
543 }
544
545 // Leaves.
546 Value *VisitIntegerLiteral(const IntegerLiteral *E) {
547 return Builder.getInt(E->getValue());
548 }
549 Value *VisitFixedPointLiteral(const FixedPointLiteral *E) {
550 return Builder.getInt(E->getValue());
551 }
552 Value *VisitFloatingLiteral(const FloatingLiteral *E) {
553 return llvm::ConstantFP::get(VMContext, E->getValue());
554 }
555 Value *VisitCharacterLiteral(const CharacterLiteral *E) {
556 // Character literals are always stored in an unsigned (even for signed
557 // char), so allow implicit truncation here.
558 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue(),
559 /*IsSigned=*/false, /*ImplicitTrunc=*/true);
560 }
561 Value *VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
562 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
563 }
564 Value *VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
565 return llvm::ConstantInt::get(ConvertType(E->getType()), E->getValue());
566 }
567 Value *VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
568 if (E->getType()->isVoidType())
569 return nullptr;
570
571 return EmitNullValue(E->getType());
572 }
573 Value *VisitGNUNullExpr(const GNUNullExpr *E) {
574 return EmitNullValue(E->getType());
575 }
576 Value *VisitOffsetOfExpr(OffsetOfExpr *E);
577 Value *VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
578 Value *VisitAddrLabelExpr(const AddrLabelExpr *E) {
579 llvm::Value *V = CGF.GetAddrOfLabel(E->getLabel());
580 return Builder.CreateBitCast(V, ConvertType(E->getType()));
581 }
582
583 Value *VisitSizeOfPackExpr(SizeOfPackExpr *E) {
584 return llvm::ConstantInt::get(ConvertType(E->getType()),E->getPackLength());
585 }
586
587 Value *VisitPseudoObjectExpr(PseudoObjectExpr *E) {
588 return CGF.EmitPseudoObjectRValue(E).getScalarVal();
589 }
590
591 Value *VisitSYCLUniqueStableNameExpr(SYCLUniqueStableNameExpr *E);
592 Value *VisitEmbedExpr(EmbedExpr *E);
593
594 Value *VisitOpaqueValueExpr(OpaqueValueExpr *E) {
595 if (E->isGLValue())
596 return EmitLoadOfLValue(CGF.getOrCreateOpaqueLValueMapping(E),
597 E->getExprLoc());
598
599 // Otherwise, assume the mapping is the scalar directly.
601 }
602
603 Value *VisitOpenACCAsteriskSizeExpr(OpenACCAsteriskSizeExpr *E) {
604 llvm_unreachable("Codegen for this isn't defined/implemented");
605 }
606
607 // l-values.
608 Value *VisitDeclRefExpr(DeclRefExpr *E) {
609 if (CodeGenFunction::ConstantEmission Constant = CGF.tryEmitAsConstant(E))
610 return CGF.emitScalarConstant(Constant, E);
611 return EmitLoadOfLValue(E);
612 }
613
614 Value *VisitObjCSelectorExpr(ObjCSelectorExpr *E) {
615 return CGF.EmitObjCSelectorExpr(E);
616 }
617 Value *VisitObjCProtocolExpr(ObjCProtocolExpr *E) {
618 return CGF.EmitObjCProtocolExpr(E);
619 }
620 Value *VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
621 return EmitLoadOfLValue(E);
622 }
623 Value *VisitObjCMessageExpr(ObjCMessageExpr *E) {
624 if (E->getMethodDecl() &&
626 return EmitLoadOfLValue(E);
627 return CGF.EmitObjCMessageExpr(E).getScalarVal();
628 }
629
630 Value *VisitObjCIsaExpr(ObjCIsaExpr *E) {
631 LValue LV = CGF.EmitObjCIsaExpr(E);
633 return V;
634 }
635
636 Value *VisitObjCAvailabilityCheckExpr(ObjCAvailabilityCheckExpr *E) {
637 VersionTuple Version = E->getVersion();
638
639 // If we're checking for a platform older than our minimum deployment
640 // target, we can fold the check away.
641 if (Version <= CGF.CGM.getTarget().getPlatformMinVersion())
642 return llvm::ConstantInt::get(Builder.getInt1Ty(), 1);
643
644 return CGF.EmitBuiltinAvailable(Version);
645 }
646
647 Value *VisitArraySubscriptExpr(ArraySubscriptExpr *E);
648 Value *VisitMatrixSingleSubscriptExpr(MatrixSingleSubscriptExpr *E);
649 Value *VisitMatrixSubscriptExpr(MatrixSubscriptExpr *E);
650 Value *VisitShuffleVectorExpr(ShuffleVectorExpr *E);
651 Value *VisitConvertVectorExpr(ConvertVectorExpr *E);
652 Value *VisitMemberExpr(MemberExpr *E);
653 Value *VisitExtVectorElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
654 Value *VisitMatrixElementExpr(Expr *E) { return EmitLoadOfLValue(E); }
655 Value *VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
656 // Strictly speaking, we shouldn't be calling EmitLoadOfLValue, which
657 // transitively calls EmitCompoundLiteralLValue, here in C++ since compound
658 // literals aren't l-values in C++. We do so simply because that's the
659 // cleanest way to handle compound literals in C++.
660 // See the discussion here: https://reviews.llvm.org/D64464
661 return EmitLoadOfLValue(E);
662 }
663
664 Value *VisitInitListExpr(InitListExpr *E);
665
666 Value *VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) {
667 assert(CGF.getArrayInitIndex() &&
668 "ArrayInitIndexExpr not inside an ArrayInitLoopExpr?");
669 return CGF.getArrayInitIndex();
670 }
671
672 Value *VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
673 return EmitNullValue(E->getType());
674 }
675 Value *VisitExplicitCastExpr(ExplicitCastExpr *E) {
676 CGF.CGM.EmitExplicitCastExprType(E, &CGF);
677 return VisitCastExpr(E);
678 }
679 Value *VisitCastExpr(CastExpr *E);
680
681 Value *VisitCallExpr(const CallExpr *E) {
683 return EmitLoadOfLValue(E);
684
685 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 // Type wrapped by _Atomic.
4095 QualType AtomicValueTy = atomicTy->getValueType();
4096 // Type resulting from FP conversion / integer promotion of the compound
4097 // assignment operands.
4098 QualType ResultTy = E->getComputationResultType();
4099 // Do not try the atomicrmw op fast-path when the compound assignment may
4100 // involve FP conversions, as the correct semantics would require promoting
4101 // the loaded integer to double, performing FP arithmetics, and truncation
4102 // back as a single atomic operation. Integer promotion is still
4103 // semantically safe.
4104 bool CanEmitAtomicRMW =
4105 !AtomicValueTy->isBooleanType() && AtomicValueTy->isIntegerType() &&
4106 ResultTy->isIntegerType() &&
4107 !(AtomicValueTy->isUnsignedIntegerType() &&
4108 CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) &&
4109 CGF.getLangOpts().getSignedOverflowBehavior() !=
4110 LangOptions::SOB_Trapping;
4111 if (CanEmitAtomicRMW) {
4112 llvm::AtomicRMWInst::BinOp AtomicOp = llvm::AtomicRMWInst::BAD_BINOP;
4113 llvm::Instruction::BinaryOps Op;
4114 switch (OpInfo.Opcode) {
4115 // We don't have atomicrmw operands for *, %, /, <<, >>
4116 case BO_MulAssign: case BO_DivAssign:
4117 case BO_RemAssign:
4118 case BO_ShlAssign:
4119 case BO_ShrAssign:
4120 break;
4121 case BO_AddAssign:
4122 AtomicOp = llvm::AtomicRMWInst::Add;
4123 Op = llvm::Instruction::Add;
4124 break;
4125 case BO_SubAssign:
4126 AtomicOp = llvm::AtomicRMWInst::Sub;
4127 Op = llvm::Instruction::Sub;
4128 break;
4129 case BO_AndAssign:
4130 AtomicOp = llvm::AtomicRMWInst::And;
4131 Op = llvm::Instruction::And;
4132 break;
4133 case BO_XorAssign:
4134 AtomicOp = llvm::AtomicRMWInst::Xor;
4135 Op = llvm::Instruction::Xor;
4136 break;
4137 case BO_OrAssign:
4138 AtomicOp = llvm::AtomicRMWInst::Or;
4139 Op = llvm::Instruction::Or;
4140 break;
4141 default:
4142 llvm_unreachable("Invalid compound assignment type");
4143 }
4144 if (AtomicOp != llvm::AtomicRMWInst::BAD_BINOP) {
4145 llvm::Value *Amt = CGF.EmitToMemory(
4146 EmitScalarConversion(OpInfo.RHS, E->getRHS()->getType(), LHSTy,
4147 E->getExprLoc()),
4148 LHSTy);
4149
4150 llvm::AtomicRMWInst *OldVal =
4151 CGF.emitAtomicRMWInst(AtomicOp, LHSLV.getAddress(), Amt);
4152
4153 // Since operation is atomic, the result type is guaranteed to be the
4154 // same as the input in LLVM terms.
4155 Result = Builder.CreateBinOp(Op, OldVal, Amt);
4156 return LHSLV;
4157 }
4158 }
4159 // FIXME: For floating point types, we should be saving and restoring the
4160 // floating point environment in the loop.
4161 llvm::BasicBlock *startBB = Builder.GetInsertBlock();
4162 llvm::BasicBlock *opBB = CGF.createBasicBlock("atomic_op", CGF.CurFn);
4163 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
4164 OpInfo.LHS = CGF.EmitToMemory(OpInfo.LHS, AtomicValueTy);
4165 Builder.CreateBr(opBB);
4166 Builder.SetInsertPoint(opBB);
4167 atomicPHI = Builder.CreatePHI(OpInfo.LHS->getType(), 2);
4168 atomicPHI->addIncoming(OpInfo.LHS, startBB);
4169 OpInfo.LHS = atomicPHI;
4170 }
4171 else
4172 OpInfo.LHS = EmitLoadOfLValue(LHSLV, E->getExprLoc());
4173
4174 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, OpInfo.FPFeatures);
4175 SourceLocation Loc = E->getExprLoc();
4176 if (!PromotionTypeLHS.isNull())
4177 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy, PromotionTypeLHS,
4178 E->getExprLoc());
4179 else
4180 OpInfo.LHS = EmitScalarConversion(OpInfo.LHS, LHSTy,
4181 E->getComputationLHSType(), Loc);
4182
4183 // Expand the binary operator.
4184 Result = (this->*Func)(OpInfo);
4185
4186 // Convert the result back to the LHS type,
4187 // potentially with Implicit Conversion sanitizer check.
4188 // If LHSLV is a bitfield, use default ScalarConversionOpts
4189 // to avoid emit any implicit integer checks.
4190 Value *Previous = nullptr;
4191 if (LHSLV.isBitField()) {
4192 Previous = Result;
4193 Result = EmitScalarConversion(Result, PromotionTypeCR, LHSTy, Loc);
4194 } else if (const auto *atomicTy = LHSTy->getAs<AtomicType>()) {
4195 Result =
4196 EmitScalarConversion(Result, PromotionTypeCR, atomicTy->getValueType(),
4197 Loc, ScalarConversionOpts(CGF.SanOpts));
4198 } else {
4199 Result = EmitScalarConversion(Result, PromotionTypeCR, LHSTy, Loc,
4200 ScalarConversionOpts(CGF.SanOpts));
4201 }
4202
4203 if (atomicPHI) {
4204 llvm::BasicBlock *curBlock = Builder.GetInsertBlock();
4205 llvm::BasicBlock *contBB = CGF.createBasicBlock("atomic_cont", CGF.CurFn);
4206 auto Pair = CGF.EmitAtomicCompareExchange(
4207 LHSLV, RValue::get(atomicPHI), RValue::get(Result), E->getExprLoc());
4208 llvm::Value *old = CGF.EmitToMemory(Pair.first.getScalarVal(), LHSTy);
4209 llvm::Value *success = Pair.second;
4210 atomicPHI->addIncoming(old, curBlock);
4211 Builder.CreateCondBr(success, contBB, atomicPHI->getParent());
4212 Builder.SetInsertPoint(contBB);
4213 return LHSLV;
4214 }
4215
4216 // Store the result value into the LHS lvalue. Bit-fields are handled
4217 // specially because the result is altered by the store, i.e., [C99 6.5.16p1]
4218 // 'An assignment expression has the value of the left operand after the
4219 // assignment...'.
4220 if (LHSLV.isBitField()) {
4221 Value *Src = Previous ? Previous : Result;
4222 QualType SrcType = E->getRHS()->getType();
4223 QualType DstType = E->getLHS()->getType();
4225 CGF.EmitBitfieldConversionCheck(Src, SrcType, Result, DstType,
4226 LHSLV.getBitFieldInfo(), E->getExprLoc());
4227 } else
4229
4230 if (CGF.getLangOpts().OpenMP)
4232 E->getLHS());
4233 return LHSLV;
4234}
4235
4236Value *ScalarExprEmitter::EmitCompoundAssign(const CompoundAssignOperator *E,
4237 Value *(ScalarExprEmitter::*Func)(const BinOpInfo &)) {
4238 bool Ignore = TestAndClearIgnoreResultAssign();
4239 Value *RHS = nullptr;
4240 LValue LHS = EmitCompoundAssignLValue(E, Func, RHS);
4241
4242 // If the result is clearly ignored, return now.
4243 if (Ignore)
4244 return nullptr;
4245
4246 // The result of an assignment in C is the assigned r-value.
4247 if (!CGF.getLangOpts().CPlusPlus)
4248 return RHS;
4249
4250 // If the lvalue is non-volatile, return the computed value of the assignment.
4251 if (!LHS.isVolatileQualified())
4252 return RHS;
4253
4254 // Otherwise, reload the value.
4255 return EmitLoadOfLValue(LHS, E->getExprLoc());
4256}
4257
4258void ScalarExprEmitter::EmitUndefinedBehaviorIntegerDivAndRemCheck(
4259 const BinOpInfo &Ops, llvm::Value *Zero, bool isDiv) {
4260 SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>, 2>
4261 Checks;
4262
4263 if (CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero)) {
4264 Checks.push_back(std::make_pair(Builder.CreateICmpNE(Ops.RHS, Zero),
4265 SanitizerKind::SO_IntegerDivideByZero));
4266 }
4267
4268 const auto *BO = cast<BinaryOperator>(Ops.E);
4269 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow) &&
4270 Ops.Ty->hasSignedIntegerRepresentation() &&
4271 !IsWidenedIntegerOp(CGF.getContext(), BO->getLHS()) &&
4272 Ops.mayHaveIntegerOverflow() &&
4274 SanitizerKind::SignedIntegerOverflow, Ops.Ty)) {
4275 llvm::IntegerType *Ty = cast<llvm::IntegerType>(Zero->getType());
4276
4277 llvm::Value *IntMin =
4278 Builder.getInt(llvm::APInt::getSignedMinValue(Ty->getBitWidth()));
4279 llvm::Value *NegOne = llvm::Constant::getAllOnesValue(Ty);
4280
4281 llvm::Value *LHSCmp = Builder.CreateICmpNE(Ops.LHS, IntMin);
4282 llvm::Value *RHSCmp = Builder.CreateICmpNE(Ops.RHS, NegOne);
4283 llvm::Value *NotOverflow = Builder.CreateOr(LHSCmp, RHSCmp, "or");
4284 Checks.push_back(
4285 std::make_pair(NotOverflow, SanitizerKind::SO_SignedIntegerOverflow));
4286 }
4287
4288 if (Checks.size() > 0)
4289 EmitBinOpCheck(Checks, Ops);
4290}
4291
4292Value *ScalarExprEmitter::EmitDiv(const BinOpInfo &Ops) {
4293 {
4294 SanitizerDebugLocation SanScope(&CGF,
4295 {SanitizerKind::SO_IntegerDivideByZero,
4296 SanitizerKind::SO_SignedIntegerOverflow,
4297 SanitizerKind::SO_FloatDivideByZero},
4298 SanitizerHandler::DivremOverflow);
4299 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
4300 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
4301 Ops.Ty->isIntegerType() &&
4302 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
4303 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
4304 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, true);
4305 } else if (CGF.SanOpts.has(SanitizerKind::FloatDivideByZero) &&
4306 Ops.Ty->isRealFloatingType() &&
4307 Ops.mayHaveFloatDivisionByZero()) {
4308 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
4309 llvm::Value *NonZero = Builder.CreateFCmpUNE(Ops.RHS, Zero);
4310 EmitBinOpCheck(
4311 std::make_pair(NonZero, SanitizerKind::SO_FloatDivideByZero), Ops);
4312 }
4313 }
4314
4315 if (Ops.Ty->isConstantMatrixType()) {
4316 llvm::MatrixBuilder MB(Builder);
4317 // We need to check the types of the operands of the operator to get the
4318 // correct matrix dimensions.
4319 auto *BO = cast<BinaryOperator>(Ops.E);
4320 (void)BO;
4321 assert(
4323 "first operand must be a matrix");
4324 assert(BO->getRHS()->getType().getCanonicalType()->isArithmeticType() &&
4325 "second operand must be an arithmetic type");
4326 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
4327 return MB.CreateScalarDiv(Ops.LHS, Ops.RHS,
4328 Ops.Ty->hasUnsignedIntegerRepresentation());
4329 }
4330
4331 if (Ops.LHS->getType()->isFPOrFPVectorTy()) {
4332 llvm::Value *Val;
4333 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, Ops.FPFeatures);
4334 Val = Builder.CreateFDiv(Ops.LHS, Ops.RHS, "div");
4335 CGF.SetDivFPAccuracy(Val);
4336 return Val;
4337 }
4338 else if (Ops.isFixedPointOp())
4339 return EmitFixedPointBinOp(Ops);
4340 else if (Ops.Ty->hasUnsignedIntegerRepresentation())
4341 return Builder.CreateUDiv(Ops.LHS, Ops.RHS, "div");
4342 else
4343 return Builder.CreateSDiv(Ops.LHS, Ops.RHS, "div");
4344}
4345
4346Value *ScalarExprEmitter::EmitRem(const BinOpInfo &Ops) {
4347 // Rem in C can't be a floating point type: C99 6.5.5p2.
4348 if ((CGF.SanOpts.has(SanitizerKind::IntegerDivideByZero) ||
4349 CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) &&
4350 Ops.Ty->isIntegerType() &&
4351 (Ops.mayHaveIntegerDivisionByZero() || Ops.mayHaveIntegerOverflow())) {
4352 SanitizerDebugLocation SanScope(&CGF,
4353 {SanitizerKind::SO_IntegerDivideByZero,
4354 SanitizerKind::SO_SignedIntegerOverflow},
4355 SanitizerHandler::DivremOverflow);
4356 llvm::Value *Zero = llvm::Constant::getNullValue(ConvertType(Ops.Ty));
4357 EmitUndefinedBehaviorIntegerDivAndRemCheck(Ops, Zero, false);
4358 }
4359
4360 if (Ops.Ty->hasUnsignedIntegerRepresentation())
4361 return Builder.CreateURem(Ops.LHS, Ops.RHS, "rem");
4362
4363 if (CGF.getLangOpts().HLSL && Ops.Ty->hasFloatingRepresentation())
4364 return Builder.CreateFRem(Ops.LHS, Ops.RHS, "rem");
4365
4366 return Builder.CreateSRem(Ops.LHS, Ops.RHS, "rem");
4367}
4368
4369Value *ScalarExprEmitter::EmitOverflowCheckedBinOp(const BinOpInfo &Ops) {
4370 unsigned IID;
4371 unsigned OpID = 0;
4372 SanitizerHandler OverflowKind;
4373
4374 bool isSigned = Ops.Ty->isSignedIntegerOrEnumerationType();
4375 switch (Ops.Opcode) {
4376 case BO_Add:
4377 case BO_AddAssign:
4378 OpID = 1;
4379 IID = isSigned ? llvm::Intrinsic::sadd_with_overflow :
4380 llvm::Intrinsic::uadd_with_overflow;
4381 OverflowKind = SanitizerHandler::AddOverflow;
4382 break;
4383 case BO_Sub:
4384 case BO_SubAssign:
4385 OpID = 2;
4386 IID = isSigned ? llvm::Intrinsic::ssub_with_overflow :
4387 llvm::Intrinsic::usub_with_overflow;
4388 OverflowKind = SanitizerHandler::SubOverflow;
4389 break;
4390 case BO_Mul:
4391 case BO_MulAssign:
4392 OpID = 3;
4393 IID = isSigned ? llvm::Intrinsic::smul_with_overflow :
4394 llvm::Intrinsic::umul_with_overflow;
4395 OverflowKind = SanitizerHandler::MulOverflow;
4396 break;
4397 default:
4398 llvm_unreachable("Unsupported operation for overflow detection");
4399 }
4400 OpID <<= 1;
4401 if (isSigned)
4402 OpID |= 1;
4403
4404 SanitizerDebugLocation SanScope(&CGF,
4405 {SanitizerKind::SO_SignedIntegerOverflow,
4406 SanitizerKind::SO_UnsignedIntegerOverflow},
4407 OverflowKind);
4408 llvm::Type *opTy = CGF.CGM.getTypes().ConvertType(Ops.Ty);
4409
4410 llvm::Function *intrinsic = CGF.CGM.getIntrinsic(IID, opTy);
4411
4412 Value *resultAndOverflow = Builder.CreateCall(intrinsic, {Ops.LHS, Ops.RHS});
4413 Value *result = Builder.CreateExtractValue(resultAndOverflow, 0);
4414 Value *overflow = Builder.CreateExtractValue(resultAndOverflow, 1);
4415
4416 // Handle overflow with llvm.trap if no custom handler has been specified.
4417 const std::string *handlerName =
4419 if (handlerName->empty()) {
4420 // If no -ftrapv handler has been specified, try to use sanitizer runtimes
4421 // if available otherwise just emit a trap. It is possible for unsigned
4422 // arithmetic to result in a trap due to the OverflowBehaviorType attribute
4423 // which describes overflow behavior on a per-type basis.
4424 if (isSigned) {
4425 if (CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)) {
4426 llvm::Value *NotOf = Builder.CreateNot(overflow);
4427 EmitBinOpCheck(
4428 std::make_pair(NotOf, SanitizerKind::SO_SignedIntegerOverflow),
4429 Ops);
4430 } else
4431 CGF.EmitTrapCheck(Builder.CreateNot(overflow), OverflowKind);
4432 return result;
4433 }
4434 if (CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow)) {
4435 llvm::Value *NotOf = Builder.CreateNot(overflow);
4436 EmitBinOpCheck(
4437 std::make_pair(NotOf, SanitizerKind::SO_UnsignedIntegerOverflow),
4438 Ops);
4439 } else
4440 CGF.EmitTrapCheck(Builder.CreateNot(overflow), OverflowKind);
4441 return result;
4442 }
4443
4444 // Branch in case of overflow.
4445 llvm::BasicBlock *initialBB = Builder.GetInsertBlock();
4446 llvm::BasicBlock *continueBB =
4447 CGF.createBasicBlock("nooverflow", CGF.CurFn, initialBB->getNextNode());
4448 llvm::BasicBlock *overflowBB = CGF.createBasicBlock("overflow", CGF.CurFn);
4449
4450 Builder.CreateCondBr(overflow, overflowBB, continueBB);
4451
4452 // If an overflow handler is set, then we want to call it and then use its
4453 // result, if it returns.
4454 Builder.SetInsertPoint(overflowBB);
4455
4456 // Get the overflow handler.
4457 llvm::Type *Int8Ty = CGF.Int8Ty;
4458 llvm::Type *argTypes[] = { CGF.Int64Ty, CGF.Int64Ty, Int8Ty, Int8Ty };
4459 llvm::FunctionType *handlerTy =
4460 llvm::FunctionType::get(CGF.Int64Ty, argTypes, true);
4461 llvm::FunctionCallee handler =
4462 CGF.CGM.CreateRuntimeFunction(handlerTy, *handlerName);
4463
4464 // Sign extend the args to 64-bit, so that we can use the same handler for
4465 // all types of overflow.
4466 llvm::Value *lhs = Builder.CreateSExt(Ops.LHS, CGF.Int64Ty);
4467 llvm::Value *rhs = Builder.CreateSExt(Ops.RHS, CGF.Int64Ty);
4468
4469 // Call the handler with the two arguments, the operation, and the size of
4470 // the result.
4471 llvm::Value *handlerArgs[] = {
4472 lhs,
4473 rhs,
4474 Builder.getInt8(OpID),
4475 Builder.getInt8(cast<llvm::IntegerType>(opTy)->getBitWidth())
4476 };
4477 llvm::Value *handlerResult =
4478 CGF.EmitNounwindRuntimeCall(handler, handlerArgs);
4479
4480 // Truncate the result back to the desired size.
4481 handlerResult = Builder.CreateTrunc(handlerResult, opTy);
4482 Builder.CreateBr(continueBB);
4483
4484 Builder.SetInsertPoint(continueBB);
4485 llvm::PHINode *phi = Builder.CreatePHI(opTy, 2);
4486 phi->addIncoming(result, initialBB);
4487 phi->addIncoming(handlerResult, overflowBB);
4488
4489 return phi;
4490}
4491
4492/// BO_Add/BO_Sub are handled by EmitPointerWithAlignment to preserve alignment
4493/// information.
4494/// This function is used for BO_AddAssign/BO_SubAssign.
4495static Value *emitPointerArithmetic(CodeGenFunction &CGF, const BinOpInfo &op,
4496 bool isSubtraction) {
4497 // Must have binary (not unary) expr here. Unary pointer
4498 // increment/decrement doesn't use this path.
4500
4501 Value *pointer = op.LHS;
4502 Expr *pointerOperand = expr->getLHS();
4503 Value *index = op.RHS;
4504 Expr *indexOperand = expr->getRHS();
4505
4506 // In a subtraction, the LHS is always the pointer.
4507 if (!isSubtraction && !pointer->getType()->isPointerTy()) {
4508 std::swap(pointer, index);
4509 std::swap(pointerOperand, indexOperand);
4510 }
4511
4512 return CGF.EmitPointerArithmetic(expr, pointerOperand, pointer, indexOperand,
4513 index, isSubtraction);
4514}
4515
4516/// Emit pointer + index arithmetic.
4518 const BinaryOperator *BO, Expr *pointerOperand, llvm::Value *pointer,
4519 Expr *indexOperand, llvm::Value *index, bool isSubtraction) {
4520 bool isSigned = indexOperand->getType()->isSignedIntegerOrEnumerationType();
4521
4522 unsigned width = cast<llvm::IntegerType>(index->getType())->getBitWidth();
4523 auto &DL = CGM.getDataLayout();
4524 auto *PtrTy = cast<llvm::PointerType>(pointer->getType());
4525
4526 // Some versions of glibc and gcc use idioms (particularly in their malloc
4527 // routines) that add a pointer-sized integer (known to be a pointer value)
4528 // to a null pointer in order to cast the value back to an integer or as
4529 // part of a pointer alignment algorithm. This is undefined behavior, but
4530 // we'd like to be able to compile programs that use it.
4531 //
4532 // Normally, we'd generate a GEP with a null-pointer base here in response
4533 // to that code, but it's also UB to dereference a pointer created that
4534 // way. Instead (as an acknowledged hack to tolerate the idiom) we will
4535 // generate a direct cast of the integer value to a pointer.
4536 //
4537 // The idiom (p = nullptr + N) is not met if any of the following are true:
4538 //
4539 // The operation is subtraction.
4540 // The index is not pointer-sized.
4541 // The pointer type is not byte-sized.
4542 //
4543 // Note that we do not suppress the pointer overflow check in this case.
4545 getContext(), BO->getOpcode(), pointerOperand, indexOperand)) {
4546 llvm::Value *Ptr = Builder.CreateIntToPtr(index, pointer->getType());
4547 if (getLangOpts().PointerOverflowDefined ||
4548 !SanOpts.has(SanitizerKind::PointerOverflow) ||
4549 NullPointerIsDefined(Builder.GetInsertBlock()->getParent(),
4550 PtrTy->getPointerAddressSpace()))
4551 return Ptr;
4552 // The inbounds GEP of null is valid iff the index is zero.
4553 auto CheckOrdinal = SanitizerKind::SO_PointerOverflow;
4554 auto CheckHandler = SanitizerHandler::PointerOverflow;
4555 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
4556 llvm::Value *IsZeroIndex = Builder.CreateIsNull(index);
4557 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(BO->getExprLoc())};
4558 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
4559 llvm::Value *IntPtr = llvm::Constant::getNullValue(IntPtrTy);
4560 llvm::Value *ComputedGEP = Builder.CreateZExtOrTrunc(index, IntPtrTy);
4561 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
4562 EmitCheck({{IsZeroIndex, CheckOrdinal}}, CheckHandler, StaticArgs,
4563 DynamicArgs);
4564 return Ptr;
4565 }
4566
4567 if (width != DL.getIndexTypeSizeInBits(PtrTy)) {
4568 // Zero-extend or sign-extend the pointer value according to
4569 // whether the index is signed or not.
4570 index = Builder.CreateIntCast(index, DL.getIndexType(PtrTy), isSigned,
4571 "idx.ext");
4572 }
4573
4574 // If this is subtraction, negate the index.
4575 if (isSubtraction)
4576 index = Builder.CreateNeg(index, "idx.neg");
4577
4578 if (SanOpts.has(SanitizerKind::ArrayBounds))
4579 EmitBoundsCheck(BO, pointerOperand, index, indexOperand->getType(),
4580 /*Accessed*/ false);
4581
4582 const PointerType *pointerType =
4583 pointerOperand->getType()->getAs<PointerType>();
4584 if (!pointerType) {
4585 QualType objectType = pointerOperand->getType()
4587 ->getPointeeType();
4588 llvm::Value *objectSize =
4589 CGM.getSize(getContext().getTypeSizeInChars(objectType));
4590
4591 index = Builder.CreateMul(index, objectSize);
4592
4593 llvm::Value *result = Builder.CreateGEP(Int8Ty, pointer, index, "add.ptr");
4594 return Builder.CreateBitCast(result, pointer->getType());
4595 }
4596
4597 QualType elementType = pointerType->getPointeeType();
4598 if (const VariableArrayType *vla =
4599 getContext().getAsVariableArrayType(elementType)) {
4600 // The element count here is the total number of non-VLA elements.
4601 llvm::Value *numElements = getVLASize(vla).NumElts;
4602
4603 // Effectively, the multiply by the VLA size is part of the GEP.
4604 // GEP indexes are signed, and scaling an index isn't permitted to
4605 // signed-overflow, so we use the same semantics for our explicit
4606 // multiply. We suppress this if overflow is not undefined behavior.
4607 llvm::Type *elemTy = ConvertTypeForMem(vla->getElementType());
4608 if (getLangOpts().PointerOverflowDefined) {
4609 index = Builder.CreateMul(index, numElements, "vla.index");
4610 pointer = Builder.CreateGEP(elemTy, pointer, index, "add.ptr");
4611 } else {
4612 index = Builder.CreateNSWMul(index, numElements, "vla.index");
4613 pointer =
4614 EmitCheckedInBoundsGEP(elemTy, pointer, index, isSigned,
4615 isSubtraction, BO->getExprLoc(), "add.ptr");
4616 }
4617 return pointer;
4618 }
4619
4620 // Explicitly handle GNU void* and function pointer arithmetic extensions. The
4621 // GNU void* casts amount to no-ops since our void* type is i8*, but this is
4622 // future proof.
4623 llvm::Type *elemTy;
4624 if (elementType->isVoidType() || elementType->isFunctionType())
4625 elemTy = Int8Ty;
4626 else
4627 elemTy = ConvertTypeForMem(elementType);
4628
4629 if (getLangOpts().PointerOverflowDefined)
4630 return Builder.CreateGEP(elemTy, pointer, index, "add.ptr");
4631
4632 return EmitCheckedInBoundsGEP(elemTy, pointer, index, isSigned, isSubtraction,
4633 BO->getExprLoc(), "add.ptr");
4634}
4635
4636// Construct an fmuladd intrinsic to represent a fused mul-add of MulOp and
4637// Addend. Use negMul and negAdd to negate the first operand of the Mul or
4638// the add operand respectively. This allows fmuladd to represent a*b-c, or
4639// c-a*b. Patterns in LLVM should catch the negated forms and translate them to
4640// efficient operations.
4641static Value* buildFMulAdd(llvm::Instruction *MulOp, Value *Addend,
4642 const CodeGenFunction &CGF, CGBuilderTy &Builder,
4643 bool negMul, bool negAdd) {
4644 Value *MulOp0 = MulOp->getOperand(0);
4645 Value *MulOp1 = MulOp->getOperand(1);
4646 if (negMul)
4647 MulOp0 = Builder.CreateFNeg(MulOp0, "neg");
4648 if (negAdd)
4649 Addend = Builder.CreateFNeg(Addend, "neg");
4650
4651 Value *FMulAdd = nullptr;
4652 if (Builder.getIsFPConstrained()) {
4653 assert(isa<llvm::ConstrainedFPIntrinsic>(MulOp) &&
4654 "Only constrained operation should be created when Builder is in FP "
4655 "constrained mode");
4656 FMulAdd = Builder.CreateConstrainedFPCall(
4657 CGF.CGM.getIntrinsic(llvm::Intrinsic::experimental_constrained_fmuladd,
4658 Addend->getType()),
4659 {MulOp0, MulOp1, Addend});
4660 } else {
4661 FMulAdd = Builder.CreateCall(
4662 CGF.CGM.getIntrinsic(llvm::Intrinsic::fmuladd, Addend->getType()),
4663 {MulOp0, MulOp1, Addend});
4664 }
4665 MulOp->eraseFromParent();
4666
4667 return FMulAdd;
4668}
4669
4670// Check whether it would be legal to emit an fmuladd intrinsic call to
4671// represent op and if so, build the fmuladd.
4672//
4673// Checks that (a) the operation is fusable, and (b) -ffp-contract=on.
4674// Does NOT check the type of the operation - it's assumed that this function
4675// will be called from contexts where it's known that the type is contractable.
4676static Value* tryEmitFMulAdd(const BinOpInfo &op,
4677 const CodeGenFunction &CGF, CGBuilderTy &Builder,
4678 bool isSub=false) {
4679
4680 assert((op.Opcode == BO_Add || op.Opcode == BO_AddAssign ||
4681 op.Opcode == BO_Sub || op.Opcode == BO_SubAssign) &&
4682 "Only fadd/fsub can be the root of an fmuladd.");
4683
4684 // Check whether this op is marked as fusable.
4685 if (!op.FPFeatures.allowFPContractWithinStatement())
4686 return nullptr;
4687
4688 Value *LHS = op.LHS;
4689 Value *RHS = op.RHS;
4690
4691 // Peek through fneg to look for fmul. Make sure fneg has no users, and that
4692 // it is the only use of its operand.
4693 bool NegLHS = false;
4694 if (auto *LHSUnOp = dyn_cast<llvm::UnaryOperator>(LHS)) {
4695 if (LHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4696 LHSUnOp->use_empty() && LHSUnOp->getOperand(0)->hasOneUse()) {
4697 LHS = LHSUnOp->getOperand(0);
4698 NegLHS = true;
4699 }
4700 }
4701
4702 bool NegRHS = false;
4703 if (auto *RHSUnOp = dyn_cast<llvm::UnaryOperator>(RHS)) {
4704 if (RHSUnOp->getOpcode() == llvm::Instruction::FNeg &&
4705 RHSUnOp->use_empty() && RHSUnOp->getOperand(0)->hasOneUse()) {
4706 RHS = RHSUnOp->getOperand(0);
4707 NegRHS = true;
4708 }
4709 }
4710
4711 // We have a potentially fusable op. Look for a mul on one of the operands.
4712 // Also, make sure that the mul result isn't used directly. In that case,
4713 // there's no point creating a muladd operation.
4714 if (auto *LHSBinOp = dyn_cast<llvm::BinaryOperator>(LHS)) {
4715 if (LHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4716 (LHSBinOp->use_empty() || NegLHS)) {
4717 // If we looked through fneg, erase it.
4718 if (NegLHS)
4719 cast<llvm::Instruction>(op.LHS)->eraseFromParent();
4720 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, NegLHS, isSub);
4721 }
4722 }
4723 if (auto *RHSBinOp = dyn_cast<llvm::BinaryOperator>(RHS)) {
4724 if (RHSBinOp->getOpcode() == llvm::Instruction::FMul &&
4725 (RHSBinOp->use_empty() || NegRHS)) {
4726 // If we looked through fneg, erase it.
4727 if (NegRHS)
4728 cast<llvm::Instruction>(op.RHS)->eraseFromParent();
4729 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub ^ NegRHS, false);
4730 }
4731 }
4732
4733 if (auto *LHSBinOp = dyn_cast<llvm::CallBase>(LHS)) {
4734 if (LHSBinOp->getIntrinsicID() ==
4735 llvm::Intrinsic::experimental_constrained_fmul &&
4736 (LHSBinOp->use_empty() || NegLHS)) {
4737 // If we looked through fneg, erase it.
4738 if (NegLHS)
4739 cast<llvm::Instruction>(op.LHS)->eraseFromParent();
4740 return buildFMulAdd(LHSBinOp, op.RHS, CGF, Builder, NegLHS, isSub);
4741 }
4742 }
4743 if (auto *RHSBinOp = dyn_cast<llvm::CallBase>(RHS)) {
4744 if (RHSBinOp->getIntrinsicID() ==
4745 llvm::Intrinsic::experimental_constrained_fmul &&
4746 (RHSBinOp->use_empty() || NegRHS)) {
4747 // If we looked through fneg, erase it.
4748 if (NegRHS)
4749 cast<llvm::Instruction>(op.RHS)->eraseFromParent();
4750 return buildFMulAdd(RHSBinOp, op.LHS, CGF, Builder, isSub ^ NegRHS, false);
4751 }
4752 }
4753
4754 return nullptr;
4755}
4756
4757Value *ScalarExprEmitter::EmitAdd(const BinOpInfo &op) {
4758 if (op.LHS->getType()->isPointerTy() ||
4759 op.RHS->getType()->isPointerTy())
4761
4762 if (op.Ty->isSignedIntegerOrEnumerationType() ||
4763 op.Ty->isUnsignedIntegerType()) {
4764 const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType();
4765 const bool hasSan =
4766 isSigned ? CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)
4767 : CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow);
4768 switch (getOverflowBehaviorConsideringType(CGF, op.Ty)) {
4769 case LangOptions::OB_Wrap:
4770 return Builder.CreateAdd(op.LHS, op.RHS, "add");
4771 case LangOptions::OB_SignedAndDefined:
4772 if (!hasSan)
4773 return Builder.CreateAdd(op.LHS, op.RHS, "add");
4774 [[fallthrough]];
4775 case LangOptions::OB_Unset:
4776 if (!hasSan)
4777 return isSigned ? Builder.CreateNSWAdd(op.LHS, op.RHS, "add")
4778 : Builder.CreateAdd(op.LHS, op.RHS, "add");
4779 [[fallthrough]];
4780 case LangOptions::OB_Trap:
4781 if (CanElideOverflowCheck(CGF.getContext(), op))
4782 return isSigned ? Builder.CreateNSWAdd(op.LHS, op.RHS, "add")
4783 : Builder.CreateAdd(op.LHS, op.RHS, "add");
4784 return EmitOverflowCheckedBinOp(op);
4785 }
4786 }
4787
4788 // For vector and matrix adds, try to fold into a fmuladd.
4789 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4790 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4791 // Try to form an fmuladd.
4792 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder))
4793 return FMulAdd;
4794 }
4795
4796 if (op.Ty->isConstantMatrixType()) {
4797 llvm::MatrixBuilder MB(Builder);
4798 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4799 return MB.CreateAdd(op.LHS, op.RHS);
4800 }
4801
4802 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4803 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4804 return Builder.CreateFAdd(op.LHS, op.RHS, "add");
4805 }
4806
4807 if (op.isFixedPointOp())
4808 return EmitFixedPointBinOp(op);
4809
4810 return Builder.CreateAdd(op.LHS, op.RHS, "add");
4811}
4812
4813/// The resulting value must be calculated with exact precision, so the operands
4814/// may not be the same type.
4815Value *ScalarExprEmitter::EmitFixedPointBinOp(const BinOpInfo &op) {
4816 using llvm::APSInt;
4817 using llvm::ConstantInt;
4818
4819 // This is either a binary operation where at least one of the operands is
4820 // a fixed-point type, or a unary operation where the operand is a fixed-point
4821 // type. The result type of a binary operation is determined by
4822 // Sema::handleFixedPointConversions().
4823 QualType ResultTy = op.Ty;
4824 QualType LHSTy, RHSTy;
4825 if (const auto *BinOp = dyn_cast<BinaryOperator>(op.E)) {
4826 RHSTy = BinOp->getRHS()->getType();
4827 if (const auto *CAO = dyn_cast<CompoundAssignOperator>(BinOp)) {
4828 // For compound assignment, the effective type of the LHS at this point
4829 // is the computation LHS type, not the actual LHS type, and the final
4830 // result type is not the type of the expression but rather the
4831 // computation result type.
4832 LHSTy = CAO->getComputationLHSType();
4833 ResultTy = CAO->getComputationResultType();
4834 } else
4835 LHSTy = BinOp->getLHS()->getType();
4836 } else if (const auto *UnOp = dyn_cast<UnaryOperator>(op.E)) {
4837 LHSTy = UnOp->getSubExpr()->getType();
4838 RHSTy = UnOp->getSubExpr()->getType();
4839 }
4840 ASTContext &Ctx = CGF.getContext();
4841 Value *LHS = op.LHS;
4842 Value *RHS = op.RHS;
4843
4844 auto LHSFixedSema = Ctx.getFixedPointSemantics(LHSTy);
4845 auto RHSFixedSema = Ctx.getFixedPointSemantics(RHSTy);
4846 auto ResultFixedSema = Ctx.getFixedPointSemantics(ResultTy);
4847 auto CommonFixedSema = LHSFixedSema.getCommonSemantics(RHSFixedSema);
4848
4849 // Perform the actual operation.
4850 Value *Result;
4851 llvm::FixedPointBuilder<CGBuilderTy> FPBuilder(Builder);
4852 switch (op.Opcode) {
4853 case BO_AddAssign:
4854 case BO_Add:
4855 Result = FPBuilder.CreateAdd(LHS, LHSFixedSema, RHS, RHSFixedSema);
4856 break;
4857 case BO_SubAssign:
4858 case BO_Sub:
4859 Result = FPBuilder.CreateSub(LHS, LHSFixedSema, RHS, RHSFixedSema);
4860 break;
4861 case BO_MulAssign:
4862 case BO_Mul:
4863 Result = FPBuilder.CreateMul(LHS, LHSFixedSema, RHS, RHSFixedSema);
4864 break;
4865 case BO_DivAssign:
4866 case BO_Div:
4867 Result = FPBuilder.CreateDiv(LHS, LHSFixedSema, RHS, RHSFixedSema);
4868 break;
4869 case BO_ShlAssign:
4870 case BO_Shl:
4871 Result = FPBuilder.CreateShl(LHS, LHSFixedSema, RHS);
4872 break;
4873 case BO_ShrAssign:
4874 case BO_Shr:
4875 Result = FPBuilder.CreateShr(LHS, LHSFixedSema, RHS);
4876 break;
4877 case BO_LT:
4878 return FPBuilder.CreateLT(LHS, LHSFixedSema, RHS, RHSFixedSema);
4879 case BO_GT:
4880 return FPBuilder.CreateGT(LHS, LHSFixedSema, RHS, RHSFixedSema);
4881 case BO_LE:
4882 return FPBuilder.CreateLE(LHS, LHSFixedSema, RHS, RHSFixedSema);
4883 case BO_GE:
4884 return FPBuilder.CreateGE(LHS, LHSFixedSema, RHS, RHSFixedSema);
4885 case BO_EQ:
4886 // For equality operations, we assume any padding bits on unsigned types are
4887 // zero'd out. They could be overwritten through non-saturating operations
4888 // that cause overflow, but this leads to undefined behavior.
4889 return FPBuilder.CreateEQ(LHS, LHSFixedSema, RHS, RHSFixedSema);
4890 case BO_NE:
4891 return FPBuilder.CreateNE(LHS, LHSFixedSema, RHS, RHSFixedSema);
4892 case BO_Cmp:
4893 case BO_LAnd:
4894 case BO_LOr:
4895 llvm_unreachable("Found unimplemented fixed point binary operation");
4896 case BO_PtrMemD:
4897 case BO_PtrMemI:
4898 case BO_Rem:
4899 case BO_Xor:
4900 case BO_And:
4901 case BO_Or:
4902 case BO_Assign:
4903 case BO_RemAssign:
4904 case BO_AndAssign:
4905 case BO_XorAssign:
4906 case BO_OrAssign:
4907 case BO_Comma:
4908 llvm_unreachable("Found unsupported binary operation for fixed point types.");
4909 }
4910
4911 bool IsShift = BinaryOperator::isShiftOp(op.Opcode) ||
4913 // Convert to the result type.
4914 return FPBuilder.CreateFixedToFixed(Result, IsShift ? LHSFixedSema
4915 : CommonFixedSema,
4916 ResultFixedSema);
4917}
4918
4919Value *ScalarExprEmitter::EmitSub(const BinOpInfo &op) {
4920 // The LHS is always a pointer if either side is.
4921 if (!op.LHS->getType()->isPointerTy()) {
4922 if (op.Ty->isSignedIntegerOrEnumerationType() ||
4923 op.Ty->isUnsignedIntegerType()) {
4924 const bool isSigned = op.Ty->isSignedIntegerOrEnumerationType();
4925 const bool hasSan =
4926 isSigned ? CGF.SanOpts.has(SanitizerKind::SignedIntegerOverflow)
4927 : CGF.SanOpts.has(SanitizerKind::UnsignedIntegerOverflow);
4928 switch (getOverflowBehaviorConsideringType(CGF, op.Ty)) {
4929 case LangOptions::OB_Wrap:
4930 return Builder.CreateSub(op.LHS, op.RHS, "sub");
4931 case LangOptions::OB_SignedAndDefined:
4932 if (!hasSan)
4933 return Builder.CreateSub(op.LHS, op.RHS, "sub");
4934 [[fallthrough]];
4935 case LangOptions::OB_Unset:
4936 if (!hasSan)
4937 return isSigned ? Builder.CreateNSWSub(op.LHS, op.RHS, "sub")
4938 : Builder.CreateSub(op.LHS, op.RHS, "sub");
4939 [[fallthrough]];
4940 case LangOptions::OB_Trap:
4941 if (CanElideOverflowCheck(CGF.getContext(), op))
4942 return isSigned ? Builder.CreateNSWSub(op.LHS, op.RHS, "sub")
4943 : Builder.CreateSub(op.LHS, op.RHS, "sub");
4944 return EmitOverflowCheckedBinOp(op);
4945 }
4946 }
4947
4948 // For vector and matrix subs, try to fold into a fmuladd.
4949 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4950 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4951 // Try to form an fmuladd.
4952 if (Value *FMulAdd = tryEmitFMulAdd(op, CGF, Builder, true))
4953 return FMulAdd;
4954 }
4955
4956 if (op.Ty->isConstantMatrixType()) {
4957 llvm::MatrixBuilder MB(Builder);
4958 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4959 return MB.CreateSub(op.LHS, op.RHS);
4960 }
4961
4962 if (op.LHS->getType()->isFPOrFPVectorTy()) {
4963 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, op.FPFeatures);
4964 return Builder.CreateFSub(op.LHS, op.RHS, "sub");
4965 }
4966
4967 if (op.isFixedPointOp())
4968 return EmitFixedPointBinOp(op);
4969
4970 return Builder.CreateSub(op.LHS, op.RHS, "sub");
4971 }
4972
4973 // If the RHS is not a pointer, then we have normal pointer
4974 // arithmetic.
4975 if (!op.RHS->getType()->isPointerTy())
4977
4978 // Otherwise, this is a pointer subtraction.
4979
4980 // Do the raw subtraction part.
4981 llvm::Value *LHS
4982 = Builder.CreatePtrToInt(op.LHS, CGF.PtrDiffTy, "sub.ptr.lhs.cast");
4983 llvm::Value *RHS
4984 = Builder.CreatePtrToInt(op.RHS, CGF.PtrDiffTy, "sub.ptr.rhs.cast");
4985 Value *diffInChars = Builder.CreateSub(LHS, RHS, "sub.ptr.sub");
4986
4987 // Okay, figure out the element size.
4988 const BinaryOperator *expr = cast<BinaryOperator>(op.E);
4989 QualType elementType = expr->getLHS()->getType()->getPointeeType();
4990
4991 llvm::Value *divisor = nullptr;
4992
4993 // For a variable-length array, this is going to be non-constant.
4994 if (const VariableArrayType *vla
4995 = CGF.getContext().getAsVariableArrayType(elementType)) {
4996 auto VlaSize = CGF.getVLASize(vla);
4997 elementType = VlaSize.Type;
4998 divisor = VlaSize.NumElts;
4999
5000 // Scale the number of non-VLA elements by the non-VLA element size.
5001 CharUnits eltSize = CGF.getContext().getTypeSizeInChars(elementType);
5002 if (!eltSize.isOne())
5003 divisor = CGF.Builder.CreateNUWMul(CGF.CGM.getSize(eltSize), divisor);
5004
5005 // For everything elese, we can just compute it, safe in the
5006 // assumption that Sema won't let anything through that we can't
5007 // safely compute the size of.
5008 } else {
5009 CharUnits elementSize;
5010 // Handle GCC extension for pointer arithmetic on void* and
5011 // function pointer types.
5012 if (elementType->isVoidType() || elementType->isFunctionType())
5013 elementSize = CharUnits::One();
5014 else
5015 elementSize = CGF.getContext().getTypeSizeInChars(elementType);
5016
5017 // Don't even emit the divide for element size of 1.
5018 if (elementSize.isOne())
5019 return diffInChars;
5020
5021 divisor = CGF.CGM.getSize(elementSize);
5022 }
5023
5024 if (CGF.getLangOpts().StablePointerSubtraction)
5025 return Builder.CreateSDiv(diffInChars, divisor, "sub.ptr.div");
5026 // Otherwise, do a full sdiv. This uses the "exact" form of sdiv, since
5027 // pointer difference in C is only defined in the case where both operands
5028 // are pointing to elements of an array.
5029 return Builder.CreateExactSDiv(diffInChars, divisor, "sub.ptr.div");
5030}
5031
5032Value *ScalarExprEmitter::GetMaximumShiftAmount(Value *LHS, Value *RHS,
5033 bool RHSIsSigned) {
5034 llvm::IntegerType *Ty;
5035 if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
5036 Ty = cast<llvm::IntegerType>(VT->getElementType());
5037 else
5038 Ty = cast<llvm::IntegerType>(LHS->getType());
5039 // For a given type of LHS the maximum shift amount is width(LHS)-1, however
5040 // it can occur that width(LHS)-1 > range(RHS). Since there is no check for
5041 // this in ConstantInt::get, this results in the value getting truncated.
5042 // Constrain the return value to be max(RHS) in this case.
5043 llvm::Type *RHSTy = RHS->getType();
5044 llvm::APInt RHSMax =
5045 RHSIsSigned ? llvm::APInt::getSignedMaxValue(RHSTy->getScalarSizeInBits())
5046 : llvm::APInt::getMaxValue(RHSTy->getScalarSizeInBits());
5047 if (RHSMax.ult(Ty->getBitWidth()))
5048 return llvm::ConstantInt::get(RHSTy, RHSMax);
5049 return llvm::ConstantInt::get(RHSTy, Ty->getBitWidth() - 1);
5050}
5051
5052Value *ScalarExprEmitter::ConstrainShiftValue(Value *LHS, Value *RHS,
5053 const Twine &Name) {
5054 llvm::IntegerType *Ty;
5055 if (auto *VT = dyn_cast<llvm::VectorType>(LHS->getType()))
5056 Ty = cast<llvm::IntegerType>(VT->getElementType());
5057 else
5058 Ty = cast<llvm::IntegerType>(LHS->getType());
5059
5060 if (llvm::isPowerOf2_64(Ty->getBitWidth()))
5061 return Builder.CreateAnd(RHS, GetMaximumShiftAmount(LHS, RHS, false), Name);
5062
5063 return Builder.CreateURem(
5064 RHS, llvm::ConstantInt::get(RHS->getType(), Ty->getBitWidth()), Name);
5065}
5066
5067Value *ScalarExprEmitter::EmitShl(const BinOpInfo &Ops) {
5068 // TODO: This misses out on the sanitizer check below.
5069 if (Ops.isFixedPointOp())
5070 return EmitFixedPointBinOp(Ops);
5071
5072 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
5073 // RHS to the same size as the LHS.
5074 Value *RHS = Ops.RHS;
5075 if (Ops.LHS->getType() != RHS->getType())
5076 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
5077
5078 bool SanitizeSignedBase = CGF.SanOpts.has(SanitizerKind::ShiftBase) &&
5079 Ops.Ty->hasSignedIntegerRepresentation() &&
5081 !CGF.getLangOpts().CPlusPlus20;
5082 bool SanitizeUnsignedBase =
5083 CGF.SanOpts.has(SanitizerKind::UnsignedShiftBase) &&
5084 Ops.Ty->hasUnsignedIntegerRepresentation();
5085 bool SanitizeBase = SanitizeSignedBase || SanitizeUnsignedBase;
5086 bool SanitizeExponent = CGF.SanOpts.has(SanitizerKind::ShiftExponent);
5087 // OpenCL 6.3j: shift values are effectively % word size of LHS.
5088 if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL)
5089 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shl.mask");
5090 else if ((SanitizeBase || SanitizeExponent) &&
5091 isa<llvm::IntegerType>(Ops.LHS->getType())) {
5092 SmallVector<SanitizerKind::SanitizerOrdinal, 3> Ordinals;
5093 if (SanitizeSignedBase)
5094 Ordinals.push_back(SanitizerKind::SO_ShiftBase);
5095 if (SanitizeUnsignedBase)
5096 Ordinals.push_back(SanitizerKind::SO_UnsignedShiftBase);
5097 if (SanitizeExponent)
5098 Ordinals.push_back(SanitizerKind::SO_ShiftExponent);
5099
5100 SanitizerDebugLocation SanScope(&CGF, Ordinals,
5101 SanitizerHandler::ShiftOutOfBounds);
5102 SmallVector<std::pair<Value *, SanitizerKind::SanitizerOrdinal>, 2> Checks;
5103 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
5104 llvm::Value *WidthMinusOne =
5105 GetMaximumShiftAmount(Ops.LHS, Ops.RHS, RHSIsSigned);
5106 llvm::Value *ValidExponent = Builder.CreateICmpULE(Ops.RHS, WidthMinusOne);
5107
5108 if (SanitizeExponent) {
5109 Checks.push_back(
5110 std::make_pair(ValidExponent, SanitizerKind::SO_ShiftExponent));
5111 }
5112
5113 if (SanitizeBase) {
5114 // Check whether we are shifting any non-zero bits off the top of the
5115 // integer. We only emit this check if exponent is valid - otherwise
5116 // instructions below will have undefined behavior themselves.
5117 llvm::BasicBlock *Orig = Builder.GetInsertBlock();
5118 llvm::BasicBlock *Cont = CGF.createBasicBlock("cont");
5119 llvm::BasicBlock *CheckShiftBase = CGF.createBasicBlock("check");
5120 Builder.CreateCondBr(ValidExponent, CheckShiftBase, Cont);
5121 llvm::Value *PromotedWidthMinusOne =
5122 (RHS == Ops.RHS) ? WidthMinusOne
5123 : GetMaximumShiftAmount(Ops.LHS, RHS, RHSIsSigned);
5124 CGF.EmitBlock(CheckShiftBase);
5125 llvm::Value *BitsShiftedOff = Builder.CreateLShr(
5126 Ops.LHS, Builder.CreateSub(PromotedWidthMinusOne, RHS, "shl.zeros",
5127 /*NUW*/ true, /*NSW*/ true),
5128 "shl.check");
5129 if (SanitizeUnsignedBase || CGF.getLangOpts().CPlusPlus) {
5130 // In C99, we are not permitted to shift a 1 bit into the sign bit.
5131 // Under C++11's rules, shifting a 1 bit into the sign bit is
5132 // OK, but shifting a 1 bit out of it is not. (C89 and C++03 don't
5133 // define signed left shifts, so we use the C99 and C++11 rules there).
5134 // Unsigned shifts can always shift into the top bit.
5135 llvm::Value *One = llvm::ConstantInt::get(BitsShiftedOff->getType(), 1);
5136 BitsShiftedOff = Builder.CreateLShr(BitsShiftedOff, One);
5137 }
5138 llvm::Value *Zero = llvm::ConstantInt::get(BitsShiftedOff->getType(), 0);
5139 llvm::Value *ValidBase = Builder.CreateICmpEQ(BitsShiftedOff, Zero);
5140 CGF.EmitBlock(Cont);
5141 llvm::PHINode *BaseCheck = Builder.CreatePHI(ValidBase->getType(), 2);
5142 BaseCheck->addIncoming(Builder.getTrue(), Orig);
5143 BaseCheck->addIncoming(ValidBase, CheckShiftBase);
5144 Checks.push_back(std::make_pair(
5145 BaseCheck, SanitizeSignedBase ? SanitizerKind::SO_ShiftBase
5146 : SanitizerKind::SO_UnsignedShiftBase));
5147 }
5148
5149 assert(!Checks.empty());
5150 EmitBinOpCheck(Checks, Ops);
5151 }
5152
5153 return Builder.CreateShl(Ops.LHS, RHS, "shl");
5154}
5155
5156Value *ScalarExprEmitter::EmitShr(const BinOpInfo &Ops) {
5157 // TODO: This misses out on the sanitizer check below.
5158 if (Ops.isFixedPointOp())
5159 return EmitFixedPointBinOp(Ops);
5160
5161 // LLVM requires the LHS and RHS to be the same type: promote or truncate the
5162 // RHS to the same size as the LHS.
5163 Value *RHS = Ops.RHS;
5164 if (Ops.LHS->getType() != RHS->getType())
5165 RHS = Builder.CreateIntCast(RHS, Ops.LHS->getType(), false, "sh_prom");
5166
5167 // OpenCL 6.3j: shift values are effectively % word size of LHS.
5168 if (CGF.getLangOpts().OpenCL || CGF.getLangOpts().HLSL)
5169 RHS = ConstrainShiftValue(Ops.LHS, RHS, "shr.mask");
5170 else if (CGF.SanOpts.has(SanitizerKind::ShiftExponent) &&
5171 isa<llvm::IntegerType>(Ops.LHS->getType())) {
5172 SanitizerDebugLocation SanScope(&CGF, {SanitizerKind::SO_ShiftExponent},
5173 SanitizerHandler::ShiftOutOfBounds);
5174 bool RHSIsSigned = Ops.rhsHasSignedIntegerRepresentation();
5175 llvm::Value *Valid = Builder.CreateICmpULE(
5176 Ops.RHS, GetMaximumShiftAmount(Ops.LHS, Ops.RHS, RHSIsSigned));
5177 EmitBinOpCheck(std::make_pair(Valid, SanitizerKind::SO_ShiftExponent), Ops);
5178 }
5179
5180 if (Ops.Ty->hasUnsignedIntegerRepresentation())
5181 return Builder.CreateLShr(Ops.LHS, RHS, "shr");
5182 return Builder.CreateAShr(Ops.LHS, RHS, "shr");
5183}
5184
5186// return corresponding comparison intrinsic for given vector type
5187static llvm::Intrinsic::ID GetIntrinsic(IntrinsicType IT,
5188 BuiltinType::Kind ElemKind) {
5189 switch (ElemKind) {
5190 default: llvm_unreachable("unexpected element type");
5191 case BuiltinType::Char_U:
5192 case BuiltinType::UChar:
5193 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
5194 llvm::Intrinsic::ppc_altivec_vcmpgtub_p;
5195 case BuiltinType::Char_S:
5196 case BuiltinType::SChar:
5197 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequb_p :
5198 llvm::Intrinsic::ppc_altivec_vcmpgtsb_p;
5199 case BuiltinType::UShort:
5200 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
5201 llvm::Intrinsic::ppc_altivec_vcmpgtuh_p;
5202 case BuiltinType::Short:
5203 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequh_p :
5204 llvm::Intrinsic::ppc_altivec_vcmpgtsh_p;
5205 case BuiltinType::UInt:
5206 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
5207 llvm::Intrinsic::ppc_altivec_vcmpgtuw_p;
5208 case BuiltinType::Int:
5209 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequw_p :
5210 llvm::Intrinsic::ppc_altivec_vcmpgtsw_p;
5211 case BuiltinType::ULong:
5212 case BuiltinType::ULongLong:
5213 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
5214 llvm::Intrinsic::ppc_altivec_vcmpgtud_p;
5215 case BuiltinType::Long:
5216 case BuiltinType::LongLong:
5217 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequd_p :
5218 llvm::Intrinsic::ppc_altivec_vcmpgtsd_p;
5219 case BuiltinType::Float:
5220 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpeqfp_p :
5221 llvm::Intrinsic::ppc_altivec_vcmpgtfp_p;
5222 case BuiltinType::Double:
5223 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_vsx_xvcmpeqdp_p :
5224 llvm::Intrinsic::ppc_vsx_xvcmpgtdp_p;
5225 case BuiltinType::UInt128:
5226 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
5227 : llvm::Intrinsic::ppc_altivec_vcmpgtuq_p;
5228 case BuiltinType::Int128:
5229 return (IT == VCMPEQ) ? llvm::Intrinsic::ppc_altivec_vcmpequq_p
5230 : llvm::Intrinsic::ppc_altivec_vcmpgtsq_p;
5231 }
5232}
5233
5234Value *ScalarExprEmitter::EmitCompare(const BinaryOperator *E,
5235 llvm::CmpInst::Predicate UICmpOpc,
5236 llvm::CmpInst::Predicate SICmpOpc,
5237 llvm::CmpInst::Predicate FCmpOpc,
5238 bool IsSignaling) {
5239 TestAndClearIgnoreResultAssign();
5240 Value *Result;
5241 QualType LHSTy = E->getLHS()->getType();
5242 QualType RHSTy = E->getRHS()->getType();
5243 if (const MemberPointerType *MPT = LHSTy->getAs<MemberPointerType>()) {
5244 assert(E->getOpcode() == BO_EQ ||
5245 E->getOpcode() == BO_NE);
5246 Value *LHS = CGF.EmitScalarExpr(E->getLHS());
5247 Value *RHS = CGF.EmitScalarExpr(E->getRHS());
5249 CGF, LHS, RHS, MPT, E->getOpcode() == BO_NE);
5250 } else if (!LHSTy->isAnyComplexType() && !RHSTy->isAnyComplexType()) {
5251 BinOpInfo BOInfo = EmitBinOps(E);
5252 Value *LHS = BOInfo.LHS;
5253 Value *RHS = BOInfo.RHS;
5254
5255 // If AltiVec, the comparison results in a numeric type, so we use
5256 // intrinsics comparing vectors and giving 0 or 1 as a result
5257 if (LHSTy->isVectorType() && !E->getType()->isVectorType()) {
5258 // constants for mapping CR6 register bits to predicate result
5259 enum { CR6_EQ=0, CR6_EQ_REV, CR6_LT, CR6_LT_REV } CR6;
5260
5261 llvm::Intrinsic::ID ID = llvm::Intrinsic::not_intrinsic;
5262
5263 // in several cases vector arguments order will be reversed
5264 Value *FirstVecArg = LHS,
5265 *SecondVecArg = RHS;
5266
5267 QualType ElTy = LHSTy->castAs<VectorType>()->getElementType();
5268 BuiltinType::Kind ElementKind = ElTy->castAs<BuiltinType>()->getKind();
5269
5270 switch(E->getOpcode()) {
5271 default: llvm_unreachable("is not a comparison operation");
5272 case BO_EQ:
5273 CR6 = CR6_LT;
5274 ID = GetIntrinsic(VCMPEQ, ElementKind);
5275 break;
5276 case BO_NE:
5277 CR6 = CR6_EQ;
5278 ID = GetIntrinsic(VCMPEQ, ElementKind);
5279 break;
5280 case BO_LT:
5281 CR6 = CR6_LT;
5282 ID = GetIntrinsic(VCMPGT, ElementKind);
5283 std::swap(FirstVecArg, SecondVecArg);
5284 break;
5285 case BO_GT:
5286 CR6 = CR6_LT;
5287 ID = GetIntrinsic(VCMPGT, ElementKind);
5288 break;
5289 case BO_LE:
5290 if (ElementKind == BuiltinType::Float) {
5291 CR6 = CR6_LT;
5292 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
5293 std::swap(FirstVecArg, SecondVecArg);
5294 }
5295 else {
5296 CR6 = CR6_EQ;
5297 ID = GetIntrinsic(VCMPGT, ElementKind);
5298 }
5299 break;
5300 case BO_GE:
5301 if (ElementKind == BuiltinType::Float) {
5302 CR6 = CR6_LT;
5303 ID = llvm::Intrinsic::ppc_altivec_vcmpgefp_p;
5304 }
5305 else {
5306 CR6 = CR6_EQ;
5307 ID = GetIntrinsic(VCMPGT, ElementKind);
5308 std::swap(FirstVecArg, SecondVecArg);
5309 }
5310 break;
5311 }
5312
5313 Value *CR6Param = Builder.getInt32(CR6);
5314 llvm::Function *F = CGF.CGM.getIntrinsic(ID);
5315 Result = Builder.CreateCall(F, {CR6Param, FirstVecArg, SecondVecArg});
5316
5317 // The result type of intrinsic may not be same as E->getType().
5318 // If E->getType() is not BoolTy, EmitScalarConversion will do the
5319 // conversion work. If E->getType() is BoolTy, EmitScalarConversion will
5320 // do nothing, if ResultTy is not i1 at the same time, it will cause
5321 // crash later.
5322 llvm::IntegerType *ResultTy = cast<llvm::IntegerType>(Result->getType());
5323 if (ResultTy->getBitWidth() > 1 &&
5324 E->getType() == CGF.getContext().BoolTy)
5325 Result = Builder.CreateTrunc(Result, Builder.getInt1Ty());
5326 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
5327 E->getExprLoc());
5328 }
5329
5330 if (BOInfo.isFixedPointOp()) {
5331 Result = EmitFixedPointBinOp(BOInfo);
5332 } else if (LHS->getType()->isFPOrFPVectorTy()) {
5333 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(CGF, BOInfo.FPFeatures);
5334 if (!IsSignaling)
5335 Result = Builder.CreateFCmp(FCmpOpc, LHS, RHS, "cmp");
5336 else
5337 Result = Builder.CreateFCmpS(FCmpOpc, LHS, RHS, "cmp");
5338 } else if (LHSTy->hasSignedIntegerRepresentation()) {
5339 Result = Builder.CreateICmp(SICmpOpc, LHS, RHS, "cmp");
5340 } else {
5341 // Unsigned integers and pointers.
5342
5343 if (CGF.CGM.getCodeGenOpts().StrictVTablePointers &&
5346
5347 // Dynamic information is required to be stripped for comparisons,
5348 // because it could leak the dynamic information. Based on comparisons
5349 // of pointers to dynamic objects, the optimizer can replace one pointer
5350 // with another, which might be incorrect in presence of invariant
5351 // groups. Comparison with null is safe because null does not carry any
5352 // dynamic information.
5353 if (LHSTy.mayBeDynamicClass())
5354 LHS = Builder.CreateStripInvariantGroup(LHS);
5355 if (RHSTy.mayBeDynamicClass())
5356 RHS = Builder.CreateStripInvariantGroup(RHS);
5357 }
5358
5359 Result = Builder.CreateICmp(UICmpOpc, LHS, RHS, "cmp");
5360 }
5361
5362 // If this is a vector comparison, sign extend the result to the appropriate
5363 // vector integer type and return it (don't convert to bool).
5364 if (LHSTy->isVectorType() || LHSTy->isSveVLSBuiltinType())
5365 return Builder.CreateSExt(Result, ConvertType(E->getType()), "sext");
5366
5367 } else {
5368 // Complex Comparison: can only be an equality comparison.
5370 QualType CETy;
5371 if (auto *CTy = LHSTy->getAs<ComplexType>()) {
5372 LHS = CGF.EmitComplexExpr(E->getLHS());
5373 CETy = CTy->getElementType();
5374 } else {
5375 LHS.first = Visit(E->getLHS());
5376 LHS.second = llvm::Constant::getNullValue(LHS.first->getType());
5377 CETy = LHSTy;
5378 }
5379 if (auto *CTy = RHSTy->getAs<ComplexType>()) {
5380 RHS = CGF.EmitComplexExpr(E->getRHS());
5381 assert(CGF.getContext().hasSameUnqualifiedType(CETy,
5382 CTy->getElementType()) &&
5383 "The element types must always match.");
5384 (void)CTy;
5385 } else {
5386 RHS.first = Visit(E->getRHS());
5387 RHS.second = llvm::Constant::getNullValue(RHS.first->getType());
5388 assert(CGF.getContext().hasSameUnqualifiedType(CETy, RHSTy) &&
5389 "The element types must always match.");
5390 }
5391
5392 Value *ResultR, *ResultI;
5393 if (CETy->isRealFloatingType()) {
5394 // As complex comparisons can only be equality comparisons, they
5395 // are never signaling comparisons.
5396 ResultR = Builder.CreateFCmp(FCmpOpc, LHS.first, RHS.first, "cmp.r");
5397 ResultI = Builder.CreateFCmp(FCmpOpc, LHS.second, RHS.second, "cmp.i");
5398 } else {
5399 // Complex comparisons can only be equality comparisons. As such, signed
5400 // and unsigned opcodes are the same.
5401 ResultR = Builder.CreateICmp(UICmpOpc, LHS.first, RHS.first, "cmp.r");
5402 ResultI = Builder.CreateICmp(UICmpOpc, LHS.second, RHS.second, "cmp.i");
5403 }
5404
5405 if (E->getOpcode() == BO_EQ) {
5406 Result = Builder.CreateAnd(ResultR, ResultI, "and.ri");
5407 } else {
5408 assert(E->getOpcode() == BO_NE &&
5409 "Complex comparison other than == or != ?");
5410 Result = Builder.CreateOr(ResultR, ResultI, "or.ri");
5411 }
5412 }
5413
5414 return EmitScalarConversion(Result, CGF.getContext().BoolTy, E->getType(),
5415 E->getExprLoc());
5416}
5417
5419 const BinaryOperator *E, Value **Previous, QualType *SrcType) {
5420 // In case we have the integer or bitfield sanitizer checks enabled
5421 // we want to get the expression before scalar conversion.
5422 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E->getRHS())) {
5423 CastKind Kind = ICE->getCastKind();
5424 if (Kind == CK_IntegralCast || Kind == CK_LValueToRValue) {
5425 *SrcType = ICE->getSubExpr()->getType();
5426 *Previous = EmitScalarExpr(ICE->getSubExpr());
5427 // Pass default ScalarConversionOpts to avoid emitting
5428 // integer sanitizer checks as E refers to bitfield.
5429 return EmitScalarConversion(*Previous, *SrcType, ICE->getType(),
5430 ICE->getExprLoc());
5431 }
5432 }
5433 return EmitScalarExpr(E->getRHS());
5434}
5435
5436Value *ScalarExprEmitter::VisitBinAssign(const BinaryOperator *E) {
5437 ApplyAtomGroup Grp(CGF.getDebugInfo());
5438 bool Ignore = TestAndClearIgnoreResultAssign();
5439
5440 Value *RHS;
5441 LValue LHS;
5442
5443 if (PointerAuthQualifier PtrAuth = E->getLHS()->getType().getPointerAuth()) {
5446 llvm::Value *RV =
5447 CGF.EmitPointerAuthQualify(PtrAuth, E->getRHS(), LV.getAddress());
5448 CGF.EmitNullabilityCheck(LV, RV, E->getExprLoc());
5450
5451 if (Ignore)
5452 return nullptr;
5453 RV = CGF.EmitPointerAuthUnqualify(PtrAuth, RV, LV.getType(),
5454 LV.getAddress(), /*nonnull*/ false);
5455 return RV;
5456 }
5457
5458 switch (E->getLHS()->getType().getObjCLifetime()) {
5460 std::tie(LHS, RHS) = CGF.EmitARCStoreStrong(E, Ignore);
5461 break;
5462
5464 std::tie(LHS, RHS) = CGF.EmitARCStoreAutoreleasing(E);
5465 break;
5466
5468 std::tie(LHS, RHS) = CGF.EmitARCStoreUnsafeUnretained(E, Ignore);
5469 break;
5470
5472 RHS = Visit(E->getRHS());
5473 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
5474 RHS = CGF.EmitARCStoreWeak(LHS.getAddress(), RHS, Ignore);
5475 break;
5476
5478 // __block variables need to have the rhs evaluated first, plus
5479 // this should improve codegen just a little.
5480 Value *Previous = nullptr;
5481 QualType SrcType = E->getRHS()->getType();
5482 // Check if LHS is a bitfield, if RHS contains an implicit cast expression
5483 // we want to extract that value and potentially (if the bitfield sanitizer
5484 // is enabled) use it to check for an implicit conversion.
5485 if (E->getLHS()->refersToBitField())
5486 RHS = CGF.EmitWithOriginalRHSBitfieldAssignment(E, &Previous, &SrcType);
5487 else
5488 RHS = Visit(E->getRHS());
5489
5490 LHS = EmitCheckedLValue(E->getLHS(), CodeGenFunction::TCK_Store);
5491
5492 // Store the value into the LHS. Bit-fields are handled specially
5493 // because the result is altered by the store, i.e., [C99 6.5.16p1]
5494 // 'An assignment expression has the value of the left operand after
5495 // the assignment...'.
5496 if (LHS.isBitField()) {
5497 CGF.EmitStoreThroughBitfieldLValue(RValue::get(RHS), LHS, &RHS);
5498 // If the expression contained an implicit conversion, make sure
5499 // to use the value before the scalar conversion.
5500 Value *Src = Previous ? Previous : RHS;
5501 QualType DstType = E->getLHS()->getType();
5502 CGF.EmitBitfieldConversionCheck(Src, SrcType, RHS, DstType,
5503 LHS.getBitFieldInfo(), E->getExprLoc());
5504 } else {
5505 CGF.EmitNullabilityCheck(LHS, RHS, E->getExprLoc());
5506 CGF.EmitStoreThroughLValue(RValue::get(RHS), LHS);
5507 }
5508 }
5509 // OpenMP: Handle lastprivate(condition:) in scalar assignment
5510 if (CGF.getLangOpts().OpenMP) {
5512 E->getLHS());
5513 }
5514
5515 // If the result is clearly ignored, return now.
5516 if (Ignore)
5517 return nullptr;
5518
5519 // The result of an assignment in C is the assigned r-value.
5520 if (!CGF.getLangOpts().CPlusPlus)
5521 return RHS;
5522
5523 // If the lvalue is non-volatile, return the computed value of the assignment.
5524 if (!LHS.isVolatileQualified())
5525 return RHS;
5526
5527 // Otherwise, reload the value.
5528 return EmitLoadOfLValue(LHS, E->getExprLoc());
5529}
5530
5531Value *ScalarExprEmitter::VisitBinLAnd(const BinaryOperator *E) {
5532 auto HasLHSSkip = CGF.hasSkipCounter(E);
5533 auto HasRHSSkip = CGF.hasSkipCounter(E->getRHS());
5534
5535 // Perform vector logical and on comparisons with zero vectors.
5536 if (E->getType()->isVectorType()) {
5538
5539 Value *LHS = Visit(E->getLHS());
5540 Value *RHS = Visit(E->getRHS());
5541 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
5542 if (LHS->getType()->isFPOrFPVectorTy()) {
5543 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
5544 CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
5545 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
5546 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
5547 } else {
5548 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
5549 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
5550 }
5551 Value *And = Builder.CreateAnd(LHS, RHS);
5552 return Builder.CreateSExt(And, ConvertType(E->getType()), "sext");
5553 }
5554
5555 bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
5556 llvm::Type *ResTy = ConvertType(E->getType());
5557
5558 // If we have 0 && RHS, see if we can elide RHS, if so, just return 0.
5559 // If we have 1 && X, just emit X without inserting the control flow.
5560 bool LHSCondVal;
5561 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
5562 if (LHSCondVal) { // If we have 1 && X, just emit X.
5563 CGF.incrementProfileCounter(CGF.UseExecPath, E, /*UseBoth=*/true);
5564
5565 // If the top of the logical operator nest, reset the MCDC temp to 0.
5566 if (CGF.isMCDCDecisionExpr(E))
5568
5569 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
5570
5571 // If we're generating for profiling or coverage, generate a branch to a
5572 // block that increments the RHS counter needed to track branch condition
5573 // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
5574 // "FalseBlock" after the increment is done.
5575 if (InstrumentRegions &&
5577 CGF.maybeUpdateMCDCCondBitmap(E->getRHS(), RHSCond);
5578 llvm::BasicBlock *FBlock = CGF.createBasicBlock("land.end");
5579 llvm::BasicBlock *RHSSkip =
5580 (HasRHSSkip ? CGF.createBasicBlock("land.rhsskip") : FBlock);
5581 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("land.rhscnt");
5582 Builder.CreateCondBr(RHSCond, RHSBlockCnt, RHSSkip);
5583 CGF.EmitBlock(RHSBlockCnt);
5585 CGF.EmitBranch(FBlock);
5586 if (HasRHSSkip) {
5587 CGF.EmitBlock(RHSSkip);
5589 }
5590 CGF.EmitBlock(FBlock);
5591 } else
5592 CGF.markStmtMaybeUsed(E->getRHS());
5593
5594 // If the top of the logical operator nest, update the MCDC bitmap.
5595 if (CGF.isMCDCDecisionExpr(E))
5597
5598 // ZExt result to int or bool.
5599 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "land.ext");
5600 }
5601
5602 // 0 && RHS: If it is safe, just elide the RHS, and return 0/false.
5603 if (!CGF.ContainsLabel(E->getRHS())) {
5604 CGF.markStmtAsUsed(false, E);
5605 if (HasLHSSkip)
5607
5608 CGF.markStmtMaybeUsed(E->getRHS());
5609
5610 return llvm::Constant::getNullValue(ResTy);
5611 }
5612 }
5613
5614 // If the top of the logical operator nest, reset the MCDC temp to 0.
5615 if (CGF.isMCDCDecisionExpr(E))
5617
5618 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("land.end");
5619 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("land.rhs");
5620
5621 llvm::BasicBlock *LHSFalseBlock =
5622 (HasLHSSkip ? CGF.createBasicBlock("land.lhsskip") : ContBlock);
5623
5624 CodeGenFunction::ConditionalEvaluation eval(CGF);
5625
5626 // Branch on the LHS first. If it is false, go to the failure (cont) block.
5627 CGF.EmitBranchOnBoolExpr(E->getLHS(), RHSBlock, LHSFalseBlock,
5628 CGF.getProfileCount(E->getRHS()));
5629
5630 if (HasLHSSkip) {
5631 CGF.EmitBlock(LHSFalseBlock);
5633 CGF.EmitBranch(ContBlock);
5634 }
5635
5636 // Any edges into the ContBlock are now from an (indeterminate number of)
5637 // edges from this first condition. All of these values will be false. Start
5638 // setting up the PHI node in the Cont Block for this.
5639 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
5640 "", ContBlock);
5641 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
5642 PI != PE; ++PI)
5643 PN->addIncoming(llvm::ConstantInt::getFalse(VMContext), *PI);
5644
5645 eval.begin(CGF);
5646 CGF.EmitBlock(RHSBlock);
5648 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
5649 eval.end(CGF);
5650
5651 // Reaquire the RHS block, as there may be subblocks inserted.
5652 RHSBlock = Builder.GetInsertBlock();
5653
5654 // If we're generating for profiling or coverage, generate a branch on the
5655 // RHS to a block that increments the RHS true counter needed to track branch
5656 // condition coverage.
5657 llvm::BasicBlock *ContIncoming = RHSBlock;
5658 if (InstrumentRegions &&
5660 CGF.maybeUpdateMCDCCondBitmap(E->getRHS(), RHSCond);
5661 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("land.rhscnt");
5662 llvm::BasicBlock *RHSBlockSkip =
5663 (HasRHSSkip ? CGF.createBasicBlock("land.rhsskip") : ContBlock);
5664 Builder.CreateCondBr(RHSCond, RHSBlockCnt, RHSBlockSkip);
5665 CGF.EmitBlock(RHSBlockCnt);
5667 CGF.EmitBranch(ContBlock);
5668 PN->addIncoming(RHSCond, RHSBlockCnt);
5669 if (HasRHSSkip) {
5670 CGF.EmitBlock(RHSBlockSkip);
5672 CGF.EmitBranch(ContBlock);
5673 ContIncoming = RHSBlockSkip;
5674 }
5675 }
5676
5677 // Emit an unconditional branch from this block to ContBlock.
5678 {
5679 // There is no need to emit line number for unconditional branch.
5680 auto NL = ApplyDebugLocation::CreateEmpty(CGF);
5681 CGF.EmitBlock(ContBlock);
5682 }
5683 // Insert an entry into the phi node for the edge with the value of RHSCond.
5684 PN->addIncoming(RHSCond, ContIncoming);
5685
5686 // If the top of the logical operator nest, update the MCDC bitmap.
5687 if (CGF.isMCDCDecisionExpr(E))
5689
5690 // Artificial location to preserve the scope information
5691 {
5693 PN->setDebugLoc(Builder.getCurrentDebugLocation());
5694 }
5695
5696 // ZExt result to int.
5697 return Builder.CreateZExtOrBitCast(PN, ResTy, "land.ext");
5698}
5699
5700Value *ScalarExprEmitter::VisitBinLOr(const BinaryOperator *E) {
5701 auto HasLHSSkip = CGF.hasSkipCounter(E);
5702 auto HasRHSSkip = CGF.hasSkipCounter(E->getRHS());
5703
5704 // Perform vector logical or on comparisons with zero vectors.
5705 if (E->getType()->isVectorType()) {
5707
5708 Value *LHS = Visit(E->getLHS());
5709 Value *RHS = Visit(E->getRHS());
5710 Value *Zero = llvm::ConstantAggregateZero::get(LHS->getType());
5711 if (LHS->getType()->isFPOrFPVectorTy()) {
5712 CodeGenFunction::CGFPOptionsRAII FPOptsRAII(
5713 CGF, E->getFPFeaturesInEffect(CGF.getLangOpts()));
5714 LHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, LHS, Zero, "cmp");
5715 RHS = Builder.CreateFCmp(llvm::CmpInst::FCMP_UNE, RHS, Zero, "cmp");
5716 } else {
5717 LHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, LHS, Zero, "cmp");
5718 RHS = Builder.CreateICmp(llvm::CmpInst::ICMP_NE, RHS, Zero, "cmp");
5719 }
5720 Value *Or = Builder.CreateOr(LHS, RHS);
5721 return Builder.CreateSExt(Or, ConvertType(E->getType()), "sext");
5722 }
5723
5724 bool InstrumentRegions = CGF.CGM.getCodeGenOpts().hasProfileClangInstr();
5725 llvm::Type *ResTy = ConvertType(E->getType());
5726
5727 // If we have 1 || RHS, see if we can elide RHS, if so, just return 1.
5728 // If we have 0 || X, just emit X without inserting the control flow.
5729 bool LHSCondVal;
5730 if (CGF.ConstantFoldsToSimpleInteger(E->getLHS(), LHSCondVal)) {
5731 if (!LHSCondVal) { // If we have 0 || X, just emit X.
5732 CGF.incrementProfileCounter(CGF.UseExecPath, E, /*UseBoth=*/true);
5733
5734 // If the top of the logical operator nest, reset the MCDC temp to 0.
5735 if (CGF.isMCDCDecisionExpr(E))
5737
5738 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
5739
5740 // If we're generating for profiling or coverage, generate a branch to a
5741 // block that increments the RHS counter need to track branch condition
5742 // coverage. In this case, use "FBlock" as both the final "TrueBlock" and
5743 // "FalseBlock" after the increment is done.
5744 if (InstrumentRegions &&
5746 CGF.maybeUpdateMCDCCondBitmap(E->getRHS(), RHSCond);
5747 llvm::BasicBlock *FBlock = CGF.createBasicBlock("lor.end");
5748 llvm::BasicBlock *RHSSkip =
5749 (HasRHSSkip ? CGF.createBasicBlock("lor.rhsskip") : FBlock);
5750 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("lor.rhscnt");
5751 Builder.CreateCondBr(RHSCond, RHSSkip, RHSBlockCnt);
5752 CGF.EmitBlock(RHSBlockCnt);
5754 CGF.EmitBranch(FBlock);
5755 if (HasRHSSkip) {
5756 CGF.EmitBlock(RHSSkip);
5758 }
5759 CGF.EmitBlock(FBlock);
5760 } else
5761 CGF.markStmtMaybeUsed(E->getRHS());
5762
5763 // If the top of the logical operator nest, update the MCDC bitmap.
5764 if (CGF.isMCDCDecisionExpr(E))
5766
5767 // ZExt result to int or bool.
5768 return Builder.CreateZExtOrBitCast(RHSCond, ResTy, "lor.ext");
5769 }
5770
5771 // 1 || RHS: If it is safe, just elide the RHS, and return 1/true.
5772 if (!CGF.ContainsLabel(E->getRHS())) {
5773 CGF.markStmtAsUsed(false, E);
5774 if (HasLHSSkip)
5776
5777 CGF.markStmtMaybeUsed(E->getRHS());
5778
5779 return llvm::ConstantInt::get(ResTy, 1);
5780 }
5781 }
5782
5783 // If the top of the logical operator nest, reset the MCDC temp to 0.
5784 if (CGF.isMCDCDecisionExpr(E))
5786
5787 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("lor.end");
5788 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("lor.rhs");
5789 llvm::BasicBlock *LHSTrueBlock =
5790 (HasLHSSkip ? CGF.createBasicBlock("lor.lhsskip") : ContBlock);
5791
5792 CodeGenFunction::ConditionalEvaluation eval(CGF);
5793
5794 // Branch on the LHS first. If it is true, go to the success (cont) block.
5795 CGF.EmitBranchOnBoolExpr(E->getLHS(), LHSTrueBlock, RHSBlock,
5797 CGF.getProfileCount(E->getRHS()));
5798
5799 if (HasLHSSkip) {
5800 CGF.EmitBlock(LHSTrueBlock);
5802 CGF.EmitBranch(ContBlock);
5803 }
5804
5805 // Any edges into the ContBlock are now from an (indeterminate number of)
5806 // edges from this first condition. All of these values will be true. Start
5807 // setting up the PHI node in the Cont Block for this.
5808 llvm::PHINode *PN = llvm::PHINode::Create(llvm::Type::getInt1Ty(VMContext), 2,
5809 "", ContBlock);
5810 for (llvm::pred_iterator PI = pred_begin(ContBlock), PE = pred_end(ContBlock);
5811 PI != PE; ++PI)
5812 PN->addIncoming(llvm::ConstantInt::getTrue(VMContext), *PI);
5813
5814 eval.begin(CGF);
5815
5816 // Emit the RHS condition as a bool value.
5817 CGF.EmitBlock(RHSBlock);
5819 Value *RHSCond = CGF.EvaluateExprAsBool(E->getRHS());
5820
5821 eval.end(CGF);
5822
5823 // Reaquire the RHS block, as there may be subblocks inserted.
5824 RHSBlock = Builder.GetInsertBlock();
5825
5826 // If we're generating for profiling or coverage, generate a branch on the
5827 // RHS to a block that increments the RHS true counter needed to track branch
5828 // condition coverage.
5829 llvm::BasicBlock *ContIncoming = RHSBlock;
5830 if (InstrumentRegions &&
5832 CGF.maybeUpdateMCDCCondBitmap(E->getRHS(), RHSCond);
5833 llvm::BasicBlock *RHSBlockCnt = CGF.createBasicBlock("lor.rhscnt");
5834 llvm::BasicBlock *RHSTrueBlock =
5835 (HasRHSSkip ? CGF.createBasicBlock("lor.rhsskip") : ContBlock);
5836 Builder.CreateCondBr(RHSCond, RHSTrueBlock, RHSBlockCnt);
5837 CGF.EmitBlock(RHSBlockCnt);
5839 CGF.EmitBranch(ContBlock);
5840 PN->addIncoming(RHSCond, RHSBlockCnt);
5841 if (HasRHSSkip) {
5842 CGF.EmitBlock(RHSTrueBlock);
5844 CGF.EmitBranch(ContBlock);
5845 ContIncoming = RHSTrueBlock;
5846 }
5847 }
5848
5849 // Emit an unconditional branch from this block to ContBlock. Insert an entry
5850 // into the phi node for the edge with the value of RHSCond.
5851 CGF.EmitBlock(ContBlock);
5852 PN->addIncoming(RHSCond, ContIncoming);
5853
5854 // If the top of the logical operator nest, update the MCDC bitmap.
5855 if (CGF.isMCDCDecisionExpr(E))
5857
5858 // ZExt result to int.
5859 return Builder.CreateZExtOrBitCast(PN, ResTy, "lor.ext");
5860}
5861
5862Value *ScalarExprEmitter::VisitBinComma(const BinaryOperator *E) {
5863 CGF.EmitIgnoredExpr(E->getLHS());
5864 CGF.EnsureInsertPoint();
5865 return Visit(E->getRHS());
5866}
5867
5868//===----------------------------------------------------------------------===//
5869// Other Operators
5870//===----------------------------------------------------------------------===//
5871
5872/// isCheapEnoughToEvaluateUnconditionally - Return true if the specified
5873/// expression is cheap enough and side-effect-free enough to evaluate
5874/// unconditionally instead of conditionally. This is used to convert control
5875/// flow into selects in some cases.
5877 CodeGenFunction &CGF) {
5878 // Anything that is an integer or floating point constant is fine.
5879 return E->IgnoreParens()->isEvaluatable(CGF.getContext());
5880
5881 // Even non-volatile automatic variables can't be evaluated unconditionally.
5882 // Referencing a thread_local may cause non-trivial initialization work to
5883 // occur. If we're inside a lambda and one of the variables is from the scope
5884 // outside the lambda, that function may have returned already. Reading its
5885 // locals is a bad idea. Also, these reads may introduce races there didn't
5886 // exist in the source-level program.
5887}
5888
5889
5890Value *ScalarExprEmitter::
5891VisitAbstractConditionalOperator(const AbstractConditionalOperator *E) {
5892 TestAndClearIgnoreResultAssign();
5893
5894 // Bind the common expression if necessary.
5895 CodeGenFunction::OpaqueValueMapping binding(CGF, E);
5896
5897 Expr *condExpr = E->getCond();
5898 Expr *lhsExpr = E->getTrueExpr();
5899 Expr *rhsExpr = E->getFalseExpr();
5900
5901 // If the condition constant folds and can be elided, try to avoid emitting
5902 // the condition and the dead arm.
5903 bool CondExprBool;
5904 if (CGF.ConstantFoldsToSimpleInteger(condExpr, CondExprBool)) {
5905 Expr *live = lhsExpr, *dead = rhsExpr;
5906 if (!CondExprBool) std::swap(live, dead);
5907
5908 // If the dead side doesn't have labels we need, just emit the Live part.
5909 if (!CGF.ContainsLabel(dead)) {
5910 CGF.incrementProfileCounter(CondExprBool ? CGF.UseExecPath
5911 : CGF.UseSkipPath,
5912 E, /*UseBoth=*/true);
5913 Value *Result = Visit(live);
5914 CGF.markStmtMaybeUsed(dead);
5915
5916 // If the live part is a throw expression, it acts like it has a void
5917 // type, so evaluating it returns a null Value*. However, a conditional
5918 // with non-void type must return a non-null Value*.
5919 if (!Result && !E->getType()->isVoidType())
5920 Result = llvm::UndefValue::get(CGF.ConvertType(E->getType()));
5921
5922 return Result;
5923 }
5924 }
5925
5926 // OpenCL: If the condition is a vector, we can treat this condition like
5927 // the select function.
5928 if (CGF.getLangOpts().OpenCL && (condExpr->getType()->isVectorType() ||
5929 condExpr->getType()->isExtVectorType())) {
5931
5932 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
5933 llvm::Value *LHS = Visit(lhsExpr);
5934 llvm::Value *RHS = Visit(rhsExpr);
5935
5936 llvm::Type *condType = ConvertType(condExpr->getType());
5937 auto *vecTy = cast<llvm::FixedVectorType>(condType);
5938
5939 unsigned numElem = vecTy->getNumElements();
5940 llvm::Type *elemType = vecTy->getElementType();
5941
5942 llvm::Value *zeroVec = llvm::Constant::getNullValue(vecTy);
5943 llvm::Value *TestMSB = Builder.CreateICmpSLT(CondV, zeroVec);
5944 llvm::Value *tmp = Builder.CreateSExt(
5945 TestMSB, llvm::FixedVectorType::get(elemType, numElem), "sext");
5946 llvm::Value *tmp2 = Builder.CreateNot(tmp);
5947
5948 // Cast float to int to perform ANDs if necessary.
5949 llvm::Value *RHSTmp = RHS;
5950 llvm::Value *LHSTmp = LHS;
5951 bool wasCast = false;
5952 llvm::VectorType *rhsVTy = cast<llvm::VectorType>(RHS->getType());
5953 if (rhsVTy->getElementType()->isFloatingPointTy()) {
5954 RHSTmp = Builder.CreateBitCast(RHS, tmp2->getType());
5955 LHSTmp = Builder.CreateBitCast(LHS, tmp->getType());
5956 wasCast = true;
5957 }
5958
5959 llvm::Value *tmp3 = Builder.CreateAnd(RHSTmp, tmp2);
5960 llvm::Value *tmp4 = Builder.CreateAnd(LHSTmp, tmp);
5961 llvm::Value *tmp5 = Builder.CreateOr(tmp3, tmp4, "cond");
5962 if (wasCast)
5963 tmp5 = Builder.CreateBitCast(tmp5, RHS->getType());
5964
5965 return tmp5;
5966 }
5967
5968 if (condExpr->getType()->isVectorType() ||
5969 condExpr->getType()->isSveVLSBuiltinType()) {
5971
5972 llvm::Value *CondV = CGF.EmitScalarExpr(condExpr);
5973 llvm::Value *LHS = Visit(lhsExpr);
5974 llvm::Value *RHS = Visit(rhsExpr);
5975
5976 llvm::Type *CondType = ConvertType(condExpr->getType());
5977 auto *VecTy = cast<llvm::VectorType>(CondType);
5978
5979 if (VecTy->getElementType()->isIntegerTy(1))
5980 return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
5981
5982 // OpenCL uses the MSB of the mask vector.
5983 llvm::Value *ZeroVec = llvm::Constant::getNullValue(VecTy);
5984 if (condExpr->getType()->isExtVectorType())
5985 CondV = Builder.CreateICmpSLT(CondV, ZeroVec, "vector_cond");
5986 else
5987 CondV = Builder.CreateICmpNE(CondV, ZeroVec, "vector_cond");
5988 return Builder.CreateSelect(CondV, LHS, RHS, "vector_select");
5989 }
5990
5991 // If this is a really simple expression (like x ? 4 : 5), emit this as a
5992 // select instead of as control flow. We can only do this if it is cheap and
5993 // safe to evaluate the LHS and RHS unconditionally.
5997 llvm::Value *CondV = CGF.EvaluateExprAsBool(condExpr);
5998 llvm::Value *StepV = Builder.CreateZExtOrBitCast(CondV, CGF.Int64Ty);
5999
6000 CGF.incrementProfileCounter(E, StepV);
6001
6002 llvm::Value *LHS = Visit(lhsExpr);
6003 llvm::Value *RHS = Visit(rhsExpr);
6004 if (!LHS) {
6005 // If the conditional has void type, make sure we return a null Value*.
6006 assert(!RHS && "LHS and RHS types must match");
6007 return nullptr;
6008 }
6009 return Builder.CreateSelect(CondV, LHS, RHS, "cond");
6010 }
6011
6012 // If the top of the logical operator nest, reset the MCDC temp to 0.
6013 if (auto E = CGF.stripCond(condExpr); CGF.isMCDCDecisionExpr(E))
6015
6016 llvm::BasicBlock *LHSBlock = CGF.createBasicBlock("cond.true");
6017 llvm::BasicBlock *RHSBlock = CGF.createBasicBlock("cond.false");
6018 llvm::BasicBlock *ContBlock = CGF.createBasicBlock("cond.end");
6019
6020 CodeGenFunction::ConditionalEvaluation eval(CGF);
6021 CGF.EmitBranchOnBoolExpr(condExpr, LHSBlock, RHSBlock,
6022 CGF.getProfileCount(lhsExpr));
6023
6024 CGF.EmitBlock(LHSBlock);
6025
6026 // If the top of the logical operator nest, update the MCDC bitmap for the
6027 // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
6028 // may also contain a boolean expression.
6029 if (auto E = CGF.stripCond(condExpr); CGF.isMCDCDecisionExpr(E))
6031
6033 eval.begin(CGF);
6034 Value *LHS = Visit(lhsExpr);
6035 eval.end(CGF);
6036
6037 LHSBlock = Builder.GetInsertBlock();
6038 Builder.CreateBr(ContBlock);
6039
6040 CGF.EmitBlock(RHSBlock);
6041
6042 // If the top of the logical operator nest, update the MCDC bitmap for the
6043 // ConditionalOperator prior to visiting its LHS and RHS blocks, since they
6044 // may also contain a boolean expression.
6045 if (auto E = CGF.stripCond(condExpr); CGF.isMCDCDecisionExpr(E))
6047
6049 eval.begin(CGF);
6050 Value *RHS = Visit(rhsExpr);
6051 eval.end(CGF);
6052
6053 RHSBlock = Builder.GetInsertBlock();
6054 CGF.EmitBlock(ContBlock);
6055
6056 // If the LHS or RHS is a throw expression, it will be legitimately null.
6057 if (!LHS)
6058 return RHS;
6059 if (!RHS)
6060 return LHS;
6061
6062 // Create a PHI node for the real part.
6063 llvm::PHINode *PN = Builder.CreatePHI(LHS->getType(), 2, "cond");
6064 PN->addIncoming(LHS, LHSBlock);
6065 PN->addIncoming(RHS, RHSBlock);
6066
6067 return PN;
6068}
6069
6070Value *ScalarExprEmitter::VisitChooseExpr(ChooseExpr *E) {
6071 return Visit(E->getChosenSubExpr());
6072}
6073
6074Value *ScalarExprEmitter::VisitVAArgExpr(VAArgExpr *VE) {
6075 Address ArgValue = Address::invalid();
6076 RValue ArgPtr = CGF.EmitVAArg(VE, ArgValue);
6077
6078 return ArgPtr.getScalarVal();
6079}
6080
6081Value *ScalarExprEmitter::VisitBlockExpr(const BlockExpr *block) {
6082 return CGF.EmitBlockLiteral(block);
6083}
6084
6085// Convert a vec3 to vec4, or vice versa.
6087 Value *Src, unsigned NumElementsDst) {
6088 static constexpr int Mask[] = {0, 1, 2, -1};
6089 return Builder.CreateShuffleVector(Src, llvm::ArrayRef(Mask, NumElementsDst));
6090}
6091
6092// Create cast instructions for converting LLVM value \p Src to LLVM type \p
6093// DstTy. \p Src has the same size as \p DstTy. Both are single value types
6094// but could be scalar or vectors of different lengths, and either can be
6095// pointer.
6096// There are 4 cases:
6097// 1. non-pointer -> non-pointer : needs 1 bitcast
6098// 2. pointer -> pointer : needs 1 bitcast or addrspacecast
6099// 3. pointer -> non-pointer
6100// a) pointer -> intptr_t : needs 1 ptrtoint
6101// b) pointer -> non-intptr_t : needs 1 ptrtoint then 1 bitcast
6102// 4. non-pointer -> pointer
6103// a) intptr_t -> pointer : needs 1 inttoptr
6104// b) non-intptr_t -> pointer : needs 1 bitcast then 1 inttoptr
6105// Note: for cases 3b and 4b two casts are required since LLVM casts do not
6106// allow casting directly between pointer types and non-integer non-pointer
6107// types.
6109 const llvm::DataLayout &DL,
6110 Value *Src, llvm::Type *DstTy,
6111 StringRef Name = "") {
6112 auto SrcTy = Src->getType();
6113
6114 // Case 1.
6115 if (!SrcTy->isPointerTy() && !DstTy->isPointerTy())
6116 return Builder.CreateBitCast(Src, DstTy, Name);
6117
6118 // Case 2.
6119 if (SrcTy->isPointerTy() && DstTy->isPointerTy())
6120 return Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy, Name);
6121
6122 // Case 3.
6123 if (SrcTy->isPointerTy() && !DstTy->isPointerTy()) {
6124 // Case 3b.
6125 if (!DstTy->isIntegerTy())
6126 Src = Builder.CreatePtrToInt(Src, DL.getIntPtrType(SrcTy));
6127 // Cases 3a and 3b.
6128 return Builder.CreateBitOrPointerCast(Src, DstTy, Name);
6129 }
6130
6131 // Case 4b.
6132 if (!SrcTy->isIntegerTy())
6133 Src = Builder.CreateBitCast(Src, DL.getIntPtrType(DstTy));
6134 // Cases 4a and 4b.
6135 return Builder.CreateIntToPtr(Src, DstTy, Name);
6136}
6137
6138Value *ScalarExprEmitter::VisitAsTypeExpr(AsTypeExpr *E) {
6139 Value *Src = CGF.EmitScalarExpr(E->getSrcExpr());
6140 llvm::Type *DstTy = ConvertType(E->getType());
6141
6142 llvm::Type *SrcTy = Src->getType();
6143 unsigned NumElementsSrc =
6145 ? cast<llvm::FixedVectorType>(SrcTy)->getNumElements()
6146 : 0;
6147 unsigned NumElementsDst =
6149 ? cast<llvm::FixedVectorType>(DstTy)->getNumElements()
6150 : 0;
6151
6152 // Use bit vector expansion for ext_vector_type boolean vectors.
6153 if (E->getType()->isExtVectorBoolType())
6154 return CGF.emitBoolVecConversion(Src, NumElementsDst, "astype");
6155
6156 // Going from vec3 to non-vec3 is a special case and requires a shuffle
6157 // vector to get a vec4, then a bitcast if the target type is different.
6158 if (NumElementsSrc == 3 && NumElementsDst != 3) {
6159 Src = ConvertVec3AndVec4(Builder, CGF, Src, 4);
6160 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
6161 DstTy);
6162
6163 Src->setName("astype");
6164 return Src;
6165 }
6166
6167 // Going from non-vec3 to vec3 is a special case and requires a bitcast
6168 // to vec4 if the original type is not vec4, then a shuffle vector to
6169 // get a vec3.
6170 if (NumElementsSrc != 3 && NumElementsDst == 3) {
6171 auto *Vec4Ty = llvm::FixedVectorType::get(
6172 cast<llvm::VectorType>(DstTy)->getElementType(), 4);
6173 Src = createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(), Src,
6174 Vec4Ty);
6175
6176 Src = ConvertVec3AndVec4(Builder, CGF, Src, 3);
6177 Src->setName("astype");
6178 return Src;
6179 }
6180
6181 return createCastsForTypeOfSameSize(Builder, CGF.CGM.getDataLayout(),
6182 Src, DstTy, "astype");
6183}
6184
6185Value *ScalarExprEmitter::VisitAtomicExpr(AtomicExpr *E) {
6186 return CGF.EmitAtomicExpr(E).getScalarVal();
6187}
6188
6189//===----------------------------------------------------------------------===//
6190// Entry Point into this File
6191//===----------------------------------------------------------------------===//
6192
6193/// Emit the computation of the specified expression of scalar type, ignoring
6194/// the result.
6195Value *CodeGenFunction::EmitScalarExpr(const Expr *E, bool IgnoreResultAssign) {
6196 assert(E && hasScalarEvaluationKind(E->getType()) &&
6197 "Invalid scalar expression to emit");
6198
6199 return ScalarExprEmitter(*this, IgnoreResultAssign)
6200 .Visit(const_cast<Expr *>(E));
6201}
6202
6203/// Emit a conversion from the specified type to the specified destination type,
6204/// both of which are LLVM scalar types.
6206 QualType DstTy,
6207 SourceLocation Loc) {
6208 assert(hasScalarEvaluationKind(SrcTy) && hasScalarEvaluationKind(DstTy) &&
6209 "Invalid scalar expression to emit");
6210 return ScalarExprEmitter(*this).EmitScalarConversion(Src, SrcTy, DstTy, Loc);
6211}
6212
6213/// Emit a conversion from the specified complex type to the specified
6214/// destination type, where the destination type is an LLVM scalar type.
6216 QualType SrcTy,
6217 QualType DstTy,
6218 SourceLocation Loc) {
6219 assert(SrcTy->isAnyComplexType() && hasScalarEvaluationKind(DstTy) &&
6220 "Invalid complex -> scalar conversion");
6221 return ScalarExprEmitter(*this)
6222 .EmitComplexToScalarConversion(Src, SrcTy, DstTy, Loc);
6223}
6224
6225
6226Value *
6228 QualType PromotionType) {
6229 if (!PromotionType.isNull())
6230 return ScalarExprEmitter(*this).EmitPromoted(E, PromotionType);
6231 else
6232 return ScalarExprEmitter(*this).Visit(const_cast<Expr *>(E));
6233}
6234
6235
6238 bool isInc, bool isPre) {
6239 return ScalarExprEmitter(*this).EmitScalarPrePostIncDec(E, LV, isInc, isPre);
6240}
6241
6243 // object->isa or (*object).isa
6244 // Generate code as for: *(Class*)object
6245
6246 Expr *BaseExpr = E->getBase();
6248 if (BaseExpr->isPRValue()) {
6249 llvm::Type *BaseTy =
6251 Addr = Address(EmitScalarExpr(BaseExpr), BaseTy, getPointerAlign());
6252 } else {
6253 Addr = EmitLValue(BaseExpr).getAddress();
6254 }
6255
6256 // Cast the address to Class*.
6257 Addr = Addr.withElementType(ConvertType(E->getType()));
6258 return MakeAddrLValue(Addr, E->getType());
6259}
6260
6261
6263 const CompoundAssignOperator *E) {
6265 ScalarExprEmitter Scalar(*this);
6266 Value *Result = nullptr;
6267 switch (E->getOpcode()) {
6268#define COMPOUND_OP(Op) \
6269 case BO_##Op##Assign: \
6270 return Scalar.EmitCompoundAssignLValue(E, &ScalarExprEmitter::Emit##Op, \
6271 Result)
6272 COMPOUND_OP(Mul);
6273 COMPOUND_OP(Div);
6274 COMPOUND_OP(Rem);
6275 COMPOUND_OP(Add);
6276 COMPOUND_OP(Sub);
6277 COMPOUND_OP(Shl);
6278 COMPOUND_OP(Shr);
6280 COMPOUND_OP(Xor);
6281 COMPOUND_OP(Or);
6282#undef COMPOUND_OP
6283
6284 case BO_PtrMemD:
6285 case BO_PtrMemI:
6286 case BO_Mul:
6287 case BO_Div:
6288 case BO_Rem:
6289 case BO_Add:
6290 case BO_Sub:
6291 case BO_Shl:
6292 case BO_Shr:
6293 case BO_LT:
6294 case BO_GT:
6295 case BO_LE:
6296 case BO_GE:
6297 case BO_EQ:
6298 case BO_NE:
6299 case BO_Cmp:
6300 case BO_And:
6301 case BO_Xor:
6302 case BO_Or:
6303 case BO_LAnd:
6304 case BO_LOr:
6305 case BO_Assign:
6306 case BO_Comma:
6307 llvm_unreachable("Not valid compound assignment operators");
6308 }
6309
6310 llvm_unreachable("Unhandled compound assignment operator");
6311}
6312
6314 // The total (signed) byte offset for the GEP.
6315 llvm::Value *TotalOffset;
6316 // The offset overflow flag - true if the total offset overflows.
6317 llvm::Value *OffsetOverflows;
6318};
6319
6320/// Evaluate given GEPVal, which is either an inbounds GEP, or a constant,
6321/// and compute the total offset it applies from it's base pointer BasePtr.
6322/// Returns offset in bytes and a boolean flag whether an overflow happened
6323/// during evaluation.
6325 llvm::LLVMContext &VMContext,
6326 CodeGenModule &CGM,
6327 CGBuilderTy &Builder) {
6328 const auto &DL = CGM.getDataLayout();
6329
6330 // The total (signed) byte offset for the GEP.
6331 llvm::Value *TotalOffset = nullptr;
6332
6333 // Was the GEP already reduced to a constant?
6334 if (isa<llvm::Constant>(GEPVal)) {
6335 // Compute the offset by casting both pointers to integers and subtracting:
6336 // GEPVal = BasePtr + ptr(Offset) <--> Offset = int(GEPVal) - int(BasePtr)
6337 Value *BasePtr_int =
6338 Builder.CreatePtrToInt(BasePtr, DL.getIntPtrType(BasePtr->getType()));
6339 Value *GEPVal_int =
6340 Builder.CreatePtrToInt(GEPVal, DL.getIntPtrType(GEPVal->getType()));
6341 TotalOffset = Builder.CreateSub(GEPVal_int, BasePtr_int);
6342 return {TotalOffset, /*OffsetOverflows=*/Builder.getFalse()};
6343 }
6344
6345 auto *GEP = cast<llvm::GEPOperator>(GEPVal);
6346 assert(GEP->getPointerOperand() == BasePtr &&
6347 "BasePtr must be the base of the GEP.");
6348 assert(GEP->isInBounds() && "Expected inbounds GEP");
6349
6350 auto *IntPtrTy = DL.getIntPtrType(GEP->getPointerOperandType());
6351
6352 // Grab references to the signed add/mul overflow intrinsics for intptr_t.
6353 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
6354 auto *SAddIntrinsic =
6355 CGM.getIntrinsic(llvm::Intrinsic::sadd_with_overflow, IntPtrTy);
6356 auto *SMulIntrinsic =
6357 CGM.getIntrinsic(llvm::Intrinsic::smul_with_overflow, IntPtrTy);
6358
6359 // The offset overflow flag - true if the total offset overflows.
6360 llvm::Value *OffsetOverflows = Builder.getFalse();
6361
6362 /// Return the result of the given binary operation.
6363 auto eval = [&](BinaryOperator::Opcode Opcode, llvm::Value *LHS,
6364 llvm::Value *RHS) -> llvm::Value * {
6365 assert((Opcode == BO_Add || Opcode == BO_Mul) && "Can't eval binop");
6366
6367 // If the operands are constants, return a constant result.
6368 if (auto *LHSCI = dyn_cast<llvm::ConstantInt>(LHS)) {
6369 if (auto *RHSCI = dyn_cast<llvm::ConstantInt>(RHS)) {
6370 llvm::APInt N;
6371 bool HasOverflow = mayHaveIntegerOverflow(LHSCI, RHSCI, Opcode,
6372 /*Signed=*/true, N);
6373 if (HasOverflow)
6374 OffsetOverflows = Builder.getTrue();
6375 return llvm::ConstantInt::get(VMContext, N);
6376 }
6377 }
6378
6379 // Otherwise, compute the result with checked arithmetic.
6380 auto *ResultAndOverflow = Builder.CreateCall(
6381 (Opcode == BO_Add) ? SAddIntrinsic : SMulIntrinsic, {LHS, RHS});
6382 OffsetOverflows = Builder.CreateOr(
6383 Builder.CreateExtractValue(ResultAndOverflow, 1), OffsetOverflows);
6384 return Builder.CreateExtractValue(ResultAndOverflow, 0);
6385 };
6386
6387 // Determine the total byte offset by looking at each GEP operand.
6388 for (auto GTI = llvm::gep_type_begin(GEP), GTE = llvm::gep_type_end(GEP);
6389 GTI != GTE; ++GTI) {
6390 llvm::Value *LocalOffset;
6391 auto *Index = GTI.getOperand();
6392 // Compute the local offset contributed by this indexing step:
6393 if (auto *STy = GTI.getStructTypeOrNull()) {
6394 // For struct indexing, the local offset is the byte position of the
6395 // specified field.
6396 unsigned FieldNo = cast<llvm::ConstantInt>(Index)->getZExtValue();
6397 LocalOffset = llvm::ConstantInt::get(
6398 IntPtrTy, DL.getStructLayout(STy)->getElementOffset(FieldNo));
6399 } else {
6400 // Otherwise this is array-like indexing. The local offset is the index
6401 // multiplied by the element size.
6402 auto *ElementSize =
6403 llvm::ConstantInt::get(IntPtrTy, GTI.getSequentialElementStride(DL));
6404 auto *IndexS = Builder.CreateIntCast(Index, IntPtrTy, /*isSigned=*/true);
6405 LocalOffset = eval(BO_Mul, ElementSize, IndexS);
6406 }
6407
6408 // If this is the first offset, set it as the total offset. Otherwise, add
6409 // the local offset into the running total.
6410 if (!TotalOffset || TotalOffset == Zero)
6411 TotalOffset = LocalOffset;
6412 else
6413 TotalOffset = eval(BO_Add, TotalOffset, LocalOffset);
6414 }
6415
6416 return {TotalOffset, OffsetOverflows};
6417}
6418
6419Value *
6420CodeGenFunction::EmitCheckedInBoundsGEP(llvm::Type *ElemTy, Value *Ptr,
6421 ArrayRef<Value *> IdxList,
6422 bool SignedIndices, bool IsSubtraction,
6423 SourceLocation Loc, const Twine &Name) {
6424 llvm::Type *PtrTy = Ptr->getType();
6425
6426 llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::inBounds();
6427 if (!SignedIndices && !IsSubtraction)
6428 NWFlags |= llvm::GEPNoWrapFlags::noUnsignedWrap();
6429
6430 Value *GEPVal = Builder.CreateGEP(ElemTy, Ptr, IdxList, Name, NWFlags);
6431
6432 // If the pointer overflow sanitizer isn't enabled, do nothing.
6433 if (!SanOpts.has(SanitizerKind::PointerOverflow))
6434 return GEPVal;
6435
6436 // Perform nullptr-and-offset check unless the nullptr is defined.
6437 bool PerformNullCheck = !NullPointerIsDefined(
6438 Builder.GetInsertBlock()->getParent(), PtrTy->getPointerAddressSpace());
6439 // Check for overflows unless the GEP got constant-folded,
6440 // and only in the default address space
6441 bool PerformOverflowCheck =
6442 !isa<llvm::Constant>(GEPVal) && PtrTy->getPointerAddressSpace() == 0;
6443
6444 if (!(PerformNullCheck || PerformOverflowCheck))
6445 return GEPVal;
6446
6447 const auto &DL = CGM.getDataLayout();
6448
6449 auto CheckOrdinal = SanitizerKind::SO_PointerOverflow;
6450 auto CheckHandler = SanitizerHandler::PointerOverflow;
6451 SanitizerDebugLocation SanScope(this, {CheckOrdinal}, CheckHandler);
6452 llvm::Type *IntPtrTy = DL.getIntPtrType(PtrTy);
6453
6454 GEPOffsetAndOverflow EvaluatedGEP =
6455 EmitGEPOffsetInBytes(Ptr, GEPVal, getLLVMContext(), CGM, Builder);
6456
6457 assert((!isa<llvm::Constant>(EvaluatedGEP.TotalOffset) ||
6458 EvaluatedGEP.OffsetOverflows == Builder.getFalse()) &&
6459 "If the offset got constant-folded, we don't expect that there was an "
6460 "overflow.");
6461
6462 auto *Zero = llvm::ConstantInt::getNullValue(IntPtrTy);
6463
6464 // Common case: if the total offset is zero, don't emit a check.
6465 if (EvaluatedGEP.TotalOffset == Zero)
6466 return GEPVal;
6467
6468 // Now that we've computed the total offset, add it to the base pointer (with
6469 // wrapping semantics).
6470 auto *IntPtr = Builder.CreatePtrToInt(Ptr, IntPtrTy);
6471 auto *ComputedGEP = Builder.CreateAdd(IntPtr, EvaluatedGEP.TotalOffset);
6472
6473 llvm::SmallVector<std::pair<llvm::Value *, SanitizerKind::SanitizerOrdinal>,
6474 2>
6475 Checks;
6476
6477 if (PerformNullCheck) {
6478 // If the base pointer evaluates to a null pointer value,
6479 // the only valid pointer this inbounds GEP can produce is also
6480 // a null pointer, so the offset must also evaluate to zero.
6481 // Likewise, if we have non-zero base pointer, we can not get null pointer
6482 // as a result, so the offset can not be -intptr_t(BasePtr).
6483 // In other words, both pointers are either null, or both are non-null,
6484 // or the behaviour is undefined.
6485 auto *BaseIsNotNullptr = Builder.CreateIsNotNull(Ptr);
6486 auto *ResultIsNotNullptr = Builder.CreateIsNotNull(ComputedGEP);
6487 auto *Valid = Builder.CreateICmpEQ(BaseIsNotNullptr, ResultIsNotNullptr);
6488 Checks.emplace_back(Valid, CheckOrdinal);
6489 }
6490
6491 if (PerformOverflowCheck) {
6492 // The GEP is valid if:
6493 // 1) The total offset doesn't overflow, and
6494 // 2) The sign of the difference between the computed address and the base
6495 // pointer matches the sign of the total offset.
6496 llvm::Value *ValidGEP;
6497 auto *NoOffsetOverflow = Builder.CreateNot(EvaluatedGEP.OffsetOverflows);
6498 if (SignedIndices) {
6499 // GEP is computed as `unsigned base + signed offset`, therefore:
6500 // * If offset was positive, then the computed pointer can not be
6501 // [unsigned] less than the base pointer, unless it overflowed.
6502 // * If offset was negative, then the computed pointer can not be
6503 // [unsigned] greater than the bas pointere, unless it overflowed.
6504 auto *PosOrZeroValid = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
6505 auto *PosOrZeroOffset =
6506 Builder.CreateICmpSGE(EvaluatedGEP.TotalOffset, Zero);
6507 llvm::Value *NegValid = Builder.CreateICmpULT(ComputedGEP, IntPtr);
6508 ValidGEP =
6509 Builder.CreateSelect(PosOrZeroOffset, PosOrZeroValid, NegValid);
6510 } else if (!IsSubtraction) {
6511 // GEP is computed as `unsigned base + unsigned offset`, therefore the
6512 // computed pointer can not be [unsigned] less than base pointer,
6513 // unless there was an overflow.
6514 // Equivalent to `@llvm.uadd.with.overflow(%base, %offset)`.
6515 ValidGEP = Builder.CreateICmpUGE(ComputedGEP, IntPtr);
6516 } else {
6517 // GEP is computed as `unsigned base - unsigned offset`, therefore the
6518 // computed pointer can not be [unsigned] greater than base pointer,
6519 // unless there was an overflow.
6520 // Equivalent to `@llvm.usub.with.overflow(%base, sub(0, %offset))`.
6521 ValidGEP = Builder.CreateICmpULE(ComputedGEP, IntPtr);
6522 }
6523 ValidGEP = Builder.CreateAnd(ValidGEP, NoOffsetOverflow);
6524 Checks.emplace_back(ValidGEP, CheckOrdinal);
6525 }
6526
6527 assert(!Checks.empty() && "Should have produced some checks.");
6528
6529 llvm::Constant *StaticArgs[] = {EmitCheckSourceLocation(Loc)};
6530 // Pass the computed GEP to the runtime to avoid emitting poisoned arguments.
6531 llvm::Value *DynamicArgs[] = {IntPtr, ComputedGEP};
6532 EmitCheck(Checks, CheckHandler, StaticArgs, DynamicArgs);
6533
6534 return GEPVal;
6535}
6536
6538 Address Addr, ArrayRef<Value *> IdxList, llvm::Type *elementType,
6539 bool SignedIndices, bool IsSubtraction, SourceLocation Loc, CharUnits Align,
6540 const Twine &Name) {
6541 if (!SanOpts.has(SanitizerKind::PointerOverflow)) {
6542 llvm::GEPNoWrapFlags NWFlags = llvm::GEPNoWrapFlags::inBounds();
6543 if (!SignedIndices && !IsSubtraction)
6544 NWFlags |= llvm::GEPNoWrapFlags::noUnsignedWrap();
6545
6546 return Builder.CreateGEP(Addr, IdxList, elementType, Align, Name, NWFlags);
6547 }
6548
6549 return RawAddress(
6550 EmitCheckedInBoundsGEP(Addr.getElementType(), Addr.emitRawPointer(*this),
6551 IdxList, SignedIndices, IsSubtraction, Loc, Name),
6552 elementType, Align);
6553}
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:511
bool isLValue() const
Definition APValue.h:493
bool isInt() const
Definition APValue.h:488
bool isNullPointer() const
Definition APValue.cpp:1056
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
CanQualType FloatTy
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
QualType getVectorType(QualType VectorType, unsigned NumElts, VectorKind VecKind) const
Return the unique reference to a vector type of the specified element type and size.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
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:3047
QualType getElementType() const
Definition TypeBase.h:3833
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:6764
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:2214
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:743
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1112
bool getValue() const
Definition ExprCXX.h:4331
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:307
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1609
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h: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:7290
llvm::Value * EmitObjCSelectorExpr(const ObjCSelectorExpr *E)
Emit a selector.
Definition CGObjC.cpp:275
SanitizerSet SanOpts
Sanitizers enabled for this function.
static bool ContainsLabel(const Stmt *S, bool IgnoreCaseStmts=false)
ContainsLabel - Return true if the statement contains a label in it.
llvm::Value * EmitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E)
Definition CGObjC.cpp:269
llvm::BlockAddress * GetAddrOfLabel(const LabelDecl *L)
const CastExpr * CurCast
If a cast expression is being visited, this holds the current cast's expression.
static bool hasScalarEvaluationKind(QualType T)
llvm::Type * ConvertType(QualType T)
llvm::Value * EmitObjCProtocolExpr(const ObjCProtocolExpr *E)
Definition CGObjC.cpp:283
llvm::Value * EmitPointerAuthQualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType ValueType, Address StorageAddress, bool IsKnownNonNull)
void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint=true)
LValue EmitObjCIsaExpr(const ObjCIsaExpr *E)
void EmitStoreThroughBitfieldLValue(RValue Src, LValue Dst, llvm::Value **Result=nullptr)
EmitStoreThroughBitfieldLValue - Store Src into Dst with same constraints as EmitStoreThroughLValue.
Definition CGExpr.cpp:3054
llvm::Constant * EmitCheckSourceLocation(SourceLocation Loc)
Emit a description of a source location in a format suitable for passing to a runtime sanitizer handl...
Definition CGExpr.cpp:4063
llvm::Value * EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV, bool isInc, bool isPre)
RValue EmitVAArg(VAArgExpr *VE, Address &VAListAddr, AggValueSlot Slot=AggValueSlot::ignored())
Generate code to get an argument from the passed in pointer and update it accordingly.
Definition CGCall.cpp:6758
llvm::Value * getAsNaturalPointerTo(Address Addr, QualType PointeeType)
RValue EmitPseudoObjectRValue(const PseudoObjectExpr *e, AggValueSlot slot=AggValueSlot::ignored())
Definition CGExpr.cpp:7391
llvm::BasicBlock * createBasicBlock(const Twine &name="", llvm::Function *parent=nullptr, llvm::BasicBlock *before=nullptr)
createBasicBlock - Create an LLVM basic block.
void maybeUpdateMCDCTestVectorBitmap(const Expr *E)
Increment the profiler's counter for the given expression by StepV.
void EmitCXXDeleteExpr(const CXXDeleteExpr *E)
llvm::Value * EmitObjCArrayLiteral(const ObjCArrayLiteral *E)
Definition CGObjC.cpp:265
llvm::Value * EmitPromotedScalarExpr(const Expr *E, QualType PromotionType)
const LangOptions & getLangOpts() const
llvm::Value * EmitARCStoreStrong(LValue lvalue, llvm::Value *value, bool resultIgnored)
Store into a strong object.
Definition CGObjC.cpp:2577
bool isPointerKnownNonNull(const Expr *E)
Address GetAddressOfDerivedClass(Address Value, const CXXRecordDecl *Derived, CastExpr::path_const_iterator PathBegin, CastExpr::path_const_iterator PathEnd, bool NullCheckValue)
Definition CGClass.cpp:389
void EmitNullabilityCheck(LValue LHS, llvm::Value *RHS, SourceLocation Loc)
Given an assignment *LHS = RHS, emit a test that checks if RHS is nonnull, if LHS is marked _Nonnull.
Definition CGDecl.cpp:773
llvm::Value * EmitPointerAuthUnqualify(PointerAuthQualifier Qualifier, llvm::Value *Pointer, QualType PointerType, Address StorageAddress, bool IsKnownNonNull)
std::pair< RValue, llvm::Value * > EmitAtomicCompareExchange(LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc, llvm::AtomicOrdering Success=llvm::AtomicOrdering::SequentiallyConsistent, llvm::AtomicOrdering Failure=llvm::AtomicOrdering::SequentiallyConsistent, bool IsWeak=false, AggValueSlot Slot=AggValueSlot::ignored())
Emit a compare-and-exchange op for atomic type.
void EmitVTablePtrCheckForCast(QualType T, Address Derived, bool MayBeNull, CFITypeCheckKind TCK, SourceLocation Loc)
Derived is the presumed address of an object of type T after a cast.
Definition CGClass.cpp:2977
TypeCheckKind
Situations in which we might emit a check for the suitability of a pointer or glvalue.
@ TCK_DowncastPointer
Checking the operand of a static_cast to a derived pointer type.
@ TCK_Store
Checking the destination of a store. Must be suitably sized and aligned.
@ TCK_Load
Checking the operand of a load. Must be suitably sized and aligned.
llvm::Value * EmitCXXNewExpr(const CXXNewExpr *E)
bool hasSkipCounter(const Stmt *S) const
void EmitBitfieldConversionCheck(llvm::Value *Src, QualType SrcType, llvm::Value *Dst, QualType DstType, const CGBitFieldInfo &Info, SourceLocation Loc)
Emit a check that an [implicit] conversion of a bitfield.
std::pair< LValue, llvm::Value * > EmitARCStoreUnsafeUnretained(const BinaryOperator *e, bool ignored)
Definition CGObjC.cpp:3661
llvm::Constant * EmitCheckTypeDescriptor(QualType T)
Emit a description of a type in a format suitable for passing to a runtime sanitizer handler.
Definition CGExpr.cpp:3953
LValue EmitScalarCompoundAssignWithComplex(const CompoundAssignOperator *E, llvm::Value *&Result)
RawAddress CreateDefaultAlignTempAlloca(llvm::Type *Ty, const Twine &Name="tmp")
CreateDefaultAlignedTempAlloca - This creates an alloca with the default ABI alignment of the given L...
Definition CGExpr.cpp:183
const TargetInfo & getTarget() const
LValue EmitCompoundAssignmentLValue(const CompoundAssignOperator *E)
llvm::Value * EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty)
Definition CGObjC.cpp:3985
void EmitIgnoredExpr(const Expr *E)
EmitIgnoredExpr - Emit an expression in a context which ignores the result.
Definition CGExpr.cpp:259
RValue EmitCallExpr(const CallExpr *E, ReturnValueSlot ReturnValue=ReturnValueSlot(), llvm::CallBase **CallOrInvoke=nullptr)
Definition CGExpr.cpp:6482
RValue EmitLoadOfLValue(LValue V, SourceLocation Loc)
EmitLoadOfLValue - Given an expression that represents a value lvalue, this method emits the address ...
Definition CGExpr.cpp:2542
llvm::Value * EmitComplexToScalarConversion(ComplexPairTy Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified complex type to the specified destination type,...
static bool isInstrumentedCondition(const Expr *C)
isInstrumentedCondition - Determine whether the given condition is an instrumentable condition (i....
VlaSizePair getVLAElements1D(const VariableArrayType *vla)
Return the number of elements for a single dimension for the given array type.
RawAddress CreateIRTempWithoutCast(QualType T, const Twine &Name="tmp")
CreateIRTempWithoutCast - Create a temporary IR object of the given type, with appropriate alignment.
Definition CGExpr.cpp:190
llvm::Value * EmitObjCBoxedExpr(const ObjCBoxedExpr *E)
EmitObjCBoxedExpr - This routine generates code to call the appropriate expression boxing method.
Definition CGObjC.cpp:65
void EmitBoundsCheck(const Expr *ArrayExpr, const Expr *ArrayExprBase, llvm::Value *Index, QualType IndexType, bool Accessed)
Emit a check that Base points into an array object, which we can access at index Index.
Definition CGExpr.cpp:1285
llvm::Value * EvaluateExprAsBool(const Expr *E)
EvaluateExprAsBool - Perform the usual unary conversions on the specified expression and compare the ...
Definition CGExpr.cpp:240
void maybeResetMCDCCondBitmap(const Expr *E)
Zero-init the MCDC temp value.
RValue EmitCoyieldExpr(const CoyieldExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
void EmitCheck(ArrayRef< std::pair< llvm::Value *, SanitizerKind::SanitizerOrdinal > > Checked, SanitizerHandler Check, ArrayRef< llvm::Constant * > StaticArgs, ArrayRef< llvm::Value * > DynamicArgs, const TrapReason *TR=nullptr)
Create a basic block that will either trap or call a handler function in the UBSan runtime with the p...
Definition CGExpr.cpp:4211
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6435
llvm::Value * emitScalarConstant(const ConstantEmission &Constant, Expr *E)
Definition CGExpr.cpp:2067
llvm::Value * EmitARCRetainScalarExpr(const Expr *expr)
EmitARCRetainScalarExpr - Semantically equivalent to EmitARCRetainObject(e->getType(),...
Definition CGObjC.cpp:3525
llvm::Value * EmitBlockLiteral(const BlockExpr *)
Emit block literal.
Definition CGBlocks.cpp:764
llvm::Value * EmitToMemory(llvm::Value *Value, QualType Ty)
EmitToMemory - Change a scalar value from its value representation to its in-memory representation.
Definition CGExpr.cpp:2267
void maybeUpdateMCDCCondBitmap(const Expr *E, llvm::Value *Val)
Update the MCDC temp value with the condition's evaluated result.
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
Definition CGExpr.cpp:6421
ComplexPairTy EmitComplexExpr(const Expr *E, bool IgnoreReal=false, bool IgnoreImag=false)
EmitComplexExpr - Emit the computation of the specified expression of complex type,...
VlaSizePair getVLASize(const VariableArrayType *vla)
Returns an LLVM value that corresponds to the size, in non-variably-sized elements,...
llvm::CallInst * EmitNounwindRuntimeCall(llvm::FunctionCallee callee, const Twine &name="")
llvm::Value * EmitWithOriginalRHSBitfieldAssignment(const BinaryOperator *E, llvm::Value **Previous, QualType *SrcType)
Retrieve the implicit cast expression of the rhs in a binary operator expression by passing pointers ...
llvm::Value * EmitLoadOfScalar(Address Addr, bool Volatile, QualType Ty, SourceLocation Loc, AlignmentSource Source=AlignmentSource::Type, bool isNontemporal=false)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
static const Expr * stripCond(const Expr *C)
Ignore parentheses and logical-NOT to track conditions consistently.
void EmitStoreThroughLValue(RValue Src, LValue Dst, bool isInit=false)
EmitStoreThroughLValue - Store the specified rvalue into the specified lvalue, where both are guarant...
Definition CGExpr.cpp:2793
Address EmitArrayToPointerDecay(const Expr *Array, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr)
Definition CGExpr.cpp:4650
Address EmitCompoundStmt(const CompoundStmt &S, bool GetLast=false, AggValueSlot AVS=AggValueSlot::ignored())
EmitCompoundStmt - Emit a compound statement {..} node.
Definition CGStmt.cpp:565
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:7400
void EmitTypeCheck(TypeCheckKind TCK, SourceLocation Loc, LValue LV, QualType Type, SanitizerSet SkippedChecks=SanitizerSet(), llvm::Value *ArraySize=nullptr)
RValue EmitCoawaitExpr(const CoawaitExpr &E, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
llvm::Value * authPointerToPointerCast(llvm::Value *ResultPtr, QualType SourceType, QualType DestType)
Address EmitPointerWithAlignment(const Expr *Addr, LValueBaseInfo *BaseInfo=nullptr, TBAAAccessInfo *TBAAInfo=nullptr, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitPointerWithAlignment - Given an expression with a pointer type, emit the value and compute our be...
Definition CGExpr.cpp:1621
void EmitBranch(llvm::BasicBlock *Block)
EmitBranch - Emit a branch to the specified basic block from the current insert block,...
Definition CGStmt.cpp:668
LValue EmitCheckedLValue(const Expr *E, TypeCheckKind TCK)
Same as EmitLValue but additionally we generate checking code to guard against undefined behavior.
Definition CGExpr.cpp:1702
RawAddress CreateMemTemp(QualType T, const Twine &Name="tmp", RawAddress *Alloca=nullptr)
CreateMemTemp - Create a temporary memory object of the given type, with appropriate alignmen and cas...
Definition CGExpr.cpp:196
llvm::Type * convertTypeForLoadStore(QualType ASTTy, llvm::Type *LLVMTy=nullptr)
bool sanitizePerformTypeCheck() const
Whether any type-checking sanitizers are enabled.
Definition CGExpr.cpp:750
llvm::Value * EmitCheckedInBoundsGEP(llvm::Type *ElemTy, llvm::Value *Ptr, ArrayRef< llvm::Value * > IdxList, bool SignedIndices, bool IsSubtraction, SourceLocation Loc, const Twine &Name="")
Same as IRBuilder::CreateInBoundsGEP, but additionally emits a check to detect undefined behavior whe...
llvm::Value * EmitBuiltinAvailable(const VersionTuple &Version)
Definition CGObjC.cpp:4065
llvm::Value * EmitScalarExpr(const Expr *E, bool IgnoreResultAssign=false)
EmitScalarExpr - Emit the computation of the specified expression of LLVM scalar type,...
llvm::Value * EmitMatrixIndexExpr(const Expr *E)
Definition CGExpr.cpp:5220
LValue MakeAddrLValue(Address Addr, QualType T, AlignmentSource Source=AlignmentSource::Type)
void EmitTrapCheck(llvm::Value *Checked, SanitizerHandler CheckHandlerID, bool NoMerge=false, const TrapReason *TR=nullptr)
Create a basic block that will call the trap intrinsic, and emit a conditional branch to it,...
Definition CGExpr.cpp:4550
llvm::Value * LoadCXXThis()
LoadCXXThis - Load the value of 'this'.
llvm::Value * EmitFromMemory(llvm::Value *Value, QualType Ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
Definition CGExpr.cpp:2301
uint64_t getProfileCount(const Stmt *S)
Get the profiler's count for the given statement.
llvm::Value * getArrayInitIndex()
Get the index of the current ArrayInitLoopExpr, if any.
bool ConstantFoldsToSimpleInteger(const Expr *Cond, bool &Result, bool AllowLabels=false)
ConstantFoldsToSimpleInteger - If the specified expression does not fold to a constant,...
llvm::Value * EmitObjCStringLiteral(const ObjCStringLiteral *E)
Emits an instance of NSConstantString representing the object.
Definition CGObjC.cpp:52
void ErrorUnsupported(const Stmt *S, const char *Type)
ErrorUnsupported - Print out an error that codegen doesn't support the specified stmt yet.
std::pair< llvm::Value *, llvm::Value * > ComplexPairTy
ConstantEmission tryEmitAsConstant(const DeclRefExpr *RefExpr)
Try to emit a reference to the given value without producing it as an l-value.
Definition CGExpr.cpp:1964
LValue EmitLValue(const Expr *E, KnownNonNull_t IsKnownNonNull=NotKnownNonNull)
EmitLValue - Emit code to compute a designator that specifies the location of the expression.
Definition CGExpr.cpp:1737
llvm::Value * EmitARCExtendBlockObject(const Expr *expr)
Definition CGObjC.cpp:3556
void markStmtAsUsed(bool Skipped, const Stmt *S)
llvm::Value * EmitARCStoreWeak(Address addr, llvm::Value *value, bool ignored)
i8* @objc_storeWeak(i8** addr, i8* value) Returns value.
Definition CGObjC.cpp:2683
void EnsureInsertPoint()
EnsureInsertPoint - Ensure that an insertion point is defined so that emitted IR has a place to go.
ComplexPairTy EmitPromotedValue(ComplexPairTy result, QualType PromotionType)
void incrementProfileCounter(const Stmt *S, llvm::Value *StepV=nullptr)
Increment the profiler's counter for the given statement by StepV.
void emitAlignmentAssumption(llvm::Value *PtrValue, QualType Ty, SourceLocation Loc, SourceLocation AssumptionLoc, llvm::Value *Alignment, llvm::Value *OffsetValue=nullptr)
bool isMCDCDecisionExpr(const Expr *E) const
llvm::Value * EmitScalarConversion(llvm::Value *Src, QualType SrcTy, QualType DstTy, SourceLocation Loc)
Emit a conversion from the specified type to the specified destination type, both of which are LLVM s...
void EmitVariablyModifiedType(QualType Ty)
EmitVLASize - Capture all the sizes for the VLA expressions in the given variably-modified type and s...
static bool ShouldNullCheckClassCastValue(const CastExpr *Cast)
void EmitStoreOfScalar(llvm::Value *Value, Address Addr, bool Volatile, QualType Ty, AlignmentSource Source=AlignmentSource::Type, bool isInit=false, bool isNontemporal=false)
EmitStoreOfScalar - Store a scalar value to an address, taking care to appropriately convert from the...
llvm::Value * EmitDynamicCast(Address V, const CXXDynamicCastExpr *DCE)
void EmitBlock(llvm::BasicBlock *BB, bool IsFinished=false)
EmitBlock - Emit the given block.
Definition CGStmt.cpp:648
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:4486
unsigned mapRowMajorToColumnMajorFlattenedIndex(unsigned RowMajorIdx) const
Given a row-major flattened index RowMajorIdx, return the equivalent column-major flattened index.
Definition TypeBase.h:4545
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:5247
size_t getDataElementCount() const
Definition Expr.h:5163
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:3097
bool isEvaluatable(const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
isEvaluatable - Call EvaluateAsRValue to see if this expression can be constant folded without side-e...
bool isPRValue() const
Definition Expr.h:285
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3081
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
QualType getType() const
Definition Expr.h:144
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3289
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:5347
bool hadArrayRangeDesignator() const
Definition Expr.h:5495
const Expr * getInit(unsigned Init) const
Definition Expr.h:5369
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:4436
Expr * getBase() const
Definition Expr.h:3447
bool isArrow() const
Definition Expr.h:3554
VersionTuple getVersion() const
Definition ExprObjC.h:1759
ObjCIsaExpr - Represent X->isa and X.isa when X is an ObjC 'id' type.
Definition ExprObjC.h:1531
Expr * getBase() const
Definition ExprObjC.h:1556
SourceLocation getExprLoc() const LLVM_READONLY
Definition ExprObjC.h:1579
const ObjCMethodDecl * getMethodDecl() const
Definition ExprObjC.h:1397
QualType getReturnType() const
Definition DeclObjC.h:329
Represents a pointer to an Objective C object.
Definition TypeBase.h:8107
const ObjCObjectType * getObjectType() const
Gets the type pointed to by this ObjC pointer.
Definition TypeBase.h:8144
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:4638
const Expr * getSubExpr() const
Definition Expr.h:2205
Pointer-authentication qualifiers.
Definition TypeBase.h:153
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3393
A (possibly-)qualified type.
Definition TypeBase.h:938
PointerAuthQualifier getPointerAuth() const
Definition TypeBase.h:1469
bool mayBeDynamicClass() const
Returns true if it is a class and it might be dynamic.
Definition Type.cpp:167
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8489
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8674
QualType getCanonicalType() const
Definition TypeBase.h:8541
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:8546
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition TypeBase.h:362
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition TypeBase.h:365
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition TypeBase.h:368
void removePointerAuth()
Definition TypeBase.h:611
bool isSatisfied() const
Whether or not the requires clause is satisfied.
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:593
static constexpr SanitizerMask bitPosToMask(const unsigned Pos)
Create a mask with a bit enabled at position Pos.
Definition Sanitizers.h:59
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h: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:4514
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2291
SourceLocation getLocation() const
Definition Expr.h:5076
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:792
const llvm::fltSemantics & getBFloat16Format() const
Definition TargetInfo.h:802
const llvm::fltSemantics & getLongDoubleFormat() const
Definition TargetInfo.h:813
const llvm::fltSemantics & getFloat128Format() const
Definition TargetInfo.h:821
const llvm::fltSemantics & getIbm128Format() const
Definition TargetInfo.h:829
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8471
bool getBoolValue() const
Definition ExprCXX.h:2950
const APValue & getAPValue() const
Definition ExprCXX.h:2955
bool isStoredAsBoolean() const
Definition ExprCXX.h:2946
bool isVoidType() const
Definition TypeBase.h:9092
bool isBooleanType() const
Definition TypeBase.h:9229
bool isSignableType(const ASTContext &Ctx) const
Definition TypeBase.h:8738
bool isMFloat8Type() const
Definition TypeBase.h:9117
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:9136
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9386
bool isReferenceType() const
Definition TypeBase.h:8750
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:8869
bool isExtVectorBoolType() const
Definition TypeBase.h:8873
bool isOCLIntelSubgroupAVCType() const
Definition TypeBase.h:9011
bool isBuiltinType() const
Helper methods to distinguish type categories.
Definition TypeBase.h:8849
RecordDecl * castAsRecordDecl() const
Definition Type.h:48
bool isAnyComplexType() const
Definition TypeBase.h:8861
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9152
bool isHalfType() const
Definition TypeBase.h:9096
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:8982
bool isMatrixType() const
Definition TypeBase.h:8889
bool isEventT() const
Definition TypeBase.h:8974
bool isFunctionType() const
Definition TypeBase.h:8722
bool isVectorType() const
Definition TypeBase.h:8865
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:2993
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
bool isNullPtrType() const
Definition TypeBase.h:9129
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:5581
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:4065
Represents a GCC generic vector type.
Definition TypeBase.h:4274
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:272
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:1525
bool Load(InterpState &S, CodePtr OpPC)
Definition Interp.h:2230
bool GE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1540
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:906
const FunctionProtoType * T
@ Off
Never emit colors regardless of the output stream.
CastKind
CastKind - The kind of operation required for a conversion.
U cast(CodeGen::Address addr)
Definition Address.h:327
unsigned long uint64_t
long int64_t
Diagnostic wrappers for TextAPI types for error reporting.
Definition Dominators.h:30
cl::opt< bool > EnableSingleByteCoverage
#define false
Definition stdbool.h:26
#define true
Definition stdbool.h:25
llvm::Value * TotalOffset
llvm::Value * OffsetOverflows
Structure with information about how a bitfield should be accessed.
unsigned Size
The total size of the bit-field, in bits.
llvm::IntegerType * Int8Ty
i8, i16, i32, and i64
llvm::Type * HalfTy
half, bfloat, float, double
static TBAAAccessInfo getMayAliasInfo()
Definition CodeGenTBAA.h:63
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h: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