Coverage Report

Created: 2019-07-24 05:18

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