Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/AST/Expr.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- Expr.cpp - Expression AST Node Implementation --------------------===//
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 file implements the Expr class and subclasses.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/Expr.h"
14
#include "clang/AST/APValue.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/Attr.h"
17
#include "clang/AST/ComputeDependence.h"
18
#include "clang/AST/DeclCXX.h"
19
#include "clang/AST/DeclObjC.h"
20
#include "clang/AST/DeclTemplate.h"
21
#include "clang/AST/DependenceFlags.h"
22
#include "clang/AST/EvaluatedExprVisitor.h"
23
#include "clang/AST/ExprCXX.h"
24
#include "clang/AST/IgnoreExpr.h"
25
#include "clang/AST/Mangle.h"
26
#include "clang/AST/RecordLayout.h"
27
#include "clang/AST/StmtVisitor.h"
28
#include "clang/Basic/Builtins.h"
29
#include "clang/Basic/CharInfo.h"
30
#include "clang/Basic/SourceManager.h"
31
#include "clang/Basic/TargetInfo.h"
32
#include "clang/Lex/Lexer.h"
33
#include "clang/Lex/LiteralSupport.h"
34
#include "clang/Lex/Preprocessor.h"
35
#include "llvm/Support/ErrorHandling.h"
36
#include "llvm/Support/Format.h"
37
#include "llvm/Support/raw_ostream.h"
38
#include <algorithm>
39
#include <cstring>
40
#include <optional>
41
using namespace clang;
42
43
0
const Expr *Expr::getBestDynamicClassTypeExpr() const {
44
0
  const Expr *E = this;
45
0
  while (true) {
46
0
    E = E->IgnoreParenBaseCasts();
47
48
    // Follow the RHS of a comma operator.
49
0
    if (auto *BO = dyn_cast<BinaryOperator>(E)) {
50
0
      if (BO->getOpcode() == BO_Comma) {
51
0
        E = BO->getRHS();
52
0
        continue;
53
0
      }
54
0
    }
55
56
    // Step into initializer for materialized temporaries.
57
0
    if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E)) {
58
0
      E = MTE->getSubExpr();
59
0
      continue;
60
0
    }
61
62
0
    break;
63
0
  }
64
65
0
  return E;
66
0
}
67
68
0
const CXXRecordDecl *Expr::getBestDynamicClassType() const {
69
0
  const Expr *E = getBestDynamicClassTypeExpr();
70
0
  QualType DerivedType = E->getType();
71
0
  if (const PointerType *PTy = DerivedType->getAs<PointerType>())
72
0
    DerivedType = PTy->getPointeeType();
73
74
0
  if (DerivedType->isDependentType())
75
0
    return nullptr;
76
77
0
  const RecordType *Ty = DerivedType->castAs<RecordType>();
78
0
  Decl *D = Ty->getDecl();
79
0
  return cast<CXXRecordDecl>(D);
80
0
}
81
82
const Expr *Expr::skipRValueSubobjectAdjustments(
83
    SmallVectorImpl<const Expr *> &CommaLHSs,
84
16
    SmallVectorImpl<SubobjectAdjustment> &Adjustments) const {
85
16
  const Expr *E = this;
86
16
  while (true) {
87
16
    E = E->IgnoreParens();
88
89
16
    if (const CastExpr *CE = dyn_cast<CastExpr>(E)) {
90
9
      if ((CE->getCastKind() == CK_DerivedToBase ||
91
9
           CE->getCastKind() == CK_UncheckedDerivedToBase) &&
92
9
          E->getType()->isRecordType()) {
93
0
        E = CE->getSubExpr();
94
0
        auto *Derived =
95
0
            cast<CXXRecordDecl>(E->getType()->castAs<RecordType>()->getDecl());
96
0
        Adjustments.push_back(SubobjectAdjustment(CE, Derived));
97
0
        continue;
98
0
      }
99
100
9
      if (CE->getCastKind() == CK_NoOp) {
101
0
        E = CE->getSubExpr();
102
0
        continue;
103
0
      }
104
9
    } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
105
0
      if (!ME->isArrow()) {
106
0
        assert(ME->getBase()->getType()->isRecordType());
107
0
        if (FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
108
0
          if (!Field->isBitField() && !Field->getType()->isReferenceType()) {
109
0
            E = ME->getBase();
110
0
            Adjustments.push_back(SubobjectAdjustment(Field));
111
0
            continue;
112
0
          }
113
0
        }
114
0
      }
115
7
    } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
116
0
      if (BO->getOpcode() == BO_PtrMemD) {
117
0
        assert(BO->getRHS()->isPRValue());
118
0
        E = BO->getLHS();
119
0
        const MemberPointerType *MPT =
120
0
          BO->getRHS()->getType()->getAs<MemberPointerType>();
121
0
        Adjustments.push_back(SubobjectAdjustment(MPT, BO->getRHS()));
122
0
        continue;
123
0
      }
124
0
      if (BO->getOpcode() == BO_Comma) {
125
0
        CommaLHSs.push_back(BO->getLHS());
126
0
        E = BO->getRHS();
127
0
        continue;
128
0
      }
129
0
    }
130
131
    // Nothing changed.
132
16
    break;
133
16
  }
134
16
  return E;
135
16
}
136
137
0
bool Expr::isKnownToHaveBooleanValue(bool Semantic) const {
138
0
  const Expr *E = IgnoreParens();
139
140
  // If this value has _Bool type, it is obvious 0/1.
141
0
  if (E->getType()->isBooleanType()) return true;
142
  // If this is a non-scalar-integer type, we don't care enough to try.
143
0
  if (!E->getType()->isIntegralOrEnumerationType()) return false;
144
145
0
  if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
146
0
    switch (UO->getOpcode()) {
147
0
    case UO_Plus:
148
0
      return UO->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
149
0
    case UO_LNot:
150
0
      return true;
151
0
    default:
152
0
      return false;
153
0
    }
154
0
  }
155
156
  // Only look through implicit casts.  If the user writes
157
  // '(int) (a && b)' treat it as an arbitrary int.
158
  // FIXME: Should we look through any cast expression in !Semantic mode?
159
0
  if (const ImplicitCastExpr *CE = dyn_cast<ImplicitCastExpr>(E))
160
0
    return CE->getSubExpr()->isKnownToHaveBooleanValue(Semantic);
161
162
0
  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
163
0
    switch (BO->getOpcode()) {
164
0
    default: return false;
165
0
    case BO_LT:   // Relational operators.
166
0
    case BO_GT:
167
0
    case BO_LE:
168
0
    case BO_GE:
169
0
    case BO_EQ:   // Equality operators.
170
0
    case BO_NE:
171
0
    case BO_LAnd: // AND operator.
172
0
    case BO_LOr:  // Logical OR operator.
173
0
      return true;
174
175
0
    case BO_And:  // Bitwise AND operator.
176
0
    case BO_Xor:  // Bitwise XOR operator.
177
0
    case BO_Or:   // Bitwise OR operator.
178
      // Handle things like (x==2)|(y==12).
179
0
      return BO->getLHS()->isKnownToHaveBooleanValue(Semantic) &&
180
0
             BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
181
182
0
    case BO_Comma:
183
0
    case BO_Assign:
184
0
      return BO->getRHS()->isKnownToHaveBooleanValue(Semantic);
185
0
    }
186
0
  }
187
188
0
  if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E))
189
0
    return CO->getTrueExpr()->isKnownToHaveBooleanValue(Semantic) &&
190
0
           CO->getFalseExpr()->isKnownToHaveBooleanValue(Semantic);
191
192
0
  if (isa<ObjCBoolLiteralExpr>(E))
193
0
    return true;
194
195
0
  if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
196
0
    return OVE->getSourceExpr()->isKnownToHaveBooleanValue(Semantic);
197
198
0
  if (const FieldDecl *FD = E->getSourceBitField())
199
0
    if (!Semantic && FD->getType()->isUnsignedIntegerType() &&
200
0
        !FD->getBitWidth()->isValueDependent() &&
201
0
        FD->getBitWidthValue(FD->getASTContext()) == 1)
202
0
      return true;
203
204
0
  return false;
205
0
}
206
207
bool Expr::isFlexibleArrayMemberLike(
208
    ASTContext &Ctx,
209
    LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
210
0
    bool IgnoreTemplateOrMacroSubstitution) const {
211
0
  const Expr *E = IgnoreParens();
212
0
  const Decl *D = nullptr;
213
214
0
  if (const auto *ME = dyn_cast<MemberExpr>(E))
215
0
    D = ME->getMemberDecl();
216
0
  else if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
217
0
    D = DRE->getDecl();
218
0
  else if (const auto *IRE = dyn_cast<ObjCIvarRefExpr>(E))
219
0
    D = IRE->getDecl();
220
221
0
  return Decl::isFlexibleArrayMemberLike(Ctx, D, E->getType(),
222
0
                                         StrictFlexArraysLevel,
223
0
                                         IgnoreTemplateOrMacroSubstitution);
224
0
}
225
226
const ValueDecl *
227
0
Expr::getAsBuiltinConstantDeclRef(const ASTContext &Context) const {
228
0
  Expr::EvalResult Eval;
229
230
0
  if (EvaluateAsConstantExpr(Eval, Context)) {
231
0
    APValue &Value = Eval.Val;
232
233
0
    if (Value.isMemberPointer())
234
0
      return Value.getMemberPointerDecl();
235
236
0
    if (Value.isLValue() && Value.getLValueOffset().isZero())
237
0
      return Value.getLValueBase().dyn_cast<const ValueDecl *>();
238
0
  }
239
240
0
  return nullptr;
241
0
}
242
243
// Amusing macro metaprogramming hack: check whether a class provides
244
// a more specific implementation of getExprLoc().
245
//
246
// See also Stmt.cpp:{getBeginLoc(),getEndLoc()}.
247
namespace {
248
  /// This implementation is used when a class provides a custom
249
  /// implementation of getExprLoc.
250
  template <class E, class T>
251
  SourceLocation getExprLocImpl(const Expr *expr,
252
3
                                SourceLocation (T::*v)() const) {
253
3
    return static_cast<const E*>(expr)->getExprLoc();
254
3
  }
Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::UnaryOperator, clang::UnaryOperator>(clang::Expr const*, clang::SourceLocation (clang::UnaryOperator::*)() const)
Line
Count
Source
252
1
                                SourceLocation (T::*v)() const) {
253
1
    return static_cast<const E*>(expr)->getExprLoc();
254
1
  }
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::PseudoObjectExpr, clang::PseudoObjectExpr>(clang::Expr const*, clang::SourceLocation (clang::PseudoObjectExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::UnresolvedMemberExpr, clang::UnresolvedMemberExpr>(clang::Expr const*, clang::SourceLocation (clang::UnresolvedMemberExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::OpaqueValueExpr, clang::OpaqueValueExpr>(clang::Expr const*, clang::SourceLocation (clang::OpaqueValueExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCIsaExpr, clang::ObjCIsaExpr>(clang::Expr const*, clang::SourceLocation (clang::ObjCIsaExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCIndirectCopyRestoreExpr, clang::ObjCIndirectCopyRestoreExpr>(clang::Expr const*, clang::SourceLocation (clang::ObjCIndirectCopyRestoreExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::OMPArraySectionExpr, clang::OMPArraySectionExpr>(clang::Expr const*, clang::SourceLocation (clang::OMPArraySectionExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::MemberExpr, clang::MemberExpr>(clang::Expr const*, clang::SourceLocation (clang::MemberExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::MatrixSubscriptExpr, clang::MatrixSubscriptExpr>(clang::Expr const*, clang::SourceLocation (clang::MatrixSubscriptExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::MSPropertySubscriptExpr, clang::MSPropertySubscriptExpr>(clang::Expr const*, clang::SourceLocation (clang::MSPropertySubscriptExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ConceptSpecializationExpr, clang::ConceptSpecializationExpr>(clang::Expr const*, clang::SourceLocation (clang::ConceptSpecializationExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXOperatorCallExpr, clang::CXXOperatorCallExpr>(clang::Expr const*, clang::SourceLocation (clang::CXXOperatorCallExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXMemberCallExpr, clang::CXXMemberCallExpr>(clang::Expr const*, clang::SourceLocation (clang::CXXMemberCallExpr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXRewrittenBinaryOperator, clang::CXXRewrittenBinaryOperator>(clang::Expr const*, clang::SourceLocation (clang::CXXRewrittenBinaryOperator::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXDefaultArgExpr, clang::CXXDefaultArgExpr>(clang::Expr const*, clang::SourceLocation (clang::CXXDefaultArgExpr::*)() const)
Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::BinaryOperator, clang::BinaryOperator>(clang::Expr const*, clang::SourceLocation (clang::BinaryOperator::*)() const)
Line
Count
Source
252
2
                                SourceLocation (T::*v)() const) {
253
2
    return static_cast<const E*>(expr)->getExprLoc();
254
2
  }
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CompoundAssignOperator, clang::BinaryOperator>(clang::Expr const*, clang::SourceLocation (clang::BinaryOperator::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ArraySubscriptExpr, clang::ArraySubscriptExpr>(clang::Expr const*, clang::SourceLocation (clang::ArraySubscriptExpr::*)() const)
255
256
  /// This implementation is used when a class doesn't provide
257
  /// a custom implementation of getExprLoc.  Overload resolution
258
  /// should pick it over the implementation above because it's
259
  /// more specialized according to function template partial ordering.
260
  template <class E>
261
  SourceLocation getExprLocImpl(const Expr *expr,
262
39
                                SourceLocation (Expr::*v)() const) {
263
39
    return static_cast<const E *>(expr)->getBeginLoc();
264
39
  }
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::VAArgExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::UnaryExprOrTypeTraitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::TypoExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::TypeTraitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::SubstNonTypeTemplateParmPackExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::SubstNonTypeTemplateParmExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::StringLiteral>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::StmtExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::SourceLocExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::SizeOfPackExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ShuffleVectorExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::SYCLUniqueStableNameExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::RequiresExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::RecoveryExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Line
Count
Source
262
10
                                SourceLocation (Expr::*v)() const) {
263
10
    return static_cast<const E *>(expr)->getBeginLoc();
264
10
  }
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::PredefinedExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ParenListExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ParenExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::PackExpansionExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::UnresolvedLookupExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::OffsetOfExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCSubscriptRefExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCStringLiteral>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCSelectorExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCProtocolExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCPropertyRefExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCMessageExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCIvarRefExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCEncodeExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCDictionaryLiteral>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCBoxedExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCBoolLiteralExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCAvailabilityCheckExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCArrayLiteral>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::OMPIteratorExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::OMPArrayShapingExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::NoInitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::MaterializeTemporaryExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::MSPropertyRefExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::LambdaExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::IntegerLiteral>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Line
Count
Source
262
10
                                SourceLocation (Expr::*v)() const) {
263
10
    return static_cast<const E *>(expr)->getBeginLoc();
264
10
  }
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::InitListExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ImplicitValueInitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ImaginaryLiteral>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::GenericSelectionExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::GNUNullExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::FunctionParmPackExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ExprWithCleanups>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ConstantExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::FloatingLiteral>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::FixedPointLiteral>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ExtVectorElementExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ExpressionTraitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::DesignatedInitUpdateExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::DesignatedInitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::DependentScopeDeclRefExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::DependentCoawaitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::DeclRefExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Line
Count
Source
262
13
                                SourceLocation (Expr::*v)() const) {
263
13
    return static_cast<const E *>(expr)->getBeginLoc();
264
13
  }
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CoyieldExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CoawaitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ConvertVectorExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CompoundLiteralExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ChooseExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CharacterLiteral>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ImplicitCastExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Line
Count
Source
262
4
                                SourceLocation (Expr::*v)() const) {
263
4
    return static_cast<const E *>(expr)->getBeginLoc();
264
4
  }
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ObjCBridgedCastExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXStaticCastExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXReinterpretCastExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXDynamicCastExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXConstCastExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXAddrspaceCastExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXFunctionalCastExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CStyleCastExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::BuiltinBitCastExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CallExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::UserDefinedLiteral>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CUDAKernelCallExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXUuidofExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXUnresolvedConstructExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXTypeidExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXThrowExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXThisExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXStdInitializerListExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXScalarValueInitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXPseudoDestructorExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXParenListInitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXNullPtrLiteralExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXNoexceptExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXNewExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXInheritedCtorInitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXFoldExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXDependentScopeMemberExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXDeleteExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXDefaultInitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXConstructExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXTemporaryObjectExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXBoolLiteralExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::CXXBindTemporaryExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::BlockExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Line
Count
Source
262
2
                                SourceLocation (Expr::*v)() const) {
263
2
    return static_cast<const E *>(expr)->getBeginLoc();
264
2
  }
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::AtomicExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::AsTypeExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ArrayTypeTraitExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ArrayInitLoopExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ArrayInitIndexExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::AddrLabelExpr>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::ConditionalOperator>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
Unexecuted instantiation: Expr.cpp:clang::SourceLocation (anonymous namespace)::getExprLocImpl<clang::BinaryConditionalOperator>(clang::Expr const*, clang::SourceLocation (clang::Expr::*)() const)
265
}
266
267
42
SourceLocation Expr::getExprLoc() const {
268
42
  switch (getStmtClass()) {
269
0
  case Stmt::NoStmtClass: llvm_unreachable("statement without class");
270
0
#define ABSTRACT_STMT(type)
271
0
#define STMT(type, base) \
272
0
  case Stmt::type##Class: break;
273
0
#define EXPR(type, base) \
274
42
  case Stmt::type##Class: return getExprLocImpl<type>(this, &type::getExprLoc);
275
42
#include "clang/AST/StmtNodes.inc"
276
42
  }
277
0
  llvm_unreachable("unknown expression kind");
278
0
}
279
280
//===----------------------------------------------------------------------===//
281
// Primary Expressions.
282
//===----------------------------------------------------------------------===//
283
284
8
static void AssertResultStorageKind(ConstantResultStorageKind Kind) {
285
8
  assert((Kind == ConstantResultStorageKind::APValue ||
286
8
          Kind == ConstantResultStorageKind::Int64 ||
287
8
          Kind == ConstantResultStorageKind::None) &&
288
8
         "Invalid StorageKind Value");
289
0
  (void)Kind;
290
8
}
291
292
16
ConstantResultStorageKind ConstantExpr::getStorageKind(const APValue &Value) {
293
16
  switch (Value.getKind()) {
294
4
  case APValue::None:
295
4
  case APValue::Indeterminate:
296
4
    return ConstantResultStorageKind::None;
297
12
  case APValue::Int:
298
12
    if (!Value.getInt().needsCleanup())
299
12
      return ConstantResultStorageKind::Int64;
300
12
    [[fallthrough]];
301
0
  default:
302
0
    return ConstantResultStorageKind::APValue;
303
16
  }
304
16
}
305
306
ConstantResultStorageKind
307
0
ConstantExpr::getStorageKind(const Type *T, const ASTContext &Context) {
308
0
  if (T->isIntegralOrEnumerationType() && Context.getTypeInfo(T).Width <= 64)
309
0
    return ConstantResultStorageKind::Int64;
310
0
  return ConstantResultStorageKind::APValue;
311
0
}
312
313
ConstantExpr::ConstantExpr(Expr *SubExpr, ConstantResultStorageKind StorageKind,
314
                           bool IsImmediateInvocation)
315
8
    : FullExpr(ConstantExprClass, SubExpr) {
316
8
  ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);
317
8
  ConstantExprBits.APValueKind = APValue::None;
318
8
  ConstantExprBits.IsUnsigned = false;
319
8
  ConstantExprBits.BitWidth = 0;
320
8
  ConstantExprBits.HasCleanup = false;
321
8
  ConstantExprBits.IsImmediateInvocation = IsImmediateInvocation;
322
323
8
  if (StorageKind == ConstantResultStorageKind::APValue)
324
0
    ::new (getTrailingObjects<APValue>()) APValue();
325
8
}
326
327
ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
328
                                   ConstantResultStorageKind StorageKind,
329
8
                                   bool IsImmediateInvocation) {
330
8
  assert(!isa<ConstantExpr>(E));
331
0
  AssertResultStorageKind(StorageKind);
332
333
8
  unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
334
8
      StorageKind == ConstantResultStorageKind::APValue,
335
8
      StorageKind == ConstantResultStorageKind::Int64);
336
8
  void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
337
8
  return new (Mem) ConstantExpr(E, StorageKind, IsImmediateInvocation);
338
8
}
339
340
ConstantExpr *ConstantExpr::Create(const ASTContext &Context, Expr *E,
341
8
                                   const APValue &Result) {
342
8
  ConstantResultStorageKind StorageKind = getStorageKind(Result);
343
8
  ConstantExpr *Self = Create(Context, E, StorageKind);
344
8
  Self->SetResult(Result, Context);
345
8
  return Self;
346
8
}
347
348
ConstantExpr::ConstantExpr(EmptyShell Empty,
349
                           ConstantResultStorageKind StorageKind)
350
0
    : FullExpr(ConstantExprClass, Empty) {
351
0
  ConstantExprBits.ResultKind = llvm::to_underlying(StorageKind);
352
353
0
  if (StorageKind == ConstantResultStorageKind::APValue)
354
0
    ::new (getTrailingObjects<APValue>()) APValue();
355
0
}
356
357
ConstantExpr *ConstantExpr::CreateEmpty(const ASTContext &Context,
358
0
                                        ConstantResultStorageKind StorageKind) {
359
0
  AssertResultStorageKind(StorageKind);
360
361
0
  unsigned Size = totalSizeToAlloc<APValue, uint64_t>(
362
0
      StorageKind == ConstantResultStorageKind::APValue,
363
0
      StorageKind == ConstantResultStorageKind::Int64);
364
0
  void *Mem = Context.Allocate(Size, alignof(ConstantExpr));
365
0
  return new (Mem) ConstantExpr(EmptyShell(), StorageKind);
366
0
}
367
368
8
void ConstantExpr::MoveIntoResult(APValue &Value, const ASTContext &Context) {
369
8
  assert((unsigned)getStorageKind(Value) <= ConstantExprBits.ResultKind &&
370
8
         "Invalid storage for this value kind");
371
0
  ConstantExprBits.APValueKind = Value.getKind();
372
8
  switch (getResultStorageKind()) {
373
2
  case ConstantResultStorageKind::None:
374
2
    return;
375
6
  case ConstantResultStorageKind::Int64:
376
6
    Int64Result() = *Value.getInt().getRawData();
377
6
    ConstantExprBits.BitWidth = Value.getInt().getBitWidth();
378
6
    ConstantExprBits.IsUnsigned = Value.getInt().isUnsigned();
379
6
    return;
380
0
  case ConstantResultStorageKind::APValue:
381
0
    if (!ConstantExprBits.HasCleanup && Value.needsCleanup()) {
382
0
      ConstantExprBits.HasCleanup = true;
383
0
      Context.addDestruction(&APValueResult());
384
0
    }
385
0
    APValueResult() = std::move(Value);
386
0
    return;
387
8
  }
388
0
  llvm_unreachable("Invalid ResultKind Bits");
389
0
}
390
391
0
llvm::APSInt ConstantExpr::getResultAsAPSInt() const {
392
0
  switch (getResultStorageKind()) {
393
0
  case ConstantResultStorageKind::APValue:
394
0
    return APValueResult().getInt();
395
0
  case ConstantResultStorageKind::Int64:
396
0
    return llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
397
0
                        ConstantExprBits.IsUnsigned);
398
0
  default:
399
0
    llvm_unreachable("invalid Accessor");
400
0
  }
401
0
}
402
403
0
APValue ConstantExpr::getAPValueResult() const {
404
405
0
  switch (getResultStorageKind()) {
406
0
  case ConstantResultStorageKind::APValue:
407
0
    return APValueResult();
408
0
  case ConstantResultStorageKind::Int64:
409
0
    return APValue(
410
0
        llvm::APSInt(llvm::APInt(ConstantExprBits.BitWidth, Int64Result()),
411
0
                     ConstantExprBits.IsUnsigned));
412
0
  case ConstantResultStorageKind::None:
413
0
    if (ConstantExprBits.APValueKind == APValue::Indeterminate)
414
0
      return APValue::IndeterminateValue();
415
0
    return APValue();
416
0
  }
417
0
  llvm_unreachable("invalid ResultKind");
418
0
}
419
420
DeclRefExpr::DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
421
                         bool RefersToEnclosingVariableOrCapture, QualType T,
422
                         ExprValueKind VK, SourceLocation L,
423
                         const DeclarationNameLoc &LocInfo,
424
                         NonOdrUseReason NOUR)
425
0
    : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D), DNLoc(LocInfo) {
426
0
  DeclRefExprBits.HasQualifier = false;
427
0
  DeclRefExprBits.HasTemplateKWAndArgsInfo = false;
428
0
  DeclRefExprBits.HasFoundDecl = false;
429
0
  DeclRefExprBits.HadMultipleCandidates = false;
430
0
  DeclRefExprBits.RefersToEnclosingVariableOrCapture =
431
0
      RefersToEnclosingVariableOrCapture;
432
0
  DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
433
0
  DeclRefExprBits.NonOdrUseReason = NOUR;
434
0
  DeclRefExprBits.IsImmediateEscalating = false;
435
0
  DeclRefExprBits.Loc = L;
436
0
  setDependence(computeDependence(this, Ctx));
437
0
}
438
439
DeclRefExpr::DeclRefExpr(const ASTContext &Ctx,
440
                         NestedNameSpecifierLoc QualifierLoc,
441
                         SourceLocation TemplateKWLoc, ValueDecl *D,
442
                         bool RefersToEnclosingVariableOrCapture,
443
                         const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
444
                         const TemplateArgumentListInfo *TemplateArgs,
445
                         QualType T, ExprValueKind VK, NonOdrUseReason NOUR)
446
    : Expr(DeclRefExprClass, T, VK, OK_Ordinary), D(D),
447
59
      DNLoc(NameInfo.getInfo()) {
448
59
  DeclRefExprBits.Loc = NameInfo.getLoc();
449
59
  DeclRefExprBits.HasQualifier = QualifierLoc ? 1 : 0;
450
59
  if (QualifierLoc)
451
0
    new (getTrailingObjects<NestedNameSpecifierLoc>())
452
0
        NestedNameSpecifierLoc(QualifierLoc);
453
59
  DeclRefExprBits.HasFoundDecl = FoundD ? 1 : 0;
454
59
  if (FoundD)
455
0
    *getTrailingObjects<NamedDecl *>() = FoundD;
456
59
  DeclRefExprBits.HasTemplateKWAndArgsInfo
457
59
    = (TemplateArgs || TemplateKWLoc.isValid()) ? 1 : 0;
458
59
  DeclRefExprBits.RefersToEnclosingVariableOrCapture =
459
59
      RefersToEnclosingVariableOrCapture;
460
59
  DeclRefExprBits.CapturedByCopyInLambdaWithExplicitObjectParameter = false;
461
59
  DeclRefExprBits.NonOdrUseReason = NOUR;
462
59
  if (TemplateArgs) {
463
0
    auto Deps = TemplateArgumentDependence::None;
464
0
    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
465
0
        TemplateKWLoc, *TemplateArgs, getTrailingObjects<TemplateArgumentLoc>(),
466
0
        Deps);
467
0
    assert(!(Deps & TemplateArgumentDependence::Dependent) &&
468
0
           "built a DeclRefExpr with dependent template args");
469
59
  } else if (TemplateKWLoc.isValid()) {
470
0
    getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
471
0
        TemplateKWLoc);
472
0
  }
473
0
  DeclRefExprBits.IsImmediateEscalating = false;
474
59
  DeclRefExprBits.HadMultipleCandidates = 0;
475
59
  setDependence(computeDependence(this, Ctx));
476
59
}
477
478
DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
479
                                 NestedNameSpecifierLoc QualifierLoc,
480
                                 SourceLocation TemplateKWLoc, ValueDecl *D,
481
                                 bool RefersToEnclosingVariableOrCapture,
482
                                 SourceLocation NameLoc, QualType T,
483
                                 ExprValueKind VK, NamedDecl *FoundD,
484
                                 const TemplateArgumentListInfo *TemplateArgs,
485
0
                                 NonOdrUseReason NOUR) {
486
0
  return Create(Context, QualifierLoc, TemplateKWLoc, D,
487
0
                RefersToEnclosingVariableOrCapture,
488
0
                DeclarationNameInfo(D->getDeclName(), NameLoc),
489
0
                T, VK, FoundD, TemplateArgs, NOUR);
490
0
}
491
492
DeclRefExpr *DeclRefExpr::Create(const ASTContext &Context,
493
                                 NestedNameSpecifierLoc QualifierLoc,
494
                                 SourceLocation TemplateKWLoc, ValueDecl *D,
495
                                 bool RefersToEnclosingVariableOrCapture,
496
                                 const DeclarationNameInfo &NameInfo,
497
                                 QualType T, ExprValueKind VK,
498
                                 NamedDecl *FoundD,
499
                                 const TemplateArgumentListInfo *TemplateArgs,
500
59
                                 NonOdrUseReason NOUR) {
501
  // Filter out cases where the found Decl is the same as the value refenenced.
502
59
  if (D == FoundD)
503
59
    FoundD = nullptr;
504
505
59
  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
506
59
  std::size_t Size =
507
59
      totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
508
59
                       ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
509
59
          QualifierLoc ? 1 : 0, FoundD ? 1 : 0,
510
59
          HasTemplateKWAndArgsInfo ? 1 : 0,
511
59
          TemplateArgs ? TemplateArgs->size() : 0);
512
513
59
  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
514
59
  return new (Mem) DeclRefExpr(Context, QualifierLoc, TemplateKWLoc, D,
515
59
                               RefersToEnclosingVariableOrCapture, NameInfo,
516
59
                               FoundD, TemplateArgs, T, VK, NOUR);
517
59
}
518
519
DeclRefExpr *DeclRefExpr::CreateEmpty(const ASTContext &Context,
520
                                      bool HasQualifier,
521
                                      bool HasFoundDecl,
522
                                      bool HasTemplateKWAndArgsInfo,
523
0
                                      unsigned NumTemplateArgs) {
524
0
  assert(NumTemplateArgs == 0 || HasTemplateKWAndArgsInfo);
525
0
  std::size_t Size =
526
0
      totalSizeToAlloc<NestedNameSpecifierLoc, NamedDecl *,
527
0
                       ASTTemplateKWAndArgsInfo, TemplateArgumentLoc>(
528
0
          HasQualifier ? 1 : 0, HasFoundDecl ? 1 : 0, HasTemplateKWAndArgsInfo,
529
0
          NumTemplateArgs);
530
0
  void *Mem = Context.Allocate(Size, alignof(DeclRefExpr));
531
0
  return new (Mem) DeclRefExpr(EmptyShell());
532
0
}
533
534
0
void DeclRefExpr::setDecl(ValueDecl *NewD) {
535
0
  D = NewD;
536
0
  if (getType()->isUndeducedType())
537
0
    setType(NewD->getType());
538
0
  setDependence(computeDependence(this, NewD->getASTContext()));
539
0
}
540
541
89
SourceLocation DeclRefExpr::getBeginLoc() const {
542
89
  if (hasQualifier())
543
0
    return getQualifierLoc().getBeginLoc();
544
89
  return getNameInfo().getBeginLoc();
545
89
}
546
57
SourceLocation DeclRefExpr::getEndLoc() const {
547
57
  if (hasExplicitTemplateArgs())
548
0
    return getRAngleLoc();
549
57
  return getNameInfo().getEndLoc();
550
57
}
551
552
SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(SourceLocation OpLoc,
553
                                                   SourceLocation LParen,
554
                                                   SourceLocation RParen,
555
                                                   QualType ResultTy,
556
                                                   TypeSourceInfo *TSI)
557
    : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary),
558
0
      OpLoc(OpLoc), LParen(LParen), RParen(RParen) {
559
0
  setTypeSourceInfo(TSI);
560
0
  setDependence(computeDependence(this));
561
0
}
562
563
SYCLUniqueStableNameExpr::SYCLUniqueStableNameExpr(EmptyShell Empty,
564
                                                   QualType ResultTy)
565
0
    : Expr(SYCLUniqueStableNameExprClass, ResultTy, VK_PRValue, OK_Ordinary) {}
566
567
SYCLUniqueStableNameExpr *
568
SYCLUniqueStableNameExpr::Create(const ASTContext &Ctx, SourceLocation OpLoc,
569
                                 SourceLocation LParen, SourceLocation RParen,
570
0
                                 TypeSourceInfo *TSI) {
571
0
  QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
572
0
  return new (Ctx)
573
0
      SYCLUniqueStableNameExpr(OpLoc, LParen, RParen, ResultTy, TSI);
574
0
}
575
576
SYCLUniqueStableNameExpr *
577
0
SYCLUniqueStableNameExpr::CreateEmpty(const ASTContext &Ctx) {
578
0
  QualType ResultTy = Ctx.getPointerType(Ctx.CharTy.withConst());
579
0
  return new (Ctx) SYCLUniqueStableNameExpr(EmptyShell(), ResultTy);
580
0
}
581
582
0
std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context) const {
583
0
  return SYCLUniqueStableNameExpr::ComputeName(Context,
584
0
                                               getTypeSourceInfo()->getType());
585
0
}
586
587
std::string SYCLUniqueStableNameExpr::ComputeName(ASTContext &Context,
588
0
                                                  QualType Ty) {
589
0
  auto MangleCallback = [](ASTContext &Ctx,
590
0
                           const NamedDecl *ND) -> std::optional<unsigned> {
591
0
    if (const auto *RD = dyn_cast<CXXRecordDecl>(ND))
592
0
      return RD->getDeviceLambdaManglingNumber();
593
0
    return std::nullopt;
594
0
  };
595
596
0
  std::unique_ptr<MangleContext> Ctx{ItaniumMangleContext::create(
597
0
      Context, Context.getDiagnostics(), MangleCallback)};
598
599
0
  std::string Buffer;
600
0
  Buffer.reserve(128);
601
0
  llvm::raw_string_ostream Out(Buffer);
602
0
  Ctx->mangleCanonicalTypeName(Ty, Out);
603
604
0
  return Out.str();
605
0
}
606
607
PredefinedExpr::PredefinedExpr(SourceLocation L, QualType FNTy,
608
                               PredefinedIdentKind IK, bool IsTransparent,
609
                               StringLiteral *SL)
610
0
    : Expr(PredefinedExprClass, FNTy, VK_LValue, OK_Ordinary) {
611
0
  PredefinedExprBits.Kind = llvm::to_underlying(IK);
612
0
  assert((getIdentKind() == IK) &&
613
0
         "IdentKind do not fit in PredefinedExprBitfields!");
614
0
  bool HasFunctionName = SL != nullptr;
615
0
  PredefinedExprBits.HasFunctionName = HasFunctionName;
616
0
  PredefinedExprBits.IsTransparent = IsTransparent;
617
0
  PredefinedExprBits.Loc = L;
618
0
  if (HasFunctionName)
619
0
    setFunctionName(SL);
620
0
  setDependence(computeDependence(this));
621
0
}
622
623
PredefinedExpr::PredefinedExpr(EmptyShell Empty, bool HasFunctionName)
624
0
    : Expr(PredefinedExprClass, Empty) {
625
0
  PredefinedExprBits.HasFunctionName = HasFunctionName;
626
0
}
627
628
PredefinedExpr *PredefinedExpr::Create(const ASTContext &Ctx, SourceLocation L,
629
                                       QualType FNTy, PredefinedIdentKind IK,
630
0
                                       bool IsTransparent, StringLiteral *SL) {
631
0
  bool HasFunctionName = SL != nullptr;
632
0
  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
633
0
                           alignof(PredefinedExpr));
634
0
  return new (Mem) PredefinedExpr(L, FNTy, IK, IsTransparent, SL);
635
0
}
636
637
PredefinedExpr *PredefinedExpr::CreateEmpty(const ASTContext &Ctx,
638
0
                                            bool HasFunctionName) {
639
0
  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(HasFunctionName),
640
0
                           alignof(PredefinedExpr));
641
0
  return new (Mem) PredefinedExpr(EmptyShell(), HasFunctionName);
642
0
}
643
644
0
StringRef PredefinedExpr::getIdentKindName(PredefinedIdentKind IK) {
645
0
  switch (IK) {
646
0
  case PredefinedIdentKind::Func:
647
0
    return "__func__";
648
0
  case PredefinedIdentKind::Function:
649
0
    return "__FUNCTION__";
650
0
  case PredefinedIdentKind::FuncDName:
651
0
    return "__FUNCDNAME__";
652
0
  case PredefinedIdentKind::LFunction:
653
0
    return "L__FUNCTION__";
654
0
  case PredefinedIdentKind::PrettyFunction:
655
0
    return "__PRETTY_FUNCTION__";
656
0
  case PredefinedIdentKind::FuncSig:
657
0
    return "__FUNCSIG__";
658
0
  case PredefinedIdentKind::LFuncSig:
659
0
    return "L__FUNCSIG__";
660
0
  case PredefinedIdentKind::PrettyFunctionNoVirtual:
661
0
    break;
662
0
  }
663
0
  llvm_unreachable("Unknown ident kind for PredefinedExpr");
664
0
}
665
666
// FIXME: Maybe this should use DeclPrinter with a special "print predefined
667
// expr" policy instead.
668
std::string PredefinedExpr::ComputeName(PredefinedIdentKind IK,
669
0
                                        const Decl *CurrentDecl) {
670
0
  ASTContext &Context = CurrentDecl->getASTContext();
671
672
0
  if (IK == PredefinedIdentKind::FuncDName) {
673
0
    if (const NamedDecl *ND = dyn_cast<NamedDecl>(CurrentDecl)) {
674
0
      std::unique_ptr<MangleContext> MC;
675
0
      MC.reset(Context.createMangleContext());
676
677
0
      if (MC->shouldMangleDeclName(ND)) {
678
0
        SmallString<256> Buffer;
679
0
        llvm::raw_svector_ostream Out(Buffer);
680
0
        GlobalDecl GD;
681
0
        if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(ND))
682
0
          GD = GlobalDecl(CD, Ctor_Base);
683
0
        else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(ND))
684
0
          GD = GlobalDecl(DD, Dtor_Base);
685
0
        else if (ND->hasAttr<CUDAGlobalAttr>())
686
0
          GD = GlobalDecl(cast<FunctionDecl>(ND));
687
0
        else
688
0
          GD = GlobalDecl(ND);
689
0
        MC->mangleName(GD, Out);
690
691
0
        if (!Buffer.empty() && Buffer.front() == '\01')
692
0
          return std::string(Buffer.substr(1));
693
0
        return std::string(Buffer.str());
694
0
      }
695
0
      return std::string(ND->getIdentifier()->getName());
696
0
    }
697
0
    return "";
698
0
  }
699
0
  if (isa<BlockDecl>(CurrentDecl)) {
700
    // For blocks we only emit something if it is enclosed in a function
701
    // For top-level block we'd like to include the name of variable, but we
702
    // don't have it at this point.
703
0
    auto DC = CurrentDecl->getDeclContext();
704
0
    if (DC->isFileContext())
705
0
      return "";
706
707
0
    SmallString<256> Buffer;
708
0
    llvm::raw_svector_ostream Out(Buffer);
709
0
    if (auto *DCBlock = dyn_cast<BlockDecl>(DC))
710
      // For nested blocks, propagate up to the parent.
711
0
      Out << ComputeName(IK, DCBlock);
712
0
    else if (auto *DCDecl = dyn_cast<Decl>(DC))
713
0
      Out << ComputeName(IK, DCDecl) << "_block_invoke";
714
0
    return std::string(Out.str());
715
0
  }
716
0
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(CurrentDecl)) {
717
0
    if (IK != PredefinedIdentKind::PrettyFunction &&
718
0
        IK != PredefinedIdentKind::PrettyFunctionNoVirtual &&
719
0
        IK != PredefinedIdentKind::FuncSig &&
720
0
        IK != PredefinedIdentKind::LFuncSig)
721
0
      return FD->getNameAsString();
722
723
0
    SmallString<256> Name;
724
0
    llvm::raw_svector_ostream Out(Name);
725
726
0
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
727
0
      if (MD->isVirtual() && IK != PredefinedIdentKind::PrettyFunctionNoVirtual)
728
0
        Out << "virtual ";
729
0
      if (MD->isStatic())
730
0
        Out << "static ";
731
0
    }
732
733
0
    class PrettyCallbacks final : public PrintingCallbacks {
734
0
    public:
735
0
      PrettyCallbacks(const LangOptions &LO) : LO(LO) {}
736
0
      std::string remapPath(StringRef Path) const override {
737
0
        SmallString<128> p(Path);
738
0
        LO.remapPathPrefix(p);
739
0
        return std::string(p);
740
0
      }
741
742
0
    private:
743
0
      const LangOptions &LO;
744
0
    };
745
0
    PrintingPolicy Policy(Context.getLangOpts());
746
0
    PrettyCallbacks PrettyCB(Context.getLangOpts());
747
0
    Policy.Callbacks = &PrettyCB;
748
0
    std::string Proto;
749
0
    llvm::raw_string_ostream POut(Proto);
750
751
0
    const FunctionDecl *Decl = FD;
752
0
    if (const FunctionDecl* Pattern = FD->getTemplateInstantiationPattern())
753
0
      Decl = Pattern;
754
0
    const FunctionType *AFT = Decl->getType()->getAs<FunctionType>();
755
0
    const FunctionProtoType *FT = nullptr;
756
0
    if (FD->hasWrittenPrototype())
757
0
      FT = dyn_cast<FunctionProtoType>(AFT);
758
759
0
    if (IK == PredefinedIdentKind::FuncSig ||
760
0
        IK == PredefinedIdentKind::LFuncSig) {
761
0
      switch (AFT->getCallConv()) {
762
0
      case CC_C: POut << "__cdecl "; break;
763
0
      case CC_X86StdCall: POut << "__stdcall "; break;
764
0
      case CC_X86FastCall: POut << "__fastcall "; break;
765
0
      case CC_X86ThisCall: POut << "__thiscall "; break;
766
0
      case CC_X86VectorCall: POut << "__vectorcall "; break;
767
0
      case CC_X86RegCall: POut << "__regcall "; break;
768
      // Only bother printing the conventions that MSVC knows about.
769
0
      default: break;
770
0
      }
771
0
    }
772
773
0
    FD->printQualifiedName(POut, Policy);
774
775
0
    POut << "(";
776
0
    if (FT) {
777
0
      for (unsigned i = 0, e = Decl->getNumParams(); i != e; ++i) {
778
0
        if (i) POut << ", ";
779
0
        POut << Decl->getParamDecl(i)->getType().stream(Policy);
780
0
      }
781
782
0
      if (FT->isVariadic()) {
783
0
        if (FD->getNumParams()) POut << ", ";
784
0
        POut << "...";
785
0
      } else if ((IK == PredefinedIdentKind::FuncSig ||
786
0
                  IK == PredefinedIdentKind::LFuncSig ||
787
0
                  !Context.getLangOpts().CPlusPlus) &&
788
0
                 !Decl->getNumParams()) {
789
0
        POut << "void";
790
0
      }
791
0
    }
792
0
    POut << ")";
793
794
0
    if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
795
0
      assert(FT && "We must have a written prototype in this case.");
796
0
      if (FT->isConst())
797
0
        POut << " const";
798
0
      if (FT->isVolatile())
799
0
        POut << " volatile";
800
0
      RefQualifierKind Ref = MD->getRefQualifier();
801
0
      if (Ref == RQ_LValue)
802
0
        POut << " &";
803
0
      else if (Ref == RQ_RValue)
804
0
        POut << " &&";
805
0
    }
806
807
0
    typedef SmallVector<const ClassTemplateSpecializationDecl *, 8> SpecsTy;
808
0
    SpecsTy Specs;
809
0
    const DeclContext *Ctx = FD->getDeclContext();
810
0
    while (Ctx && isa<NamedDecl>(Ctx)) {
811
0
      const ClassTemplateSpecializationDecl *Spec
812
0
                               = dyn_cast<ClassTemplateSpecializationDecl>(Ctx);
813
0
      if (Spec && !Spec->isExplicitSpecialization())
814
0
        Specs.push_back(Spec);
815
0
      Ctx = Ctx->getParent();
816
0
    }
817
818
0
    std::string TemplateParams;
819
0
    llvm::raw_string_ostream TOut(TemplateParams);
820
0
    for (const ClassTemplateSpecializationDecl *D : llvm::reverse(Specs)) {
821
0
      const TemplateParameterList *Params =
822
0
          D->getSpecializedTemplate()->getTemplateParameters();
823
0
      const TemplateArgumentList &Args = D->getTemplateArgs();
824
0
      assert(Params->size() == Args.size());
825
0
      for (unsigned i = 0, numParams = Params->size(); i != numParams; ++i) {
826
0
        StringRef Param = Params->getParam(i)->getName();
827
0
        if (Param.empty()) continue;
828
0
        TOut << Param << " = ";
829
0
        Args.get(i).print(Policy, TOut,
830
0
                          TemplateParameterList::shouldIncludeTypeForArgument(
831
0
                              Policy, Params, i));
832
0
        TOut << ", ";
833
0
      }
834
0
    }
835
836
0
    FunctionTemplateSpecializationInfo *FSI
837
0
                                          = FD->getTemplateSpecializationInfo();
838
0
    if (FSI && !FSI->isExplicitSpecialization()) {
839
0
      const TemplateParameterList* Params
840
0
                                  = FSI->getTemplate()->getTemplateParameters();
841
0
      const TemplateArgumentList* Args = FSI->TemplateArguments;
842
0
      assert(Params->size() == Args->size());
843
0
      for (unsigned i = 0, e = Params->size(); i != e; ++i) {
844
0
        StringRef Param = Params->getParam(i)->getName();
845
0
        if (Param.empty()) continue;
846
0
        TOut << Param << " = ";
847
0
        Args->get(i).print(Policy, TOut, /*IncludeType*/ true);
848
0
        TOut << ", ";
849
0
      }
850
0
    }
851
852
0
    TOut.flush();
853
0
    if (!TemplateParams.empty()) {
854
      // remove the trailing comma and space
855
0
      TemplateParams.resize(TemplateParams.size() - 2);
856
0
      POut << " [" << TemplateParams << "]";
857
0
    }
858
859
0
    POut.flush();
860
861
    // Print "auto" for all deduced return types. This includes C++1y return
862
    // type deduction and lambdas. For trailing return types resolve the
863
    // decltype expression. Otherwise print the real type when this is
864
    // not a constructor or destructor.
865
0
    if (isa<CXXMethodDecl>(FD) &&
866
0
         cast<CXXMethodDecl>(FD)->getParent()->isLambda())
867
0
      Proto = "auto " + Proto;
868
0
    else if (FT && FT->getReturnType()->getAs<DecltypeType>())
869
0
      FT->getReturnType()
870
0
          ->getAs<DecltypeType>()
871
0
          ->getUnderlyingType()
872
0
          .getAsStringInternal(Proto, Policy);
873
0
    else if (!isa<CXXConstructorDecl>(FD) && !isa<CXXDestructorDecl>(FD))
874
0
      AFT->getReturnType().getAsStringInternal(Proto, Policy);
875
876
0
    Out << Proto;
877
878
0
    return std::string(Name);
879
0
  }
880
0
  if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(CurrentDecl)) {
881
0
    for (const DeclContext *DC = CD->getParent(); DC; DC = DC->getParent())
882
      // Skip to its enclosing function or method, but not its enclosing
883
      // CapturedDecl.
884
0
      if (DC->isFunctionOrMethod() && (DC->getDeclKind() != Decl::Captured)) {
885
0
        const Decl *D = Decl::castFromDeclContext(DC);
886
0
        return ComputeName(IK, D);
887
0
      }
888
0
    llvm_unreachable("CapturedDecl not inside a function or method");
889
0
  }
890
0
  if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurrentDecl)) {
891
0
    SmallString<256> Name;
892
0
    llvm::raw_svector_ostream Out(Name);
893
0
    Out << (MD->isInstanceMethod() ? '-' : '+');
894
0
    Out << '[';
895
896
    // For incorrect code, there might not be an ObjCInterfaceDecl.  Do
897
    // a null check to avoid a crash.
898
0
    if (const ObjCInterfaceDecl *ID = MD->getClassInterface())
899
0
      Out << *ID;
900
901
0
    if (const ObjCCategoryImplDecl *CID =
902
0
        dyn_cast<ObjCCategoryImplDecl>(MD->getDeclContext()))
903
0
      Out << '(' << *CID << ')';
904
905
0
    Out <<  ' ';
906
0
    MD->getSelector().print(Out);
907
0
    Out <<  ']';
908
909
0
    return std::string(Name);
910
0
  }
911
0
  if (isa<TranslationUnitDecl>(CurrentDecl) &&
912
0
      IK == PredefinedIdentKind::PrettyFunction) {
913
    // __PRETTY_FUNCTION__ -> "top level", the others produce an empty string.
914
0
    return "top level";
915
0
  }
916
0
  return "";
917
0
}
918
919
void APNumericStorage::setIntValue(const ASTContext &C,
920
48
                                   const llvm::APInt &Val) {
921
48
  if (hasAllocation())
922
0
    C.Deallocate(pVal);
923
924
48
  BitWidth = Val.getBitWidth();
925
48
  unsigned NumWords = Val.getNumWords();
926
48
  const uint64_t* Words = Val.getRawData();
927
48
  if (NumWords > 1) {
928
0
    pVal = new (C) uint64_t[NumWords];
929
0
    std::copy(Words, Words + NumWords, pVal);
930
48
  } else if (NumWords == 1)
931
48
    VAL = Words[0];
932
0
  else
933
0
    VAL = 0;
934
48
}
935
936
IntegerLiteral::IntegerLiteral(const ASTContext &C, const llvm::APInt &V,
937
                               QualType type, SourceLocation l)
938
47
    : Expr(IntegerLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l) {
939
47
  assert(type->isIntegerType() && "Illegal type in IntegerLiteral");
940
0
  assert(V.getBitWidth() == C.getIntWidth(type) &&
941
47
         "Integer type is not the correct size for constant.");
942
0
  setValue(C, V);
943
47
  setDependence(ExprDependence::None);
944
47
}
945
946
IntegerLiteral *
947
IntegerLiteral::Create(const ASTContext &C, const llvm::APInt &V,
948
47
                       QualType type, SourceLocation l) {
949
47
  return new (C) IntegerLiteral(C, V, type, l);
950
47
}
951
952
IntegerLiteral *
953
0
IntegerLiteral::Create(const ASTContext &C, EmptyShell Empty) {
954
0
  return new (C) IntegerLiteral(Empty);
955
0
}
956
957
FixedPointLiteral::FixedPointLiteral(const ASTContext &C, const llvm::APInt &V,
958
                                     QualType type, SourceLocation l,
959
                                     unsigned Scale)
960
    : Expr(FixedPointLiteralClass, type, VK_PRValue, OK_Ordinary), Loc(l),
961
0
      Scale(Scale) {
962
0
  assert(type->isFixedPointType() && "Illegal type in FixedPointLiteral");
963
0
  assert(V.getBitWidth() == C.getTypeInfo(type).Width &&
964
0
         "Fixed point type is not the correct size for constant.");
965
0
  setValue(C, V);
966
0
  setDependence(ExprDependence::None);
967
0
}
968
969
FixedPointLiteral *FixedPointLiteral::CreateFromRawInt(const ASTContext &C,
970
                                                       const llvm::APInt &V,
971
                                                       QualType type,
972
                                                       SourceLocation l,
973
0
                                                       unsigned Scale) {
974
0
  return new (C) FixedPointLiteral(C, V, type, l, Scale);
975
0
}
976
977
FixedPointLiteral *FixedPointLiteral::Create(const ASTContext &C,
978
0
                                             EmptyShell Empty) {
979
0
  return new (C) FixedPointLiteral(Empty);
980
0
}
981
982
0
std::string FixedPointLiteral::getValueAsString(unsigned Radix) const {
983
  // Currently the longest decimal number that can be printed is the max for an
984
  // unsigned long _Accum: 4294967295.99999999976716935634613037109375
985
  // which is 43 characters.
986
0
  SmallString<64> S;
987
0
  FixedPointValueToString(
988
0
      S, llvm::APSInt::getUnsigned(getValue().getZExtValue()), Scale);
989
0
  return std::string(S.str());
990
0
}
991
992
void CharacterLiteral::print(unsigned Val, CharacterLiteralKind Kind,
993
0
                             raw_ostream &OS) {
994
0
  switch (Kind) {
995
0
  case CharacterLiteralKind::Ascii:
996
0
    break; // no prefix.
997
0
  case CharacterLiteralKind::Wide:
998
0
    OS << 'L';
999
0
    break;
1000
0
  case CharacterLiteralKind::UTF8:
1001
0
    OS << "u8";
1002
0
    break;
1003
0
  case CharacterLiteralKind::UTF16:
1004
0
    OS << 'u';
1005
0
    break;
1006
0
  case CharacterLiteralKind::UTF32:
1007
0
    OS << 'U';
1008
0
    break;
1009
0
  }
1010
1011
0
  StringRef Escaped = escapeCStyle<EscapeChar::Single>(Val);
1012
0
  if (!Escaped.empty()) {
1013
0
    OS << "'" << Escaped << "'";
1014
0
  } else {
1015
    // A character literal might be sign-extended, which
1016
    // would result in an invalid \U escape sequence.
1017
    // FIXME: multicharacter literals such as '\xFF\xFF\xFF\xFF'
1018
    // are not correctly handled.
1019
0
    if ((Val & ~0xFFu) == ~0xFFu && Kind == CharacterLiteralKind::Ascii)
1020
0
      Val &= 0xFFu;
1021
0
    if (Val < 256 && isPrintable((unsigned char)Val))
1022
0
      OS << "'" << (char)Val << "'";
1023
0
    else if (Val < 256)
1024
0
      OS << "'\\x" << llvm::format("%02x", Val) << "'";
1025
0
    else if (Val <= 0xFFFF)
1026
0
      OS << "'\\u" << llvm::format("%04x", Val) << "'";
1027
0
    else
1028
0
      OS << "'\\U" << llvm::format("%08x", Val) << "'";
1029
0
  }
1030
0
}
1031
1032
FloatingLiteral::FloatingLiteral(const ASTContext &C, const llvm::APFloat &V,
1033
                                 bool isexact, QualType Type, SourceLocation L)
1034
1
    : Expr(FloatingLiteralClass, Type, VK_PRValue, OK_Ordinary), Loc(L) {
1035
1
  setSemantics(V.getSemantics());
1036
1
  FloatingLiteralBits.IsExact = isexact;
1037
1
  setValue(C, V);
1038
1
  setDependence(ExprDependence::None);
1039
1
}
1040
1041
FloatingLiteral::FloatingLiteral(const ASTContext &C, EmptyShell Empty)
1042
0
  : Expr(FloatingLiteralClass, Empty) {
1043
0
  setRawSemantics(llvm::APFloatBase::S_IEEEhalf);
1044
0
  FloatingLiteralBits.IsExact = false;
1045
0
}
1046
1047
FloatingLiteral *
1048
FloatingLiteral::Create(const ASTContext &C, const llvm::APFloat &V,
1049
1
                        bool isexact, QualType Type, SourceLocation L) {
1050
1
  return new (C) FloatingLiteral(C, V, isexact, Type, L);
1051
1
}
1052
1053
FloatingLiteral *
1054
0
FloatingLiteral::Create(const ASTContext &C, EmptyShell Empty) {
1055
0
  return new (C) FloatingLiteral(C, Empty);
1056
0
}
1057
1058
/// getValueAsApproximateDouble - This returns the value as an inaccurate
1059
/// double.  Note that this may cause loss of precision, but is useful for
1060
/// debugging dumps, etc.
1061
0
double FloatingLiteral::getValueAsApproximateDouble() const {
1062
0
  llvm::APFloat V = getValue();
1063
0
  bool ignored;
1064
0
  V.convert(llvm::APFloat::IEEEdouble(), llvm::APFloat::rmNearestTiesToEven,
1065
0
            &ignored);
1066
0
  return V.convertToDouble();
1067
0
}
1068
1069
unsigned StringLiteral::mapCharByteWidth(TargetInfo const &Target,
1070
1
                                         StringLiteralKind SK) {
1071
1
  unsigned CharByteWidth = 0;
1072
1
  switch (SK) {
1073
1
  case StringLiteralKind::Ordinary:
1074
1
  case StringLiteralKind::UTF8:
1075
1
    CharByteWidth = Target.getCharWidth();
1076
1
    break;
1077
0
  case StringLiteralKind::Wide:
1078
0
    CharByteWidth = Target.getWCharWidth();
1079
0
    break;
1080
0
  case StringLiteralKind::UTF16:
1081
0
    CharByteWidth = Target.getChar16Width();
1082
0
    break;
1083
0
  case StringLiteralKind::UTF32:
1084
0
    CharByteWidth = Target.getChar32Width();
1085
0
    break;
1086
0
  case StringLiteralKind::Unevaluated:
1087
0
    return sizeof(char); // Host;
1088
1
  }
1089
1
  assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
1090
0
  CharByteWidth /= 8;
1091
1
  assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
1092
1
         "The only supported character byte widths are 1,2 and 4!");
1093
0
  return CharByteWidth;
1094
1
}
1095
1096
StringLiteral::StringLiteral(const ASTContext &Ctx, StringRef Str,
1097
                             StringLiteralKind Kind, bool Pascal, QualType Ty,
1098
                             const SourceLocation *Loc,
1099
                             unsigned NumConcatenated)
1100
1
    : Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary) {
1101
1102
1
  unsigned Length = Str.size();
1103
1104
1
  StringLiteralBits.Kind = llvm::to_underlying(Kind);
1105
1
  StringLiteralBits.NumConcatenated = NumConcatenated;
1106
1107
1
  if (Kind != StringLiteralKind::Unevaluated) {
1108
1
    assert(Ctx.getAsConstantArrayType(Ty) &&
1109
1
           "StringLiteral must be of constant array type!");
1110
0
    unsigned CharByteWidth = mapCharByteWidth(Ctx.getTargetInfo(), Kind);
1111
1
    unsigned ByteLength = Str.size();
1112
1
    assert((ByteLength % CharByteWidth == 0) &&
1113
1
           "The size of the data must be a multiple of CharByteWidth!");
1114
1115
    // Avoid the expensive division. The compiler should be able to figure it
1116
    // out by itself. However as of clang 7, even with the appropriate
1117
    // llvm_unreachable added just here, it is not able to do so.
1118
0
    switch (CharByteWidth) {
1119
1
    case 1:
1120
1
      Length = ByteLength;
1121
1
      break;
1122
0
    case 2:
1123
0
      Length = ByteLength / 2;
1124
0
      break;
1125
0
    case 4:
1126
0
      Length = ByteLength / 4;
1127
0
      break;
1128
0
    default:
1129
0
      llvm_unreachable("Unsupported character width!");
1130
1
    }
1131
1132
1
    StringLiteralBits.CharByteWidth = CharByteWidth;
1133
1
    StringLiteralBits.IsPascal = Pascal;
1134
1
  } else {
1135
0
    assert(!Pascal && "Can't make an unevaluated Pascal string");
1136
0
    StringLiteralBits.CharByteWidth = 1;
1137
0
    StringLiteralBits.IsPascal = false;
1138
0
  }
1139
1140
1
  *getTrailingObjects<unsigned>() = Length;
1141
1142
  // Initialize the trailing array of SourceLocation.
1143
  // This is safe since SourceLocation is POD-like.
1144
1
  std::memcpy(getTrailingObjects<SourceLocation>(), Loc,
1145
1
              NumConcatenated * sizeof(SourceLocation));
1146
1147
  // Initialize the trailing array of char holding the string data.
1148
1
  std::memcpy(getTrailingObjects<char>(), Str.data(), Str.size());
1149
1150
1
  setDependence(ExprDependence::None);
1151
1
}
1152
1153
StringLiteral::StringLiteral(EmptyShell Empty, unsigned NumConcatenated,
1154
                             unsigned Length, unsigned CharByteWidth)
1155
0
    : Expr(StringLiteralClass, Empty) {
1156
0
  StringLiteralBits.CharByteWidth = CharByteWidth;
1157
0
  StringLiteralBits.NumConcatenated = NumConcatenated;
1158
0
  *getTrailingObjects<unsigned>() = Length;
1159
0
}
1160
1161
StringLiteral *StringLiteral::Create(const ASTContext &Ctx, StringRef Str,
1162
                                     StringLiteralKind Kind, bool Pascal,
1163
                                     QualType Ty, const SourceLocation *Loc,
1164
1
                                     unsigned NumConcatenated) {
1165
1
  void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1166
1
                               1, NumConcatenated, Str.size()),
1167
1
                           alignof(StringLiteral));
1168
1
  return new (Mem)
1169
1
      StringLiteral(Ctx, Str, Kind, Pascal, Ty, Loc, NumConcatenated);
1170
1
}
1171
1172
StringLiteral *StringLiteral::CreateEmpty(const ASTContext &Ctx,
1173
                                          unsigned NumConcatenated,
1174
                                          unsigned Length,
1175
0
                                          unsigned CharByteWidth) {
1176
0
  void *Mem = Ctx.Allocate(totalSizeToAlloc<unsigned, SourceLocation, char>(
1177
0
                               1, NumConcatenated, Length * CharByteWidth),
1178
0
                           alignof(StringLiteral));
1179
0
  return new (Mem)
1180
0
      StringLiteral(EmptyShell(), NumConcatenated, Length, CharByteWidth);
1181
0
}
1182
1183
0
void StringLiteral::outputString(raw_ostream &OS) const {
1184
0
  switch (getKind()) {
1185
0
  case StringLiteralKind::Unevaluated:
1186
0
  case StringLiteralKind::Ordinary:
1187
0
    break; // no prefix.
1188
0
  case StringLiteralKind::Wide:
1189
0
    OS << 'L';
1190
0
    break;
1191
0
  case StringLiteralKind::UTF8:
1192
0
    OS << "u8";
1193
0
    break;
1194
0
  case StringLiteralKind::UTF16:
1195
0
    OS << 'u';
1196
0
    break;
1197
0
  case StringLiteralKind::UTF32:
1198
0
    OS << 'U';
1199
0
    break;
1200
0
  }
1201
0
  OS << '"';
1202
0
  static const char Hex[] = "0123456789ABCDEF";
1203
1204
0
  unsigned LastSlashX = getLength();
1205
0
  for (unsigned I = 0, N = getLength(); I != N; ++I) {
1206
0
    uint32_t Char = getCodeUnit(I);
1207
0
    StringRef Escaped = escapeCStyle<EscapeChar::Double>(Char);
1208
0
    if (Escaped.empty()) {
1209
      // FIXME: Convert UTF-8 back to codepoints before rendering.
1210
1211
      // Convert UTF-16 surrogate pairs back to codepoints before rendering.
1212
      // Leave invalid surrogates alone; we'll use \x for those.
1213
0
      if (getKind() == StringLiteralKind::UTF16 && I != N - 1 &&
1214
0
          Char >= 0xd800 && Char <= 0xdbff) {
1215
0
        uint32_t Trail = getCodeUnit(I + 1);
1216
0
        if (Trail >= 0xdc00 && Trail <= 0xdfff) {
1217
0
          Char = 0x10000 + ((Char - 0xd800) << 10) + (Trail - 0xdc00);
1218
0
          ++I;
1219
0
        }
1220
0
      }
1221
1222
0
      if (Char > 0xff) {
1223
        // If this is a wide string, output characters over 0xff using \x
1224
        // escapes. Otherwise, this is a UTF-16 or UTF-32 string, and Char is a
1225
        // codepoint: use \x escapes for invalid codepoints.
1226
0
        if (getKind() == StringLiteralKind::Wide ||
1227
0
            (Char >= 0xd800 && Char <= 0xdfff) || Char >= 0x110000) {
1228
          // FIXME: Is this the best way to print wchar_t?
1229
0
          OS << "\\x";
1230
0
          int Shift = 28;
1231
0
          while ((Char >> Shift) == 0)
1232
0
            Shift -= 4;
1233
0
          for (/**/; Shift >= 0; Shift -= 4)
1234
0
            OS << Hex[(Char >> Shift) & 15];
1235
0
          LastSlashX = I;
1236
0
          continue;
1237
0
        }
1238
1239
0
        if (Char > 0xffff)
1240
0
          OS << "\\U00"
1241
0
             << Hex[(Char >> 20) & 15]
1242
0
             << Hex[(Char >> 16) & 15];
1243
0
        else
1244
0
          OS << "\\u";
1245
0
        OS << Hex[(Char >> 12) & 15]
1246
0
           << Hex[(Char >>  8) & 15]
1247
0
           << Hex[(Char >>  4) & 15]
1248
0
           << Hex[(Char >>  0) & 15];
1249
0
        continue;
1250
0
      }
1251
1252
      // If we used \x... for the previous character, and this character is a
1253
      // hexadecimal digit, prevent it being slurped as part of the \x.
1254
0
      if (LastSlashX + 1 == I) {
1255
0
        switch (Char) {
1256
0
          case '0': case '1': case '2': case '3': case '4':
1257
0
          case '5': case '6': case '7': case '8': case '9':
1258
0
          case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
1259
0
          case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
1260
0
            OS << "\"\"";
1261
0
        }
1262
0
      }
1263
1264
0
      assert(Char <= 0xff &&
1265
0
             "Characters above 0xff should already have been handled.");
1266
1267
0
      if (isPrintable(Char))
1268
0
        OS << (char)Char;
1269
0
      else  // Output anything hard as an octal escape.
1270
0
        OS << '\\'
1271
0
           << (char)('0' + ((Char >> 6) & 7))
1272
0
           << (char)('0' + ((Char >> 3) & 7))
1273
0
           << (char)('0' + ((Char >> 0) & 7));
1274
0
    } else {
1275
      // Handle some common non-printable cases to make dumps prettier.
1276
0
      OS << Escaped;
1277
0
    }
1278
0
  }
1279
0
  OS << '"';
1280
0
}
1281
1282
/// getLocationOfByte - Return a source location that points to the specified
1283
/// byte of this string literal.
1284
///
1285
/// Strings are amazingly complex.  They can be formed from multiple tokens and
1286
/// can have escape sequences in them in addition to the usual trigraph and
1287
/// escaped newline business.  This routine handles this complexity.
1288
///
1289
/// The *StartToken sets the first token to be searched in this function and
1290
/// the *StartTokenByteOffset is the byte offset of the first token. Before
1291
/// returning, it updates the *StartToken to the TokNo of the token being found
1292
/// and sets *StartTokenByteOffset to the byte offset of the token in the
1293
/// string.
1294
/// Using these two parameters can reduce the time complexity from O(n^2) to
1295
/// O(n) if one wants to get the location of byte for all the tokens in a
1296
/// string.
1297
///
1298
SourceLocation
1299
StringLiteral::getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1300
                                 const LangOptions &Features,
1301
                                 const TargetInfo &Target, unsigned *StartToken,
1302
0
                                 unsigned *StartTokenByteOffset) const {
1303
0
  assert((getKind() == StringLiteralKind::Ordinary ||
1304
0
          getKind() == StringLiteralKind::UTF8 ||
1305
0
          getKind() == StringLiteralKind::Unevaluated) &&
1306
0
         "Only narrow string literals are currently supported");
1307
1308
  // Loop over all of the tokens in this string until we find the one that
1309
  // contains the byte we're looking for.
1310
0
  unsigned TokNo = 0;
1311
0
  unsigned StringOffset = 0;
1312
0
  if (StartToken)
1313
0
    TokNo = *StartToken;
1314
0
  if (StartTokenByteOffset) {
1315
0
    StringOffset = *StartTokenByteOffset;
1316
0
    ByteNo -= StringOffset;
1317
0
  }
1318
0
  while (true) {
1319
0
    assert(TokNo < getNumConcatenated() && "Invalid byte number!");
1320
0
    SourceLocation StrTokLoc = getStrTokenLoc(TokNo);
1321
1322
    // Get the spelling of the string so that we can get the data that makes up
1323
    // the string literal, not the identifier for the macro it is potentially
1324
    // expanded through.
1325
0
    SourceLocation StrTokSpellingLoc = SM.getSpellingLoc(StrTokLoc);
1326
1327
    // Re-lex the token to get its length and original spelling.
1328
0
    std::pair<FileID, unsigned> LocInfo =
1329
0
        SM.getDecomposedLoc(StrTokSpellingLoc);
1330
0
    bool Invalid = false;
1331
0
    StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1332
0
    if (Invalid) {
1333
0
      if (StartTokenByteOffset != nullptr)
1334
0
        *StartTokenByteOffset = StringOffset;
1335
0
      if (StartToken != nullptr)
1336
0
        *StartToken = TokNo;
1337
0
      return StrTokSpellingLoc;
1338
0
    }
1339
1340
0
    const char *StrData = Buffer.data()+LocInfo.second;
1341
1342
    // Create a lexer starting at the beginning of this token.
1343
0
    Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), Features,
1344
0
                   Buffer.begin(), StrData, Buffer.end());
1345
0
    Token TheTok;
1346
0
    TheLexer.LexFromRawLexer(TheTok);
1347
1348
    // Use the StringLiteralParser to compute the length of the string in bytes.
1349
0
    StringLiteralParser SLP(TheTok, SM, Features, Target);
1350
0
    unsigned TokNumBytes = SLP.GetStringLength();
1351
1352
    // If the byte is in this token, return the location of the byte.
1353
0
    if (ByteNo < TokNumBytes ||
1354
0
        (ByteNo == TokNumBytes && TokNo == getNumConcatenated() - 1)) {
1355
0
      unsigned Offset = SLP.getOffsetOfStringByte(TheTok, ByteNo);
1356
1357
      // Now that we know the offset of the token in the spelling, use the
1358
      // preprocessor to get the offset in the original source.
1359
0
      if (StartTokenByteOffset != nullptr)
1360
0
        *StartTokenByteOffset = StringOffset;
1361
0
      if (StartToken != nullptr)
1362
0
        *StartToken = TokNo;
1363
0
      return Lexer::AdvanceToTokenCharacter(StrTokLoc, Offset, SM, Features);
1364
0
    }
1365
1366
    // Move to the next string token.
1367
0
    StringOffset += TokNumBytes;
1368
0
    ++TokNo;
1369
0
    ByteNo -= TokNumBytes;
1370
0
  }
1371
0
}
1372
1373
/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1374
/// corresponds to, e.g. "sizeof" or "[pre]++".
1375
0
StringRef UnaryOperator::getOpcodeStr(Opcode Op) {
1376
0
  switch (Op) {
1377
0
#define UNARY_OPERATION(Name, Spelling) case UO_##Name: return Spelling;
1378
0
#include "clang/AST/OperationKinds.def"
1379
0
  }
1380
0
  llvm_unreachable("Unknown unary operator");
1381
0
}
1382
1383
UnaryOperatorKind
1384
0
UnaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix) {
1385
0
  switch (OO) {
1386
0
  default: llvm_unreachable("No unary operator for overloaded function");
1387
0
  case OO_PlusPlus:   return Postfix ? UO_PostInc : UO_PreInc;
1388
0
  case OO_MinusMinus: return Postfix ? UO_PostDec : UO_PreDec;
1389
0
  case OO_Amp:        return UO_AddrOf;
1390
0
  case OO_Star:       return UO_Deref;
1391
0
  case OO_Plus:       return UO_Plus;
1392
0
  case OO_Minus:      return UO_Minus;
1393
0
  case OO_Tilde:      return UO_Not;
1394
0
  case OO_Exclaim:    return UO_LNot;
1395
0
  case OO_Coawait:    return UO_Coawait;
1396
0
  }
1397
0
}
1398
1399
18
OverloadedOperatorKind UnaryOperator::getOverloadedOperator(Opcode Opc) {
1400
18
  switch (Opc) {
1401
0
  case UO_PostInc: case UO_PreInc: return OO_PlusPlus;
1402
0
  case UO_PostDec: case UO_PreDec: return OO_MinusMinus;
1403
3
  case UO_AddrOf: return OO_Amp;
1404
6
  case UO_Deref: return OO_Star;
1405
0
  case UO_Plus: return OO_Plus;
1406
6
  case UO_Minus: return OO_Minus;
1407
0
  case UO_Not: return OO_Tilde;
1408
3
  case UO_LNot: return OO_Exclaim;
1409
0
  case UO_Coawait: return OO_Coawait;
1410
0
  default: return OO_None;
1411
18
  }
1412
18
}
1413
1414
1415
//===----------------------------------------------------------------------===//
1416
// Postfix Operators.
1417
//===----------------------------------------------------------------------===//
1418
1419
CallExpr::CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
1420
                   ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1421
                   SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
1422
                   unsigned MinNumArgs, ADLCallKind UsesADL)
1423
0
    : Expr(SC, Ty, VK, OK_Ordinary), RParenLoc(RParenLoc) {
1424
0
  NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1425
0
  unsigned NumPreArgs = PreArgs.size();
1426
0
  CallExprBits.NumPreArgs = NumPreArgs;
1427
0
  assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1428
1429
0
  unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1430
0
  CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1431
0
  assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1432
0
         "OffsetToTrailingObjects overflow!");
1433
1434
0
  CallExprBits.UsesADL = static_cast<bool>(UsesADL);
1435
1436
0
  setCallee(Fn);
1437
0
  for (unsigned I = 0; I != NumPreArgs; ++I)
1438
0
    setPreArg(I, PreArgs[I]);
1439
0
  for (unsigned I = 0; I != Args.size(); ++I)
1440
0
    setArg(I, Args[I]);
1441
0
  for (unsigned I = Args.size(); I != NumArgs; ++I)
1442
0
    setArg(I, nullptr);
1443
1444
0
  this->computeDependence();
1445
1446
0
  CallExprBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
1447
0
  if (hasStoredFPFeatures())
1448
0
    setStoredFPFeatures(FPFeatures);
1449
0
}
1450
1451
CallExpr::CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
1452
                   bool HasFPFeatures, EmptyShell Empty)
1453
0
    : Expr(SC, Empty), NumArgs(NumArgs) {
1454
0
  CallExprBits.NumPreArgs = NumPreArgs;
1455
0
  assert((NumPreArgs == getNumPreArgs()) && "NumPreArgs overflow!");
1456
1457
0
  unsigned OffsetToTrailingObjects = offsetToTrailingObjects(SC);
1458
0
  CallExprBits.OffsetToTrailingObjects = OffsetToTrailingObjects;
1459
0
  assert((CallExprBits.OffsetToTrailingObjects == OffsetToTrailingObjects) &&
1460
0
         "OffsetToTrailingObjects overflow!");
1461
0
  CallExprBits.HasFPFeatures = HasFPFeatures;
1462
0
}
1463
1464
CallExpr *CallExpr::Create(const ASTContext &Ctx, Expr *Fn,
1465
                           ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
1466
                           SourceLocation RParenLoc,
1467
                           FPOptionsOverride FPFeatures, unsigned MinNumArgs,
1468
0
                           ADLCallKind UsesADL) {
1469
0
  unsigned NumArgs = std::max<unsigned>(Args.size(), MinNumArgs);
1470
0
  unsigned SizeOfTrailingObjects = CallExpr::sizeOfTrailingObjects(
1471
0
      /*NumPreArgs=*/0, NumArgs, FPFeatures.requiresTrailingStorage());
1472
0
  void *Mem =
1473
0
      Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1474
0
  return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, Args, Ty, VK,
1475
0
                            RParenLoc, FPFeatures, MinNumArgs, UsesADL);
1476
0
}
1477
1478
CallExpr *CallExpr::CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
1479
                                    ExprValueKind VK, SourceLocation RParenLoc,
1480
0
                                    ADLCallKind UsesADL) {
1481
0
  assert(!(reinterpret_cast<uintptr_t>(Mem) % alignof(CallExpr)) &&
1482
0
         "Misaligned memory in CallExpr::CreateTemporary!");
1483
0
  return new (Mem) CallExpr(CallExprClass, Fn, /*PreArgs=*/{}, /*Args=*/{}, Ty,
1484
0
                            VK, RParenLoc, FPOptionsOverride(),
1485
0
                            /*MinNumArgs=*/0, UsesADL);
1486
0
}
1487
1488
CallExpr *CallExpr::CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
1489
0
                                bool HasFPFeatures, EmptyShell Empty) {
1490
0
  unsigned SizeOfTrailingObjects =
1491
0
      CallExpr::sizeOfTrailingObjects(/*NumPreArgs=*/0, NumArgs, HasFPFeatures);
1492
0
  void *Mem =
1493
0
      Ctx.Allocate(sizeof(CallExpr) + SizeOfTrailingObjects, alignof(CallExpr));
1494
0
  return new (Mem)
1495
0
      CallExpr(CallExprClass, /*NumPreArgs=*/0, NumArgs, HasFPFeatures, Empty);
1496
0
}
1497
1498
0
unsigned CallExpr::offsetToTrailingObjects(StmtClass SC) {
1499
0
  switch (SC) {
1500
0
  case CallExprClass:
1501
0
    return sizeof(CallExpr);
1502
0
  case CXXOperatorCallExprClass:
1503
0
    return sizeof(CXXOperatorCallExpr);
1504
0
  case CXXMemberCallExprClass:
1505
0
    return sizeof(CXXMemberCallExpr);
1506
0
  case UserDefinedLiteralClass:
1507
0
    return sizeof(UserDefinedLiteral);
1508
0
  case CUDAKernelCallExprClass:
1509
0
    return sizeof(CUDAKernelCallExpr);
1510
0
  default:
1511
0
    llvm_unreachable("unexpected class deriving from CallExpr!");
1512
0
  }
1513
0
}
1514
1515
0
Decl *Expr::getReferencedDeclOfCallee() {
1516
0
  Expr *CEE = IgnoreParenImpCasts();
1517
1518
0
  while (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(CEE))
1519
0
    CEE = NTTP->getReplacement()->IgnoreParenImpCasts();
1520
1521
  // If we're calling a dereference, look at the pointer instead.
1522
0
  while (true) {
1523
0
    if (auto *BO = dyn_cast<BinaryOperator>(CEE)) {
1524
0
      if (BO->isPtrMemOp()) {
1525
0
        CEE = BO->getRHS()->IgnoreParenImpCasts();
1526
0
        continue;
1527
0
      }
1528
0
    } else if (auto *UO = dyn_cast<UnaryOperator>(CEE)) {
1529
0
      if (UO->getOpcode() == UO_Deref || UO->getOpcode() == UO_AddrOf ||
1530
0
          UO->getOpcode() == UO_Plus) {
1531
0
        CEE = UO->getSubExpr()->IgnoreParenImpCasts();
1532
0
        continue;
1533
0
      }
1534
0
    }
1535
0
    break;
1536
0
  }
1537
1538
0
  if (auto *DRE = dyn_cast<DeclRefExpr>(CEE))
1539
0
    return DRE->getDecl();
1540
0
  if (auto *ME = dyn_cast<MemberExpr>(CEE))
1541
0
    return ME->getMemberDecl();
1542
0
  if (auto *BE = dyn_cast<BlockExpr>(CEE))
1543
0
    return BE->getBlockDecl();
1544
1545
0
  return nullptr;
1546
0
}
1547
1548
/// If this is a call to a builtin, return the builtin ID. If not, return 0.
1549
0
unsigned CallExpr::getBuiltinCallee() const {
1550
0
  const auto *FDecl = getDirectCallee();
1551
0
  return FDecl ? FDecl->getBuiltinID() : 0;
1552
0
}
1553
1554
0
bool CallExpr::isUnevaluatedBuiltinCall(const ASTContext &Ctx) const {
1555
0
  if (unsigned BI = getBuiltinCallee())
1556
0
    return Ctx.BuiltinInfo.isUnevaluated(BI);
1557
0
  return false;
1558
0
}
1559
1560
0
QualType CallExpr::getCallReturnType(const ASTContext &Ctx) const {
1561
0
  const Expr *Callee = getCallee();
1562
0
  QualType CalleeType = Callee->getType();
1563
0
  if (const auto *FnTypePtr = CalleeType->getAs<PointerType>()) {
1564
0
    CalleeType = FnTypePtr->getPointeeType();
1565
0
  } else if (const auto *BPT = CalleeType->getAs<BlockPointerType>()) {
1566
0
    CalleeType = BPT->getPointeeType();
1567
0
  } else if (CalleeType->isSpecificPlaceholderType(BuiltinType::BoundMember)) {
1568
0
    if (isa<CXXPseudoDestructorExpr>(Callee->IgnoreParens()))
1569
0
      return Ctx.VoidTy;
1570
1571
0
    if (isa<UnresolvedMemberExpr>(Callee->IgnoreParens()))
1572
0
      return Ctx.DependentTy;
1573
1574
    // This should never be overloaded and so should never return null.
1575
0
    CalleeType = Expr::findBoundMemberType(Callee);
1576
0
    assert(!CalleeType.isNull());
1577
0
  } else if (CalleeType->isRecordType()) {
1578
    // If the Callee is a record type, then it is a not-yet-resolved
1579
    // dependent call to the call operator of that type.
1580
0
    return Ctx.DependentTy;
1581
0
  } else if (CalleeType->isDependentType() ||
1582
0
             CalleeType->isSpecificPlaceholderType(BuiltinType::Overload)) {
1583
0
    return Ctx.DependentTy;
1584
0
  }
1585
1586
0
  const FunctionType *FnType = CalleeType->castAs<FunctionType>();
1587
0
  return FnType->getReturnType();
1588
0
}
1589
1590
0
const Attr *CallExpr::getUnusedResultAttr(const ASTContext &Ctx) const {
1591
  // If the return type is a struct, union, or enum that is marked nodiscard,
1592
  // then return the return type attribute.
1593
0
  if (const TagDecl *TD = getCallReturnType(Ctx)->getAsTagDecl())
1594
0
    if (const auto *A = TD->getAttr<WarnUnusedResultAttr>())
1595
0
      return A;
1596
1597
0
  for (const auto *TD = getCallReturnType(Ctx)->getAs<TypedefType>(); TD;
1598
0
       TD = TD->desugar()->getAs<TypedefType>())
1599
0
    if (const auto *A = TD->getDecl()->getAttr<WarnUnusedResultAttr>())
1600
0
      return A;
1601
1602
  // Otherwise, see if the callee is marked nodiscard and return that attribute
1603
  // instead.
1604
0
  const Decl *D = getCalleeDecl();
1605
0
  return D ? D->getAttr<WarnUnusedResultAttr>() : nullptr;
1606
0
}
1607
1608
0
SourceLocation CallExpr::getBeginLoc() const {
1609
0
  if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))
1610
0
    return OCE->getBeginLoc();
1611
1612
0
  SourceLocation begin = getCallee()->getBeginLoc();
1613
0
  if (begin.isInvalid() && getNumArgs() > 0 && getArg(0))
1614
0
    begin = getArg(0)->getBeginLoc();
1615
0
  return begin;
1616
0
}
1617
0
SourceLocation CallExpr::getEndLoc() const {
1618
0
  if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(this))
1619
0
    return OCE->getEndLoc();
1620
1621
0
  SourceLocation end = getRParenLoc();
1622
0
  if (end.isInvalid() && getNumArgs() > 0 && getArg(getNumArgs() - 1))
1623
0
    end = getArg(getNumArgs() - 1)->getEndLoc();
1624
0
  return end;
1625
0
}
1626
1627
OffsetOfExpr *OffsetOfExpr::Create(const ASTContext &C, QualType type,
1628
                                   SourceLocation OperatorLoc,
1629
                                   TypeSourceInfo *tsi,
1630
                                   ArrayRef<OffsetOfNode> comps,
1631
                                   ArrayRef<Expr*> exprs,
1632
0
                                   SourceLocation RParenLoc) {
1633
0
  void *Mem = C.Allocate(
1634
0
      totalSizeToAlloc<OffsetOfNode, Expr *>(comps.size(), exprs.size()));
1635
1636
0
  return new (Mem) OffsetOfExpr(C, type, OperatorLoc, tsi, comps, exprs,
1637
0
                                RParenLoc);
1638
0
}
1639
1640
OffsetOfExpr *OffsetOfExpr::CreateEmpty(const ASTContext &C,
1641
0
                                        unsigned numComps, unsigned numExprs) {
1642
0
  void *Mem =
1643
0
      C.Allocate(totalSizeToAlloc<OffsetOfNode, Expr *>(numComps, numExprs));
1644
0
  return new (Mem) OffsetOfExpr(numComps, numExprs);
1645
0
}
1646
1647
OffsetOfExpr::OffsetOfExpr(const ASTContext &C, QualType type,
1648
                           SourceLocation OperatorLoc, TypeSourceInfo *tsi,
1649
                           ArrayRef<OffsetOfNode> comps, ArrayRef<Expr *> exprs,
1650
                           SourceLocation RParenLoc)
1651
    : Expr(OffsetOfExprClass, type, VK_PRValue, OK_Ordinary),
1652
      OperatorLoc(OperatorLoc), RParenLoc(RParenLoc), TSInfo(tsi),
1653
0
      NumComps(comps.size()), NumExprs(exprs.size()) {
1654
0
  for (unsigned i = 0; i != comps.size(); ++i)
1655
0
    setComponent(i, comps[i]);
1656
0
  for (unsigned i = 0; i != exprs.size(); ++i)
1657
0
    setIndexExpr(i, exprs[i]);
1658
1659
0
  setDependence(computeDependence(this));
1660
0
}
1661
1662
0
IdentifierInfo *OffsetOfNode::getFieldName() const {
1663
0
  assert(getKind() == Field || getKind() == Identifier);
1664
0
  if (getKind() == Field)
1665
0
    return getField()->getIdentifier();
1666
1667
0
  return reinterpret_cast<IdentifierInfo *> (Data & ~(uintptr_t)Mask);
1668
0
}
1669
1670
UnaryExprOrTypeTraitExpr::UnaryExprOrTypeTraitExpr(
1671
    UnaryExprOrTypeTrait ExprKind, Expr *E, QualType resultType,
1672
    SourceLocation op, SourceLocation rp)
1673
    : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue, OK_Ordinary),
1674
0
      OpLoc(op), RParenLoc(rp) {
1675
0
  assert(ExprKind <= UETT_Last && "invalid enum value!");
1676
0
  UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
1677
0
  assert(static_cast<unsigned>(ExprKind) == UnaryExprOrTypeTraitExprBits.Kind &&
1678
0
         "UnaryExprOrTypeTraitExprBits.Kind overflow!");
1679
0
  UnaryExprOrTypeTraitExprBits.IsType = false;
1680
0
  Argument.Ex = E;
1681
0
  setDependence(computeDependence(this));
1682
0
}
1683
1684
MemberExpr::MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1685
                       ValueDecl *MemberDecl,
1686
                       const DeclarationNameInfo &NameInfo, QualType T,
1687
                       ExprValueKind VK, ExprObjectKind OK,
1688
                       NonOdrUseReason NOUR)
1689
    : Expr(MemberExprClass, T, VK, OK), Base(Base), MemberDecl(MemberDecl),
1690
0
      MemberDNLoc(NameInfo.getInfo()), MemberLoc(NameInfo.getLoc()) {
1691
0
  assert(!NameInfo.getName() ||
1692
0
         MemberDecl->getDeclName() == NameInfo.getName());
1693
0
  MemberExprBits.IsArrow = IsArrow;
1694
0
  MemberExprBits.HasQualifierOrFoundDecl = false;
1695
0
  MemberExprBits.HasTemplateKWAndArgsInfo = false;
1696
0
  MemberExprBits.HadMultipleCandidates = false;
1697
0
  MemberExprBits.NonOdrUseReason = NOUR;
1698
0
  MemberExprBits.OperatorLoc = OperatorLoc;
1699
0
  setDependence(computeDependence(this));
1700
0
}
1701
1702
MemberExpr *MemberExpr::Create(
1703
    const ASTContext &C, Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
1704
    NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc,
1705
    ValueDecl *MemberDecl, DeclAccessPair FoundDecl,
1706
    DeclarationNameInfo NameInfo, const TemplateArgumentListInfo *TemplateArgs,
1707
0
    QualType T, ExprValueKind VK, ExprObjectKind OK, NonOdrUseReason NOUR) {
1708
0
  bool HasQualOrFound = QualifierLoc || FoundDecl.getDecl() != MemberDecl ||
1709
0
                        FoundDecl.getAccess() != MemberDecl->getAccess();
1710
0
  bool HasTemplateKWAndArgsInfo = TemplateArgs || TemplateKWLoc.isValid();
1711
0
  std::size_t Size =
1712
0
      totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1713
0
                       TemplateArgumentLoc>(
1714
0
          HasQualOrFound ? 1 : 0, HasTemplateKWAndArgsInfo ? 1 : 0,
1715
0
          TemplateArgs ? TemplateArgs->size() : 0);
1716
1717
0
  void *Mem = C.Allocate(Size, alignof(MemberExpr));
1718
0
  MemberExpr *E = new (Mem) MemberExpr(Base, IsArrow, OperatorLoc, MemberDecl,
1719
0
                                       NameInfo, T, VK, OK, NOUR);
1720
1721
0
  if (HasQualOrFound) {
1722
0
    E->MemberExprBits.HasQualifierOrFoundDecl = true;
1723
1724
0
    MemberExprNameQualifier *NQ =
1725
0
        E->getTrailingObjects<MemberExprNameQualifier>();
1726
0
    NQ->QualifierLoc = QualifierLoc;
1727
0
    NQ->FoundDecl = FoundDecl;
1728
0
  }
1729
1730
0
  E->MemberExprBits.HasTemplateKWAndArgsInfo =
1731
0
      TemplateArgs || TemplateKWLoc.isValid();
1732
1733
  // FIXME: remove remaining dependence computation to computeDependence().
1734
0
  auto Deps = E->getDependence();
1735
0
  if (TemplateArgs) {
1736
0
    auto TemplateArgDeps = TemplateArgumentDependence::None;
1737
0
    E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1738
0
        TemplateKWLoc, *TemplateArgs,
1739
0
        E->getTrailingObjects<TemplateArgumentLoc>(), TemplateArgDeps);
1740
0
    for (const TemplateArgumentLoc &ArgLoc : TemplateArgs->arguments()) {
1741
0
      Deps |= toExprDependence(ArgLoc.getArgument().getDependence());
1742
0
    }
1743
0
  } else if (TemplateKWLoc.isValid()) {
1744
0
    E->getTrailingObjects<ASTTemplateKWAndArgsInfo>()->initializeFrom(
1745
0
        TemplateKWLoc);
1746
0
  }
1747
0
  E->setDependence(Deps);
1748
1749
0
  return E;
1750
0
}
1751
1752
MemberExpr *MemberExpr::CreateEmpty(const ASTContext &Context,
1753
                                    bool HasQualifier, bool HasFoundDecl,
1754
                                    bool HasTemplateKWAndArgsInfo,
1755
0
                                    unsigned NumTemplateArgs) {
1756
0
  assert((!NumTemplateArgs || HasTemplateKWAndArgsInfo) &&
1757
0
         "template args but no template arg info?");
1758
0
  bool HasQualOrFound = HasQualifier || HasFoundDecl;
1759
0
  std::size_t Size =
1760
0
      totalSizeToAlloc<MemberExprNameQualifier, ASTTemplateKWAndArgsInfo,
1761
0
                       TemplateArgumentLoc>(HasQualOrFound ? 1 : 0,
1762
0
                                            HasTemplateKWAndArgsInfo ? 1 : 0,
1763
0
                                            NumTemplateArgs);
1764
0
  void *Mem = Context.Allocate(Size, alignof(MemberExpr));
1765
0
  return new (Mem) MemberExpr(EmptyShell());
1766
0
}
1767
1768
0
void MemberExpr::setMemberDecl(ValueDecl *NewD) {
1769
0
  MemberDecl = NewD;
1770
0
  if (getType()->isUndeducedType())
1771
0
    setType(NewD->getType());
1772
0
  setDependence(computeDependence(this));
1773
0
}
1774
1775
0
SourceLocation MemberExpr::getBeginLoc() const {
1776
0
  if (isImplicitAccess()) {
1777
0
    if (hasQualifier())
1778
0
      return getQualifierLoc().getBeginLoc();
1779
0
    return MemberLoc;
1780
0
  }
1781
1782
  // FIXME: We don't want this to happen. Rather, we should be able to
1783
  // detect all kinds of implicit accesses more cleanly.
1784
0
  SourceLocation BaseStartLoc = getBase()->getBeginLoc();
1785
0
  if (BaseStartLoc.isValid())
1786
0
    return BaseStartLoc;
1787
0
  return MemberLoc;
1788
0
}
1789
0
SourceLocation MemberExpr::getEndLoc() const {
1790
0
  SourceLocation EndLoc = getMemberNameInfo().getEndLoc();
1791
0
  if (hasExplicitTemplateArgs())
1792
0
    EndLoc = getRAngleLoc();
1793
0
  else if (EndLoc.isInvalid())
1794
0
    EndLoc = getBase()->getEndLoc();
1795
0
  return EndLoc;
1796
0
}
1797
1798
28
bool CastExpr::CastConsistency() const {
1799
28
  switch (getCastKind()) {
1800
0
  case CK_DerivedToBase:
1801
0
  case CK_UncheckedDerivedToBase:
1802
0
  case CK_DerivedToBaseMemberPointer:
1803
0
  case CK_BaseToDerived:
1804
0
  case CK_BaseToDerivedMemberPointer:
1805
0
    assert(!path_empty() && "Cast kind should have a base path!");
1806
0
    break;
1807
1808
0
  case CK_CPointerToObjCPointerCast:
1809
0
    assert(getType()->isObjCObjectPointerType());
1810
0
    assert(getSubExpr()->getType()->isPointerType());
1811
0
    goto CheckNoBasePath;
1812
1813
0
  case CK_BlockPointerToObjCPointerCast:
1814
0
    assert(getType()->isObjCObjectPointerType());
1815
0
    assert(getSubExpr()->getType()->isBlockPointerType());
1816
0
    goto CheckNoBasePath;
1817
1818
0
  case CK_ReinterpretMemberPointer:
1819
0
    assert(getType()->isMemberPointerType());
1820
0
    assert(getSubExpr()->getType()->isMemberPointerType());
1821
0
    goto CheckNoBasePath;
1822
1823
0
  case CK_BitCast:
1824
    // Arbitrary casts to C pointer types count as bitcasts.
1825
    // Otherwise, we should only have block and ObjC pointer casts
1826
    // here if they stay within the type kind.
1827
0
    if (!getType()->isPointerType()) {
1828
0
      assert(getType()->isObjCObjectPointerType() ==
1829
0
             getSubExpr()->getType()->isObjCObjectPointerType());
1830
0
      assert(getType()->isBlockPointerType() ==
1831
0
             getSubExpr()->getType()->isBlockPointerType());
1832
0
    }
1833
0
    goto CheckNoBasePath;
1834
1835
0
  case CK_AnyPointerToBlockPointerCast:
1836
0
    assert(getType()->isBlockPointerType());
1837
0
    assert(getSubExpr()->getType()->isAnyPointerType() &&
1838
0
           !getSubExpr()->getType()->isBlockPointerType());
1839
0
    goto CheckNoBasePath;
1840
1841
0
  case CK_CopyAndAutoreleaseBlockObject:
1842
0
    assert(getType()->isBlockPointerType());
1843
0
    assert(getSubExpr()->getType()->isBlockPointerType());
1844
0
    goto CheckNoBasePath;
1845
1846
0
  case CK_FunctionToPointerDecay:
1847
0
    assert(getType()->isPointerType());
1848
0
    assert(getSubExpr()->getType()->isFunctionType());
1849
0
    goto CheckNoBasePath;
1850
1851
0
  case CK_AddressSpaceConversion: {
1852
0
    auto Ty = getType();
1853
0
    auto SETy = getSubExpr()->getType();
1854
0
    assert(getValueKindForType(Ty) == Expr::getValueKindForType(SETy));
1855
0
    if (isPRValue() && !Ty->isDependentType() && !SETy->isDependentType()) {
1856
0
      Ty = Ty->getPointeeType();
1857
0
      SETy = SETy->getPointeeType();
1858
0
    }
1859
0
    assert((Ty->isDependentType() || SETy->isDependentType()) ||
1860
0
           (!Ty.isNull() && !SETy.isNull() &&
1861
0
            Ty.getAddressSpace() != SETy.getAddressSpace()));
1862
0
    goto CheckNoBasePath;
1863
0
  }
1864
  // These should not have an inheritance path.
1865
0
  case CK_Dynamic:
1866
0
  case CK_ToUnion:
1867
0
  case CK_ArrayToPointerDecay:
1868
0
  case CK_NullToMemberPointer:
1869
0
  case CK_NullToPointer:
1870
0
  case CK_ConstructorConversion:
1871
1
  case CK_IntegralToPointer:
1872
1
  case CK_PointerToIntegral:
1873
1
  case CK_ToVoid:
1874
1
  case CK_VectorSplat:
1875
1
  case CK_IntegralCast:
1876
1
  case CK_BooleanToSignedIntegral:
1877
1
  case CK_IntegralToFloating:
1878
1
  case CK_FloatingToIntegral:
1879
1
  case CK_FloatingCast:
1880
1
  case CK_ObjCObjectLValueCast:
1881
1
  case CK_FloatingRealToComplex:
1882
1
  case CK_FloatingComplexToReal:
1883
1
  case CK_FloatingComplexCast:
1884
1
  case CK_FloatingComplexToIntegralComplex:
1885
1
  case CK_IntegralRealToComplex:
1886
1
  case CK_IntegralComplexToReal:
1887
1
  case CK_IntegralComplexCast:
1888
1
  case CK_IntegralComplexToFloatingComplex:
1889
1
  case CK_ARCProduceObject:
1890
1
  case CK_ARCConsumeObject:
1891
1
  case CK_ARCReclaimReturnedObject:
1892
1
  case CK_ARCExtendBlockObject:
1893
1
  case CK_ZeroToOCLOpaqueType:
1894
1
  case CK_IntToOCLSampler:
1895
1
  case CK_FloatingToFixedPoint:
1896
1
  case CK_FixedPointToFloating:
1897
1
  case CK_FixedPointCast:
1898
1
  case CK_FixedPointToIntegral:
1899
1
  case CK_IntegralToFixedPoint:
1900
1
  case CK_MatrixCast:
1901
1
    assert(!getType()->isBooleanType() && "unheralded conversion to bool");
1902
0
    goto CheckNoBasePath;
1903
1904
0
  case CK_Dependent:
1905
27
  case CK_LValueToRValue:
1906
27
  case CK_NoOp:
1907
27
  case CK_AtomicToNonAtomic:
1908
27
  case CK_NonAtomicToAtomic:
1909
27
  case CK_PointerToBoolean:
1910
27
  case CK_IntegralToBoolean:
1911
27
  case CK_FloatingToBoolean:
1912
27
  case CK_MemberPointerToBoolean:
1913
27
  case CK_FloatingComplexToBoolean:
1914
27
  case CK_IntegralComplexToBoolean:
1915
27
  case CK_LValueBitCast:            // -> bool&
1916
27
  case CK_LValueToRValueBitCast:
1917
27
  case CK_UserDefinedConversion:    // operator bool()
1918
27
  case CK_BuiltinFnToFnPtr:
1919
27
  case CK_FixedPointToBoolean:
1920
28
  CheckNoBasePath:
1921
28
    assert(path_empty() && "Cast kind should not have a base path!");
1922
0
    break;
1923
28
  }
1924
28
  return true;
1925
28
}
1926
1927
0
const char *CastExpr::getCastKindName(CastKind CK) {
1928
0
  switch (CK) {
1929
0
#define CAST_OPERATION(Name) case CK_##Name: return #Name;
1930
0
#include "clang/AST/OperationKinds.def"
1931
0
  }
1932
0
  llvm_unreachable("Unhandled cast kind!");
1933
0
}
1934
1935
namespace {
1936
// Skip over implicit nodes produced as part of semantic analysis.
1937
// Designed for use with IgnoreExprNodes.
1938
2
static Expr *ignoreImplicitSemaNodes(Expr *E) {
1939
2
  if (auto *Materialize = dyn_cast<MaterializeTemporaryExpr>(E))
1940
0
    return Materialize->getSubExpr();
1941
1942
2
  if (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
1943
0
    return Binder->getSubExpr();
1944
1945
2
  if (auto *Full = dyn_cast<FullExpr>(E))
1946
0
    return Full->getSubExpr();
1947
1948
2
  if (auto *CPLIE = dyn_cast<CXXParenListInitExpr>(E);
1949
2
      CPLIE && CPLIE->getInitExprs().size() == 1)
1950
0
    return CPLIE->getInitExprs()[0];
1951
1952
2
  return E;
1953
2
}
1954
} // namespace
1955
1956
2
Expr *CastExpr::getSubExprAsWritten() {
1957
2
  const Expr *SubExpr = nullptr;
1958
1959
4
  for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1960
2
    SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
1961
1962
    // Conversions by constructor and conversion functions have a
1963
    // subexpression describing the call; strip it off.
1964
2
    if (E->getCastKind() == CK_ConstructorConversion) {
1965
0
      SubExpr = IgnoreExprNodes(cast<CXXConstructExpr>(SubExpr)->getArg(0),
1966
0
                                ignoreImplicitSemaNodes);
1967
2
    } else if (E->getCastKind() == CK_UserDefinedConversion) {
1968
0
      assert((isa<CXXMemberCallExpr>(SubExpr) || isa<BlockExpr>(SubExpr)) &&
1969
0
             "Unexpected SubExpr for CK_UserDefinedConversion.");
1970
0
      if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1971
0
        SubExpr = MCE->getImplicitObjectArgument();
1972
0
    }
1973
2
  }
1974
1975
2
  return const_cast<Expr *>(SubExpr);
1976
2
}
1977
1978
0
NamedDecl *CastExpr::getConversionFunction() const {
1979
0
  const Expr *SubExpr = nullptr;
1980
1981
0
  for (const CastExpr *E = this; E; E = dyn_cast<ImplicitCastExpr>(SubExpr)) {
1982
0
    SubExpr = IgnoreExprNodes(E->getSubExpr(), ignoreImplicitSemaNodes);
1983
1984
0
    if (E->getCastKind() == CK_ConstructorConversion)
1985
0
      return cast<CXXConstructExpr>(SubExpr)->getConstructor();
1986
1987
0
    if (E->getCastKind() == CK_UserDefinedConversion) {
1988
0
      if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SubExpr))
1989
0
        return MCE->getMethodDecl();
1990
0
    }
1991
0
  }
1992
1993
0
  return nullptr;
1994
0
}
1995
1996
0
CXXBaseSpecifier **CastExpr::path_buffer() {
1997
0
  switch (getStmtClass()) {
1998
0
#define ABSTRACT_STMT(x)
1999
0
#define CASTEXPR(Type, Base)                                                   \
2000
0
  case Stmt::Type##Class:                                                      \
2001
0
    return static_cast<Type *>(this)->getTrailingObjects<CXXBaseSpecifier *>();
2002
0
#define STMT(Type, Base)
2003
0
#include "clang/AST/StmtNodes.inc"
2004
0
  default:
2005
0
    llvm_unreachable("non-cast expressions not possible here");
2006
0
  }
2007
0
}
2008
2009
const FieldDecl *CastExpr::getTargetFieldForToUnionCast(QualType unionType,
2010
0
                                                        QualType opType) {
2011
0
  auto RD = unionType->castAs<RecordType>()->getDecl();
2012
0
  return getTargetFieldForToUnionCast(RD, opType);
2013
0
}
2014
2015
const FieldDecl *CastExpr::getTargetFieldForToUnionCast(const RecordDecl *RD,
2016
0
                                                        QualType OpType) {
2017
0
  auto &Ctx = RD->getASTContext();
2018
0
  RecordDecl::field_iterator Field, FieldEnd;
2019
0
  for (Field = RD->field_begin(), FieldEnd = RD->field_end();
2020
0
       Field != FieldEnd; ++Field) {
2021
0
    if (Ctx.hasSameUnqualifiedType(Field->getType(), OpType) &&
2022
0
        !Field->isUnnamedBitfield()) {
2023
0
      return *Field;
2024
0
    }
2025
0
  }
2026
0
  return nullptr;
2027
0
}
2028
2029
0
FPOptionsOverride *CastExpr::getTrailingFPFeatures() {
2030
0
  assert(hasStoredFPFeatures());
2031
0
  switch (getStmtClass()) {
2032
0
  case ImplicitCastExprClass:
2033
0
    return static_cast<ImplicitCastExpr *>(this)
2034
0
        ->getTrailingObjects<FPOptionsOverride>();
2035
0
  case CStyleCastExprClass:
2036
0
    return static_cast<CStyleCastExpr *>(this)
2037
0
        ->getTrailingObjects<FPOptionsOverride>();
2038
0
  case CXXFunctionalCastExprClass:
2039
0
    return static_cast<CXXFunctionalCastExpr *>(this)
2040
0
        ->getTrailingObjects<FPOptionsOverride>();
2041
0
  case CXXStaticCastExprClass:
2042
0
    return static_cast<CXXStaticCastExpr *>(this)
2043
0
        ->getTrailingObjects<FPOptionsOverride>();
2044
0
  default:
2045
0
    llvm_unreachable("Cast does not have FPFeatures");
2046
0
  }
2047
0
}
2048
2049
ImplicitCastExpr *ImplicitCastExpr::Create(const ASTContext &C, QualType T,
2050
                                           CastKind Kind, Expr *Operand,
2051
                                           const CXXCastPath *BasePath,
2052
                                           ExprValueKind VK,
2053
28
                                           FPOptionsOverride FPO) {
2054
28
  unsigned PathSize = (BasePath ? BasePath->size() : 0);
2055
28
  void *Buffer =
2056
28
      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2057
28
          PathSize, FPO.requiresTrailingStorage()));
2058
  // Per C++ [conv.lval]p3, lvalue-to-rvalue conversions on class and
2059
  // std::nullptr_t have special semantics not captured by CK_LValueToRValue.
2060
28
  assert((Kind != CK_LValueToRValue ||
2061
28
          !(T->isNullPtrType() || T->getAsCXXRecordDecl())) &&
2062
28
         "invalid type for lvalue-to-rvalue conversion");
2063
0
  ImplicitCastExpr *E =
2064
28
      new (Buffer) ImplicitCastExpr(T, Kind, Operand, PathSize, FPO, VK);
2065
28
  if (PathSize)
2066
0
    std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2067
0
                              E->getTrailingObjects<CXXBaseSpecifier *>());
2068
28
  return E;
2069
28
}
2070
2071
ImplicitCastExpr *ImplicitCastExpr::CreateEmpty(const ASTContext &C,
2072
                                                unsigned PathSize,
2073
0
                                                bool HasFPFeatures) {
2074
0
  void *Buffer =
2075
0
      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2076
0
          PathSize, HasFPFeatures));
2077
0
  return new (Buffer) ImplicitCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2078
0
}
2079
2080
CStyleCastExpr *CStyleCastExpr::Create(const ASTContext &C, QualType T,
2081
                                       ExprValueKind VK, CastKind K, Expr *Op,
2082
                                       const CXXCastPath *BasePath,
2083
                                       FPOptionsOverride FPO,
2084
                                       TypeSourceInfo *WrittenTy,
2085
0
                                       SourceLocation L, SourceLocation R) {
2086
0
  unsigned PathSize = (BasePath ? BasePath->size() : 0);
2087
0
  void *Buffer =
2088
0
      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2089
0
          PathSize, FPO.requiresTrailingStorage()));
2090
0
  CStyleCastExpr *E =
2091
0
      new (Buffer) CStyleCastExpr(T, VK, K, Op, PathSize, FPO, WrittenTy, L, R);
2092
0
  if (PathSize)
2093
0
    std::uninitialized_copy_n(BasePath->data(), BasePath->size(),
2094
0
                              E->getTrailingObjects<CXXBaseSpecifier *>());
2095
0
  return E;
2096
0
}
2097
2098
CStyleCastExpr *CStyleCastExpr::CreateEmpty(const ASTContext &C,
2099
                                            unsigned PathSize,
2100
0
                                            bool HasFPFeatures) {
2101
0
  void *Buffer =
2102
0
      C.Allocate(totalSizeToAlloc<CXXBaseSpecifier *, FPOptionsOverride>(
2103
0
          PathSize, HasFPFeatures));
2104
0
  return new (Buffer) CStyleCastExpr(EmptyShell(), PathSize, HasFPFeatures);
2105
0
}
2106
2107
/// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2108
/// corresponds to, e.g. "<<=".
2109
0
StringRef BinaryOperator::getOpcodeStr(Opcode Op) {
2110
0
  switch (Op) {
2111
0
#define BINARY_OPERATION(Name, Spelling) case BO_##Name: return Spelling;
2112
0
#include "clang/AST/OperationKinds.def"
2113
0
  }
2114
0
  llvm_unreachable("Invalid OpCode!");
2115
0
}
2116
2117
BinaryOperatorKind
2118
0
BinaryOperator::getOverloadedOpcode(OverloadedOperatorKind OO) {
2119
0
  switch (OO) {
2120
0
  default: llvm_unreachable("Not an overloadable binary operator");
2121
0
  case OO_Plus: return BO_Add;
2122
0
  case OO_Minus: return BO_Sub;
2123
0
  case OO_Star: return BO_Mul;
2124
0
  case OO_Slash: return BO_Div;
2125
0
  case OO_Percent: return BO_Rem;
2126
0
  case OO_Caret: return BO_Xor;
2127
0
  case OO_Amp: return BO_And;
2128
0
  case OO_Pipe: return BO_Or;
2129
0
  case OO_Equal: return BO_Assign;
2130
0
  case OO_Spaceship: return BO_Cmp;
2131
0
  case OO_Less: return BO_LT;
2132
0
  case OO_Greater: return BO_GT;
2133
0
  case OO_PlusEqual: return BO_AddAssign;
2134
0
  case OO_MinusEqual: return BO_SubAssign;
2135
0
  case OO_StarEqual: return BO_MulAssign;
2136
0
  case OO_SlashEqual: return BO_DivAssign;
2137
0
  case OO_PercentEqual: return BO_RemAssign;
2138
0
  case OO_CaretEqual: return BO_XorAssign;
2139
0
  case OO_AmpEqual: return BO_AndAssign;
2140
0
  case OO_PipeEqual: return BO_OrAssign;
2141
0
  case OO_LessLess: return BO_Shl;
2142
0
  case OO_GreaterGreater: return BO_Shr;
2143
0
  case OO_LessLessEqual: return BO_ShlAssign;
2144
0
  case OO_GreaterGreaterEqual: return BO_ShrAssign;
2145
0
  case OO_EqualEqual: return BO_EQ;
2146
0
  case OO_ExclaimEqual: return BO_NE;
2147
0
  case OO_LessEqual: return BO_LE;
2148
0
  case OO_GreaterEqual: return BO_GE;
2149
0
  case OO_AmpAmp: return BO_LAnd;
2150
0
  case OO_PipePipe: return BO_LOr;
2151
0
  case OO_Comma: return BO_Comma;
2152
0
  case OO_ArrowStar: return BO_PtrMemI;
2153
0
  }
2154
0
}
2155
2156
46
OverloadedOperatorKind BinaryOperator::getOverloadedOperator(Opcode Opc) {
2157
46
  static const OverloadedOperatorKind OverOps[] = {
2158
46
    /* .* Cannot be overloaded */OO_None, OO_ArrowStar,
2159
46
    OO_Star, OO_Slash, OO_Percent,
2160
46
    OO_Plus, OO_Minus,
2161
46
    OO_LessLess, OO_GreaterGreater,
2162
46
    OO_Spaceship,
2163
46
    OO_Less, OO_Greater, OO_LessEqual, OO_GreaterEqual,
2164
46
    OO_EqualEqual, OO_ExclaimEqual,
2165
46
    OO_Amp,
2166
46
    OO_Caret,
2167
46
    OO_Pipe,
2168
46
    OO_AmpAmp,
2169
46
    OO_PipePipe,
2170
46
    OO_Equal, OO_StarEqual,
2171
46
    OO_SlashEqual, OO_PercentEqual,
2172
46
    OO_PlusEqual, OO_MinusEqual,
2173
46
    OO_LessLessEqual, OO_GreaterGreaterEqual,
2174
46
    OO_AmpEqual, OO_CaretEqual,
2175
46
    OO_PipeEqual,
2176
46
    OO_Comma
2177
46
  };
2178
46
  return OverOps[Opc];
2179
46
}
2180
2181
bool BinaryOperator::isNullPointerArithmeticExtension(ASTContext &Ctx,
2182
                                                      Opcode Opc,
2183
                                                      const Expr *LHS,
2184
0
                                                      const Expr *RHS) {
2185
0
  if (Opc != BO_Add)
2186
0
    return false;
2187
2188
  // Check that we have one pointer and one integer operand.
2189
0
  const Expr *PExp;
2190
0
  if (LHS->getType()->isPointerType()) {
2191
0
    if (!RHS->getType()->isIntegerType())
2192
0
      return false;
2193
0
    PExp = LHS;
2194
0
  } else if (RHS->getType()->isPointerType()) {
2195
0
    if (!LHS->getType()->isIntegerType())
2196
0
      return false;
2197
0
    PExp = RHS;
2198
0
  } else {
2199
0
    return false;
2200
0
  }
2201
2202
  // Check that the pointer is a nullptr.
2203
0
  if (!PExp->IgnoreParenCasts()
2204
0
          ->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull))
2205
0
    return false;
2206
2207
  // Check that the pointee type is char-sized.
2208
0
  const PointerType *PTy = PExp->getType()->getAs<PointerType>();
2209
0
  if (!PTy || !PTy->getPointeeType()->isCharType())
2210
0
    return false;
2211
2212
0
  return true;
2213
0
}
2214
2215
SourceLocExpr::SourceLocExpr(const ASTContext &Ctx, SourceLocIdentKind Kind,
2216
                             QualType ResultTy, SourceLocation BLoc,
2217
                             SourceLocation RParenLoc,
2218
                             DeclContext *ParentContext)
2219
    : Expr(SourceLocExprClass, ResultTy, VK_PRValue, OK_Ordinary),
2220
0
      BuiltinLoc(BLoc), RParenLoc(RParenLoc), ParentContext(ParentContext) {
2221
0
  SourceLocExprBits.Kind = llvm::to_underlying(Kind);
2222
0
  setDependence(ExprDependence::None);
2223
0
}
2224
2225
0
StringRef SourceLocExpr::getBuiltinStr() const {
2226
0
  switch (getIdentKind()) {
2227
0
  case SourceLocIdentKind::File:
2228
0
    return "__builtin_FILE";
2229
0
  case SourceLocIdentKind::FileName:
2230
0
    return "__builtin_FILE_NAME";
2231
0
  case SourceLocIdentKind::Function:
2232
0
    return "__builtin_FUNCTION";
2233
0
  case SourceLocIdentKind::FuncSig:
2234
0
    return "__builtin_FUNCSIG";
2235
0
  case SourceLocIdentKind::Line:
2236
0
    return "__builtin_LINE";
2237
0
  case SourceLocIdentKind::Column:
2238
0
    return "__builtin_COLUMN";
2239
0
  case SourceLocIdentKind::SourceLocStruct:
2240
0
    return "__builtin_source_location";
2241
0
  }
2242
0
  llvm_unreachable("unexpected IdentKind!");
2243
0
}
2244
2245
APValue SourceLocExpr::EvaluateInContext(const ASTContext &Ctx,
2246
0
                                         const Expr *DefaultExpr) const {
2247
0
  SourceLocation Loc;
2248
0
  const DeclContext *Context;
2249
2250
0
  if (const auto *DIE = dyn_cast_if_present<CXXDefaultInitExpr>(DefaultExpr)) {
2251
0
    Loc = DIE->getUsedLocation();
2252
0
    Context = DIE->getUsedContext();
2253
0
  } else if (const auto *DAE =
2254
0
                 dyn_cast_if_present<CXXDefaultArgExpr>(DefaultExpr)) {
2255
0
    Loc = DAE->getUsedLocation();
2256
0
    Context = DAE->getUsedContext();
2257
0
  } else {
2258
0
    Loc = getLocation();
2259
0
    Context = getParentContext();
2260
0
  }
2261
2262
0
  PresumedLoc PLoc = Ctx.getSourceManager().getPresumedLoc(
2263
0
      Ctx.getSourceManager().getExpansionRange(Loc).getEnd());
2264
2265
0
  auto MakeStringLiteral = [&](StringRef Tmp) {
2266
0
    using LValuePathEntry = APValue::LValuePathEntry;
2267
0
    StringLiteral *Res = Ctx.getPredefinedStringLiteralFromCache(Tmp);
2268
    // Decay the string to a pointer to the first character.
2269
0
    LValuePathEntry Path[1] = {LValuePathEntry::ArrayIndex(0)};
2270
0
    return APValue(Res, CharUnits::Zero(), Path, /*OnePastTheEnd=*/false);
2271
0
  };
2272
2273
0
  switch (getIdentKind()) {
2274
0
  case SourceLocIdentKind::FileName: {
2275
    // __builtin_FILE_NAME() is a Clang-specific extension that expands to the
2276
    // the last part of __builtin_FILE().
2277
0
    SmallString<256> FileName;
2278
0
    clang::Preprocessor::processPathToFileName(
2279
0
        FileName, PLoc, Ctx.getLangOpts(), Ctx.getTargetInfo());
2280
0
    return MakeStringLiteral(FileName);
2281
0
  }
2282
0
  case SourceLocIdentKind::File: {
2283
0
    SmallString<256> Path(PLoc.getFilename());
2284
0
    clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),
2285
0
                                                 Ctx.getTargetInfo());
2286
0
    return MakeStringLiteral(Path);
2287
0
  }
2288
0
  case SourceLocIdentKind::Function:
2289
0
  case SourceLocIdentKind::FuncSig: {
2290
0
    const auto *CurDecl = dyn_cast<Decl>(Context);
2291
0
    const auto Kind = getIdentKind() == SourceLocIdentKind::Function
2292
0
                          ? PredefinedIdentKind::Function
2293
0
                          : PredefinedIdentKind::FuncSig;
2294
0
    return MakeStringLiteral(
2295
0
        CurDecl ? PredefinedExpr::ComputeName(Kind, CurDecl) : std::string(""));
2296
0
  }
2297
0
  case SourceLocIdentKind::Line:
2298
0
    return APValue(Ctx.MakeIntValue(PLoc.getLine(), Ctx.UnsignedIntTy));
2299
0
  case SourceLocIdentKind::Column:
2300
0
    return APValue(Ctx.MakeIntValue(PLoc.getColumn(), Ctx.UnsignedIntTy));
2301
0
  case SourceLocIdentKind::SourceLocStruct: {
2302
    // Fill in a std::source_location::__impl structure, by creating an
2303
    // artificial file-scoped CompoundLiteralExpr, and returning a pointer to
2304
    // that.
2305
0
    const CXXRecordDecl *ImplDecl = getType()->getPointeeCXXRecordDecl();
2306
0
    assert(ImplDecl);
2307
2308
    // Construct an APValue for the __impl struct, and get or create a Decl
2309
    // corresponding to that. Note that we've already verified that the shape of
2310
    // the ImplDecl type is as expected.
2311
2312
0
    APValue Value(APValue::UninitStruct(), 0, 4);
2313
0
    for (const FieldDecl *F : ImplDecl->fields()) {
2314
0
      StringRef Name = F->getName();
2315
0
      if (Name == "_M_file_name") {
2316
0
        SmallString<256> Path(PLoc.getFilename());
2317
0
        clang::Preprocessor::processPathForFileMacro(Path, Ctx.getLangOpts(),
2318
0
                                                     Ctx.getTargetInfo());
2319
0
        Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(Path);
2320
0
      } else if (Name == "_M_function_name") {
2321
        // Note: this emits the PrettyFunction name -- different than what
2322
        // __builtin_FUNCTION() above returns!
2323
0
        const auto *CurDecl = dyn_cast<Decl>(Context);
2324
0
        Value.getStructField(F->getFieldIndex()) = MakeStringLiteral(
2325
0
            CurDecl && !isa<TranslationUnitDecl>(CurDecl)
2326
0
                ? StringRef(PredefinedExpr::ComputeName(
2327
0
                      PredefinedIdentKind::PrettyFunction, CurDecl))
2328
0
                : "");
2329
0
      } else if (Name == "_M_line") {
2330
0
        llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getLine(), F->getType());
2331
0
        Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2332
0
      } else if (Name == "_M_column") {
2333
0
        llvm::APSInt IntVal = Ctx.MakeIntValue(PLoc.getColumn(), F->getType());
2334
0
        Value.getStructField(F->getFieldIndex()) = APValue(IntVal);
2335
0
      }
2336
0
    }
2337
2338
0
    UnnamedGlobalConstantDecl *GV =
2339
0
        Ctx.getUnnamedGlobalConstantDecl(getType()->getPointeeType(), Value);
2340
2341
0
    return APValue(GV, CharUnits::Zero(), ArrayRef<APValue::LValuePathEntry>{},
2342
0
                   false);
2343
0
  }
2344
0
  }
2345
0
  llvm_unreachable("unhandled case");
2346
0
}
2347
2348
InitListExpr::InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
2349
                           ArrayRef<Expr *> initExprs, SourceLocation rbraceloc)
2350
    : Expr(InitListExprClass, QualType(), VK_PRValue, OK_Ordinary),
2351
      InitExprs(C, initExprs.size()), LBraceLoc(lbraceloc),
2352
3
      RBraceLoc(rbraceloc), AltForm(nullptr, true) {
2353
3
  sawArrayRangeDesignator(false);
2354
3
  InitExprs.insert(C, InitExprs.end(), initExprs.begin(), initExprs.end());
2355
2356
3
  setDependence(computeDependence(this));
2357
3
}
2358
2359
0
void InitListExpr::reserveInits(const ASTContext &C, unsigned NumInits) {
2360
0
  if (NumInits > InitExprs.size())
2361
0
    InitExprs.reserve(C, NumInits);
2362
0
}
2363
2364
0
void InitListExpr::resizeInits(const ASTContext &C, unsigned NumInits) {
2365
0
  InitExprs.resize(C, NumInits, nullptr);
2366
0
}
2367
2368
0
Expr *InitListExpr::updateInit(const ASTContext &C, unsigned Init, Expr *expr) {
2369
0
  if (Init >= InitExprs.size()) {
2370
0
    InitExprs.insert(C, InitExprs.end(), Init - InitExprs.size() + 1, nullptr);
2371
0
    setInit(Init, expr);
2372
0
    return nullptr;
2373
0
  }
2374
2375
0
  Expr *Result = cast_or_null<Expr>(InitExprs[Init]);
2376
0
  setInit(Init, expr);
2377
0
  return Result;
2378
0
}
2379
2380
0
void InitListExpr::setArrayFiller(Expr *filler) {
2381
0
  assert(!hasArrayFiller() && "Filler already set!");
2382
0
  ArrayFillerOrUnionFieldInit = filler;
2383
  // Fill out any "holes" in the array due to designated initializers.
2384
0
  Expr **inits = getInits();
2385
0
  for (unsigned i = 0, e = getNumInits(); i != e; ++i)
2386
0
    if (inits[i] == nullptr)
2387
0
      inits[i] = filler;
2388
0
}
2389
2390
0
bool InitListExpr::isStringLiteralInit() const {
2391
0
  if (getNumInits() != 1)
2392
0
    return false;
2393
0
  const ArrayType *AT = getType()->getAsArrayTypeUnsafe();
2394
0
  if (!AT || !AT->getElementType()->isIntegerType())
2395
0
    return false;
2396
  // It is possible for getInit() to return null.
2397
0
  const Expr *Init = getInit(0);
2398
0
  if (!Init)
2399
0
    return false;
2400
0
  Init = Init->IgnoreParenImpCasts();
2401
0
  return isa<StringLiteral>(Init) || isa<ObjCEncodeExpr>(Init);
2402
0
}
2403
2404
0
bool InitListExpr::isTransparent() const {
2405
0
  assert(isSemanticForm() && "syntactic form never semantically transparent");
2406
2407
  // A glvalue InitListExpr is always just sugar.
2408
0
  if (isGLValue()) {
2409
0
    assert(getNumInits() == 1 && "multiple inits in glvalue init list");
2410
0
    return true;
2411
0
  }
2412
2413
  // Otherwise, we're sugar if and only if we have exactly one initializer that
2414
  // is of the same type.
2415
0
  if (getNumInits() != 1 || !getInit(0))
2416
0
    return false;
2417
2418
  // Don't confuse aggregate initialization of a struct X { X &x; }; with a
2419
  // transparent struct copy.
2420
0
  if (!getInit(0)->isPRValue() && getType()->isRecordType())
2421
0
    return false;
2422
2423
0
  return getType().getCanonicalType() ==
2424
0
         getInit(0)->getType().getCanonicalType();
2425
0
}
2426
2427
0
bool InitListExpr::isIdiomaticZeroInitializer(const LangOptions &LangOpts) const {
2428
0
  assert(isSyntacticForm() && "only test syntactic form as zero initializer");
2429
2430
0
  if (LangOpts.CPlusPlus || getNumInits() != 1 || !getInit(0)) {
2431
0
    return false;
2432
0
  }
2433
2434
0
  const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(getInit(0)->IgnoreImplicit());
2435
0
  return Lit && Lit->getValue() == 0;
2436
0
}
2437
2438
0
SourceLocation InitListExpr::getBeginLoc() const {
2439
0
  if (InitListExpr *SyntacticForm = getSyntacticForm())
2440
0
    return SyntacticForm->getBeginLoc();
2441
0
  SourceLocation Beg = LBraceLoc;
2442
0
  if (Beg.isInvalid()) {
2443
    // Find the first non-null initializer.
2444
0
    for (InitExprsTy::const_iterator I = InitExprs.begin(),
2445
0
                                     E = InitExprs.end();
2446
0
      I != E; ++I) {
2447
0
      if (Stmt *S = *I) {
2448
0
        Beg = S->getBeginLoc();
2449
0
        break;
2450
0
      }
2451
0
    }
2452
0
  }
2453
0
  return Beg;
2454
0
}
2455
2456
0
SourceLocation InitListExpr::getEndLoc() const {
2457
0
  if (InitListExpr *SyntacticForm = getSyntacticForm())
2458
0
    return SyntacticForm->getEndLoc();
2459
0
  SourceLocation End = RBraceLoc;
2460
0
  if (End.isInvalid()) {
2461
    // Find the first non-null initializer from the end.
2462
0
    for (Stmt *S : llvm::reverse(InitExprs)) {
2463
0
      if (S) {
2464
0
        End = S->getEndLoc();
2465
0
        break;
2466
0
      }
2467
0
    }
2468
0
  }
2469
0
  return End;
2470
0
}
2471
2472
/// getFunctionType - Return the underlying function type for this block.
2473
///
2474
0
const FunctionProtoType *BlockExpr::getFunctionType() const {
2475
  // The block pointer is never sugared, but the function type might be.
2476
0
  return cast<BlockPointerType>(getType())
2477
0
           ->getPointeeType()->castAs<FunctionProtoType>();
2478
0
}
2479
2480
8
SourceLocation BlockExpr::getCaretLocation() const {
2481
8
  return TheBlock->getCaretLocation();
2482
8
}
2483
1
const Stmt *BlockExpr::getBody() const {
2484
1
  return TheBlock->getBody();
2485
1
}
2486
0
Stmt *BlockExpr::getBody() {
2487
0
  return TheBlock->getBody();
2488
0
}
2489
2490
2491
//===----------------------------------------------------------------------===//
2492
// Generic Expression Routines
2493
//===----------------------------------------------------------------------===//
2494
2495
0
bool Expr::isReadIfDiscardedInCPlusPlus11() const {
2496
  // In C++11, discarded-value expressions of a certain form are special,
2497
  // according to [expr]p10:
2498
  //   The lvalue-to-rvalue conversion (4.1) is applied only if the
2499
  //   expression is a glvalue of volatile-qualified type and it has
2500
  //   one of the following forms:
2501
0
  if (!isGLValue() || !getType().isVolatileQualified())
2502
0
    return false;
2503
2504
0
  const Expr *E = IgnoreParens();
2505
2506
  //   - id-expression (5.1.1),
2507
0
  if (isa<DeclRefExpr>(E))
2508
0
    return true;
2509
2510
  //   - subscripting (5.2.1),
2511
0
  if (isa<ArraySubscriptExpr>(E))
2512
0
    return true;
2513
2514
  //   - class member access (5.2.5),
2515
0
  if (isa<MemberExpr>(E))
2516
0
    return true;
2517
2518
  //   - indirection (5.3.1),
2519
0
  if (auto *UO = dyn_cast<UnaryOperator>(E))
2520
0
    if (UO->getOpcode() == UO_Deref)
2521
0
      return true;
2522
2523
0
  if (auto *BO = dyn_cast<BinaryOperator>(E)) {
2524
    //   - pointer-to-member operation (5.5),
2525
0
    if (BO->isPtrMemOp())
2526
0
      return true;
2527
2528
    //   - comma expression (5.18) where the right operand is one of the above.
2529
0
    if (BO->getOpcode() == BO_Comma)
2530
0
      return BO->getRHS()->isReadIfDiscardedInCPlusPlus11();
2531
0
  }
2532
2533
  //   - conditional expression (5.16) where both the second and the third
2534
  //     operands are one of the above, or
2535
0
  if (auto *CO = dyn_cast<ConditionalOperator>(E))
2536
0
    return CO->getTrueExpr()->isReadIfDiscardedInCPlusPlus11() &&
2537
0
           CO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2538
  // The related edge case of "*x ?: *x".
2539
0
  if (auto *BCO =
2540
0
          dyn_cast<BinaryConditionalOperator>(E)) {
2541
0
    if (auto *OVE = dyn_cast<OpaqueValueExpr>(BCO->getTrueExpr()))
2542
0
      return OVE->getSourceExpr()->isReadIfDiscardedInCPlusPlus11() &&
2543
0
             BCO->getFalseExpr()->isReadIfDiscardedInCPlusPlus11();
2544
0
  }
2545
2546
  // Objective-C++ extensions to the rule.
2547
0
  if (isa<ObjCIvarRefExpr>(E))
2548
0
    return true;
2549
0
  if (const auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
2550
0
    if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(POE->getSyntacticForm()))
2551
0
      return true;
2552
0
  }
2553
2554
0
  return false;
2555
0
}
2556
2557
/// isUnusedResultAWarning - Return true if this immediate expression should
2558
/// be warned about if the result is unused.  If so, fill in Loc and Ranges
2559
/// with location to warn on and the source range[s] to report with the
2560
/// warning.
2561
bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
2562
                                  SourceRange &R1, SourceRange &R2,
2563
0
                                  ASTContext &Ctx) const {
2564
  // Don't warn if the expr is type dependent. The type could end up
2565
  // instantiating to void.
2566
0
  if (isTypeDependent())
2567
0
    return false;
2568
2569
0
  switch (getStmtClass()) {
2570
0
  default:
2571
0
    if (getType()->isVoidType())
2572
0
      return false;
2573
0
    WarnE = this;
2574
0
    Loc = getExprLoc();
2575
0
    R1 = getSourceRange();
2576
0
    return true;
2577
0
  case ParenExprClass:
2578
0
    return cast<ParenExpr>(this)->getSubExpr()->
2579
0
      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2580
0
  case GenericSelectionExprClass:
2581
0
    return cast<GenericSelectionExpr>(this)->getResultExpr()->
2582
0
      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2583
0
  case CoawaitExprClass:
2584
0
  case CoyieldExprClass:
2585
0
    return cast<CoroutineSuspendExpr>(this)->getResumeExpr()->
2586
0
      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2587
0
  case ChooseExprClass:
2588
0
    return cast<ChooseExpr>(this)->getChosenSubExpr()->
2589
0
      isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2590
0
  case UnaryOperatorClass: {
2591
0
    const UnaryOperator *UO = cast<UnaryOperator>(this);
2592
2593
0
    switch (UO->getOpcode()) {
2594
0
    case UO_Plus:
2595
0
    case UO_Minus:
2596
0
    case UO_AddrOf:
2597
0
    case UO_Not:
2598
0
    case UO_LNot:
2599
0
    case UO_Deref:
2600
0
      break;
2601
0
    case UO_Coawait:
2602
      // This is just the 'operator co_await' call inside the guts of a
2603
      // dependent co_await call.
2604
0
    case UO_PostInc:
2605
0
    case UO_PostDec:
2606
0
    case UO_PreInc:
2607
0
    case UO_PreDec:                 // ++/--
2608
0
      return false;  // Not a warning.
2609
0
    case UO_Real:
2610
0
    case UO_Imag:
2611
      // accessing a piece of a volatile complex is a side-effect.
2612
0
      if (Ctx.getCanonicalType(UO->getSubExpr()->getType())
2613
0
          .isVolatileQualified())
2614
0
        return false;
2615
0
      break;
2616
0
    case UO_Extension:
2617
0
      return UO->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2618
0
    }
2619
0
    WarnE = this;
2620
0
    Loc = UO->getOperatorLoc();
2621
0
    R1 = UO->getSubExpr()->getSourceRange();
2622
0
    return true;
2623
0
  }
2624
0
  case BinaryOperatorClass: {
2625
0
    const BinaryOperator *BO = cast<BinaryOperator>(this);
2626
0
    switch (BO->getOpcode()) {
2627
0
      default:
2628
0
        break;
2629
      // Consider the RHS of comma for side effects. LHS was checked by
2630
      // Sema::CheckCommaOperands.
2631
0
      case BO_Comma:
2632
        // ((foo = <blah>), 0) is an idiom for hiding the result (and
2633
        // lvalue-ness) of an assignment written in a macro.
2634
0
        if (IntegerLiteral *IE =
2635
0
              dyn_cast<IntegerLiteral>(BO->getRHS()->IgnoreParens()))
2636
0
          if (IE->getValue() == 0)
2637
0
            return false;
2638
0
        return BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2639
      // Consider '||', '&&' to have side effects if the LHS or RHS does.
2640
0
      case BO_LAnd:
2641
0
      case BO_LOr:
2642
0
        if (!BO->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) ||
2643
0
            !BO->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx))
2644
0
          return false;
2645
0
        break;
2646
0
    }
2647
0
    if (BO->isAssignmentOp())
2648
0
      return false;
2649
0
    WarnE = this;
2650
0
    Loc = BO->getOperatorLoc();
2651
0
    R1 = BO->getLHS()->getSourceRange();
2652
0
    R2 = BO->getRHS()->getSourceRange();
2653
0
    return true;
2654
0
  }
2655
0
  case CompoundAssignOperatorClass:
2656
0
  case VAArgExprClass:
2657
0
  case AtomicExprClass:
2658
0
    return false;
2659
2660
0
  case ConditionalOperatorClass: {
2661
    // If only one of the LHS or RHS is a warning, the operator might
2662
    // be being used for control flow. Only warn if both the LHS and
2663
    // RHS are warnings.
2664
0
    const auto *Exp = cast<ConditionalOperator>(this);
2665
0
    return Exp->getLHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx) &&
2666
0
           Exp->getRHS()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2667
0
  }
2668
0
  case BinaryConditionalOperatorClass: {
2669
0
    const auto *Exp = cast<BinaryConditionalOperator>(this);
2670
0
    return Exp->getFalseExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2671
0
  }
2672
2673
0
  case MemberExprClass:
2674
0
    WarnE = this;
2675
0
    Loc = cast<MemberExpr>(this)->getMemberLoc();
2676
0
    R1 = SourceRange(Loc, Loc);
2677
0
    R2 = cast<MemberExpr>(this)->getBase()->getSourceRange();
2678
0
    return true;
2679
2680
0
  case ArraySubscriptExprClass:
2681
0
    WarnE = this;
2682
0
    Loc = cast<ArraySubscriptExpr>(this)->getRBracketLoc();
2683
0
    R1 = cast<ArraySubscriptExpr>(this)->getLHS()->getSourceRange();
2684
0
    R2 = cast<ArraySubscriptExpr>(this)->getRHS()->getSourceRange();
2685
0
    return true;
2686
2687
0
  case CXXOperatorCallExprClass: {
2688
    // Warn about operator ==,!=,<,>,<=, and >= even when user-defined operator
2689
    // overloads as there is no reasonable way to define these such that they
2690
    // have non-trivial, desirable side-effects. See the -Wunused-comparison
2691
    // warning: operators == and != are commonly typo'ed, and so warning on them
2692
    // provides additional value as well. If this list is updated,
2693
    // DiagnoseUnusedComparison should be as well.
2694
0
    const CXXOperatorCallExpr *Op = cast<CXXOperatorCallExpr>(this);
2695
0
    switch (Op->getOperator()) {
2696
0
    default:
2697
0
      break;
2698
0
    case OO_EqualEqual:
2699
0
    case OO_ExclaimEqual:
2700
0
    case OO_Less:
2701
0
    case OO_Greater:
2702
0
    case OO_GreaterEqual:
2703
0
    case OO_LessEqual:
2704
0
      if (Op->getCallReturnType(Ctx)->isReferenceType() ||
2705
0
          Op->getCallReturnType(Ctx)->isVoidType())
2706
0
        break;
2707
0
      WarnE = this;
2708
0
      Loc = Op->getOperatorLoc();
2709
0
      R1 = Op->getSourceRange();
2710
0
      return true;
2711
0
    }
2712
2713
    // Fallthrough for generic call handling.
2714
0
    [[fallthrough]];
2715
0
  }
2716
0
  case CallExprClass:
2717
0
  case CXXMemberCallExprClass:
2718
0
  case UserDefinedLiteralClass: {
2719
    // If this is a direct call, get the callee.
2720
0
    const CallExpr *CE = cast<CallExpr>(this);
2721
0
    if (const Decl *FD = CE->getCalleeDecl()) {
2722
      // If the callee has attribute pure, const, or warn_unused_result, warn
2723
      // about it. void foo() { strlen("bar"); } should warn.
2724
      //
2725
      // Note: If new cases are added here, DiagnoseUnusedExprResult should be
2726
      // updated to match for QoI.
2727
0
      if (CE->hasUnusedResultAttr(Ctx) ||
2728
0
          FD->hasAttr<PureAttr>() || FD->hasAttr<ConstAttr>()) {
2729
0
        WarnE = this;
2730
0
        Loc = CE->getCallee()->getBeginLoc();
2731
0
        R1 = CE->getCallee()->getSourceRange();
2732
2733
0
        if (unsigned NumArgs = CE->getNumArgs())
2734
0
          R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2735
0
                           CE->getArg(NumArgs - 1)->getEndLoc());
2736
0
        return true;
2737
0
      }
2738
0
    }
2739
0
    return false;
2740
0
  }
2741
2742
  // If we don't know precisely what we're looking at, let's not warn.
2743
0
  case UnresolvedLookupExprClass:
2744
0
  case CXXUnresolvedConstructExprClass:
2745
0
  case RecoveryExprClass:
2746
0
    return false;
2747
2748
0
  case CXXTemporaryObjectExprClass:
2749
0
  case CXXConstructExprClass: {
2750
0
    if (const CXXRecordDecl *Type = getType()->getAsCXXRecordDecl()) {
2751
0
      const auto *WarnURAttr = Type->getAttr<WarnUnusedResultAttr>();
2752
0
      if (Type->hasAttr<WarnUnusedAttr>() ||
2753
0
          (WarnURAttr && WarnURAttr->IsCXX11NoDiscard())) {
2754
0
        WarnE = this;
2755
0
        Loc = getBeginLoc();
2756
0
        R1 = getSourceRange();
2757
0
        return true;
2758
0
      }
2759
0
    }
2760
2761
0
    const auto *CE = cast<CXXConstructExpr>(this);
2762
0
    if (const CXXConstructorDecl *Ctor = CE->getConstructor()) {
2763
0
      const auto *WarnURAttr = Ctor->getAttr<WarnUnusedResultAttr>();
2764
0
      if (WarnURAttr && WarnURAttr->IsCXX11NoDiscard()) {
2765
0
        WarnE = this;
2766
0
        Loc = getBeginLoc();
2767
0
        R1 = getSourceRange();
2768
2769
0
        if (unsigned NumArgs = CE->getNumArgs())
2770
0
          R2 = SourceRange(CE->getArg(0)->getBeginLoc(),
2771
0
                           CE->getArg(NumArgs - 1)->getEndLoc());
2772
0
        return true;
2773
0
      }
2774
0
    }
2775
2776
0
    return false;
2777
0
  }
2778
2779
0
  case ObjCMessageExprClass: {
2780
0
    const ObjCMessageExpr *ME = cast<ObjCMessageExpr>(this);
2781
0
    if (Ctx.getLangOpts().ObjCAutoRefCount &&
2782
0
        ME->isInstanceMessage() &&
2783
0
        !ME->getType()->isVoidType() &&
2784
0
        ME->getMethodFamily() == OMF_init) {
2785
0
      WarnE = this;
2786
0
      Loc = getExprLoc();
2787
0
      R1 = ME->getSourceRange();
2788
0
      return true;
2789
0
    }
2790
2791
0
    if (const ObjCMethodDecl *MD = ME->getMethodDecl())
2792
0
      if (MD->hasAttr<WarnUnusedResultAttr>()) {
2793
0
        WarnE = this;
2794
0
        Loc = getExprLoc();
2795
0
        return true;
2796
0
      }
2797
2798
0
    return false;
2799
0
  }
2800
2801
0
  case ObjCPropertyRefExprClass:
2802
0
  case ObjCSubscriptRefExprClass:
2803
0
    WarnE = this;
2804
0
    Loc = getExprLoc();
2805
0
    R1 = getSourceRange();
2806
0
    return true;
2807
2808
0
  case PseudoObjectExprClass: {
2809
0
    const auto *POE = cast<PseudoObjectExpr>(this);
2810
2811
    // For some syntactic forms, we should always warn.
2812
0
    if (isa<ObjCPropertyRefExpr, ObjCSubscriptRefExpr>(
2813
0
            POE->getSyntacticForm())) {
2814
0
      WarnE = this;
2815
0
      Loc = getExprLoc();
2816
0
      R1 = getSourceRange();
2817
0
      return true;
2818
0
    }
2819
2820
    // For others, we should never warn.
2821
0
    if (auto *BO = dyn_cast<BinaryOperator>(POE->getSyntacticForm()))
2822
0
      if (BO->isAssignmentOp())
2823
0
        return false;
2824
0
    if (auto *UO = dyn_cast<UnaryOperator>(POE->getSyntacticForm()))
2825
0
      if (UO->isIncrementDecrementOp())
2826
0
        return false;
2827
2828
    // Otherwise, warn if the result expression would warn.
2829
0
    const Expr *Result = POE->getResultExpr();
2830
0
    return Result && Result->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2831
0
  }
2832
2833
0
  case StmtExprClass: {
2834
    // Statement exprs don't logically have side effects themselves, but are
2835
    // sometimes used in macros in ways that give them a type that is unused.
2836
    // For example ({ blah; foo(); }) will end up with a type if foo has a type.
2837
    // however, if the result of the stmt expr is dead, we don't want to emit a
2838
    // warning.
2839
0
    const CompoundStmt *CS = cast<StmtExpr>(this)->getSubStmt();
2840
0
    if (!CS->body_empty()) {
2841
0
      if (const Expr *E = dyn_cast<Expr>(CS->body_back()))
2842
0
        return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2843
0
      if (const LabelStmt *Label = dyn_cast<LabelStmt>(CS->body_back()))
2844
0
        if (const Expr *E = dyn_cast<Expr>(Label->getSubStmt()))
2845
0
          return E->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2846
0
    }
2847
2848
0
    if (getType()->isVoidType())
2849
0
      return false;
2850
0
    WarnE = this;
2851
0
    Loc = cast<StmtExpr>(this)->getLParenLoc();
2852
0
    R1 = getSourceRange();
2853
0
    return true;
2854
0
  }
2855
0
  case CXXFunctionalCastExprClass:
2856
0
  case CStyleCastExprClass: {
2857
    // Ignore an explicit cast to void, except in C++98 if the operand is a
2858
    // volatile glvalue for which we would trigger an implicit read in any
2859
    // other language mode. (Such an implicit read always happens as part of
2860
    // the lvalue conversion in C, and happens in C++ for expressions of all
2861
    // forms where it seems likely the user intended to trigger a volatile
2862
    // load.)
2863
0
    const CastExpr *CE = cast<CastExpr>(this);
2864
0
    const Expr *SubE = CE->getSubExpr()->IgnoreParens();
2865
0
    if (CE->getCastKind() == CK_ToVoid) {
2866
0
      if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
2867
0
          SubE->isReadIfDiscardedInCPlusPlus11()) {
2868
        // Suppress the "unused value" warning for idiomatic usage of
2869
        // '(void)var;' used to suppress "unused variable" warnings.
2870
0
        if (auto *DRE = dyn_cast<DeclRefExpr>(SubE))
2871
0
          if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
2872
0
            if (!VD->isExternallyVisible())
2873
0
              return false;
2874
2875
        // The lvalue-to-rvalue conversion would have no effect for an array.
2876
        // It's implausible that the programmer expected this to result in a
2877
        // volatile array load, so don't warn.
2878
0
        if (SubE->getType()->isArrayType())
2879
0
          return false;
2880
2881
0
        return SubE->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2882
0
      }
2883
0
      return false;
2884
0
    }
2885
2886
    // If this is a cast to a constructor conversion, check the operand.
2887
    // Otherwise, the result of the cast is unused.
2888
0
    if (CE->getCastKind() == CK_ConstructorConversion)
2889
0
      return CE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2890
0
    if (CE->getCastKind() == CK_Dependent)
2891
0
      return false;
2892
2893
0
    WarnE = this;
2894
0
    if (const CXXFunctionalCastExpr *CXXCE =
2895
0
            dyn_cast<CXXFunctionalCastExpr>(this)) {
2896
0
      Loc = CXXCE->getBeginLoc();
2897
0
      R1 = CXXCE->getSubExpr()->getSourceRange();
2898
0
    } else {
2899
0
      const CStyleCastExpr *CStyleCE = cast<CStyleCastExpr>(this);
2900
0
      Loc = CStyleCE->getLParenLoc();
2901
0
      R1 = CStyleCE->getSubExpr()->getSourceRange();
2902
0
    }
2903
0
    return true;
2904
0
  }
2905
0
  case ImplicitCastExprClass: {
2906
0
    const CastExpr *ICE = cast<ImplicitCastExpr>(this);
2907
2908
    // lvalue-to-rvalue conversion on a volatile lvalue is a side-effect.
2909
0
    if (ICE->getCastKind() == CK_LValueToRValue &&
2910
0
        ICE->getSubExpr()->getType().isVolatileQualified())
2911
0
      return false;
2912
2913
0
    return ICE->getSubExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2914
0
  }
2915
0
  case CXXDefaultArgExprClass:
2916
0
    return (cast<CXXDefaultArgExpr>(this)
2917
0
            ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2918
0
  case CXXDefaultInitExprClass:
2919
0
    return (cast<CXXDefaultInitExpr>(this)
2920
0
            ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
2921
2922
0
  case CXXNewExprClass:
2923
    // FIXME: In theory, there might be new expressions that don't have side
2924
    // effects (e.g. a placement new with an uninitialized POD).
2925
0
  case CXXDeleteExprClass:
2926
0
    return false;
2927
0
  case MaterializeTemporaryExprClass:
2928
0
    return cast<MaterializeTemporaryExpr>(this)
2929
0
        ->getSubExpr()
2930
0
        ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2931
0
  case CXXBindTemporaryExprClass:
2932
0
    return cast<CXXBindTemporaryExpr>(this)->getSubExpr()
2933
0
               ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2934
0
  case ExprWithCleanupsClass:
2935
0
    return cast<ExprWithCleanups>(this)->getSubExpr()
2936
0
               ->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx);
2937
0
  }
2938
0
}
2939
2940
/// isOBJCGCCandidate - Check if an expression is objc gc'able.
2941
/// returns true, if it is; false otherwise.
2942
0
bool Expr::isOBJCGCCandidate(ASTContext &Ctx) const {
2943
0
  const Expr *E = IgnoreParens();
2944
0
  switch (E->getStmtClass()) {
2945
0
  default:
2946
0
    return false;
2947
0
  case ObjCIvarRefExprClass:
2948
0
    return true;
2949
0
  case Expr::UnaryOperatorClass:
2950
0
    return cast<UnaryOperator>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2951
0
  case ImplicitCastExprClass:
2952
0
    return cast<ImplicitCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2953
0
  case MaterializeTemporaryExprClass:
2954
0
    return cast<MaterializeTemporaryExpr>(E)->getSubExpr()->isOBJCGCCandidate(
2955
0
        Ctx);
2956
0
  case CStyleCastExprClass:
2957
0
    return cast<CStyleCastExpr>(E)->getSubExpr()->isOBJCGCCandidate(Ctx);
2958
0
  case DeclRefExprClass: {
2959
0
    const Decl *D = cast<DeclRefExpr>(E)->getDecl();
2960
2961
0
    if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2962
0
      if (VD->hasGlobalStorage())
2963
0
        return true;
2964
0
      QualType T = VD->getType();
2965
      // dereferencing to a  pointer is always a gc'able candidate,
2966
      // unless it is __weak.
2967
0
      return T->isPointerType() &&
2968
0
             (Ctx.getObjCGCAttrKind(T) != Qualifiers::Weak);
2969
0
    }
2970
0
    return false;
2971
0
  }
2972
0
  case MemberExprClass: {
2973
0
    const MemberExpr *M = cast<MemberExpr>(E);
2974
0
    return M->getBase()->isOBJCGCCandidate(Ctx);
2975
0
  }
2976
0
  case ArraySubscriptExprClass:
2977
0
    return cast<ArraySubscriptExpr>(E)->getBase()->isOBJCGCCandidate(Ctx);
2978
0
  }
2979
0
}
2980
2981
0
bool Expr::isBoundMemberFunction(ASTContext &Ctx) const {
2982
0
  if (isTypeDependent())
2983
0
    return false;
2984
0
  return ClassifyLValue(Ctx) == Expr::LV_MemberFunction;
2985
0
}
2986
2987
0
QualType Expr::findBoundMemberType(const Expr *expr) {
2988
0
  assert(expr->hasPlaceholderType(BuiltinType::BoundMember));
2989
2990
  // Bound member expressions are always one of these possibilities:
2991
  //   x->m      x.m      x->*y      x.*y
2992
  // (possibly parenthesized)
2993
2994
0
  expr = expr->IgnoreParens();
2995
0
  if (const MemberExpr *mem = dyn_cast<MemberExpr>(expr)) {
2996
0
    assert(isa<CXXMethodDecl>(mem->getMemberDecl()));
2997
0
    return mem->getMemberDecl()->getType();
2998
0
  }
2999
3000
0
  if (const BinaryOperator *op = dyn_cast<BinaryOperator>(expr)) {
3001
0
    QualType type = op->getRHS()->getType()->castAs<MemberPointerType>()
3002
0
                      ->getPointeeType();
3003
0
    assert(type->isFunctionType());
3004
0
    return type;
3005
0
  }
3006
3007
0
  assert(isa<UnresolvedMemberExpr>(expr) || isa<CXXPseudoDestructorExpr>(expr));
3008
0
  return QualType();
3009
0
}
3010
3011
5
Expr *Expr::IgnoreImpCasts() {
3012
5
  return IgnoreExprNodes(this, IgnoreImplicitCastsSingleStep);
3013
5
}
3014
3015
0
Expr *Expr::IgnoreCasts() {
3016
0
  return IgnoreExprNodes(this, IgnoreCastsSingleStep);
3017
0
}
3018
3019
2
Expr *Expr::IgnoreImplicit() {
3020
2
  return IgnoreExprNodes(this, IgnoreImplicitSingleStep);
3021
2
}
3022
3023
0
Expr *Expr::IgnoreImplicitAsWritten() {
3024
0
  return IgnoreExprNodes(this, IgnoreImplicitAsWrittenSingleStep);
3025
0
}
3026
3027
29
Expr *Expr::IgnoreParens() {
3028
29
  return IgnoreExprNodes(this, IgnoreParensSingleStep);
3029
29
}
3030
3031
57
Expr *Expr::IgnoreParenImpCasts() {
3032
57
  return IgnoreExprNodes(this, IgnoreParensSingleStep,
3033
57
                         IgnoreImplicitCastsExtraSingleStep);
3034
57
}
3035
3036
93
Expr *Expr::IgnoreParenCasts() {
3037
93
  return IgnoreExprNodes(this, IgnoreParensSingleStep, IgnoreCastsSingleStep);
3038
93
}
3039
3040
2
Expr *Expr::IgnoreConversionOperatorSingleStep() {
3041
2
  if (auto *MCE = dyn_cast<CXXMemberCallExpr>(this)) {
3042
0
    if (MCE->getMethodDecl() && isa<CXXConversionDecl>(MCE->getMethodDecl()))
3043
0
      return MCE->getImplicitObjectArgument();
3044
0
  }
3045
2
  return this;
3046
2
}
3047
3048
0
Expr *Expr::IgnoreParenLValueCasts() {
3049
0
  return IgnoreExprNodes(this, IgnoreParensSingleStep,
3050
0
                         IgnoreLValueCastsSingleStep);
3051
0
}
3052
3053
0
Expr *Expr::IgnoreParenBaseCasts() {
3054
0
  return IgnoreExprNodes(this, IgnoreParensSingleStep,
3055
0
                         IgnoreBaseCastsSingleStep);
3056
0
}
3057
3058
0
Expr *Expr::IgnoreParenNoopCasts(const ASTContext &Ctx) {
3059
0
  auto IgnoreNoopCastsSingleStep = [&Ctx](Expr *E) {
3060
0
    if (auto *CE = dyn_cast<CastExpr>(E)) {
3061
      // We ignore integer <-> casts that are of the same width, ptr<->ptr and
3062
      // ptr<->int casts of the same width. We also ignore all identity casts.
3063
0
      Expr *SubExpr = CE->getSubExpr();
3064
0
      bool IsIdentityCast =
3065
0
          Ctx.hasSameUnqualifiedType(E->getType(), SubExpr->getType());
3066
0
      bool IsSameWidthCast = (E->getType()->isPointerType() ||
3067
0
                              E->getType()->isIntegralType(Ctx)) &&
3068
0
                             (SubExpr->getType()->isPointerType() ||
3069
0
                              SubExpr->getType()->isIntegralType(Ctx)) &&
3070
0
                             (Ctx.getTypeSize(E->getType()) ==
3071
0
                              Ctx.getTypeSize(SubExpr->getType()));
3072
3073
0
      if (IsIdentityCast || IsSameWidthCast)
3074
0
        return SubExpr;
3075
0
    } else if (auto *NTTP = dyn_cast<SubstNonTypeTemplateParmExpr>(E))
3076
0
      return NTTP->getReplacement();
3077
3078
0
    return E;
3079
0
  };
3080
0
  return IgnoreExprNodes(this, IgnoreParensSingleStep,
3081
0
                         IgnoreNoopCastsSingleStep);
3082
0
}
3083
3084
0
Expr *Expr::IgnoreUnlessSpelledInSource() {
3085
0
  auto IgnoreImplicitConstructorSingleStep = [](Expr *E) {
3086
0
    if (auto *Cast = dyn_cast<CXXFunctionalCastExpr>(E)) {
3087
0
      auto *SE = Cast->getSubExpr();
3088
0
      if (SE->getSourceRange() == E->getSourceRange())
3089
0
        return SE;
3090
0
    }
3091
3092
0
    if (auto *C = dyn_cast<CXXConstructExpr>(E)) {
3093
0
      auto NumArgs = C->getNumArgs();
3094
0
      if (NumArgs == 1 ||
3095
0
          (NumArgs > 1 && isa<CXXDefaultArgExpr>(C->getArg(1)))) {
3096
0
        Expr *A = C->getArg(0);
3097
0
        if (A->getSourceRange() == E->getSourceRange() || C->isElidable())
3098
0
          return A;
3099
0
      }
3100
0
    }
3101
0
    return E;
3102
0
  };
3103
0
  auto IgnoreImplicitMemberCallSingleStep = [](Expr *E) {
3104
0
    if (auto *C = dyn_cast<CXXMemberCallExpr>(E)) {
3105
0
      Expr *ExprNode = C->getImplicitObjectArgument();
3106
0
      if (ExprNode->getSourceRange() == E->getSourceRange()) {
3107
0
        return ExprNode;
3108
0
      }
3109
0
      if (auto *PE = dyn_cast<ParenExpr>(ExprNode)) {
3110
0
        if (PE->getSourceRange() == C->getSourceRange()) {
3111
0
          return cast<Expr>(PE);
3112
0
        }
3113
0
      }
3114
0
      ExprNode = ExprNode->IgnoreParenImpCasts();
3115
0
      if (ExprNode->getSourceRange() == E->getSourceRange())
3116
0
        return ExprNode;
3117
0
    }
3118
0
    return E;
3119
0
  };
3120
0
  return IgnoreExprNodes(
3121
0
      this, IgnoreImplicitSingleStep, IgnoreImplicitCastsExtraSingleStep,
3122
0
      IgnoreParensOnlySingleStep, IgnoreImplicitConstructorSingleStep,
3123
0
      IgnoreImplicitMemberCallSingleStep);
3124
0
}
3125
3126
0
bool Expr::isDefaultArgument() const {
3127
0
  const Expr *E = this;
3128
0
  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3129
0
    E = M->getSubExpr();
3130
3131
0
  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
3132
0
    E = ICE->getSubExprAsWritten();
3133
3134
0
  return isa<CXXDefaultArgExpr>(E);
3135
0
}
3136
3137
/// Skip over any no-op casts and any temporary-binding
3138
/// expressions.
3139
0
static const Expr *skipTemporaryBindingsNoOpCastsAndParens(const Expr *E) {
3140
0
  if (const MaterializeTemporaryExpr *M = dyn_cast<MaterializeTemporaryExpr>(E))
3141
0
    E = M->getSubExpr();
3142
3143
0
  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3144
0
    if (ICE->getCastKind() == CK_NoOp)
3145
0
      E = ICE->getSubExpr();
3146
0
    else
3147
0
      break;
3148
0
  }
3149
3150
0
  while (const CXXBindTemporaryExpr *BE = dyn_cast<CXXBindTemporaryExpr>(E))
3151
0
    E = BE->getSubExpr();
3152
3153
0
  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3154
0
    if (ICE->getCastKind() == CK_NoOp)
3155
0
      E = ICE->getSubExpr();
3156
0
    else
3157
0
      break;
3158
0
  }
3159
3160
0
  return E->IgnoreParens();
3161
0
}
3162
3163
/// isTemporaryObject - Determines if this expression produces a
3164
/// temporary of the given class type.
3165
0
bool Expr::isTemporaryObject(ASTContext &C, const CXXRecordDecl *TempTy) const {
3166
0
  if (!C.hasSameUnqualifiedType(getType(), C.getTypeDeclType(TempTy)))
3167
0
    return false;
3168
3169
0
  const Expr *E = skipTemporaryBindingsNoOpCastsAndParens(this);
3170
3171
  // Temporaries are by definition pr-values of class type.
3172
0
  if (!E->Classify(C).isPRValue()) {
3173
    // In this context, property reference is a message call and is pr-value.
3174
0
    if (!isa<ObjCPropertyRefExpr>(E))
3175
0
      return false;
3176
0
  }
3177
3178
  // Black-list a few cases which yield pr-values of class type that don't
3179
  // refer to temporaries of that type:
3180
3181
  // - implicit derived-to-base conversions
3182
0
  if (isa<ImplicitCastExpr>(E)) {
3183
0
    switch (cast<ImplicitCastExpr>(E)->getCastKind()) {
3184
0
    case CK_DerivedToBase:
3185
0
    case CK_UncheckedDerivedToBase:
3186
0
      return false;
3187
0
    default:
3188
0
      break;
3189
0
    }
3190
0
  }
3191
3192
  // - member expressions (all)
3193
0
  if (isa<MemberExpr>(E))
3194
0
    return false;
3195
3196
0
  if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E))
3197
0
    if (BO->isPtrMemOp())
3198
0
      return false;
3199
3200
  // - opaque values (all)
3201
0
  if (isa<OpaqueValueExpr>(E))
3202
0
    return false;
3203
3204
0
  return true;
3205
0
}
3206
3207
7
bool Expr::isImplicitCXXThis() const {
3208
7
  const Expr *E = this;
3209
3210
  // Strip away parentheses and casts we don't care about.
3211
7
  while (true) {
3212
7
    if (const ParenExpr *Paren = dyn_cast<ParenExpr>(E)) {
3213
0
      E = Paren->getSubExpr();
3214
0
      continue;
3215
0
    }
3216
3217
7
    if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
3218
0
      if (ICE->getCastKind() == CK_NoOp ||
3219
0
          ICE->getCastKind() == CK_LValueToRValue ||
3220
0
          ICE->getCastKind() == CK_DerivedToBase ||
3221
0
          ICE->getCastKind() == CK_UncheckedDerivedToBase) {
3222
0
        E = ICE->getSubExpr();
3223
0
        continue;
3224
0
      }
3225
0
    }
3226
3227
7
    if (const UnaryOperator* UnOp = dyn_cast<UnaryOperator>(E)) {
3228
0
      if (UnOp->getOpcode() == UO_Extension) {
3229
0
        E = UnOp->getSubExpr();
3230
0
        continue;
3231
0
      }
3232
0
    }
3233
3234
7
    if (const MaterializeTemporaryExpr *M
3235
7
                                      = dyn_cast<MaterializeTemporaryExpr>(E)) {
3236
0
      E = M->getSubExpr();
3237
0
      continue;
3238
0
    }
3239
3240
7
    break;
3241
7
  }
3242
3243
7
  if (const CXXThisExpr *This = dyn_cast<CXXThisExpr>(E))
3244
0
    return This->isImplicit();
3245
3246
7
  return false;
3247
7
}
3248
3249
/// hasAnyTypeDependentArguments - Determines if any of the expressions
3250
/// in Exprs is type-dependent.
3251
19
bool Expr::hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs) {
3252
26
  for (unsigned I = 0; I < Exprs.size(); ++I)
3253
19
    if (Exprs[I]->isTypeDependent())
3254
12
      return true;
3255
3256
7
  return false;
3257
19
}
3258
3259
bool Expr::isConstantInitializer(ASTContext &Ctx, bool IsForRef,
3260
11
                                 const Expr **Culprit) const {
3261
11
  assert(!isValueDependent() &&
3262
11
         "Expression evaluator can't be called on a dependent expression.");
3263
3264
  // This function is attempting whether an expression is an initializer
3265
  // which can be evaluated at compile-time. It very closely parallels
3266
  // ConstExprEmitter in CGExprConstant.cpp; if they don't match, it
3267
  // will lead to unexpected results.  Like ConstExprEmitter, it falls back
3268
  // to isEvaluatable most of the time.
3269
  //
3270
  // If we ever capture reference-binding directly in the AST, we can
3271
  // kill the second parameter.
3272
3273
11
  if (IsForRef) {
3274
0
    if (auto *EWC = dyn_cast<ExprWithCleanups>(this))
3275
0
      return EWC->getSubExpr()->isConstantInitializer(Ctx, true, Culprit);
3276
0
    if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(this))
3277
0
      return MTE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3278
0
    EvalResult Result;
3279
0
    if (EvaluateAsLValue(Result, Ctx) && !Result.HasSideEffects)
3280
0
      return true;
3281
0
    if (Culprit)
3282
0
      *Culprit = this;
3283
0
    return false;
3284
0
  }
3285
3286
11
  switch (getStmtClass()) {
3287
7
  default: break;
3288
7
  case Stmt::ExprWithCleanupsClass:
3289
0
    return cast<ExprWithCleanups>(this)->getSubExpr()->isConstantInitializer(
3290
0
        Ctx, IsForRef, Culprit);
3291
0
  case StringLiteralClass:
3292
0
  case ObjCEncodeExprClass:
3293
0
    return true;
3294
0
  case CXXTemporaryObjectExprClass:
3295
0
  case CXXConstructExprClass: {
3296
0
    const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3297
3298
0
    if (CE->getConstructor()->isTrivial() &&
3299
0
        CE->getConstructor()->getParent()->hasTrivialDestructor()) {
3300
      // Trivial default constructor
3301
0
      if (!CE->getNumArgs()) return true;
3302
3303
      // Trivial copy constructor
3304
0
      assert(CE->getNumArgs() == 1 && "trivial ctor with > 1 argument");
3305
0
      return CE->getArg(0)->isConstantInitializer(Ctx, false, Culprit);
3306
0
    }
3307
3308
0
    break;
3309
0
  }
3310
0
  case ConstantExprClass: {
3311
    // FIXME: We should be able to return "true" here, but it can lead to extra
3312
    // error messages. E.g. in Sema/array-init.c.
3313
0
    const Expr *Exp = cast<ConstantExpr>(this)->getSubExpr();
3314
0
    return Exp->isConstantInitializer(Ctx, false, Culprit);
3315
0
  }
3316
0
  case CompoundLiteralExprClass: {
3317
    // This handles gcc's extension that allows global initializers like
3318
    // "struct x {int x;} x = (struct x) {};".
3319
    // FIXME: This accepts other cases it shouldn't!
3320
0
    const Expr *Exp = cast<CompoundLiteralExpr>(this)->getInitializer();
3321
0
    return Exp->isConstantInitializer(Ctx, false, Culprit);
3322
0
  }
3323
0
  case DesignatedInitUpdateExprClass: {
3324
0
    const DesignatedInitUpdateExpr *DIUE = cast<DesignatedInitUpdateExpr>(this);
3325
0
    return DIUE->getBase()->isConstantInitializer(Ctx, false, Culprit) &&
3326
0
           DIUE->getUpdater()->isConstantInitializer(Ctx, false, Culprit);
3327
0
  }
3328
0
  case InitListExprClass: {
3329
0
    const InitListExpr *ILE = cast<InitListExpr>(this);
3330
0
    assert(ILE->isSemanticForm() && "InitListExpr must be in semantic form");
3331
0
    if (ILE->getType()->isArrayType()) {
3332
0
      unsigned numInits = ILE->getNumInits();
3333
0
      for (unsigned i = 0; i < numInits; i++) {
3334
0
        if (!ILE->getInit(i)->isConstantInitializer(Ctx, false, Culprit))
3335
0
          return false;
3336
0
      }
3337
0
      return true;
3338
0
    }
3339
3340
0
    if (ILE->getType()->isRecordType()) {
3341
0
      unsigned ElementNo = 0;
3342
0
      RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl();
3343
0
      for (const auto *Field : RD->fields()) {
3344
        // If this is a union, skip all the fields that aren't being initialized.
3345
0
        if (RD->isUnion() && ILE->getInitializedFieldInUnion() != Field)
3346
0
          continue;
3347
3348
        // Don't emit anonymous bitfields, they just affect layout.
3349
0
        if (Field->isUnnamedBitfield())
3350
0
          continue;
3351
3352
0
        if (ElementNo < ILE->getNumInits()) {
3353
0
          const Expr *Elt = ILE->getInit(ElementNo++);
3354
0
          if (Field->isBitField()) {
3355
            // Bitfields have to evaluate to an integer.
3356
0
            EvalResult Result;
3357
0
            if (!Elt->EvaluateAsInt(Result, Ctx)) {
3358
0
              if (Culprit)
3359
0
                *Culprit = Elt;
3360
0
              return false;
3361
0
            }
3362
0
          } else {
3363
0
            bool RefType = Field->getType()->isReferenceType();
3364
0
            if (!Elt->isConstantInitializer(Ctx, RefType, Culprit))
3365
0
              return false;
3366
0
          }
3367
0
        }
3368
0
      }
3369
0
      return true;
3370
0
    }
3371
3372
0
    break;
3373
0
  }
3374
0
  case ImplicitValueInitExprClass:
3375
0
  case NoInitExprClass:
3376
0
    return true;
3377
0
  case ParenExprClass:
3378
0
    return cast<ParenExpr>(this)->getSubExpr()
3379
0
      ->isConstantInitializer(Ctx, IsForRef, Culprit);
3380
0
  case GenericSelectionExprClass:
3381
0
    return cast<GenericSelectionExpr>(this)->getResultExpr()
3382
0
      ->isConstantInitializer(Ctx, IsForRef, Culprit);
3383
0
  case ChooseExprClass:
3384
0
    if (cast<ChooseExpr>(this)->isConditionDependent()) {
3385
0
      if (Culprit)
3386
0
        *Culprit = this;
3387
0
      return false;
3388
0
    }
3389
0
    return cast<ChooseExpr>(this)->getChosenSubExpr()
3390
0
      ->isConstantInitializer(Ctx, IsForRef, Culprit);
3391
0
  case UnaryOperatorClass: {
3392
0
    const UnaryOperator* Exp = cast<UnaryOperator>(this);
3393
0
    if (Exp->getOpcode() == UO_Extension)
3394
0
      return Exp->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3395
0
    break;
3396
0
  }
3397
0
  case CXXFunctionalCastExprClass:
3398
0
  case CXXStaticCastExprClass:
3399
4
  case ImplicitCastExprClass:
3400
4
  case CStyleCastExprClass:
3401
4
  case ObjCBridgedCastExprClass:
3402
4
  case CXXDynamicCastExprClass:
3403
4
  case CXXReinterpretCastExprClass:
3404
4
  case CXXAddrspaceCastExprClass:
3405
4
  case CXXConstCastExprClass: {
3406
4
    const CastExpr *CE = cast<CastExpr>(this);
3407
3408
    // Handle misc casts we want to ignore.
3409
4
    if (CE->getCastKind() == CK_NoOp ||
3410
4
        CE->getCastKind() == CK_LValueToRValue ||
3411
4
        CE->getCastKind() == CK_ToUnion ||
3412
4
        CE->getCastKind() == CK_ConstructorConversion ||
3413
4
        CE->getCastKind() == CK_NonAtomicToAtomic ||
3414
4
        CE->getCastKind() == CK_AtomicToNonAtomic ||
3415
4
        CE->getCastKind() == CK_NullToPointer ||
3416
4
        CE->getCastKind() == CK_IntToOCLSampler)
3417
3
      return CE->getSubExpr()->isConstantInitializer(Ctx, false, Culprit);
3418
3419
1
    break;
3420
4
  }
3421
1
  case MaterializeTemporaryExprClass:
3422
0
    return cast<MaterializeTemporaryExpr>(this)
3423
0
        ->getSubExpr()
3424
0
        ->isConstantInitializer(Ctx, false, Culprit);
3425
3426
0
  case SubstNonTypeTemplateParmExprClass:
3427
0
    return cast<SubstNonTypeTemplateParmExpr>(this)->getReplacement()
3428
0
      ->isConstantInitializer(Ctx, false, Culprit);
3429
0
  case CXXDefaultArgExprClass:
3430
0
    return cast<CXXDefaultArgExpr>(this)->getExpr()
3431
0
      ->isConstantInitializer(Ctx, false, Culprit);
3432
0
  case CXXDefaultInitExprClass:
3433
0
    return cast<CXXDefaultInitExpr>(this)->getExpr()
3434
0
      ->isConstantInitializer(Ctx, false, Culprit);
3435
11
  }
3436
  // Allow certain forms of UB in constant initializers: signed integer
3437
  // overflow and floating-point division by zero. We'll give a warning on
3438
  // these, but they're common enough that we have to accept them.
3439
8
  if (isEvaluatable(Ctx, SE_AllowUndefinedBehavior))
3440
3
    return true;
3441
5
  if (Culprit)
3442
5
    *Culprit = this;
3443
5
  return false;
3444
8
}
3445
3446
0
bool CallExpr::isBuiltinAssumeFalse(const ASTContext &Ctx) const {
3447
0
  unsigned BuiltinID = getBuiltinCallee();
3448
0
  if (BuiltinID != Builtin::BI__assume &&
3449
0
      BuiltinID != Builtin::BI__builtin_assume)
3450
0
    return false;
3451
3452
0
  const Expr* Arg = getArg(0);
3453
0
  bool ArgVal;
3454
0
  return !Arg->isValueDependent() &&
3455
0
         Arg->EvaluateAsBooleanCondition(ArgVal, Ctx) && !ArgVal;
3456
0
}
3457
3458
0
bool CallExpr::isCallToStdMove() const {
3459
0
  return getBuiltinCallee() == Builtin::BImove;
3460
0
}
3461
3462
namespace {
3463
  /// Look for any side effects within a Stmt.
3464
  class SideEffectFinder : public ConstEvaluatedExprVisitor<SideEffectFinder> {
3465
    typedef ConstEvaluatedExprVisitor<SideEffectFinder> Inherited;
3466
    const bool IncludePossibleEffects;
3467
    bool HasSideEffects;
3468
3469
  public:
3470
    explicit SideEffectFinder(const ASTContext &Context, bool IncludePossible)
3471
      : Inherited(Context),
3472
0
        IncludePossibleEffects(IncludePossible), HasSideEffects(false) { }
3473
3474
0
    bool hasSideEffects() const { return HasSideEffects; }
3475
3476
0
    void VisitDecl(const Decl *D) {
3477
0
      if (!D)
3478
0
        return;
3479
3480
      // We assume the caller checks subexpressions (eg, the initializer, VLA
3481
      // bounds) for side-effects on our behalf.
3482
0
      if (auto *VD = dyn_cast<VarDecl>(D)) {
3483
        // Registering a destructor is a side-effect.
3484
0
        if (IncludePossibleEffects && VD->isThisDeclarationADefinition() &&
3485
0
            VD->needsDestruction(Context))
3486
0
          HasSideEffects = true;
3487
0
      }
3488
0
    }
3489
3490
0
    void VisitDeclStmt(const DeclStmt *DS) {
3491
0
      for (auto *D : DS->decls())
3492
0
        VisitDecl(D);
3493
0
      Inherited::VisitDeclStmt(DS);
3494
0
    }
3495
3496
0
    void VisitExpr(const Expr *E) {
3497
0
      if (!HasSideEffects &&
3498
0
          E->HasSideEffects(Context, IncludePossibleEffects))
3499
0
        HasSideEffects = true;
3500
0
    }
3501
  };
3502
}
3503
3504
bool Expr::HasSideEffects(const ASTContext &Ctx,
3505
0
                          bool IncludePossibleEffects) const {
3506
  // In circumstances where we care about definite side effects instead of
3507
  // potential side effects, we want to ignore expressions that are part of a
3508
  // macro expansion as a potential side effect.
3509
0
  if (!IncludePossibleEffects && getExprLoc().isMacroID())
3510
0
    return false;
3511
3512
0
  switch (getStmtClass()) {
3513
0
  case NoStmtClass:
3514
0
  #define ABSTRACT_STMT(Type)
3515
0
  #define STMT(Type, Base) case Type##Class:
3516
0
  #define EXPR(Type, Base)
3517
0
  #include "clang/AST/StmtNodes.inc"
3518
0
    llvm_unreachable("unexpected Expr kind");
3519
3520
0
  case DependentScopeDeclRefExprClass:
3521
0
  case CXXUnresolvedConstructExprClass:
3522
0
  case CXXDependentScopeMemberExprClass:
3523
0
  case UnresolvedLookupExprClass:
3524
0
  case UnresolvedMemberExprClass:
3525
0
  case PackExpansionExprClass:
3526
0
  case SubstNonTypeTemplateParmPackExprClass:
3527
0
  case FunctionParmPackExprClass:
3528
0
  case TypoExprClass:
3529
0
  case RecoveryExprClass:
3530
0
  case CXXFoldExprClass:
3531
    // Make a conservative assumption for dependent nodes.
3532
0
    return IncludePossibleEffects;
3533
3534
0
  case DeclRefExprClass:
3535
0
  case ObjCIvarRefExprClass:
3536
0
  case PredefinedExprClass:
3537
0
  case IntegerLiteralClass:
3538
0
  case FixedPointLiteralClass:
3539
0
  case FloatingLiteralClass:
3540
0
  case ImaginaryLiteralClass:
3541
0
  case StringLiteralClass:
3542
0
  case CharacterLiteralClass:
3543
0
  case OffsetOfExprClass:
3544
0
  case ImplicitValueInitExprClass:
3545
0
  case UnaryExprOrTypeTraitExprClass:
3546
0
  case AddrLabelExprClass:
3547
0
  case GNUNullExprClass:
3548
0
  case ArrayInitIndexExprClass:
3549
0
  case NoInitExprClass:
3550
0
  case CXXBoolLiteralExprClass:
3551
0
  case CXXNullPtrLiteralExprClass:
3552
0
  case CXXThisExprClass:
3553
0
  case CXXScalarValueInitExprClass:
3554
0
  case TypeTraitExprClass:
3555
0
  case ArrayTypeTraitExprClass:
3556
0
  case ExpressionTraitExprClass:
3557
0
  case CXXNoexceptExprClass:
3558
0
  case SizeOfPackExprClass:
3559
0
  case ObjCStringLiteralClass:
3560
0
  case ObjCEncodeExprClass:
3561
0
  case ObjCBoolLiteralExprClass:
3562
0
  case ObjCAvailabilityCheckExprClass:
3563
0
  case CXXUuidofExprClass:
3564
0
  case OpaqueValueExprClass:
3565
0
  case SourceLocExprClass:
3566
0
  case ConceptSpecializationExprClass:
3567
0
  case RequiresExprClass:
3568
0
  case SYCLUniqueStableNameExprClass:
3569
    // These never have a side-effect.
3570
0
    return false;
3571
3572
0
  case ConstantExprClass:
3573
    // FIXME: Move this into the "return false;" block above.
3574
0
    return cast<ConstantExpr>(this)->getSubExpr()->HasSideEffects(
3575
0
        Ctx, IncludePossibleEffects);
3576
3577
0
  case CallExprClass:
3578
0
  case CXXOperatorCallExprClass:
3579
0
  case CXXMemberCallExprClass:
3580
0
  case CUDAKernelCallExprClass:
3581
0
  case UserDefinedLiteralClass: {
3582
    // We don't know a call definitely has side effects, except for calls
3583
    // to pure/const functions that definitely don't.
3584
    // If the call itself is considered side-effect free, check the operands.
3585
0
    const Decl *FD = cast<CallExpr>(this)->getCalleeDecl();
3586
0
    bool IsPure = FD && (FD->hasAttr<ConstAttr>() || FD->hasAttr<PureAttr>());
3587
0
    if (IsPure || !IncludePossibleEffects)
3588
0
      break;
3589
0
    return true;
3590
0
  }
3591
3592
0
  case BlockExprClass:
3593
0
  case CXXBindTemporaryExprClass:
3594
0
    if (!IncludePossibleEffects)
3595
0
      break;
3596
0
    return true;
3597
3598
0
  case MSPropertyRefExprClass:
3599
0
  case MSPropertySubscriptExprClass:
3600
0
  case CompoundAssignOperatorClass:
3601
0
  case VAArgExprClass:
3602
0
  case AtomicExprClass:
3603
0
  case CXXThrowExprClass:
3604
0
  case CXXNewExprClass:
3605
0
  case CXXDeleteExprClass:
3606
0
  case CoawaitExprClass:
3607
0
  case DependentCoawaitExprClass:
3608
0
  case CoyieldExprClass:
3609
    // These always have a side-effect.
3610
0
    return true;
3611
3612
0
  case StmtExprClass: {
3613
    // StmtExprs have a side-effect if any substatement does.
3614
0
    SideEffectFinder Finder(Ctx, IncludePossibleEffects);
3615
0
    Finder.Visit(cast<StmtExpr>(this)->getSubStmt());
3616
0
    return Finder.hasSideEffects();
3617
0
  }
3618
3619
0
  case ExprWithCleanupsClass:
3620
0
    if (IncludePossibleEffects)
3621
0
      if (cast<ExprWithCleanups>(this)->cleanupsHaveSideEffects())
3622
0
        return true;
3623
0
    break;
3624
3625
0
  case ParenExprClass:
3626
0
  case ArraySubscriptExprClass:
3627
0
  case MatrixSubscriptExprClass:
3628
0
  case OMPArraySectionExprClass:
3629
0
  case OMPArrayShapingExprClass:
3630
0
  case OMPIteratorExprClass:
3631
0
  case MemberExprClass:
3632
0
  case ConditionalOperatorClass:
3633
0
  case BinaryConditionalOperatorClass:
3634
0
  case CompoundLiteralExprClass:
3635
0
  case ExtVectorElementExprClass:
3636
0
  case DesignatedInitExprClass:
3637
0
  case DesignatedInitUpdateExprClass:
3638
0
  case ArrayInitLoopExprClass:
3639
0
  case ParenListExprClass:
3640
0
  case CXXPseudoDestructorExprClass:
3641
0
  case CXXRewrittenBinaryOperatorClass:
3642
0
  case CXXStdInitializerListExprClass:
3643
0
  case SubstNonTypeTemplateParmExprClass:
3644
0
  case MaterializeTemporaryExprClass:
3645
0
  case ShuffleVectorExprClass:
3646
0
  case ConvertVectorExprClass:
3647
0
  case AsTypeExprClass:
3648
0
  case CXXParenListInitExprClass:
3649
    // These have a side-effect if any subexpression does.
3650
0
    break;
3651
3652
0
  case UnaryOperatorClass:
3653
0
    if (cast<UnaryOperator>(this)->isIncrementDecrementOp())
3654
0
      return true;
3655
0
    break;
3656
3657
0
  case BinaryOperatorClass:
3658
0
    if (cast<BinaryOperator>(this)->isAssignmentOp())
3659
0
      return true;
3660
0
    break;
3661
3662
0
  case InitListExprClass:
3663
    // FIXME: The children for an InitListExpr doesn't include the array filler.
3664
0
    if (const Expr *E = cast<InitListExpr>(this)->getArrayFiller())
3665
0
      if (E->HasSideEffects(Ctx, IncludePossibleEffects))
3666
0
        return true;
3667
0
    break;
3668
3669
0
  case GenericSelectionExprClass:
3670
0
    return cast<GenericSelectionExpr>(this)->getResultExpr()->
3671
0
        HasSideEffects(Ctx, IncludePossibleEffects);
3672
3673
0
  case ChooseExprClass:
3674
0
    return cast<ChooseExpr>(this)->getChosenSubExpr()->HasSideEffects(
3675
0
        Ctx, IncludePossibleEffects);
3676
3677
0
  case CXXDefaultArgExprClass:
3678
0
    return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(
3679
0
        Ctx, IncludePossibleEffects);
3680
3681
0
  case CXXDefaultInitExprClass: {
3682
0
    const FieldDecl *FD = cast<CXXDefaultInitExpr>(this)->getField();
3683
0
    if (const Expr *E = FD->getInClassInitializer())
3684
0
      return E->HasSideEffects(Ctx, IncludePossibleEffects);
3685
    // If we've not yet parsed the initializer, assume it has side-effects.
3686
0
    return true;
3687
0
  }
3688
3689
0
  case CXXDynamicCastExprClass: {
3690
    // A dynamic_cast expression has side-effects if it can throw.
3691
0
    const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
3692
0
    if (DCE->getTypeAsWritten()->isReferenceType() &&
3693
0
        DCE->getCastKind() == CK_Dynamic)
3694
0
      return true;
3695
0
    }
3696
0
    [[fallthrough]];
3697
0
  case ImplicitCastExprClass:
3698
0
  case CStyleCastExprClass:
3699
0
  case CXXStaticCastExprClass:
3700
0
  case CXXReinterpretCastExprClass:
3701
0
  case CXXConstCastExprClass:
3702
0
  case CXXAddrspaceCastExprClass:
3703
0
  case CXXFunctionalCastExprClass:
3704
0
  case BuiltinBitCastExprClass: {
3705
    // While volatile reads are side-effecting in both C and C++, we treat them
3706
    // as having possible (not definite) side-effects. This allows idiomatic
3707
    // code to behave without warning, such as sizeof(*v) for a volatile-
3708
    // qualified pointer.
3709
0
    if (!IncludePossibleEffects)
3710
0
      break;
3711
3712
0
    const CastExpr *CE = cast<CastExpr>(this);
3713
0
    if (CE->getCastKind() == CK_LValueToRValue &&
3714
0
        CE->getSubExpr()->getType().isVolatileQualified())
3715
0
      return true;
3716
0
    break;
3717
0
  }
3718
3719
0
  case CXXTypeidExprClass:
3720
    // typeid might throw if its subexpression is potentially-evaluated, so has
3721
    // side-effects in that case whether or not its subexpression does.
3722
0
    return cast<CXXTypeidExpr>(this)->isPotentiallyEvaluated();
3723
3724
0
  case CXXConstructExprClass:
3725
0
  case CXXTemporaryObjectExprClass: {
3726
0
    const CXXConstructExpr *CE = cast<CXXConstructExpr>(this);
3727
0
    if (!CE->getConstructor()->isTrivial() && IncludePossibleEffects)
3728
0
      return true;
3729
    // A trivial constructor does not add any side-effects of its own. Just look
3730
    // at its arguments.
3731
0
    break;
3732
0
  }
3733
3734
0
  case CXXInheritedCtorInitExprClass: {
3735
0
    const auto *ICIE = cast<CXXInheritedCtorInitExpr>(this);
3736
0
    if (!ICIE->getConstructor()->isTrivial() && IncludePossibleEffects)
3737
0
      return true;
3738
0
    break;
3739
0
  }
3740
3741
0
  case LambdaExprClass: {
3742
0
    const LambdaExpr *LE = cast<LambdaExpr>(this);
3743
0
    for (Expr *E : LE->capture_inits())
3744
0
      if (E && E->HasSideEffects(Ctx, IncludePossibleEffects))
3745
0
        return true;
3746
0
    return false;
3747
0
  }
3748
3749
0
  case PseudoObjectExprClass: {
3750
    // Only look for side-effects in the semantic form, and look past
3751
    // OpaqueValueExpr bindings in that form.
3752
0
    const PseudoObjectExpr *PO = cast<PseudoObjectExpr>(this);
3753
0
    for (PseudoObjectExpr::const_semantics_iterator I = PO->semantics_begin(),
3754
0
                                                    E = PO->semantics_end();
3755
0
         I != E; ++I) {
3756
0
      const Expr *Subexpr = *I;
3757
0
      if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Subexpr))
3758
0
        Subexpr = OVE->getSourceExpr();
3759
0
      if (Subexpr->HasSideEffects(Ctx, IncludePossibleEffects))
3760
0
        return true;
3761
0
    }
3762
0
    return false;
3763
0
  }
3764
3765
0
  case ObjCBoxedExprClass:
3766
0
  case ObjCArrayLiteralClass:
3767
0
  case ObjCDictionaryLiteralClass:
3768
0
  case ObjCSelectorExprClass:
3769
0
  case ObjCProtocolExprClass:
3770
0
  case ObjCIsaExprClass:
3771
0
  case ObjCIndirectCopyRestoreExprClass:
3772
0
  case ObjCSubscriptRefExprClass:
3773
0
  case ObjCBridgedCastExprClass:
3774
0
  case ObjCMessageExprClass:
3775
0
  case ObjCPropertyRefExprClass:
3776
  // FIXME: Classify these cases better.
3777
0
    if (IncludePossibleEffects)
3778
0
      return true;
3779
0
    break;
3780
0
  }
3781
3782
  // Recurse to children.
3783
0
  for (const Stmt *SubStmt : children())
3784
0
    if (SubStmt &&
3785
0
        cast<Expr>(SubStmt)->HasSideEffects(Ctx, IncludePossibleEffects))
3786
0
      return true;
3787
3788
0
  return false;
3789
0
}
3790
3791
0
FPOptions Expr::getFPFeaturesInEffect(const LangOptions &LO) const {
3792
0
  if (auto Call = dyn_cast<CallExpr>(this))
3793
0
    return Call->getFPFeaturesInEffect(LO);
3794
0
  if (auto UO = dyn_cast<UnaryOperator>(this))
3795
0
    return UO->getFPFeaturesInEffect(LO);
3796
0
  if (auto BO = dyn_cast<BinaryOperator>(this))
3797
0
    return BO->getFPFeaturesInEffect(LO);
3798
0
  if (auto Cast = dyn_cast<CastExpr>(this))
3799
0
    return Cast->getFPFeaturesInEffect(LO);
3800
0
  return FPOptions::defaultWithoutTrailingStorage(LO);
3801
0
}
3802
3803
namespace {
3804
  /// Look for a call to a non-trivial function within an expression.
3805
  class NonTrivialCallFinder : public ConstEvaluatedExprVisitor<NonTrivialCallFinder>
3806
  {
3807
    typedef ConstEvaluatedExprVisitor<NonTrivialCallFinder> Inherited;
3808
3809
    bool NonTrivial;
3810
3811
  public:
3812
    explicit NonTrivialCallFinder(const ASTContext &Context)
3813
0
      : Inherited(Context), NonTrivial(false) { }
3814
3815
0
    bool hasNonTrivialCall() const { return NonTrivial; }
3816
3817
0
    void VisitCallExpr(const CallExpr *E) {
3818
0
      if (const CXXMethodDecl *Method
3819
0
          = dyn_cast_or_null<const CXXMethodDecl>(E->getCalleeDecl())) {
3820
0
        if (Method->isTrivial()) {
3821
          // Recurse to children of the call.
3822
0
          Inherited::VisitStmt(E);
3823
0
          return;
3824
0
        }
3825
0
      }
3826
3827
0
      NonTrivial = true;
3828
0
    }
3829
3830
0
    void VisitCXXConstructExpr(const CXXConstructExpr *E) {
3831
0
      if (E->getConstructor()->isTrivial()) {
3832
        // Recurse to children of the call.
3833
0
        Inherited::VisitStmt(E);
3834
0
        return;
3835
0
      }
3836
3837
0
      NonTrivial = true;
3838
0
    }
3839
3840
0
    void VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E) {
3841
0
      if (E->getTemporary()->getDestructor()->isTrivial()) {
3842
0
        Inherited::VisitStmt(E);
3843
0
        return;
3844
0
      }
3845
3846
0
      NonTrivial = true;
3847
0
    }
3848
  };
3849
}
3850
3851
0
bool Expr::hasNonTrivialCall(const ASTContext &Ctx) const {
3852
0
  NonTrivialCallFinder Finder(Ctx);
3853
0
  Finder.Visit(this);
3854
0
  return Finder.hasNonTrivialCall();
3855
0
}
3856
3857
/// isNullPointerConstant - C99 6.3.2.3p3 - Return whether this is a null
3858
/// pointer constant or not, as well as the specific kind of constant detected.
3859
/// Null pointer constants can be integer constant expressions with the
3860
/// value zero, casts of zero to void*, nullptr (C++0X), or __null
3861
/// (a GNU extension).
3862
Expr::NullPointerConstantKind
3863
Expr::isNullPointerConstant(ASTContext &Ctx,
3864
2
                            NullPointerConstantValueDependence NPC) const {
3865
2
  if (isValueDependent() &&
3866
2
      (!Ctx.getLangOpts().CPlusPlus11 || Ctx.getLangOpts().MSVCCompat)) {
3867
    // Error-dependent expr should never be a null pointer.
3868
0
    if (containsErrors())
3869
0
      return NPCK_NotNull;
3870
0
    switch (NPC) {
3871
0
    case NPC_NeverValueDependent:
3872
0
      llvm_unreachable("Unexpected value dependent expression!");
3873
0
    case NPC_ValueDependentIsNull:
3874
0
      if (isTypeDependent() || getType()->isIntegralType(Ctx))
3875
0
        return NPCK_ZeroExpression;
3876
0
      else
3877
0
        return NPCK_NotNull;
3878
3879
0
    case NPC_ValueDependentIsNotNull:
3880
0
      return NPCK_NotNull;
3881
0
    }
3882
0
  }
3883
3884
  // Strip off a cast to void*, if it exists. Except in C++.
3885
2
  if (const ExplicitCastExpr *CE = dyn_cast<ExplicitCastExpr>(this)) {
3886
0
    if (!Ctx.getLangOpts().CPlusPlus) {
3887
      // Check that it is a cast to void*.
3888
0
      if (const PointerType *PT = CE->getType()->getAs<PointerType>()) {
3889
0
        QualType Pointee = PT->getPointeeType();
3890
0
        Qualifiers Qs = Pointee.getQualifiers();
3891
        // Only (void*)0 or equivalent are treated as nullptr. If pointee type
3892
        // has non-default address space it is not treated as nullptr.
3893
        // (__generic void*)0 in OpenCL 2.0 should not be treated as nullptr
3894
        // since it cannot be assigned to a pointer to constant address space.
3895
0
        if (Ctx.getLangOpts().OpenCL &&
3896
0
            Pointee.getAddressSpace() == Ctx.getDefaultOpenCLPointeeAddrSpace())
3897
0
          Qs.removeAddressSpace();
3898
3899
0
        if (Pointee->isVoidType() && Qs.empty() && // to void*
3900
0
            CE->getSubExpr()->getType()->isIntegerType()) // from int
3901
0
          return CE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3902
0
      }
3903
0
    }
3904
2
  } else if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(this)) {
3905
    // Ignore the ImplicitCastExpr type entirely.
3906
1
    return ICE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3907
1
  } else if (const ParenExpr *PE = dyn_cast<ParenExpr>(this)) {
3908
    // Accept ((void*)0) as a null pointer constant, as many other
3909
    // implementations do.
3910
0
    return PE->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3911
1
  } else if (const GenericSelectionExpr *GE =
3912
1
               dyn_cast<GenericSelectionExpr>(this)) {
3913
0
    if (GE->isResultDependent())
3914
0
      return NPCK_NotNull;
3915
0
    return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
3916
1
  } else if (const ChooseExpr *CE = dyn_cast<ChooseExpr>(this)) {
3917
0
    if (CE->isConditionDependent())
3918
0
      return NPCK_NotNull;
3919
0
    return CE->getChosenSubExpr()->isNullPointerConstant(Ctx, NPC);
3920
1
  } else if (const CXXDefaultArgExpr *DefaultArg
3921
1
               = dyn_cast<CXXDefaultArgExpr>(this)) {
3922
    // See through default argument expressions.
3923
0
    return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
3924
1
  } else if (const CXXDefaultInitExpr *DefaultInit
3925
1
               = dyn_cast<CXXDefaultInitExpr>(this)) {
3926
    // See through default initializer expressions.
3927
0
    return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
3928
1
  } else if (isa<GNUNullExpr>(this)) {
3929
    // The GNU __null extension is always a null pointer constant.
3930
0
    return NPCK_GNUNull;
3931
1
  } else if (const MaterializeTemporaryExpr *M
3932
1
                                   = dyn_cast<MaterializeTemporaryExpr>(this)) {
3933
0
    return M->getSubExpr()->isNullPointerConstant(Ctx, NPC);
3934
1
  } else if (const OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(this)) {
3935
0
    if (const Expr *Source = OVE->getSourceExpr())
3936
0
      return Source->isNullPointerConstant(Ctx, NPC);
3937
0
  }
3938
3939
  // If the expression has no type information, it cannot be a null pointer
3940
  // constant.
3941
1
  if (getType().isNull())
3942
0
    return NPCK_NotNull;
3943
3944
  // C++11/C23 nullptr_t is always a null pointer constant.
3945
1
  if (getType()->isNullPtrType())
3946
0
    return NPCK_CXX11_nullptr;
3947
3948
1
  if (const RecordType *UT = getType()->getAsUnionType())
3949
0
    if (!Ctx.getLangOpts().CPlusPlus11 &&
3950
0
        UT && UT->getDecl()->hasAttr<TransparentUnionAttr>())
3951
0
      if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(this)){
3952
0
        const Expr *InitExpr = CLE->getInitializer();
3953
0
        if (const InitListExpr *ILE = dyn_cast<InitListExpr>(InitExpr))
3954
0
          return ILE->getInit(0)->isNullPointerConstant(Ctx, NPC);
3955
0
      }
3956
  // This expression must be an integer type.
3957
1
  if (!getType()->isIntegerType() ||
3958
1
      (Ctx.getLangOpts().CPlusPlus && getType()->isEnumeralType()))
3959
0
    return NPCK_NotNull;
3960
3961
1
  if (Ctx.getLangOpts().CPlusPlus11) {
3962
    // C++11 [conv.ptr]p1: A null pointer constant is an integer literal with
3963
    // value zero or a prvalue of type std::nullptr_t.
3964
    // Microsoft mode permits C++98 rules reflecting MSVC behavior.
3965
0
    const IntegerLiteral *Lit = dyn_cast<IntegerLiteral>(this);
3966
0
    if (Lit && !Lit->getValue())
3967
0
      return NPCK_ZeroLiteral;
3968
0
    if (!Ctx.getLangOpts().MSVCCompat || !isCXX98IntegralConstantExpr(Ctx))
3969
0
      return NPCK_NotNull;
3970
1
  } else {
3971
    // If we have an integer constant expression, we need to *evaluate* it and
3972
    // test for the value 0.
3973
1
    if (!isIntegerConstantExpr(Ctx))
3974
1
      return NPCK_NotNull;
3975
1
  }
3976
3977
0
  if (EvaluateKnownConstInt(Ctx) != 0)
3978
0
    return NPCK_NotNull;
3979
3980
0
  if (isa<IntegerLiteral>(this))
3981
0
    return NPCK_ZeroLiteral;
3982
0
  return NPCK_ZeroExpression;
3983
0
}
3984
3985
/// If this expression is an l-value for an Objective C
3986
/// property, find the underlying property reference expression.
3987
0
const ObjCPropertyRefExpr *Expr::getObjCProperty() const {
3988
0
  const Expr *E = this;
3989
0
  while (true) {
3990
0
    assert((E->isLValue() && E->getObjectKind() == OK_ObjCProperty) &&
3991
0
           "expression is not a property reference");
3992
0
    E = E->IgnoreParenCasts();
3993
0
    if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3994
0
      if (BO->getOpcode() == BO_Comma) {
3995
0
        E = BO->getRHS();
3996
0
        continue;
3997
0
      }
3998
0
    }
3999
4000
0
    break;
4001
0
  }
4002
4003
0
  return cast<ObjCPropertyRefExpr>(E);
4004
0
}
4005
4006
0
bool Expr::isObjCSelfExpr() const {
4007
0
  const Expr *E = IgnoreParenImpCasts();
4008
4009
0
  const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E);
4010
0
  if (!DRE)
4011
0
    return false;
4012
4013
0
  const ImplicitParamDecl *Param = dyn_cast<ImplicitParamDecl>(DRE->getDecl());
4014
0
  if (!Param)
4015
0
    return false;
4016
4017
0
  const ObjCMethodDecl *M = dyn_cast<ObjCMethodDecl>(Param->getDeclContext());
4018
0
  if (!M)
4019
0
    return false;
4020
4021
0
  return M->getSelfDecl() == Param;
4022
0
}
4023
4024
3
FieldDecl *Expr::getSourceBitField() {
4025
3
  Expr *E = this->IgnoreParens();
4026
4027
4
  while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4028
1
    if (ICE->getCastKind() == CK_LValueToRValue ||
4029
1
        (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp))
4030
1
      E = ICE->getSubExpr()->IgnoreParens();
4031
0
    else
4032
0
      break;
4033
1
  }
4034
4035
3
  if (MemberExpr *MemRef = dyn_cast<MemberExpr>(E))
4036
0
    if (FieldDecl *Field = dyn_cast<FieldDecl>(MemRef->getMemberDecl()))
4037
0
      if (Field->isBitField())
4038
0
        return Field;
4039
4040
3
  if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E)) {
4041
0
    FieldDecl *Ivar = IvarRef->getDecl();
4042
0
    if (Ivar->isBitField())
4043
0
      return Ivar;
4044
0
  }
4045
4046
3
  if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E)) {
4047
1
    if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
4048
0
      if (Field->isBitField())
4049
0
        return Field;
4050
4051
1
    if (BindingDecl *BD = dyn_cast<BindingDecl>(DeclRef->getDecl()))
4052
0
      if (Expr *E = BD->getBinding())
4053
0
        return E->getSourceBitField();
4054
1
  }
4055
4056
3
  if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
4057
0
    if (BinOp->isAssignmentOp() && BinOp->getLHS())
4058
0
      return BinOp->getLHS()->getSourceBitField();
4059
4060
0
    if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
4061
0
      return BinOp->getRHS()->getSourceBitField();
4062
0
  }
4063
4064
3
  if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E))
4065
0
    if (UnOp->isPrefix() && UnOp->isIncrementDecrementOp())
4066
0
      return UnOp->getSubExpr()->getSourceBitField();
4067
4068
3
  return nullptr;
4069
3
}
4070
4071
0
bool Expr::refersToVectorElement() const {
4072
  // FIXME: Why do we not just look at the ObjectKind here?
4073
0
  const Expr *E = this->IgnoreParens();
4074
4075
0
  while (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
4076
0
    if (ICE->isGLValue() && ICE->getCastKind() == CK_NoOp)
4077
0
      E = ICE->getSubExpr()->IgnoreParens();
4078
0
    else
4079
0
      break;
4080
0
  }
4081
4082
0
  if (const ArraySubscriptExpr *ASE = dyn_cast<ArraySubscriptExpr>(E))
4083
0
    return ASE->getBase()->getType()->isVectorType();
4084
4085
0
  if (isa<ExtVectorElementExpr>(E))
4086
0
    return true;
4087
4088
0
  if (auto *DRE = dyn_cast<DeclRefExpr>(E))
4089
0
    if (auto *BD = dyn_cast<BindingDecl>(DRE->getDecl()))
4090
0
      if (auto *E = BD->getBinding())
4091
0
        return E->refersToVectorElement();
4092
4093
0
  return false;
4094
0
}
4095
4096
0
bool Expr::refersToGlobalRegisterVar() const {
4097
0
  const Expr *E = this->IgnoreParenImpCasts();
4098
4099
0
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
4100
0
    if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
4101
0
      if (VD->getStorageClass() == SC_Register &&
4102
0
          VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())
4103
0
        return true;
4104
4105
0
  return false;
4106
0
}
4107
4108
0
bool Expr::isSameComparisonOperand(const Expr* E1, const Expr* E2) {
4109
0
  E1 = E1->IgnoreParens();
4110
0
  E2 = E2->IgnoreParens();
4111
4112
0
  if (E1->getStmtClass() != E2->getStmtClass())
4113
0
    return false;
4114
4115
0
  switch (E1->getStmtClass()) {
4116
0
    default:
4117
0
      return false;
4118
0
    case CXXThisExprClass:
4119
0
      return true;
4120
0
    case DeclRefExprClass: {
4121
      // DeclRefExpr without an ImplicitCastExpr can happen for integral
4122
      // template parameters.
4123
0
      const auto *DRE1 = cast<DeclRefExpr>(E1);
4124
0
      const auto *DRE2 = cast<DeclRefExpr>(E2);
4125
0
      return DRE1->isPRValue() && DRE2->isPRValue() &&
4126
0
             DRE1->getDecl() == DRE2->getDecl();
4127
0
    }
4128
0
    case ImplicitCastExprClass: {
4129
      // Peel off implicit casts.
4130
0
      while (true) {
4131
0
        const auto *ICE1 = dyn_cast<ImplicitCastExpr>(E1);
4132
0
        const auto *ICE2 = dyn_cast<ImplicitCastExpr>(E2);
4133
0
        if (!ICE1 || !ICE2)
4134
0
          return false;
4135
0
        if (ICE1->getCastKind() != ICE2->getCastKind())
4136
0
          return false;
4137
0
        E1 = ICE1->getSubExpr()->IgnoreParens();
4138
0
        E2 = ICE2->getSubExpr()->IgnoreParens();
4139
        // The final cast must be one of these types.
4140
0
        if (ICE1->getCastKind() == CK_LValueToRValue ||
4141
0
            ICE1->getCastKind() == CK_ArrayToPointerDecay ||
4142
0
            ICE1->getCastKind() == CK_FunctionToPointerDecay) {
4143
0
          break;
4144
0
        }
4145
0
      }
4146
4147
0
      const auto *DRE1 = dyn_cast<DeclRefExpr>(E1);
4148
0
      const auto *DRE2 = dyn_cast<DeclRefExpr>(E2);
4149
0
      if (DRE1 && DRE2)
4150
0
        return declaresSameEntity(DRE1->getDecl(), DRE2->getDecl());
4151
4152
0
      const auto *Ivar1 = dyn_cast<ObjCIvarRefExpr>(E1);
4153
0
      const auto *Ivar2 = dyn_cast<ObjCIvarRefExpr>(E2);
4154
0
      if (Ivar1 && Ivar2) {
4155
0
        return Ivar1->isFreeIvar() && Ivar2->isFreeIvar() &&
4156
0
               declaresSameEntity(Ivar1->getDecl(), Ivar2->getDecl());
4157
0
      }
4158
4159
0
      const auto *Array1 = dyn_cast<ArraySubscriptExpr>(E1);
4160
0
      const auto *Array2 = dyn_cast<ArraySubscriptExpr>(E2);
4161
0
      if (Array1 && Array2) {
4162
0
        if (!isSameComparisonOperand(Array1->getBase(), Array2->getBase()))
4163
0
          return false;
4164
4165
0
        auto Idx1 = Array1->getIdx();
4166
0
        auto Idx2 = Array2->getIdx();
4167
0
        const auto Integer1 = dyn_cast<IntegerLiteral>(Idx1);
4168
0
        const auto Integer2 = dyn_cast<IntegerLiteral>(Idx2);
4169
0
        if (Integer1 && Integer2) {
4170
0
          if (!llvm::APInt::isSameValue(Integer1->getValue(),
4171
0
                                        Integer2->getValue()))
4172
0
            return false;
4173
0
        } else {
4174
0
          if (!isSameComparisonOperand(Idx1, Idx2))
4175
0
            return false;
4176
0
        }
4177
4178
0
        return true;
4179
0
      }
4180
4181
      // Walk the MemberExpr chain.
4182
0
      while (isa<MemberExpr>(E1) && isa<MemberExpr>(E2)) {
4183
0
        const auto *ME1 = cast<MemberExpr>(E1);
4184
0
        const auto *ME2 = cast<MemberExpr>(E2);
4185
0
        if (!declaresSameEntity(ME1->getMemberDecl(), ME2->getMemberDecl()))
4186
0
          return false;
4187
0
        if (const auto *D = dyn_cast<VarDecl>(ME1->getMemberDecl()))
4188
0
          if (D->isStaticDataMember())
4189
0
            return true;
4190
0
        E1 = ME1->getBase()->IgnoreParenImpCasts();
4191
0
        E2 = ME2->getBase()->IgnoreParenImpCasts();
4192
0
      }
4193
4194
0
      if (isa<CXXThisExpr>(E1) && isa<CXXThisExpr>(E2))
4195
0
        return true;
4196
4197
      // A static member variable can end the MemberExpr chain with either
4198
      // a MemberExpr or a DeclRefExpr.
4199
0
      auto getAnyDecl = [](const Expr *E) -> const ValueDecl * {
4200
0
        if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4201
0
          return DRE->getDecl();
4202
0
        if (const auto *ME = dyn_cast<MemberExpr>(E))
4203
0
          return ME->getMemberDecl();
4204
0
        return nullptr;
4205
0
      };
4206
4207
0
      const ValueDecl *VD1 = getAnyDecl(E1);
4208
0
      const ValueDecl *VD2 = getAnyDecl(E2);
4209
0
      return declaresSameEntity(VD1, VD2);
4210
0
    }
4211
0
  }
4212
0
}
4213
4214
/// isArrow - Return true if the base expression is a pointer to vector,
4215
/// return false if the base expression is a vector.
4216
0
bool ExtVectorElementExpr::isArrow() const {
4217
0
  return getBase()->getType()->isPointerType();
4218
0
}
4219
4220
0
unsigned ExtVectorElementExpr::getNumElements() const {
4221
0
  if (const VectorType *VT = getType()->getAs<VectorType>())
4222
0
    return VT->getNumElements();
4223
0
  return 1;
4224
0
}
4225
4226
/// containsDuplicateElements - Return true if any element access is repeated.
4227
0
bool ExtVectorElementExpr::containsDuplicateElements() const {
4228
  // FIXME: Refactor this code to an accessor on the AST node which returns the
4229
  // "type" of component access, and share with code below and in Sema.
4230
0
  StringRef Comp = Accessor->getName();
4231
4232
  // Halving swizzles do not contain duplicate elements.
4233
0
  if (Comp == "hi" || Comp == "lo" || Comp == "even" || Comp == "odd")
4234
0
    return false;
4235
4236
  // Advance past s-char prefix on hex swizzles.
4237
0
  if (Comp[0] == 's' || Comp[0] == 'S')
4238
0
    Comp = Comp.substr(1);
4239
4240
0
  for (unsigned i = 0, e = Comp.size(); i != e; ++i)
4241
0
    if (Comp.substr(i + 1).contains(Comp[i]))
4242
0
        return true;
4243
4244
0
  return false;
4245
0
}
4246
4247
/// getEncodedElementAccess - We encode the fields as a llvm ConstantArray.
4248
void ExtVectorElementExpr::getEncodedElementAccess(
4249
0
    SmallVectorImpl<uint32_t> &Elts) const {
4250
0
  StringRef Comp = Accessor->getName();
4251
0
  bool isNumericAccessor = false;
4252
0
  if (Comp[0] == 's' || Comp[0] == 'S') {
4253
0
    Comp = Comp.substr(1);
4254
0
    isNumericAccessor = true;
4255
0
  }
4256
4257
0
  bool isHi =   Comp == "hi";
4258
0
  bool isLo =   Comp == "lo";
4259
0
  bool isEven = Comp == "even";
4260
0
  bool isOdd  = Comp == "odd";
4261
4262
0
  for (unsigned i = 0, e = getNumElements(); i != e; ++i) {
4263
0
    uint64_t Index;
4264
4265
0
    if (isHi)
4266
0
      Index = e + i;
4267
0
    else if (isLo)
4268
0
      Index = i;
4269
0
    else if (isEven)
4270
0
      Index = 2 * i;
4271
0
    else if (isOdd)
4272
0
      Index = 2 * i + 1;
4273
0
    else
4274
0
      Index = ExtVectorType::getAccessorIdx(Comp[i], isNumericAccessor);
4275
4276
0
    Elts.push_back(Index);
4277
0
  }
4278
0
}
4279
4280
ShuffleVectorExpr::ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr *> args,
4281
                                     QualType Type, SourceLocation BLoc,
4282
                                     SourceLocation RP)
4283
    : Expr(ShuffleVectorExprClass, Type, VK_PRValue, OK_Ordinary),
4284
0
      BuiltinLoc(BLoc), RParenLoc(RP), NumExprs(args.size()) {
4285
0
  SubExprs = new (C) Stmt*[args.size()];
4286
0
  for (unsigned i = 0; i != args.size(); i++)
4287
0
    SubExprs[i] = args[i];
4288
4289
0
  setDependence(computeDependence(this));
4290
0
}
4291
4292
0
void ShuffleVectorExpr::setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs) {
4293
0
  if (SubExprs) C.Deallocate(SubExprs);
4294
4295
0
  this->NumExprs = Exprs.size();
4296
0
  SubExprs = new (C) Stmt*[NumExprs];
4297
0
  memcpy(SubExprs, Exprs.data(), sizeof(Expr *) * Exprs.size());
4298
0
}
4299
4300
GenericSelectionExpr::GenericSelectionExpr(
4301
    const ASTContext &, SourceLocation GenericLoc, Expr *ControllingExpr,
4302
    ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4303
    SourceLocation DefaultLoc, SourceLocation RParenLoc,
4304
    bool ContainsUnexpandedParameterPack, unsigned ResultIndex)
4305
    : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4306
           AssocExprs[ResultIndex]->getValueKind(),
4307
           AssocExprs[ResultIndex]->getObjectKind()),
4308
      NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4309
0
      IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4310
0
  assert(AssocTypes.size() == AssocExprs.size() &&
4311
0
         "Must have the same number of association expressions"
4312
0
         " and TypeSourceInfo!");
4313
0
  assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4314
4315
0
  GenericSelectionExprBits.GenericLoc = GenericLoc;
4316
0
  getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4317
0
      ControllingExpr;
4318
0
  std::copy(AssocExprs.begin(), AssocExprs.end(),
4319
0
            getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4320
0
  std::copy(AssocTypes.begin(), AssocTypes.end(),
4321
0
            getTrailingObjects<TypeSourceInfo *>() +
4322
0
                getIndexOfStartOfAssociatedTypes());
4323
4324
0
  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4325
0
}
4326
4327
GenericSelectionExpr::GenericSelectionExpr(
4328
    const ASTContext &, SourceLocation GenericLoc,
4329
    TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4330
    ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4331
    SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4332
    unsigned ResultIndex)
4333
    : Expr(GenericSelectionExprClass, AssocExprs[ResultIndex]->getType(),
4334
           AssocExprs[ResultIndex]->getValueKind(),
4335
           AssocExprs[ResultIndex]->getObjectKind()),
4336
      NumAssocs(AssocExprs.size()), ResultIndex(ResultIndex),
4337
0
      IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4338
0
  assert(AssocTypes.size() == AssocExprs.size() &&
4339
0
         "Must have the same number of association expressions"
4340
0
         " and TypeSourceInfo!");
4341
0
  assert(ResultIndex < NumAssocs && "ResultIndex is out-of-bounds!");
4342
4343
0
  GenericSelectionExprBits.GenericLoc = GenericLoc;
4344
0
  getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4345
0
      ControllingType;
4346
0
  std::copy(AssocExprs.begin(), AssocExprs.end(),
4347
0
            getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4348
0
  std::copy(AssocTypes.begin(), AssocTypes.end(),
4349
0
            getTrailingObjects<TypeSourceInfo *>() +
4350
0
                getIndexOfStartOfAssociatedTypes());
4351
4352
0
  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4353
0
}
4354
4355
GenericSelectionExpr::GenericSelectionExpr(
4356
    const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4357
    ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4358
    SourceLocation DefaultLoc, SourceLocation RParenLoc,
4359
    bool ContainsUnexpandedParameterPack)
4360
    : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4361
           OK_Ordinary),
4362
      NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4363
0
      IsExprPredicate(true), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4364
0
  assert(AssocTypes.size() == AssocExprs.size() &&
4365
0
         "Must have the same number of association expressions"
4366
0
         " and TypeSourceInfo!");
4367
4368
0
  GenericSelectionExprBits.GenericLoc = GenericLoc;
4369
0
  getTrailingObjects<Stmt *>()[getIndexOfControllingExpression()] =
4370
0
      ControllingExpr;
4371
0
  std::copy(AssocExprs.begin(), AssocExprs.end(),
4372
0
            getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4373
0
  std::copy(AssocTypes.begin(), AssocTypes.end(),
4374
0
            getTrailingObjects<TypeSourceInfo *>() +
4375
0
                getIndexOfStartOfAssociatedTypes());
4376
4377
0
  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4378
0
}
4379
4380
GenericSelectionExpr::GenericSelectionExpr(
4381
    const ASTContext &Context, SourceLocation GenericLoc,
4382
    TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4383
    ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4384
    SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack)
4385
    : Expr(GenericSelectionExprClass, Context.DependentTy, VK_PRValue,
4386
           OK_Ordinary),
4387
      NumAssocs(AssocExprs.size()), ResultIndex(ResultDependentIndex),
4388
0
      IsExprPredicate(false), DefaultLoc(DefaultLoc), RParenLoc(RParenLoc) {
4389
0
  assert(AssocTypes.size() == AssocExprs.size() &&
4390
0
         "Must have the same number of association expressions"
4391
0
         " and TypeSourceInfo!");
4392
4393
0
  GenericSelectionExprBits.GenericLoc = GenericLoc;
4394
0
  getTrailingObjects<TypeSourceInfo *>()[getIndexOfControllingType()] =
4395
0
      ControllingType;
4396
0
  std::copy(AssocExprs.begin(), AssocExprs.end(),
4397
0
            getTrailingObjects<Stmt *>() + getIndexOfStartOfAssociatedExprs());
4398
0
  std::copy(AssocTypes.begin(), AssocTypes.end(),
4399
0
            getTrailingObjects<TypeSourceInfo *>() +
4400
0
                getIndexOfStartOfAssociatedTypes());
4401
4402
0
  setDependence(computeDependence(this, ContainsUnexpandedParameterPack));
4403
0
}
4404
4405
GenericSelectionExpr::GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs)
4406
0
    : Expr(GenericSelectionExprClass, Empty), NumAssocs(NumAssocs) {}
4407
4408
GenericSelectionExpr *GenericSelectionExpr::Create(
4409
    const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4410
    ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4411
    SourceLocation DefaultLoc, SourceLocation RParenLoc,
4412
0
    bool ContainsUnexpandedParameterPack, unsigned ResultIndex) {
4413
0
  unsigned NumAssocs = AssocExprs.size();
4414
0
  void *Mem = Context.Allocate(
4415
0
      totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4416
0
      alignof(GenericSelectionExpr));
4417
0
  return new (Mem) GenericSelectionExpr(
4418
0
      Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4419
0
      RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4420
0
}
4421
4422
GenericSelectionExpr *GenericSelectionExpr::Create(
4423
    const ASTContext &Context, SourceLocation GenericLoc, Expr *ControllingExpr,
4424
    ArrayRef<TypeSourceInfo *> AssocTypes, ArrayRef<Expr *> AssocExprs,
4425
    SourceLocation DefaultLoc, SourceLocation RParenLoc,
4426
0
    bool ContainsUnexpandedParameterPack) {
4427
0
  unsigned NumAssocs = AssocExprs.size();
4428
0
  void *Mem = Context.Allocate(
4429
0
      totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4430
0
      alignof(GenericSelectionExpr));
4431
0
  return new (Mem) GenericSelectionExpr(
4432
0
      Context, GenericLoc, ControllingExpr, AssocTypes, AssocExprs, DefaultLoc,
4433
0
      RParenLoc, ContainsUnexpandedParameterPack);
4434
0
}
4435
4436
GenericSelectionExpr *GenericSelectionExpr::Create(
4437
    const ASTContext &Context, SourceLocation GenericLoc,
4438
    TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4439
    ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4440
    SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
4441
0
    unsigned ResultIndex) {
4442
0
  unsigned NumAssocs = AssocExprs.size();
4443
0
  void *Mem = Context.Allocate(
4444
0
      totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4445
0
      alignof(GenericSelectionExpr));
4446
0
  return new (Mem) GenericSelectionExpr(
4447
0
      Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4448
0
      RParenLoc, ContainsUnexpandedParameterPack, ResultIndex);
4449
0
}
4450
4451
GenericSelectionExpr *GenericSelectionExpr::Create(
4452
    const ASTContext &Context, SourceLocation GenericLoc,
4453
    TypeSourceInfo *ControllingType, ArrayRef<TypeSourceInfo *> AssocTypes,
4454
    ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
4455
0
    SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack) {
4456
0
  unsigned NumAssocs = AssocExprs.size();
4457
0
  void *Mem = Context.Allocate(
4458
0
      totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4459
0
      alignof(GenericSelectionExpr));
4460
0
  return new (Mem) GenericSelectionExpr(
4461
0
      Context, GenericLoc, ControllingType, AssocTypes, AssocExprs, DefaultLoc,
4462
0
      RParenLoc, ContainsUnexpandedParameterPack);
4463
0
}
4464
4465
GenericSelectionExpr *
4466
GenericSelectionExpr::CreateEmpty(const ASTContext &Context,
4467
0
                                  unsigned NumAssocs) {
4468
0
  void *Mem = Context.Allocate(
4469
0
      totalSizeToAlloc<Stmt *, TypeSourceInfo *>(1 + NumAssocs, NumAssocs),
4470
0
      alignof(GenericSelectionExpr));
4471
0
  return new (Mem) GenericSelectionExpr(EmptyShell(), NumAssocs);
4472
0
}
4473
4474
//===----------------------------------------------------------------------===//
4475
//  DesignatedInitExpr
4476
//===----------------------------------------------------------------------===//
4477
4478
0
const IdentifierInfo *DesignatedInitExpr::Designator::getFieldName() const {
4479
0
  assert(isFieldDesignator() && "Only valid on a field designator");
4480
0
  if (FieldInfo.NameOrField & 0x01)
4481
0
    return reinterpret_cast<IdentifierInfo *>(FieldInfo.NameOrField & ~0x01);
4482
0
  return getFieldDecl()->getIdentifier();
4483
0
}
4484
4485
DesignatedInitExpr::DesignatedInitExpr(const ASTContext &C, QualType Ty,
4486
                                       llvm::ArrayRef<Designator> Designators,
4487
                                       SourceLocation EqualOrColonLoc,
4488
                                       bool GNUSyntax,
4489
                                       ArrayRef<Expr *> IndexExprs, Expr *Init)
4490
    : Expr(DesignatedInitExprClass, Ty, Init->getValueKind(),
4491
           Init->getObjectKind()),
4492
      EqualOrColonLoc(EqualOrColonLoc), GNUSyntax(GNUSyntax),
4493
0
      NumDesignators(Designators.size()), NumSubExprs(IndexExprs.size() + 1) {
4494
0
  this->Designators = new (C) Designator[NumDesignators];
4495
4496
  // Record the initializer itself.
4497
0
  child_iterator Child = child_begin();
4498
0
  *Child++ = Init;
4499
4500
  // Copy the designators and their subexpressions, computing
4501
  // value-dependence along the way.
4502
0
  unsigned IndexIdx = 0;
4503
0
  for (unsigned I = 0; I != NumDesignators; ++I) {
4504
0
    this->Designators[I] = Designators[I];
4505
0
    if (this->Designators[I].isArrayDesignator()) {
4506
      // Copy the index expressions into permanent storage.
4507
0
      *Child++ = IndexExprs[IndexIdx++];
4508
0
    } else if (this->Designators[I].isArrayRangeDesignator()) {
4509
      // Copy the start/end expressions into permanent storage.
4510
0
      *Child++ = IndexExprs[IndexIdx++];
4511
0
      *Child++ = IndexExprs[IndexIdx++];
4512
0
    }
4513
0
  }
4514
4515
0
  assert(IndexIdx == IndexExprs.size() && "Wrong number of index expressions");
4516
0
  setDependence(computeDependence(this));
4517
0
}
4518
4519
DesignatedInitExpr *
4520
DesignatedInitExpr::Create(const ASTContext &C,
4521
                           llvm::ArrayRef<Designator> Designators,
4522
                           ArrayRef<Expr*> IndexExprs,
4523
                           SourceLocation ColonOrEqualLoc,
4524
0
                           bool UsesColonSyntax, Expr *Init) {
4525
0
  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(IndexExprs.size() + 1),
4526
0
                         alignof(DesignatedInitExpr));
4527
0
  return new (Mem) DesignatedInitExpr(C, C.VoidTy, Designators,
4528
0
                                      ColonOrEqualLoc, UsesColonSyntax,
4529
0
                                      IndexExprs, Init);
4530
0
}
4531
4532
DesignatedInitExpr *DesignatedInitExpr::CreateEmpty(const ASTContext &C,
4533
0
                                                    unsigned NumIndexExprs) {
4534
0
  void *Mem = C.Allocate(totalSizeToAlloc<Stmt *>(NumIndexExprs + 1),
4535
0
                         alignof(DesignatedInitExpr));
4536
0
  return new (Mem) DesignatedInitExpr(NumIndexExprs + 1);
4537
0
}
4538
4539
void DesignatedInitExpr::setDesignators(const ASTContext &C,
4540
                                        const Designator *Desigs,
4541
0
                                        unsigned NumDesigs) {
4542
0
  Designators = new (C) Designator[NumDesigs];
4543
0
  NumDesignators = NumDesigs;
4544
0
  for (unsigned I = 0; I != NumDesigs; ++I)
4545
0
    Designators[I] = Desigs[I];
4546
0
}
4547
4548
0
SourceRange DesignatedInitExpr::getDesignatorsSourceRange() const {
4549
0
  DesignatedInitExpr *DIE = const_cast<DesignatedInitExpr*>(this);
4550
0
  if (size() == 1)
4551
0
    return DIE->getDesignator(0)->getSourceRange();
4552
0
  return SourceRange(DIE->getDesignator(0)->getBeginLoc(),
4553
0
                     DIE->getDesignator(size() - 1)->getEndLoc());
4554
0
}
4555
4556
0
SourceLocation DesignatedInitExpr::getBeginLoc() const {
4557
0
  auto *DIE = const_cast<DesignatedInitExpr *>(this);
4558
0
  Designator &First = *DIE->getDesignator(0);
4559
0
  if (First.isFieldDesignator())
4560
0
    return GNUSyntax ? First.getFieldLoc() : First.getDotLoc();
4561
0
  return First.getLBracketLoc();
4562
0
}
4563
4564
0
SourceLocation DesignatedInitExpr::getEndLoc() const {
4565
0
  return getInit()->getEndLoc();
4566
0
}
4567
4568
0
Expr *DesignatedInitExpr::getArrayIndex(const Designator& D) const {
4569
0
  assert(D.isArrayDesignator() && "Requires array designator");
4570
0
  return getSubExpr(D.getArrayIndex() + 1);
4571
0
}
4572
4573
0
Expr *DesignatedInitExpr::getArrayRangeStart(const Designator &D) const {
4574
0
  assert(D.isArrayRangeDesignator() && "Requires array range designator");
4575
0
  return getSubExpr(D.getArrayIndex() + 1);
4576
0
}
4577
4578
0
Expr *DesignatedInitExpr::getArrayRangeEnd(const Designator &D) const {
4579
0
  assert(D.isArrayRangeDesignator() && "Requires array range designator");
4580
0
  return getSubExpr(D.getArrayIndex() + 2);
4581
0
}
4582
4583
/// Replaces the designator at index @p Idx with the series
4584
/// of designators in [First, Last).
4585
void DesignatedInitExpr::ExpandDesignator(const ASTContext &C, unsigned Idx,
4586
                                          const Designator *First,
4587
0
                                          const Designator *Last) {
4588
0
  unsigned NumNewDesignators = Last - First;
4589
0
  if (NumNewDesignators == 0) {
4590
0
    std::copy_backward(Designators + Idx + 1,
4591
0
                       Designators + NumDesignators,
4592
0
                       Designators + Idx);
4593
0
    --NumNewDesignators;
4594
0
    return;
4595
0
  }
4596
0
  if (NumNewDesignators == 1) {
4597
0
    Designators[Idx] = *First;
4598
0
    return;
4599
0
  }
4600
4601
0
  Designator *NewDesignators
4602
0
    = new (C) Designator[NumDesignators - 1 + NumNewDesignators];
4603
0
  std::copy(Designators, Designators + Idx, NewDesignators);
4604
0
  std::copy(First, Last, NewDesignators + Idx);
4605
0
  std::copy(Designators + Idx + 1, Designators + NumDesignators,
4606
0
            NewDesignators + Idx + NumNewDesignators);
4607
0
  Designators = NewDesignators;
4608
0
  NumDesignators = NumDesignators - 1 + NumNewDesignators;
4609
0
}
4610
4611
DesignatedInitUpdateExpr::DesignatedInitUpdateExpr(const ASTContext &C,
4612
                                                   SourceLocation lBraceLoc,
4613
                                                   Expr *baseExpr,
4614
                                                   SourceLocation rBraceLoc)
4615
    : Expr(DesignatedInitUpdateExprClass, baseExpr->getType(), VK_PRValue,
4616
0
           OK_Ordinary) {
4617
0
  BaseAndUpdaterExprs[0] = baseExpr;
4618
4619
0
  InitListExpr *ILE =
4620
0
      new (C) InitListExpr(C, lBraceLoc, std::nullopt, rBraceLoc);
4621
0
  ILE->setType(baseExpr->getType());
4622
0
  BaseAndUpdaterExprs[1] = ILE;
4623
4624
  // FIXME: this is wrong, set it correctly.
4625
0
  setDependence(ExprDependence::None);
4626
0
}
4627
4628
0
SourceLocation DesignatedInitUpdateExpr::getBeginLoc() const {
4629
0
  return getBase()->getBeginLoc();
4630
0
}
4631
4632
0
SourceLocation DesignatedInitUpdateExpr::getEndLoc() const {
4633
0
  return getBase()->getEndLoc();
4634
0
}
4635
4636
ParenListExpr::ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
4637
                             SourceLocation RParenLoc)
4638
    : Expr(ParenListExprClass, QualType(), VK_PRValue, OK_Ordinary),
4639
11
      LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4640
11
  ParenListExprBits.NumExprs = Exprs.size();
4641
4642
22
  for (unsigned I = 0, N = Exprs.size(); I != N; ++I)
4643
11
    getTrailingObjects<Stmt *>()[I] = Exprs[I];
4644
11
  setDependence(computeDependence(this));
4645
11
}
4646
4647
ParenListExpr::ParenListExpr(EmptyShell Empty, unsigned NumExprs)
4648
0
    : Expr(ParenListExprClass, Empty) {
4649
0
  ParenListExprBits.NumExprs = NumExprs;
4650
0
}
4651
4652
ParenListExpr *ParenListExpr::Create(const ASTContext &Ctx,
4653
                                     SourceLocation LParenLoc,
4654
                                     ArrayRef<Expr *> Exprs,
4655
11
                                     SourceLocation RParenLoc) {
4656
11
  void *Mem = Ctx.Allocate(totalSizeToAlloc<Stmt *>(Exprs.size()),
4657
11
                           alignof(ParenListExpr));
4658
11
  return new (Mem) ParenListExpr(LParenLoc, Exprs, RParenLoc);
4659
11
}
4660
4661
ParenListExpr *ParenListExpr::CreateEmpty(const ASTContext &Ctx,
4662
0
                                          unsigned NumExprs) {
4663
0
  void *Mem =
4664
0
      Ctx.Allocate(totalSizeToAlloc<Stmt *>(NumExprs), alignof(ParenListExpr));
4665
0
  return new (Mem) ParenListExpr(EmptyShell(), NumExprs);
4666
0
}
4667
4668
BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4669
                               Opcode opc, QualType ResTy, ExprValueKind VK,
4670
                               ExprObjectKind OK, SourceLocation opLoc,
4671
                               FPOptionsOverride FPFeatures)
4672
26
    : Expr(BinaryOperatorClass, ResTy, VK, OK) {
4673
26
  BinaryOperatorBits.Opc = opc;
4674
26
  assert(!isCompoundAssignmentOp() &&
4675
26
         "Use CompoundAssignOperator for compound assignments");
4676
0
  BinaryOperatorBits.OpLoc = opLoc;
4677
26
  SubExprs[LHS] = lhs;
4678
26
  SubExprs[RHS] = rhs;
4679
26
  BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4680
26
  if (hasStoredFPFeatures())
4681
0
    setStoredFPFeatures(FPFeatures);
4682
26
  setDependence(computeDependence(this));
4683
26
}
4684
4685
BinaryOperator::BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
4686
                               Opcode opc, QualType ResTy, ExprValueKind VK,
4687
                               ExprObjectKind OK, SourceLocation opLoc,
4688
                               FPOptionsOverride FPFeatures, bool dead2)
4689
0
    : Expr(CompoundAssignOperatorClass, ResTy, VK, OK) {
4690
0
  BinaryOperatorBits.Opc = opc;
4691
0
  assert(isCompoundAssignmentOp() &&
4692
0
         "Use CompoundAssignOperator for compound assignments");
4693
0
  BinaryOperatorBits.OpLoc = opLoc;
4694
0
  SubExprs[LHS] = lhs;
4695
0
  SubExprs[RHS] = rhs;
4696
0
  BinaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4697
0
  if (hasStoredFPFeatures())
4698
0
    setStoredFPFeatures(FPFeatures);
4699
0
  setDependence(computeDependence(this));
4700
0
}
4701
4702
BinaryOperator *BinaryOperator::CreateEmpty(const ASTContext &C,
4703
0
                                            bool HasFPFeatures) {
4704
0
  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4705
0
  void *Mem =
4706
0
      C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4707
0
  return new (Mem) BinaryOperator(EmptyShell());
4708
0
}
4709
4710
BinaryOperator *BinaryOperator::Create(const ASTContext &C, Expr *lhs,
4711
                                       Expr *rhs, Opcode opc, QualType ResTy,
4712
                                       ExprValueKind VK, ExprObjectKind OK,
4713
                                       SourceLocation opLoc,
4714
26
                                       FPOptionsOverride FPFeatures) {
4715
26
  bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4716
26
  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4717
26
  void *Mem =
4718
26
      C.Allocate(sizeof(BinaryOperator) + Extra, alignof(BinaryOperator));
4719
26
  return new (Mem)
4720
26
      BinaryOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures);
4721
26
}
4722
4723
CompoundAssignOperator *
4724
0
CompoundAssignOperator::CreateEmpty(const ASTContext &C, bool HasFPFeatures) {
4725
0
  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4726
0
  void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4727
0
                         alignof(CompoundAssignOperator));
4728
0
  return new (Mem) CompoundAssignOperator(C, EmptyShell(), HasFPFeatures);
4729
0
}
4730
4731
CompoundAssignOperator *
4732
CompoundAssignOperator::Create(const ASTContext &C, Expr *lhs, Expr *rhs,
4733
                               Opcode opc, QualType ResTy, ExprValueKind VK,
4734
                               ExprObjectKind OK, SourceLocation opLoc,
4735
                               FPOptionsOverride FPFeatures,
4736
0
                               QualType CompLHSType, QualType CompResultType) {
4737
0
  bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4738
0
  unsigned Extra = sizeOfTrailingObjects(HasFPFeatures);
4739
0
  void *Mem = C.Allocate(sizeof(CompoundAssignOperator) + Extra,
4740
0
                         alignof(CompoundAssignOperator));
4741
0
  return new (Mem)
4742
0
      CompoundAssignOperator(C, lhs, rhs, opc, ResTy, VK, OK, opLoc, FPFeatures,
4743
0
                             CompLHSType, CompResultType);
4744
0
}
4745
4746
UnaryOperator *UnaryOperator::CreateEmpty(const ASTContext &C,
4747
0
                                          bool hasFPFeatures) {
4748
0
  void *Mem = C.Allocate(totalSizeToAlloc<FPOptionsOverride>(hasFPFeatures),
4749
0
                         alignof(UnaryOperator));
4750
0
  return new (Mem) UnaryOperator(hasFPFeatures, EmptyShell());
4751
0
}
4752
4753
UnaryOperator::UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc,
4754
                             QualType type, ExprValueKind VK, ExprObjectKind OK,
4755
                             SourceLocation l, bool CanOverflow,
4756
                             FPOptionsOverride FPFeatures)
4757
11
    : Expr(UnaryOperatorClass, type, VK, OK), Val(input) {
4758
11
  UnaryOperatorBits.Opc = opc;
4759
11
  UnaryOperatorBits.CanOverflow = CanOverflow;
4760
11
  UnaryOperatorBits.Loc = l;
4761
11
  UnaryOperatorBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
4762
11
  if (hasStoredFPFeatures())
4763
0
    setStoredFPFeatures(FPFeatures);
4764
11
  setDependence(computeDependence(this, Ctx));
4765
11
}
4766
4767
UnaryOperator *UnaryOperator::Create(const ASTContext &C, Expr *input,
4768
                                     Opcode opc, QualType type,
4769
                                     ExprValueKind VK, ExprObjectKind OK,
4770
                                     SourceLocation l, bool CanOverflow,
4771
11
                                     FPOptionsOverride FPFeatures) {
4772
11
  bool HasFPFeatures = FPFeatures.requiresTrailingStorage();
4773
11
  unsigned Size = totalSizeToAlloc<FPOptionsOverride>(HasFPFeatures);
4774
11
  void *Mem = C.Allocate(Size, alignof(UnaryOperator));
4775
11
  return new (Mem)
4776
11
      UnaryOperator(C, input, opc, type, VK, OK, l, CanOverflow, FPFeatures);
4777
11
}
4778
4779
0
const OpaqueValueExpr *OpaqueValueExpr::findInCopyConstruct(const Expr *e) {
4780
0
  if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(e))
4781
0
    e = ewc->getSubExpr();
4782
0
  if (const MaterializeTemporaryExpr *m = dyn_cast<MaterializeTemporaryExpr>(e))
4783
0
    e = m->getSubExpr();
4784
0
  e = cast<CXXConstructExpr>(e)->getArg(0);
4785
0
  while (const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
4786
0
    e = ice->getSubExpr();
4787
0
  return cast<OpaqueValueExpr>(e);
4788
0
}
4789
4790
PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &Context,
4791
                                           EmptyShell sh,
4792
0
                                           unsigned numSemanticExprs) {
4793
0
  void *buffer =
4794
0
      Context.Allocate(totalSizeToAlloc<Expr *>(1 + numSemanticExprs),
4795
0
                       alignof(PseudoObjectExpr));
4796
0
  return new(buffer) PseudoObjectExpr(sh, numSemanticExprs);
4797
0
}
4798
4799
PseudoObjectExpr::PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs)
4800
0
  : Expr(PseudoObjectExprClass, shell) {
4801
0
  PseudoObjectExprBits.NumSubExprs = numSemanticExprs + 1;
4802
0
}
4803
4804
PseudoObjectExpr *PseudoObjectExpr::Create(const ASTContext &C, Expr *syntax,
4805
                                           ArrayRef<Expr*> semantics,
4806
0
                                           unsigned resultIndex) {
4807
0
  assert(syntax && "no syntactic expression!");
4808
0
  assert(semantics.size() && "no semantic expressions!");
4809
4810
0
  QualType type;
4811
0
  ExprValueKind VK;
4812
0
  if (resultIndex == NoResult) {
4813
0
    type = C.VoidTy;
4814
0
    VK = VK_PRValue;
4815
0
  } else {
4816
0
    assert(resultIndex < semantics.size());
4817
0
    type = semantics[resultIndex]->getType();
4818
0
    VK = semantics[resultIndex]->getValueKind();
4819
0
    assert(semantics[resultIndex]->getObjectKind() == OK_Ordinary);
4820
0
  }
4821
4822
0
  void *buffer = C.Allocate(totalSizeToAlloc<Expr *>(semantics.size() + 1),
4823
0
                            alignof(PseudoObjectExpr));
4824
0
  return new(buffer) PseudoObjectExpr(type, VK, syntax, semantics,
4825
0
                                      resultIndex);
4826
0
}
4827
4828
PseudoObjectExpr::PseudoObjectExpr(QualType type, ExprValueKind VK,
4829
                                   Expr *syntax, ArrayRef<Expr *> semantics,
4830
                                   unsigned resultIndex)
4831
0
    : Expr(PseudoObjectExprClass, type, VK, OK_Ordinary) {
4832
0
  PseudoObjectExprBits.NumSubExprs = semantics.size() + 1;
4833
0
  PseudoObjectExprBits.ResultIndex = resultIndex + 1;
4834
4835
0
  for (unsigned i = 0, e = semantics.size() + 1; i != e; ++i) {
4836
0
    Expr *E = (i == 0 ? syntax : semantics[i-1]);
4837
0
    getSubExprsBuffer()[i] = E;
4838
4839
0
    if (isa<OpaqueValueExpr>(E))
4840
0
      assert(cast<OpaqueValueExpr>(E)->getSourceExpr() != nullptr &&
4841
0
             "opaque-value semantic expressions for pseudo-object "
4842
0
             "operations must have sources");
4843
0
  }
4844
4845
0
  setDependence(computeDependence(this));
4846
0
}
4847
4848
//===----------------------------------------------------------------------===//
4849
//  Child Iterators for iterating over subexpressions/substatements
4850
//===----------------------------------------------------------------------===//
4851
4852
// UnaryExprOrTypeTraitExpr
4853
0
Stmt::child_range UnaryExprOrTypeTraitExpr::children() {
4854
0
  const_child_range CCR =
4855
0
      const_cast<const UnaryExprOrTypeTraitExpr *>(this)->children();
4856
0
  return child_range(cast_away_const(CCR.begin()), cast_away_const(CCR.end()));
4857
0
}
4858
4859
0
Stmt::const_child_range UnaryExprOrTypeTraitExpr::children() const {
4860
  // If this is of a type and the type is a VLA type (and not a typedef), the
4861
  // size expression of the VLA needs to be treated as an executable expression.
4862
  // Why isn't this weirdness documented better in StmtIterator?
4863
0
  if (isArgumentType()) {
4864
0
    if (const VariableArrayType *T =
4865
0
            dyn_cast<VariableArrayType>(getArgumentType().getTypePtr()))
4866
0
      return const_child_range(const_child_iterator(T), const_child_iterator());
4867
0
    return const_child_range(const_child_iterator(), const_child_iterator());
4868
0
  }
4869
0
  return const_child_range(&Argument.Ex, &Argument.Ex + 1);
4870
0
}
4871
4872
AtomicExpr::AtomicExpr(SourceLocation BLoc, ArrayRef<Expr *> args, QualType t,
4873
                       AtomicOp op, SourceLocation RP)
4874
    : Expr(AtomicExprClass, t, VK_PRValue, OK_Ordinary),
4875
0
      NumSubExprs(args.size()), BuiltinLoc(BLoc), RParenLoc(RP), Op(op) {
4876
0
  assert(args.size() == getNumSubExprs(op) && "wrong number of subexpressions");
4877
0
  for (unsigned i = 0; i != args.size(); i++)
4878
0
    SubExprs[i] = args[i];
4879
0
  setDependence(computeDependence(this));
4880
0
}
4881
4882
0
unsigned AtomicExpr::getNumSubExprs(AtomicOp Op) {
4883
0
  switch (Op) {
4884
0
  case AO__c11_atomic_init:
4885
0
  case AO__opencl_atomic_init:
4886
0
  case AO__c11_atomic_load:
4887
0
  case AO__atomic_load_n:
4888
0
    return 2;
4889
4890
0
  case AO__scoped_atomic_load_n:
4891
0
  case AO__opencl_atomic_load:
4892
0
  case AO__hip_atomic_load:
4893
0
  case AO__c11_atomic_store:
4894
0
  case AO__c11_atomic_exchange:
4895
0
  case AO__atomic_load:
4896
0
  case AO__atomic_store:
4897
0
  case AO__atomic_store_n:
4898
0
  case AO__atomic_exchange_n:
4899
0
  case AO__c11_atomic_fetch_add:
4900
0
  case AO__c11_atomic_fetch_sub:
4901
0
  case AO__c11_atomic_fetch_and:
4902
0
  case AO__c11_atomic_fetch_or:
4903
0
  case AO__c11_atomic_fetch_xor:
4904
0
  case AO__c11_atomic_fetch_nand:
4905
0
  case AO__c11_atomic_fetch_max:
4906
0
  case AO__c11_atomic_fetch_min:
4907
0
  case AO__atomic_fetch_add:
4908
0
  case AO__atomic_fetch_sub:
4909
0
  case AO__atomic_fetch_and:
4910
0
  case AO__atomic_fetch_or:
4911
0
  case AO__atomic_fetch_xor:
4912
0
  case AO__atomic_fetch_nand:
4913
0
  case AO__atomic_add_fetch:
4914
0
  case AO__atomic_sub_fetch:
4915
0
  case AO__atomic_and_fetch:
4916
0
  case AO__atomic_or_fetch:
4917
0
  case AO__atomic_xor_fetch:
4918
0
  case AO__atomic_nand_fetch:
4919
0
  case AO__atomic_min_fetch:
4920
0
  case AO__atomic_max_fetch:
4921
0
  case AO__atomic_fetch_min:
4922
0
  case AO__atomic_fetch_max:
4923
0
    return 3;
4924
4925
0
  case AO__scoped_atomic_load:
4926
0
  case AO__scoped_atomic_store:
4927
0
  case AO__scoped_atomic_store_n:
4928
0
  case AO__scoped_atomic_fetch_add:
4929
0
  case AO__scoped_atomic_fetch_sub:
4930
0
  case AO__scoped_atomic_fetch_and:
4931
0
  case AO__scoped_atomic_fetch_or:
4932
0
  case AO__scoped_atomic_fetch_xor:
4933
0
  case AO__scoped_atomic_fetch_nand:
4934
0
  case AO__scoped_atomic_add_fetch:
4935
0
  case AO__scoped_atomic_sub_fetch:
4936
0
  case AO__scoped_atomic_and_fetch:
4937
0
  case AO__scoped_atomic_or_fetch:
4938
0
  case AO__scoped_atomic_xor_fetch:
4939
0
  case AO__scoped_atomic_nand_fetch:
4940
0
  case AO__scoped_atomic_min_fetch:
4941
0
  case AO__scoped_atomic_max_fetch:
4942
0
  case AO__scoped_atomic_fetch_min:
4943
0
  case AO__scoped_atomic_fetch_max:
4944
0
  case AO__scoped_atomic_exchange_n:
4945
0
  case AO__hip_atomic_exchange:
4946
0
  case AO__hip_atomic_fetch_add:
4947
0
  case AO__hip_atomic_fetch_sub:
4948
0
  case AO__hip_atomic_fetch_and:
4949
0
  case AO__hip_atomic_fetch_or:
4950
0
  case AO__hip_atomic_fetch_xor:
4951
0
  case AO__hip_atomic_fetch_min:
4952
0
  case AO__hip_atomic_fetch_max:
4953
0
  case AO__opencl_atomic_store:
4954
0
  case AO__hip_atomic_store:
4955
0
  case AO__opencl_atomic_exchange:
4956
0
  case AO__opencl_atomic_fetch_add:
4957
0
  case AO__opencl_atomic_fetch_sub:
4958
0
  case AO__opencl_atomic_fetch_and:
4959
0
  case AO__opencl_atomic_fetch_or:
4960
0
  case AO__opencl_atomic_fetch_xor:
4961
0
  case AO__opencl_atomic_fetch_min:
4962
0
  case AO__opencl_atomic_fetch_max:
4963
0
  case AO__atomic_exchange:
4964
0
    return 4;
4965
4966
0
  case AO__scoped_atomic_exchange:
4967
0
  case AO__c11_atomic_compare_exchange_strong:
4968
0
  case AO__c11_atomic_compare_exchange_weak:
4969
0
    return 5;
4970
0
  case AO__hip_atomic_compare_exchange_strong:
4971
0
  case AO__opencl_atomic_compare_exchange_strong:
4972
0
  case AO__opencl_atomic_compare_exchange_weak:
4973
0
  case AO__hip_atomic_compare_exchange_weak:
4974
0
  case AO__atomic_compare_exchange:
4975
0
  case AO__atomic_compare_exchange_n:
4976
0
    return 6;
4977
4978
0
  case AO__scoped_atomic_compare_exchange:
4979
0
  case AO__scoped_atomic_compare_exchange_n:
4980
0
    return 7;
4981
0
  }
4982
0
  llvm_unreachable("unknown atomic op");
4983
0
}
4984
4985
0
QualType AtomicExpr::getValueType() const {
4986
0
  auto T = getPtr()->getType()->castAs<PointerType>()->getPointeeType();
4987
0
  if (auto AT = T->getAs<AtomicType>())
4988
0
    return AT->getValueType();
4989
0
  return T;
4990
0
}
4991
4992
0
QualType OMPArraySectionExpr::getBaseOriginalType(const Expr *Base) {
4993
0
  unsigned ArraySectionCount = 0;
4994
0
  while (auto *OASE = dyn_cast<OMPArraySectionExpr>(Base->IgnoreParens())) {
4995
0
    Base = OASE->getBase();
4996
0
    ++ArraySectionCount;
4997
0
  }
4998
0
  while (auto *ASE =
4999
0
             dyn_cast<ArraySubscriptExpr>(Base->IgnoreParenImpCasts())) {
5000
0
    Base = ASE->getBase();
5001
0
    ++ArraySectionCount;
5002
0
  }
5003
0
  Base = Base->IgnoreParenImpCasts();
5004
0
  auto OriginalTy = Base->getType();
5005
0
  if (auto *DRE = dyn_cast<DeclRefExpr>(Base))
5006
0
    if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
5007
0
      OriginalTy = PVD->getOriginalType().getNonReferenceType();
5008
5009
0
  for (unsigned Cnt = 0; Cnt < ArraySectionCount; ++Cnt) {
5010
0
    if (OriginalTy->isAnyPointerType())
5011
0
      OriginalTy = OriginalTy->getPointeeType();
5012
0
    else if (OriginalTy->isArrayType())
5013
0
      OriginalTy = OriginalTy->castAsArrayTypeUnsafe()->getElementType();
5014
0
    else
5015
0
      return {};
5016
0
  }
5017
0
  return OriginalTy;
5018
0
}
5019
5020
RecoveryExpr::RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
5021
                           SourceLocation EndLoc, ArrayRef<Expr *> SubExprs)
5022
    : Expr(RecoveryExprClass, T.getNonReferenceType(),
5023
           T->isDependentType() ? VK_LValue : getValueKindForType(T),
5024
           OK_Ordinary),
5025
258
      BeginLoc(BeginLoc), EndLoc(EndLoc), NumExprs(SubExprs.size()) {
5026
258
  assert(!T.isNull());
5027
0
  assert(!llvm::is_contained(SubExprs, nullptr));
5028
5029
0
  llvm::copy(SubExprs, getTrailingObjects<Expr *>());
5030
258
  setDependence(computeDependence(this));
5031
258
}
5032
5033
RecoveryExpr *RecoveryExpr::Create(ASTContext &Ctx, QualType T,
5034
                                   SourceLocation BeginLoc,
5035
                                   SourceLocation EndLoc,
5036
258
                                   ArrayRef<Expr *> SubExprs) {
5037
258
  void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(SubExprs.size()),
5038
258
                           alignof(RecoveryExpr));
5039
258
  return new (Mem) RecoveryExpr(Ctx, T, BeginLoc, EndLoc, SubExprs);
5040
258
}
5041
5042
0
RecoveryExpr *RecoveryExpr::CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs) {
5043
0
  void *Mem = Ctx.Allocate(totalSizeToAlloc<Expr *>(NumSubExprs),
5044
0
                           alignof(RecoveryExpr));
5045
0
  return new (Mem) RecoveryExpr(EmptyShell(), NumSubExprs);
5046
0
}
5047
5048
0
void OMPArrayShapingExpr::setDimensions(ArrayRef<Expr *> Dims) {
5049
0
  assert(
5050
0
      NumDims == Dims.size() &&
5051
0
      "Preallocated number of dimensions is different from the provided one.");
5052
0
  llvm::copy(Dims, getTrailingObjects<Expr *>());
5053
0
}
5054
5055
0
void OMPArrayShapingExpr::setBracketsRanges(ArrayRef<SourceRange> BR) {
5056
0
  assert(
5057
0
      NumDims == BR.size() &&
5058
0
      "Preallocated number of dimensions is different from the provided one.");
5059
0
  llvm::copy(BR, getTrailingObjects<SourceRange>());
5060
0
}
5061
5062
OMPArrayShapingExpr::OMPArrayShapingExpr(QualType ExprTy, Expr *Op,
5063
                                         SourceLocation L, SourceLocation R,
5064
                                         ArrayRef<Expr *> Dims)
5065
    : Expr(OMPArrayShapingExprClass, ExprTy, VK_LValue, OK_Ordinary), LPLoc(L),
5066
0
      RPLoc(R), NumDims(Dims.size()) {
5067
0
  setBase(Op);
5068
0
  setDimensions(Dims);
5069
0
  setDependence(computeDependence(this));
5070
0
}
5071
5072
OMPArrayShapingExpr *
5073
OMPArrayShapingExpr::Create(const ASTContext &Context, QualType T, Expr *Op,
5074
                            SourceLocation L, SourceLocation R,
5075
                            ArrayRef<Expr *> Dims,
5076
0
                            ArrayRef<SourceRange> BracketRanges) {
5077
0
  assert(Dims.size() == BracketRanges.size() &&
5078
0
         "Different number of dimensions and brackets ranges.");
5079
0
  void *Mem = Context.Allocate(
5080
0
      totalSizeToAlloc<Expr *, SourceRange>(Dims.size() + 1, Dims.size()),
5081
0
      alignof(OMPArrayShapingExpr));
5082
0
  auto *E = new (Mem) OMPArrayShapingExpr(T, Op, L, R, Dims);
5083
0
  E->setBracketsRanges(BracketRanges);
5084
0
  return E;
5085
0
}
5086
5087
OMPArrayShapingExpr *OMPArrayShapingExpr::CreateEmpty(const ASTContext &Context,
5088
0
                                                      unsigned NumDims) {
5089
0
  void *Mem = Context.Allocate(
5090
0
      totalSizeToAlloc<Expr *, SourceRange>(NumDims + 1, NumDims),
5091
0
      alignof(OMPArrayShapingExpr));
5092
0
  return new (Mem) OMPArrayShapingExpr(EmptyShell(), NumDims);
5093
0
}
5094
5095
0
void OMPIteratorExpr::setIteratorDeclaration(unsigned I, Decl *D) {
5096
0
  assert(I < NumIterators &&
5097
0
         "Idx is greater or equal the number of iterators definitions.");
5098
0
  getTrailingObjects<Decl *>()[I] = D;
5099
0
}
5100
5101
0
void OMPIteratorExpr::setAssignmentLoc(unsigned I, SourceLocation Loc) {
5102
0
  assert(I < NumIterators &&
5103
0
         "Idx is greater or equal the number of iterators definitions.");
5104
0
  getTrailingObjects<
5105
0
      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5106
0
                        static_cast<int>(RangeLocOffset::AssignLoc)] = Loc;
5107
0
}
5108
5109
void OMPIteratorExpr::setIteratorRange(unsigned I, Expr *Begin,
5110
                                       SourceLocation ColonLoc, Expr *End,
5111
                                       SourceLocation SecondColonLoc,
5112
0
                                       Expr *Step) {
5113
0
  assert(I < NumIterators &&
5114
0
         "Idx is greater or equal the number of iterators definitions.");
5115
0
  getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5116
0
                               static_cast<int>(RangeExprOffset::Begin)] =
5117
0
      Begin;
5118
0
  getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5119
0
                               static_cast<int>(RangeExprOffset::End)] = End;
5120
0
  getTrailingObjects<Expr *>()[I * static_cast<int>(RangeExprOffset::Total) +
5121
0
                               static_cast<int>(RangeExprOffset::Step)] = Step;
5122
0
  getTrailingObjects<
5123
0
      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5124
0
                        static_cast<int>(RangeLocOffset::FirstColonLoc)] =
5125
0
      ColonLoc;
5126
0
  getTrailingObjects<
5127
0
      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5128
0
                        static_cast<int>(RangeLocOffset::SecondColonLoc)] =
5129
0
      SecondColonLoc;
5130
0
}
5131
5132
0
Decl *OMPIteratorExpr::getIteratorDecl(unsigned I) {
5133
0
  return getTrailingObjects<Decl *>()[I];
5134
0
}
5135
5136
0
OMPIteratorExpr::IteratorRange OMPIteratorExpr::getIteratorRange(unsigned I) {
5137
0
  IteratorRange Res;
5138
0
  Res.Begin =
5139
0
      getTrailingObjects<Expr *>()[I * static_cast<int>(
5140
0
                                           RangeExprOffset::Total) +
5141
0
                                   static_cast<int>(RangeExprOffset::Begin)];
5142
0
  Res.End =
5143
0
      getTrailingObjects<Expr *>()[I * static_cast<int>(
5144
0
                                           RangeExprOffset::Total) +
5145
0
                                   static_cast<int>(RangeExprOffset::End)];
5146
0
  Res.Step =
5147
0
      getTrailingObjects<Expr *>()[I * static_cast<int>(
5148
0
                                           RangeExprOffset::Total) +
5149
0
                                   static_cast<int>(RangeExprOffset::Step)];
5150
0
  return Res;
5151
0
}
5152
5153
0
SourceLocation OMPIteratorExpr::getAssignLoc(unsigned I) const {
5154
0
  return getTrailingObjects<
5155
0
      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5156
0
                        static_cast<int>(RangeLocOffset::AssignLoc)];
5157
0
}
5158
5159
0
SourceLocation OMPIteratorExpr::getColonLoc(unsigned I) const {
5160
0
  return getTrailingObjects<
5161
0
      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5162
0
                        static_cast<int>(RangeLocOffset::FirstColonLoc)];
5163
0
}
5164
5165
0
SourceLocation OMPIteratorExpr::getSecondColonLoc(unsigned I) const {
5166
0
  return getTrailingObjects<
5167
0
      SourceLocation>()[I * static_cast<int>(RangeLocOffset::Total) +
5168
0
                        static_cast<int>(RangeLocOffset::SecondColonLoc)];
5169
0
}
5170
5171
0
void OMPIteratorExpr::setHelper(unsigned I, const OMPIteratorHelperData &D) {
5172
0
  getTrailingObjects<OMPIteratorHelperData>()[I] = D;
5173
0
}
5174
5175
0
OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) {
5176
0
  return getTrailingObjects<OMPIteratorHelperData>()[I];
5177
0
}
5178
5179
0
const OMPIteratorHelperData &OMPIteratorExpr::getHelper(unsigned I) const {
5180
0
  return getTrailingObjects<OMPIteratorHelperData>()[I];
5181
0
}
5182
5183
OMPIteratorExpr::OMPIteratorExpr(
5184
    QualType ExprTy, SourceLocation IteratorKwLoc, SourceLocation L,
5185
    SourceLocation R, ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
5186
    ArrayRef<OMPIteratorHelperData> Helpers)
5187
    : Expr(OMPIteratorExprClass, ExprTy, VK_LValue, OK_Ordinary),
5188
      IteratorKwLoc(IteratorKwLoc), LPLoc(L), RPLoc(R),
5189
0
      NumIterators(Data.size()) {
5190
0
  for (unsigned I = 0, E = Data.size(); I < E; ++I) {
5191
0
    const IteratorDefinition &D = Data[I];
5192
0
    setIteratorDeclaration(I, D.IteratorDecl);
5193
0
    setAssignmentLoc(I, D.AssignmentLoc);
5194
0
    setIteratorRange(I, D.Range.Begin, D.ColonLoc, D.Range.End,
5195
0
                     D.SecondColonLoc, D.Range.Step);
5196
0
    setHelper(I, Helpers[I]);
5197
0
  }
5198
0
  setDependence(computeDependence(this));
5199
0
}
5200
5201
OMPIteratorExpr *
5202
OMPIteratorExpr::Create(const ASTContext &Context, QualType T,
5203
                        SourceLocation IteratorKwLoc, SourceLocation L,
5204
                        SourceLocation R,
5205
                        ArrayRef<OMPIteratorExpr::IteratorDefinition> Data,
5206
0
                        ArrayRef<OMPIteratorHelperData> Helpers) {
5207
0
  assert(Data.size() == Helpers.size() &&
5208
0
         "Data and helpers must have the same size.");
5209
0
  void *Mem = Context.Allocate(
5210
0
      totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5211
0
          Data.size(), Data.size() * static_cast<int>(RangeExprOffset::Total),
5212
0
          Data.size() * static_cast<int>(RangeLocOffset::Total),
5213
0
          Helpers.size()),
5214
0
      alignof(OMPIteratorExpr));
5215
0
  return new (Mem) OMPIteratorExpr(T, IteratorKwLoc, L, R, Data, Helpers);
5216
0
}
5217
5218
OMPIteratorExpr *OMPIteratorExpr::CreateEmpty(const ASTContext &Context,
5219
0
                                              unsigned NumIterators) {
5220
0
  void *Mem = Context.Allocate(
5221
0
      totalSizeToAlloc<Decl *, Expr *, SourceLocation, OMPIteratorHelperData>(
5222
0
          NumIterators, NumIterators * static_cast<int>(RangeExprOffset::Total),
5223
0
          NumIterators * static_cast<int>(RangeLocOffset::Total), NumIterators),
5224
0
      alignof(OMPIteratorExpr));
5225
0
  return new (Mem) OMPIteratorExpr(EmptyShell(), NumIterators);
5226
0
}