Coverage Report

Created: 2020-02-15 09:57

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