Coverage Report

Created: 2024-01-17 10:31

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