Subversion Repositories QNX 8.QNX8 LLVM/Clang compiler suite

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
14 pmbaty 1
//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
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 defines the Expr interface and subclasses.
10
//
11
//===----------------------------------------------------------------------===//
12
 
13
#ifndef LLVM_CLANG_AST_EXPR_H
14
#define LLVM_CLANG_AST_EXPR_H
15
 
16
#include "clang/AST/APValue.h"
17
#include "clang/AST/ASTVector.h"
18
#include "clang/AST/ComputeDependence.h"
19
#include "clang/AST/Decl.h"
20
#include "clang/AST/DeclAccessPair.h"
21
#include "clang/AST/DependenceFlags.h"
22
#include "clang/AST/OperationKinds.h"
23
#include "clang/AST/Stmt.h"
24
#include "clang/AST/TemplateBase.h"
25
#include "clang/AST/Type.h"
26
#include "clang/Basic/CharInfo.h"
27
#include "clang/Basic/LangOptions.h"
28
#include "clang/Basic/SyncScope.h"
29
#include "clang/Basic/TypeTraits.h"
30
#include "llvm/ADT/APFloat.h"
31
#include "llvm/ADT/APSInt.h"
32
#include "llvm/ADT/SmallVector.h"
33
#include "llvm/ADT/StringRef.h"
34
#include "llvm/ADT/iterator.h"
35
#include "llvm/ADT/iterator_range.h"
36
#include "llvm/Support/AtomicOrdering.h"
37
#include "llvm/Support/Compiler.h"
38
#include "llvm/Support/TrailingObjects.h"
39
#include <optional>
40
 
41
namespace clang {
42
  class APValue;
43
  class ASTContext;
44
  class BlockDecl;
45
  class CXXBaseSpecifier;
46
  class CXXMemberCallExpr;
47
  class CXXOperatorCallExpr;
48
  class CastExpr;
49
  class Decl;
50
  class IdentifierInfo;
51
  class MaterializeTemporaryExpr;
52
  class NamedDecl;
53
  class ObjCPropertyRefExpr;
54
  class OpaqueValueExpr;
55
  class ParmVarDecl;
56
  class StringLiteral;
57
  class TargetInfo;
58
  class ValueDecl;
59
 
60
/// A simple array of base specifiers.
61
typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
62
 
63
/// An adjustment to be made to the temporary created when emitting a
64
/// reference binding, which accesses a particular subobject of that temporary.
65
struct SubobjectAdjustment {
66
  enum {
67
    DerivedToBaseAdjustment,
68
    FieldAdjustment,
69
    MemberPointerAdjustment
70
  } Kind;
71
 
72
  struct DTB {
73
    const CastExpr *BasePath;
74
    const CXXRecordDecl *DerivedClass;
75
  };
76
 
77
  struct P {
78
    const MemberPointerType *MPT;
79
    Expr *RHS;
80
  };
81
 
82
  union {
83
    struct DTB DerivedToBase;
84
    FieldDecl *Field;
85
    struct P Ptr;
86
  };
87
 
88
  SubobjectAdjustment(const CastExpr *BasePath,
89
                      const CXXRecordDecl *DerivedClass)
90
    : Kind(DerivedToBaseAdjustment) {
91
    DerivedToBase.BasePath = BasePath;
92
    DerivedToBase.DerivedClass = DerivedClass;
93
  }
94
 
95
  SubobjectAdjustment(FieldDecl *Field)
96
    : Kind(FieldAdjustment) {
97
    this->Field = Field;
98
  }
99
 
100
  SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
101
    : Kind(MemberPointerAdjustment) {
102
    this->Ptr.MPT = MPT;
103
    this->Ptr.RHS = RHS;
104
  }
105
};
106
 
107
/// This represents one expression.  Note that Expr's are subclasses of Stmt.
108
/// This allows an expression to be transparently used any place a Stmt is
109
/// required.
110
class Expr : public ValueStmt {
111
  QualType TR;
112
 
113
public:
114
  Expr() = delete;
115
  Expr(const Expr&) = delete;
116
  Expr(Expr &&) = delete;
117
  Expr &operator=(const Expr&) = delete;
118
  Expr &operator=(Expr&&) = delete;
119
 
120
protected:
121
  Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK)
122
      : ValueStmt(SC) {
123
    ExprBits.Dependent = 0;
124
    ExprBits.ValueKind = VK;
125
    ExprBits.ObjectKind = OK;
126
    assert(ExprBits.ObjectKind == OK && "truncated kind");
127
    setType(T);
128
  }
129
 
130
  /// Construct an empty expression.
131
  explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
132
 
133
  /// Each concrete expr subclass is expected to compute its dependence and call
134
  /// this in the constructor.
135
  void setDependence(ExprDependence Deps) {
136
    ExprBits.Dependent = static_cast<unsigned>(Deps);
137
  }
138
  friend class ASTImporter; // Sets dependence dircetly.
139
  friend class ASTStmtReader; // Sets dependence dircetly.
140
 
141
public:
142
  QualType getType() const { return TR; }
143
  void setType(QualType t) {
144
    // In C++, the type of an expression is always adjusted so that it
145
    // will not have reference type (C++ [expr]p6). Use
146
    // QualType::getNonReferenceType() to retrieve the non-reference
147
    // type. Additionally, inspect Expr::isLvalue to determine whether
148
    // an expression that is adjusted in this manner should be
149
    // considered an lvalue.
150
    assert((t.isNull() || !t->isReferenceType()) &&
151
           "Expressions can't have reference type");
152
 
153
    TR = t;
154
  }
155
 
156
  ExprDependence getDependence() const {
157
    return static_cast<ExprDependence>(ExprBits.Dependent);
158
  }
159
 
160
  /// Determines whether the value of this expression depends on
161
  ///   - a template parameter (C++ [temp.dep.constexpr])
162
  ///   - or an error, whose resolution is unknown
163
  ///
164
  /// For example, the array bound of "Chars" in the following example is
165
  /// value-dependent.
166
  /// @code
167
  /// template<int Size, char (&Chars)[Size]> struct meta_string;
168
  /// @endcode
169
  bool isValueDependent() const {
170
    return static_cast<bool>(getDependence() & ExprDependence::Value);
171
  }
172
 
173
  /// Determines whether the type of this expression depends on
174
  ///   - a template paramter (C++ [temp.dep.expr], which means that its type
175
  ///     could change from one template instantiation to the next)
176
  ///   - or an error
177
  ///
178
  /// For example, the expressions "x" and "x + y" are type-dependent in
179
  /// the following code, but "y" is not type-dependent:
180
  /// @code
181
  /// template<typename T>
182
  /// void add(T x, int y) {
183
  ///   x + y;
184
  /// }
185
  /// @endcode
186
  bool isTypeDependent() const {
187
    return static_cast<bool>(getDependence() & ExprDependence::Type);
188
  }
189
 
190
  /// Whether this expression is instantiation-dependent, meaning that
191
  /// it depends in some way on
192
  ///    - a template parameter (even if neither its type nor (constant) value
193
  ///      can change due to the template instantiation)
194
  ///    - or an error
195
  ///
196
  /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
197
  /// instantiation-dependent (since it involves a template parameter \c T), but
198
  /// is neither type- nor value-dependent, since the type of the inner
199
  /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
200
  /// \c sizeof is known.
201
  ///
202
  /// \code
203
  /// template<typename T>
204
  /// void f(T x, T y) {
205
  ///   sizeof(sizeof(T() + T());
206
  /// }
207
  /// \endcode
208
  ///
209
  /// \code
210
  /// void func(int) {
211
  ///   func(); // the expression is instantiation-dependent, because it depends
212
  ///           // on an error.
213
  /// }
214
  /// \endcode
215
  bool isInstantiationDependent() const {
216
    return static_cast<bool>(getDependence() & ExprDependence::Instantiation);
217
  }
218
 
219
  /// Whether this expression contains an unexpanded parameter
220
  /// pack (for C++11 variadic templates).
221
  ///
222
  /// Given the following function template:
223
  ///
224
  /// \code
225
  /// template<typename F, typename ...Types>
226
  /// void forward(const F &f, Types &&...args) {
227
  ///   f(static_cast<Types&&>(args)...);
228
  /// }
229
  /// \endcode
230
  ///
231
  /// The expressions \c args and \c static_cast<Types&&>(args) both
232
  /// contain parameter packs.
233
  bool containsUnexpandedParameterPack() const {
234
    return static_cast<bool>(getDependence() & ExprDependence::UnexpandedPack);
235
  }
236
 
237
  /// Whether this expression contains subexpressions which had errors, e.g. a
238
  /// TypoExpr.
239
  bool containsErrors() const {
240
    return static_cast<bool>(getDependence() & ExprDependence::Error);
241
  }
242
 
243
  /// getExprLoc - Return the preferred location for the arrow when diagnosing
244
  /// a problem with a generic expression.
245
  SourceLocation getExprLoc() const LLVM_READONLY;
246
 
247
  /// Determine whether an lvalue-to-rvalue conversion should implicitly be
248
  /// applied to this expression if it appears as a discarded-value expression
249
  /// in C++11 onwards. This applies to certain forms of volatile glvalues.
250
  bool isReadIfDiscardedInCPlusPlus11() const;
251
 
252
  /// isUnusedResultAWarning - Return true if this immediate expression should
253
  /// be warned about if the result is unused.  If so, fill in expr, location,
254
  /// and ranges with expr to warn on and source locations/ranges appropriate
255
  /// for a warning.
256
  bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
257
                              SourceRange &R1, SourceRange &R2,
258
                              ASTContext &Ctx) const;
259
 
260
  /// isLValue - True if this expression is an "l-value" according to
261
  /// the rules of the current language.  C and C++ give somewhat
262
  /// different rules for this concept, but in general, the result of
263
  /// an l-value expression identifies a specific object whereas the
264
  /// result of an r-value expression is a value detached from any
265
  /// specific storage.
266
  ///
267
  /// C++11 divides the concept of "r-value" into pure r-values
268
  /// ("pr-values") and so-called expiring values ("x-values"), which
269
  /// identify specific objects that can be safely cannibalized for
270
  /// their resources.
271
  bool isLValue() const { return getValueKind() == VK_LValue; }
272
  bool isPRValue() const { return getValueKind() == VK_PRValue; }
273
  bool isXValue() const { return getValueKind() == VK_XValue; }
274
  bool isGLValue() const { return getValueKind() != VK_PRValue; }
275
 
276
  enum LValueClassification {
277
    LV_Valid,
278
    LV_NotObjectType,
279
    LV_IncompleteVoidType,
280
    LV_DuplicateVectorComponents,
281
    LV_InvalidExpression,
282
    LV_InvalidMessageExpression,
283
    LV_MemberFunction,
284
    LV_SubObjCPropertySetting,
285
    LV_ClassTemporary,
286
    LV_ArrayTemporary
287
  };
288
  /// Reasons why an expression might not be an l-value.
289
  LValueClassification ClassifyLValue(ASTContext &Ctx) const;
290
 
291
  enum isModifiableLvalueResult {
292
    MLV_Valid,
293
    MLV_NotObjectType,
294
    MLV_IncompleteVoidType,
295
    MLV_DuplicateVectorComponents,
296
    MLV_InvalidExpression,
297
    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
298
    MLV_IncompleteType,
299
    MLV_ConstQualified,
300
    MLV_ConstQualifiedField,
301
    MLV_ConstAddrSpace,
302
    MLV_ArrayType,
303
    MLV_NoSetterProperty,
304
    MLV_MemberFunction,
305
    MLV_SubObjCPropertySetting,
306
    MLV_InvalidMessageExpression,
307
    MLV_ClassTemporary,
308
    MLV_ArrayTemporary
309
  };
310
  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
311
  /// does not have an incomplete type, does not have a const-qualified type,
312
  /// and if it is a structure or union, does not have any member (including,
313
  /// recursively, any member or element of all contained aggregates or unions)
314
  /// with a const-qualified type.
315
  ///
316
  /// \param Loc [in,out] - A source location which *may* be filled
317
  /// in with the location of the expression making this a
318
  /// non-modifiable lvalue, if specified.
319
  isModifiableLvalueResult
320
  isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
321
 
322
  /// The return type of classify(). Represents the C++11 expression
323
  ///        taxonomy.
324
  class Classification {
325
  public:
326
    /// The various classification results. Most of these mean prvalue.
327
    enum Kinds {
328
      CL_LValue,
329
      CL_XValue,
330
      CL_Function, // Functions cannot be lvalues in C.
331
      CL_Void, // Void cannot be an lvalue in C.
332
      CL_AddressableVoid, // Void expression whose address can be taken in C.
333
      CL_DuplicateVectorComponents, // A vector shuffle with dupes.
334
      CL_MemberFunction, // An expression referring to a member function
335
      CL_SubObjCPropertySetting,
336
      CL_ClassTemporary, // A temporary of class type, or subobject thereof.
337
      CL_ArrayTemporary, // A temporary of array type.
338
      CL_ObjCMessageRValue, // ObjC message is an rvalue
339
      CL_PRValue // A prvalue for any other reason, of any other type
340
    };
341
    /// The results of modification testing.
342
    enum ModifiableType {
343
      CM_Untested, // testModifiable was false.
344
      CM_Modifiable,
345
      CM_RValue, // Not modifiable because it's an rvalue
346
      CM_Function, // Not modifiable because it's a function; C++ only
347
      CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
348
      CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
349
      CM_ConstQualified,
350
      CM_ConstQualifiedField,
351
      CM_ConstAddrSpace,
352
      CM_ArrayType,
353
      CM_IncompleteType
354
    };
355
 
356
  private:
357
    friend class Expr;
358
 
359
    unsigned short Kind;
360
    unsigned short Modifiable;
361
 
362
    explicit Classification(Kinds k, ModifiableType m)
363
      : Kind(k), Modifiable(m)
364
    {}
365
 
366
  public:
367
    Classification() {}
368
 
369
    Kinds getKind() const { return static_cast<Kinds>(Kind); }
370
    ModifiableType getModifiable() const {
371
      assert(Modifiable != CM_Untested && "Did not test for modifiability.");
372
      return static_cast<ModifiableType>(Modifiable);
373
    }
374
    bool isLValue() const { return Kind == CL_LValue; }
375
    bool isXValue() const { return Kind == CL_XValue; }
376
    bool isGLValue() const { return Kind <= CL_XValue; }
377
    bool isPRValue() const { return Kind >= CL_Function; }
378
    bool isRValue() const { return Kind >= CL_XValue; }
379
    bool isModifiable() const { return getModifiable() == CM_Modifiable; }
380
 
381
    /// Create a simple, modifiably lvalue
382
    static Classification makeSimpleLValue() {
383
      return Classification(CL_LValue, CM_Modifiable);
384
    }
385
 
386
  };
387
  /// Classify - Classify this expression according to the C++11
388
  ///        expression taxonomy.
389
  ///
390
  /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
391
  /// old lvalue vs rvalue. This function determines the type of expression this
392
  /// is. There are three expression types:
393
  /// - lvalues are classical lvalues as in C++03.
394
  /// - prvalues are equivalent to rvalues in C++03.
395
  /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
396
  ///   function returning an rvalue reference.
397
  /// lvalues and xvalues are collectively referred to as glvalues, while
398
  /// prvalues and xvalues together form rvalues.
399
  Classification Classify(ASTContext &Ctx) const {
400
    return ClassifyImpl(Ctx, nullptr);
401
  }
402
 
403
  /// ClassifyModifiable - Classify this expression according to the
404
  ///        C++11 expression taxonomy, and see if it is valid on the left side
405
  ///        of an assignment.
406
  ///
407
  /// This function extends classify in that it also tests whether the
408
  /// expression is modifiable (C99 6.3.2.1p1).
409
  /// \param Loc A source location that might be filled with a relevant location
410
  ///            if the expression is not modifiable.
411
  Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
412
    return ClassifyImpl(Ctx, &Loc);
413
  }
414
 
415
  /// Returns the set of floating point options that apply to this expression.
416
  /// Only meaningful for operations on floating point values.
417
  FPOptions getFPFeaturesInEffect(const LangOptions &LO) const;
418
 
419
  /// getValueKindForType - Given a formal return or parameter type,
420
  /// give its value kind.
421
  static ExprValueKind getValueKindForType(QualType T) {
422
    if (const ReferenceType *RT = T->getAs<ReferenceType>())
423
      return (isa<LValueReferenceType>(RT)
424
                ? VK_LValue
425
                : (RT->getPointeeType()->isFunctionType()
426
                     ? VK_LValue : VK_XValue));
427
    return VK_PRValue;
428
  }
429
 
430
  /// getValueKind - The value kind that this expression produces.
431
  ExprValueKind getValueKind() const {
432
    return static_cast<ExprValueKind>(ExprBits.ValueKind);
433
  }
434
 
435
  /// getObjectKind - The object kind that this expression produces.
436
  /// Object kinds are meaningful only for expressions that yield an
437
  /// l-value or x-value.
438
  ExprObjectKind getObjectKind() const {
439
    return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
440
  }
441
 
442
  bool isOrdinaryOrBitFieldObject() const {
443
    ExprObjectKind OK = getObjectKind();
444
    return (OK == OK_Ordinary || OK == OK_BitField);
445
  }
446
 
447
  /// setValueKind - Set the value kind produced by this expression.
448
  void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
449
 
450
  /// setObjectKind - Set the object kind produced by this expression.
451
  void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
452
 
453
private:
454
  Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
455
 
456
public:
457
 
458
  /// Returns true if this expression is a gl-value that
459
  /// potentially refers to a bit-field.
460
  ///
461
  /// In C++, whether a gl-value refers to a bitfield is essentially
462
  /// an aspect of the value-kind type system.
463
  bool refersToBitField() const { return getObjectKind() == OK_BitField; }
464
 
465
  /// If this expression refers to a bit-field, retrieve the
466
  /// declaration of that bit-field.
467
  ///
468
  /// Note that this returns a non-null pointer in subtly different
469
  /// places than refersToBitField returns true.  In particular, this can
470
  /// return a non-null pointer even for r-values loaded from
471
  /// bit-fields, but it will return null for a conditional bit-field.
472
  FieldDecl *getSourceBitField();
473
 
474
  const FieldDecl *getSourceBitField() const {
475
    return const_cast<Expr*>(this)->getSourceBitField();
476
  }
477
 
478
  Decl *getReferencedDeclOfCallee();
479
  const Decl *getReferencedDeclOfCallee() const {
480
    return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
481
  }
482
 
483
  /// If this expression is an l-value for an Objective C
484
  /// property, find the underlying property reference expression.
485
  const ObjCPropertyRefExpr *getObjCProperty() const;
486
 
487
  /// Check if this expression is the ObjC 'self' implicit parameter.
488
  bool isObjCSelfExpr() const;
489
 
490
  /// Returns whether this expression refers to a vector element.
491
  bool refersToVectorElement() const;
492
 
493
  /// Returns whether this expression refers to a matrix element.
494
  bool refersToMatrixElement() const {
495
    return getObjectKind() == OK_MatrixComponent;
496
  }
497
 
498
  /// Returns whether this expression refers to a global register
499
  /// variable.
500
  bool refersToGlobalRegisterVar() const;
501
 
502
  /// Returns whether this expression has a placeholder type.
503
  bool hasPlaceholderType() const {
504
    return getType()->isPlaceholderType();
505
  }
506
 
507
  /// Returns whether this expression has a specific placeholder type.
508
  bool hasPlaceholderType(BuiltinType::Kind K) const {
509
    assert(BuiltinType::isPlaceholderTypeKind(K));
510
    if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
511
      return BT->getKind() == K;
512
    return false;
513
  }
514
 
515
  /// isKnownToHaveBooleanValue - Return true if this is an integer expression
516
  /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
517
  /// but also int expressions which are produced by things like comparisons in
518
  /// C.
519
  ///
520
  /// \param Semantic If true, only return true for expressions that are known
521
  /// to be semantically boolean, which might not be true even for expressions
522
  /// that are known to evaluate to 0/1. For instance, reading an unsigned
523
  /// bit-field with width '1' will evaluate to 0/1, but doesn't necessarily
524
  /// semantically correspond to a bool.
525
  bool isKnownToHaveBooleanValue(bool Semantic = true) const;
526
 
527
  /// Check whether this array fits the idiom of a flexible array member,
528
  /// depending on the value of -fstrict-flex-array.
529
  /// When IgnoreTemplateOrMacroSubstitution is set, it doesn't consider sizes
530
  /// resulting from the substitution of a macro or a template as special sizes.
531
  bool isFlexibleArrayMemberLike(
532
      ASTContext &Context,
533
      LangOptions::StrictFlexArraysLevelKind StrictFlexArraysLevel,
534
      bool IgnoreTemplateOrMacroSubstitution = false) const;
535
 
536
  /// isIntegerConstantExpr - Return the value if this expression is a valid
537
  /// integer constant expression.  If not a valid i-c-e, return std::nullopt
538
  /// and fill in Loc (if specified) with the location of the invalid
539
  /// expression.
540
  ///
541
  /// Note: This does not perform the implicit conversions required by C++11
542
  /// [expr.const]p5.
543
  std::optional<llvm::APSInt>
544
  getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc = nullptr,
545
                         bool isEvaluated = true) const;
546
  bool isIntegerConstantExpr(const ASTContext &Ctx,
547
                             SourceLocation *Loc = nullptr) const;
548
 
549
  /// isCXX98IntegralConstantExpr - Return true if this expression is an
550
  /// integral constant expression in C++98. Can only be used in C++.
551
  bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
552
 
553
  /// isCXX11ConstantExpr - Return true if this expression is a constant
554
  /// expression in C++11. Can only be used in C++.
555
  ///
556
  /// Note: This does not perform the implicit conversions required by C++11
557
  /// [expr.const]p5.
558
  bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
559
                           SourceLocation *Loc = nullptr) const;
560
 
561
  /// isPotentialConstantExpr - Return true if this function's definition
562
  /// might be usable in a constant expression in C++11, if it were marked
563
  /// constexpr. Return false if the function can never produce a constant
564
  /// expression, along with diagnostics describing why not.
565
  static bool isPotentialConstantExpr(const FunctionDecl *FD,
566
                                      SmallVectorImpl<
567
                                        PartialDiagnosticAt> &Diags);
568
 
569
  /// isPotentialConstantExprUnevaluted - Return true if this expression might
570
  /// be usable in a constant expression in C++11 in an unevaluated context, if
571
  /// it were in function FD marked constexpr. Return false if the function can
572
  /// never produce a constant expression, along with diagnostics describing
573
  /// why not.
574
  static bool isPotentialConstantExprUnevaluated(Expr *E,
575
                                                 const FunctionDecl *FD,
576
                                                 SmallVectorImpl<
577
                                                   PartialDiagnosticAt> &Diags);
578
 
579
  /// isConstantInitializer - Returns true if this expression can be emitted to
580
  /// IR as a constant, and thus can be used as a constant initializer in C.
581
  /// If this expression is not constant and Culprit is non-null,
582
  /// it is used to store the address of first non constant expr.
583
  bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
584
                             const Expr **Culprit = nullptr) const;
585
 
586
  /// If this expression is an unambiguous reference to a single declaration,
587
  /// in the style of __builtin_function_start, return that declaration.  Note
588
  /// that this may return a non-static member function or field in C++ if this
589
  /// expression is a member pointer constant.
590
  const ValueDecl *getAsBuiltinConstantDeclRef(const ASTContext &Context) const;
591
 
592
  /// EvalStatus is a struct with detailed info about an evaluation in progress.
593
  struct EvalStatus {
594
    /// Whether the evaluated expression has side effects.
595
    /// For example, (f() && 0) can be folded, but it still has side effects.
596
    bool HasSideEffects;
597
 
598
    /// Whether the evaluation hit undefined behavior.
599
    /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
600
    /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
601
    bool HasUndefinedBehavior;
602
 
603
    /// Diag - If this is non-null, it will be filled in with a stack of notes
604
    /// indicating why evaluation failed (or why it failed to produce a constant
605
    /// expression).
606
    /// If the expression is unfoldable, the notes will indicate why it's not
607
    /// foldable. If the expression is foldable, but not a constant expression,
608
    /// the notes will describes why it isn't a constant expression. If the
609
    /// expression *is* a constant expression, no notes will be produced.
610
    SmallVectorImpl<PartialDiagnosticAt> *Diag;
611
 
612
    EvalStatus()
613
        : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
614
 
615
    // hasSideEffects - Return true if the evaluated expression has
616
    // side effects.
617
    bool hasSideEffects() const {
618
      return HasSideEffects;
619
    }
620
  };
621
 
622
  /// EvalResult is a struct with detailed info about an evaluated expression.
623
  struct EvalResult : EvalStatus {
624
    /// Val - This is the value the expression can be folded to.
625
    APValue Val;
626
 
627
    // isGlobalLValue - Return true if the evaluated lvalue expression
628
    // is global.
629
    bool isGlobalLValue() const;
630
  };
631
 
632
  /// EvaluateAsRValue - Return true if this is a constant which we can fold to
633
  /// an rvalue using any crazy technique (that has nothing to do with language
634
  /// standards) that we want to, even if the expression has side-effects. If
635
  /// this function returns true, it returns the folded constant in Result. If
636
  /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
637
  /// applied.
638
  bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
639
                        bool InConstantContext = false) const;
640
 
641
  /// EvaluateAsBooleanCondition - Return true if this is a constant
642
  /// which we can fold and convert to a boolean condition using
643
  /// any crazy technique that we want to, even if the expression has
644
  /// side-effects.
645
  bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
646
                                  bool InConstantContext = false) const;
647
 
648
  enum SideEffectsKind {
649
    SE_NoSideEffects,          ///< Strictly evaluate the expression.
650
    SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
651
                               ///< arbitrary unmodeled side effects.
652
    SE_AllowSideEffects        ///< Allow any unmodeled side effect.
653
  };
654
 
655
  /// EvaluateAsInt - Return true if this is a constant which we can fold and
656
  /// convert to an integer, using any crazy technique that we want to.
657
  bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
658
                     SideEffectsKind AllowSideEffects = SE_NoSideEffects,
659
                     bool InConstantContext = false) const;
660
 
661
  /// EvaluateAsFloat - Return true if this is a constant which we can fold and
662
  /// convert to a floating point value, using any crazy technique that we
663
  /// want to.
664
  bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
665
                       SideEffectsKind AllowSideEffects = SE_NoSideEffects,
666
                       bool InConstantContext = false) const;
667
 
668
  /// EvaluateAsFloat - Return true if this is a constant which we can fold and
669
  /// convert to a fixed point value.
670
  bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
671
                            SideEffectsKind AllowSideEffects = SE_NoSideEffects,
672
                            bool InConstantContext = false) const;
673
 
674
  /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
675
  /// constant folded without side-effects, but discard the result.
676
  bool isEvaluatable(const ASTContext &Ctx,
677
                     SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
678
 
679
  /// HasSideEffects - This routine returns true for all those expressions
680
  /// which have any effect other than producing a value. Example is a function
681
  /// call, volatile variable read, or throwing an exception. If
682
  /// IncludePossibleEffects is false, this call treats certain expressions with
683
  /// potential side effects (such as function call-like expressions,
684
  /// instantiation-dependent expressions, or invocations from a macro) as not
685
  /// having side effects.
686
  bool HasSideEffects(const ASTContext &Ctx,
687
                      bool IncludePossibleEffects = true) const;
688
 
689
  /// Determine whether this expression involves a call to any function
690
  /// that is not trivial.
691
  bool hasNonTrivialCall(const ASTContext &Ctx) const;
692
 
693
  /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
694
  /// integer. This must be called on an expression that constant folds to an
695
  /// integer.
696
  llvm::APSInt EvaluateKnownConstInt(
697
      const ASTContext &Ctx,
698
      SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
699
 
700
  llvm::APSInt EvaluateKnownConstIntCheckOverflow(
701
      const ASTContext &Ctx,
702
      SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
703
 
704
  void EvaluateForOverflow(const ASTContext &Ctx) const;
705
 
706
  /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
707
  /// lvalue with link time known address, with no side-effects.
708
  bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
709
                        bool InConstantContext = false) const;
710
 
711
  /// EvaluateAsInitializer - Evaluate an expression as if it were the
712
  /// initializer of the given declaration. Returns true if the initializer
713
  /// can be folded to a constant, and produces any relevant notes. In C++11,
714
  /// notes will be produced if the expression is not a constant expression.
715
  bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
716
                             const VarDecl *VD,
717
                             SmallVectorImpl<PartialDiagnosticAt> &Notes,
718
                             bool IsConstantInitializer) const;
719
 
720
  /// EvaluateWithSubstitution - Evaluate an expression as if from the context
721
  /// of a call to the given function with the given arguments, inside an
722
  /// unevaluated context. Returns true if the expression could be folded to a
723
  /// constant.
724
  bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
725
                                const FunctionDecl *Callee,
726
                                ArrayRef<const Expr*> Args,
727
                                const Expr *This = nullptr) const;
728
 
729
  enum class ConstantExprKind {
730
    /// An integer constant expression (an array bound, enumerator, case value,
731
    /// bit-field width, or similar) or similar.
732
    Normal,
733
    /// A non-class template argument. Such a value is only used for mangling,
734
    /// not for code generation, so can refer to dllimported functions.
735
    NonClassTemplateArgument,
736
    /// A class template argument. Such a value is used for code generation.
737
    ClassTemplateArgument,
738
    /// An immediate invocation. The destruction of the end result of this
739
    /// evaluation is not part of the evaluation, but all other temporaries
740
    /// are destroyed.
741
    ImmediateInvocation,
742
  };
743
 
744
  /// Evaluate an expression that is required to be a constant expression. Does
745
  /// not check the syntactic constraints for C and C++98 constant expressions.
746
  bool EvaluateAsConstantExpr(
747
      EvalResult &Result, const ASTContext &Ctx,
748
      ConstantExprKind Kind = ConstantExprKind::Normal) const;
749
 
750
  /// If the current Expr is a pointer, this will try to statically
751
  /// determine the number of bytes available where the pointer is pointing.
752
  /// Returns true if all of the above holds and we were able to figure out the
753
  /// size, false otherwise.
754
  ///
755
  /// \param Type - How to evaluate the size of the Expr, as defined by the
756
  /// "type" parameter of __builtin_object_size
757
  bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
758
                             unsigned Type) const;
759
 
760
  /// If the current Expr is a pointer, this will try to statically
761
  /// determine the strlen of the string pointed to.
762
  /// Returns true if all of the above holds and we were able to figure out the
763
  /// strlen, false otherwise.
764
  bool tryEvaluateStrLen(uint64_t &Result, ASTContext &Ctx) const;
765
 
766
  /// Enumeration used to describe the kind of Null pointer constant
767
  /// returned from \c isNullPointerConstant().
768
  enum NullPointerConstantKind {
769
    /// Expression is not a Null pointer constant.
770
    NPCK_NotNull = 0,
771
 
772
    /// Expression is a Null pointer constant built from a zero integer
773
    /// expression that is not a simple, possibly parenthesized, zero literal.
774
    /// C++ Core Issue 903 will classify these expressions as "not pointers"
775
    /// once it is adopted.
776
    /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
777
    NPCK_ZeroExpression,
778
 
779
    /// Expression is a Null pointer constant built from a literal zero.
780
    NPCK_ZeroLiteral,
781
 
782
    /// Expression is a C++11 nullptr.
783
    NPCK_CXX11_nullptr,
784
 
785
    /// Expression is a GNU-style __null constant.
786
    NPCK_GNUNull
787
  };
788
 
789
  /// Enumeration used to describe how \c isNullPointerConstant()
790
  /// should cope with value-dependent expressions.
791
  enum NullPointerConstantValueDependence {
792
    /// Specifies that the expression should never be value-dependent.
793
    NPC_NeverValueDependent = 0,
794
 
795
    /// Specifies that a value-dependent expression of integral or
796
    /// dependent type should be considered a null pointer constant.
797
    NPC_ValueDependentIsNull,
798
 
799
    /// Specifies that a value-dependent expression should be considered
800
    /// to never be a null pointer constant.
801
    NPC_ValueDependentIsNotNull
802
  };
803
 
804
  /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
805
  /// a Null pointer constant. The return value can further distinguish the
806
  /// kind of NULL pointer constant that was detected.
807
  NullPointerConstantKind isNullPointerConstant(
808
      ASTContext &Ctx,
809
      NullPointerConstantValueDependence NPC) const;
810
 
811
  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
812
  /// write barrier.
813
  bool isOBJCGCCandidate(ASTContext &Ctx) const;
814
 
815
  /// Returns true if this expression is a bound member function.
816
  bool isBoundMemberFunction(ASTContext &Ctx) const;
817
 
818
  /// Given an expression of bound-member type, find the type
819
  /// of the member.  Returns null if this is an *overloaded* bound
820
  /// member expression.
821
  static QualType findBoundMemberType(const Expr *expr);
822
 
823
  /// Skip past any invisble AST nodes which might surround this
824
  /// statement, such as ExprWithCleanups or ImplicitCastExpr nodes,
825
  /// but also injected CXXMemberExpr and CXXConstructExpr which represent
826
  /// implicit conversions.
827
  Expr *IgnoreUnlessSpelledInSource();
828
  const Expr *IgnoreUnlessSpelledInSource() const {
829
    return const_cast<Expr *>(this)->IgnoreUnlessSpelledInSource();
830
  }
831
 
832
  /// Skip past any implicit casts which might surround this expression until
833
  /// reaching a fixed point. Skips:
834
  /// * ImplicitCastExpr
835
  /// * FullExpr
836
  Expr *IgnoreImpCasts() LLVM_READONLY;
837
  const Expr *IgnoreImpCasts() const {
838
    return const_cast<Expr *>(this)->IgnoreImpCasts();
839
  }
840
 
841
  /// Skip past any casts which might surround this expression until reaching
842
  /// a fixed point. Skips:
843
  /// * CastExpr
844
  /// * FullExpr
845
  /// * MaterializeTemporaryExpr
846
  /// * SubstNonTypeTemplateParmExpr
847
  Expr *IgnoreCasts() LLVM_READONLY;
848
  const Expr *IgnoreCasts() const {
849
    return const_cast<Expr *>(this)->IgnoreCasts();
850
  }
851
 
852
  /// Skip past any implicit AST nodes which might surround this expression
853
  /// until reaching a fixed point. Skips:
854
  /// * What IgnoreImpCasts() skips
855
  /// * MaterializeTemporaryExpr
856
  /// * CXXBindTemporaryExpr
857
  Expr *IgnoreImplicit() LLVM_READONLY;
858
  const Expr *IgnoreImplicit() const {
859
    return const_cast<Expr *>(this)->IgnoreImplicit();
860
  }
861
 
862
  /// Skip past any implicit AST nodes which might surround this expression
863
  /// until reaching a fixed point. Same as IgnoreImplicit, except that it
864
  /// also skips over implicit calls to constructors and conversion functions.
865
  ///
866
  /// FIXME: Should IgnoreImplicit do this?
867
  Expr *IgnoreImplicitAsWritten() LLVM_READONLY;
868
  const Expr *IgnoreImplicitAsWritten() const {
869
    return const_cast<Expr *>(this)->IgnoreImplicitAsWritten();
870
  }
871
 
872
  /// Skip past any parentheses which might surround this expression until
873
  /// reaching a fixed point. Skips:
874
  /// * ParenExpr
875
  /// * UnaryOperator if `UO_Extension`
876
  /// * GenericSelectionExpr if `!isResultDependent()`
877
  /// * ChooseExpr if `!isConditionDependent()`
878
  /// * ConstantExpr
879
  Expr *IgnoreParens() LLVM_READONLY;
880
  const Expr *IgnoreParens() const {
881
    return const_cast<Expr *>(this)->IgnoreParens();
882
  }
883
 
884
  /// Skip past any parentheses and implicit casts which might surround this
885
  /// expression until reaching a fixed point.
886
  /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
887
  /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
888
  /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
889
  /// * What IgnoreParens() skips
890
  /// * What IgnoreImpCasts() skips
891
  /// * MaterializeTemporaryExpr
892
  /// * SubstNonTypeTemplateParmExpr
893
  Expr *IgnoreParenImpCasts() LLVM_READONLY;
894
  const Expr *IgnoreParenImpCasts() const {
895
    return const_cast<Expr *>(this)->IgnoreParenImpCasts();
896
  }
897
 
898
  /// Skip past any parentheses and casts which might surround this expression
899
  /// until reaching a fixed point. Skips:
900
  /// * What IgnoreParens() skips
901
  /// * What IgnoreCasts() skips
902
  Expr *IgnoreParenCasts() LLVM_READONLY;
903
  const Expr *IgnoreParenCasts() const {
904
    return const_cast<Expr *>(this)->IgnoreParenCasts();
905
  }
906
 
907
  /// Skip conversion operators. If this Expr is a call to a conversion
908
  /// operator, return the argument.
909
  Expr *IgnoreConversionOperatorSingleStep() LLVM_READONLY;
910
  const Expr *IgnoreConversionOperatorSingleStep() const {
911
    return const_cast<Expr *>(this)->IgnoreConversionOperatorSingleStep();
912
  }
913
 
914
  /// Skip past any parentheses and lvalue casts which might surround this
915
  /// expression until reaching a fixed point. Skips:
916
  /// * What IgnoreParens() skips
917
  /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
918
  ///   casts are skipped
919
  /// FIXME: This is intended purely as a temporary workaround for code
920
  /// that hasn't yet been rewritten to do the right thing about those
921
  /// casts, and may disappear along with the last internal use.
922
  Expr *IgnoreParenLValueCasts() LLVM_READONLY;
923
  const Expr *IgnoreParenLValueCasts() const {
924
    return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
925
  }
926
 
927
  /// Skip past any parenthese and casts which do not change the value
928
  /// (including ptr->int casts of the same size) until reaching a fixed point.
929
  /// Skips:
930
  /// * What IgnoreParens() skips
931
  /// * CastExpr which do not change the value
932
  /// * SubstNonTypeTemplateParmExpr
933
  Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY;
934
  const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
935
    return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
936
  }
937
 
938
  /// Skip past any parentheses and derived-to-base casts until reaching a
939
  /// fixed point. Skips:
940
  /// * What IgnoreParens() skips
941
  /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
942
  ///   CK_UncheckedDerivedToBase and CK_NoOp)
943
  Expr *IgnoreParenBaseCasts() LLVM_READONLY;
944
  const Expr *IgnoreParenBaseCasts() const {
945
    return const_cast<Expr *>(this)->IgnoreParenBaseCasts();
946
  }
947
 
948
  /// Determine whether this expression is a default function argument.
949
  ///
950
  /// Default arguments are implicitly generated in the abstract syntax tree
951
  /// by semantic analysis for function calls, object constructions, etc. in
952
  /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
953
  /// this routine also looks through any implicit casts to determine whether
954
  /// the expression is a default argument.
955
  bool isDefaultArgument() const;
956
 
957
  /// Determine whether the result of this expression is a
958
  /// temporary object of the given class type.
959
  bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
960
 
961
  /// Whether this expression is an implicit reference to 'this' in C++.
962
  bool isImplicitCXXThis() const;
963
 
964
  static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
965
 
966
  /// For an expression of class type or pointer to class type,
967
  /// return the most derived class decl the expression is known to refer to.
968
  ///
969
  /// If this expression is a cast, this method looks through it to find the
970
  /// most derived decl that can be inferred from the expression.
971
  /// This is valid because derived-to-base conversions have undefined
972
  /// behavior if the object isn't dynamically of the derived type.
973
  const CXXRecordDecl *getBestDynamicClassType() const;
974
 
975
  /// Get the inner expression that determines the best dynamic class.
976
  /// If this is a prvalue, we guarantee that it is of the most-derived type
977
  /// for the object itself.
978
  const Expr *getBestDynamicClassTypeExpr() const;
979
 
980
  /// Walk outwards from an expression we want to bind a reference to and
981
  /// find the expression whose lifetime needs to be extended. Record
982
  /// the LHSs of comma expressions and adjustments needed along the path.
983
  const Expr *skipRValueSubobjectAdjustments(
984
      SmallVectorImpl<const Expr *> &CommaLHS,
985
      SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
986
  const Expr *skipRValueSubobjectAdjustments() const {
987
    SmallVector<const Expr *, 8> CommaLHSs;
988
    SmallVector<SubobjectAdjustment, 8> Adjustments;
989
    return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
990
  }
991
 
992
  /// Checks that the two Expr's will refer to the same value as a comparison
993
  /// operand.  The caller must ensure that the values referenced by the Expr's
994
  /// are not modified between E1 and E2 or the result my be invalid.
995
  static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
996
 
997
  static bool classof(const Stmt *T) {
998
    return T->getStmtClass() >= firstExprConstant &&
999
           T->getStmtClass() <= lastExprConstant;
1000
  }
1001
};
1002
// PointerLikeTypeTraits is specialized so it can be used with a forward-decl of
1003
// Expr. Verify that we got it right.
1004
static_assert(llvm::PointerLikeTypeTraits<Expr *>::NumLowBitsAvailable <=
1005
                  llvm::detail::ConstantLog2<alignof(Expr)>::value,
1006
              "PointerLikeTypeTraits<Expr*> assumes too much alignment.");
1007
 
1008
using ConstantExprKind = Expr::ConstantExprKind;
1009
 
1010
//===----------------------------------------------------------------------===//
1011
// Wrapper Expressions.
1012
//===----------------------------------------------------------------------===//
1013
 
1014
/// FullExpr - Represents a "full-expression" node.
1015
class FullExpr : public Expr {
1016
protected:
1017
 Stmt *SubExpr;
1018
 
1019
 FullExpr(StmtClass SC, Expr *subexpr)
1020
     : Expr(SC, subexpr->getType(), subexpr->getValueKind(),
1021
            subexpr->getObjectKind()),
1022
       SubExpr(subexpr) {
1023
   setDependence(computeDependence(this));
1024
 }
1025
  FullExpr(StmtClass SC, EmptyShell Empty)
1026
    : Expr(SC, Empty) {}
1027
public:
1028
  const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
1029
  Expr *getSubExpr() { return cast<Expr>(SubExpr); }
1030
 
1031
  /// As with any mutator of the AST, be very careful when modifying an
1032
  /// existing AST to preserve its invariants.
1033
  void setSubExpr(Expr *E) { SubExpr = E; }
1034
 
1035
  static bool classof(const Stmt *T) {
1036
    return T->getStmtClass() >= firstFullExprConstant &&
1037
           T->getStmtClass() <= lastFullExprConstant;
1038
  }
1039
};
1040
 
1041
/// ConstantExpr - An expression that occurs in a constant context and
1042
/// optionally the result of evaluating the expression.
1043
class ConstantExpr final
1044
    : public FullExpr,
1045
      private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
1046
  static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
1047
                "ConstantExpr assumes that llvm::APInt::WordType is uint64_t "
1048
                "for tail-allocated storage");
1049
  friend TrailingObjects;
1050
  friend class ASTStmtReader;
1051
  friend class ASTStmtWriter;
1052
 
1053
public:
1054
  /// Describes the kind of result that can be tail-allocated.
1055
  enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue };
1056
 
1057
private:
1058
  size_t numTrailingObjects(OverloadToken<APValue>) const {
1059
    return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue;
1060
  }
1061
  size_t numTrailingObjects(OverloadToken<uint64_t>) const {
1062
    return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64;
1063
  }
1064
 
1065
  uint64_t &Int64Result() {
1066
    assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&
1067
           "invalid accessor");
1068
    return *getTrailingObjects<uint64_t>();
1069
  }
1070
  const uint64_t &Int64Result() const {
1071
    return const_cast<ConstantExpr *>(this)->Int64Result();
1072
  }
1073
  APValue &APValueResult() {
1074
    assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&
1075
           "invalid accessor");
1076
    return *getTrailingObjects<APValue>();
1077
  }
1078
  APValue &APValueResult() const {
1079
    return const_cast<ConstantExpr *>(this)->APValueResult();
1080
  }
1081
 
1082
  ConstantExpr(Expr *SubExpr, ResultStorageKind StorageKind,
1083
               bool IsImmediateInvocation);
1084
  ConstantExpr(EmptyShell Empty, ResultStorageKind StorageKind);
1085
 
1086
public:
1087
  static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1088
                              const APValue &Result);
1089
  static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1090
                              ResultStorageKind Storage = RSK_None,
1091
                              bool IsImmediateInvocation = false);
1092
  static ConstantExpr *CreateEmpty(const ASTContext &Context,
1093
                                   ResultStorageKind StorageKind);
1094
 
1095
  static ResultStorageKind getStorageKind(const APValue &Value);
1096
  static ResultStorageKind getStorageKind(const Type *T,
1097
                                          const ASTContext &Context);
1098
 
1099
  SourceLocation getBeginLoc() const LLVM_READONLY {
1100
    return SubExpr->getBeginLoc();
1101
  }
1102
  SourceLocation getEndLoc() const LLVM_READONLY {
1103
    return SubExpr->getEndLoc();
1104
  }
1105
 
1106
  static bool classof(const Stmt *T) {
1107
    return T->getStmtClass() == ConstantExprClass;
1108
  }
1109
 
1110
  void SetResult(APValue Value, const ASTContext &Context) {
1111
    MoveIntoResult(Value, Context);
1112
  }
1113
  void MoveIntoResult(APValue &Value, const ASTContext &Context);
1114
 
1115
  APValue::ValueKind getResultAPValueKind() const {
1116
    return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1117
  }
1118
  ResultStorageKind getResultStorageKind() const {
1119
    return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind);
1120
  }
1121
  bool isImmediateInvocation() const {
1122
    return ConstantExprBits.IsImmediateInvocation;
1123
  }
1124
  bool hasAPValueResult() const {
1125
    return ConstantExprBits.APValueKind != APValue::None;
1126
  }
1127
  APValue getAPValueResult() const;
1128
  APValue &getResultAsAPValue() const { return APValueResult(); }
1129
  llvm::APSInt getResultAsAPSInt() const;
1130
  // Iterators
1131
  child_range children() { return child_range(&SubExpr, &SubExpr+1); }
1132
  const_child_range children() const {
1133
    return const_child_range(&SubExpr, &SubExpr + 1);
1134
  }
1135
};
1136
 
1137
//===----------------------------------------------------------------------===//
1138
// Primary Expressions.
1139
//===----------------------------------------------------------------------===//
1140
 
1141
/// OpaqueValueExpr - An expression referring to an opaque object of a
1142
/// fixed type and value class.  These don't correspond to concrete
1143
/// syntax; instead they're used to express operations (usually copy
1144
/// operations) on values whose source is generally obvious from
1145
/// context.
1146
class OpaqueValueExpr : public Expr {
1147
  friend class ASTStmtReader;
1148
  Expr *SourceExpr;
1149
 
1150
public:
1151
  OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
1152
                  ExprObjectKind OK = OK_Ordinary, Expr *SourceExpr = nullptr)
1153
      : Expr(OpaqueValueExprClass, T, VK, OK), SourceExpr(SourceExpr) {
1154
    setIsUnique(false);
1155
    OpaqueValueExprBits.Loc = Loc;
1156
    setDependence(computeDependence(this));
1157
  }
1158
 
1159
  /// Given an expression which invokes a copy constructor --- i.e.  a
1160
  /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1161
  /// find the OpaqueValueExpr that's the source of the construction.
1162
  static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1163
 
1164
  explicit OpaqueValueExpr(EmptyShell Empty)
1165
    : Expr(OpaqueValueExprClass, Empty) {}
1166
 
1167
  /// Retrieve the location of this expression.
1168
  SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
1169
 
1170
  SourceLocation getBeginLoc() const LLVM_READONLY {
1171
    return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1172
  }
1173
  SourceLocation getEndLoc() const LLVM_READONLY {
1174
    return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1175
  }
1176
  SourceLocation getExprLoc() const LLVM_READONLY {
1177
    return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1178
  }
1179
 
1180
  child_range children() {
1181
    return child_range(child_iterator(), child_iterator());
1182
  }
1183
 
1184
  const_child_range children() const {
1185
    return const_child_range(const_child_iterator(), const_child_iterator());
1186
  }
1187
 
1188
  /// The source expression of an opaque value expression is the
1189
  /// expression which originally generated the value.  This is
1190
  /// provided as a convenience for analyses that don't wish to
1191
  /// precisely model the execution behavior of the program.
1192
  ///
1193
  /// The source expression is typically set when building the
1194
  /// expression which binds the opaque value expression in the first
1195
  /// place.
1196
  Expr *getSourceExpr() const { return SourceExpr; }
1197
 
1198
  void setIsUnique(bool V) {
1199
    assert((!V || SourceExpr) &&
1200
           "unique OVEs are expected to have source expressions");
1201
    OpaqueValueExprBits.IsUnique = V;
1202
  }
1203
 
1204
  bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1205
 
1206
  static bool classof(const Stmt *T) {
1207
    return T->getStmtClass() == OpaqueValueExprClass;
1208
  }
1209
};
1210
 
1211
/// A reference to a declared variable, function, enum, etc.
1212
/// [C99 6.5.1p2]
1213
///
1214
/// This encodes all the information about how a declaration is referenced
1215
/// within an expression.
1216
///
1217
/// There are several optional constructs attached to DeclRefExprs only when
1218
/// they apply in order to conserve memory. These are laid out past the end of
1219
/// the object, and flags in the DeclRefExprBitfield track whether they exist:
1220
///
1221
///   DeclRefExprBits.HasQualifier:
1222
///       Specifies when this declaration reference expression has a C++
1223
///       nested-name-specifier.
1224
///   DeclRefExprBits.HasFoundDecl:
1225
///       Specifies when this declaration reference expression has a record of
1226
///       a NamedDecl (different from the referenced ValueDecl) which was found
1227
///       during name lookup and/or overload resolution.
1228
///   DeclRefExprBits.HasTemplateKWAndArgsInfo:
1229
///       Specifies when this declaration reference expression has an explicit
1230
///       C++ template keyword and/or template argument list.
1231
///   DeclRefExprBits.RefersToEnclosingVariableOrCapture
1232
///       Specifies when this declaration reference expression (validly)
1233
///       refers to an enclosed local or a captured variable.
1234
class DeclRefExpr final
1235
    : public Expr,
1236
      private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1237
                                    NamedDecl *, ASTTemplateKWAndArgsInfo,
1238
                                    TemplateArgumentLoc> {
1239
  friend class ASTStmtReader;
1240
  friend class ASTStmtWriter;
1241
  friend TrailingObjects;
1242
 
1243
  /// The declaration that we are referencing.
1244
  ValueDecl *D;
1245
 
1246
  /// Provides source/type location info for the declaration name
1247
  /// embedded in D.
1248
  DeclarationNameLoc DNLoc;
1249
 
1250
  size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1251
    return hasQualifier();
1252
  }
1253
 
1254
  size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1255
    return hasFoundDecl();
1256
  }
1257
 
1258
  size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1259
    return hasTemplateKWAndArgsInfo();
1260
  }
1261
 
1262
  /// Test whether there is a distinct FoundDecl attached to the end of
1263
  /// this DRE.
1264
  bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1265
 
1266
  DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1267
              SourceLocation TemplateKWLoc, ValueDecl *D,
1268
              bool RefersToEnlosingVariableOrCapture,
1269
              const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1270
              const TemplateArgumentListInfo *TemplateArgs, QualType T,
1271
              ExprValueKind VK, NonOdrUseReason NOUR);
1272
 
1273
  /// Construct an empty declaration reference expression.
1274
  explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1275
 
1276
public:
1277
  DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1278
              bool RefersToEnclosingVariableOrCapture, QualType T,
1279
              ExprValueKind VK, SourceLocation L,
1280
              const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1281
              NonOdrUseReason NOUR = NOUR_None);
1282
 
1283
  static DeclRefExpr *
1284
  Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1285
         SourceLocation TemplateKWLoc, ValueDecl *D,
1286
         bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1287
         QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1288
         const TemplateArgumentListInfo *TemplateArgs = nullptr,
1289
         NonOdrUseReason NOUR = NOUR_None);
1290
 
1291
  static DeclRefExpr *
1292
  Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1293
         SourceLocation TemplateKWLoc, ValueDecl *D,
1294
         bool RefersToEnclosingVariableOrCapture,
1295
         const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1296
         NamedDecl *FoundD = nullptr,
1297
         const TemplateArgumentListInfo *TemplateArgs = nullptr,
1298
         NonOdrUseReason NOUR = NOUR_None);
1299
 
1300
  /// Construct an empty declaration reference expression.
1301
  static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1302
                                  bool HasFoundDecl,
1303
                                  bool HasTemplateKWAndArgsInfo,
1304
                                  unsigned NumTemplateArgs);
1305
 
1306
  ValueDecl *getDecl() { return D; }
1307
  const ValueDecl *getDecl() const { return D; }
1308
  void setDecl(ValueDecl *NewD);
1309
 
1310
  DeclarationNameInfo getNameInfo() const {
1311
    return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1312
  }
1313
 
1314
  SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
1315
  void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
1316
  SourceLocation getBeginLoc() const LLVM_READONLY;
1317
  SourceLocation getEndLoc() const LLVM_READONLY;
1318
 
1319
  /// Determine whether this declaration reference was preceded by a
1320
  /// C++ nested-name-specifier, e.g., \c N::foo.
1321
  bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1322
 
1323
  /// If the name was qualified, retrieves the nested-name-specifier
1324
  /// that precedes the name, with source-location information.
1325
  NestedNameSpecifierLoc getQualifierLoc() const {
1326
    if (!hasQualifier())
1327
      return NestedNameSpecifierLoc();
1328
    return *getTrailingObjects<NestedNameSpecifierLoc>();
1329
  }
1330
 
1331
  /// If the name was qualified, retrieves the nested-name-specifier
1332
  /// that precedes the name. Otherwise, returns NULL.
1333
  NestedNameSpecifier *getQualifier() const {
1334
    return getQualifierLoc().getNestedNameSpecifier();
1335
  }
1336
 
1337
  /// Get the NamedDecl through which this reference occurred.
1338
  ///
1339
  /// This Decl may be different from the ValueDecl actually referred to in the
1340
  /// presence of using declarations, etc. It always returns non-NULL, and may
1341
  /// simple return the ValueDecl when appropriate.
1342
 
1343
  NamedDecl *getFoundDecl() {
1344
    return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1345
  }
1346
 
1347
  /// Get the NamedDecl through which this reference occurred.
1348
  /// See non-const variant.
1349
  const NamedDecl *getFoundDecl() const {
1350
    return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1351
  }
1352
 
1353
  bool hasTemplateKWAndArgsInfo() const {
1354
    return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1355
  }
1356
 
1357
  /// Retrieve the location of the template keyword preceding
1358
  /// this name, if any.
1359
  SourceLocation getTemplateKeywordLoc() const {
1360
    if (!hasTemplateKWAndArgsInfo())
1361
      return SourceLocation();
1362
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1363
  }
1364
 
1365
  /// Retrieve the location of the left angle bracket starting the
1366
  /// explicit template argument list following the name, if any.
1367
  SourceLocation getLAngleLoc() const {
1368
    if (!hasTemplateKWAndArgsInfo())
1369
      return SourceLocation();
1370
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1371
  }
1372
 
1373
  /// Retrieve the location of the right angle bracket ending the
1374
  /// explicit template argument list following the name, if any.
1375
  SourceLocation getRAngleLoc() const {
1376
    if (!hasTemplateKWAndArgsInfo())
1377
      return SourceLocation();
1378
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1379
  }
1380
 
1381
  /// Determines whether the name in this declaration reference
1382
  /// was preceded by the template keyword.
1383
  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1384
 
1385
  /// Determines whether this declaration reference was followed by an
1386
  /// explicit template argument list.
1387
  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1388
 
1389
  /// Copies the template arguments (if present) into the given
1390
  /// structure.
1391
  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1392
    if (hasExplicitTemplateArgs())
1393
      getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1394
          getTrailingObjects<TemplateArgumentLoc>(), List);
1395
  }
1396
 
1397
  /// Retrieve the template arguments provided as part of this
1398
  /// template-id.
1399
  const TemplateArgumentLoc *getTemplateArgs() const {
1400
    if (!hasExplicitTemplateArgs())
1401
      return nullptr;
1402
    return getTrailingObjects<TemplateArgumentLoc>();
1403
  }
1404
 
1405
  /// Retrieve the number of template arguments provided as part of this
1406
  /// template-id.
1407
  unsigned getNumTemplateArgs() const {
1408
    if (!hasExplicitTemplateArgs())
1409
      return 0;
1410
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1411
  }
1412
 
1413
  ArrayRef<TemplateArgumentLoc> template_arguments() const {
1414
    return {getTemplateArgs(), getNumTemplateArgs()};
1415
  }
1416
 
1417
  /// Returns true if this expression refers to a function that
1418
  /// was resolved from an overloaded set having size greater than 1.
1419
  bool hadMultipleCandidates() const {
1420
    return DeclRefExprBits.HadMultipleCandidates;
1421
  }
1422
  /// Sets the flag telling whether this expression refers to
1423
  /// a function that was resolved from an overloaded set having size
1424
  /// greater than 1.
1425
  void setHadMultipleCandidates(bool V = true) {
1426
    DeclRefExprBits.HadMultipleCandidates = V;
1427
  }
1428
 
1429
  /// Is this expression a non-odr-use reference, and if so, why?
1430
  NonOdrUseReason isNonOdrUse() const {
1431
    return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1432
  }
1433
 
1434
  /// Does this DeclRefExpr refer to an enclosing local or a captured
1435
  /// variable?
1436
  bool refersToEnclosingVariableOrCapture() const {
1437
    return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1438
  }
1439
 
1440
  static bool classof(const Stmt *T) {
1441
    return T->getStmtClass() == DeclRefExprClass;
1442
  }
1443
 
1444
  // Iterators
1445
  child_range children() {
1446
    return child_range(child_iterator(), child_iterator());
1447
  }
1448
 
1449
  const_child_range children() const {
1450
    return const_child_range(const_child_iterator(), const_child_iterator());
1451
  }
1452
};
1453
 
1454
/// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1455
/// leaking memory.
1456
///
1457
/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1458
/// to represent these numbers.  Unfortunately, when we use a BumpPtrAllocator
1459
/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1460
/// the APFloat/APInt values will never get freed. APNumericStorage uses
1461
/// ASTContext's allocator for memory allocation.
1462
class APNumericStorage {
1463
  union {
1464
    uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
1465
    uint64_t *pVal;  ///< Used to store the >64 bits integer value.
1466
  };
1467
  unsigned BitWidth;
1468
 
1469
  bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1470
 
1471
  APNumericStorage(const APNumericStorage &) = delete;
1472
  void operator=(const APNumericStorage &) = delete;
1473
 
1474
protected:
1475
  APNumericStorage() : VAL(0), BitWidth(0) { }
1476
 
1477
  llvm::APInt getIntValue() const {
1478
    unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1479
    if (NumWords > 1)
1480
      return llvm::APInt(BitWidth, NumWords, pVal);
1481
    else
1482
      return llvm::APInt(BitWidth, VAL);
1483
  }
1484
  void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1485
};
1486
 
1487
class APIntStorage : private APNumericStorage {
1488
public:
1489
  llvm::APInt getValue() const { return getIntValue(); }
1490
  void setValue(const ASTContext &C, const llvm::APInt &Val) {
1491
    setIntValue(C, Val);
1492
  }
1493
};
1494
 
1495
class APFloatStorage : private APNumericStorage {
1496
public:
1497
  llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1498
    return llvm::APFloat(Semantics, getIntValue());
1499
  }
1500
  void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1501
    setIntValue(C, Val.bitcastToAPInt());
1502
  }
1503
};
1504
 
1505
class IntegerLiteral : public Expr, public APIntStorage {
1506
  SourceLocation Loc;
1507
 
1508
  /// Construct an empty integer literal.
1509
  explicit IntegerLiteral(EmptyShell Empty)
1510
    : Expr(IntegerLiteralClass, Empty) { }
1511
 
1512
public:
1513
  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1514
  // or UnsignedLongLongTy
1515
  IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1516
                 SourceLocation l);
1517
 
1518
  /// Returns a new integer literal with value 'V' and type 'type'.
1519
  /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1520
  /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1521
  /// \param V - the value that the returned integer literal contains.
1522
  static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1523
                                QualType type, SourceLocation l);
1524
  /// Returns a new empty integer literal.
1525
  static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1526
 
1527
  SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1528
  SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1529
 
1530
  /// Retrieve the location of the literal.
1531
  SourceLocation getLocation() const { return Loc; }
1532
 
1533
  void setLocation(SourceLocation Location) { Loc = Location; }
1534
 
1535
  static bool classof(const Stmt *T) {
1536
    return T->getStmtClass() == IntegerLiteralClass;
1537
  }
1538
 
1539
  // Iterators
1540
  child_range children() {
1541
    return child_range(child_iterator(), child_iterator());
1542
  }
1543
  const_child_range children() const {
1544
    return const_child_range(const_child_iterator(), const_child_iterator());
1545
  }
1546
};
1547
 
1548
class FixedPointLiteral : public Expr, public APIntStorage {
1549
  SourceLocation Loc;
1550
  unsigned Scale;
1551
 
1552
  /// \brief Construct an empty fixed-point literal.
1553
  explicit FixedPointLiteral(EmptyShell Empty)
1554
      : Expr(FixedPointLiteralClass, Empty) {}
1555
 
1556
 public:
1557
  FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1558
                    SourceLocation l, unsigned Scale);
1559
 
1560
  // Store the int as is without any bit shifting.
1561
  static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1562
                                             const llvm::APInt &V,
1563
                                             QualType type, SourceLocation l,
1564
                                             unsigned Scale);
1565
 
1566
  /// Returns an empty fixed-point literal.
1567
  static FixedPointLiteral *Create(const ASTContext &C, EmptyShell Empty);
1568
 
1569
  SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1570
  SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1571
 
1572
  /// \brief Retrieve the location of the literal.
1573
  SourceLocation getLocation() const { return Loc; }
1574
 
1575
  void setLocation(SourceLocation Location) { Loc = Location; }
1576
 
1577
  unsigned getScale() const { return Scale; }
1578
  void setScale(unsigned S) { Scale = S; }
1579
 
1580
  static bool classof(const Stmt *T) {
1581
    return T->getStmtClass() == FixedPointLiteralClass;
1582
  }
1583
 
1584
  std::string getValueAsString(unsigned Radix) const;
1585
 
1586
  // Iterators
1587
  child_range children() {
1588
    return child_range(child_iterator(), child_iterator());
1589
  }
1590
  const_child_range children() const {
1591
    return const_child_range(const_child_iterator(), const_child_iterator());
1592
  }
1593
};
1594
 
1595
class CharacterLiteral : public Expr {
1596
public:
1597
  enum CharacterKind {
1598
    Ascii,
1599
    Wide,
1600
    UTF8,
1601
    UTF16,
1602
    UTF32
1603
  };
1604
 
1605
private:
1606
  unsigned Value;
1607
  SourceLocation Loc;
1608
public:
1609
  // type should be IntTy
1610
  CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1611
                   SourceLocation l)
1612
      : Expr(CharacterLiteralClass, type, VK_PRValue, OK_Ordinary),
1613
        Value(value), Loc(l) {
1614
    CharacterLiteralBits.Kind = kind;
1615
    setDependence(ExprDependence::None);
1616
  }
1617
 
1618
  /// Construct an empty character literal.
1619
  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1620
 
1621
  SourceLocation getLocation() const { return Loc; }
1622
  CharacterKind getKind() const {
1623
    return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1624
  }
1625
 
1626
  SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1627
  SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1628
 
1629
  unsigned getValue() const { return Value; }
1630
 
1631
  void setLocation(SourceLocation Location) { Loc = Location; }
1632
  void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1633
  void setValue(unsigned Val) { Value = Val; }
1634
 
1635
  static bool classof(const Stmt *T) {
1636
    return T->getStmtClass() == CharacterLiteralClass;
1637
  }
1638
 
1639
  static void print(unsigned val, CharacterKind Kind, raw_ostream &OS);
1640
 
1641
  // Iterators
1642
  child_range children() {
1643
    return child_range(child_iterator(), child_iterator());
1644
  }
1645
  const_child_range children() const {
1646
    return const_child_range(const_child_iterator(), const_child_iterator());
1647
  }
1648
};
1649
 
1650
class FloatingLiteral : public Expr, private APFloatStorage {
1651
  SourceLocation Loc;
1652
 
1653
  FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1654
                  QualType Type, SourceLocation L);
1655
 
1656
  /// Construct an empty floating-point literal.
1657
  explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1658
 
1659
public:
1660
  static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1661
                                 bool isexact, QualType Type, SourceLocation L);
1662
  static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1663
 
1664
  llvm::APFloat getValue() const {
1665
    return APFloatStorage::getValue(getSemantics());
1666
  }
1667
  void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1668
    assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1669
    APFloatStorage::setValue(C, Val);
1670
  }
1671
 
1672
  /// Get a raw enumeration value representing the floating-point semantics of
1673
  /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1674
  llvm::APFloatBase::Semantics getRawSemantics() const {
1675
    return static_cast<llvm::APFloatBase::Semantics>(
1676
        FloatingLiteralBits.Semantics);
1677
  }
1678
 
1679
  /// Set the raw enumeration value representing the floating-point semantics of
1680
  /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1681
  void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1682
    FloatingLiteralBits.Semantics = Sem;
1683
  }
1684
 
1685
  /// Return the APFloat semantics this literal uses.
1686
  const llvm::fltSemantics &getSemantics() const {
1687
    return llvm::APFloatBase::EnumToSemantics(
1688
        static_cast<llvm::APFloatBase::Semantics>(
1689
            FloatingLiteralBits.Semantics));
1690
  }
1691
 
1692
  /// Set the APFloat semantics this literal uses.
1693
  void setSemantics(const llvm::fltSemantics &Sem) {
1694
    FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1695
  }
1696
 
1697
  bool isExact() const { return FloatingLiteralBits.IsExact; }
1698
  void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1699
 
1700
  /// getValueAsApproximateDouble - This returns the value as an inaccurate
1701
  /// double.  Note that this may cause loss of precision, but is useful for
1702
  /// debugging dumps, etc.
1703
  double getValueAsApproximateDouble() const;
1704
 
1705
  SourceLocation getLocation() const { return Loc; }
1706
  void setLocation(SourceLocation L) { Loc = L; }
1707
 
1708
  SourceLocation getBeginLoc() const LLVM_READONLY { return Loc; }
1709
  SourceLocation getEndLoc() const LLVM_READONLY { return Loc; }
1710
 
1711
  static bool classof(const Stmt *T) {
1712
    return T->getStmtClass() == FloatingLiteralClass;
1713
  }
1714
 
1715
  // Iterators
1716
  child_range children() {
1717
    return child_range(child_iterator(), child_iterator());
1718
  }
1719
  const_child_range children() const {
1720
    return const_child_range(const_child_iterator(), const_child_iterator());
1721
  }
1722
};
1723
 
1724
/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1725
/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
1726
/// IntegerLiteral classes.  Instances of this class always have a Complex type
1727
/// whose element type matches the subexpression.
1728
///
1729
class ImaginaryLiteral : public Expr {
1730
  Stmt *Val;
1731
public:
1732
  ImaginaryLiteral(Expr *val, QualType Ty)
1733
      : Expr(ImaginaryLiteralClass, Ty, VK_PRValue, OK_Ordinary), Val(val) {
1734
    setDependence(ExprDependence::None);
1735
  }
1736
 
1737
  /// Build an empty imaginary literal.
1738
  explicit ImaginaryLiteral(EmptyShell Empty)
1739
    : Expr(ImaginaryLiteralClass, Empty) { }
1740
 
1741
  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1742
  Expr *getSubExpr() { return cast<Expr>(Val); }
1743
  void setSubExpr(Expr *E) { Val = E; }
1744
 
1745
  SourceLocation getBeginLoc() const LLVM_READONLY {
1746
    return Val->getBeginLoc();
1747
  }
1748
  SourceLocation getEndLoc() const LLVM_READONLY { return Val->getEndLoc(); }
1749
 
1750
  static bool classof(const Stmt *T) {
1751
    return T->getStmtClass() == ImaginaryLiteralClass;
1752
  }
1753
 
1754
  // Iterators
1755
  child_range children() { return child_range(&Val, &Val+1); }
1756
  const_child_range children() const {
1757
    return const_child_range(&Val, &Val + 1);
1758
  }
1759
};
1760
 
1761
/// StringLiteral - This represents a string literal expression, e.g. "foo"
1762
/// or L"bar" (wide strings). The actual string data can be obtained with
1763
/// getBytes() and is NOT null-terminated. The length of the string data is
1764
/// determined by calling getByteLength().
1765
///
1766
/// The C type for a string is always a ConstantArrayType. In C++, the char
1767
/// type is const qualified, in C it is not.
1768
///
1769
/// Note that strings in C can be formed by concatenation of multiple string
1770
/// literal pptokens in translation phase #6. This keeps track of the locations
1771
/// of each of these pieces.
1772
///
1773
/// Strings in C can also be truncated and extended by assigning into arrays,
1774
/// e.g. with constructs like:
1775
///   char X[2] = "foobar";
1776
/// In this case, getByteLength() will return 6, but the string literal will
1777
/// have type "char[2]".
1778
class StringLiteral final
1779
    : public Expr,
1780
      private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1781
                                    char> {
1782
  friend class ASTStmtReader;
1783
  friend TrailingObjects;
1784
 
1785
  /// StringLiteral is followed by several trailing objects. They are in order:
1786
  ///
1787
  /// * A single unsigned storing the length in characters of this string. The
1788
  ///   length in bytes is this length times the width of a single character.
1789
  ///   Always present and stored as a trailing objects because storing it in
1790
  ///   StringLiteral would increase the size of StringLiteral by sizeof(void *)
1791
  ///   due to alignment requirements. If you add some data to StringLiteral,
1792
  ///   consider moving it inside StringLiteral.
1793
  ///
1794
  /// * An array of getNumConcatenated() SourceLocation, one for each of the
1795
  ///   token this string is made of.
1796
  ///
1797
  /// * An array of getByteLength() char used to store the string data.
1798
 
1799
public:
1800
  enum StringKind { Ordinary, Wide, UTF8, UTF16, UTF32 };
1801
 
1802
private:
1803
  unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
1804
  unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1805
    return getNumConcatenated();
1806
  }
1807
 
1808
  unsigned numTrailingObjects(OverloadToken<char>) const {
1809
    return getByteLength();
1810
  }
1811
 
1812
  char *getStrDataAsChar() { return getTrailingObjects<char>(); }
1813
  const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1814
 
1815
  const uint16_t *getStrDataAsUInt16() const {
1816
    return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1817
  }
1818
 
1819
  const uint32_t *getStrDataAsUInt32() const {
1820
    return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1821
  }
1822
 
1823
  /// Build a string literal.
1824
  StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind,
1825
                bool Pascal, QualType Ty, const SourceLocation *Loc,
1826
                unsigned NumConcatenated);
1827
 
1828
  /// Build an empty string literal.
1829
  StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1830
                unsigned CharByteWidth);
1831
 
1832
  /// Map a target and string kind to the appropriate character width.
1833
  static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK);
1834
 
1835
  /// Set one of the string literal token.
1836
  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1837
    assert(TokNum < getNumConcatenated() && "Invalid tok number");
1838
    getTrailingObjects<SourceLocation>()[TokNum] = L;
1839
  }
1840
 
1841
public:
1842
  /// This is the "fully general" constructor that allows representation of
1843
  /// strings formed from multiple concatenated tokens.
1844
  static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1845
                               StringKind Kind, bool Pascal, QualType Ty,
1846
                               const SourceLocation *Loc,
1847
                               unsigned NumConcatenated);
1848
 
1849
  /// Simple constructor for string literals made from one token.
1850
  static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1851
                               StringKind Kind, bool Pascal, QualType Ty,
1852
                               SourceLocation Loc) {
1853
    return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
1854
  }
1855
 
1856
  /// Construct an empty string literal.
1857
  static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1858
                                    unsigned NumConcatenated, unsigned Length,
1859
                                    unsigned CharByteWidth);
1860
 
1861
  StringRef getString() const {
1862
    assert(getCharByteWidth() == 1 &&
1863
           "This function is used in places that assume strings use char");
1864
    return StringRef(getStrDataAsChar(), getByteLength());
1865
  }
1866
 
1867
  /// Allow access to clients that need the byte representation, such as
1868
  /// ASTWriterStmt::VisitStringLiteral().
1869
  StringRef getBytes() const {
1870
    // FIXME: StringRef may not be the right type to use as a result for this.
1871
    return StringRef(getStrDataAsChar(), getByteLength());
1872
  }
1873
 
1874
  void outputString(raw_ostream &OS) const;
1875
 
1876
  uint32_t getCodeUnit(size_t i) const {
1877
    assert(i < getLength() && "out of bounds access");
1878
    switch (getCharByteWidth()) {
1879
    case 1:
1880
      return static_cast<unsigned char>(getStrDataAsChar()[i]);
1881
    case 2:
1882
      return getStrDataAsUInt16()[i];
1883
    case 4:
1884
      return getStrDataAsUInt32()[i];
1885
    }
1886
    llvm_unreachable("Unsupported character width!");
1887
  }
1888
 
1889
  unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
1890
  unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
1891
  unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1892
 
1893
  StringKind getKind() const {
1894
    return static_cast<StringKind>(StringLiteralBits.Kind);
1895
  }
1896
 
1897
  bool isOrdinary() const { return getKind() == Ordinary; }
1898
  bool isWide() const { return getKind() == Wide; }
1899
  bool isUTF8() const { return getKind() == UTF8; }
1900
  bool isUTF16() const { return getKind() == UTF16; }
1901
  bool isUTF32() const { return getKind() == UTF32; }
1902
  bool isPascal() const { return StringLiteralBits.IsPascal; }
1903
 
1904
  bool containsNonAscii() const {
1905
    for (auto c : getString())
1906
      if (!isASCII(c))
1907
        return true;
1908
    return false;
1909
  }
1910
 
1911
  bool containsNonAsciiOrNull() const {
1912
    for (auto c : getString())
1913
      if (!isASCII(c) || !c)
1914
        return true;
1915
    return false;
1916
  }
1917
 
1918
  /// getNumConcatenated - Get the number of string literal tokens that were
1919
  /// concatenated in translation phase #6 to form this string literal.
1920
  unsigned getNumConcatenated() const {
1921
    return StringLiteralBits.NumConcatenated;
1922
  }
1923
 
1924
  /// Get one of the string literal token.
1925
  SourceLocation getStrTokenLoc(unsigned TokNum) const {
1926
    assert(TokNum < getNumConcatenated() && "Invalid tok number");
1927
    return getTrailingObjects<SourceLocation>()[TokNum];
1928
  }
1929
 
1930
  /// getLocationOfByte - Return a source location that points to the specified
1931
  /// byte of this string literal.
1932
  ///
1933
  /// Strings are amazingly complex.  They can be formed from multiple tokens
1934
  /// and can have escape sequences in them in addition to the usual trigraph
1935
  /// and escaped newline business.  This routine handles this complexity.
1936
  ///
1937
  SourceLocation
1938
  getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1939
                    const LangOptions &Features, const TargetInfo &Target,
1940
                    unsigned *StartToken = nullptr,
1941
                    unsigned *StartTokenByteOffset = nullptr) const;
1942
 
1943
  typedef const SourceLocation *tokloc_iterator;
1944
 
1945
  tokloc_iterator tokloc_begin() const {
1946
    return getTrailingObjects<SourceLocation>();
1947
  }
1948
 
1949
  tokloc_iterator tokloc_end() const {
1950
    return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1951
  }
1952
 
1953
  SourceLocation getBeginLoc() const LLVM_READONLY { return *tokloc_begin(); }
1954
  SourceLocation getEndLoc() const LLVM_READONLY { return *(tokloc_end() - 1); }
1955
 
1956
  static bool classof(const Stmt *T) {
1957
    return T->getStmtClass() == StringLiteralClass;
1958
  }
1959
 
1960
  // Iterators
1961
  child_range children() {
1962
    return child_range(child_iterator(), child_iterator());
1963
  }
1964
  const_child_range children() const {
1965
    return const_child_range(const_child_iterator(), const_child_iterator());
1966
  }
1967
};
1968
 
1969
/// [C99 6.4.2.2] - A predefined identifier such as __func__.
1970
class PredefinedExpr final
1971
    : public Expr,
1972
      private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1973
  friend class ASTStmtReader;
1974
  friend TrailingObjects;
1975
 
1976
  // PredefinedExpr is optionally followed by a single trailing
1977
  // "Stmt *" for the predefined identifier. It is present if and only if
1978
  // hasFunctionName() is true and is always a "StringLiteral *".
1979
 
1980
public:
1981
  enum IdentKind {
1982
    Func,
1983
    Function,
1984
    LFunction, // Same as Function, but as wide string.
1985
    FuncDName,
1986
    FuncSig,
1987
    LFuncSig, // Same as FuncSig, but as wide string
1988
    PrettyFunction,
1989
    /// The same as PrettyFunction, except that the
1990
    /// 'virtual' keyword is omitted for virtual member functions.
1991
    PrettyFunctionNoVirtual
1992
  };
1993
 
1994
private:
1995
  PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
1996
                 StringLiteral *SL);
1997
 
1998
  explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
1999
 
2000
  /// True if this PredefinedExpr has storage for a function name.
2001
  bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
2002
 
2003
  void setFunctionName(StringLiteral *SL) {
2004
    assert(hasFunctionName() &&
2005
           "This PredefinedExpr has no storage for a function name!");
2006
    *getTrailingObjects<Stmt *>() = SL;
2007
  }
2008
 
2009
public:
2010
  /// Create a PredefinedExpr.
2011
  static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
2012
                                QualType FNTy, IdentKind IK, StringLiteral *SL);
2013
 
2014
  /// Create an empty PredefinedExpr.
2015
  static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
2016
                                     bool HasFunctionName);
2017
 
2018
  IdentKind getIdentKind() const {
2019
    return static_cast<IdentKind>(PredefinedExprBits.Kind);
2020
  }
2021
 
2022
  SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
2023
  void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
2024
 
2025
  StringLiteral *getFunctionName() {
2026
    return hasFunctionName()
2027
               ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2028
               : nullptr;
2029
  }
2030
 
2031
  const StringLiteral *getFunctionName() const {
2032
    return hasFunctionName()
2033
               ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
2034
               : nullptr;
2035
  }
2036
 
2037
  static StringRef getIdentKindName(IdentKind IK);
2038
  StringRef getIdentKindName() const {
2039
    return getIdentKindName(getIdentKind());
2040
  }
2041
 
2042
  static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
2043
 
2044
  SourceLocation getBeginLoc() const { return getLocation(); }
2045
  SourceLocation getEndLoc() const { return getLocation(); }
2046
 
2047
  static bool classof(const Stmt *T) {
2048
    return T->getStmtClass() == PredefinedExprClass;
2049
  }
2050
 
2051
  // Iterators
2052
  child_range children() {
2053
    return child_range(getTrailingObjects<Stmt *>(),
2054
                       getTrailingObjects<Stmt *>() + hasFunctionName());
2055
  }
2056
 
2057
  const_child_range children() const {
2058
    return const_child_range(getTrailingObjects<Stmt *>(),
2059
                             getTrailingObjects<Stmt *>() + hasFunctionName());
2060
  }
2061
};
2062
 
2063
// This represents a use of the __builtin_sycl_unique_stable_name, which takes a
2064
// type-id, and at CodeGen time emits a unique string representation of the
2065
// type in a way that permits us to properly encode information about the SYCL
2066
// kernels.
2067
class SYCLUniqueStableNameExpr final : public Expr {
2068
  friend class ASTStmtReader;
2069
  SourceLocation OpLoc, LParen, RParen;
2070
  TypeSourceInfo *TypeInfo;
2071
 
2072
  SYCLUniqueStableNameExpr(EmptyShell Empty, QualType ResultTy);
2073
  SYCLUniqueStableNameExpr(SourceLocation OpLoc, SourceLocation LParen,
2074
                           SourceLocation RParen, QualType ResultTy,
2075
                           TypeSourceInfo *TSI);
2076
 
2077
  void setTypeSourceInfo(TypeSourceInfo *Ty) { TypeInfo = Ty; }
2078
 
2079
  void setLocation(SourceLocation L) { OpLoc = L; }
2080
  void setLParenLocation(SourceLocation L) { LParen = L; }
2081
  void setRParenLocation(SourceLocation L) { RParen = L; }
2082
 
2083
public:
2084
  TypeSourceInfo *getTypeSourceInfo() { return TypeInfo; }
2085
 
2086
  const TypeSourceInfo *getTypeSourceInfo() const { return TypeInfo; }
2087
 
2088
  static SYCLUniqueStableNameExpr *
2089
  Create(const ASTContext &Ctx, SourceLocation OpLoc, SourceLocation LParen,
2090
         SourceLocation RParen, TypeSourceInfo *TSI);
2091
 
2092
  static SYCLUniqueStableNameExpr *CreateEmpty(const ASTContext &Ctx);
2093
 
2094
  SourceLocation getBeginLoc() const { return getLocation(); }
2095
  SourceLocation getEndLoc() const { return RParen; }
2096
  SourceLocation getLocation() const { return OpLoc; }
2097
  SourceLocation getLParenLocation() const { return LParen; }
2098
  SourceLocation getRParenLocation() const { return RParen; }
2099
 
2100
  static bool classof(const Stmt *T) {
2101
    return T->getStmtClass() == SYCLUniqueStableNameExprClass;
2102
  }
2103
 
2104
  // Iterators
2105
  child_range children() {
2106
    return child_range(child_iterator(), child_iterator());
2107
  }
2108
 
2109
  const_child_range children() const {
2110
    return const_child_range(const_child_iterator(), const_child_iterator());
2111
  }
2112
 
2113
  // Convenience function to generate the name of the currently stored type.
2114
  std::string ComputeName(ASTContext &Context) const;
2115
 
2116
  // Get the generated name of the type.  Note that this only works after all
2117
  // kernels have been instantiated.
2118
  static std::string ComputeName(ASTContext &Context, QualType Ty);
2119
};
2120
 
2121
/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
2122
/// AST node is only formed if full location information is requested.
2123
class ParenExpr : public Expr {
2124
  SourceLocation L, R;
2125
  Stmt *Val;
2126
public:
2127
  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
2128
      : Expr(ParenExprClass, val->getType(), val->getValueKind(),
2129
             val->getObjectKind()),
2130
        L(l), R(r), Val(val) {
2131
    setDependence(computeDependence(this));
2132
  }
2133
 
2134
  /// Construct an empty parenthesized expression.
2135
  explicit ParenExpr(EmptyShell Empty)
2136
    : Expr(ParenExprClass, Empty) { }
2137
 
2138
  const Expr *getSubExpr() const { return cast<Expr>(Val); }
2139
  Expr *getSubExpr() { return cast<Expr>(Val); }
2140
  void setSubExpr(Expr *E) { Val = E; }
2141
 
2142
  SourceLocation getBeginLoc() const LLVM_READONLY { return L; }
2143
  SourceLocation getEndLoc() const LLVM_READONLY { return R; }
2144
 
2145
  /// Get the location of the left parentheses '('.
2146
  SourceLocation getLParen() const { return L; }
2147
  void setLParen(SourceLocation Loc) { L = Loc; }
2148
 
2149
  /// Get the location of the right parentheses ')'.
2150
  SourceLocation getRParen() const { return R; }
2151
  void setRParen(SourceLocation Loc) { R = Loc; }
2152
 
2153
  static bool classof(const Stmt *T) {
2154
    return T->getStmtClass() == ParenExprClass;
2155
  }
2156
 
2157
  // Iterators
2158
  child_range children() { return child_range(&Val, &Val+1); }
2159
  const_child_range children() const {
2160
    return const_child_range(&Val, &Val + 1);
2161
  }
2162
};
2163
 
2164
/// UnaryOperator - This represents the unary-expression's (except sizeof and
2165
/// alignof), the postinc/postdec operators from postfix-expression, and various
2166
/// extensions.
2167
///
2168
/// Notes on various nodes:
2169
///
2170
/// Real/Imag - These return the real/imag part of a complex operand.  If
2171
///   applied to a non-complex value, the former returns its operand and the
2172
///   later returns zero in the type of the operand.
2173
///
2174
class UnaryOperator final
2175
    : public Expr,
2176
      private llvm::TrailingObjects<UnaryOperator, FPOptionsOverride> {
2177
  Stmt *Val;
2178
 
2179
  size_t numTrailingObjects(OverloadToken<FPOptionsOverride>) const {
2180
    return UnaryOperatorBits.HasFPFeatures ? 1 : 0;
2181
  }
2182
 
2183
  FPOptionsOverride &getTrailingFPFeatures() {
2184
    assert(UnaryOperatorBits.HasFPFeatures);
2185
    return *getTrailingObjects<FPOptionsOverride>();
2186
  }
2187
 
2188
  const FPOptionsOverride &getTrailingFPFeatures() const {
2189
    assert(UnaryOperatorBits.HasFPFeatures);
2190
    return *getTrailingObjects<FPOptionsOverride>();
2191
  }
2192
 
2193
public:
2194
  typedef UnaryOperatorKind Opcode;
2195
 
2196
protected:
2197
  UnaryOperator(const ASTContext &Ctx, Expr *input, Opcode opc, QualType type,
2198
                ExprValueKind VK, ExprObjectKind OK, SourceLocation l,
2199
                bool CanOverflow, FPOptionsOverride FPFeatures);
2200
 
2201
  /// Build an empty unary operator.
2202
  explicit UnaryOperator(bool HasFPFeatures, EmptyShell Empty)
2203
      : Expr(UnaryOperatorClass, Empty) {
2204
    UnaryOperatorBits.Opc = UO_AddrOf;
2205
    UnaryOperatorBits.HasFPFeatures = HasFPFeatures;
2206
  }
2207
 
2208
public:
2209
  static UnaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
2210
 
2211
  static UnaryOperator *Create(const ASTContext &C, Expr *input, Opcode opc,
2212
                               QualType type, ExprValueKind VK,
2213
                               ExprObjectKind OK, SourceLocation l,
2214
                               bool CanOverflow, FPOptionsOverride FPFeatures);
2215
 
2216
  Opcode getOpcode() const {
2217
    return static_cast<Opcode>(UnaryOperatorBits.Opc);
2218
  }
2219
  void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2220
 
2221
  Expr *getSubExpr() const { return cast<Expr>(Val); }
2222
  void setSubExpr(Expr *E) { Val = E; }
2223
 
2224
  /// getOperatorLoc - Return the location of the operator.
2225
  SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
2226
  void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
2227
 
2228
  /// Returns true if the unary operator can cause an overflow. For instance,
2229
  ///   signed int i = INT_MAX; i++;
2230
  ///   signed char c = CHAR_MAX; c++;
2231
  /// Due to integer promotions, c++ is promoted to an int before the postfix
2232
  /// increment, and the result is an int that cannot overflow. However, i++
2233
  /// can overflow.
2234
  bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
2235
  void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2236
 
2237
  // Get the FP contractability status of this operator. Only meaningful for
2238
  // operations on floating point types.
2239
  bool isFPContractableWithinStatement(const LangOptions &LO) const {
2240
    return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
2241
  }
2242
 
2243
  // Get the FENV_ACCESS status of this operator. Only meaningful for
2244
  // operations on floating point types.
2245
  bool isFEnvAccessOn(const LangOptions &LO) const {
2246
    return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
2247
  }
2248
 
2249
  /// isPostfix - Return true if this is a postfix operation, like x++.
2250
  static bool isPostfix(Opcode Op) {
2251
    return Op == UO_PostInc || Op == UO_PostDec;
2252
  }
2253
 
2254
  /// isPrefix - Return true if this is a prefix operation, like --x.
2255
  static bool isPrefix(Opcode Op) {
2256
    return Op == UO_PreInc || Op == UO_PreDec;
2257
  }
2258
 
2259
  bool isPrefix() const { return isPrefix(getOpcode()); }
2260
  bool isPostfix() const { return isPostfix(getOpcode()); }
2261
 
2262
  static bool isIncrementOp(Opcode Op) {
2263
    return Op == UO_PreInc || Op == UO_PostInc;
2264
  }
2265
  bool isIncrementOp() const {
2266
    return isIncrementOp(getOpcode());
2267
  }
2268
 
2269
  static bool isDecrementOp(Opcode Op) {
2270
    return Op == UO_PreDec || Op == UO_PostDec;
2271
  }
2272
  bool isDecrementOp() const {
2273
    return isDecrementOp(getOpcode());
2274
  }
2275
 
2276
  static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
2277
  bool isIncrementDecrementOp() const {
2278
    return isIncrementDecrementOp(getOpcode());
2279
  }
2280
 
2281
  static bool isArithmeticOp(Opcode Op) {
2282
    return Op >= UO_Plus && Op <= UO_LNot;
2283
  }
2284
  bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
2285
 
2286
  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2287
  /// corresponds to, e.g. "sizeof" or "[pre]++"
2288
  static StringRef getOpcodeStr(Opcode Op);
2289
 
2290
  /// Retrieve the unary opcode that corresponds to the given
2291
  /// overloaded operator.
2292
  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2293
 
2294
  /// Retrieve the overloaded operator kind that corresponds to
2295
  /// the given unary opcode.
2296
  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2297
 
2298
  SourceLocation getBeginLoc() const LLVM_READONLY {
2299
    return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2300
  }
2301
  SourceLocation getEndLoc() const LLVM_READONLY {
2302
    return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2303
  }
2304
  SourceLocation getExprLoc() const { return getOperatorLoc(); }
2305
 
2306
  static bool classof(const Stmt *T) {
2307
    return T->getStmtClass() == UnaryOperatorClass;
2308
  }
2309
 
2310
  // Iterators
2311
  child_range children() { return child_range(&Val, &Val+1); }
2312
  const_child_range children() const {
2313
    return const_child_range(&Val, &Val + 1);
2314
  }
2315
 
2316
  /// Is FPFeatures in Trailing Storage?
2317
  bool hasStoredFPFeatures() const { return UnaryOperatorBits.HasFPFeatures; }
2318
 
2319
  /// Get FPFeatures from trailing storage.
2320
  FPOptionsOverride getStoredFPFeatures() const {
2321
    return getTrailingFPFeatures();
2322
  }
2323
 
2324
protected:
2325
  /// Set FPFeatures in trailing storage, used only by Serialization
2326
  void setStoredFPFeatures(FPOptionsOverride F) { getTrailingFPFeatures() = F; }
2327
 
2328
public:
2329
  // Get the FP features status of this operator. Only meaningful for
2330
  // operations on floating point types.
2331
  FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
2332
    if (UnaryOperatorBits.HasFPFeatures)
2333
      return getStoredFPFeatures().applyOverrides(LO);
2334
    return FPOptions::defaultWithoutTrailingStorage(LO);
2335
  }
2336
  FPOptionsOverride getFPOptionsOverride() const {
2337
    if (UnaryOperatorBits.HasFPFeatures)
2338
      return getStoredFPFeatures();
2339
    return FPOptionsOverride();
2340
  }
2341
 
2342
  friend TrailingObjects;
2343
  friend class ASTReader;
2344
  friend class ASTStmtReader;
2345
  friend class ASTStmtWriter;
2346
};
2347
 
2348
/// Helper class for OffsetOfExpr.
2349
 
2350
// __builtin_offsetof(type, identifier(.identifier|[expr])*)
2351
class OffsetOfNode {
2352
public:
2353
  /// The kind of offsetof node we have.
2354
  enum Kind {
2355
    /// An index into an array.
2356
    Array = 0x00,
2357
    /// A field.
2358
    Field = 0x01,
2359
    /// A field in a dependent type, known only by its name.
2360
    Identifier = 0x02,
2361
    /// An implicit indirection through a C++ base class, when the
2362
    /// field found is in a base class.
2363
    Base = 0x03
2364
  };
2365
 
2366
private:
2367
  enum { MaskBits = 2, Mask = 0x03 };
2368
 
2369
  /// The source range that covers this part of the designator.
2370
  SourceRange Range;
2371
 
2372
  /// The data describing the designator, which comes in three
2373
  /// different forms, depending on the lower two bits.
2374
  ///   - An unsigned index into the array of Expr*'s stored after this node
2375
  ///     in memory, for [constant-expression] designators.
2376
  ///   - A FieldDecl*, for references to a known field.
2377
  ///   - An IdentifierInfo*, for references to a field with a given name
2378
  ///     when the class type is dependent.
2379
  ///   - A CXXBaseSpecifier*, for references that look at a field in a
2380
  ///     base class.
2381
  uintptr_t Data;
2382
 
2383
public:
2384
  /// Create an offsetof node that refers to an array element.
2385
  OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2386
               SourceLocation RBracketLoc)
2387
      : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2388
 
2389
  /// Create an offsetof node that refers to a field.
2390
  OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2391
      : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2392
        Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2393
 
2394
  /// Create an offsetof node that refers to an identifier.
2395
  OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2396
               SourceLocation NameLoc)
2397
      : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2398
        Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2399
 
2400
  /// Create an offsetof node that refers into a C++ base class.
2401
  explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2402
      : Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2403
 
2404
  /// Determine what kind of offsetof node this is.
2405
  Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2406
 
2407
  /// For an array element node, returns the index into the array
2408
  /// of expressions.
2409
  unsigned getArrayExprIndex() const {
2410
    assert(getKind() == Array);
2411
    return Data >> 2;
2412
  }
2413
 
2414
  /// For a field offsetof node, returns the field.
2415
  FieldDecl *getField() const {
2416
    assert(getKind() == Field);
2417
    return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2418
  }
2419
 
2420
  /// For a field or identifier offsetof node, returns the name of
2421
  /// the field.
2422
  IdentifierInfo *getFieldName() const;
2423
 
2424
  /// For a base class node, returns the base specifier.
2425
  CXXBaseSpecifier *getBase() const {
2426
    assert(getKind() == Base);
2427
    return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2428
  }
2429
 
2430
  /// Retrieve the source range that covers this offsetof node.
2431
  ///
2432
  /// For an array element node, the source range contains the locations of
2433
  /// the square brackets. For a field or identifier node, the source range
2434
  /// contains the location of the period (if there is one) and the
2435
  /// identifier.
2436
  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
2437
  SourceLocation getBeginLoc() const LLVM_READONLY { return Range.getBegin(); }
2438
  SourceLocation getEndLoc() const LLVM_READONLY { return Range.getEnd(); }
2439
};
2440
 
2441
/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2442
/// offsetof(record-type, member-designator). For example, given:
2443
/// @code
2444
/// struct S {
2445
///   float f;
2446
///   double d;
2447
/// };
2448
/// struct T {
2449
///   int i;
2450
///   struct S s[10];
2451
/// };
2452
/// @endcode
2453
/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2454
 
2455
class OffsetOfExpr final
2456
    : public Expr,
2457
      private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2458
  SourceLocation OperatorLoc, RParenLoc;
2459
  // Base type;
2460
  TypeSourceInfo *TSInfo;
2461
  // Number of sub-components (i.e. instances of OffsetOfNode).
2462
  unsigned NumComps;
2463
  // Number of sub-expressions (i.e. array subscript expressions).
2464
  unsigned NumExprs;
2465
 
2466
  size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2467
    return NumComps;
2468
  }
2469
 
2470
  OffsetOfExpr(const ASTContext &C, QualType type,
2471
               SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2472
               ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2473
               SourceLocation RParenLoc);
2474
 
2475
  explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2476
    : Expr(OffsetOfExprClass, EmptyShell()),
2477
      TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2478
 
2479
public:
2480
 
2481
  static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2482
                              SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2483
                              ArrayRef<OffsetOfNode> comps,
2484
                              ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2485
 
2486
  static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2487
                                   unsigned NumComps, unsigned NumExprs);
2488
 
2489
  /// getOperatorLoc - Return the location of the operator.
2490
  SourceLocation getOperatorLoc() const { return OperatorLoc; }
2491
  void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2492
 
2493
  /// Return the location of the right parentheses.
2494
  SourceLocation getRParenLoc() const { return RParenLoc; }
2495
  void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2496
 
2497
  TypeSourceInfo *getTypeSourceInfo() const {
2498
    return TSInfo;
2499
  }
2500
  void setTypeSourceInfo(TypeSourceInfo *tsi) {
2501
    TSInfo = tsi;
2502
  }
2503
 
2504
  const OffsetOfNode &getComponent(unsigned Idx) const {
2505
    assert(Idx < NumComps && "Subscript out of range");
2506
    return getTrailingObjects<OffsetOfNode>()[Idx];
2507
  }
2508
 
2509
  void setComponent(unsigned Idx, OffsetOfNode ON) {
2510
    assert(Idx < NumComps && "Subscript out of range");
2511
    getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2512
  }
2513
 
2514
  unsigned getNumComponents() const {
2515
    return NumComps;
2516
  }
2517
 
2518
  Expr* getIndexExpr(unsigned Idx) {
2519
    assert(Idx < NumExprs && "Subscript out of range");
2520
    return getTrailingObjects<Expr *>()[Idx];
2521
  }
2522
 
2523
  const Expr *getIndexExpr(unsigned Idx) const {
2524
    assert(Idx < NumExprs && "Subscript out of range");
2525
    return getTrailingObjects<Expr *>()[Idx];
2526
  }
2527
 
2528
  void setIndexExpr(unsigned Idx, Expr* E) {
2529
    assert(Idx < NumComps && "Subscript out of range");
2530
    getTrailingObjects<Expr *>()[Idx] = E;
2531
  }
2532
 
2533
  unsigned getNumExpressions() const {
2534
    return NumExprs;
2535
  }
2536
 
2537
  SourceLocation getBeginLoc() const LLVM_READONLY { return OperatorLoc; }
2538
  SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2539
 
2540
  static bool classof(const Stmt *T) {
2541
    return T->getStmtClass() == OffsetOfExprClass;
2542
  }
2543
 
2544
  // Iterators
2545
  child_range children() {
2546
    Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2547
    return child_range(begin, begin + NumExprs);
2548
  }
2549
  const_child_range children() const {
2550
    Stmt *const *begin =
2551
        reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2552
    return const_child_range(begin, begin + NumExprs);
2553
  }
2554
  friend TrailingObjects;
2555
};
2556
 
2557
/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2558
/// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
2559
/// vec_step (OpenCL 1.1 6.11.12).
2560
class UnaryExprOrTypeTraitExpr : public Expr {
2561
  union {
2562
    TypeSourceInfo *Ty;
2563
    Stmt *Ex;
2564
  } Argument;
2565
  SourceLocation OpLoc, RParenLoc;
2566
 
2567
public:
2568
  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2569
                           QualType resultType, SourceLocation op,
2570
                           SourceLocation rp)
2571
      : Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_PRValue,
2572
             OK_Ordinary),
2573
        OpLoc(op), RParenLoc(rp) {
2574
    assert(ExprKind <= UETT_Last && "invalid enum value!");
2575
    UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2576
    assert(static_cast<unsigned>(ExprKind) ==
2577
               UnaryExprOrTypeTraitExprBits.Kind &&
2578
           "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2579
    UnaryExprOrTypeTraitExprBits.IsType = true;
2580
    Argument.Ty = TInfo;
2581
    setDependence(computeDependence(this));
2582
  }
2583
 
2584
  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2585
                           QualType resultType, SourceLocation op,
2586
                           SourceLocation rp);
2587
 
2588
  /// Construct an empty sizeof/alignof expression.
2589
  explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2590
    : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2591
 
2592
  UnaryExprOrTypeTrait getKind() const {
2593
    return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2594
  }
2595
  void setKind(UnaryExprOrTypeTrait K) {
2596
    assert(K <= UETT_Last && "invalid enum value!");
2597
    UnaryExprOrTypeTraitExprBits.Kind = K;
2598
    assert(static_cast<unsigned>(K) == UnaryExprOrTypeTraitExprBits.Kind &&
2599
           "UnaryExprOrTypeTraitExprBits.Kind overflow!");
2600
  }
2601
 
2602
  bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2603
  QualType getArgumentType() const {
2604
    return getArgumentTypeInfo()->getType();
2605
  }
2606
  TypeSourceInfo *getArgumentTypeInfo() const {
2607
    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2608
    return Argument.Ty;
2609
  }
2610
  Expr *getArgumentExpr() {
2611
    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2612
    return static_cast<Expr*>(Argument.Ex);
2613
  }
2614
  const Expr *getArgumentExpr() const {
2615
    return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2616
  }
2617
 
2618
  void setArgument(Expr *E) {
2619
    Argument.Ex = E;
2620
    UnaryExprOrTypeTraitExprBits.IsType = false;
2621
  }
2622
  void setArgument(TypeSourceInfo *TInfo) {
2623
    Argument.Ty = TInfo;
2624
    UnaryExprOrTypeTraitExprBits.IsType = true;
2625
  }
2626
 
2627
  /// Gets the argument type, or the type of the argument expression, whichever
2628
  /// is appropriate.
2629
  QualType getTypeOfArgument() const {
2630
    return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2631
  }
2632
 
2633
  SourceLocation getOperatorLoc() const { return OpLoc; }
2634
  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2635
 
2636
  SourceLocation getRParenLoc() const { return RParenLoc; }
2637
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2638
 
2639
  SourceLocation getBeginLoc() const LLVM_READONLY { return OpLoc; }
2640
  SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
2641
 
2642
  static bool classof(const Stmt *T) {
2643
    return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2644
  }
2645
 
2646
  // Iterators
2647
  child_range children();
2648
  const_child_range children() const;
2649
};
2650
 
2651
//===----------------------------------------------------------------------===//
2652
// Postfix Operators.
2653
//===----------------------------------------------------------------------===//
2654
 
2655
/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2656
class ArraySubscriptExpr : public Expr {
2657
  enum { LHS, RHS, END_EXPR };
2658
  Stmt *SubExprs[END_EXPR];
2659
 
2660
  bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2661
 
2662
public:
2663
  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t, ExprValueKind VK,
2664
                     ExprObjectKind OK, SourceLocation rbracketloc)
2665
      : Expr(ArraySubscriptExprClass, t, VK, OK) {
2666
    SubExprs[LHS] = lhs;
2667
    SubExprs[RHS] = rhs;
2668
    ArrayOrMatrixSubscriptExprBits.RBracketLoc = rbracketloc;
2669
    setDependence(computeDependence(this));
2670
  }
2671
 
2672
  /// Create an empty array subscript expression.
2673
  explicit ArraySubscriptExpr(EmptyShell Shell)
2674
    : Expr(ArraySubscriptExprClass, Shell) { }
2675
 
2676
  /// An array access can be written A[4] or 4[A] (both are equivalent).
2677
  /// - getBase() and getIdx() always present the normalized view: A[4].
2678
  ///    In this case getBase() returns "A" and getIdx() returns "4".
2679
  /// - getLHS() and getRHS() present the syntactic view. e.g. for
2680
  ///    4[A] getLHS() returns "4".
2681
  /// Note: Because vector element access is also written A[4] we must
2682
  /// predicate the format conversion in getBase and getIdx only on the
2683
  /// the type of the RHS, as it is possible for the LHS to be a vector of
2684
  /// integer type
2685
  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2686
  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2687
  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2688
 
2689
  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2690
  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2691
  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2692
 
2693
  Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
2694
  const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2695
 
2696
  Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
2697
  const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2698
 
2699
  SourceLocation getBeginLoc() const LLVM_READONLY {
2700
    return getLHS()->getBeginLoc();
2701
  }
2702
  SourceLocation getEndLoc() const { return getRBracketLoc(); }
2703
 
2704
  SourceLocation getRBracketLoc() const {
2705
    return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2706
  }
2707
  void setRBracketLoc(SourceLocation L) {
2708
    ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2709
  }
2710
 
2711
  SourceLocation getExprLoc() const LLVM_READONLY {
2712
    return getBase()->getExprLoc();
2713
  }
2714
 
2715
  static bool classof(const Stmt *T) {
2716
    return T->getStmtClass() == ArraySubscriptExprClass;
2717
  }
2718
 
2719
  // Iterators
2720
  child_range children() {
2721
    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2722
  }
2723
  const_child_range children() const {
2724
    return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2725
  }
2726
};
2727
 
2728
/// MatrixSubscriptExpr - Matrix subscript expression for the MatrixType
2729
/// extension.
2730
/// MatrixSubscriptExpr can be either incomplete (only Base and RowIdx are set
2731
/// so far, the type is IncompleteMatrixIdx) or complete (Base, RowIdx and
2732
/// ColumnIdx refer to valid expressions). Incomplete matrix expressions only
2733
/// exist during the initial construction of the AST.
2734
class MatrixSubscriptExpr : public Expr {
2735
  enum { BASE, ROW_IDX, COLUMN_IDX, END_EXPR };
2736
  Stmt *SubExprs[END_EXPR];
2737
 
2738
public:
2739
  MatrixSubscriptExpr(Expr *Base, Expr *RowIdx, Expr *ColumnIdx, QualType T,
2740
                      SourceLocation RBracketLoc)
2741
      : Expr(MatrixSubscriptExprClass, T, Base->getValueKind(),
2742
             OK_MatrixComponent) {
2743
    SubExprs[BASE] = Base;
2744
    SubExprs[ROW_IDX] = RowIdx;
2745
    SubExprs[COLUMN_IDX] = ColumnIdx;
2746
    ArrayOrMatrixSubscriptExprBits.RBracketLoc = RBracketLoc;
2747
    setDependence(computeDependence(this));
2748
  }
2749
 
2750
  /// Create an empty matrix subscript expression.
2751
  explicit MatrixSubscriptExpr(EmptyShell Shell)
2752
      : Expr(MatrixSubscriptExprClass, Shell) {}
2753
 
2754
  bool isIncomplete() const {
2755
    bool IsIncomplete = hasPlaceholderType(BuiltinType::IncompleteMatrixIdx);
2756
    assert((SubExprs[COLUMN_IDX] || IsIncomplete) &&
2757
           "expressions without column index must be marked as incomplete");
2758
    return IsIncomplete;
2759
  }
2760
  Expr *getBase() { return cast<Expr>(SubExprs[BASE]); }
2761
  const Expr *getBase() const { return cast<Expr>(SubExprs[BASE]); }
2762
  void setBase(Expr *E) { SubExprs[BASE] = E; }
2763
 
2764
  Expr *getRowIdx() { return cast<Expr>(SubExprs[ROW_IDX]); }
2765
  const Expr *getRowIdx() const { return cast<Expr>(SubExprs[ROW_IDX]); }
2766
  void setRowIdx(Expr *E) { SubExprs[ROW_IDX] = E; }
2767
 
2768
  Expr *getColumnIdx() { return cast_or_null<Expr>(SubExprs[COLUMN_IDX]); }
2769
  const Expr *getColumnIdx() const {
2770
    assert(!isIncomplete() &&
2771
           "cannot get the column index of an incomplete expression");
2772
    return cast<Expr>(SubExprs[COLUMN_IDX]);
2773
  }
2774
  void setColumnIdx(Expr *E) { SubExprs[COLUMN_IDX] = E; }
2775
 
2776
  SourceLocation getBeginLoc() const LLVM_READONLY {
2777
    return getBase()->getBeginLoc();
2778
  }
2779
 
2780
  SourceLocation getEndLoc() const { return getRBracketLoc(); }
2781
 
2782
  SourceLocation getExprLoc() const LLVM_READONLY {
2783
    return getBase()->getExprLoc();
2784
  }
2785
 
2786
  SourceLocation getRBracketLoc() const {
2787
    return ArrayOrMatrixSubscriptExprBits.RBracketLoc;
2788
  }
2789
  void setRBracketLoc(SourceLocation L) {
2790
    ArrayOrMatrixSubscriptExprBits.RBracketLoc = L;
2791
  }
2792
 
2793
  static bool classof(const Stmt *T) {
2794
    return T->getStmtClass() == MatrixSubscriptExprClass;
2795
  }
2796
 
2797
  // Iterators
2798
  child_range children() {
2799
    return child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2800
  }
2801
  const_child_range children() const {
2802
    return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2803
  }
2804
};
2805
 
2806
/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2807
/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2808
/// while its subclasses may represent alternative syntax that (semantically)
2809
/// results in a function call. For example, CXXOperatorCallExpr is
2810
/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2811
/// "str1 + str2" to resolve to a function call.
2812
class CallExpr : public Expr {
2813
  enum { FN = 0, PREARGS_START = 1 };
2814
 
2815
  /// The number of arguments in the call expression.
2816
  unsigned NumArgs;
2817
 
2818
  /// The location of the right parenthese. This has a different meaning for
2819
  /// the derived classes of CallExpr.
2820
  SourceLocation RParenLoc;
2821
 
2822
  // CallExpr store some data in trailing objects. However since CallExpr
2823
  // is used a base of other expression classes we cannot use
2824
  // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2825
  // and casts.
2826
  //
2827
  // The trailing objects are in order:
2828
  //
2829
  // * A single "Stmt *" for the callee expression.
2830
  //
2831
  // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2832
  //
2833
  // * An array of getNumArgs() "Stmt *" for the argument expressions.
2834
  //
2835
  // * An optional of type FPOptionsOverride.
2836
  //
2837
  // Note that we store the offset in bytes from the this pointer to the start
2838
  // of the trailing objects. It would be perfectly possible to compute it
2839
  // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2840
  // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2841
  // compute this once and then load the offset from the bit-fields of Stmt,
2842
  // instead of re-computing the offset each time the trailing objects are
2843
  // accessed.
2844
 
2845
  /// Return a pointer to the start of the trailing array of "Stmt *".
2846
  Stmt **getTrailingStmts() {
2847
    return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2848
                                     CallExprBits.OffsetToTrailingObjects);
2849
  }
2850
  Stmt *const *getTrailingStmts() const {
2851
    return const_cast<CallExpr *>(this)->getTrailingStmts();
2852
  }
2853
 
2854
  /// Map a statement class to the appropriate offset in bytes from the
2855
  /// this pointer to the trailing objects.
2856
  static unsigned offsetToTrailingObjects(StmtClass SC);
2857
 
2858
  unsigned getSizeOfTrailingStmts() const {
2859
    return (1 + getNumPreArgs() + getNumArgs()) * sizeof(Stmt *);
2860
  }
2861
 
2862
  size_t getOffsetOfTrailingFPFeatures() const {
2863
    assert(hasStoredFPFeatures());
2864
    return CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts();
2865
  }
2866
 
2867
public:
2868
  enum class ADLCallKind : bool { NotADL, UsesADL };
2869
  static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
2870
  static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
2871
 
2872
protected:
2873
  /// Build a call expression, assuming that appropriate storage has been
2874
  /// allocated for the trailing objects.
2875
  CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2876
           ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2877
           SourceLocation RParenLoc, FPOptionsOverride FPFeatures,
2878
           unsigned MinNumArgs, ADLCallKind UsesADL);
2879
 
2880
  /// Build an empty call expression, for deserialization.
2881
  CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2882
           bool hasFPFeatures, EmptyShell Empty);
2883
 
2884
  /// Return the size in bytes needed for the trailing objects.
2885
  /// Used by the derived classes to allocate the right amount of storage.
2886
  static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs,
2887
                                        bool HasFPFeatures) {
2888
    return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *) +
2889
           HasFPFeatures * sizeof(FPOptionsOverride);
2890
  }
2891
 
2892
  Stmt *getPreArg(unsigned I) {
2893
    assert(I < getNumPreArgs() && "Prearg access out of range!");
2894
    return getTrailingStmts()[PREARGS_START + I];
2895
  }
2896
  const Stmt *getPreArg(unsigned I) const {
2897
    assert(I < getNumPreArgs() && "Prearg access out of range!");
2898
    return getTrailingStmts()[PREARGS_START + I];
2899
  }
2900
  void setPreArg(unsigned I, Stmt *PreArg) {
2901
    assert(I < getNumPreArgs() && "Prearg access out of range!");
2902
    getTrailingStmts()[PREARGS_START + I] = PreArg;
2903
  }
2904
 
2905
  unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2906
 
2907
  /// Return a pointer to the trailing FPOptions
2908
  FPOptionsOverride *getTrailingFPFeatures() {
2909
    assert(hasStoredFPFeatures());
2910
    return reinterpret_cast<FPOptionsOverride *>(
2911
        reinterpret_cast<char *>(this) + CallExprBits.OffsetToTrailingObjects +
2912
        getSizeOfTrailingStmts());
2913
  }
2914
  const FPOptionsOverride *getTrailingFPFeatures() const {
2915
    assert(hasStoredFPFeatures());
2916
    return reinterpret_cast<const FPOptionsOverride *>(
2917
        reinterpret_cast<const char *>(this) +
2918
        CallExprBits.OffsetToTrailingObjects + getSizeOfTrailingStmts());
2919
  }
2920
 
2921
public:
2922
  /// Create a call expression.
2923
  /// \param Fn     The callee expression,
2924
  /// \param Args   The argument array,
2925
  /// \param Ty     The type of the call expression (which is *not* the return
2926
  ///               type in general),
2927
  /// \param VK     The value kind of the call expression (lvalue, rvalue, ...),
2928
  /// \param RParenLoc  The location of the right parenthesis in the call
2929
  ///                   expression.
2930
  /// \param FPFeatures Floating-point features associated with the call,
2931
  /// \param MinNumArgs Specifies the minimum number of arguments. The actual
2932
  ///                   number of arguments will be the greater of Args.size()
2933
  ///                   and MinNumArgs. This is used in a few places to allocate
2934
  ///                   enough storage for the default arguments.
2935
  /// \param UsesADL    Specifies whether the callee was found through
2936
  ///                   argument-dependent lookup.
2937
  ///
2938
  /// Note that you can use CreateTemporary if you need a temporary call
2939
  /// expression on the stack.
2940
  static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
2941
                          ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2942
                          SourceLocation RParenLoc,
2943
                          FPOptionsOverride FPFeatures, unsigned MinNumArgs = 0,
2944
                          ADLCallKind UsesADL = NotADL);
2945
 
2946
  /// Create a temporary call expression with no arguments in the memory
2947
  /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
2948
  /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
2949
  ///
2950
  /// \code{.cpp}
2951
  ///   alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
2952
  ///   CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
2953
  /// \endcode
2954
  static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
2955
                                   ExprValueKind VK, SourceLocation RParenLoc,
2956
                                   ADLCallKind UsesADL = NotADL);
2957
 
2958
  /// Create an empty call expression, for deserialization.
2959
  static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
2960
                               bool HasFPFeatures, EmptyShell Empty);
2961
 
2962
  Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
2963
  const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
2964
  void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
2965
 
2966
  ADLCallKind getADLCallKind() const {
2967
    return static_cast<ADLCallKind>(CallExprBits.UsesADL);
2968
  }
2969
  void setADLCallKind(ADLCallKind V = UsesADL) {
2970
    CallExprBits.UsesADL = static_cast<bool>(V);
2971
  }
2972
  bool usesADL() const { return getADLCallKind() == UsesADL; }
2973
 
2974
  bool hasStoredFPFeatures() const { return CallExprBits.HasFPFeatures; }
2975
 
2976
  Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
2977
  const Decl *getCalleeDecl() const {
2978
    return getCallee()->getReferencedDeclOfCallee();
2979
  }
2980
 
2981
  /// If the callee is a FunctionDecl, return it. Otherwise return null.
2982
  FunctionDecl *getDirectCallee() {
2983
    return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2984
  }
2985
  const FunctionDecl *getDirectCallee() const {
2986
    return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2987
  }
2988
 
2989
  /// getNumArgs - Return the number of actual arguments to this call.
2990
  unsigned getNumArgs() const { return NumArgs; }
2991
 
2992
  /// Retrieve the call arguments.
2993
  Expr **getArgs() {
2994
    return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
2995
                                     getNumPreArgs());
2996
  }
2997
  const Expr *const *getArgs() const {
2998
    return reinterpret_cast<const Expr *const *>(
2999
        getTrailingStmts() + PREARGS_START + getNumPreArgs());
3000
  }
3001
 
3002
  /// getArg - Return the specified argument.
3003
  Expr *getArg(unsigned Arg) {
3004
    assert(Arg < getNumArgs() && "Arg access out of range!");
3005
    return getArgs()[Arg];
3006
  }
3007
  const Expr *getArg(unsigned Arg) const {
3008
    assert(Arg < getNumArgs() && "Arg access out of range!");
3009
    return getArgs()[Arg];
3010
  }
3011
 
3012
  /// setArg - Set the specified argument.
3013
  /// ! the dependence bits might be stale after calling this setter, it is
3014
  /// *caller*'s responsibility to recompute them by calling
3015
  /// computeDependence().
3016
  void setArg(unsigned Arg, Expr *ArgExpr) {
3017
    assert(Arg < getNumArgs() && "Arg access out of range!");
3018
    getArgs()[Arg] = ArgExpr;
3019
  }
3020
 
3021
  /// Compute and set dependence bits.
3022
  void computeDependence() {
3023
    setDependence(clang::computeDependence(
3024
        this, llvm::ArrayRef(
3025
                  reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START),
3026
                  getNumPreArgs())));
3027
  }
3028
 
3029
  /// Reduce the number of arguments in this call expression. This is used for
3030
  /// example during error recovery to drop extra arguments. There is no way
3031
  /// to perform the opposite because: 1.) We don't track how much storage
3032
  /// we have for the argument array 2.) This would potentially require growing
3033
  /// the argument array, something we cannot support since the arguments are
3034
  /// stored in a trailing array.
3035
  void shrinkNumArgs(unsigned NewNumArgs) {
3036
    assert((NewNumArgs <= getNumArgs()) &&
3037
           "shrinkNumArgs cannot increase the number of arguments!");
3038
    NumArgs = NewNumArgs;
3039
  }
3040
 
3041
  /// Bluntly set a new number of arguments without doing any checks whatsoever.
3042
  /// Only used during construction of a CallExpr in a few places in Sema.
3043
  /// FIXME: Find a way to remove it.
3044
  void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
3045
 
3046
  typedef ExprIterator arg_iterator;
3047
  typedef ConstExprIterator const_arg_iterator;
3048
  typedef llvm::iterator_range<arg_iterator> arg_range;
3049
  typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
3050
 
3051
  arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
3052
  const_arg_range arguments() const {
3053
    return const_arg_range(arg_begin(), arg_end());
3054
  }
3055
 
3056
  arg_iterator arg_begin() {
3057
    return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3058
  }
3059
  arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
3060
 
3061
  const_arg_iterator arg_begin() const {
3062
    return getTrailingStmts() + PREARGS_START + getNumPreArgs();
3063
  }
3064
  const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
3065
 
3066
  /// This method provides fast access to all the subexpressions of
3067
  /// a CallExpr without going through the slower virtual child_iterator
3068
  /// interface.  This provides efficient reverse iteration of the
3069
  /// subexpressions.  This is currently used for CFG construction.
3070
  ArrayRef<Stmt *> getRawSubExprs() {
3071
    return llvm::ArrayRef(getTrailingStmts(),
3072
                          PREARGS_START + getNumPreArgs() + getNumArgs());
3073
  }
3074
 
3075
  /// Get FPOptionsOverride from trailing storage.
3076
  FPOptionsOverride getStoredFPFeatures() const {
3077
    assert(hasStoredFPFeatures());
3078
    return *getTrailingFPFeatures();
3079
  }
3080
  /// Set FPOptionsOverride in trailing storage. Used only by Serialization.
3081
  void setStoredFPFeatures(FPOptionsOverride F) {
3082
    assert(hasStoredFPFeatures());
3083
    *getTrailingFPFeatures() = F;
3084
  }
3085
 
3086
  // Get the FP features status of this operator. Only meaningful for
3087
  // operations on floating point types.
3088
  FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3089
    if (hasStoredFPFeatures())
3090
      return getStoredFPFeatures().applyOverrides(LO);
3091
    return FPOptions::defaultWithoutTrailingStorage(LO);
3092
  }
3093
 
3094
  FPOptionsOverride getFPFeatures() const {
3095
    if (hasStoredFPFeatures())
3096
      return getStoredFPFeatures();
3097
    return FPOptionsOverride();
3098
  }
3099
 
3100
  /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
3101
  /// of the callee. If not, return 0.
3102
  unsigned getBuiltinCallee() const;
3103
 
3104
  /// Returns \c true if this is a call to a builtin which does not
3105
  /// evaluate side-effects within its arguments.
3106
  bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
3107
 
3108
  /// getCallReturnType - Get the return type of the call expr. This is not
3109
  /// always the type of the expr itself, if the return type is a reference
3110
  /// type.
3111
  QualType getCallReturnType(const ASTContext &Ctx) const;
3112
 
3113
  /// Returns the WarnUnusedResultAttr that is either declared on the called
3114
  /// function, or its return type declaration.
3115
  const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
3116
 
3117
  /// Returns true if this call expression should warn on unused results.
3118
  bool hasUnusedResultAttr(const ASTContext &Ctx) const {
3119
    return getUnusedResultAttr(Ctx) != nullptr;
3120
  }
3121
 
3122
  SourceLocation getRParenLoc() const { return RParenLoc; }
3123
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3124
 
3125
  SourceLocation getBeginLoc() const LLVM_READONLY;
3126
  SourceLocation getEndLoc() const LLVM_READONLY;
3127
 
3128
  /// Return true if this is a call to __assume() or __builtin_assume() with
3129
  /// a non-value-dependent constant parameter evaluating as false.
3130
  bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
3131
 
3132
  /// Used by Sema to implement MSVC-compatible delayed name lookup.
3133
  /// (Usually Exprs themselves should set dependence).
3134
  void markDependentForPostponedNameLookup() {
3135
    setDependence(getDependence() | ExprDependence::TypeValueInstantiation);
3136
  }
3137
 
3138
  bool isCallToStdMove() const;
3139
 
3140
  static bool classof(const Stmt *T) {
3141
    return T->getStmtClass() >= firstCallExprConstant &&
3142
           T->getStmtClass() <= lastCallExprConstant;
3143
  }
3144
 
3145
  // Iterators
3146
  child_range children() {
3147
    return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
3148
                                               getNumPreArgs() + getNumArgs());
3149
  }
3150
 
3151
  const_child_range children() const {
3152
    return const_child_range(getTrailingStmts(),
3153
                             getTrailingStmts() + PREARGS_START +
3154
                                 getNumPreArgs() + getNumArgs());
3155
  }
3156
};
3157
 
3158
/// Extra data stored in some MemberExpr objects.
3159
struct MemberExprNameQualifier {
3160
  /// The nested-name-specifier that qualifies the name, including
3161
  /// source-location information.
3162
  NestedNameSpecifierLoc QualifierLoc;
3163
 
3164
  /// The DeclAccessPair through which the MemberDecl was found due to
3165
  /// name qualifiers.
3166
  DeclAccessPair FoundDecl;
3167
};
3168
 
3169
/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
3170
///
3171
class MemberExpr final
3172
    : public Expr,
3173
      private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
3174
                                    ASTTemplateKWAndArgsInfo,
3175
                                    TemplateArgumentLoc> {
3176
  friend class ASTReader;
3177
  friend class ASTStmtReader;
3178
  friend class ASTStmtWriter;
3179
  friend TrailingObjects;
3180
 
3181
  /// Base - the expression for the base pointer or structure references.  In
3182
  /// X.F, this is "X".
3183
  Stmt *Base;
3184
 
3185
  /// MemberDecl - This is the decl being referenced by the field/member name.
3186
  /// In X.F, this is the decl referenced by F.
3187
  ValueDecl *MemberDecl;
3188
 
3189
  /// MemberDNLoc - Provides source/type location info for the
3190
  /// declaration name embedded in MemberDecl.
3191
  DeclarationNameLoc MemberDNLoc;
3192
 
3193
  /// MemberLoc - This is the location of the member name.
3194
  SourceLocation MemberLoc;
3195
 
3196
  size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
3197
    return hasQualifierOrFoundDecl();
3198
  }
3199
 
3200
  size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
3201
    return hasTemplateKWAndArgsInfo();
3202
  }
3203
 
3204
  bool hasQualifierOrFoundDecl() const {
3205
    return MemberExprBits.HasQualifierOrFoundDecl;
3206
  }
3207
 
3208
  bool hasTemplateKWAndArgsInfo() const {
3209
    return MemberExprBits.HasTemplateKWAndArgsInfo;
3210
  }
3211
 
3212
  MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
3213
             ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
3214
             QualType T, ExprValueKind VK, ExprObjectKind OK,
3215
             NonOdrUseReason NOUR);
3216
  MemberExpr(EmptyShell Empty)
3217
      : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
3218
 
3219
public:
3220
  static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
3221
                            SourceLocation OperatorLoc,
3222
                            NestedNameSpecifierLoc QualifierLoc,
3223
                            SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
3224
                            DeclAccessPair FoundDecl,
3225
                            DeclarationNameInfo MemberNameInfo,
3226
                            const TemplateArgumentListInfo *TemplateArgs,
3227
                            QualType T, ExprValueKind VK, ExprObjectKind OK,
3228
                            NonOdrUseReason NOUR);
3229
 
3230
  /// Create an implicit MemberExpr, with no location, qualifier, template
3231
  /// arguments, and so on. Suitable only for non-static member access.
3232
  static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
3233
                                    bool IsArrow, ValueDecl *MemberDecl,
3234
                                    QualType T, ExprValueKind VK,
3235
                                    ExprObjectKind OK) {
3236
    return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
3237
                  SourceLocation(), MemberDecl,
3238
                  DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
3239
                  DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
3240
  }
3241
 
3242
  static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
3243
                                 bool HasFoundDecl,
3244
                                 bool HasTemplateKWAndArgsInfo,
3245
                                 unsigned NumTemplateArgs);
3246
 
3247
  void setBase(Expr *E) { Base = E; }
3248
  Expr *getBase() const { return cast<Expr>(Base); }
3249
 
3250
  /// Retrieve the member declaration to which this expression refers.
3251
  ///
3252
  /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
3253
  /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
3254
  ValueDecl *getMemberDecl() const { return MemberDecl; }
3255
  void setMemberDecl(ValueDecl *D);
3256
 
3257
  /// Retrieves the declaration found by lookup.
3258
  DeclAccessPair getFoundDecl() const {
3259
    if (!hasQualifierOrFoundDecl())
3260
      return DeclAccessPair::make(getMemberDecl(),
3261
                                  getMemberDecl()->getAccess());
3262
    return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
3263
  }
3264
 
3265
  /// Determines whether this member expression actually had
3266
  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
3267
  /// x->Base::foo.
3268
  bool hasQualifier() const { return getQualifier() != nullptr; }
3269
 
3270
  /// If the member name was qualified, retrieves the
3271
  /// nested-name-specifier that precedes the member name, with source-location
3272
  /// information.
3273
  NestedNameSpecifierLoc getQualifierLoc() const {
3274
    if (!hasQualifierOrFoundDecl())
3275
      return NestedNameSpecifierLoc();
3276
    return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
3277
  }
3278
 
3279
  /// If the member name was qualified, retrieves the
3280
  /// nested-name-specifier that precedes the member name. Otherwise, returns
3281
  /// NULL.
3282
  NestedNameSpecifier *getQualifier() const {
3283
    return getQualifierLoc().getNestedNameSpecifier();
3284
  }
3285
 
3286
  /// Retrieve the location of the template keyword preceding
3287
  /// the member name, if any.
3288
  SourceLocation getTemplateKeywordLoc() const {
3289
    if (!hasTemplateKWAndArgsInfo())
3290
      return SourceLocation();
3291
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
3292
  }
3293
 
3294
  /// Retrieve the location of the left angle bracket starting the
3295
  /// explicit template argument list following the member name, if any.
3296
  SourceLocation getLAngleLoc() const {
3297
    if (!hasTemplateKWAndArgsInfo())
3298
      return SourceLocation();
3299
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
3300
  }
3301
 
3302
  /// Retrieve the location of the right angle bracket ending the
3303
  /// explicit template argument list following the member name, if any.
3304
  SourceLocation getRAngleLoc() const {
3305
    if (!hasTemplateKWAndArgsInfo())
3306
      return SourceLocation();
3307
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
3308
  }
3309
 
3310
  /// Determines whether the member name was preceded by the template keyword.
3311
  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
3312
 
3313
  /// Determines whether the member name was followed by an
3314
  /// explicit template argument list.
3315
  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
3316
 
3317
  /// Copies the template arguments (if present) into the given
3318
  /// structure.
3319
  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
3320
    if (hasExplicitTemplateArgs())
3321
      getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
3322
          getTrailingObjects<TemplateArgumentLoc>(), List);
3323
  }
3324
 
3325
  /// Retrieve the template arguments provided as part of this
3326
  /// template-id.
3327
  const TemplateArgumentLoc *getTemplateArgs() const {
3328
    if (!hasExplicitTemplateArgs())
3329
      return nullptr;
3330
 
3331
    return getTrailingObjects<TemplateArgumentLoc>();
3332
  }
3333
 
3334
  /// Retrieve the number of template arguments provided as part of this
3335
  /// template-id.
3336
  unsigned getNumTemplateArgs() const {
3337
    if (!hasExplicitTemplateArgs())
3338
      return 0;
3339
 
3340
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
3341
  }
3342
 
3343
  ArrayRef<TemplateArgumentLoc> template_arguments() const {
3344
    return {getTemplateArgs(), getNumTemplateArgs()};
3345
  }
3346
 
3347
  /// Retrieve the member declaration name info.
3348
  DeclarationNameInfo getMemberNameInfo() const {
3349
    return DeclarationNameInfo(MemberDecl->getDeclName(),
3350
                               MemberLoc, MemberDNLoc);
3351
  }
3352
 
3353
  SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
3354
 
3355
  bool isArrow() const { return MemberExprBits.IsArrow; }
3356
  void setArrow(bool A) { MemberExprBits.IsArrow = A; }
3357
 
3358
  /// getMemberLoc - Return the location of the "member", in X->F, it is the
3359
  /// location of 'F'.
3360
  SourceLocation getMemberLoc() const { return MemberLoc; }
3361
  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3362
 
3363
  SourceLocation getBeginLoc() const LLVM_READONLY;
3364
  SourceLocation getEndLoc() const LLVM_READONLY;
3365
 
3366
  SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
3367
 
3368
  /// Determine whether the base of this explicit is implicit.
3369
  bool isImplicitAccess() const {
3370
    return getBase() && getBase()->isImplicitCXXThis();
3371
  }
3372
 
3373
  /// Returns true if this member expression refers to a method that
3374
  /// was resolved from an overloaded set having size greater than 1.
3375
  bool hadMultipleCandidates() const {
3376
    return MemberExprBits.HadMultipleCandidates;
3377
  }
3378
  /// Sets the flag telling whether this expression refers to
3379
  /// a method that was resolved from an overloaded set having size
3380
  /// greater than 1.
3381
  void setHadMultipleCandidates(bool V = true) {
3382
    MemberExprBits.HadMultipleCandidates = V;
3383
  }
3384
 
3385
  /// Returns true if virtual dispatch is performed.
3386
  /// If the member access is fully qualified, (i.e. X::f()), virtual
3387
  /// dispatching is not performed. In -fapple-kext mode qualified
3388
  /// calls to virtual method will still go through the vtable.
3389
  bool performsVirtualDispatch(const LangOptions &LO) const {
3390
    return LO.AppleKext || !hasQualifier();
3391
  }
3392
 
3393
  /// Is this expression a non-odr-use reference, and if so, why?
3394
  /// This is only meaningful if the named member is a static member.
3395
  NonOdrUseReason isNonOdrUse() const {
3396
    return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3397
  }
3398
 
3399
  static bool classof(const Stmt *T) {
3400
    return T->getStmtClass() == MemberExprClass;
3401
  }
3402
 
3403
  // Iterators
3404
  child_range children() { return child_range(&Base, &Base+1); }
3405
  const_child_range children() const {
3406
    return const_child_range(&Base, &Base + 1);
3407
  }
3408
};
3409
 
3410
/// CompoundLiteralExpr - [C99 6.5.2.5]
3411
///
3412
class CompoundLiteralExpr : public Expr {
3413
  /// LParenLoc - If non-null, this is the location of the left paren in a
3414
  /// compound literal like "(int){4}".  This can be null if this is a
3415
  /// synthesized compound expression.
3416
  SourceLocation LParenLoc;
3417
 
3418
  /// The type as written.  This can be an incomplete array type, in
3419
  /// which case the actual expression type will be different.
3420
  /// The int part of the pair stores whether this expr is file scope.
3421
  llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3422
  Stmt *Init;
3423
public:
3424
  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
3425
                      QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3426
      : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary),
3427
        LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {
3428
    setDependence(computeDependence(this));
3429
  }
3430
 
3431
  /// Construct an empty compound literal.
3432
  explicit CompoundLiteralExpr(EmptyShell Empty)
3433
    : Expr(CompoundLiteralExprClass, Empty) { }
3434
 
3435
  const Expr *getInitializer() const { return cast<Expr>(Init); }
3436
  Expr *getInitializer() { return cast<Expr>(Init); }
3437
  void setInitializer(Expr *E) { Init = E; }
3438
 
3439
  bool isFileScope() const { return TInfoAndScope.getInt(); }
3440
  void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3441
 
3442
  SourceLocation getLParenLoc() const { return LParenLoc; }
3443
  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3444
 
3445
  TypeSourceInfo *getTypeSourceInfo() const {
3446
    return TInfoAndScope.getPointer();
3447
  }
3448
  void setTypeSourceInfo(TypeSourceInfo *tinfo) {
3449
    TInfoAndScope.setPointer(tinfo);
3450
  }
3451
 
3452
  SourceLocation getBeginLoc() const LLVM_READONLY {
3453
    // FIXME: Init should never be null.
3454
    if (!Init)
3455
      return SourceLocation();
3456
    if (LParenLoc.isInvalid())
3457
      return Init->getBeginLoc();
3458
    return LParenLoc;
3459
  }
3460
  SourceLocation getEndLoc() const LLVM_READONLY {
3461
    // FIXME: Init should never be null.
3462
    if (!Init)
3463
      return SourceLocation();
3464
    return Init->getEndLoc();
3465
  }
3466
 
3467
  static bool classof(const Stmt *T) {
3468
    return T->getStmtClass() == CompoundLiteralExprClass;
3469
  }
3470
 
3471
  // Iterators
3472
  child_range children() { return child_range(&Init, &Init+1); }
3473
  const_child_range children() const {
3474
    return const_child_range(&Init, &Init + 1);
3475
  }
3476
};
3477
 
3478
/// CastExpr - Base class for type casts, including both implicit
3479
/// casts (ImplicitCastExpr) and explicit casts that have some
3480
/// representation in the source code (ExplicitCastExpr's derived
3481
/// classes).
3482
class CastExpr : public Expr {
3483
  Stmt *Op;
3484
 
3485
  bool CastConsistency() const;
3486
 
3487
  const CXXBaseSpecifier * const *path_buffer() const {
3488
    return const_cast<CastExpr*>(this)->path_buffer();
3489
  }
3490
  CXXBaseSpecifier **path_buffer();
3491
 
3492
  friend class ASTStmtReader;
3493
 
3494
protected:
3495
  CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
3496
           Expr *op, unsigned BasePathSize, bool HasFPFeatures)
3497
      : Expr(SC, ty, VK, OK_Ordinary), Op(op) {
3498
    CastExprBits.Kind = kind;
3499
    CastExprBits.PartOfExplicitCast = false;
3500
    CastExprBits.BasePathSize = BasePathSize;
3501
    assert((CastExprBits.BasePathSize == BasePathSize) &&
3502
           "BasePathSize overflow!");
3503
    assert(CastConsistency());
3504
    CastExprBits.HasFPFeatures = HasFPFeatures;
3505
  }
3506
 
3507
  /// Construct an empty cast.
3508
  CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize,
3509
           bool HasFPFeatures)
3510
      : Expr(SC, Empty) {
3511
    CastExprBits.PartOfExplicitCast = false;
3512
    CastExprBits.BasePathSize = BasePathSize;
3513
    CastExprBits.HasFPFeatures = HasFPFeatures;
3514
    assert((CastExprBits.BasePathSize == BasePathSize) &&
3515
           "BasePathSize overflow!");
3516
  }
3517
 
3518
  /// Return a pointer to the trailing FPOptions.
3519
  /// \pre hasStoredFPFeatures() == true
3520
  FPOptionsOverride *getTrailingFPFeatures();
3521
  const FPOptionsOverride *getTrailingFPFeatures() const {
3522
    return const_cast<CastExpr *>(this)->getTrailingFPFeatures();
3523
  }
3524
 
3525
public:
3526
  CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
3527
  void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3528
 
3529
  static const char *getCastKindName(CastKind CK);
3530
  const char *getCastKindName() const { return getCastKindName(getCastKind()); }
3531
 
3532
  Expr *getSubExpr() { return cast<Expr>(Op); }
3533
  const Expr *getSubExpr() const { return cast<Expr>(Op); }
3534
  void setSubExpr(Expr *E) { Op = E; }
3535
 
3536
  /// Retrieve the cast subexpression as it was written in the source
3537
  /// code, looking through any implicit casts or other intermediate nodes
3538
  /// introduced by semantic analysis.
3539
  Expr *getSubExprAsWritten();
3540
  const Expr *getSubExprAsWritten() const {
3541
    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3542
  }
3543
 
3544
  /// If this cast applies a user-defined conversion, retrieve the conversion
3545
  /// function that it invokes.
3546
  NamedDecl *getConversionFunction() const;
3547
 
3548
  typedef CXXBaseSpecifier **path_iterator;
3549
  typedef const CXXBaseSpecifier *const *path_const_iterator;
3550
  bool path_empty() const { return path_size() == 0; }
3551
  unsigned path_size() const { return CastExprBits.BasePathSize; }
3552
  path_iterator path_begin() { return path_buffer(); }
3553
  path_iterator path_end() { return path_buffer() + path_size(); }
3554
  path_const_iterator path_begin() const { return path_buffer(); }
3555
  path_const_iterator path_end() const { return path_buffer() + path_size(); }
3556
 
3557
  llvm::iterator_range<path_iterator> path() {
3558
    return llvm::make_range(path_begin(), path_end());
3559
  }
3560
  llvm::iterator_range<path_const_iterator> path() const {
3561
    return llvm::make_range(path_begin(), path_end());
3562
  }
3563
 
3564
  const FieldDecl *getTargetUnionField() const {
3565
    assert(getCastKind() == CK_ToUnion);
3566
    return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
3567
  }
3568
 
3569
  bool hasStoredFPFeatures() const { return CastExprBits.HasFPFeatures; }
3570
 
3571
  /// Get FPOptionsOverride from trailing storage.
3572
  FPOptionsOverride getStoredFPFeatures() const {
3573
    assert(hasStoredFPFeatures());
3574
    return *getTrailingFPFeatures();
3575
  }
3576
 
3577
  // Get the FP features status of this operation. Only meaningful for
3578
  // operations on floating point types.
3579
  FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
3580
    if (hasStoredFPFeatures())
3581
      return getStoredFPFeatures().applyOverrides(LO);
3582
    return FPOptions::defaultWithoutTrailingStorage(LO);
3583
  }
3584
 
3585
  FPOptionsOverride getFPFeatures() const {
3586
    if (hasStoredFPFeatures())
3587
      return getStoredFPFeatures();
3588
    return FPOptionsOverride();
3589
  }
3590
 
3591
  static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3592
                                                       QualType opType);
3593
  static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3594
                                                       QualType opType);
3595
 
3596
  static bool classof(const Stmt *T) {
3597
    return T->getStmtClass() >= firstCastExprConstant &&
3598
           T->getStmtClass() <= lastCastExprConstant;
3599
  }
3600
 
3601
  // Iterators
3602
  child_range children() { return child_range(&Op, &Op+1); }
3603
  const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3604
};
3605
 
3606
/// ImplicitCastExpr - Allows us to explicitly represent implicit type
3607
/// conversions, which have no direct representation in the original
3608
/// source code. For example: converting T[]->T*, void f()->void
3609
/// (*f)(), float->double, short->int, etc.
3610
///
3611
/// In C, implicit casts always produce rvalues. However, in C++, an
3612
/// implicit cast whose result is being bound to a reference will be
3613
/// an lvalue or xvalue. For example:
3614
///
3615
/// @code
3616
/// class Base { };
3617
/// class Derived : public Base { };
3618
/// Derived &&ref();
3619
/// void f(Derived d) {
3620
///   Base& b = d; // initializer is an ImplicitCastExpr
3621
///                // to an lvalue of type Base
3622
///   Base&& r = ref(); // initializer is an ImplicitCastExpr
3623
///                     // to an xvalue of type Base
3624
/// }
3625
/// @endcode
3626
class ImplicitCastExpr final
3627
    : public CastExpr,
3628
      private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *,
3629
                                    FPOptionsOverride> {
3630
 
3631
  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3632
                   unsigned BasePathLength, FPOptionsOverride FPO,
3633
                   ExprValueKind VK)
3634
      : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength,
3635
                 FPO.requiresTrailingStorage()) {
3636
    setDependence(computeDependence(this));
3637
    if (hasStoredFPFeatures())
3638
      *getTrailingFPFeatures() = FPO;
3639
  }
3640
 
3641
  /// Construct an empty implicit cast.
3642
  explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize,
3643
                            bool HasFPFeatures)
3644
      : CastExpr(ImplicitCastExprClass, Shell, PathSize, HasFPFeatures) {}
3645
 
3646
  unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3647
    return path_size();
3648
  }
3649
 
3650
public:
3651
  enum OnStack_t { OnStack };
3652
  ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
3653
                   ExprValueKind VK, FPOptionsOverride FPO)
3654
      : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0,
3655
                 FPO.requiresTrailingStorage()) {
3656
    if (hasStoredFPFeatures())
3657
      *getTrailingFPFeatures() = FPO;
3658
  }
3659
 
3660
  bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
3661
  void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3662
    CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3663
  }
3664
 
3665
  static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3666
                                  CastKind Kind, Expr *Operand,
3667
                                  const CXXCastPath *BasePath,
3668
                                  ExprValueKind Cat, FPOptionsOverride FPO);
3669
 
3670
  static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3671
                                       unsigned PathSize, bool HasFPFeatures);
3672
 
3673
  SourceLocation getBeginLoc() const LLVM_READONLY {
3674
    return getSubExpr()->getBeginLoc();
3675
  }
3676
  SourceLocation getEndLoc() const LLVM_READONLY {
3677
    return getSubExpr()->getEndLoc();
3678
  }
3679
 
3680
  static bool classof(const Stmt *T) {
3681
    return T->getStmtClass() == ImplicitCastExprClass;
3682
  }
3683
 
3684
  friend TrailingObjects;
3685
  friend class CastExpr;
3686
};
3687
 
3688
/// ExplicitCastExpr - An explicit cast written in the source
3689
/// code.
3690
///
3691
/// This class is effectively an abstract class, because it provides
3692
/// the basic representation of an explicitly-written cast without
3693
/// specifying which kind of cast (C cast, functional cast, static
3694
/// cast, etc.) was written; specific derived classes represent the
3695
/// particular style of cast and its location information.
3696
///
3697
/// Unlike implicit casts, explicit cast nodes have two different
3698
/// types: the type that was written into the source code, and the
3699
/// actual type of the expression as determined by semantic
3700
/// analysis. These types may differ slightly. For example, in C++ one
3701
/// can cast to a reference type, which indicates that the resulting
3702
/// expression will be an lvalue or xvalue. The reference type, however,
3703
/// will not be used as the type of the expression.
3704
class ExplicitCastExpr : public CastExpr {
3705
  /// TInfo - Source type info for the (written) type
3706
  /// this expression is casting to.
3707
  TypeSourceInfo *TInfo;
3708
 
3709
protected:
3710
  ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3711
                   CastKind kind, Expr *op, unsigned PathSize,
3712
                   bool HasFPFeatures, TypeSourceInfo *writtenTy)
3713
      : CastExpr(SC, exprTy, VK, kind, op, PathSize, HasFPFeatures),
3714
        TInfo(writtenTy) {
3715
    setDependence(computeDependence(this));
3716
  }
3717
 
3718
  /// Construct an empty explicit cast.
3719
  ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize,
3720
                   bool HasFPFeatures)
3721
      : CastExpr(SC, Shell, PathSize, HasFPFeatures) {}
3722
 
3723
public:
3724
  /// getTypeInfoAsWritten - Returns the type source info for the type
3725
  /// that this expression is casting to.
3726
  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
3727
  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3728
 
3729
  /// getTypeAsWritten - Returns the type that this expression is
3730
  /// casting to, as written in the source code.
3731
  QualType getTypeAsWritten() const { return TInfo->getType(); }
3732
 
3733
  static bool classof(const Stmt *T) {
3734
     return T->getStmtClass() >= firstExplicitCastExprConstant &&
3735
            T->getStmtClass() <= lastExplicitCastExprConstant;
3736
  }
3737
};
3738
 
3739
/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3740
/// cast in C++ (C++ [expr.cast]), which uses the syntax
3741
/// (Type)expr. For example: @c (int)f.
3742
class CStyleCastExpr final
3743
    : public ExplicitCastExpr,
3744
      private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *,
3745
                                    FPOptionsOverride> {
3746
  SourceLocation LPLoc; // the location of the left paren
3747
  SourceLocation RPLoc; // the location of the right paren
3748
 
3749
  CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3750
                 unsigned PathSize, FPOptionsOverride FPO,
3751
                 TypeSourceInfo *writtenTy, SourceLocation l, SourceLocation r)
3752
      : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3753
                         FPO.requiresTrailingStorage(), writtenTy),
3754
        LPLoc(l), RPLoc(r) {
3755
    if (hasStoredFPFeatures())
3756
      *getTrailingFPFeatures() = FPO;
3757
  }
3758
 
3759
  /// Construct an empty C-style explicit cast.
3760
  explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize,
3761
                          bool HasFPFeatures)
3762
      : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize, HasFPFeatures) {}
3763
 
3764
  unsigned numTrailingObjects(OverloadToken<CXXBaseSpecifier *>) const {
3765
    return path_size();
3766
  }
3767
 
3768
public:
3769
  static CStyleCastExpr *
3770
  Create(const ASTContext &Context, QualType T, ExprValueKind VK, CastKind K,
3771
         Expr *Op, const CXXCastPath *BasePath, FPOptionsOverride FPO,
3772
         TypeSourceInfo *WrittenTy, SourceLocation L, SourceLocation R);
3773
 
3774
  static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3775
                                     unsigned PathSize, bool HasFPFeatures);
3776
 
3777
  SourceLocation getLParenLoc() const { return LPLoc; }
3778
  void setLParenLoc(SourceLocation L) { LPLoc = L; }
3779
 
3780
  SourceLocation getRParenLoc() const { return RPLoc; }
3781
  void setRParenLoc(SourceLocation L) { RPLoc = L; }
3782
 
3783
  SourceLocation getBeginLoc() const LLVM_READONLY { return LPLoc; }
3784
  SourceLocation getEndLoc() const LLVM_READONLY {
3785
    return getSubExpr()->getEndLoc();
3786
  }
3787
 
3788
  static bool classof(const Stmt *T) {
3789
    return T->getStmtClass() == CStyleCastExprClass;
3790
  }
3791
 
3792
  friend TrailingObjects;
3793
  friend class CastExpr;
3794
};
3795
 
3796
/// A builtin binary operation expression such as "x + y" or "x <= y".
3797
///
3798
/// This expression node kind describes a builtin binary operation,
3799
/// such as "x + y" for integer values "x" and "y". The operands will
3800
/// already have been converted to appropriate types (e.g., by
3801
/// performing promotions or conversions).
3802
///
3803
/// In C++, where operators may be overloaded, a different kind of
3804
/// expression node (CXXOperatorCallExpr) is used to express the
3805
/// invocation of an overloaded operator with operator syntax. Within
3806
/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3807
/// used to store an expression "x + y" depends on the subexpressions
3808
/// for x and y. If neither x or y is type-dependent, and the "+"
3809
/// operator resolves to a built-in operation, BinaryOperator will be
3810
/// used to express the computation (x and y may still be
3811
/// value-dependent). If either x or y is type-dependent, or if the
3812
/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3813
/// be used to express the computation.
3814
class BinaryOperator : public Expr {
3815
  enum { LHS, RHS, END_EXPR };
3816
  Stmt *SubExprs[END_EXPR];
3817
 
3818
public:
3819
  typedef BinaryOperatorKind Opcode;
3820
 
3821
protected:
3822
  size_t offsetOfTrailingStorage() const;
3823
 
3824
  /// Return a pointer to the trailing FPOptions
3825
  FPOptionsOverride *getTrailingFPFeatures() {
3826
    assert(BinaryOperatorBits.HasFPFeatures);
3827
    return reinterpret_cast<FPOptionsOverride *>(
3828
        reinterpret_cast<char *>(this) + offsetOfTrailingStorage());
3829
  }
3830
  const FPOptionsOverride *getTrailingFPFeatures() const {
3831
    assert(BinaryOperatorBits.HasFPFeatures);
3832
    return reinterpret_cast<const FPOptionsOverride *>(
3833
        reinterpret_cast<const char *>(this) + offsetOfTrailingStorage());
3834
  }
3835
 
3836
  /// Build a binary operator, assuming that appropriate storage has been
3837
  /// allocated for the trailing objects when needed.
3838
  BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
3839
                 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
3840
                 SourceLocation opLoc, FPOptionsOverride FPFeatures);
3841
 
3842
  /// Construct an empty binary operator.
3843
  explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3844
    BinaryOperatorBits.Opc = BO_Comma;
3845
  }
3846
 
3847
public:
3848
  static BinaryOperator *CreateEmpty(const ASTContext &C, bool hasFPFeatures);
3849
 
3850
  static BinaryOperator *Create(const ASTContext &C, Expr *lhs, Expr *rhs,
3851
                                Opcode opc, QualType ResTy, ExprValueKind VK,
3852
                                ExprObjectKind OK, SourceLocation opLoc,
3853
                                FPOptionsOverride FPFeatures);
3854
  SourceLocation getExprLoc() const { return getOperatorLoc(); }
3855
  SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
3856
  void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
3857
 
3858
  Opcode getOpcode() const {
3859
    return static_cast<Opcode>(BinaryOperatorBits.Opc);
3860
  }
3861
  void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3862
 
3863
  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3864
  void setLHS(Expr *E) { SubExprs[LHS] = E; }
3865
  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3866
  void setRHS(Expr *E) { SubExprs[RHS] = E; }
3867
 
3868
  SourceLocation getBeginLoc() const LLVM_READONLY {
3869
    return getLHS()->getBeginLoc();
3870
  }
3871
  SourceLocation getEndLoc() const LLVM_READONLY {
3872
    return getRHS()->getEndLoc();
3873
  }
3874
 
3875
  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3876
  /// corresponds to, e.g. "<<=".
3877
  static StringRef getOpcodeStr(Opcode Op);
3878
 
3879
  StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3880
 
3881
  /// Retrieve the binary opcode that corresponds to the given
3882
  /// overloaded operator.
3883
  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3884
 
3885
  /// Retrieve the overloaded operator kind that corresponds to
3886
  /// the given binary opcode.
3887
  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3888
 
3889
  /// predicates to categorize the respective opcodes.
3890
  static bool isPtrMemOp(Opcode Opc) {
3891
    return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3892
  }
3893
  bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
3894
 
3895
  static bool isMultiplicativeOp(Opcode Opc) {
3896
    return Opc >= BO_Mul && Opc <= BO_Rem;
3897
  }
3898
  bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
3899
  static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3900
  bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3901
  static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3902
  bool isShiftOp() const { return isShiftOp(getOpcode()); }
3903
 
3904
  static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3905
  bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3906
 
3907
  static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3908
  bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3909
 
3910
  static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3911
  bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3912
 
3913
  static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3914
  bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3915
 
3916
  static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
3917
  bool isCommaOp() const { return isCommaOp(getOpcode()); }
3918
 
3919
  static Opcode negateComparisonOp(Opcode Opc) {
3920
    switch (Opc) {
3921
    default:
3922
      llvm_unreachable("Not a comparison operator.");
3923
    case BO_LT: return BO_GE;
3924
    case BO_GT: return BO_LE;
3925
    case BO_LE: return BO_GT;
3926
    case BO_GE: return BO_LT;
3927
    case BO_EQ: return BO_NE;
3928
    case BO_NE: return BO_EQ;
3929
    }
3930
  }
3931
 
3932
  static Opcode reverseComparisonOp(Opcode Opc) {
3933
    switch (Opc) {
3934
    default:
3935
      llvm_unreachable("Not a comparison operator.");
3936
    case BO_LT: return BO_GT;
3937
    case BO_GT: return BO_LT;
3938
    case BO_LE: return BO_GE;
3939
    case BO_GE: return BO_LE;
3940
    case BO_EQ:
3941
    case BO_NE:
3942
      return Opc;
3943
    }
3944
  }
3945
 
3946
  static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3947
  bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3948
 
3949
  static bool isAssignmentOp(Opcode Opc) {
3950
    return Opc >= BO_Assign && Opc <= BO_OrAssign;
3951
  }
3952
  bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3953
 
3954
  static bool isCompoundAssignmentOp(Opcode Opc) {
3955
    return Opc > BO_Assign && Opc <= BO_OrAssign;
3956
  }
3957
  bool isCompoundAssignmentOp() const {
3958
    return isCompoundAssignmentOp(getOpcode());
3959
  }
3960
  static Opcode getOpForCompoundAssignment(Opcode Opc) {
3961
    assert(isCompoundAssignmentOp(Opc));
3962
    if (Opc >= BO_AndAssign)
3963
      return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3964
    else
3965
      return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3966
  }
3967
 
3968
  static bool isShiftAssignOp(Opcode Opc) {
3969
    return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3970
  }
3971
  bool isShiftAssignOp() const {
3972
    return isShiftAssignOp(getOpcode());
3973
  }
3974
 
3975
  // Return true if a binary operator using the specified opcode and operands
3976
  // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3977
  // integer to a pointer.
3978
  static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3979
                                               Expr *LHS, Expr *RHS);
3980
 
3981
  static bool classof(const Stmt *S) {
3982
    return S->getStmtClass() >= firstBinaryOperatorConstant &&
3983
           S->getStmtClass() <= lastBinaryOperatorConstant;
3984
  }
3985
 
3986
  // Iterators
3987
  child_range children() {
3988
    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3989
  }
3990
  const_child_range children() const {
3991
    return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3992
  }
3993
 
3994
  /// Set and fetch the bit that shows whether FPFeatures needs to be
3995
  /// allocated in Trailing Storage
3996
  void setHasStoredFPFeatures(bool B) { BinaryOperatorBits.HasFPFeatures = B; }
3997
  bool hasStoredFPFeatures() const { return BinaryOperatorBits.HasFPFeatures; }
3998
 
3999
  /// Get FPFeatures from trailing storage
4000
  FPOptionsOverride getStoredFPFeatures() const {
4001
    assert(hasStoredFPFeatures());
4002
    return *getTrailingFPFeatures();
4003
  }
4004
  /// Set FPFeatures in trailing storage, used only by Serialization
4005
  void setStoredFPFeatures(FPOptionsOverride F) {
4006
    assert(BinaryOperatorBits.HasFPFeatures);
4007
    *getTrailingFPFeatures() = F;
4008
  }
4009
 
4010
  // Get the FP features status of this operator. Only meaningful for
4011
  // operations on floating point types.
4012
  FPOptions getFPFeaturesInEffect(const LangOptions &LO) const {
4013
    if (BinaryOperatorBits.HasFPFeatures)
4014
      return getStoredFPFeatures().applyOverrides(LO);
4015
    return FPOptions::defaultWithoutTrailingStorage(LO);
4016
  }
4017
 
4018
  // This is used in ASTImporter
4019
  FPOptionsOverride getFPFeatures() const {
4020
    if (BinaryOperatorBits.HasFPFeatures)
4021
      return getStoredFPFeatures();
4022
    return FPOptionsOverride();
4023
  }
4024
 
4025
  // Get the FP contractability status of this operator. Only meaningful for
4026
  // operations on floating point types.
4027
  bool isFPContractableWithinStatement(const LangOptions &LO) const {
4028
    return getFPFeaturesInEffect(LO).allowFPContractWithinStatement();
4029
  }
4030
 
4031
  // Get the FENV_ACCESS status of this operator. Only meaningful for
4032
  // operations on floating point types.
4033
  bool isFEnvAccessOn(const LangOptions &LO) const {
4034
    return getFPFeaturesInEffect(LO).getAllowFEnvAccess();
4035
  }
4036
 
4037
protected:
4038
  BinaryOperator(const ASTContext &Ctx, Expr *lhs, Expr *rhs, Opcode opc,
4039
                 QualType ResTy, ExprValueKind VK, ExprObjectKind OK,
4040
                 SourceLocation opLoc, FPOptionsOverride FPFeatures,
4041
                 bool dead2);
4042
 
4043
  /// Construct an empty BinaryOperator, SC is CompoundAssignOperator.
4044
  BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
4045
    BinaryOperatorBits.Opc = BO_MulAssign;
4046
  }
4047
 
4048
  /// Return the size in bytes needed for the trailing objects.
4049
  /// Used to allocate the right amount of storage.
4050
  static unsigned sizeOfTrailingObjects(bool HasFPFeatures) {
4051
    return HasFPFeatures * sizeof(FPOptionsOverride);
4052
  }
4053
};
4054
 
4055
/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
4056
/// track of the type the operation is performed in.  Due to the semantics of
4057
/// these operators, the operands are promoted, the arithmetic performed, an
4058
/// implicit conversion back to the result type done, then the assignment takes
4059
/// place.  This captures the intermediate type which the computation is done
4060
/// in.
4061
class CompoundAssignOperator : public BinaryOperator {
4062
  QualType ComputationLHSType;
4063
  QualType ComputationResultType;
4064
 
4065
  /// Construct an empty CompoundAssignOperator.
4066
  explicit CompoundAssignOperator(const ASTContext &C, EmptyShell Empty,
4067
                                  bool hasFPFeatures)
4068
      : BinaryOperator(CompoundAssignOperatorClass, Empty) {}
4069
 
4070
protected:
4071
  CompoundAssignOperator(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc,
4072
                         QualType ResType, ExprValueKind VK, ExprObjectKind OK,
4073
                         SourceLocation OpLoc, FPOptionsOverride FPFeatures,
4074
                         QualType CompLHSType, QualType CompResultType)
4075
      : BinaryOperator(C, lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
4076
                       true),
4077
        ComputationLHSType(CompLHSType), ComputationResultType(CompResultType) {
4078
    assert(isCompoundAssignmentOp() &&
4079
           "Only should be used for compound assignments");
4080
  }
4081
 
4082
public:
4083
  static CompoundAssignOperator *CreateEmpty(const ASTContext &C,
4084
                                             bool hasFPFeatures);
4085
 
4086
  static CompoundAssignOperator *
4087
  Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
4088
         ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc,
4089
         FPOptionsOverride FPFeatures, QualType CompLHSType = QualType(),
4090
         QualType CompResultType = QualType());
4091
 
4092
  // The two computation types are the type the LHS is converted
4093
  // to for the computation and the type of the result; the two are
4094
  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
4095
  QualType getComputationLHSType() const { return ComputationLHSType; }
4096
  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
4097
 
4098
  QualType getComputationResultType() const { return ComputationResultType; }
4099
  void setComputationResultType(QualType T) { ComputationResultType = T; }
4100
 
4101
  static bool classof(const Stmt *S) {
4102
    return S->getStmtClass() == CompoundAssignOperatorClass;
4103
  }
4104
};
4105
 
4106
inline size_t BinaryOperator::offsetOfTrailingStorage() const {
4107
  assert(BinaryOperatorBits.HasFPFeatures);
4108
  return isa<CompoundAssignOperator>(this) ? sizeof(CompoundAssignOperator)
4109
                                           : sizeof(BinaryOperator);
4110
}
4111
 
4112
/// AbstractConditionalOperator - An abstract base class for
4113
/// ConditionalOperator and BinaryConditionalOperator.
4114
class AbstractConditionalOperator : public Expr {
4115
  SourceLocation QuestionLoc, ColonLoc;
4116
  friend class ASTStmtReader;
4117
 
4118
protected:
4119
  AbstractConditionalOperator(StmtClass SC, QualType T, ExprValueKind VK,
4120
                              ExprObjectKind OK, SourceLocation qloc,
4121
                              SourceLocation cloc)
4122
      : Expr(SC, T, VK, OK), QuestionLoc(qloc), ColonLoc(cloc) {}
4123
 
4124
  AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
4125
    : Expr(SC, Empty) { }
4126
 
4127
public:
4128
  // getCond - Return the expression representing the condition for
4129
  //   the ?: operator.
4130
  Expr *getCond() const;
4131
 
4132
  // getTrueExpr - Return the subexpression representing the value of
4133
  //   the expression if the condition evaluates to true.
4134
  Expr *getTrueExpr() const;
4135
 
4136
  // getFalseExpr - Return the subexpression representing the value of
4137
  //   the expression if the condition evaluates to false.  This is
4138
  //   the same as getRHS.
4139
  Expr *getFalseExpr() const;
4140
 
4141
  SourceLocation getQuestionLoc() const { return QuestionLoc; }
4142
  SourceLocation getColonLoc() const { return ColonLoc; }
4143
 
4144
  static bool classof(const Stmt *T) {
4145
    return T->getStmtClass() == ConditionalOperatorClass ||
4146
           T->getStmtClass() == BinaryConditionalOperatorClass;
4147
  }
4148
};
4149
 
4150
/// ConditionalOperator - The ?: ternary operator.  The GNU "missing
4151
/// middle" extension is a BinaryConditionalOperator.
4152
class ConditionalOperator : public AbstractConditionalOperator {
4153
  enum { COND, LHS, RHS, END_EXPR };
4154
  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4155
 
4156
  friend class ASTStmtReader;
4157
public:
4158
  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
4159
                      SourceLocation CLoc, Expr *rhs, QualType t,
4160
                      ExprValueKind VK, ExprObjectKind OK)
4161
      : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK, QLoc,
4162
                                    CLoc) {
4163
    SubExprs[COND] = cond;
4164
    SubExprs[LHS] = lhs;
4165
    SubExprs[RHS] = rhs;
4166
    setDependence(computeDependence(this));
4167
  }
4168
 
4169
  /// Build an empty conditional operator.
4170
  explicit ConditionalOperator(EmptyShell Empty)
4171
    : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
4172
 
4173
  // getCond - Return the expression representing the condition for
4174
  //   the ?: operator.
4175
  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4176
 
4177
  // getTrueExpr - Return the subexpression representing the value of
4178
  //   the expression if the condition evaluates to true.
4179
  Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
4180
 
4181
  // getFalseExpr - Return the subexpression representing the value of
4182
  //   the expression if the condition evaluates to false.  This is
4183
  //   the same as getRHS.
4184
  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
4185
 
4186
  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
4187
  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4188
 
4189
  SourceLocation getBeginLoc() const LLVM_READONLY {
4190
    return getCond()->getBeginLoc();
4191
  }
4192
  SourceLocation getEndLoc() const LLVM_READONLY {
4193
    return getRHS()->getEndLoc();
4194
  }
4195
 
4196
  static bool classof(const Stmt *T) {
4197
    return T->getStmtClass() == ConditionalOperatorClass;
4198
  }
4199
 
4200
  // Iterators
4201
  child_range children() {
4202
    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4203
  }
4204
  const_child_range children() const {
4205
    return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4206
  }
4207
};
4208
 
4209
/// BinaryConditionalOperator - The GNU extension to the conditional
4210
/// operator which allows the middle operand to be omitted.
4211
///
4212
/// This is a different expression kind on the assumption that almost
4213
/// every client ends up needing to know that these are different.
4214
class BinaryConditionalOperator : public AbstractConditionalOperator {
4215
  enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
4216
 
4217
  /// - the common condition/left-hand-side expression, which will be
4218
  ///   evaluated as the opaque value
4219
  /// - the condition, expressed in terms of the opaque value
4220
  /// - the left-hand-side, expressed in terms of the opaque value
4221
  /// - the right-hand-side
4222
  Stmt *SubExprs[NUM_SUBEXPRS];
4223
  OpaqueValueExpr *OpaqueValue;
4224
 
4225
  friend class ASTStmtReader;
4226
public:
4227
  BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
4228
                            Expr *cond, Expr *lhs, Expr *rhs,
4229
                            SourceLocation qloc, SourceLocation cloc,
4230
                            QualType t, ExprValueKind VK, ExprObjectKind OK)
4231
      : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
4232
                                    qloc, cloc),
4233
        OpaqueValue(opaqueValue) {
4234
    SubExprs[COMMON] = common;
4235
    SubExprs[COND] = cond;
4236
    SubExprs[LHS] = lhs;
4237
    SubExprs[RHS] = rhs;
4238
    assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
4239
    setDependence(computeDependence(this));
4240
  }
4241
 
4242
  /// Build an empty conditional operator.
4243
  explicit BinaryConditionalOperator(EmptyShell Empty)
4244
    : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
4245
 
4246
  /// getCommon - Return the common expression, written to the
4247
  ///   left of the condition.  The opaque value will be bound to the
4248
  ///   result of this expression.
4249
  Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
4250
 
4251
  /// getOpaqueValue - Return the opaque value placeholder.
4252
  OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
4253
 
4254
  /// getCond - Return the condition expression; this is defined
4255
  ///   in terms of the opaque value.
4256
  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4257
 
4258
  /// getTrueExpr - Return the subexpression which will be
4259
  ///   evaluated if the condition evaluates to true;  this is defined
4260
  ///   in terms of the opaque value.
4261
  Expr *getTrueExpr() const {
4262
    return cast<Expr>(SubExprs[LHS]);
4263
  }
4264
 
4265
  /// getFalseExpr - Return the subexpression which will be
4266
  ///   evaluated if the condnition evaluates to false; this is
4267
  ///   defined in terms of the opaque value.
4268
  Expr *getFalseExpr() const {
4269
    return cast<Expr>(SubExprs[RHS]);
4270
  }
4271
 
4272
  SourceLocation getBeginLoc() const LLVM_READONLY {
4273
    return getCommon()->getBeginLoc();
4274
  }
4275
  SourceLocation getEndLoc() const LLVM_READONLY {
4276
    return getFalseExpr()->getEndLoc();
4277
  }
4278
 
4279
  static bool classof(const Stmt *T) {
4280
    return T->getStmtClass() == BinaryConditionalOperatorClass;
4281
  }
4282
 
4283
  // Iterators
4284
  child_range children() {
4285
    return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4286
  }
4287
  const_child_range children() const {
4288
    return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
4289
  }
4290
};
4291
 
4292
inline Expr *AbstractConditionalOperator::getCond() const {
4293
  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4294
    return co->getCond();
4295
  return cast<BinaryConditionalOperator>(this)->getCond();
4296
}
4297
 
4298
inline Expr *AbstractConditionalOperator::getTrueExpr() const {
4299
  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4300
    return co->getTrueExpr();
4301
  return cast<BinaryConditionalOperator>(this)->getTrueExpr();
4302
}
4303
 
4304
inline Expr *AbstractConditionalOperator::getFalseExpr() const {
4305
  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
4306
    return co->getFalseExpr();
4307
  return cast<BinaryConditionalOperator>(this)->getFalseExpr();
4308
}
4309
 
4310
/// AddrLabelExpr - The GNU address of label extension, representing &&label.
4311
class AddrLabelExpr : public Expr {
4312
  SourceLocation AmpAmpLoc, LabelLoc;
4313
  LabelDecl *Label;
4314
public:
4315
  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
4316
                QualType t)
4317
      : Expr(AddrLabelExprClass, t, VK_PRValue, OK_Ordinary), AmpAmpLoc(AALoc),
4318
        LabelLoc(LLoc), Label(L) {
4319
    setDependence(ExprDependence::None);
4320
  }
4321
 
4322
  /// Build an empty address of a label expression.
4323
  explicit AddrLabelExpr(EmptyShell Empty)
4324
    : Expr(AddrLabelExprClass, Empty) { }
4325
 
4326
  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
4327
  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
4328
  SourceLocation getLabelLoc() const { return LabelLoc; }
4329
  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
4330
 
4331
  SourceLocation getBeginLoc() const LLVM_READONLY { return AmpAmpLoc; }
4332
  SourceLocation getEndLoc() const LLVM_READONLY { return LabelLoc; }
4333
 
4334
  LabelDecl *getLabel() const { return Label; }
4335
  void setLabel(LabelDecl *L) { Label = L; }
4336
 
4337
  static bool classof(const Stmt *T) {
4338
    return T->getStmtClass() == AddrLabelExprClass;
4339
  }
4340
 
4341
  // Iterators
4342
  child_range children() {
4343
    return child_range(child_iterator(), child_iterator());
4344
  }
4345
  const_child_range children() const {
4346
    return const_child_range(const_child_iterator(), const_child_iterator());
4347
  }
4348
};
4349
 
4350
/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
4351
/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
4352
/// takes the value of the last subexpression.
4353
///
4354
/// A StmtExpr is always an r-value; values "returned" out of a
4355
/// StmtExpr will be copied.
4356
class StmtExpr : public Expr {
4357
  Stmt *SubStmt;
4358
  SourceLocation LParenLoc, RParenLoc;
4359
public:
4360
  StmtExpr(CompoundStmt *SubStmt, QualType T, SourceLocation LParenLoc,
4361
           SourceLocation RParenLoc, unsigned TemplateDepth)
4362
      : Expr(StmtExprClass, T, VK_PRValue, OK_Ordinary), SubStmt(SubStmt),
4363
        LParenLoc(LParenLoc), RParenLoc(RParenLoc) {
4364
    setDependence(computeDependence(this, TemplateDepth));
4365
    // FIXME: A templated statement expression should have an associated
4366
    // DeclContext so that nested declarations always have a dependent context.
4367
    StmtExprBits.TemplateDepth = TemplateDepth;
4368
  }
4369
 
4370
  /// Build an empty statement expression.
4371
  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
4372
 
4373
  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
4374
  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
4375
  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
4376
 
4377
  SourceLocation getBeginLoc() const LLVM_READONLY { return LParenLoc; }
4378
  SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4379
 
4380
  SourceLocation getLParenLoc() const { return LParenLoc; }
4381
  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
4382
  SourceLocation getRParenLoc() const { return RParenLoc; }
4383
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4384
 
4385
  unsigned getTemplateDepth() const { return StmtExprBits.TemplateDepth; }
4386
 
4387
  static bool classof(const Stmt *T) {
4388
    return T->getStmtClass() == StmtExprClass;
4389
  }
4390
 
4391
  // Iterators
4392
  child_range children() { return child_range(&SubStmt, &SubStmt+1); }
4393
  const_child_range children() const {
4394
    return const_child_range(&SubStmt, &SubStmt + 1);
4395
  }
4396
};
4397
 
4398
/// ShuffleVectorExpr - clang-specific builtin-in function
4399
/// __builtin_shufflevector.
4400
/// This AST node represents a operator that does a constant
4401
/// shuffle, similar to LLVM's shufflevector instruction. It takes
4402
/// two vectors and a variable number of constant indices,
4403
/// and returns the appropriately shuffled vector.
4404
class ShuffleVectorExpr : public Expr {
4405
  SourceLocation BuiltinLoc, RParenLoc;
4406
 
4407
  // SubExprs - the list of values passed to the __builtin_shufflevector
4408
  // function. The first two are vectors, and the rest are constant
4409
  // indices.  The number of values in this list is always
4410
  // 2+the number of indices in the vector type.
4411
  Stmt **SubExprs;
4412
  unsigned NumExprs;
4413
 
4414
public:
4415
  ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
4416
                    SourceLocation BLoc, SourceLocation RP);
4417
 
4418
  /// Build an empty vector-shuffle expression.
4419
  explicit ShuffleVectorExpr(EmptyShell Empty)
4420
    : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
4421
 
4422
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4423
  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4424
 
4425
  SourceLocation getRParenLoc() const { return RParenLoc; }
4426
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4427
 
4428
  SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4429
  SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4430
 
4431
  static bool classof(const Stmt *T) {
4432
    return T->getStmtClass() == ShuffleVectorExprClass;
4433
  }
4434
 
4435
  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
4436
  /// constant expression, the actual arguments passed in, and the function
4437
  /// pointers.
4438
  unsigned getNumSubExprs() const { return NumExprs; }
4439
 
4440
  /// Retrieve the array of expressions.
4441
  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
4442
 
4443
  /// getExpr - Return the Expr at the specified index.
4444
  Expr *getExpr(unsigned Index) {
4445
    assert((Index < NumExprs) && "Arg access out of range!");
4446
    return cast<Expr>(SubExprs[Index]);
4447
  }
4448
  const Expr *getExpr(unsigned Index) const {
4449
    assert((Index < NumExprs) && "Arg access out of range!");
4450
    return cast<Expr>(SubExprs[Index]);
4451
  }
4452
 
4453
  void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
4454
 
4455
  llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
4456
    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
4457
    return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
4458
  }
4459
 
4460
  // Iterators
4461
  child_range children() {
4462
    return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
4463
  }
4464
  const_child_range children() const {
4465
    return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
4466
  }
4467
};
4468
 
4469
/// ConvertVectorExpr - Clang builtin function __builtin_convertvector
4470
/// This AST node provides support for converting a vector type to another
4471
/// vector type of the same arity.
4472
class ConvertVectorExpr : public Expr {
4473
private:
4474
  Stmt *SrcExpr;
4475
  TypeSourceInfo *TInfo;
4476
  SourceLocation BuiltinLoc, RParenLoc;
4477
 
4478
  friend class ASTReader;
4479
  friend class ASTStmtReader;
4480
  explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
4481
 
4482
public:
4483
  ConvertVectorExpr(Expr *SrcExpr, TypeSourceInfo *TI, QualType DstType,
4484
                    ExprValueKind VK, ExprObjectKind OK,
4485
                    SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4486
      : Expr(ConvertVectorExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
4487
        TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
4488
    setDependence(computeDependence(this));
4489
  }
4490
 
4491
  /// getSrcExpr - Return the Expr to be converted.
4492
  Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
4493
 
4494
  /// getTypeSourceInfo - Return the destination type.
4495
  TypeSourceInfo *getTypeSourceInfo() const {
4496
    return TInfo;
4497
  }
4498
  void setTypeSourceInfo(TypeSourceInfo *ti) {
4499
    TInfo = ti;
4500
  }
4501
 
4502
  /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
4503
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4504
 
4505
  /// getRParenLoc - Return the location of final right parenthesis.
4506
  SourceLocation getRParenLoc() const { return RParenLoc; }
4507
 
4508
  SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4509
  SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4510
 
4511
  static bool classof(const Stmt *T) {
4512
    return T->getStmtClass() == ConvertVectorExprClass;
4513
  }
4514
 
4515
  // Iterators
4516
  child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
4517
  const_child_range children() const {
4518
    return const_child_range(&SrcExpr, &SrcExpr + 1);
4519
  }
4520
};
4521
 
4522
/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
4523
/// This AST node is similar to the conditional operator (?:) in C, with
4524
/// the following exceptions:
4525
/// - the test expression must be a integer constant expression.
4526
/// - the expression returned acts like the chosen subexpression in every
4527
///   visible way: the type is the same as that of the chosen subexpression,
4528
///   and all predicates (whether it's an l-value, whether it's an integer
4529
///   constant expression, etc.) return the same result as for the chosen
4530
///   sub-expression.
4531
class ChooseExpr : public Expr {
4532
  enum { COND, LHS, RHS, END_EXPR };
4533
  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
4534
  SourceLocation BuiltinLoc, RParenLoc;
4535
  bool CondIsTrue;
4536
public:
4537
  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs, QualType t,
4538
             ExprValueKind VK, ExprObjectKind OK, SourceLocation RP,
4539
             bool condIsTrue)
4540
      : Expr(ChooseExprClass, t, VK, OK), BuiltinLoc(BLoc), RParenLoc(RP),
4541
        CondIsTrue(condIsTrue) {
4542
    SubExprs[COND] = cond;
4543
    SubExprs[LHS] = lhs;
4544
    SubExprs[RHS] = rhs;
4545
 
4546
    setDependence(computeDependence(this));
4547
  }
4548
 
4549
  /// Build an empty __builtin_choose_expr.
4550
  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
4551
 
4552
  /// isConditionTrue - Return whether the condition is true (i.e. not
4553
  /// equal to zero).
4554
  bool isConditionTrue() const {
4555
    assert(!isConditionDependent() &&
4556
           "Dependent condition isn't true or false");
4557
    return CondIsTrue;
4558
  }
4559
  void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
4560
 
4561
  bool isConditionDependent() const {
4562
    return getCond()->isTypeDependent() || getCond()->isValueDependent();
4563
  }
4564
 
4565
  /// getChosenSubExpr - Return the subexpression chosen according to the
4566
  /// condition.
4567
  Expr *getChosenSubExpr() const {
4568
    return isConditionTrue() ? getLHS() : getRHS();
4569
  }
4570
 
4571
  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
4572
  void setCond(Expr *E) { SubExprs[COND] = E; }
4573
  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
4574
  void setLHS(Expr *E) { SubExprs[LHS] = E; }
4575
  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
4576
  void setRHS(Expr *E) { SubExprs[RHS] = E; }
4577
 
4578
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4579
  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4580
 
4581
  SourceLocation getRParenLoc() const { return RParenLoc; }
4582
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4583
 
4584
  SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4585
  SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4586
 
4587
  static bool classof(const Stmt *T) {
4588
    return T->getStmtClass() == ChooseExprClass;
4589
  }
4590
 
4591
  // Iterators
4592
  child_range children() {
4593
    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
4594
  }
4595
  const_child_range children() const {
4596
    return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
4597
  }
4598
};
4599
 
4600
/// GNUNullExpr - Implements the GNU __null extension, which is a name
4601
/// for a null pointer constant that has integral type (e.g., int or
4602
/// long) and is the same size and alignment as a pointer. The __null
4603
/// extension is typically only used by system headers, which define
4604
/// NULL as __null in C++ rather than using 0 (which is an integer
4605
/// that may not match the size of a pointer).
4606
class GNUNullExpr : public Expr {
4607
  /// TokenLoc - The location of the __null keyword.
4608
  SourceLocation TokenLoc;
4609
 
4610
public:
4611
  GNUNullExpr(QualType Ty, SourceLocation Loc)
4612
      : Expr(GNUNullExprClass, Ty, VK_PRValue, OK_Ordinary), TokenLoc(Loc) {
4613
    setDependence(ExprDependence::None);
4614
  }
4615
 
4616
  /// Build an empty GNU __null expression.
4617
  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
4618
 
4619
  /// getTokenLocation - The location of the __null token.
4620
  SourceLocation getTokenLocation() const { return TokenLoc; }
4621
  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
4622
 
4623
  SourceLocation getBeginLoc() const LLVM_READONLY { return TokenLoc; }
4624
  SourceLocation getEndLoc() const LLVM_READONLY { return TokenLoc; }
4625
 
4626
  static bool classof(const Stmt *T) {
4627
    return T->getStmtClass() == GNUNullExprClass;
4628
  }
4629
 
4630
  // Iterators
4631
  child_range children() {
4632
    return child_range(child_iterator(), child_iterator());
4633
  }
4634
  const_child_range children() const {
4635
    return const_child_range(const_child_iterator(), const_child_iterator());
4636
  }
4637
};
4638
 
4639
/// Represents a call to the builtin function \c __builtin_va_arg.
4640
class VAArgExpr : public Expr {
4641
  Stmt *Val;
4642
  llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
4643
  SourceLocation BuiltinLoc, RParenLoc;
4644
public:
4645
  VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
4646
            SourceLocation RPLoc, QualType t, bool IsMS)
4647
      : Expr(VAArgExprClass, t, VK_PRValue, OK_Ordinary), Val(e),
4648
        TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {
4649
    setDependence(computeDependence(this));
4650
  }
4651
 
4652
  /// Create an empty __builtin_va_arg expression.
4653
  explicit VAArgExpr(EmptyShell Empty)
4654
      : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
4655
 
4656
  const Expr *getSubExpr() const { return cast<Expr>(Val); }
4657
  Expr *getSubExpr() { return cast<Expr>(Val); }
4658
  void setSubExpr(Expr *E) { Val = E; }
4659
 
4660
  /// Returns whether this is really a Win64 ABI va_arg expression.
4661
  bool isMicrosoftABI() const { return TInfo.getInt(); }
4662
  void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
4663
 
4664
  TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
4665
  void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
4666
 
4667
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
4668
  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
4669
 
4670
  SourceLocation getRParenLoc() const { return RParenLoc; }
4671
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
4672
 
4673
  SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
4674
  SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
4675
 
4676
  static bool classof(const Stmt *T) {
4677
    return T->getStmtClass() == VAArgExprClass;
4678
  }
4679
 
4680
  // Iterators
4681
  child_range children() { return child_range(&Val, &Val+1); }
4682
  const_child_range children() const {
4683
    return const_child_range(&Val, &Val + 1);
4684
  }
4685
};
4686
 
4687
/// Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(),
4688
/// __builtin_FUNCTION(), __builtin_FILE(), or __builtin_source_location().
4689
class SourceLocExpr final : public Expr {
4690
  SourceLocation BuiltinLoc, RParenLoc;
4691
  DeclContext *ParentContext;
4692
 
4693
public:
4694
  enum IdentKind { Function, File, Line, Column, SourceLocStruct };
4695
 
4696
  SourceLocExpr(const ASTContext &Ctx, IdentKind Type, QualType ResultTy,
4697
                SourceLocation BLoc, SourceLocation RParenLoc,
4698
                DeclContext *Context);
4699
 
4700
  /// Build an empty call expression.
4701
  explicit SourceLocExpr(EmptyShell Empty) : Expr(SourceLocExprClass, Empty) {}
4702
 
4703
  /// Return the result of evaluating this SourceLocExpr in the specified
4704
  /// (and possibly null) default argument or initialization context.
4705
  APValue EvaluateInContext(const ASTContext &Ctx,
4706
                            const Expr *DefaultExpr) const;
4707
 
4708
  /// Return a string representing the name of the specific builtin function.
4709
  StringRef getBuiltinStr() const;
4710
 
4711
  IdentKind getIdentKind() const {
4712
    return static_cast<IdentKind>(SourceLocExprBits.Kind);
4713
  }
4714
 
4715
  bool isIntType() const {
4716
    switch (getIdentKind()) {
4717
    case File:
4718
    case Function:
4719
    case SourceLocStruct:
4720
      return false;
4721
    case Line:
4722
    case Column:
4723
      return true;
4724
    }
4725
    llvm_unreachable("unknown source location expression kind");
4726
  }
4727
 
4728
  /// If the SourceLocExpr has been resolved return the subexpression
4729
  /// representing the resolved value. Otherwise return null.
4730
  const DeclContext *getParentContext() const { return ParentContext; }
4731
  DeclContext *getParentContext() { return ParentContext; }
4732
 
4733
  SourceLocation getLocation() const { return BuiltinLoc; }
4734
  SourceLocation getBeginLoc() const { return BuiltinLoc; }
4735
  SourceLocation getEndLoc() const { return RParenLoc; }
4736
 
4737
  child_range children() {
4738
    return child_range(child_iterator(), child_iterator());
4739
  }
4740
 
4741
  const_child_range children() const {
4742
    return const_child_range(child_iterator(), child_iterator());
4743
  }
4744
 
4745
  static bool classof(const Stmt *T) {
4746
    return T->getStmtClass() == SourceLocExprClass;
4747
  }
4748
 
4749
private:
4750
  friend class ASTStmtReader;
4751
};
4752
 
4753
/// Describes an C or C++ initializer list.
4754
///
4755
/// InitListExpr describes an initializer list, which can be used to
4756
/// initialize objects of different types, including
4757
/// struct/class/union types, arrays, and vectors. For example:
4758
///
4759
/// @code
4760
/// struct foo x = { 1, { 2, 3 } };
4761
/// @endcode
4762
///
4763
/// Prior to semantic analysis, an initializer list will represent the
4764
/// initializer list as written by the user, but will have the
4765
/// placeholder type "void". This initializer list is called the
4766
/// syntactic form of the initializer, and may contain C99 designated
4767
/// initializers (represented as DesignatedInitExprs), initializations
4768
/// of subobject members without explicit braces, and so on. Clients
4769
/// interested in the original syntax of the initializer list should
4770
/// use the syntactic form of the initializer list.
4771
///
4772
/// After semantic analysis, the initializer list will represent the
4773
/// semantic form of the initializer, where the initializations of all
4774
/// subobjects are made explicit with nested InitListExpr nodes and
4775
/// C99 designators have been eliminated by placing the designated
4776
/// initializations into the subobject they initialize. Additionally,
4777
/// any "holes" in the initialization, where no initializer has been
4778
/// specified for a particular subobject, will be replaced with
4779
/// implicitly-generated ImplicitValueInitExpr expressions that
4780
/// value-initialize the subobjects. Note, however, that the
4781
/// initializer lists may still have fewer initializers than there are
4782
/// elements to initialize within the object.
4783
///
4784
/// After semantic analysis has completed, given an initializer list,
4785
/// method isSemanticForm() returns true if and only if this is the
4786
/// semantic form of the initializer list (note: the same AST node
4787
/// may at the same time be the syntactic form).
4788
/// Given the semantic form of the initializer list, one can retrieve
4789
/// the syntactic form of that initializer list (when different)
4790
/// using method getSyntacticForm(); the method returns null if applied
4791
/// to a initializer list which is already in syntactic form.
4792
/// Similarly, given the syntactic form (i.e., an initializer list such
4793
/// that isSemanticForm() returns false), one can retrieve the semantic
4794
/// form using method getSemanticForm().
4795
/// Since many initializer lists have the same syntactic and semantic forms,
4796
/// getSyntacticForm() may return NULL, indicating that the current
4797
/// semantic initializer list also serves as its syntactic form.
4798
class InitListExpr : public Expr {
4799
  // FIXME: Eliminate this vector in favor of ASTContext allocation
4800
  typedef ASTVector<Stmt *> InitExprsTy;
4801
  InitExprsTy InitExprs;
4802
  SourceLocation LBraceLoc, RBraceLoc;
4803
 
4804
  /// The alternative form of the initializer list (if it exists).
4805
  /// The int part of the pair stores whether this initializer list is
4806
  /// in semantic form. If not null, the pointer points to:
4807
  ///   - the syntactic form, if this is in semantic form;
4808
  ///   - the semantic form, if this is in syntactic form.
4809
  llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
4810
 
4811
  /// Either:
4812
  ///  If this initializer list initializes an array with more elements than
4813
  ///  there are initializers in the list, specifies an expression to be used
4814
  ///  for value initialization of the rest of the elements.
4815
  /// Or
4816
  ///  If this initializer list initializes a union, specifies which
4817
  ///  field within the union will be initialized.
4818
  llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
4819
 
4820
public:
4821
  InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
4822
               ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
4823
 
4824
  /// Build an empty initializer list.
4825
  explicit InitListExpr(EmptyShell Empty)
4826
    : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
4827
 
4828
  unsigned getNumInits() const { return InitExprs.size(); }
4829
 
4830
  /// Retrieve the set of initializers.
4831
  Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
4832
 
4833
  /// Retrieve the set of initializers.
4834
  Expr * const *getInits() const {
4835
    return reinterpret_cast<Expr * const *>(InitExprs.data());
4836
  }
4837
 
4838
  ArrayRef<Expr *> inits() { return llvm::ArrayRef(getInits(), getNumInits()); }
4839
 
4840
  ArrayRef<Expr *> inits() const {
4841
    return llvm::ArrayRef(getInits(), getNumInits());
4842
  }
4843
 
4844
  const Expr *getInit(unsigned Init) const {
4845
    assert(Init < getNumInits() && "Initializer access out of range!");
4846
    return cast_or_null<Expr>(InitExprs[Init]);
4847
  }
4848
 
4849
  Expr *getInit(unsigned Init) {
4850
    assert(Init < getNumInits() && "Initializer access out of range!");
4851
    return cast_or_null<Expr>(InitExprs[Init]);
4852
  }
4853
 
4854
  void setInit(unsigned Init, Expr *expr) {
4855
    assert(Init < getNumInits() && "Initializer access out of range!");
4856
    InitExprs[Init] = expr;
4857
 
4858
    if (expr)
4859
      setDependence(getDependence() | expr->getDependence());
4860
  }
4861
 
4862
  /// Mark the semantic form of the InitListExpr as error when the semantic
4863
  /// analysis fails.
4864
  void markError() {
4865
    assert(isSemanticForm());
4866
    setDependence(getDependence() | ExprDependence::ErrorDependent);
4867
  }
4868
 
4869
  /// Reserve space for some number of initializers.
4870
  void reserveInits(const ASTContext &C, unsigned NumInits);
4871
 
4872
  /// Specify the number of initializers
4873
  ///
4874
  /// If there are more than @p NumInits initializers, the remaining
4875
  /// initializers will be destroyed. If there are fewer than @p
4876
  /// NumInits initializers, NULL expressions will be added for the
4877
  /// unknown initializers.
4878
  void resizeInits(const ASTContext &Context, unsigned NumInits);
4879
 
4880
  /// Updates the initializer at index @p Init with the new
4881
  /// expression @p expr, and returns the old expression at that
4882
  /// location.
4883
  ///
4884
  /// When @p Init is out of range for this initializer list, the
4885
  /// initializer list will be extended with NULL expressions to
4886
  /// accommodate the new entry.
4887
  Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
4888
 
4889
  /// If this initializer list initializes an array with more elements
4890
  /// than there are initializers in the list, specifies an expression to be
4891
  /// used for value initialization of the rest of the elements.
4892
  Expr *getArrayFiller() {
4893
    return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
4894
  }
4895
  const Expr *getArrayFiller() const {
4896
    return const_cast<InitListExpr *>(this)->getArrayFiller();
4897
  }
4898
  void setArrayFiller(Expr *filler);
4899
 
4900
  /// Return true if this is an array initializer and its array "filler"
4901
  /// has been set.
4902
  bool hasArrayFiller() const { return getArrayFiller(); }
4903
 
4904
  /// If this initializes a union, specifies which field in the
4905
  /// union to initialize.
4906
  ///
4907
  /// Typically, this field is the first named field within the
4908
  /// union. However, a designated initializer can specify the
4909
  /// initialization of a different field within the union.
4910
  FieldDecl *getInitializedFieldInUnion() {
4911
    return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
4912
  }
4913
  const FieldDecl *getInitializedFieldInUnion() const {
4914
    return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
4915
  }
4916
  void setInitializedFieldInUnion(FieldDecl *FD) {
4917
    assert((FD == nullptr
4918
            || getInitializedFieldInUnion() == nullptr
4919
            || getInitializedFieldInUnion() == FD)
4920
           && "Only one field of a union may be initialized at a time!");
4921
    ArrayFillerOrUnionFieldInit = FD;
4922
  }
4923
 
4924
  // Explicit InitListExpr's originate from source code (and have valid source
4925
  // locations). Implicit InitListExpr's are created by the semantic analyzer.
4926
  // FIXME: This is wrong; InitListExprs created by semantic analysis have
4927
  // valid source locations too!
4928
  bool isExplicit() const {
4929
    return LBraceLoc.isValid() && RBraceLoc.isValid();
4930
  }
4931
 
4932
  // Is this an initializer for an array of characters, initialized by a string
4933
  // literal or an @encode?
4934
  bool isStringLiteralInit() const;
4935
 
4936
  /// Is this a transparent initializer list (that is, an InitListExpr that is
4937
  /// purely syntactic, and whose semantics are that of the sole contained
4938
  /// initializer)?
4939
  bool isTransparent() const;
4940
 
4941
  /// Is this the zero initializer {0} in a language which considers it
4942
  /// idiomatic?
4943
  bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4944
 
4945
  SourceLocation getLBraceLoc() const { return LBraceLoc; }
4946
  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
4947
  SourceLocation getRBraceLoc() const { return RBraceLoc; }
4948
  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4949
 
4950
  bool isSemanticForm() const { return AltForm.getInt(); }
4951
  InitListExpr *getSemanticForm() const {
4952
    return isSemanticForm() ? nullptr : AltForm.getPointer();
4953
  }
4954
  bool isSyntacticForm() const {
4955
    return !AltForm.getInt() || !AltForm.getPointer();
4956
  }
4957
  InitListExpr *getSyntacticForm() const {
4958
    return isSemanticForm() ? AltForm.getPointer() : nullptr;
4959
  }
4960
 
4961
  void setSyntacticForm(InitListExpr *Init) {
4962
    AltForm.setPointer(Init);
4963
    AltForm.setInt(true);
4964
    Init->AltForm.setPointer(this);
4965
    Init->AltForm.setInt(false);
4966
  }
4967
 
4968
  bool hadArrayRangeDesignator() const {
4969
    return InitListExprBits.HadArrayRangeDesignator != 0;
4970
  }
4971
  void sawArrayRangeDesignator(bool ARD = true) {
4972
    InitListExprBits.HadArrayRangeDesignator = ARD;
4973
  }
4974
 
4975
  SourceLocation getBeginLoc() const LLVM_READONLY;
4976
  SourceLocation getEndLoc() const LLVM_READONLY;
4977
 
4978
  static bool classof(const Stmt *T) {
4979
    return T->getStmtClass() == InitListExprClass;
4980
  }
4981
 
4982
  // Iterators
4983
  child_range children() {
4984
    const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
4985
    return child_range(cast_away_const(CCR.begin()),
4986
                       cast_away_const(CCR.end()));
4987
  }
4988
 
4989
  const_child_range children() const {
4990
    // FIXME: This does not include the array filler expression.
4991
    if (InitExprs.empty())
4992
      return const_child_range(const_child_iterator(), const_child_iterator());
4993
    return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
4994
  }
4995
 
4996
  typedef InitExprsTy::iterator iterator;
4997
  typedef InitExprsTy::const_iterator const_iterator;
4998
  typedef InitExprsTy::reverse_iterator reverse_iterator;
4999
  typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
5000
 
5001
  iterator begin() { return InitExprs.begin(); }
5002
  const_iterator begin() const { return InitExprs.begin(); }
5003
  iterator end() { return InitExprs.end(); }
5004
  const_iterator end() const { return InitExprs.end(); }
5005
  reverse_iterator rbegin() { return InitExprs.rbegin(); }
5006
  const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
5007
  reverse_iterator rend() { return InitExprs.rend(); }
5008
  const_reverse_iterator rend() const { return InitExprs.rend(); }
5009
 
5010
  friend class ASTStmtReader;
5011
  friend class ASTStmtWriter;
5012
};
5013
 
5014
/// Represents a C99 designated initializer expression.
5015
///
5016
/// A designated initializer expression (C99 6.7.8) contains one or
5017
/// more designators (which can be field designators, array
5018
/// designators, or GNU array-range designators) followed by an
5019
/// expression that initializes the field or element(s) that the
5020
/// designators refer to. For example, given:
5021
///
5022
/// @code
5023
/// struct point {
5024
///   double x;
5025
///   double y;
5026
/// };
5027
/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
5028
/// @endcode
5029
///
5030
/// The InitListExpr contains three DesignatedInitExprs, the first of
5031
/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
5032
/// designators, one array designator for @c [2] followed by one field
5033
/// designator for @c .y. The initialization expression will be 1.0.
5034
class DesignatedInitExpr final
5035
    : public Expr,
5036
      private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
5037
public:
5038
  /// Forward declaration of the Designator class.
5039
  class Designator;
5040
 
5041
private:
5042
  /// The location of the '=' or ':' prior to the actual initializer
5043
  /// expression.
5044
  SourceLocation EqualOrColonLoc;
5045
 
5046
  /// Whether this designated initializer used the GNU deprecated
5047
  /// syntax rather than the C99 '=' syntax.
5048
  unsigned GNUSyntax : 1;
5049
 
5050
  /// The number of designators in this initializer expression.
5051
  unsigned NumDesignators : 15;
5052
 
5053
  /// The number of subexpressions of this initializer expression,
5054
  /// which contains both the initializer and any additional
5055
  /// expressions used by array and array-range designators.
5056
  unsigned NumSubExprs : 16;
5057
 
5058
  /// The designators in this designated initialization
5059
  /// expression.
5060
  Designator *Designators;
5061
 
5062
  DesignatedInitExpr(const ASTContext &C, QualType Ty,
5063
                     llvm::ArrayRef<Designator> Designators,
5064
                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
5065
                     ArrayRef<Expr *> IndexExprs, Expr *Init);
5066
 
5067
  explicit DesignatedInitExpr(unsigned NumSubExprs)
5068
    : Expr(DesignatedInitExprClass, EmptyShell()),
5069
      NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
5070
 
5071
public:
5072
  /// A field designator, e.g., ".x".
5073
  struct FieldDesignator {
5074
    /// Refers to the field that is being initialized. The low bit
5075
    /// of this field determines whether this is actually a pointer
5076
    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
5077
    /// initially constructed, a field designator will store an
5078
    /// IdentifierInfo*. After semantic analysis has resolved that
5079
    /// name, the field designator will instead store a FieldDecl*.
5080
    uintptr_t NameOrField;
5081
 
5082
    /// The location of the '.' in the designated initializer.
5083
    SourceLocation DotLoc;
5084
 
5085
    /// The location of the field name in the designated initializer.
5086
    SourceLocation FieldLoc;
5087
  };
5088
 
5089
  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
5090
  struct ArrayOrRangeDesignator {
5091
    /// Location of the first index expression within the designated
5092
    /// initializer expression's list of subexpressions.
5093
    unsigned Index;
5094
    /// The location of the '[' starting the array range designator.
5095
    SourceLocation LBracketLoc;
5096
    /// The location of the ellipsis separating the start and end
5097
    /// indices. Only valid for GNU array-range designators.
5098
    SourceLocation EllipsisLoc;
5099
    /// The location of the ']' terminating the array range designator.
5100
    SourceLocation RBracketLoc;
5101
  };
5102
 
5103
  /// Represents a single C99 designator.
5104
  ///
5105
  /// @todo This class is infuriatingly similar to clang::Designator,
5106
  /// but minor differences (storing indices vs. storing pointers)
5107
  /// keep us from reusing it. Try harder, later, to rectify these
5108
  /// differences.
5109
  class Designator {
5110
    /// The kind of designator this describes.
5111
    enum {
5112
      FieldDesignator,
5113
      ArrayDesignator,
5114
      ArrayRangeDesignator
5115
    } Kind;
5116
 
5117
    union {
5118
      /// A field designator, e.g., ".x".
5119
      struct FieldDesignator Field;
5120
      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
5121
      struct ArrayOrRangeDesignator ArrayOrRange;
5122
    };
5123
    friend class DesignatedInitExpr;
5124
 
5125
  public:
5126
    Designator() {}
5127
 
5128
    /// Initializes a field designator.
5129
    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
5130
               SourceLocation FieldLoc)
5131
      : Kind(FieldDesignator) {
5132
      new (&Field) DesignatedInitExpr::FieldDesignator;
5133
      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
5134
      Field.DotLoc = DotLoc;
5135
      Field.FieldLoc = FieldLoc;
5136
    }
5137
 
5138
    /// Initializes an array designator.
5139
    Designator(unsigned Index, SourceLocation LBracketLoc,
5140
               SourceLocation RBracketLoc)
5141
      : Kind(ArrayDesignator) {
5142
      new (&ArrayOrRange) DesignatedInitExpr::ArrayOrRangeDesignator;
5143
      ArrayOrRange.Index = Index;
5144
      ArrayOrRange.LBracketLoc = LBracketLoc;
5145
      ArrayOrRange.EllipsisLoc = SourceLocation();
5146
      ArrayOrRange.RBracketLoc = RBracketLoc;
5147
    }
5148
 
5149
    /// Initializes a GNU array-range designator.
5150
    Designator(unsigned Index, SourceLocation LBracketLoc,
5151
               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
5152
      : Kind(ArrayRangeDesignator) {
5153
      new (&ArrayOrRange) DesignatedInitExpr::ArrayOrRangeDesignator;
5154
      ArrayOrRange.Index = Index;
5155
      ArrayOrRange.LBracketLoc = LBracketLoc;
5156
      ArrayOrRange.EllipsisLoc = EllipsisLoc;
5157
      ArrayOrRange.RBracketLoc = RBracketLoc;
5158
    }
5159
 
5160
    bool isFieldDesignator() const { return Kind == FieldDesignator; }
5161
    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
5162
    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
5163
 
5164
    IdentifierInfo *getFieldName() const;
5165
 
5166
    FieldDecl *getField() const {
5167
      assert(Kind == FieldDesignator && "Only valid on a field designator");
5168
      if (Field.NameOrField & 0x01)
5169
        return nullptr;
5170
      else
5171
        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
5172
    }
5173
 
5174
    void setField(FieldDecl *FD) {
5175
      assert(Kind == FieldDesignator && "Only valid on a field designator");
5176
      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
5177
    }
5178
 
5179
    SourceLocation getDotLoc() const {
5180
      assert(Kind == FieldDesignator && "Only valid on a field designator");
5181
      return Field.DotLoc;
5182
    }
5183
 
5184
    SourceLocation getFieldLoc() const {
5185
      assert(Kind == FieldDesignator && "Only valid on a field designator");
5186
      return Field.FieldLoc;
5187
    }
5188
 
5189
    SourceLocation getLBracketLoc() const {
5190
      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
5191
             "Only valid on an array or array-range designator");
5192
      return ArrayOrRange.LBracketLoc;
5193
    }
5194
 
5195
    SourceLocation getRBracketLoc() const {
5196
      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
5197
             "Only valid on an array or array-range designator");
5198
      return ArrayOrRange.RBracketLoc;
5199
    }
5200
 
5201
    SourceLocation getEllipsisLoc() const {
5202
      assert(Kind == ArrayRangeDesignator &&
5203
             "Only valid on an array-range designator");
5204
      return ArrayOrRange.EllipsisLoc;
5205
    }
5206
 
5207
    unsigned getFirstExprIndex() const {
5208
      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
5209
             "Only valid on an array or array-range designator");
5210
      return ArrayOrRange.Index;
5211
    }
5212
 
5213
    SourceLocation getBeginLoc() const LLVM_READONLY {
5214
      if (Kind == FieldDesignator)
5215
        return getDotLoc().isInvalid()? getFieldLoc() : getDotLoc();
5216
      else
5217
        return getLBracketLoc();
5218
    }
5219
    SourceLocation getEndLoc() const LLVM_READONLY {
5220
      return Kind == FieldDesignator ? getFieldLoc() : getRBracketLoc();
5221
    }
5222
    SourceRange getSourceRange() const LLVM_READONLY {
5223
      return SourceRange(getBeginLoc(), getEndLoc());
5224
    }
5225
  };
5226
 
5227
  static DesignatedInitExpr *Create(const ASTContext &C,
5228
                                    llvm::ArrayRef<Designator> Designators,
5229
                                    ArrayRef<Expr*> IndexExprs,
5230
                                    SourceLocation EqualOrColonLoc,
5231
                                    bool GNUSyntax, Expr *Init);
5232
 
5233
  static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
5234
                                         unsigned NumIndexExprs);
5235
 
5236
  /// Returns the number of designators in this initializer.
5237
  unsigned size() const { return NumDesignators; }
5238
 
5239
  // Iterator access to the designators.
5240
  llvm::MutableArrayRef<Designator> designators() {
5241
    return {Designators, NumDesignators};
5242
  }
5243
 
5244
  llvm::ArrayRef<Designator> designators() const {
5245
    return {Designators, NumDesignators};
5246
  }
5247
 
5248
  Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
5249
  const Designator *getDesignator(unsigned Idx) const {
5250
    return &designators()[Idx];
5251
  }
5252
 
5253
  void setDesignators(const ASTContext &C, const Designator *Desigs,
5254
                      unsigned NumDesigs);
5255
 
5256
  Expr *getArrayIndex(const Designator &D) const;
5257
  Expr *getArrayRangeStart(const Designator &D) const;
5258
  Expr *getArrayRangeEnd(const Designator &D) const;
5259
 
5260
  /// Retrieve the location of the '=' that precedes the
5261
  /// initializer value itself, if present.
5262
  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
5263
  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
5264
 
5265
  /// Whether this designated initializer should result in direct-initialization
5266
  /// of the designated subobject (eg, '{.foo{1, 2, 3}}').
5267
  bool isDirectInit() const { return EqualOrColonLoc.isInvalid(); }
5268
 
5269
  /// Determines whether this designated initializer used the
5270
  /// deprecated GNU syntax for designated initializers.
5271
  bool usesGNUSyntax() const { return GNUSyntax; }
5272
  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
5273
 
5274
  /// Retrieve the initializer value.
5275
  Expr *getInit() const {
5276
    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
5277
  }
5278
 
5279
  void setInit(Expr *init) {
5280
    *child_begin() = init;
5281
  }
5282
 
5283
  /// Retrieve the total number of subexpressions in this
5284
  /// designated initializer expression, including the actual
5285
  /// initialized value and any expressions that occur within array
5286
  /// and array-range designators.
5287
  unsigned getNumSubExprs() const { return NumSubExprs; }
5288
 
5289
  Expr *getSubExpr(unsigned Idx) const {
5290
    assert(Idx < NumSubExprs && "Subscript out of range");
5291
    return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
5292
  }
5293
 
5294
  void setSubExpr(unsigned Idx, Expr *E) {
5295
    assert(Idx < NumSubExprs && "Subscript out of range");
5296
    getTrailingObjects<Stmt *>()[Idx] = E;
5297
  }
5298
 
5299
  /// Replaces the designator at index @p Idx with the series
5300
  /// of designators in [First, Last).
5301
  void ExpandDesignator(const ASTContext &C, unsigned Idx,
5302
                        const Designator *First, const Designator *Last);
5303
 
5304
  SourceRange getDesignatorsSourceRange() const;
5305
 
5306
  SourceLocation getBeginLoc() const LLVM_READONLY;
5307
  SourceLocation getEndLoc() const LLVM_READONLY;
5308
 
5309
  static bool classof(const Stmt *T) {
5310
    return T->getStmtClass() == DesignatedInitExprClass;
5311
  }
5312
 
5313
  // Iterators
5314
  child_range children() {
5315
    Stmt **begin = getTrailingObjects<Stmt *>();
5316
    return child_range(begin, begin + NumSubExprs);
5317
  }
5318
  const_child_range children() const {
5319
    Stmt * const *begin = getTrailingObjects<Stmt *>();
5320
    return const_child_range(begin, begin + NumSubExprs);
5321
  }
5322
 
5323
  friend TrailingObjects;
5324
};
5325
 
5326
/// Represents a place-holder for an object not to be initialized by
5327
/// anything.
5328
///
5329
/// This only makes sense when it appears as part of an updater of a
5330
/// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
5331
/// initializes a big object, and the NoInitExpr's mark the spots within the
5332
/// big object not to be overwritten by the updater.
5333
///
5334
/// \see DesignatedInitUpdateExpr
5335
class NoInitExpr : public Expr {
5336
public:
5337
  explicit NoInitExpr(QualType ty)
5338
      : Expr(NoInitExprClass, ty, VK_PRValue, OK_Ordinary) {
5339
    setDependence(computeDependence(this));
5340
  }
5341
 
5342
  explicit NoInitExpr(EmptyShell Empty)
5343
    : Expr(NoInitExprClass, Empty) { }
5344
 
5345
  static bool classof(const Stmt *T) {
5346
    return T->getStmtClass() == NoInitExprClass;
5347
  }
5348
 
5349
  SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5350
  SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5351
 
5352
  // Iterators
5353
  child_range children() {
5354
    return child_range(child_iterator(), child_iterator());
5355
  }
5356
  const_child_range children() const {
5357
    return const_child_range(const_child_iterator(), const_child_iterator());
5358
  }
5359
};
5360
 
5361
// In cases like:
5362
//   struct Q { int a, b, c; };
5363
//   Q *getQ();
5364
//   void foo() {
5365
//     struct A { Q q; } a = { *getQ(), .q.b = 3 };
5366
//   }
5367
//
5368
// We will have an InitListExpr for a, with type A, and then a
5369
// DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
5370
// is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
5371
//
5372
class DesignatedInitUpdateExpr : public Expr {
5373
  // BaseAndUpdaterExprs[0] is the base expression;
5374
  // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
5375
  Stmt *BaseAndUpdaterExprs[2];
5376
 
5377
public:
5378
  DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
5379
                           Expr *baseExprs, SourceLocation rBraceLoc);
5380
 
5381
  explicit DesignatedInitUpdateExpr(EmptyShell Empty)
5382
    : Expr(DesignatedInitUpdateExprClass, Empty) { }
5383
 
5384
  SourceLocation getBeginLoc() const LLVM_READONLY;
5385
  SourceLocation getEndLoc() const LLVM_READONLY;
5386
 
5387
  static bool classof(const Stmt *T) {
5388
    return T->getStmtClass() == DesignatedInitUpdateExprClass;
5389
  }
5390
 
5391
  Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
5392
  void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
5393
 
5394
  InitListExpr *getUpdater() const {
5395
    return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
5396
  }
5397
  void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
5398
 
5399
  // Iterators
5400
  // children = the base and the updater
5401
  child_range children() {
5402
    return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
5403
  }
5404
  const_child_range children() const {
5405
    return const_child_range(&BaseAndUpdaterExprs[0],
5406
                             &BaseAndUpdaterExprs[0] + 2);
5407
  }
5408
};
5409
 
5410
/// Represents a loop initializing the elements of an array.
5411
///
5412
/// The need to initialize the elements of an array occurs in a number of
5413
/// contexts:
5414
///
5415
///  * in the implicit copy/move constructor for a class with an array member
5416
///  * when a lambda-expression captures an array by value
5417
///  * when a decomposition declaration decomposes an array
5418
///
5419
/// There are two subexpressions: a common expression (the source array)
5420
/// that is evaluated once up-front, and a per-element initializer that
5421
/// runs once for each array element.
5422
///
5423
/// Within the per-element initializer, the common expression may be referenced
5424
/// via an OpaqueValueExpr, and the current index may be obtained via an
5425
/// ArrayInitIndexExpr.
5426
class ArrayInitLoopExpr : public Expr {
5427
  Stmt *SubExprs[2];
5428
 
5429
  explicit ArrayInitLoopExpr(EmptyShell Empty)
5430
      : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
5431
 
5432
public:
5433
  explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
5434
      : Expr(ArrayInitLoopExprClass, T, VK_PRValue, OK_Ordinary),
5435
        SubExprs{CommonInit, ElementInit} {
5436
    setDependence(computeDependence(this));
5437
  }
5438
 
5439
  /// Get the common subexpression shared by all initializations (the source
5440
  /// array).
5441
  OpaqueValueExpr *getCommonExpr() const {
5442
    return cast<OpaqueValueExpr>(SubExprs[0]);
5443
  }
5444
 
5445
  /// Get the initializer to use for each array element.
5446
  Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
5447
 
5448
  llvm::APInt getArraySize() const {
5449
    return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
5450
        ->getSize();
5451
  }
5452
 
5453
  static bool classof(const Stmt *S) {
5454
    return S->getStmtClass() == ArrayInitLoopExprClass;
5455
  }
5456
 
5457
  SourceLocation getBeginLoc() const LLVM_READONLY {
5458
    return getCommonExpr()->getBeginLoc();
5459
  }
5460
  SourceLocation getEndLoc() const LLVM_READONLY {
5461
    return getCommonExpr()->getEndLoc();
5462
  }
5463
 
5464
  child_range children() {
5465
    return child_range(SubExprs, SubExprs + 2);
5466
  }
5467
  const_child_range children() const {
5468
    return const_child_range(SubExprs, SubExprs + 2);
5469
  }
5470
 
5471
  friend class ASTReader;
5472
  friend class ASTStmtReader;
5473
  friend class ASTStmtWriter;
5474
};
5475
 
5476
/// Represents the index of the current element of an array being
5477
/// initialized by an ArrayInitLoopExpr. This can only appear within the
5478
/// subexpression of an ArrayInitLoopExpr.
5479
class ArrayInitIndexExpr : public Expr {
5480
  explicit ArrayInitIndexExpr(EmptyShell Empty)
5481
      : Expr(ArrayInitIndexExprClass, Empty) {}
5482
 
5483
public:
5484
  explicit ArrayInitIndexExpr(QualType T)
5485
      : Expr(ArrayInitIndexExprClass, T, VK_PRValue, OK_Ordinary) {
5486
    setDependence(ExprDependence::None);
5487
  }
5488
 
5489
  static bool classof(const Stmt *S) {
5490
    return S->getStmtClass() == ArrayInitIndexExprClass;
5491
  }
5492
 
5493
  SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5494
  SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5495
 
5496
  child_range children() {
5497
    return child_range(child_iterator(), child_iterator());
5498
  }
5499
  const_child_range children() const {
5500
    return const_child_range(const_child_iterator(), const_child_iterator());
5501
  }
5502
 
5503
  friend class ASTReader;
5504
  friend class ASTStmtReader;
5505
};
5506
 
5507
/// Represents an implicitly-generated value initialization of
5508
/// an object of a given type.
5509
///
5510
/// Implicit value initializations occur within semantic initializer
5511
/// list expressions (InitListExpr) as placeholders for subobject
5512
/// initializations not explicitly specified by the user.
5513
///
5514
/// \see InitListExpr
5515
class ImplicitValueInitExpr : public Expr {
5516
public:
5517
  explicit ImplicitValueInitExpr(QualType ty)
5518
      : Expr(ImplicitValueInitExprClass, ty, VK_PRValue, OK_Ordinary) {
5519
    setDependence(computeDependence(this));
5520
  }
5521
 
5522
  /// Construct an empty implicit value initialization.
5523
  explicit ImplicitValueInitExpr(EmptyShell Empty)
5524
    : Expr(ImplicitValueInitExprClass, Empty) { }
5525
 
5526
  static bool classof(const Stmt *T) {
5527
    return T->getStmtClass() == ImplicitValueInitExprClass;
5528
  }
5529
 
5530
  SourceLocation getBeginLoc() const LLVM_READONLY { return SourceLocation(); }
5531
  SourceLocation getEndLoc() const LLVM_READONLY { return SourceLocation(); }
5532
 
5533
  // Iterators
5534
  child_range children() {
5535
    return child_range(child_iterator(), child_iterator());
5536
  }
5537
  const_child_range children() const {
5538
    return const_child_range(const_child_iterator(), const_child_iterator());
5539
  }
5540
};
5541
 
5542
class ParenListExpr final
5543
    : public Expr,
5544
      private llvm::TrailingObjects<ParenListExpr, Stmt *> {
5545
  friend class ASTStmtReader;
5546
  friend TrailingObjects;
5547
 
5548
  /// The location of the left and right parentheses.
5549
  SourceLocation LParenLoc, RParenLoc;
5550
 
5551
  /// Build a paren list.
5552
  ParenListExpr(SourceLocation LParenLoc, ArrayRef<Expr *> Exprs,
5553
                SourceLocation RParenLoc);
5554
 
5555
  /// Build an empty paren list.
5556
  ParenListExpr(EmptyShell Empty, unsigned NumExprs);
5557
 
5558
public:
5559
  /// Create a paren list.
5560
  static ParenListExpr *Create(const ASTContext &Ctx, SourceLocation LParenLoc,
5561
                               ArrayRef<Expr *> Exprs,
5562
                               SourceLocation RParenLoc);
5563
 
5564
  /// Create an empty paren list.
5565
  static ParenListExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumExprs);
5566
 
5567
  /// Return the number of expressions in this paren list.
5568
  unsigned getNumExprs() const { return ParenListExprBits.NumExprs; }
5569
 
5570
  Expr *getExpr(unsigned Init) {
5571
    assert(Init < getNumExprs() && "Initializer access out of range!");
5572
    return getExprs()[Init];
5573
  }
5574
 
5575
  const Expr *getExpr(unsigned Init) const {
5576
    return const_cast<ParenListExpr *>(this)->getExpr(Init);
5577
  }
5578
 
5579
  Expr **getExprs() {
5580
    return reinterpret_cast<Expr **>(getTrailingObjects<Stmt *>());
5581
  }
5582
 
5583
  ArrayRef<Expr *> exprs() { return llvm::ArrayRef(getExprs(), getNumExprs()); }
5584
 
5585
  SourceLocation getLParenLoc() const { return LParenLoc; }
5586
  SourceLocation getRParenLoc() const { return RParenLoc; }
5587
  SourceLocation getBeginLoc() const { return getLParenLoc(); }
5588
  SourceLocation getEndLoc() const { return getRParenLoc(); }
5589
 
5590
  static bool classof(const Stmt *T) {
5591
    return T->getStmtClass() == ParenListExprClass;
5592
  }
5593
 
5594
  // Iterators
5595
  child_range children() {
5596
    return child_range(getTrailingObjects<Stmt *>(),
5597
                       getTrailingObjects<Stmt *>() + getNumExprs());
5598
  }
5599
  const_child_range children() const {
5600
    return const_child_range(getTrailingObjects<Stmt *>(),
5601
                             getTrailingObjects<Stmt *>() + getNumExprs());
5602
  }
5603
};
5604
 
5605
/// Represents a C11 generic selection.
5606
///
5607
/// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
5608
/// expression, followed by one or more generic associations.  Each generic
5609
/// association specifies a type name and an expression, or "default" and an
5610
/// expression (in which case it is known as a default generic association).
5611
/// The type and value of the generic selection are identical to those of its
5612
/// result expression, which is defined as the expression in the generic
5613
/// association with a type name that is compatible with the type of the
5614
/// controlling expression, or the expression in the default generic association
5615
/// if no types are compatible.  For example:
5616
///
5617
/// @code
5618
/// _Generic(X, double: 1, float: 2, default: 3)
5619
/// @endcode
5620
///
5621
/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
5622
/// or 3 if "hello".
5623
///
5624
/// As an extension, generic selections are allowed in C++, where the following
5625
/// additional semantics apply:
5626
///
5627
/// Any generic selection whose controlling expression is type-dependent or
5628
/// which names a dependent type in its association list is result-dependent,
5629
/// which means that the choice of result expression is dependent.
5630
/// Result-dependent generic associations are both type- and value-dependent.
5631
class GenericSelectionExpr final
5632
    : public Expr,
5633
      private llvm::TrailingObjects<GenericSelectionExpr, Stmt *,
5634
                                    TypeSourceInfo *> {
5635
  friend class ASTStmtReader;
5636
  friend class ASTStmtWriter;
5637
  friend TrailingObjects;
5638
 
5639
  /// The number of association expressions and the index of the result
5640
  /// expression in the case where the generic selection expression is not
5641
  /// result-dependent. The result index is equal to ResultDependentIndex
5642
  /// if and only if the generic selection expression is result-dependent.
5643
  unsigned NumAssocs, ResultIndex;
5644
  enum : unsigned {
5645
    ResultDependentIndex = std::numeric_limits<unsigned>::max(),
5646
    ControllingIndex = 0,
5647
    AssocExprStartIndex = 1
5648
  };
5649
 
5650
  /// The location of the "default" and of the right parenthesis.
5651
  SourceLocation DefaultLoc, RParenLoc;
5652
 
5653
  // GenericSelectionExpr is followed by several trailing objects.
5654
  // They are (in order):
5655
  //
5656
  // * A single Stmt * for the controlling expression.
5657
  // * An array of getNumAssocs() Stmt * for the association expressions.
5658
  // * An array of getNumAssocs() TypeSourceInfo *, one for each of the
5659
  //   association expressions.
5660
  unsigned numTrailingObjects(OverloadToken<Stmt *>) const {
5661
    // Add one to account for the controlling expression; the remainder
5662
    // are the associated expressions.
5663
    return 1 + getNumAssocs();
5664
  }
5665
 
5666
  unsigned numTrailingObjects(OverloadToken<TypeSourceInfo *>) const {
5667
    return getNumAssocs();
5668
  }
5669
 
5670
  template <bool Const> class AssociationIteratorTy;
5671
  /// Bundle together an association expression and its TypeSourceInfo.
5672
  /// The Const template parameter is for the const and non-const versions
5673
  /// of AssociationTy.
5674
  template <bool Const> class AssociationTy {
5675
    friend class GenericSelectionExpr;
5676
    template <bool OtherConst> friend class AssociationIteratorTy;
5677
    using ExprPtrTy = std::conditional_t<Const, const Expr *, Expr *>;
5678
    using TSIPtrTy =
5679
        std::conditional_t<Const, const TypeSourceInfo *, TypeSourceInfo *>;
5680
    ExprPtrTy E;
5681
    TSIPtrTy TSI;
5682
    bool Selected;
5683
    AssociationTy(ExprPtrTy E, TSIPtrTy TSI, bool Selected)
5684
        : E(E), TSI(TSI), Selected(Selected) {}
5685
 
5686
  public:
5687
    ExprPtrTy getAssociationExpr() const { return E; }
5688
    TSIPtrTy getTypeSourceInfo() const { return TSI; }
5689
    QualType getType() const { return TSI ? TSI->getType() : QualType(); }
5690
    bool isSelected() const { return Selected; }
5691
    AssociationTy *operator->() { return this; }
5692
    const AssociationTy *operator->() const { return this; }
5693
  }; // class AssociationTy
5694
 
5695
  /// Iterator over const and non-const Association objects. The Association
5696
  /// objects are created on the fly when the iterator is dereferenced.
5697
  /// This abstract over how exactly the association expressions and the
5698
  /// corresponding TypeSourceInfo * are stored.
5699
  template <bool Const>
5700
  class AssociationIteratorTy
5701
      : public llvm::iterator_facade_base<
5702
            AssociationIteratorTy<Const>, std::input_iterator_tag,
5703
            AssociationTy<Const>, std::ptrdiff_t, AssociationTy<Const>,
5704
            AssociationTy<Const>> {
5705
    friend class GenericSelectionExpr;
5706
    // FIXME: This iterator could conceptually be a random access iterator, and
5707
    // it would be nice if we could strengthen the iterator category someday.
5708
    // However this iterator does not satisfy two requirements of forward
5709
    // iterators:
5710
    // a) reference = T& or reference = const T&
5711
    // b) If It1 and It2 are both dereferenceable, then It1 == It2 if and only
5712
    //    if *It1 and *It2 are bound to the same objects.
5713
    // An alternative design approach was discussed during review;
5714
    // store an Association object inside the iterator, and return a reference
5715
    // to it when dereferenced. This idea was discarded beacuse of nasty
5716
    // lifetime issues:
5717
    //    AssociationIterator It = ...;
5718
    //    const Association &Assoc = *It++; // Oops, Assoc is dangling.
5719
    using BaseTy = typename AssociationIteratorTy::iterator_facade_base;
5720
    using StmtPtrPtrTy =
5721
        std::conditional_t<Const, const Stmt *const *, Stmt **>;
5722
    using TSIPtrPtrTy = std::conditional_t<Const, const TypeSourceInfo *const *,
5723
                                           TypeSourceInfo **>;
5724
    StmtPtrPtrTy E; // = nullptr; FIXME: Once support for gcc 4.8 is dropped.
5725
    TSIPtrPtrTy TSI; // Kept in sync with E.
5726
    unsigned Offset = 0, SelectedOffset = 0;
5727
    AssociationIteratorTy(StmtPtrPtrTy E, TSIPtrPtrTy TSI, unsigned Offset,
5728
                          unsigned SelectedOffset)
5729
        : E(E), TSI(TSI), Offset(Offset), SelectedOffset(SelectedOffset) {}
5730
 
5731
  public:
5732
    AssociationIteratorTy() : E(nullptr), TSI(nullptr) {}
5733
    typename BaseTy::reference operator*() const {
5734
      return AssociationTy<Const>(cast<Expr>(*E), *TSI,
5735
                                  Offset == SelectedOffset);
5736
    }
5737
    typename BaseTy::pointer operator->() const { return **this; }
5738
    using BaseTy::operator++;
5739
    AssociationIteratorTy &operator++() {
5740
      ++E;
5741
      ++TSI;
5742
      ++Offset;
5743
      return *this;
5744
    }
5745
    bool operator==(AssociationIteratorTy Other) const { return E == Other.E; }
5746
  }; // class AssociationIterator
5747
 
5748
  /// Build a non-result-dependent generic selection expression.
5749
  GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5750
                       Expr *ControllingExpr,
5751
                       ArrayRef<TypeSourceInfo *> AssocTypes,
5752
                       ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5753
                       SourceLocation RParenLoc,
5754
                       bool ContainsUnexpandedParameterPack,
5755
                       unsigned ResultIndex);
5756
 
5757
  /// Build a result-dependent generic selection expression.
5758
  GenericSelectionExpr(const ASTContext &Context, SourceLocation GenericLoc,
5759
                       Expr *ControllingExpr,
5760
                       ArrayRef<TypeSourceInfo *> AssocTypes,
5761
                       ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5762
                       SourceLocation RParenLoc,
5763
                       bool ContainsUnexpandedParameterPack);
5764
 
5765
  /// Build an empty generic selection expression for deserialization.
5766
  explicit GenericSelectionExpr(EmptyShell Empty, unsigned NumAssocs);
5767
 
5768
public:
5769
  /// Create a non-result-dependent generic selection expression.
5770
  static GenericSelectionExpr *
5771
  Create(const ASTContext &Context, SourceLocation GenericLoc,
5772
         Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
5773
         ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5774
         SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack,
5775
         unsigned ResultIndex);
5776
 
5777
  /// Create a result-dependent generic selection expression.
5778
  static GenericSelectionExpr *
5779
  Create(const ASTContext &Context, SourceLocation GenericLoc,
5780
         Expr *ControllingExpr, ArrayRef<TypeSourceInfo *> AssocTypes,
5781
         ArrayRef<Expr *> AssocExprs, SourceLocation DefaultLoc,
5782
         SourceLocation RParenLoc, bool ContainsUnexpandedParameterPack);
5783
 
5784
  /// Create an empty generic selection expression for deserialization.
5785
  static GenericSelectionExpr *CreateEmpty(const ASTContext &Context,
5786
                                           unsigned NumAssocs);
5787
 
5788
  using Association = AssociationTy<false>;
5789
  using ConstAssociation = AssociationTy<true>;
5790
  using AssociationIterator = AssociationIteratorTy<false>;
5791
  using ConstAssociationIterator = AssociationIteratorTy<true>;
5792
  using association_range = llvm::iterator_range<AssociationIterator>;
5793
  using const_association_range =
5794
      llvm::iterator_range<ConstAssociationIterator>;
5795
 
5796
  /// The number of association expressions.
5797
  unsigned getNumAssocs() const { return NumAssocs; }
5798
 
5799
  /// The zero-based index of the result expression's generic association in
5800
  /// the generic selection's association list.  Defined only if the
5801
  /// generic selection is not result-dependent.
5802
  unsigned getResultIndex() const {
5803
    assert(!isResultDependent() &&
5804
           "Generic selection is result-dependent but getResultIndex called!");
5805
    return ResultIndex;
5806
  }
5807
 
5808
  /// Whether this generic selection is result-dependent.
5809
  bool isResultDependent() const { return ResultIndex == ResultDependentIndex; }
5810
 
5811
  /// Return the controlling expression of this generic selection expression.
5812
  Expr *getControllingExpr() {
5813
    return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
5814
  }
5815
  const Expr *getControllingExpr() const {
5816
    return cast<Expr>(getTrailingObjects<Stmt *>()[ControllingIndex]);
5817
  }
5818
 
5819
  /// Return the result expression of this controlling expression. Defined if
5820
  /// and only if the generic selection expression is not result-dependent.
5821
  Expr *getResultExpr() {
5822
    return cast<Expr>(
5823
        getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
5824
  }
5825
  const Expr *getResultExpr() const {
5826
    return cast<Expr>(
5827
        getTrailingObjects<Stmt *>()[AssocExprStartIndex + getResultIndex()]);
5828
  }
5829
 
5830
  ArrayRef<Expr *> getAssocExprs() const {
5831
    return {reinterpret_cast<Expr *const *>(getTrailingObjects<Stmt *>() +
5832
                                            AssocExprStartIndex),
5833
            NumAssocs};
5834
  }
5835
  ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
5836
    return {getTrailingObjects<TypeSourceInfo *>(), NumAssocs};
5837
  }
5838
 
5839
  /// Return the Ith association expression with its TypeSourceInfo,
5840
  /// bundled together in GenericSelectionExpr::(Const)Association.
5841
  Association getAssociation(unsigned I) {
5842
    assert(I < getNumAssocs() &&
5843
           "Out-of-range index in GenericSelectionExpr::getAssociation!");
5844
    return Association(
5845
        cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
5846
        getTrailingObjects<TypeSourceInfo *>()[I],
5847
        !isResultDependent() && (getResultIndex() == I));
5848
  }
5849
  ConstAssociation getAssociation(unsigned I) const {
5850
    assert(I < getNumAssocs() &&
5851
           "Out-of-range index in GenericSelectionExpr::getAssociation!");
5852
    return ConstAssociation(
5853
        cast<Expr>(getTrailingObjects<Stmt *>()[AssocExprStartIndex + I]),
5854
        getTrailingObjects<TypeSourceInfo *>()[I],
5855
        !isResultDependent() && (getResultIndex() == I));
5856
  }
5857
 
5858
  association_range associations() {
5859
    AssociationIterator Begin(getTrailingObjects<Stmt *>() +
5860
                                  AssocExprStartIndex,
5861
                              getTrailingObjects<TypeSourceInfo *>(),
5862
                              /*Offset=*/0, ResultIndex);
5863
    AssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
5864
                            /*Offset=*/NumAssocs, ResultIndex);
5865
    return llvm::make_range(Begin, End);
5866
  }
5867
 
5868
  const_association_range associations() const {
5869
    ConstAssociationIterator Begin(getTrailingObjects<Stmt *>() +
5870
                                       AssocExprStartIndex,
5871
                                   getTrailingObjects<TypeSourceInfo *>(),
5872
                                   /*Offset=*/0, ResultIndex);
5873
    ConstAssociationIterator End(Begin.E + NumAssocs, Begin.TSI + NumAssocs,
5874
                                 /*Offset=*/NumAssocs, ResultIndex);
5875
    return llvm::make_range(Begin, End);
5876
  }
5877
 
5878
  SourceLocation getGenericLoc() const {
5879
    return GenericSelectionExprBits.GenericLoc;
5880
  }
5881
  SourceLocation getDefaultLoc() const { return DefaultLoc; }
5882
  SourceLocation getRParenLoc() const { return RParenLoc; }
5883
  SourceLocation getBeginLoc() const { return getGenericLoc(); }
5884
  SourceLocation getEndLoc() const { return getRParenLoc(); }
5885
 
5886
  static bool classof(const Stmt *T) {
5887
    return T->getStmtClass() == GenericSelectionExprClass;
5888
  }
5889
 
5890
  child_range children() {
5891
    return child_range(getTrailingObjects<Stmt *>(),
5892
                       getTrailingObjects<Stmt *>() +
5893
                           numTrailingObjects(OverloadToken<Stmt *>()));
5894
  }
5895
  const_child_range children() const {
5896
    return const_child_range(getTrailingObjects<Stmt *>(),
5897
                             getTrailingObjects<Stmt *>() +
5898
                                 numTrailingObjects(OverloadToken<Stmt *>()));
5899
  }
5900
};
5901
 
5902
//===----------------------------------------------------------------------===//
5903
// Clang Extensions
5904
//===----------------------------------------------------------------------===//
5905
 
5906
/// ExtVectorElementExpr - This represents access to specific elements of a
5907
/// vector, and may occur on the left hand side or right hand side.  For example
5908
/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
5909
///
5910
/// Note that the base may have either vector or pointer to vector type, just
5911
/// like a struct field reference.
5912
///
5913
class ExtVectorElementExpr : public Expr {
5914
  Stmt *Base;
5915
  IdentifierInfo *Accessor;
5916
  SourceLocation AccessorLoc;
5917
public:
5918
  ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
5919
                       IdentifierInfo &accessor, SourceLocation loc)
5920
      : Expr(ExtVectorElementExprClass, ty, VK,
5921
             (VK == VK_PRValue ? OK_Ordinary : OK_VectorComponent)),
5922
        Base(base), Accessor(&accessor), AccessorLoc(loc) {
5923
    setDependence(computeDependence(this));
5924
  }
5925
 
5926
  /// Build an empty vector element expression.
5927
  explicit ExtVectorElementExpr(EmptyShell Empty)
5928
    : Expr(ExtVectorElementExprClass, Empty) { }
5929
 
5930
  const Expr *getBase() const { return cast<Expr>(Base); }
5931
  Expr *getBase() { return cast<Expr>(Base); }
5932
  void setBase(Expr *E) { Base = E; }
5933
 
5934
  IdentifierInfo &getAccessor() const { return *Accessor; }
5935
  void setAccessor(IdentifierInfo *II) { Accessor = II; }
5936
 
5937
  SourceLocation getAccessorLoc() const { return AccessorLoc; }
5938
  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
5939
 
5940
  /// getNumElements - Get the number of components being selected.
5941
  unsigned getNumElements() const;
5942
 
5943
  /// containsDuplicateElements - Return true if any element access is
5944
  /// repeated.
5945
  bool containsDuplicateElements() const;
5946
 
5947
  /// getEncodedElementAccess - Encode the elements accessed into an llvm
5948
  /// aggregate Constant of ConstantInt(s).
5949
  void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
5950
 
5951
  SourceLocation getBeginLoc() const LLVM_READONLY {
5952
    return getBase()->getBeginLoc();
5953
  }
5954
  SourceLocation getEndLoc() const LLVM_READONLY { return AccessorLoc; }
5955
 
5956
  /// isArrow - Return true if the base expression is a pointer to vector,
5957
  /// return false if the base expression is a vector.
5958
  bool isArrow() const;
5959
 
5960
  static bool classof(const Stmt *T) {
5961
    return T->getStmtClass() == ExtVectorElementExprClass;
5962
  }
5963
 
5964
  // Iterators
5965
  child_range children() { return child_range(&Base, &Base+1); }
5966
  const_child_range children() const {
5967
    return const_child_range(&Base, &Base + 1);
5968
  }
5969
};
5970
 
5971
/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
5972
/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
5973
class BlockExpr : public Expr {
5974
protected:
5975
  BlockDecl *TheBlock;
5976
public:
5977
  BlockExpr(BlockDecl *BD, QualType ty)
5978
      : Expr(BlockExprClass, ty, VK_PRValue, OK_Ordinary), TheBlock(BD) {
5979
    setDependence(computeDependence(this));
5980
  }
5981
 
5982
  /// Build an empty block expression.
5983
  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
5984
 
5985
  const BlockDecl *getBlockDecl() const { return TheBlock; }
5986
  BlockDecl *getBlockDecl() { return TheBlock; }
5987
  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
5988
 
5989
  // Convenience functions for probing the underlying BlockDecl.
5990
  SourceLocation getCaretLocation() const;
5991
  const Stmt *getBody() const;
5992
  Stmt *getBody();
5993
 
5994
  SourceLocation getBeginLoc() const LLVM_READONLY {
5995
    return getCaretLocation();
5996
  }
5997
  SourceLocation getEndLoc() const LLVM_READONLY {
5998
    return getBody()->getEndLoc();
5999
  }
6000
 
6001
  /// getFunctionType - Return the underlying function type for this block.
6002
  const FunctionProtoType *getFunctionType() const;
6003
 
6004
  static bool classof(const Stmt *T) {
6005
    return T->getStmtClass() == BlockExprClass;
6006
  }
6007
 
6008
  // Iterators
6009
  child_range children() {
6010
    return child_range(child_iterator(), child_iterator());
6011
  }
6012
  const_child_range children() const {
6013
    return const_child_range(const_child_iterator(), const_child_iterator());
6014
  }
6015
};
6016
 
6017
/// Copy initialization expr of a __block variable and a boolean flag that
6018
/// indicates whether the expression can throw.
6019
struct BlockVarCopyInit {
6020
  BlockVarCopyInit() = default;
6021
  BlockVarCopyInit(Expr *CopyExpr, bool CanThrow)
6022
      : ExprAndFlag(CopyExpr, CanThrow) {}
6023
  void setExprAndFlag(Expr *CopyExpr, bool CanThrow) {
6024
    ExprAndFlag.setPointerAndInt(CopyExpr, CanThrow);
6025
  }
6026
  Expr *getCopyExpr() const { return ExprAndFlag.getPointer(); }
6027
  bool canThrow() const { return ExprAndFlag.getInt(); }
6028
  llvm::PointerIntPair<Expr *, 1, bool> ExprAndFlag;
6029
};
6030
 
6031
/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
6032
/// This AST node provides support for reinterpreting a type to another
6033
/// type of the same size.
6034
class AsTypeExpr : public Expr {
6035
private:
6036
  Stmt *SrcExpr;
6037
  SourceLocation BuiltinLoc, RParenLoc;
6038
 
6039
  friend class ASTReader;
6040
  friend class ASTStmtReader;
6041
  explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
6042
 
6043
public:
6044
  AsTypeExpr(Expr *SrcExpr, QualType DstType, ExprValueKind VK,
6045
             ExprObjectKind OK, SourceLocation BuiltinLoc,
6046
             SourceLocation RParenLoc)
6047
      : Expr(AsTypeExprClass, DstType, VK, OK), SrcExpr(SrcExpr),
6048
        BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {
6049
    setDependence(computeDependence(this));
6050
  }
6051
 
6052
  /// getSrcExpr - Return the Expr to be converted.
6053
  Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
6054
 
6055
  /// getBuiltinLoc - Return the location of the __builtin_astype token.
6056
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
6057
 
6058
  /// getRParenLoc - Return the location of final right parenthesis.
6059
  SourceLocation getRParenLoc() const { return RParenLoc; }
6060
 
6061
  SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
6062
  SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
6063
 
6064
  static bool classof(const Stmt *T) {
6065
    return T->getStmtClass() == AsTypeExprClass;
6066
  }
6067
 
6068
  // Iterators
6069
  child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
6070
  const_child_range children() const {
6071
    return const_child_range(&SrcExpr, &SrcExpr + 1);
6072
  }
6073
};
6074
 
6075
/// PseudoObjectExpr - An expression which accesses a pseudo-object
6076
/// l-value.  A pseudo-object is an abstract object, accesses to which
6077
/// are translated to calls.  The pseudo-object expression has a
6078
/// syntactic form, which shows how the expression was actually
6079
/// written in the source code, and a semantic form, which is a series
6080
/// of expressions to be executed in order which detail how the
6081
/// operation is actually evaluated.  Optionally, one of the semantic
6082
/// forms may also provide a result value for the expression.
6083
///
6084
/// If any of the semantic-form expressions is an OpaqueValueExpr,
6085
/// that OVE is required to have a source expression, and it is bound
6086
/// to the result of that source expression.  Such OVEs may appear
6087
/// only in subsequent semantic-form expressions and as
6088
/// sub-expressions of the syntactic form.
6089
///
6090
/// PseudoObjectExpr should be used only when an operation can be
6091
/// usefully described in terms of fairly simple rewrite rules on
6092
/// objects and functions that are meant to be used by end-developers.
6093
/// For example, under the Itanium ABI, dynamic casts are implemented
6094
/// as a call to a runtime function called __dynamic_cast; using this
6095
/// class to describe that would be inappropriate because that call is
6096
/// not really part of the user-visible semantics, and instead the
6097
/// cast is properly reflected in the AST and IR-generation has been
6098
/// taught to generate the call as necessary.  In contrast, an
6099
/// Objective-C property access is semantically defined to be
6100
/// equivalent to a particular message send, and this is very much
6101
/// part of the user model.  The name of this class encourages this
6102
/// modelling design.
6103
class PseudoObjectExpr final
6104
    : public Expr,
6105
      private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
6106
  // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
6107
  // Always at least two, because the first sub-expression is the
6108
  // syntactic form.
6109
 
6110
  // PseudoObjectExprBits.ResultIndex - The index of the
6111
  // sub-expression holding the result.  0 means the result is void,
6112
  // which is unambiguous because it's the index of the syntactic
6113
  // form.  Note that this is therefore 1 higher than the value passed
6114
  // in to Create, which is an index within the semantic forms.
6115
  // Note also that ASTStmtWriter assumes this encoding.
6116
 
6117
  Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
6118
  const Expr * const *getSubExprsBuffer() const {
6119
    return getTrailingObjects<Expr *>();
6120
  }
6121
 
6122
  PseudoObjectExpr(QualType type, ExprValueKind VK,
6123
                   Expr *syntactic, ArrayRef<Expr*> semantic,
6124
                   unsigned resultIndex);
6125
 
6126
  PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
6127
 
6128
  unsigned getNumSubExprs() const {
6129
    return PseudoObjectExprBits.NumSubExprs;
6130
  }
6131
 
6132
public:
6133
  /// NoResult - A value for the result index indicating that there is
6134
  /// no semantic result.
6135
  enum : unsigned { NoResult = ~0U };
6136
 
6137
  static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
6138
                                  ArrayRef<Expr*> semantic,
6139
                                  unsigned resultIndex);
6140
 
6141
  static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
6142
                                  unsigned numSemanticExprs);
6143
 
6144
  /// Return the syntactic form of this expression, i.e. the
6145
  /// expression it actually looks like.  Likely to be expressed in
6146
  /// terms of OpaqueValueExprs bound in the semantic form.
6147
  Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
6148
  const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
6149
 
6150
  /// Return the index of the result-bearing expression into the semantics
6151
  /// expressions, or PseudoObjectExpr::NoResult if there is none.
6152
  unsigned getResultExprIndex() const {
6153
    if (PseudoObjectExprBits.ResultIndex == 0) return NoResult;
6154
    return PseudoObjectExprBits.ResultIndex - 1;
6155
  }
6156
 
6157
  /// Return the result-bearing expression, or null if there is none.
6158
  Expr *getResultExpr() {
6159
    if (PseudoObjectExprBits.ResultIndex == 0)
6160
      return nullptr;
6161
    return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
6162
  }
6163
  const Expr *getResultExpr() const {
6164
    return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
6165
  }
6166
 
6167
  unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
6168
 
6169
  typedef Expr * const *semantics_iterator;
6170
  typedef const Expr * const *const_semantics_iterator;
6171
  semantics_iterator semantics_begin() {
6172
    return getSubExprsBuffer() + 1;
6173
  }
6174
  const_semantics_iterator semantics_begin() const {
6175
    return getSubExprsBuffer() + 1;
6176
  }
6177
  semantics_iterator semantics_end() {
6178
    return getSubExprsBuffer() + getNumSubExprs();
6179
  }
6180
  const_semantics_iterator semantics_end() const {
6181
    return getSubExprsBuffer() + getNumSubExprs();
6182
  }
6183
 
6184
  llvm::iterator_range<semantics_iterator> semantics() {
6185
    return llvm::make_range(semantics_begin(), semantics_end());
6186
  }
6187
  llvm::iterator_range<const_semantics_iterator> semantics() const {
6188
    return llvm::make_range(semantics_begin(), semantics_end());
6189
  }
6190
 
6191
  Expr *getSemanticExpr(unsigned index) {
6192
    assert(index + 1 < getNumSubExprs());
6193
    return getSubExprsBuffer()[index + 1];
6194
  }
6195
  const Expr *getSemanticExpr(unsigned index) const {
6196
    return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
6197
  }
6198
 
6199
  SourceLocation getExprLoc() const LLVM_READONLY {
6200
    return getSyntacticForm()->getExprLoc();
6201
  }
6202
 
6203
  SourceLocation getBeginLoc() const LLVM_READONLY {
6204
    return getSyntacticForm()->getBeginLoc();
6205
  }
6206
  SourceLocation getEndLoc() const LLVM_READONLY {
6207
    return getSyntacticForm()->getEndLoc();
6208
  }
6209
 
6210
  child_range children() {
6211
    const_child_range CCR =
6212
        const_cast<const PseudoObjectExpr *>(this)->children();
6213
    return child_range(cast_away_const(CCR.begin()),
6214
                       cast_away_const(CCR.end()));
6215
  }
6216
  const_child_range children() const {
6217
    Stmt *const *cs = const_cast<Stmt *const *>(
6218
        reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
6219
    return const_child_range(cs, cs + getNumSubExprs());
6220
  }
6221
 
6222
  static bool classof(const Stmt *T) {
6223
    return T->getStmtClass() == PseudoObjectExprClass;
6224
  }
6225
 
6226
  friend TrailingObjects;
6227
  friend class ASTStmtReader;
6228
};
6229
 
6230
/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
6231
/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
6232
/// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
6233
/// and corresponding __opencl_atomic_* for OpenCL 2.0.
6234
/// All of these instructions take one primary pointer, at least one memory
6235
/// order. The instructions for which getScopeModel returns non-null value
6236
/// take one synch scope.
6237
class AtomicExpr : public Expr {
6238
public:
6239
  enum AtomicOp {
6240
#define BUILTIN(ID, TYPE, ATTRS)
6241
#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
6242
#include "clang/Basic/Builtins.def"
6243
    // Avoid trailing comma
6244
    BI_First = 0
6245
  };
6246
 
6247
private:
6248
  /// Location of sub-expressions.
6249
  /// The location of Scope sub-expression is NumSubExprs - 1, which is
6250
  /// not fixed, therefore is not defined in enum.
6251
  enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
6252
  Stmt *SubExprs[END_EXPR + 1];
6253
  unsigned NumSubExprs;
6254
  SourceLocation BuiltinLoc, RParenLoc;
6255
  AtomicOp Op;
6256
 
6257
  friend class ASTStmtReader;
6258
public:
6259
  AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
6260
             AtomicOp op, SourceLocation RP);
6261
 
6262
  /// Determine the number of arguments the specified atomic builtin
6263
  /// should have.
6264
  static unsigned getNumSubExprs(AtomicOp Op);
6265
 
6266
  /// Build an empty AtomicExpr.
6267
  explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
6268
 
6269
  Expr *getPtr() const {
6270
    return cast<Expr>(SubExprs[PTR]);
6271
  }
6272
  Expr *getOrder() const {
6273
    return cast<Expr>(SubExprs[ORDER]);
6274
  }
6275
  Expr *getScope() const {
6276
    assert(getScopeModel() && "No scope");
6277
    return cast<Expr>(SubExprs[NumSubExprs - 1]);
6278
  }
6279
  Expr *getVal1() const {
6280
    if (Op == AO__c11_atomic_init || Op == AO__opencl_atomic_init)
6281
      return cast<Expr>(SubExprs[ORDER]);
6282
    assert(NumSubExprs > VAL1);
6283
    return cast<Expr>(SubExprs[VAL1]);
6284
  }
6285
  Expr *getOrderFail() const {
6286
    assert(NumSubExprs > ORDER_FAIL);
6287
    return cast<Expr>(SubExprs[ORDER_FAIL]);
6288
  }
6289
  Expr *getVal2() const {
6290
    if (Op == AO__atomic_exchange)
6291
      return cast<Expr>(SubExprs[ORDER_FAIL]);
6292
    assert(NumSubExprs > VAL2);
6293
    return cast<Expr>(SubExprs[VAL2]);
6294
  }
6295
  Expr *getWeak() const {
6296
    assert(NumSubExprs > WEAK);
6297
    return cast<Expr>(SubExprs[WEAK]);
6298
  }
6299
  QualType getValueType() const;
6300
 
6301
  AtomicOp getOp() const { return Op; }
6302
  unsigned getNumSubExprs() const { return NumSubExprs; }
6303
 
6304
  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
6305
  const Expr * const *getSubExprs() const {
6306
    return reinterpret_cast<Expr * const *>(SubExprs);
6307
  }
6308
 
6309
  bool isVolatile() const {
6310
    return getPtr()->getType()->getPointeeType().isVolatileQualified();
6311
  }
6312
 
6313
  bool isCmpXChg() const {
6314
    return getOp() == AO__c11_atomic_compare_exchange_strong ||
6315
           getOp() == AO__c11_atomic_compare_exchange_weak ||
6316
           getOp() == AO__hip_atomic_compare_exchange_strong ||
6317
           getOp() == AO__opencl_atomic_compare_exchange_strong ||
6318
           getOp() == AO__opencl_atomic_compare_exchange_weak ||
6319
           getOp() == AO__hip_atomic_compare_exchange_weak ||
6320
           getOp() == AO__atomic_compare_exchange ||
6321
           getOp() == AO__atomic_compare_exchange_n;
6322
  }
6323
 
6324
  bool isOpenCL() const {
6325
    return getOp() >= AO__opencl_atomic_init &&
6326
           getOp() <= AO__opencl_atomic_fetch_max;
6327
  }
6328
 
6329
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
6330
  SourceLocation getRParenLoc() const { return RParenLoc; }
6331
 
6332
  SourceLocation getBeginLoc() const LLVM_READONLY { return BuiltinLoc; }
6333
  SourceLocation getEndLoc() const LLVM_READONLY { return RParenLoc; }
6334
 
6335
  static bool classof(const Stmt *T) {
6336
    return T->getStmtClass() == AtomicExprClass;
6337
  }
6338
 
6339
  // Iterators
6340
  child_range children() {
6341
    return child_range(SubExprs, SubExprs+NumSubExprs);
6342
  }
6343
  const_child_range children() const {
6344
    return const_child_range(SubExprs, SubExprs + NumSubExprs);
6345
  }
6346
 
6347
  /// Get atomic scope model for the atomic op code.
6348
  /// \return empty atomic scope model if the atomic op code does not have
6349
  ///   scope operand.
6350
  static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
6351
    auto Kind =
6352
        (Op >= AO__opencl_atomic_load && Op <= AO__opencl_atomic_fetch_max)
6353
            ? AtomicScopeModelKind::OpenCL
6354
        : (Op >= AO__hip_atomic_load && Op <= AO__hip_atomic_fetch_max)
6355
            ? AtomicScopeModelKind::HIP
6356
            : AtomicScopeModelKind::None;
6357
    return AtomicScopeModel::create(Kind);
6358
  }
6359
 
6360
  /// Get atomic scope model.
6361
  /// \return empty atomic scope model if this atomic expression does not have
6362
  ///   scope operand.
6363
  std::unique_ptr<AtomicScopeModel> getScopeModel() const {
6364
    return getScopeModel(getOp());
6365
  }
6366
};
6367
 
6368
/// TypoExpr - Internal placeholder for expressions where typo correction
6369
/// still needs to be performed and/or an error diagnostic emitted.
6370
class TypoExpr : public Expr {
6371
  // The location for the typo name.
6372
  SourceLocation TypoLoc;
6373
 
6374
public:
6375
  TypoExpr(QualType T, SourceLocation TypoLoc)
6376
      : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary), TypoLoc(TypoLoc) {
6377
    assert(T->isDependentType() && "TypoExpr given a non-dependent type");
6378
    setDependence(ExprDependence::TypeValueInstantiation |
6379
                  ExprDependence::Error);
6380
  }
6381
 
6382
  child_range children() {
6383
    return child_range(child_iterator(), child_iterator());
6384
  }
6385
  const_child_range children() const {
6386
    return const_child_range(const_child_iterator(), const_child_iterator());
6387
  }
6388
 
6389
  SourceLocation getBeginLoc() const LLVM_READONLY { return TypoLoc; }
6390
  SourceLocation getEndLoc() const LLVM_READONLY { return TypoLoc; }
6391
 
6392
  static bool classof(const Stmt *T) {
6393
    return T->getStmtClass() == TypoExprClass;
6394
  }
6395
 
6396
};
6397
 
6398
/// Frontend produces RecoveryExprs on semantic errors that prevent creating
6399
/// other well-formed expressions. E.g. when type-checking of a binary operator
6400
/// fails, we cannot produce a BinaryOperator expression. Instead, we can choose
6401
/// to produce a recovery expression storing left and right operands.
6402
///
6403
/// RecoveryExpr does not have any semantic meaning in C++, it is only useful to
6404
/// preserve expressions in AST that would otherwise be dropped. It captures
6405
/// subexpressions of some expression that we could not construct and source
6406
/// range covered by the expression.
6407
///
6408
/// By default, RecoveryExpr uses dependence-bits to take advantage of existing
6409
/// machinery to deal with dependent code in C++, e.g. RecoveryExpr is preserved
6410
/// in `decltype(<broken-expr>)` as part of the `DependentDecltypeType`. In
6411
/// addition to that, clang does not report most errors on dependent
6412
/// expressions, so we get rid of bogus errors for free. However, note that
6413
/// unlike other dependent expressions, RecoveryExpr can be produced in
6414
/// non-template contexts.
6415
///
6416
/// We will preserve the type in RecoveryExpr when the type is known, e.g.
6417
/// preserving the return type for a broken non-overloaded function call, a
6418
/// overloaded call where all candidates have the same return type. In this
6419
/// case, the expression is not type-dependent (unless the known type is itself
6420
/// dependent)
6421
///
6422
/// One can also reliably suppress all bogus errors on expressions containing
6423
/// recovery expressions by examining results of Expr::containsErrors().
6424
class RecoveryExpr final : public Expr,
6425
                           private llvm::TrailingObjects<RecoveryExpr, Expr *> {
6426
public:
6427
  static RecoveryExpr *Create(ASTContext &Ctx, QualType T,
6428
                              SourceLocation BeginLoc, SourceLocation EndLoc,
6429
                              ArrayRef<Expr *> SubExprs);
6430
  static RecoveryExpr *CreateEmpty(ASTContext &Ctx, unsigned NumSubExprs);
6431
 
6432
  ArrayRef<Expr *> subExpressions() {
6433
    auto *B = getTrailingObjects<Expr *>();
6434
    return llvm::ArrayRef(B, B + NumExprs);
6435
  }
6436
 
6437
  ArrayRef<const Expr *> subExpressions() const {
6438
    return const_cast<RecoveryExpr *>(this)->subExpressions();
6439
  }
6440
 
6441
  child_range children() {
6442
    Stmt **B = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
6443
    return child_range(B, B + NumExprs);
6444
  }
6445
 
6446
  SourceLocation getBeginLoc() const { return BeginLoc; }
6447
  SourceLocation getEndLoc() const { return EndLoc; }
6448
 
6449
  static bool classof(const Stmt *T) {
6450
    return T->getStmtClass() == RecoveryExprClass;
6451
  }
6452
 
6453
private:
6454
  RecoveryExpr(ASTContext &Ctx, QualType T, SourceLocation BeginLoc,
6455
               SourceLocation EndLoc, ArrayRef<Expr *> SubExprs);
6456
  RecoveryExpr(EmptyShell Empty, unsigned NumSubExprs)
6457
      : Expr(RecoveryExprClass, Empty), NumExprs(NumSubExprs) {}
6458
 
6459
  size_t numTrailingObjects(OverloadToken<Stmt *>) const { return NumExprs; }
6460
 
6461
  SourceLocation BeginLoc, EndLoc;
6462
  unsigned NumExprs;
6463
  friend TrailingObjects;
6464
  friend class ASTStmtReader;
6465
  friend class ASTStmtWriter;
6466
};
6467
 
6468
} // end namespace clang
6469
 
6470
#endif // LLVM_CLANG_AST_EXPR_H