Coverage Report

Created: 2022-01-18 06:27

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