Coverage Report

Created: 2018-07-19 20:53

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/include/clang/AST/Expr.h
Line
Count
Source (jump to first uncovered line)
1
//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
2
//
3
//                     The LLVM Compiler Infrastructure
4
//
5
// This file is distributed under the University of Illinois Open Source
6
// License. See LICENSE.TXT for details.
7
//
8
//===----------------------------------------------------------------------===//
9
//
10
//  This file defines the Expr interface and subclasses.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#ifndef LLVM_CLANG_AST_EXPR_H
15
#define LLVM_CLANG_AST_EXPR_H
16
17
#include "clang/AST/APValue.h"
18
#include "clang/AST/ASTVector.h"
19
#include "clang/AST/Decl.h"
20
#include "clang/AST/DeclAccessPair.h"
21
#include "clang/AST/OperationKinds.h"
22
#include "clang/AST/Stmt.h"
23
#include "clang/AST/TemplateBase.h"
24
#include "clang/AST/Type.h"
25
#include "clang/Basic/CharInfo.h"
26
#include "clang/Basic/LangOptions.h"
27
#include "clang/Basic/SyncScope.h"
28
#include "clang/Basic/TypeTraits.h"
29
#include "llvm/ADT/APFloat.h"
30
#include "llvm/ADT/APSInt.h"
31
#include "llvm/ADT/SmallVector.h"
32
#include "llvm/ADT/StringRef.h"
33
#include "llvm/Support/AtomicOrdering.h"
34
#include "llvm/Support/Compiler.h"
35
36
namespace clang {
37
  class APValue;
38
  class ASTContext;
39
  class BlockDecl;
40
  class CXXBaseSpecifier;
41
  class CXXMemberCallExpr;
42
  class CXXOperatorCallExpr;
43
  class CastExpr;
44
  class Decl;
45
  class IdentifierInfo;
46
  class MaterializeTemporaryExpr;
47
  class NamedDecl;
48
  class ObjCPropertyRefExpr;
49
  class OpaqueValueExpr;
50
  class ParmVarDecl;
51
  class StringLiteral;
52
  class TargetInfo;
53
  class ValueDecl;
54
55
/// A simple array of base specifiers.
56
typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
57
58
/// An adjustment to be made to the temporary created when emitting a
59
/// reference binding, which accesses a particular subobject of that temporary.
60
struct SubobjectAdjustment {
61
  enum {
62
    DerivedToBaseAdjustment,
63
    FieldAdjustment,
64
    MemberPointerAdjustment
65
  } Kind;
66
67
  struct DTB {
68
    const CastExpr *BasePath;
69
    const CXXRecordDecl *DerivedClass;
70
  };
71
72
  struct P {
73
    const MemberPointerType *MPT;
74
    Expr *RHS;
75
  };
76
77
  union {
78
    struct DTB DerivedToBase;
79
    FieldDecl *Field;
80
    struct P Ptr;
81
  };
82
83
  SubobjectAdjustment(const CastExpr *BasePath,
84
                      const CXXRecordDecl *DerivedClass)
85
3.32k
    : Kind(DerivedToBaseAdjustment) {
86
3.32k
    DerivedToBase.BasePath = BasePath;
87
3.32k
    DerivedToBase.DerivedClass = DerivedClass;
88
3.32k
  }
89
90
  SubobjectAdjustment(FieldDecl *Field)
91
2.81k
    : Kind(FieldAdjustment) {
92
2.81k
    this->Field = Field;
93
2.81k
  }
94
95
  SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
96
58
    : Kind(MemberPointerAdjustment) {
97
58
    this->Ptr.MPT = MPT;
98
58
    this->Ptr.RHS = RHS;
99
58
  }
100
};
101
102
/// Expr - This represents one expression.  Note that Expr's are subclasses of
103
/// Stmt.  This allows an expression to be transparently used any place a Stmt
104
/// is required.
105
///
106
class Expr : public Stmt {
107
  QualType TR;
108
109
protected:
110
  Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
111
       bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
112
    : Stmt(SC)
113
82.5M
  {
114
82.5M
    ExprBits.TypeDependent = TD;
115
82.5M
    ExprBits.ValueDependent = VD;
116
82.5M
    ExprBits.InstantiationDependent = ID;
117
82.5M
    ExprBits.ValueKind = VK;
118
82.5M
    ExprBits.ObjectKind = OK;
119
82.5M
    assert(ExprBits.ObjectKind == OK && "truncated kind");
120
82.5M
    ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
121
82.5M
    setType(T);
122
82.5M
  }
123
124
  /// Construct an empty expression.
125
460k
  explicit Expr(StmtClass SC, EmptyShell) : Stmt(SC) { }
126
127
public:
128
792M
  QualType getType() const { return TR; }
129
86.8M
  void setType(QualType t) {
130
86.8M
    // In C++, the type of an expression is always adjusted so that it
131
86.8M
    // will not have reference type (C++ [expr]p6). Use
132
86.8M
    // QualType::getNonReferenceType() to retrieve the non-reference
133
86.8M
    // type. Additionally, inspect Expr::isLvalue to determine whether
134
86.8M
    // an expression that is adjusted in this manner should be
135
86.8M
    // considered an lvalue.
136
86.8M
    assert((t.isNull() || !t->isReferenceType()) &&
137
86.8M
           "Expressions can't have reference type");
138
86.8M
139
86.8M
    TR = t;
140
86.8M
  }
141
142
  /// isValueDependent - Determines whether this expression is
143
  /// value-dependent (C++ [temp.dep.constexpr]). For example, the
144
  /// array bound of "Chars" in the following example is
145
  /// value-dependent.
146
  /// @code
147
  /// template<int Size, char (&Chars)[Size]> struct meta_string;
148
  /// @endcode
149
152M
  bool isValueDependent() const { return ExprBits.ValueDependent; }
150
151
  /// Set whether this expression is value-dependent or not.
152
479k
  void setValueDependent(bool VD) {
153
479k
    ExprBits.ValueDependent = VD;
154
479k
  }
155
156
  /// isTypeDependent - Determines whether this expression is
157
  /// type-dependent (C++ [temp.dep.expr]), which means that its type
158
  /// could change from one template instantiation to the next. For
159
  /// example, the expressions "x" and "x + y" are type-dependent in
160
  /// the following code, but "y" is not type-dependent:
161
  /// @code
162
  /// template<typename T>
163
  /// void add(T x, int y) {
164
  ///   x + y;
165
  /// }
166
  /// @endcode
167
155M
  bool isTypeDependent() const { return ExprBits.TypeDependent; }
168
169
  /// Set whether this expression is type-dependent or not.
170
462k
  void setTypeDependent(bool TD) {
171
462k
    ExprBits.TypeDependent = TD;
172
462k
  }
173
174
  /// Whether this expression is instantiation-dependent, meaning that
175
  /// it depends in some way on a template parameter, even if neither its type
176
  /// nor (constant) value can change due to the template instantiation.
177
  ///
178
  /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
179
  /// instantiation-dependent (since it involves a template parameter \c T), but
180
  /// is neither type- nor value-dependent, since the type of the inner
181
  /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
182
  /// \c sizeof is known.
183
  ///
184
  /// \code
185
  /// template<typename T>
186
  /// void f(T x, T y) {
187
  ///   sizeof(sizeof(T() + T());
188
  /// }
189
  /// \endcode
190
  ///
191
82.9M
  bool isInstantiationDependent() const {
192
82.9M
    return ExprBits.InstantiationDependent;
193
82.9M
  }
194
195
  /// Set whether this expression is instantiation-dependent or not.
196
479k
  void setInstantiationDependent(bool ID) {
197
479k
    ExprBits.InstantiationDependent = ID;
198
479k
  }
199
200
  /// Whether this expression contains an unexpanded parameter
201
  /// pack (for C++11 variadic templates).
202
  ///
203
  /// Given the following function template:
204
  ///
205
  /// \code
206
  /// template<typename F, typename ...Types>
207
  /// void forward(const F &f, Types &&...args) {
208
  ///   f(static_cast<Types&&>(args)...);
209
  /// }
210
  /// \endcode
211
  ///
212
  /// The expressions \c args and \c static_cast<Types&&>(args) both
213
  /// contain parameter packs.
214
86.4M
  bool containsUnexpandedParameterPack() const {
215
86.4M
    return ExprBits.ContainsUnexpandedParameterPack;
216
86.4M
  }
217
218
  /// Set the bit that describes whether this expression
219
  /// contains an unexpanded parameter pack.
220
3
  void setContainsUnexpandedParameterPack(bool PP = true) {
221
3
    ExprBits.ContainsUnexpandedParameterPack = PP;
222
3
  }
223
224
  /// getExprLoc - Return the preferred location for the arrow when diagnosing
225
  /// a problem with a generic expression.
226
  SourceLocation getExprLoc() const LLVM_READONLY;
227
228
  /// isUnusedResultAWarning - Return true if this immediate expression should
229
  /// be warned about if the result is unused.  If so, fill in expr, location,
230
  /// and ranges with expr to warn on and source locations/ranges appropriate
231
  /// for a warning.
232
  bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
233
                              SourceRange &R1, SourceRange &R2,
234
                              ASTContext &Ctx) const;
235
236
  /// isLValue - True if this expression is an "l-value" according to
237
  /// the rules of the current language.  C and C++ give somewhat
238
  /// different rules for this concept, but in general, the result of
239
  /// an l-value expression identifies a specific object whereas the
240
  /// result of an r-value expression is a value detached from any
241
  /// specific storage.
242
  ///
243
  /// C++11 divides the concept of "r-value" into pure r-values
244
  /// ("pr-values") and so-called expiring values ("x-values"), which
245
  /// identify specific objects that can be safely cannibalized for
246
  /// their resources.  This is an unfortunate abuse of terminology on
247
  /// the part of the C++ committee.  In Clang, when we say "r-value",
248
  /// we generally mean a pr-value.
249
828k
  bool isLValue() const { return getValueKind() == VK_LValue; }
250
33.8M
  bool isRValue() const { return getValueKind() == VK_RValue; }
251
422
  bool isXValue() const { return getValueKind() == VK_XValue; }
252
86.7M
  bool isGLValue() const { return getValueKind() != VK_RValue; }
253
254
  enum LValueClassification {
255
    LV_Valid,
256
    LV_NotObjectType,
257
    LV_IncompleteVoidType,
258
    LV_DuplicateVectorComponents,
259
    LV_InvalidExpression,
260
    LV_InvalidMessageExpression,
261
    LV_MemberFunction,
262
    LV_SubObjCPropertySetting,
263
    LV_ClassTemporary,
264
    LV_ArrayTemporary
265
  };
266
  /// Reasons why an expression might not be an l-value.
267
  LValueClassification ClassifyLValue(ASTContext &Ctx) const;
268
269
  enum isModifiableLvalueResult {
270
    MLV_Valid,
271
    MLV_NotObjectType,
272
    MLV_IncompleteVoidType,
273
    MLV_DuplicateVectorComponents,
274
    MLV_InvalidExpression,
275
    MLV_LValueCast,           // Specialized form of MLV_InvalidExpression.
276
    MLV_IncompleteType,
277
    MLV_ConstQualified,
278
    MLV_ConstQualifiedField,
279
    MLV_ConstAddrSpace,
280
    MLV_ArrayType,
281
    MLV_NoSetterProperty,
282
    MLV_MemberFunction,
283
    MLV_SubObjCPropertySetting,
284
    MLV_InvalidMessageExpression,
285
    MLV_ClassTemporary,
286
    MLV_ArrayTemporary
287
  };
288
  /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
289
  /// does not have an incomplete type, does not have a const-qualified type,
290
  /// and if it is a structure or union, does not have any member (including,
291
  /// recursively, any member or element of all contained aggregates or unions)
292
  /// with a const-qualified type.
293
  ///
294
  /// \param Loc [in,out] - A source location which *may* be filled
295
  /// in with the location of the expression making this a
296
  /// non-modifiable lvalue, if specified.
297
  isModifiableLvalueResult
298
  isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
299
300
  /// The return type of classify(). Represents the C++11 expression
301
  ///        taxonomy.
302
  class Classification {
303
  public:
304
    /// The various classification results. Most of these mean prvalue.
305
    enum Kinds {
306
      CL_LValue,
307
      CL_XValue,
308
      CL_Function, // Functions cannot be lvalues in C.
309
      CL_Void, // Void cannot be an lvalue in C.
310
      CL_AddressableVoid, // Void expression whose address can be taken in C.
311
      CL_DuplicateVectorComponents, // A vector shuffle with dupes.
312
      CL_MemberFunction, // An expression referring to a member function
313
      CL_SubObjCPropertySetting,
314
      CL_ClassTemporary, // A temporary of class type, or subobject thereof.
315
      CL_ArrayTemporary, // A temporary of array type.
316
      CL_ObjCMessageRValue, // ObjC message is an rvalue
317
      CL_PRValue // A prvalue for any other reason, of any other type
318
    };
319
    /// The results of modification testing.
320
    enum ModifiableType {
321
      CM_Untested, // testModifiable was false.
322
      CM_Modifiable,
323
      CM_RValue, // Not modifiable because it's an rvalue
324
      CM_Function, // Not modifiable because it's a function; C++ only
325
      CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
326
      CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
327
      CM_ConstQualified,
328
      CM_ConstQualifiedField,
329
      CM_ConstAddrSpace,
330
      CM_ArrayType,
331
      CM_IncompleteType
332
    };
333
334
  private:
335
    friend class Expr;
336
337
    unsigned short Kind;
338
    unsigned short Modifiable;
339
340
    explicit Classification(Kinds k, ModifiableType m)
341
      : Kind(k), Modifiable(m)
342
10.7M
    {}
343
344
  public:
345
1.11M
    Classification() {}
346
347
2.00M
    Kinds getKind() const { return static_cast<Kinds>(Kind); }
348
1.78M
    ModifiableType getModifiable() const {
349
1.78M
      assert(Modifiable != CM_Untested && "Did not test for modifiability.");
350
1.78M
      return static_cast<ModifiableType>(Modifiable);
351
1.78M
    }
352
5.74M
    bool isLValue() const { return Kind == CL_LValue; }
353
723k
    bool isXValue() const { return Kind == CL_XValue; }
354
0
    bool isGLValue() const { return Kind <= CL_XValue; }
355
797k
    bool isPRValue() const { return Kind >= CL_Function; }
356
2.51M
    bool isRValue() const { return Kind >= CL_XValue; }
357
0
    bool isModifiable() const { return getModifiable() == CM_Modifiable; }
358
359
    /// Create a simple, modifiably lvalue
360
347k
    static Classification makeSimpleLValue() {
361
347k
      return Classification(CL_LValue, CM_Modifiable);
362
347k
    }
363
364
  };
365
  /// Classify - Classify this expression according to the C++11
366
  ///        expression taxonomy.
367
  ///
368
  /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
369
  /// old lvalue vs rvalue. This function determines the type of expression this
370
  /// is. There are three expression types:
371
  /// - lvalues are classical lvalues as in C++03.
372
  /// - prvalues are equivalent to rvalues in C++03.
373
  /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
374
  ///   function returning an rvalue reference.
375
  /// lvalues and xvalues are collectively referred to as glvalues, while
376
  /// prvalues and xvalues together form rvalues.
377
8.63M
  Classification Classify(ASTContext &Ctx) const {
378
8.63M
    return ClassifyImpl(Ctx, nullptr);
379
8.63M
  }
380
381
  /// ClassifyModifiable - Classify this expression according to the
382
  ///        C++11 expression taxonomy, and see if it is valid on the left side
383
  ///        of an assignment.
384
  ///
385
  /// This function extends classify in that it also tests whether the
386
  /// expression is modifiable (C99 6.3.2.1p1).
387
  /// \param Loc A source location that might be filled with a relevant location
388
  ///            if the expression is not modifiable.
389
1.78M
  Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
390
1.78M
    return ClassifyImpl(Ctx, &Loc);
391
1.78M
  }
392
393
  /// getValueKindForType - Given a formal return or parameter type,
394
  /// give its value kind.
395
7.60M
  static ExprValueKind getValueKindForType(QualType T) {
396
7.60M
    if (const ReferenceType *RT = T->getAs<ReferenceType>())
397
398k
      return (isa<LValueReferenceType>(RT)
398
398k
                ? 
VK_LValue304k
399
398k
                : (RT->getPointeeType()->isFunctionType()
400
93.5k
                     ? 
VK_LValue3
:
VK_XValue93.5k
));
401
7.20M
    return VK_RValue;
402
7.20M
  }
403
404
  /// getValueKind - The value kind that this expression produces.
405
128M
  ExprValueKind getValueKind() const {
406
128M
    return static_cast<ExprValueKind>(ExprBits.ValueKind);
407
128M
  }
408
409
  /// getObjectKind - The object kind that this expression produces.
410
  /// Object kinds are meaningful only for expressions that yield an
411
  /// l-value or x-value.
412
6.89M
  ExprObjectKind getObjectKind() const {
413
6.89M
    return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
414
6.89M
  }
415
416
17.3k
  bool isOrdinaryOrBitFieldObject() const {
417
17.3k
    ExprObjectKind OK = getObjectKind();
418
17.3k
    return (OK == OK_Ordinary || 
OK == OK_BitField40
);
419
17.3k
  }
420
421
  /// setValueKind - Set the value kind produced by this expression.
422
3.14M
  void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
423
424
  /// setObjectKind - Set the object kind produced by this expression.
425
462k
  void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
426
427
private:
428
  Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
429
430
public:
431
432
  /// Returns true if this expression is a gl-value that
433
  /// potentially refers to a bit-field.
434
  ///
435
  /// In C++, whether a gl-value refers to a bitfield is essentially
436
  /// an aspect of the value-kind type system.
437
449k
  bool refersToBitField() const { return getObjectKind() == OK_BitField; }
438
439
  /// If this expression refers to a bit-field, retrieve the
440
  /// declaration of that bit-field.
441
  ///
442
  /// Note that this returns a non-null pointer in subtly different
443
  /// places than refersToBitField returns true.  In particular, this can
444
  /// return a non-null pointer even for r-values loaded from
445
  /// bit-fields, but it will return null for a conditional bit-field.
446
  FieldDecl *getSourceBitField();
447
448
373k
  const FieldDecl *getSourceBitField() const {
449
373k
    return const_cast<Expr*>(this)->getSourceBitField();
450
373k
  }
451
452
  Decl *getReferencedDeclOfCallee();
453
4.85k
  const Decl *getReferencedDeclOfCallee() const {
454
4.85k
    return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
455
4.85k
  }
456
457
  /// If this expression is an l-value for an Objective C
458
  /// property, find the underlying property reference expression.
459
  const ObjCPropertyRefExpr *getObjCProperty() const;
460
461
  /// Check if this expression is the ObjC 'self' implicit parameter.
462
  bool isObjCSelfExpr() const;
463
464
  /// Returns whether this expression refers to a vector element.
465
  bool refersToVectorElement() const;
466
467
  /// Returns whether this expression refers to a global register
468
  /// variable.
469
  bool refersToGlobalRegisterVar() const;
470
471
  /// Returns whether this expression has a placeholder type.
472
3.98M
  bool hasPlaceholderType() const {
473
3.98M
    return getType()->isPlaceholderType();
474
3.98M
  }
475
476
  /// Returns whether this expression has a specific placeholder type.
477
6.33k
  bool hasPlaceholderType(BuiltinType::Kind K) const {
478
6.33k
    assert(BuiltinType::isPlaceholderTypeKind(K));
479
6.33k
    if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
480
3.29k
      return BT->getKind() == K;
481
3.04k
    return false;
482
3.04k
  }
483
484
  /// isKnownToHaveBooleanValue - Return true if this is an integer expression
485
  /// that is known to return 0 or 1.  This happens for _Bool/bool expressions
486
  /// but also int expressions which are produced by things like comparisons in
487
  /// C.
488
  bool isKnownToHaveBooleanValue() const;
489
490
  /// isIntegerConstantExpr - Return true if this expression is a valid integer
491
  /// constant expression, and, if so, return its value in Result.  If not a
492
  /// valid i-c-e, return false and fill in Loc (if specified) with the location
493
  /// of the invalid expression.
494
  ///
495
  /// Note: This does not perform the implicit conversions required by C++11
496
  /// [expr.const]p5.
497
  bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
498
                             SourceLocation *Loc = nullptr,
499
                             bool isEvaluated = true) const;
500
  bool isIntegerConstantExpr(const ASTContext &Ctx,
501
                             SourceLocation *Loc = nullptr) const;
502
503
  /// isCXX98IntegralConstantExpr - Return true if this expression is an
504
  /// integral constant expression in C++98. Can only be used in C++.
505
  bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
506
507
  /// isCXX11ConstantExpr - Return true if this expression is a constant
508
  /// expression in C++11. Can only be used in C++.
509
  ///
510
  /// Note: This does not perform the implicit conversions required by C++11
511
  /// [expr.const]p5.
512
  bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
513
                           SourceLocation *Loc = nullptr) const;
514
515
  /// isPotentialConstantExpr - Return true if this function's definition
516
  /// might be usable in a constant expression in C++11, if it were marked
517
  /// constexpr. Return false if the function can never produce a constant
518
  /// expression, along with diagnostics describing why not.
519
  static bool isPotentialConstantExpr(const FunctionDecl *FD,
520
                                      SmallVectorImpl<
521
                                        PartialDiagnosticAt> &Diags);
522
523
  /// isPotentialConstantExprUnevaluted - Return true if this expression might
524
  /// be usable in a constant expression in C++11 in an unevaluated context, if
525
  /// it were in function FD marked constexpr. Return false if the function can
526
  /// never produce a constant expression, along with diagnostics describing
527
  /// why not.
528
  static bool isPotentialConstantExprUnevaluated(Expr *E,
529
                                                 const FunctionDecl *FD,
530
                                                 SmallVectorImpl<
531
                                                   PartialDiagnosticAt> &Diags);
532
533
  /// isConstantInitializer - Returns true if this expression can be emitted to
534
  /// IR as a constant, and thus can be used as a constant initializer in C.
535
  /// If this expression is not constant and Culprit is non-null,
536
  /// it is used to store the address of first non constant expr.
537
  bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
538
                             const Expr **Culprit = nullptr) const;
539
540
  /// EvalStatus is a struct with detailed info about an evaluation in progress.
541
  struct EvalStatus {
542
    /// Whether the evaluated expression has side effects.
543
    /// For example, (f() && 0) can be folded, but it still has side effects.
544
    bool HasSideEffects;
545
546
    /// Whether the evaluation hit undefined behavior.
547
    /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
548
    /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
549
    bool HasUndefinedBehavior;
550
551
    /// Diag - If this is non-null, it will be filled in with a stack of notes
552
    /// indicating why evaluation failed (or why it failed to produce a constant
553
    /// expression).
554
    /// If the expression is unfoldable, the notes will indicate why it's not
555
    /// foldable. If the expression is foldable, but not a constant expression,
556
    /// the notes will describes why it isn't a constant expression. If the
557
    /// expression *is* a constant expression, no notes will be produced.
558
    SmallVectorImpl<PartialDiagnosticAt> *Diag;
559
560
    EvalStatus()
561
27.9M
        : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
562
563
    // hasSideEffects - Return true if the evaluated expression has
564
    // side effects.
565
1.80k
    bool hasSideEffects() const {
566
1.80k
      return HasSideEffects;
567
1.80k
    }
568
  };
569
570
  /// EvalResult is a struct with detailed info about an evaluated expression.
571
  struct EvalResult : EvalStatus {
572
    /// Val - This is the value the expression can be folded to.
573
    APValue Val;
574
575
    // isGlobalLValue - Return true if the evaluated lvalue expression
576
    // is global.
577
    bool isGlobalLValue() const;
578
  };
579
580
  /// EvaluateAsRValue - Return true if this is a constant which we can fold to
581
  /// an rvalue using any crazy technique (that has nothing to do with language
582
  /// standards) that we want to, even if the expression has side-effects. If
583
  /// this function returns true, it returns the folded constant in Result. If
584
  /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
585
  /// applied.
586
  bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const;
587
588
  /// EvaluateAsBooleanCondition - Return true if this is a constant
589
  /// which we can fold and convert to a boolean condition using
590
  /// any crazy technique that we want to, even if the expression has
591
  /// side-effects.
592
  bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx) const;
593
594
  enum SideEffectsKind {
595
    SE_NoSideEffects,          ///< Strictly evaluate the expression.
596
    SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
597
                               ///< arbitrary unmodeled side effects.
598
    SE_AllowSideEffects        ///< Allow any unmodeled side effect.
599
  };
600
601
  /// EvaluateAsInt - Return true if this is a constant which we can fold and
602
  /// convert to an integer, using any crazy technique that we want to.
603
  bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx,
604
                     SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
605
606
  /// EvaluateAsFloat - Return true if this is a constant which we can fold and
607
  /// convert to a floating point value, using any crazy technique that we
608
  /// want to.
609
  bool
610
  EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
611
                  SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
612
613
  /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
614
  /// constant folded without side-effects, but discard the result.
615
  bool isEvaluatable(const ASTContext &Ctx,
616
                     SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
617
618
  /// HasSideEffects - This routine returns true for all those expressions
619
  /// which have any effect other than producing a value. Example is a function
620
  /// call, volatile variable read, or throwing an exception. If
621
  /// IncludePossibleEffects is false, this call treats certain expressions with
622
  /// potential side effects (such as function call-like expressions,
623
  /// instantiation-dependent expressions, or invocations from a macro) as not
624
  /// having side effects.
625
  bool HasSideEffects(const ASTContext &Ctx,
626
                      bool IncludePossibleEffects = true) const;
627
628
  /// Determine whether this expression involves a call to any function
629
  /// that is not trivial.
630
  bool hasNonTrivialCall(const ASTContext &Ctx) const;
631
632
  /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
633
  /// integer. This must be called on an expression that constant folds to an
634
  /// integer.
635
  llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx,
636
                    SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
637
638
  void EvaluateForOverflow(const ASTContext &Ctx) const;
639
640
  /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
641
  /// lvalue with link time known address, with no side-effects.
642
  bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const;
643
644
  /// EvaluateAsInitializer - Evaluate an expression as if it were the
645
  /// initializer of the given declaration. Returns true if the initializer
646
  /// can be folded to a constant, and produces any relevant notes. In C++11,
647
  /// notes will be produced if the expression is not a constant expression.
648
  bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
649
                             const VarDecl *VD,
650
                             SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
651
652
  /// EvaluateWithSubstitution - Evaluate an expression as if from the context
653
  /// of a call to the given function with the given arguments, inside an
654
  /// unevaluated context. Returns true if the expression could be folded to a
655
  /// constant.
656
  bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
657
                                const FunctionDecl *Callee,
658
                                ArrayRef<const Expr*> Args,
659
                                const Expr *This = nullptr) const;
660
661
  /// Indicates how the constant expression will be used.
662
  enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling };
663
664
  /// Evaluate an expression that is required to be a constant expression.
665
  bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
666
                              const ASTContext &Ctx) const;
667
668
  /// If the current Expr is a pointer, this will try to statically
669
  /// determine the number of bytes available where the pointer is pointing.
670
  /// Returns true if all of the above holds and we were able to figure out the
671
  /// size, false otherwise.
672
  ///
673
  /// \param Type - How to evaluate the size of the Expr, as defined by the
674
  /// "type" parameter of __builtin_object_size
675
  bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
676
                             unsigned Type) const;
677
678
  /// Enumeration used to describe the kind of Null pointer constant
679
  /// returned from \c isNullPointerConstant().
680
  enum NullPointerConstantKind {
681
    /// Expression is not a Null pointer constant.
682
    NPCK_NotNull = 0,
683
684
    /// Expression is a Null pointer constant built from a zero integer
685
    /// expression that is not a simple, possibly parenthesized, zero literal.
686
    /// C++ Core Issue 903 will classify these expressions as "not pointers"
687
    /// once it is adopted.
688
    /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
689
    NPCK_ZeroExpression,
690
691
    /// Expression is a Null pointer constant built from a literal zero.
692
    NPCK_ZeroLiteral,
693
694
    /// Expression is a C++11 nullptr.
695
    NPCK_CXX11_nullptr,
696
697
    /// Expression is a GNU-style __null constant.
698
    NPCK_GNUNull
699
  };
700
701
  /// Enumeration used to describe how \c isNullPointerConstant()
702
  /// should cope with value-dependent expressions.
703
  enum NullPointerConstantValueDependence {
704
    /// Specifies that the expression should never be value-dependent.
705
    NPC_NeverValueDependent = 0,
706
707
    /// Specifies that a value-dependent expression of integral or
708
    /// dependent type should be considered a null pointer constant.
709
    NPC_ValueDependentIsNull,
710
711
    /// Specifies that a value-dependent expression should be considered
712
    /// to never be a null pointer constant.
713
    NPC_ValueDependentIsNotNull
714
  };
715
716
  /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
717
  /// a Null pointer constant. The return value can further distinguish the
718
  /// kind of NULL pointer constant that was detected.
719
  NullPointerConstantKind isNullPointerConstant(
720
      ASTContext &Ctx,
721
      NullPointerConstantValueDependence NPC) const;
722
723
  /// isOBJCGCCandidate - Return true if this expression may be used in a read/
724
  /// write barrier.
725
  bool isOBJCGCCandidate(ASTContext &Ctx) const;
726
727
  /// Returns true if this expression is a bound member function.
728
  bool isBoundMemberFunction(ASTContext &Ctx) const;
729
730
  /// Given an expression of bound-member type, find the type
731
  /// of the member.  Returns null if this is an *overloaded* bound
732
  /// member expression.
733
  static QualType findBoundMemberType(const Expr *expr);
734
735
  /// IgnoreImpCasts - Skip past any implicit casts which might
736
  /// surround this expression.  Only skips ImplicitCastExprs.
737
  Expr *IgnoreImpCasts() LLVM_READONLY;
738
739
  /// IgnoreImplicit - Skip past any implicit AST nodes which might
740
  /// surround this expression.
741
393k
  Expr *IgnoreImplicit() LLVM_READONLY {
742
393k
    return cast<Expr>(Stmt::IgnoreImplicit());
743
393k
  }
744
745
26.1k
  const Expr *IgnoreImplicit() const LLVM_READONLY {
746
26.1k
    return const_cast<Expr*>(this)->IgnoreImplicit();
747
26.1k
  }
748
749
  /// IgnoreParens - Ignore parentheses.  If this Expr is a ParenExpr, return
750
  ///  its subexpression.  If that subexpression is also a ParenExpr,
751
  ///  then this method recursively returns its subexpression, and so forth.
752
  ///  Otherwise, the method returns the current Expr.
753
  Expr *IgnoreParens() LLVM_READONLY;
754
755
  /// IgnoreParenCasts - Ignore parentheses and casts.  Strip off any ParenExpr
756
  /// or CastExprs, returning their operand.
757
  Expr *IgnoreParenCasts() LLVM_READONLY;
758
759
  /// Ignore casts.  Strip off any CastExprs, returning their operand.
760
  Expr *IgnoreCasts() LLVM_READONLY;
761
762
  /// IgnoreParenImpCasts - Ignore parentheses and implicit casts.  Strip off
763
  /// any ParenExpr or ImplicitCastExprs, returning their operand.
764
  Expr *IgnoreParenImpCasts() LLVM_READONLY;
765
766
  /// IgnoreConversionOperator - Ignore conversion operator. If this Expr is a
767
  /// call to a conversion operator, return the argument.
768
  Expr *IgnoreConversionOperator() LLVM_READONLY;
769
770
0
  const Expr *IgnoreConversionOperator() const LLVM_READONLY {
771
0
    return const_cast<Expr*>(this)->IgnoreConversionOperator();
772
0
  }
773
774
31.0M
  const Expr *IgnoreParenImpCasts() const LLVM_READONLY {
775
31.0M
    return const_cast<Expr*>(this)->IgnoreParenImpCasts();
776
31.0M
  }
777
778
  /// Ignore parentheses and lvalue casts.  Strip off any ParenExpr and
779
  /// CastExprs that represent lvalue casts, returning their operand.
780
  Expr *IgnoreParenLValueCasts() LLVM_READONLY;
781
782
1.25k
  const Expr *IgnoreParenLValueCasts() const LLVM_READONLY {
783
1.25k
    return const_cast<Expr*>(this)->IgnoreParenLValueCasts();
784
1.25k
  }
785
786
  /// IgnoreParenNoopCasts - Ignore parentheses and casts that do not change the
787
  /// value (including ptr->int casts of the same size).  Strip off any
788
  /// ParenExpr or CastExprs, returning their operand.
789
  Expr *IgnoreParenNoopCasts(ASTContext &Ctx) LLVM_READONLY;
790
791
  /// Ignore parentheses and derived-to-base casts.
792
  Expr *ignoreParenBaseCasts() LLVM_READONLY;
793
794
96.2k
  const Expr *ignoreParenBaseCasts() const LLVM_READONLY {
795
96.2k
    return const_cast<Expr*>(this)->ignoreParenBaseCasts();
796
96.2k
  }
797
798
  /// Determine whether this expression is a default function argument.
799
  ///
800
  /// Default arguments are implicitly generated in the abstract syntax tree
801
  /// by semantic analysis for function calls, object constructions, etc. in
802
  /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
803
  /// this routine also looks through any implicit casts to determine whether
804
  /// the expression is a default argument.
805
  bool isDefaultArgument() const;
806
807
  /// Determine whether the result of this expression is a
808
  /// temporary object of the given class type.
809
  bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
810
811
  /// Whether this expression is an implicit reference to 'this' in C++.
812
  bool isImplicitCXXThis() const;
813
814
970k
  const Expr *IgnoreImpCasts() const LLVM_READONLY {
815
970k
    return const_cast<Expr*>(this)->IgnoreImpCasts();
816
970k
  }
817
28.0M
  const Expr *IgnoreParens() const LLVM_READONLY {
818
28.0M
    return const_cast<Expr*>(this)->IgnoreParens();
819
28.0M
  }
820
1.03M
  const Expr *IgnoreParenCasts() const LLVM_READONLY {
821
1.03M
    return const_cast<Expr*>(this)->IgnoreParenCasts();
822
1.03M
  }
823
  /// Strip off casts, but keep parentheses.
824
944
  const Expr *IgnoreCasts() const LLVM_READONLY {
825
944
    return const_cast<Expr*>(this)->IgnoreCasts();
826
944
  }
827
828
2.01M
  const Expr *IgnoreParenNoopCasts(ASTContext &Ctx) const LLVM_READONLY {
829
2.01M
    return const_cast<Expr*>(this)->IgnoreParenNoopCasts(Ctx);
830
2.01M
  }
831
832
  static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
833
834
  /// For an expression of class type or pointer to class type,
835
  /// return the most derived class decl the expression is known to refer to.
836
  ///
837
  /// If this expression is a cast, this method looks through it to find the
838
  /// most derived decl that can be inferred from the expression.
839
  /// This is valid because derived-to-base conversions have undefined
840
  /// behavior if the object isn't dynamically of the derived type.
841
  const CXXRecordDecl *getBestDynamicClassType() const;
842
843
  /// Get the inner expression that determines the best dynamic class.
844
  /// If this is a prvalue, we guarantee that it is of the most-derived type
845
  /// for the object itself.
846
  const Expr *getBestDynamicClassTypeExpr() const;
847
848
  /// Walk outwards from an expression we want to bind a reference to and
849
  /// find the expression whose lifetime needs to be extended. Record
850
  /// the LHSs of comma expressions and adjustments needed along the path.
851
  const Expr *skipRValueSubobjectAdjustments(
852
      SmallVectorImpl<const Expr *> &CommaLHS,
853
      SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
854
174k
  const Expr *skipRValueSubobjectAdjustments() const {
855
174k
    SmallVector<const Expr *, 8> CommaLHSs;
856
174k
    SmallVector<SubobjectAdjustment, 8> Adjustments;
857
174k
    return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
858
174k
  }
859
860
62.5M
  static bool classof(const Stmt *T) {
861
62.5M
    return T->getStmtClass() >= firstExprConstant &&
862
62.5M
           
T->getStmtClass() <= lastExprConstant57.2M
;
863
62.5M
  }
864
};
865
866
//===----------------------------------------------------------------------===//
867
// Primary Expressions.
868
//===----------------------------------------------------------------------===//
869
870
/// OpaqueValueExpr - An expression referring to an opaque object of a
871
/// fixed type and value class.  These don't correspond to concrete
872
/// syntax; instead they're used to express operations (usually copy
873
/// operations) on values whose source is generally obvious from
874
/// context.
875
class OpaqueValueExpr : public Expr {
876
  friend class ASTStmtReader;
877
  Expr *SourceExpr;
878
  SourceLocation Loc;
879
880
public:
881
  OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
882
                  ExprObjectKind OK = OK_Ordinary,
883
                  Expr *SourceExpr = nullptr)
884
    : Expr(OpaqueValueExprClass, T, VK, OK,
885
           T->isDependentType() ||
886
           (SourceExpr && SourceExpr->isTypeDependent()),
887
           T->isDependentType() || 
888
           (SourceExpr && SourceExpr->isValueDependent()),
889
           T->isInstantiationDependentType() ||
890
           (SourceExpr && SourceExpr->isInstantiationDependent()),
891
           false),
892
500k
      SourceExpr(SourceExpr), Loc(Loc) {
893
500k
    setIsUnique(false);
894
500k
  }
895
896
  /// Given an expression which invokes a copy constructor --- i.e.  a
897
  /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
898
  /// find the OpaqueValueExpr that's the source of the construction.
899
  static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
900
901
  explicit OpaqueValueExpr(EmptyShell Empty)
902
621
    : Expr(OpaqueValueExprClass, Empty) { }
903
904
  /// Retrieve the location of this expression.
905
619
  SourceLocation getLocation() const { return Loc; }
906
907
432k
  SourceLocation getLocStart() const LLVM_READONLY {
908
432k
    return SourceExpr ? 
SourceExpr->getLocStart()42.2k
:
Loc390k
;
909
432k
  }
910
8.12k
  SourceLocation getLocEnd() const LLVM_READONLY {
911
8.12k
    return SourceExpr ? 
SourceExpr->getLocEnd()6.26k
:
Loc1.85k
;
912
8.12k
  }
913
24.9k
  SourceLocation getExprLoc() const LLVM_READONLY {
914
24.9k
    if (SourceExpr) 
return SourceExpr->getExprLoc()16.1k
;
915
8.80k
    return Loc;
916
8.80k
  }
917
918
32.3k
  child_range children() {
919
32.3k
    return child_range(child_iterator(), child_iterator());
920
32.3k
  }
921
922
0
  const_child_range children() const {
923
0
    return const_child_range(const_child_iterator(), const_child_iterator());
924
0
  }
925
926
  /// The source expression of an opaque value expression is the
927
  /// expression which originally generated the value.  This is
928
  /// provided as a convenience for analyses that don't wish to
929
  /// precisely model the execution behavior of the program.
930
  ///
931
  /// The source expression is typically set when building the
932
  /// expression which binds the opaque value expression in the first
933
  /// place.
934
22.1k
  Expr *getSourceExpr() const { return SourceExpr; }
935
936
505k
  void setIsUnique(bool V) {
937
505k
    assert((!V || SourceExpr) &&
938
505k
           "unique OVEs are expected to have source expressions");
939
505k
    OpaqueValueExprBits.IsUnique = V;
940
505k
  }
941
942
1.30k
  bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
943
944
6.95M
  static bool classof(const Stmt *T) {
945
6.95M
    return T->getStmtClass() == OpaqueValueExprClass;
946
6.95M
  }
947
};
948
949
/// A reference to a declared variable, function, enum, etc.
950
/// [C99 6.5.1p2]
951
///
952
/// This encodes all the information about how a declaration is referenced
953
/// within an expression.
954
///
955
/// There are several optional constructs attached to DeclRefExprs only when
956
/// they apply in order to conserve memory. These are laid out past the end of
957
/// the object, and flags in the DeclRefExprBitfield track whether they exist:
958
///
959
///   DeclRefExprBits.HasQualifier:
960
///       Specifies when this declaration reference expression has a C++
961
///       nested-name-specifier.
962
///   DeclRefExprBits.HasFoundDecl:
963
///       Specifies when this declaration reference expression has a record of
964
///       a NamedDecl (different from the referenced ValueDecl) which was found
965
///       during name lookup and/or overload resolution.
966
///   DeclRefExprBits.HasTemplateKWAndArgsInfo:
967
///       Specifies when this declaration reference expression has an explicit
968
///       C++ template keyword and/or template argument list.
969
///   DeclRefExprBits.RefersToEnclosingVariableOrCapture
970
///       Specifies when this declaration reference expression (validly)
971
///       refers to an enclosed local or a captured variable.
972
class DeclRefExpr final
973
    : public Expr,
974
      private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
975
                                    NamedDecl *, ASTTemplateKWAndArgsInfo,
976
                                    TemplateArgumentLoc> {
977
  /// The declaration that we are referencing.
978
  ValueDecl *D;
979
980
  /// The location of the declaration name itself.
981
  SourceLocation Loc;
982
983
  /// Provides source/type location info for the declaration name
984
  /// embedded in D.
985
  DeclarationNameLoc DNLoc;
986
987
945k
  size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
988
945k
    return hasQualifier() ? 
1619k
:
0325k
;
989
945k
  }
990
991
673k
  size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
992
673k
    return hasFoundDecl() ? 
1671k
:
02.28k
;
993
673k
  }
994
995
166k
  size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
996
166k
    return hasTemplateKWAndArgsInfo() ? 1 : 
00
;
997
166k
  }
998
999
  /// Test whether there is a distinct FoundDecl attached to the end of
1000
  /// this DRE.
1001
1.48M
  bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1002
1003
  DeclRefExpr(const ASTContext &Ctx,
1004
              NestedNameSpecifierLoc QualifierLoc,
1005
              SourceLocation TemplateKWLoc,
1006
              ValueDecl *D, bool RefersToEnlosingVariableOrCapture,
1007
              const DeclarationNameInfo &NameInfo,
1008
              NamedDecl *FoundD,
1009
              const TemplateArgumentListInfo *TemplateArgs,
1010
              QualType T, ExprValueKind VK);
1011
1012
  /// Construct an empty declaration reference expression.
1013
  explicit DeclRefExpr(EmptyShell Empty)
1014
129k
    : Expr(DeclRefExprClass, Empty) { }
1015
1016
  /// Computes the type- and value-dependence flags for this
1017
  /// declaration reference expression.
1018
  void computeDependence(const ASTContext &C);
1019
1020
public:
1021
  DeclRefExpr(ValueDecl *D, bool RefersToEnclosingVariableOrCapture, QualType T,
1022
              ExprValueKind VK, SourceLocation L,
1023
              const DeclarationNameLoc &LocInfo = DeclarationNameLoc())
1024
    : Expr(DeclRefExprClass, T, VK, OK_Ordinary, false, false, false, false),
1025
1.55M
      D(D), Loc(L), DNLoc(LocInfo) {
1026
1.55M
    DeclRefExprBits.HasQualifier = 0;
1027
1.55M
    DeclRefExprBits.HasTemplateKWAndArgsInfo = 0;
1028
1.55M
    DeclRefExprBits.HasFoundDecl = 0;
1029
1.55M
    DeclRefExprBits.HadMultipleCandidates = 0;
1030
1.55M
    DeclRefExprBits.RefersToEnclosingVariableOrCapture =
1031
1.55M
        RefersToEnclosingVariableOrCapture;
1032
1.55M
    computeDependence(D->getASTContext());
1033
1.55M
  }
1034
1035
  static DeclRefExpr *
1036
  Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1037
         SourceLocation TemplateKWLoc, ValueDecl *D,
1038
         bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1039
         QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1040
         const TemplateArgumentListInfo *TemplateArgs = nullptr);
1041
1042
  static DeclRefExpr *
1043
  Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1044
         SourceLocation TemplateKWLoc, ValueDecl *D,
1045
         bool RefersToEnclosingVariableOrCapture,
1046
         const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1047
         NamedDecl *FoundD = nullptr,
1048
         const TemplateArgumentListInfo *TemplateArgs = nullptr);
1049
1050
  /// Construct an empty declaration reference expression.
1051
  static DeclRefExpr *CreateEmpty(const ASTContext &Context,
1052
                                  bool HasQualifier,
1053
                                  bool HasFoundDecl,
1054
                                  bool HasTemplateKWAndArgsInfo,
1055
                                  unsigned NumTemplateArgs);
1056
1057
108M
  ValueDecl *getDecl() { return D; }
1058
152M
  const ValueDecl *getDecl() const { return D; }
1059
129k
  void setDecl(ValueDecl *NewD) { D = NewD; }
1060
1061
106M
  DeclarationNameInfo getNameInfo() const {
1062
106M
    return DeclarationNameInfo(getDecl()->getDeclName(), Loc, DNLoc);
1063
106M
  }
1064
1065
19.3M
  SourceLocation getLocation() const { return Loc; }
1066
129k
  void setLocation(SourceLocation L) { Loc = L; }
1067
  SourceLocation getLocStart() const LLVM_READONLY;
1068
  SourceLocation getLocEnd() const LLVM_READONLY;
1069
1070
  /// Determine whether this declaration reference was preceded by a
1071
  /// C++ nested-name-specifier, e.g., \c N::foo.
1072
118M
  bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1073
1074
  /// If the name was qualified, retrieves the nested-name-specifier
1075
  /// that precedes the name, with source-location information.
1076
10.9M
  NestedNameSpecifierLoc getQualifierLoc() const {
1077
10.9M
    if (!hasQualifier())
1078
3.16M
      return NestedNameSpecifierLoc();
1079
7.77M
    return *getTrailingObjects<NestedNameSpecifierLoc>();
1080
7.77M
  }
1081
1082
  /// If the name was qualified, retrieves the nested-name-specifier
1083
  /// that precedes the name. Otherwise, returns NULL.
1084
552k
  NestedNameSpecifier *getQualifier() const {
1085
552k
    return getQualifierLoc().getNestedNameSpecifier();
1086
552k
  }
1087
1088
  /// Get the NamedDecl through which this reference occurred.
1089
  ///
1090
  /// This Decl may be different from the ValueDecl actually referred to in the
1091
  /// presence of using declarations, etc. It always returns non-NULL, and may
1092
  /// simple return the ValueDecl when appropriate.
1093
1094
679k
  NamedDecl *getFoundDecl() {
1095
679k
    return hasFoundDecl() ? 
*getTrailingObjects<NamedDecl *>()2.76k
:
D676k
;
1096
679k
  }
1097
1098
  /// Get the NamedDecl through which this reference occurred.
1099
  /// See non-const variant.
1100
1.48k
  const NamedDecl *getFoundDecl() const {
1101
1.48k
    return hasFoundDecl() ? 
*getTrailingObjects<NamedDecl *>()138
:
D1.34k
;
1102
1.48k
  }
1103
1104
11.8M
  bool hasTemplateKWAndArgsInfo() const {
1105
11.8M
    return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1106
11.8M
  }
1107
1108
  /// Retrieve the location of the template keyword preceding
1109
  /// this name, if any.
1110
96.4k
  SourceLocation getTemplateKeywordLoc() const {
1111
96.4k
    if (!hasTemplateKWAndArgsInfo()) 
return SourceLocation()95.6k
;
1112
846
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1113
846
  }
1114
1115
  /// Retrieve the location of the left angle bracket starting the
1116
  /// explicit template argument list following the name, if any.
1117
10.1M
  SourceLocation getLAngleLoc() const {
1118
10.1M
    if (!hasTemplateKWAndArgsInfo()) 
return SourceLocation()10.0M
;
1119
176k
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1120
176k
  }
1121
1122
  /// Retrieve the location of the right angle bracket ending the
1123
  /// explicit template argument list following the name, if any.
1124
210k
  SourceLocation getRAngleLoc() const {
1125
210k
    if (!hasTemplateKWAndArgsInfo()) 
return SourceLocation()48.7k
;
1126
161k
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1127
161k
  }
1128
1129
  /// Determines whether the name in this declaration reference
1130
  /// was preceded by the template keyword.
1131
96.2k
  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1132
1133
  /// Determines whether this declaration reference was followed by an
1134
  /// explicit template argument list.
1135
10.1M
  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1136
1137
  /// Copies the template arguments (if present) into the given
1138
  /// structure.
1139
0
  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1140
0
    if (hasExplicitTemplateArgs())
1141
0
      getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1142
0
          getTrailingObjects<TemplateArgumentLoc>(), List);
1143
0
  }
1144
1145
  /// Retrieve the template arguments provided as part of this
1146
  /// template-id.
1147
128k
  const TemplateArgumentLoc *getTemplateArgs() const {
1148
128k
    if (!hasExplicitTemplateArgs())
1149
124k
      return nullptr;
1150
3.78k
1151
3.78k
    return getTrailingObjects<TemplateArgumentLoc>();
1152
3.78k
  }
1153
1154
  /// Retrieve the number of template arguments provided as part of this
1155
  /// template-id.
1156
128k
  unsigned getNumTemplateArgs() const {
1157
128k
    if (!hasExplicitTemplateArgs())
1158
124k
      return 0;
1159
4.53k
1160
4.53k
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1161
4.53k
  }
1162
1163
842
  ArrayRef<TemplateArgumentLoc> template_arguments() const {
1164
842
    return {getTemplateArgs(), getNumTemplateArgs()};
1165
842
  }
1166
1167
  /// Returns true if this expression refers to a function that
1168
  /// was resolved from an overloaded set having size greater than 1.
1169
219k
  bool hadMultipleCandidates() const {
1170
219k
    return DeclRefExprBits.HadMultipleCandidates;
1171
219k
  }
1172
  /// Sets the flag telling whether this expression refers to
1173
  /// a function that was resolved from an overloaded set having size
1174
  /// greater than 1.
1175
868k
  void setHadMultipleCandidates(bool V = true) {
1176
868k
    DeclRefExprBits.HadMultipleCandidates = V;
1177
868k
  }
1178
1179
  /// Does this DeclRefExpr refer to an enclosing local or a captured
1180
  /// variable?
1181
3.65M
  bool refersToEnclosingVariableOrCapture() const {
1182
3.65M
    return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1183
3.65M
  }
1184
1185
56.0M
  static bool classof(const Stmt *T) {
1186
56.0M
    return T->getStmtClass() == DeclRefExprClass;
1187
56.0M
  }
1188
1189
  // Iterators
1190
19.9M
  child_range children() {
1191
19.9M
    return child_range(child_iterator(), child_iterator());
1192
19.9M
  }
1193
1194
0
  const_child_range children() const {
1195
0
    return const_child_range(const_child_iterator(), const_child_iterator());
1196
0
  }
1197
1198
  friend TrailingObjects;
1199
  friend class ASTStmtReader;
1200
  friend class ASTStmtWriter;
1201
};
1202
1203
/// [C99 6.4.2.2] - A predefined identifier such as __func__.
1204
class PredefinedExpr : public Expr {
1205
public:
1206
  enum IdentType {
1207
    Func,
1208
    Function,
1209
    LFunction,  // Same as Function, but as wide string.
1210
    FuncDName,
1211
    FuncSig,
1212
    PrettyFunction,
1213
    /// The same as PrettyFunction, except that the
1214
    /// 'virtual' keyword is omitted for virtual member functions.
1215
    PrettyFunctionNoVirtual
1216
  };
1217
1218
private:
1219
  SourceLocation Loc;
1220
  IdentType Type;
1221
  Stmt *FnName;
1222
1223
public:
1224
  PredefinedExpr(SourceLocation L, QualType FNTy, IdentType IT,
1225
                 StringLiteral *SL);
1226
1227
  /// Construct an empty predefined expression.
1228
  explicit PredefinedExpr(EmptyShell Empty)
1229
16
      : Expr(PredefinedExprClass, Empty), Loc(), Type(Func), FnName(nullptr) {}
1230
1231
2.27k
  IdentType getIdentType() const { return Type; }
1232
1233
90
  SourceLocation getLocation() const { return Loc; }
1234
16
  void setLocation(SourceLocation L) { Loc = L; }
1235
1236
  StringLiteral *getFunctionName();
1237
2.13k
  const StringLiteral *getFunctionName() const {
1238
2.13k
    return const_cast<PredefinedExpr *>(this)->getFunctionName();
1239
2.13k
  }
1240
1241
  static StringRef getIdentTypeName(IdentType IT);
1242
  static std::string ComputeName(IdentType IT, const Decl *CurrentDecl);
1243
1244
25.2k
  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1245
127
  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1246
1247
86.2k
  static bool classof(const Stmt *T) {
1248
86.2k
    return T->getStmtClass() == PredefinedExprClass;
1249
86.2k
  }
1250
1251
  // Iterators
1252
9.97k
  child_range children() { return child_range(&FnName, &FnName + 1); }
1253
0
  const_child_range children() const {
1254
0
    return const_child_range(&FnName, &FnName + 1);
1255
0
  }
1256
1257
  friend class ASTStmtReader;
1258
};
1259
1260
/// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1261
/// leaking memory.
1262
///
1263
/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1264
/// to represent these numbers.  Unfortunately, when we use a BumpPtrAllocator
1265
/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1266
/// the APFloat/APInt values will never get freed. APNumericStorage uses
1267
/// ASTContext's allocator for memory allocation.
1268
class APNumericStorage {
1269
  union {
1270
    uint64_t VAL;    ///< Used to store the <= 64 bits integer value.
1271
    uint64_t *pVal;  ///< Used to store the >64 bits integer value.
1272
  };
1273
  unsigned BitWidth;
1274
1275
6.24M
  bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1276
1277
  APNumericStorage(const APNumericStorage &) = delete;
1278
  void operator=(const APNumericStorage &) = delete;
1279
1280
protected:
1281
6.24M
  APNumericStorage() : VAL(0), BitWidth(0) { }
1282
1283
12.4M
  llvm::APInt getIntValue() const {
1284
12.4M
    unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1285
12.4M
    if (NumWords > 1)
1286
950
      return llvm::APInt(BitWidth, NumWords, pVal);
1287
12.4M
    else
1288
12.4M
      return llvm::APInt(BitWidth, VAL);
1289
12.4M
  }
1290
  void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1291
};
1292
1293
class APIntStorage : private APNumericStorage {
1294
public:
1295
12.1M
  llvm::APInt getValue() const { return getIntValue(); }
1296
6.00M
  void setValue(const ASTContext &C, const llvm::APInt &Val) {
1297
6.00M
    setIntValue(C, Val);
1298
6.00M
  }
1299
};
1300
1301
class APFloatStorage : private APNumericStorage {
1302
public:
1303
295k
  llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1304
295k
    return llvm::APFloat(Semantics, getIntValue());
1305
295k
  }
1306
234k
  void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1307
234k
    setIntValue(C, Val.bitcastToAPInt());
1308
234k
  }
1309
};
1310
1311
class IntegerLiteral : public Expr, public APIntStorage {
1312
  SourceLocation Loc;
1313
1314
  /// Construct an empty integer literal.
1315
  explicit IntegerLiteral(EmptyShell Empty)
1316
69.0k
    : Expr(IntegerLiteralClass, Empty) { }
1317
1318
public:
1319
  // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1320
  // or UnsignedLongLongTy
1321
  IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1322
                 SourceLocation l);
1323
1324
  /// Returns a new integer literal with value 'V' and type 'type'.
1325
  /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1326
  /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1327
  /// \param V - the value that the returned integer literal contains.
1328
  static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1329
                                QualType type, SourceLocation l);
1330
  /// Returns a new empty integer literal.
1331
  static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1332
1333
22.4M
  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1334
727k
  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1335
1336
  /// Retrieve the location of the literal.
1337
87.0k
  SourceLocation getLocation() const { return Loc; }
1338
1339
69.0k
  void setLocation(SourceLocation Location) { Loc = Location; }
1340
1341
13.2M
  static bool classof(const Stmt *T) {
1342
13.2M
    return T->getStmtClass() == IntegerLiteralClass;
1343
13.2M
  }
1344
1345
  // Iterators
1346
13.0M
  child_range children() {
1347
13.0M
    return child_range(child_iterator(), child_iterator());
1348
13.0M
  }
1349
0
  const_child_range children() const {
1350
0
    return const_child_range(const_child_iterator(), const_child_iterator());
1351
0
  }
1352
};
1353
1354
class FixedPointLiteral : public Expr, public APIntStorage {
1355
  SourceLocation Loc;
1356
  unsigned Scale;
1357
1358
  /// \brief Construct an empty integer literal.
1359
  explicit FixedPointLiteral(EmptyShell Empty)
1360
      : Expr(FixedPointLiteralClass, Empty) {}
1361
1362
 public:
1363
  FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1364
                    SourceLocation l, unsigned Scale);
1365
1366
  // Store the int as is without any bit shifting.
1367
  static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1368
                                             const llvm::APInt &V,
1369
                                             QualType type, SourceLocation l,
1370
                                             unsigned Scale);
1371
1372
818
  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1373
83
  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1374
1375
  /// \brief Retrieve the location of the literal.
1376
0
  SourceLocation getLocation() const { return Loc; }
1377
1378
0
  void setLocation(SourceLocation Location) { Loc = Location; }
1379
1380
0
  static bool classof(const Stmt *T) {
1381
0
    return T->getStmtClass() == FixedPointLiteralClass;
1382
0
  }
1383
1384
  std::string getValueAsString(unsigned Radix) const;
1385
1386
  // Iterators
1387
605
  child_range children() {
1388
605
    return child_range(child_iterator(), child_iterator());
1389
605
  }
1390
0
  const_child_range children() const {
1391
0
    return const_child_range(const_child_iterator(), const_child_iterator());
1392
0
  }
1393
};
1394
1395
class CharacterLiteral : public Expr {
1396
public:
1397
  enum CharacterKind {
1398
    Ascii,
1399
    Wide,
1400
    UTF8,
1401
    UTF16,
1402
    UTF32
1403
  };
1404
1405
private:
1406
  unsigned Value;
1407
  SourceLocation Loc;
1408
public:
1409
  // type should be IntTy
1410
  CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1411
                   SourceLocation l)
1412
    : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1413
           false, false),
1414
75.2k
      Value(value), Loc(l) {
1415
75.2k
    CharacterLiteralBits.Kind = kind;
1416
75.2k
  }
1417
1418
  /// Construct an empty character literal.
1419
207
  CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1420
1421
221
  SourceLocation getLocation() const { return Loc; }
1422
1.05k
  CharacterKind getKind() const {
1423
1.05k
    return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1424
1.05k
  }
1425
1426
408k
  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1427
15.1k
  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1428
1429
188k
  unsigned getValue() const { return Value; }
1430
1431
207
  void setLocation(SourceLocation Location) { Loc = Location; }
1432
207
  void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1433
207
  void setValue(unsigned Val) { Value = Val; }
1434
1435
1.39M
  static bool classof(const Stmt *T) {
1436
1.39M
    return T->getStmtClass() == CharacterLiteralClass;
1437
1.39M
  }
1438
1439
  // Iterators
1440
199k
  child_range children() {
1441
199k
    return child_range(child_iterator(), child_iterator());
1442
199k
  }
1443
0
  const_child_range children() const {
1444
0
    return const_child_range(const_child_iterator(), const_child_iterator());
1445
0
  }
1446
};
1447
1448
class FloatingLiteral : public Expr, private APFloatStorage {
1449
  SourceLocation Loc;
1450
1451
  FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1452
                  QualType Type, SourceLocation L);
1453
1454
  /// Construct an empty floating-point literal.
1455
  explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1456
1457
public:
1458
  static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1459
                                 bool isexact, QualType Type, SourceLocation L);
1460
  static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1461
1462
295k
  llvm::APFloat getValue() const {
1463
295k
    return APFloatStorage::getValue(getSemantics());
1464
295k
  }
1465
234k
  void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1466
234k
    assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics");
1467
234k
    APFloatStorage::setValue(C, Val);
1468
234k
  }
1469
1470
  /// Get a raw enumeration value representing the floating-point semantics of
1471
  /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1472
1.03k
  APFloatSemantics getRawSemantics() const {
1473
1.03k
    return static_cast<APFloatSemantics>(FloatingLiteralBits.Semantics);
1474
1.03k
  }
1475
1476
  /// Set the raw enumeration value representing the floating-point semantics of
1477
  /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1478
1.85k
  void setRawSemantics(APFloatSemantics Sem) {
1479
1.85k
    FloatingLiteralBits.Semantics = Sem;
1480
1.85k
  }
1481
1482
  /// Return the APFloat semantics this literal uses.
1483
  const llvm::fltSemantics &getSemantics() const;
1484
1485
  /// Set the APFloat semantics this literal uses.
1486
  void setSemantics(const llvm::fltSemantics &Sem);
1487
1488
1.80k
  bool isExact() const { return FloatingLiteralBits.IsExact; }
1489
927
  void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1490
1491
  /// getValueAsApproximateDouble - This returns the value as an inaccurate
1492
  /// double.  Note that this may cause loss of precision, but is useful for
1493
  /// debugging dumps, etc.
1494
  double getValueAsApproximateDouble() const;
1495
1496
1.07k
  SourceLocation getLocation() const { return Loc; }
1497
927
  void setLocation(SourceLocation L) { Loc = L; }
1498
1499
1.00M
  SourceLocation getLocStart() const LLVM_READONLY { return Loc; }
1500
36.9k
  SourceLocation getLocEnd() const LLVM_READONLY { return Loc; }
1501
1502
143k
  static bool classof(const Stmt *T) {
1503
143k
    return T->getStmtClass() == FloatingLiteralClass;
1504
143k
  }
1505
1506
  // Iterators
1507
668k
  child_range children() {
1508
668k
    return child_range(child_iterator(), child_iterator());
1509
668k
  }
1510
0
  const_child_range children() const {
1511
0
    return const_child_range(const_child_iterator(), const_child_iterator());
1512
0
  }
1513
};
1514
1515
/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1516
/// like "1.0i".  We represent these as a wrapper around FloatingLiteral and
1517
/// IntegerLiteral classes.  Instances of this class always have a Complex type
1518
/// whose element type matches the subexpression.
1519
///
1520
class ImaginaryLiteral : public Expr {
1521
  Stmt *Val;
1522
public:
1523
  ImaginaryLiteral(Expr *val, QualType Ty)
1524
    : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1525
           false, false),
1526
354
      Val(val) {}
1527
1528
  /// Build an empty imaginary literal.
1529
  explicit ImaginaryLiteral(EmptyShell Empty)
1530
1
    : Expr(ImaginaryLiteralClass, Empty) { }
1531
1532
463
  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1533
1
  Expr *getSubExpr() { return cast<Expr>(Val); }
1534
1
  void setSubExpr(Expr *E) { Val = E; }
1535
1536
938
  SourceLocation getLocStart() const LLVM_READONLY { return Val->getLocStart(); }
1537
92
  SourceLocation getLocEnd() const LLVM_READONLY { return Val->getLocEnd(); }
1538
1539
  static bool classof(const Stmt *T) {
1540
    return T->getStmtClass() == ImaginaryLiteralClass;
1541
  }
1542
1543
  // Iterators
1544
879
  child_range children() { return child_range(&Val, &Val+1); }
1545
0
  const_child_range children() const {
1546
0
    return const_child_range(&Val, &Val + 1);
1547
0
  }
1548
};
1549
1550
/// StringLiteral - This represents a string literal expression, e.g. "foo"
1551
/// or L"bar" (wide strings).  The actual string is returned by getBytes()
1552
/// is NOT null-terminated, and the length of the string is determined by
1553
/// calling getByteLength().  The C type for a string is always a
1554
/// ConstantArrayType.  In C++, the char type is const qualified, in C it is
1555
/// not.
1556
///
1557
/// Note that strings in C can be formed by concatenation of multiple string
1558
/// literal pptokens in translation phase #6.  This keeps track of the locations
1559
/// of each of these pieces.
1560
///
1561
/// Strings in C can also be truncated and extended by assigning into arrays,
1562
/// e.g. with constructs like:
1563
///   char X[2] = "foobar";
1564
/// In this case, getByteLength() will return 6, but the string literal will
1565
/// have type "char[2]".
1566
class StringLiteral : public Expr {
1567
public:
1568
  enum StringKind {
1569
    Ascii,
1570
    Wide,
1571
    UTF8,
1572
    UTF16,
1573
    UTF32
1574
  };
1575
1576
private:
1577
  friend class ASTStmtReader;
1578
1579
  union {
1580
    const char *asChar;
1581
    const uint16_t *asUInt16;
1582
    const uint32_t *asUInt32;
1583
  } StrData;
1584
  unsigned Length;
1585
  unsigned CharByteWidth : 4;
1586
  unsigned Kind : 3;
1587
  unsigned IsPascal : 1;
1588
  unsigned NumConcatenated;
1589
  SourceLocation TokLocs[1];
1590
1591
  StringLiteral(QualType Ty) :
1592
    Expr(StringLiteralClass, Ty, VK_LValue, OK_Ordinary, false, false, false,
1593
2.49M
         false) {}
1594
1595
  static int mapCharByteWidth(TargetInfo const &target,StringKind k);
1596
1597
public:
1598
  /// This is the "fully general" constructor that allows representation of
1599
  /// strings formed from multiple concatenated tokens.
1600
  static StringLiteral *Create(const ASTContext &C, StringRef Str,
1601
                               StringKind Kind, bool Pascal, QualType Ty,
1602
                               const SourceLocation *Loc, unsigned NumStrs);
1603
1604
  /// Simple constructor for string literals made from one token.
1605
  static StringLiteral *Create(const ASTContext &C, StringRef Str,
1606
                               StringKind Kind, bool Pascal, QualType Ty,
1607
2.68k
                               SourceLocation Loc) {
1608
2.68k
    return Create(C, Str, Kind, Pascal, Ty, &Loc, 1);
1609
2.68k
  }
1610
1611
  /// Construct an empty string literal.
1612
  static StringLiteral *CreateEmpty(const ASTContext &C, unsigned NumStrs);
1613
1614
2.56M
  StringRef getString() const {
1615
2.56M
    assert(CharByteWidth==1
1616
2.56M
           && "This function is used in places that assume strings use char");
1617
2.56M
    return StringRef(StrData.asChar, getByteLength());
1618
2.56M
  }
1619
1620
  /// Allow access to clients that need the byte representation, such as
1621
  /// ASTWriterStmt::VisitStringLiteral().
1622
1.44k
  StringRef getBytes() const {
1623
1.44k
    // FIXME: StringRef may not be the right type to use as a result for this.
1624
1.44k
    if (CharByteWidth == 1)
1625
1.40k
      return StringRef(StrData.asChar, getByteLength());
1626
47
    if (CharByteWidth == 4)
1627
31
      return StringRef(reinterpret_cast<const char*>(StrData.asUInt32),
1628
31
                       getByteLength());
1629
16
    assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1630
16
    return StringRef(reinterpret_cast<const char*>(StrData.asUInt16),
1631
16
                     getByteLength());
1632
16
  }
1633
1634
  void outputString(raw_ostream &OS) const;
1635
1636
19.7k
  uint32_t getCodeUnit(size_t i) const {
1637
19.7k
    assert(i < Length && "out of bounds access");
1638
19.7k
    if (CharByteWidth == 1)
1639
13.1k
      return static_cast<unsigned char>(StrData.asChar[i]);
1640
6.63k
    if (CharByteWidth == 4)
1641
4.21k
      return StrData.asUInt32[i];
1642
2.42k
    assert(CharByteWidth == 2 && "unsupported CharByteWidth");
1643
2.42k
    return StrData.asUInt16[i];
1644
2.42k
  }
1645
1646
2.56M
  unsigned getByteLength() const { return CharByteWidth*Length; }
1647
55.7k
  unsigned getLength() const { return Length; }
1648
211k
  unsigned getCharByteWidth() const { return CharByteWidth; }
1649
1650
  /// Sets the string data to the given string data.
1651
  void setString(const ASTContext &C, StringRef Str,
1652
                 StringKind Kind, bool IsPascal);
1653
1654
15.7k
  StringKind getKind() const { return static_cast<StringKind>(Kind); }
1655
1656
1657
2.04M
  bool isAscii() const { return Kind == Ascii; }
1658
4.64k
  bool isWide() const { return Kind == Wide; }
1659
6
  bool isUTF8() const { return Kind == UTF8; }
1660
0
  bool isUTF16() const { return Kind == UTF16; }
1661
0
  bool isUTF32() const { return Kind == UTF32; }
1662
786
  bool isPascal() const { return IsPascal; }
1663
1664
3
  bool containsNonAscii() const {
1665
3
    StringRef Str = getString();
1666
28
    for (unsigned i = 0, e = Str.size(); i != e; 
++i25
)
1667
25
      if (!isASCII(Str[i]))
1668
0
        return true;
1669
3
    return false;
1670
3
  }
1671
1672
1.75k
  bool containsNonAsciiOrNull() const {
1673
1.75k
    StringRef Str = getString();
1674
12.4k
    for (unsigned i = 0, e = Str.size(); i != e; 
++i10.7k
)
1675
10.7k
      if (!isASCII(Str[i]) || 
!Str[i]10.7k
)
1676
57
        return true;
1677
1.75k
    
return false1.70k
;
1678
1.75k
  }
1679
1680
  /// getNumConcatenated - Get the number of string literal tokens that were
1681
  /// concatenated in translation phase #6 to form this string literal.
1682
2.65k
  unsigned getNumConcatenated() const { return NumConcatenated; }
1683
1684
224k
  SourceLocation getStrTokenLoc(unsigned TokNum) const {
1685
224k
    assert(TokNum < NumConcatenated && "Invalid tok number");
1686
224k
    return TokLocs[TokNum];
1687
224k
  }
1688
203
  void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1689
203
    assert(TokNum < NumConcatenated && "Invalid tok number");
1690
203
    TokLocs[TokNum] = L;
1691
203
  }
1692
1693
  /// getLocationOfByte - Return a source location that points to the specified
1694
  /// byte of this string literal.
1695
  ///
1696
  /// Strings are amazingly complex.  They can be formed from multiple tokens
1697
  /// and can have escape sequences in them in addition to the usual trigraph
1698
  /// and escaped newline business.  This routine handles this complexity.
1699
  ///
1700
  SourceLocation
1701
  getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1702
                    const LangOptions &Features, const TargetInfo &Target,
1703
                    unsigned *StartToken = nullptr,
1704
                    unsigned *StartTokenByteOffset = nullptr) const;
1705
1706
  typedef const SourceLocation *tokloc_iterator;
1707
65
  tokloc_iterator tokloc_begin() const { return TokLocs; }
1708
65
  tokloc_iterator tokloc_end() const { return TokLocs + NumConcatenated; }
1709
1710
6.10M
  SourceLocation getLocStart() const LLVM_READONLY { return TokLocs[0]; }
1711
16.8k
  SourceLocation getLocEnd() const LLVM_READONLY {
1712
16.8k
    return TokLocs[NumConcatenated - 1];
1713
16.8k
  }
1714
1715
5.98M
  static bool classof(const Stmt *T) {
1716
5.98M
    return T->getStmtClass() == StringLiteralClass;
1717
5.98M
  }
1718
1719
  // Iterators
1720
1.28M
  child_range children() {
1721
1.28M
    return child_range(child_iterator(), child_iterator());
1722
1.28M
  }
1723
0
  const_child_range children() const {
1724
0
    return const_child_range(const_child_iterator(), const_child_iterator());
1725
0
  }
1726
};
1727
1728
/// ParenExpr - This represents a parethesized expression, e.g. "(1)".  This
1729
/// AST node is only formed if full location information is requested.
1730
class ParenExpr : public Expr {
1731
  SourceLocation L, R;
1732
  Stmt *Val;
1733
public:
1734
  ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1735
    : Expr(ParenExprClass, val->getType(),
1736
           val->getValueKind(), val->getObjectKind(),
1737
           val->isTypeDependent(), val->isValueDependent(),
1738
           val->isInstantiationDependent(),
1739
           val->containsUnexpandedParameterPack()),
1740
2.41M
      L(l), R(r), Val(val) {}
1741
1742
  /// Construct an empty parenthesized expression.
1743
  explicit ParenExpr(EmptyShell Empty)
1744
11.8k
    : Expr(ParenExprClass, Empty) { }
1745
1746
2.17M
  const Expr *getSubExpr() const { return cast<Expr>(Val); }
1747
13.2M
  Expr *getSubExpr() { return cast<Expr>(Val); }
1748
11.8k
  void setSubExpr(Expr *E) { Val = E; }
1749
1750
5.70M
  SourceLocation getLocStart() const LLVM_READONLY { return L; }
1751
1.22M
  SourceLocation getLocEnd() const LLVM_READONLY { return R; }
1752
1753
  /// Get the location of the left parentheses '('.
1754
252k
  SourceLocation getLParen() const { return L; }
1755
11.8k
  void setLParen(SourceLocation Loc) { L = Loc; }
1756
1757
  /// Get the location of the right parentheses ')'.
1758
252k
  SourceLocation getRParen() const { return R; }
1759
11.8k
  void setRParen(SourceLocation Loc) { R = Loc; }
1760
1761
362M
  static bool classof(const Stmt *T) {
1762
362M
    return T->getStmtClass() == ParenExprClass;
1763
362M
  }
1764
1765
  // Iterators
1766
2.83M
  child_range children() { return child_range(&Val, &Val+1); }
1767
0
  const_child_range children() const {
1768
0
    return const_child_range(&Val, &Val + 1);
1769
0
  }
1770
};
1771
1772
/// UnaryOperator - This represents the unary-expression's (except sizeof and
1773
/// alignof), the postinc/postdec operators from postfix-expression, and various
1774
/// extensions.
1775
///
1776
/// Notes on various nodes:
1777
///
1778
/// Real/Imag - These return the real/imag part of a complex operand.  If
1779
///   applied to a non-complex value, the former returns its operand and the
1780
///   later returns zero in the type of the operand.
1781
///
1782
class UnaryOperator : public Expr {
1783
public:
1784
  typedef UnaryOperatorKind Opcode;
1785
1786
private:
1787
  unsigned Opc : 5;
1788
  unsigned CanOverflow : 1;
1789
  SourceLocation Loc;
1790
  Stmt *Val;
1791
public:
1792
  UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK,
1793
                ExprObjectKind OK, SourceLocation l, bool CanOverflow)
1794
      : Expr(UnaryOperatorClass, type, VK, OK,
1795
             input->isTypeDependent() || type->isDependentType(),
1796
             input->isValueDependent(),
1797
             (input->isInstantiationDependent() ||
1798
              type->isInstantiationDependentType()),
1799
             input->containsUnexpandedParameterPack()),
1800
2.44M
        Opc(opc), CanOverflow(CanOverflow), Loc(l), Val(input) {}
1801
1802
  /// Build an empty unary operator.
1803
  explicit UnaryOperator(EmptyShell Empty)
1804
9.84k
    : Expr(UnaryOperatorClass, Empty), Opc(UO_AddrOf) { }
1805
1806
26.3M
  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
1807
9.84k
  void setOpcode(Opcode O) { Opc = O; }
1808
1809
6.19M
  Expr *getSubExpr() const { return cast<Expr>(Val); }
1810
9.85k
  void setSubExpr(Expr *E) { Val = E; }
1811
1812
  /// getOperatorLoc - Return the location of the operator.
1813
354k
  SourceLocation getOperatorLoc() const { return Loc; }
1814
9.84k
  void setOperatorLoc(SourceLocation L) { Loc = L; }
1815
1816
  /// Returns true if the unary operator can cause an overflow. For instance,
1817
  ///   signed int i = INT_MAX; i++;
1818
  ///   signed char c = CHAR_MAX; c++;
1819
  /// Due to integer promotions, c++ is promoted to an int before the postfix
1820
  /// increment, and the result is an int that cannot overflow. However, i++
1821
  /// can overflow.
1822
74.8k
  bool canOverflow() const { return CanOverflow; }
1823
9.84k
  void setCanOverflow(bool C) { CanOverflow = C; }
1824
1825
  /// isPostfix - Return true if this is a postfix operation, like x++.
1826
5.11M
  static bool isPostfix(Opcode Op) {
1827
5.11M
    return Op == UO_PostInc || 
Op == UO_PostDec4.90M
;
1828
5.11M
  }
1829
1830
  /// isPrefix - Return true if this is a prefix operation, like --x.
1831
321k
  static bool isPrefix(Opcode Op) {
1832
321k
    return Op == UO_PreInc || 
Op == UO_PreDec319k
;
1833
321k
  }
1834
1835
321k
  bool isPrefix() const { return isPrefix(getOpcode()); }
1836
5.11M
  bool isPostfix() const { return isPostfix(getOpcode()); }
1837
1838
56.7k
  static bool isIncrementOp(Opcode Op) {
1839
56.7k
    return Op == UO_PreInc || 
Op == UO_PostInc20.7k
;
1840
56.7k
  }
1841
56.7k
  bool isIncrementOp() const {
1842
56.7k
    return isIncrementOp(getOpcode());
1843
56.7k
  }
1844
1845
71.8k
  static bool isDecrementOp(Opcode Op) {
1846
71.8k
    return Op == UO_PreDec || 
Op == UO_PostDec71.8k
;
1847
71.8k
  }
1848
71.8k
  bool isDecrementOp() const {
1849
71.8k
    return isDecrementOp(getOpcode());
1850
71.8k
  }
1851
1852
629k
  static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
1853
629k
  bool isIncrementDecrementOp() const {
1854
629k
    return isIncrementDecrementOp(getOpcode());
1855
629k
  }
1856
1857
  static bool isArithmeticOp(Opcode Op) {
1858
    return Op >= UO_Plus && Op <= UO_LNot;
1859
  }
1860
  bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
1861
1862
  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
1863
  /// corresponds to, e.g. "sizeof" or "[pre]++"
1864
  static StringRef getOpcodeStr(Opcode Op);
1865
1866
  /// Retrieve the unary opcode that corresponds to the given
1867
  /// overloaded operator.
1868
  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
1869
1870
  /// Retrieve the overloaded operator kind that corresponds to
1871
  /// the given unary opcode.
1872
  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
1873
1874
4.64M
  SourceLocation getLocStart() const LLVM_READONLY {
1875
4.64M
    return isPostfix() ? 
Val->getLocStart()183k
:
Loc4.46M
;
1876
4.64M
  }
1877
412k
  SourceLocation getLocEnd() const LLVM_READONLY {
1878
412k
    return isPostfix() ? 
Loc32.4k
:
Val->getLocEnd()380k
;
1879
412k
  }
1880
3.55M
  SourceLocation getExprLoc() const LLVM_READONLY { return Loc; }
1881
1882
529M
  static bool classof(const Stmt *T) {
1883
529M
    return T->getStmtClass() == UnaryOperatorClass;
1884
529M
  }
1885
1886
  // Iterators
1887
3.64M
  child_range children() { return child_range(&Val, &Val+1); }
1888
0
  const_child_range children() const {
1889
0
    return const_child_range(&Val, &Val + 1);
1890
0
  }
1891
};
1892
1893
/// Helper class for OffsetOfExpr.
1894
1895
// __builtin_offsetof(type, identifier(.identifier|[expr])*)
1896
0
class OffsetOfNode {
1897
public:
1898
  /// The kind of offsetof node we have.
1899
  enum Kind {
1900
    /// An index into an array.
1901
    Array = 0x00,
1902
    /// A field.
1903
    Field = 0x01,
1904
    /// A field in a dependent type, known only by its name.
1905
    Identifier = 0x02,
1906
    /// An implicit indirection through a C++ base class, when the
1907
    /// field found is in a base class.
1908
    Base = 0x03
1909
  };
1910
1911
private:
1912
  enum { MaskBits = 2, Mask = 0x03 };
1913
1914
  /// The source range that covers this part of the designator.
1915
  SourceRange Range;
1916
1917
  /// The data describing the designator, which comes in three
1918
  /// different forms, depending on the lower two bits.
1919
  ///   - An unsigned index into the array of Expr*'s stored after this node
1920
  ///     in memory, for [constant-expression] designators.
1921
  ///   - A FieldDecl*, for references to a known field.
1922
  ///   - An IdentifierInfo*, for references to a field with a given name
1923
  ///     when the class type is dependent.
1924
  ///   - A CXXBaseSpecifier*, for references that look at a field in a
1925
  ///     base class.
1926
  uintptr_t Data;
1927
1928
public:
1929
  /// Create an offsetof node that refers to an array element.
1930
  OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
1931
               SourceLocation RBracketLoc)
1932
43
      : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
1933
1934
  /// Create an offsetof node that refers to a field.
1935
  OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
1936
      : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1937
4.28k
        Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
1938
1939
  /// Create an offsetof node that refers to an identifier.
1940
  OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
1941
               SourceLocation NameLoc)
1942
      : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
1943
17
        Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
1944
1945
  /// Create an offsetof node that refers into a C++ base class.
1946
  explicit OffsetOfNode(const CXXBaseSpecifier *Base)
1947
18
      : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
1948
1949
  /// Determine what kind of offsetof node this is.
1950
5.23k
  Kind getKind() const { return static_cast<Kind>(Data & Mask); }
1951
1952
  /// For an array element node, returns the index into the array
1953
  /// of expressions.
1954
45
  unsigned getArrayExprIndex() const {
1955
45
    assert(getKind() == Array);
1956
45
    return Data >> 2;
1957
45
  }
1958
1959
  /// For a field offsetof node, returns the field.
1960
5.07k
  FieldDecl *getField() const {
1961
5.07k
    assert(getKind() == Field);
1962
5.07k
    return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
1963
5.07k
  }
1964
1965
  /// For a field or identifier offsetof node, returns the name of
1966
  /// the field.
1967
  IdentifierInfo *getFieldName() const;
1968
1969
  /// For a base class node, returns the base specifier.
1970
35
  CXXBaseSpecifier *getBase() const {
1971
35
    assert(getKind() == Base);
1972
35
    return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
1973
35
  }
1974
1975
  /// Retrieve the source range that covers this offsetof node.
1976
  ///
1977
  /// For an array element node, the source range contains the locations of
1978
  /// the square brackets. For a field or identifier node, the source range
1979
  /// contains the location of the period (if there is one) and the
1980
  /// identifier.
1981
40
  SourceRange getSourceRange() const LLVM_READONLY { return Range; }
1982
3
  SourceLocation getLocStart() const LLVM_READONLY { return Range.getBegin(); }
1983
33
  SourceLocation getLocEnd() const LLVM_READONLY { return Range.getEnd(); }
1984
};
1985
1986
/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
1987
/// offsetof(record-type, member-designator). For example, given:
1988
/// @code
1989
/// struct S {
1990
///   float f;
1991
///   double d;
1992
/// };
1993
/// struct T {
1994
///   int i;
1995
///   struct S s[10];
1996
/// };
1997
/// @endcode
1998
/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
1999
2000
class OffsetOfExpr final
2001
    : public Expr,
2002
      private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2003
  SourceLocation OperatorLoc, RParenLoc;
2004
  // Base type;
2005
  TypeSourceInfo *TSInfo;
2006
  // Number of sub-components (i.e. instances of OffsetOfNode).
2007
  unsigned NumComps;
2008
  // Number of sub-expressions (i.e. array subscript expressions).
2009
  unsigned NumExprs;
2010
2011
613
  size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2012
613
    return NumComps;
2013
613
  }
2014
2015
  OffsetOfExpr(const ASTContext &C, QualType type,
2016
               SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2017
               ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2018
               SourceLocation RParenLoc);
2019
2020
  explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2021
    : Expr(OffsetOfExprClass, EmptyShell()),
2022
3
      TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2023
2024
public:
2025
2026
  static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2027
                              SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2028
                              ArrayRef<OffsetOfNode> comps,
2029
                              ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2030
2031
  static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2032
                                   unsigned NumComps, unsigned NumExprs);
2033
2034
  /// getOperatorLoc - Return the location of the operator.
2035
8
  SourceLocation getOperatorLoc() const { return OperatorLoc; }
2036
3
  void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2037
2038
  /// Return the location of the right parentheses.
2039
8
  SourceLocation getRParenLoc() const { return RParenLoc; }
2040
3
  void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2041
2042
5.12k
  TypeSourceInfo *getTypeSourceInfo() const {
2043
5.12k
    return TSInfo;
2044
5.12k
  }
2045
3
  void setTypeSourceInfo(TypeSourceInfo *tsi) {
2046
3
    TSInfo = tsi;
2047
3
  }
2048
2049
5.18k
  const OffsetOfNode &getComponent(unsigned Idx) const {
2050
5.18k
    assert(Idx < NumComps && "Subscript out of range");
2051
5.18k
    return getTrailingObjects<OffsetOfNode>()[Idx];
2052
5.18k
  }
2053
2054
4.35k
  void setComponent(unsigned Idx, OffsetOfNode ON) {
2055
4.35k
    assert(Idx < NumComps && "Subscript out of range");
2056
4.35k
    getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2057
4.35k
  }
2058
2059
5.05k
  unsigned getNumComponents() const {
2060
5.05k
    return NumComps;
2061
5.05k
  }
2062
2063
6
  Expr* getIndexExpr(unsigned Idx) {
2064
6
    assert(Idx < NumExprs && "Subscript out of range");
2065
6
    return getTrailingObjects<Expr *>()[Idx];
2066
6
  }
2067
2068
39
  const Expr *getIndexExpr(unsigned Idx) const {
2069
39
    assert(Idx < NumExprs && "Subscript out of range");
2070
39
    return getTrailingObjects<Expr *>()[Idx];
2071
39
  }
2072
2073
41
  void setIndexExpr(unsigned Idx, Expr* E) {
2074
41
    assert(Idx < NumComps && "Subscript out of range");
2075
41
    getTrailingObjects<Expr *>()[Idx] = E;
2076
41
  }
2077
2078
11
  unsigned getNumExpressions() const {
2079
11
    return NumExprs;
2080
11
  }
2081
2082
3.90k
  SourceLocation getLocStart() const LLVM_READONLY { return OperatorLoc; }
2083
70
  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2084
2085
95
  static bool classof(const Stmt *T) {
2086
95
    return T->getStmtClass() == OffsetOfExprClass;
2087
95
  }
2088
2089
  // Iterators
2090
527
  child_range children() {
2091
527
    Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2092
527
    return child_range(begin, begin + NumExprs);
2093
527
  }
2094
0
  const_child_range children() const {
2095
0
    Stmt *const *begin =
2096
0
        reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2097
0
    return const_child_range(begin, begin + NumExprs);
2098
0
  }
2099
  friend TrailingObjects;
2100
};
2101
2102
/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2103
/// expression operand.  Used for sizeof/alignof (C99 6.5.3.4) and
2104
/// vec_step (OpenCL 1.1 6.11.12).
2105
class UnaryExprOrTypeTraitExpr : public Expr {
2106
  union {
2107
    TypeSourceInfo *Ty;
2108
    Stmt *Ex;
2109
  } Argument;
2110
  SourceLocation OpLoc, RParenLoc;
2111
2112
public:
2113
  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2114
                           QualType resultType, SourceLocation op,
2115
                           SourceLocation rp) :
2116
      Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2117
           false, // Never type-dependent (C++ [temp.dep.expr]p3).
2118
           // Value-dependent if the argument is type-dependent.
2119
           TInfo->getType()->isDependentType(),
2120
           TInfo->getType()->isInstantiationDependentType(),
2121
           TInfo->getType()->containsUnexpandedParameterPack()),
2122
142k
      OpLoc(op), RParenLoc(rp) {
2123
142k
    UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2124
142k
    UnaryExprOrTypeTraitExprBits.IsType = true;
2125
142k
    Argument.Ty = TInfo;
2126
142k
  }
2127
2128
  UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2129
                           QualType resultType, SourceLocation op,
2130
                           SourceLocation rp);
2131
2132
  /// Construct an empty sizeof/alignof expression.
2133
  explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2134
32
    : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2135
2136
486k
  UnaryExprOrTypeTrait getKind() const {
2137
486k
    return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2138
486k
  }
2139
32
  void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2140
2141
680k
  bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2142
453k
  QualType getArgumentType() const {
2143
453k
    return getArgumentTypeInfo()->getType();
2144
453k
  }
2145
514k
  TypeSourceInfo *getArgumentTypeInfo() const {
2146
514k
    assert(isArgumentType() && "calling getArgumentType() when arg is expr");
2147
514k
    return Argument.Ty;
2148
514k
  }
2149
157k
  Expr *getArgumentExpr() {
2150
157k
    assert(!isArgumentType() && "calling getArgumentExpr() when arg is type");
2151
157k
    return static_cast<Expr*>(Argument.Ex);
2152
157k
  }
2153
96.6k
  const Expr *getArgumentExpr() const {
2154
96.6k
    return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2155
96.6k
  }
2156
2157
18
  void setArgument(Expr *E) {
2158
18
    Argument.Ex = E;
2159
18
    UnaryExprOrTypeTraitExprBits.IsType = false;
2160
18
  }
2161
14
  void setArgument(TypeSourceInfo *TInfo) {
2162
14
    Argument.Ty = TInfo;
2163
14
    UnaryExprOrTypeTraitExprBits.IsType = true;
2164
14
  }
2165
2166
  /// Gets the argument type, or the type of the argument expression, whichever
2167
  /// is appropriate.
2168
345k
  QualType getTypeOfArgument() const {
2169
345k
    return isArgumentType() ? 
getArgumentType()250k
:
getArgumentExpr()->getType()95.1k
;
2170
345k
  }
2171
2172
60.4k
  SourceLocation getOperatorLoc() const { return OpLoc; }
2173
32
  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2174
2175
46
  SourceLocation getRParenLoc() const { return RParenLoc; }
2176
32
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2177
2178
777k
  SourceLocation getLocStart() const LLVM_READONLY { return OpLoc; }
2179
49.2k
  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
2180
2181
27.9M
  static bool classof(const Stmt *T) {
2182
27.9M
    return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2183
27.9M
  }
2184
2185
  // Iterators
2186
  child_range children();
2187
  const_child_range children() const;
2188
};
2189
2190
//===----------------------------------------------------------------------===//
2191
// Postfix Operators.
2192
//===----------------------------------------------------------------------===//
2193
2194
/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2195
class ArraySubscriptExpr : public Expr {
2196
  enum { LHS, RHS, END_EXPR=2 };
2197
  Stmt* SubExprs[END_EXPR];
2198
  SourceLocation RBracketLoc;
2199
public:
2200
  ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2201
                     ExprValueKind VK, ExprObjectKind OK,
2202
                     SourceLocation rbracketloc)
2203
  : Expr(ArraySubscriptExprClass, t, VK, OK,
2204
         lhs->isTypeDependent() || rhs->isTypeDependent(),
2205
         lhs->isValueDependent() || rhs->isValueDependent(),
2206
         (lhs->isInstantiationDependent() ||
2207
          rhs->isInstantiationDependent()),
2208
         (lhs->containsUnexpandedParameterPack() ||
2209
          rhs->containsUnexpandedParameterPack())),
2210
674k
    RBracketLoc(rbracketloc) {
2211
674k
    SubExprs[LHS] = lhs;
2212
674k
    SubExprs[RHS] = rhs;
2213
674k
  }
2214
2215
  /// Create an empty array subscript expression.
2216
  explicit ArraySubscriptExpr(EmptyShell Shell)
2217
5.14k
    : Expr(ArraySubscriptExprClass, Shell) { }
2218
2219
  /// An array access can be written A[4] or 4[A] (both are equivalent).
2220
  /// - getBase() and getIdx() always present the normalized view: A[4].
2221
  ///    In this case getBase() returns "A" and getIdx() returns "4".
2222
  /// - getLHS() and getRHS() present the syntactic view. e.g. for
2223
  ///    4[A] getLHS() returns "4".
2224
  /// Note: Because vector element access is also written A[4] we must
2225
  /// predicate the format conversion in getBase and getIdx only on the
2226
  /// the type of the RHS, as it is possible for the LHS to be a vector of
2227
  /// integer type
2228
369k
  Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2229
8.45M
  const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2230
5.14k
  void setLHS(Expr *E) { SubExprs[LHS] = E; }
2231
2232
219k
  Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2233
9.11M
  const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2234
5.14k
  void setRHS(Expr *E) { SubExprs[RHS] = E; }
2235
2236
132k
  Expr *getBase() {
2237
132k
    return getRHS()->getType()->isIntegerType() ? 
getLHS()132k
:
getRHS()21
;
2238
132k
  }
2239
2240
5.79M
  const Expr *getBase() const {
2241
5.79M
    return getRHS()->getType()->isIntegerType() ? 
getLHS()5.79M
:
getRHS()6.06k
;
2242
5.79M
  }
2243
2244
1.61k
  Expr *getIdx() {
2245
1.61k
    return getRHS()->getType()->isIntegerType() ? getRHS() : 
getLHS()0
;
2246
1.61k
  }
2247
2248
1.65M
  const Expr *getIdx() const {
2249
1.65M
    return getRHS()->getType()->isIntegerType() ? 
getRHS()1.65M
:
getLHS()125
;
2250
1.65M
  }
2251
2252
2.22M
  SourceLocation getLocStart() const LLVM_READONLY {
2253
2.22M
    return getLHS()->getLocStart();
2254
2.22M
  }
2255
140k
  SourceLocation getLocEnd() const LLVM_READONLY { return RBracketLoc; }
2256
2257
92.2k
  SourceLocation getRBracketLoc() const { return RBracketLoc; }
2258
5.14k
  void setRBracketLoc(SourceLocation L) { RBracketLoc = L; }
2259
2260
1.63M
  SourceLocation getExprLoc() const LLVM_READONLY {
2261
1.63M
    return getBase()->getExprLoc();
2262
1.63M
  }
2263
2264
1.13M
  static bool classof(const Stmt *T) {
2265
1.13M
    return T->getStmtClass() == ArraySubscriptExprClass;
2266
1.13M
  }
2267
2268
  // Iterators
2269
1.42M
  child_range children() {
2270
1.42M
    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2271
1.42M
  }
2272
0
  const_child_range children() const {
2273
0
    return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2274
0
  }
2275
};
2276
2277
/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2278
/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2279
/// while its subclasses may represent alternative syntax that (semantically)
2280
/// results in a function call. For example, CXXOperatorCallExpr is
2281
/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2282
/// "str1 + str2" to resolve to a function call.
2283
class CallExpr : public Expr {
2284
  enum { FN=0, PREARGS_START=1 };
2285
  Stmt **SubExprs;
2286
  unsigned NumArgs;
2287
  SourceLocation RParenLoc;
2288
2289
  void updateDependenciesFromArg(Expr *Arg);
2290
2291
protected:
2292
  // These versions of the constructor are for derived classes.
2293
  CallExpr(const ASTContext &C, StmtClass SC, Expr *fn,
2294
           ArrayRef<Expr *> preargs, ArrayRef<Expr *> args, QualType t,
2295
           ExprValueKind VK, SourceLocation rparenloc);
2296
  CallExpr(const ASTContext &C, StmtClass SC, Expr *fn, ArrayRef<Expr *> args,
2297
           QualType t, ExprValueKind VK, SourceLocation rparenloc);
2298
  CallExpr(const ASTContext &C, StmtClass SC, unsigned NumPreArgs,
2299
           EmptyShell Empty);
2300
2301
4
  Stmt *getPreArg(unsigned i) {
2302
4
    assert(i < getNumPreArgs() && "Prearg access out of range!");
2303
4
    return SubExprs[PREARGS_START+i];
2304
4
  }
2305
8
  const Stmt *getPreArg(unsigned i) const {
2306
8
    assert(i < getNumPreArgs() && "Prearg access out of range!");
2307
8
    return SubExprs[PREARGS_START+i];
2308
8
  }
2309
0
  void setPreArg(unsigned i, Stmt *PreArg) {
2310
0
    assert(i < getNumPreArgs() && "Prearg access out of range!");
2311
0
    SubExprs[PREARGS_START+i] = PreArg;
2312
0
  }
2313
2314
39.6M
  unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2315
2316
public:
2317
  CallExpr(const ASTContext& C, Expr *fn, ArrayRef<Expr*> args, QualType t,
2318
           ExprValueKind VK, SourceLocation rparenloc);
2319
2320
  /// Build an empty call expression.
2321
  CallExpr(const ASTContext &C, StmtClass SC, EmptyShell Empty);
2322
2323
30.6M
  const Expr *getCallee() const { return cast<Expr>(SubExprs[FN]); }
2324
15.0M
  Expr *getCallee() { return cast<Expr>(SubExprs[FN]); }
2325
14.1k
  void setCallee(Expr *F) { SubExprs[FN] = F; }
2326
2327
  Decl *getCalleeDecl();
2328
1.81M
  const Decl *getCalleeDecl() const {
2329
1.81M
    return const_cast<CallExpr*>(this)->getCalleeDecl();
2330
1.81M
  }
2331
2332
  /// If the callee is a FunctionDecl, return it. Otherwise return 0.
2333
  FunctionDecl *getDirectCallee();
2334
2.44M
  const FunctionDecl *getDirectCallee() const {
2335
2.44M
    return const_cast<CallExpr*>(this)->getDirectCallee();
2336
2.44M
  }
2337
2338
  /// getNumArgs - Return the number of actual arguments to this call.
2339
  ///
2340
22.5M
  unsigned getNumArgs() const { return NumArgs; }
2341
2342
  /// Retrieve the call arguments.
2343
5.03M
  Expr **getArgs() {
2344
5.03M
    return reinterpret_cast<Expr **>(SubExprs+getNumPreArgs()+PREARGS_START);
2345
5.03M
  }
2346
865k
  const Expr *const *getArgs() const {
2347
865k
    return reinterpret_cast<Expr **>(SubExprs + getNumPreArgs() +
2348
865k
                                     PREARGS_START);
2349
865k
  }
2350
2351
  /// getArg - Return the specified argument.
2352
8.14M
  Expr *getArg(unsigned Arg) {
2353
8.14M
    assert(Arg < NumArgs && "Arg access out of range!");
2354
8.14M
    return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2355
8.14M
  }
2356
2.30M
  const Expr *getArg(unsigned Arg) const {
2357
2.30M
    assert(Arg < NumArgs && "Arg access out of range!");
2358
2.30M
    return cast_or_null<Expr>(SubExprs[Arg + getNumPreArgs() + PREARGS_START]);
2359
2.30M
  }
2360
2361
  /// setArg - Set the specified argument.
2362
6.50M
  void setArg(unsigned Arg, Expr *ArgExpr) {
2363
6.50M
    assert(Arg < NumArgs && "Arg access out of range!");
2364
6.50M
    SubExprs[Arg+getNumPreArgs()+PREARGS_START] = ArgExpr;
2365
6.50M
  }
2366
2367
  /// setNumArgs - This changes the number of arguments present in this call.
2368
  /// Any orphaned expressions are deleted by this, and any new operands are set
2369
  /// to null.
2370
  void setNumArgs(const ASTContext& C, unsigned NumArgs);
2371
2372
  typedef ExprIterator arg_iterator;
2373
  typedef ConstExprIterator const_arg_iterator;
2374
  typedef llvm::iterator_range<arg_iterator> arg_range;
2375
  typedef llvm::iterator_range<const_arg_iterator> arg_const_range;
2376
2377
724k
  arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2378
788k
  arg_const_range arguments() const {
2379
788k
    return arg_const_range(arg_begin(), arg_end());
2380
788k
  }
2381
2382
3.47M
  arg_iterator arg_begin() { return SubExprs+PREARGS_START+getNumPreArgs(); }
2383
3.47M
  arg_iterator arg_end() {
2384
3.47M
    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2385
3.47M
  }
2386
794k
  const_arg_iterator arg_begin() const {
2387
794k
    return SubExprs+PREARGS_START+getNumPreArgs();
2388
794k
  }
2389
789k
  const_arg_iterator arg_end() const {
2390
789k
    return SubExprs+PREARGS_START+getNumPreArgs()+getNumArgs();
2391
789k
  }
2392
2393
  /// This method provides fast access to all the subexpressions of
2394
  /// a CallExpr without going through the slower virtual child_iterator
2395
  /// interface.  This provides efficient reverse iteration of the
2396
  /// subexpressions.  This is currently used for CFG construction.
2397
712k
  ArrayRef<Stmt*> getRawSubExprs() {
2398
712k
    return llvm::makeArrayRef(SubExprs,
2399
712k
                              getNumPreArgs() + PREARGS_START + getNumArgs());
2400
712k
  }
2401
2402
  /// getNumCommas - Return the number of commas that must have been present in
2403
  /// this function call.
2404
0
  unsigned getNumCommas() const { return NumArgs ? NumArgs - 1 : 0; }
2405
2406
  /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2407
  /// of the callee. If not, return 0.
2408
  unsigned getBuiltinCallee() const;
2409
2410
  /// Returns \c true if this is a call to a builtin which does not
2411
  /// evaluate side-effects within its arguments.
2412
  bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2413
2414
  /// getCallReturnType - Get the return type of the call expr. This is not
2415
  /// always the type of the expr itself, if the return type is a reference
2416
  /// type.
2417
  QualType getCallReturnType(const ASTContext &Ctx) const;
2418
2419
6.26M
  SourceLocation getRParenLoc() const { return RParenLoc; }
2420
4.52k
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2421
2422
  SourceLocation getLocStart() const LLVM_READONLY;
2423
  SourceLocation getLocEnd() const LLVM_READONLY;
2424
2425
  /// Return true if this is a call to __assume() or __builtin_assume() with
2426
  /// a non-value-dependent constant parameter evaluating as false.
2427
  bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
2428
2429
523k
  bool isCallToStdMove() const {
2430
523k
    const FunctionDecl* FD = getDirectCallee();
2431
523k
    return getNumArgs() == 1 && 
FD134k
&&
FD->isInStdNamespace()122k
&&
2432
523k
           
FD->getIdentifier()1.10k
&&
FD->getIdentifier()->isStr("move")1.07k
;
2433
523k
  }
2434
2435
60.8M
  static bool classof(const Stmt *T) {
2436
60.8M
    return T->getStmtClass() >= firstCallExprConstant &&
2437
60.8M
           
T->getStmtClass() <= lastCallExprConstant51.1M
;
2438
60.8M
  }
2439
2440
  // Iterators
2441
7.53M
  child_range children() {
2442
7.53M
    return child_range(&SubExprs[0],
2443
7.53M
                       &SubExprs[0]+NumArgs+getNumPreArgs()+PREARGS_START);
2444
7.53M
  }
2445
2446
0
  const_child_range children() const {
2447
0
    return const_child_range(&SubExprs[0], &SubExprs[0] + NumArgs +
2448
0
                                               getNumPreArgs() + PREARGS_START);
2449
0
  }
2450
};
2451
2452
/// Extra data stored in some MemberExpr objects.
2453
struct MemberExprNameQualifier {
2454
  /// The nested-name-specifier that qualifies the name, including
2455
  /// source-location information.
2456
  NestedNameSpecifierLoc QualifierLoc;
2457
2458
  /// The DeclAccessPair through which the MemberDecl was found due to
2459
  /// name qualifiers.
2460
  DeclAccessPair FoundDecl;
2461
};
2462
2463
/// MemberExpr - [C99 6.5.2.3] Structure and Union Members.  X->F and X.F.
2464
///
2465
class MemberExpr final
2466
    : public Expr,
2467
      private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2468
                                    ASTTemplateKWAndArgsInfo,
2469
                                    TemplateArgumentLoc> {
2470
  /// Base - the expression for the base pointer or structure references.  In
2471
  /// X.F, this is "X".
2472
  Stmt *Base;
2473
2474
  /// MemberDecl - This is the decl being referenced by the field/member name.
2475
  /// In X.F, this is the decl referenced by F.
2476
  ValueDecl *MemberDecl;
2477
2478
  /// MemberDNLoc - Provides source/type location info for the
2479
  /// declaration name embedded in MemberDecl.
2480
  DeclarationNameLoc MemberDNLoc;
2481
2482
  /// MemberLoc - This is the location of the member name.
2483
  SourceLocation MemberLoc;
2484
2485
  /// This is the location of the -> or . in the expression.
2486
  SourceLocation OperatorLoc;
2487
2488
  /// IsArrow - True if this is "X->F", false if this is "X.F".
2489
  bool IsArrow : 1;
2490
2491
  /// True if this member expression used a nested-name-specifier to
2492
  /// refer to the member, e.g., "x->Base::f", or found its member via a using
2493
  /// declaration.  When true, a MemberExprNameQualifier
2494
  /// structure is allocated immediately after the MemberExpr.
2495
  bool HasQualifierOrFoundDecl : 1;
2496
2497
  /// True if this member expression specified a template keyword
2498
  /// and/or a template argument list explicitly, e.g., x->f<int>,
2499
  /// x->template f, x->template f<int>.
2500
  /// When true, an ASTTemplateKWAndArgsInfo structure and its
2501
  /// TemplateArguments (if any) are present.
2502
  bool HasTemplateKWAndArgsInfo : 1;
2503
2504
  /// True if this member expression refers to a method that
2505
  /// was resolved from an overloaded set having size greater than 1.
2506
  bool HadMultipleCandidates : 1;
2507
2508
6.08k
  size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2509
6.08k
    return HasQualifierOrFoundDecl ? 1 : 
00
;
2510
6.08k
  }
2511
2512
1.47k
  size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2513
1.47k
    return HasTemplateKWAndArgsInfo ? 1 : 
00
;
2514
1.47k
  }
2515
2516
public:
2517
  MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2518
             ValueDecl *memberdecl, const DeclarationNameInfo &NameInfo,
2519
             QualType ty, ExprValueKind VK, ExprObjectKind OK)
2520
      : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2521
             base->isValueDependent(), base->isInstantiationDependent(),
2522
             base->containsUnexpandedParameterPack()),
2523
        Base(base), MemberDecl(memberdecl), MemberDNLoc(NameInfo.getInfo()),
2524
        MemberLoc(NameInfo.getLoc()), OperatorLoc(operatorloc),
2525
        IsArrow(isarrow), HasQualifierOrFoundDecl(false),
2526
2.63M
        HasTemplateKWAndArgsInfo(false), HadMultipleCandidates(false) {
2527
2.63M
    assert(memberdecl->getDeclName() == NameInfo.getName());
2528
2.63M
  }
2529
2530
  // NOTE: this constructor should be used only when it is known that
2531
  // the member name can not provide additional syntactic info
2532
  // (i.e., source locations for C++ operator names or type source info
2533
  // for constructors, destructors and conversion operators).
2534
  MemberExpr(Expr *base, bool isarrow, SourceLocation operatorloc,
2535
             ValueDecl *memberdecl, SourceLocation l, QualType ty,
2536
             ExprValueKind VK, ExprObjectKind OK)
2537
      : Expr(MemberExprClass, ty, VK, OK, base->isTypeDependent(),
2538
             base->isValueDependent(), base->isInstantiationDependent(),
2539
             base->containsUnexpandedParameterPack()),
2540
        Base(base), MemberDecl(memberdecl), MemberDNLoc(), MemberLoc(l),
2541
        OperatorLoc(operatorloc), IsArrow(isarrow),
2542
        HasQualifierOrFoundDecl(false), HasTemplateKWAndArgsInfo(false),
2543
28.4k
        HadMultipleCandidates(false) {}
2544
2545
  static MemberExpr *Create(const ASTContext &C, Expr *base, bool isarrow,
2546
                            SourceLocation OperatorLoc,
2547
                            NestedNameSpecifierLoc QualifierLoc,
2548
                            SourceLocation TemplateKWLoc, ValueDecl *memberdecl,
2549
                            DeclAccessPair founddecl,
2550
                            DeclarationNameInfo MemberNameInfo,
2551
                            const TemplateArgumentListInfo *targs, QualType ty,
2552
                            ExprValueKind VK, ExprObjectKind OK);
2553
2554
453k
  void setBase(Expr *E) { Base = E; }
2555
37.5M
  Expr *getBase() const { return cast<Expr>(Base); }
2556
2557
  /// Retrieve the member declaration to which this expression refers.
2558
  ///
2559
  /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2560
  /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2561
18.8M
  ValueDecl *getMemberDecl() const { return MemberDecl; }
2562
  void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2563
2564
  /// Retrieves the declaration found by lookup.
2565
582k
  DeclAccessPair getFoundDecl() const {
2566
582k
    if (!HasQualifierOrFoundDecl)
2567
570k
      return DeclAccessPair::make(getMemberDecl(),
2568
570k
                                  getMemberDecl()->getAccess());
2569
12.1k
    return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2570
12.1k
  }
2571
2572
  /// Determines whether this member expression actually had
2573
  /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2574
  /// x->Base::foo.
2575
7.50M
  bool hasQualifier() const { return getQualifier() != nullptr; }
2576
2577
  /// If the member name was qualified, retrieves the
2578
  /// nested-name-specifier that precedes the member name, with source-location
2579
  /// information.
2580
7.92M
  NestedNameSpecifierLoc getQualifierLoc() const {
2581
7.92M
    if (!HasQualifierOrFoundDecl)
2582
7.68M
      return NestedNameSpecifierLoc();
2583
232k
2584
232k
    return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2585
232k
  }
2586
2587
  /// If the member name was qualified, retrieves the
2588
  /// nested-name-specifier that precedes the member name. Otherwise, returns
2589
  /// NULL.
2590
7.85M
  NestedNameSpecifier *getQualifier() const {
2591
7.85M
    return getQualifierLoc().getNestedNameSpecifier();
2592
7.85M
  }
2593
2594
  /// Retrieve the location of the template keyword preceding
2595
  /// the member name, if any.
2596
239k
  SourceLocation getTemplateKeywordLoc() const {
2597
239k
    if (!HasTemplateKWAndArgsInfo) 
return SourceLocation()239k
;
2598
31
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2599
31
  }
2600
2601
  /// Retrieve the location of the left angle bracket starting the
2602
  /// explicit template argument list following the member name, if any.
2603
1.51M
  SourceLocation getLAngleLoc() const {
2604
1.51M
    if (!HasTemplateKWAndArgsInfo) 
return SourceLocation()1.51M
;
2605
1.62k
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2606
1.62k
  }
2607
2608
  /// Retrieve the location of the right angle bracket ending the
2609
  /// explicit template argument list following the member name, if any.
2610
1.43k
  SourceLocation getRAngleLoc() const {
2611
1.43k
    if (!HasTemplateKWAndArgsInfo) 
return SourceLocation()0
;
2612
1.43k
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2613
1.43k
  }
2614
2615
  /// Determines whether the member name was preceded by the template keyword.
2616
4.21k
  bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2617
2618
  /// Determines whether the member name was followed by an
2619
  /// explicit template argument list.
2620
1.51M
  bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2621
2622
  /// Copies the template arguments (if present) into the given
2623
  /// structure.
2624
  void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2625
    if (hasExplicitTemplateArgs())
2626
      getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2627
          getTrailingObjects<TemplateArgumentLoc>(), List);
2628
  }
2629
2630
  /// Retrieve the template arguments provided as part of this
2631
  /// template-id.
2632
14.9k
  const TemplateArgumentLoc *getTemplateArgs() const {
2633
14.9k
    if (!hasExplicitTemplateArgs())
2634
14.8k
      return nullptr;
2635
57
2636
57
    return getTrailingObjects<TemplateArgumentLoc>();
2637
57
  }
2638
2639
  /// Retrieve the number of template arguments provided as part of this
2640
  /// template-id.
2641
14.9k
  unsigned getNumTemplateArgs() const {
2642
14.9k
    if (!hasExplicitTemplateArgs())
2643
14.8k
      return 0;
2644
57
2645
57
    return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2646
57
  }
2647
2648
9
  ArrayRef<TemplateArgumentLoc> template_arguments() const {
2649
9
    return {getTemplateArgs(), getNumTemplateArgs()};
2650
9
  }
2651
2652
  /// Retrieve the member declaration name info.
2653
1.26M
  DeclarationNameInfo getMemberNameInfo() const {
2654
1.26M
    return DeclarationNameInfo(MemberDecl->getDeclName(),
2655
1.26M
                               MemberLoc, MemberDNLoc);
2656
1.26M
  }
2657
2658
6.31k
  SourceLocation getOperatorLoc() const LLVM_READONLY { return OperatorLoc; }
2659
2660
3.78M
  bool isArrow() const { return IsArrow; }
2661
  void setArrow(bool A) { IsArrow = A; }
2662
2663
  /// getMemberLoc - Return the location of the "member", in X->F, it is the
2664
  /// location of 'F'.
2665
5.99M
  SourceLocation getMemberLoc() const { return MemberLoc; }
2666
  void setMemberLoc(SourceLocation L) { MemberLoc = L; }
2667
2668
  SourceLocation getLocStart() const LLVM_READONLY;
2669
  SourceLocation getLocEnd() const LLVM_READONLY;
2670
2671
5.96M
  SourceLocation getExprLoc() const LLVM_READONLY { return MemberLoc; }
2672
2673
  /// Determine whether the base of this explicit is implicit.
2674
10.1M
  bool isImplicitAccess() const {
2675
10.1M
    return getBase() && getBase()->isImplicitCXXThis();
2676
10.1M
  }
2677
2678
  /// Returns true if this member expression refers to a method that
2679
  /// was resolved from an overloaded set having size greater than 1.
2680
6.30k
  bool hadMultipleCandidates() const {
2681
6.30k
    return HadMultipleCandidates;
2682
6.30k
  }
2683
  /// Sets the flag telling whether this expression refers to
2684
  /// a method that was resolved from an overloaded set having size
2685
  /// greater than 1.
2686
138k
  void setHadMultipleCandidates(bool V = true) {
2687
138k
    HadMultipleCandidates = V;
2688
138k
  }
2689
2690
  /// Returns true if virtual dispatch is performed.
2691
  /// If the member access is fully qualified, (i.e. X::f()), virtual
2692
  /// dispatching is not performed. In -fapple-kext mode qualified
2693
  /// calls to virtual method will still go through the vtable.
2694
2.69M
  bool performsVirtualDispatch(const LangOptions &LO) const {
2695
2.69M
    return LO.AppleKext || 
!hasQualifier()2.69M
;
2696
2.69M
  }
2697
2698
40.0M
  static bool classof(const Stmt *T) {
2699
40.0M
    return T->getStmtClass() == MemberExprClass;
2700
40.0M
  }
2701
2702
  // Iterators
2703
2.50M
  child_range children() { return child_range(&Base, &Base+1); }
2704
0
  const_child_range children() const {
2705
0
    return const_child_range(&Base, &Base + 1);
2706
0
  }
2707
2708
  friend TrailingObjects;
2709
  friend class ASTReader;
2710
  friend class ASTStmtWriter;
2711
};
2712
2713
/// CompoundLiteralExpr - [C99 6.5.2.5]
2714
///
2715
class CompoundLiteralExpr : public Expr {
2716
  /// LParenLoc - If non-null, this is the location of the left paren in a
2717
  /// compound literal like "(int){4}".  This can be null if this is a
2718
  /// synthesized compound expression.
2719
  SourceLocation LParenLoc;
2720
2721
  /// The type as written.  This can be an incomplete array type, in
2722
  /// which case the actual expression type will be different.
2723
  /// The int part of the pair stores whether this expr is file scope.
2724
  llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
2725
  Stmt *Init;
2726
public:
2727
  CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
2728
                      QualType T, ExprValueKind VK, Expr *init, bool fileScope)
2729
    : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
2730
           tinfo->getType()->isDependentType(),
2731
           init->isValueDependent(),
2732
           (init->isInstantiationDependent() ||
2733
            tinfo->getType()->isInstantiationDependentType()),
2734
           init->containsUnexpandedParameterPack()),
2735
27.2k
      LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
2736
2737
  /// Construct an empty compound literal.
2738
  explicit CompoundLiteralExpr(EmptyShell Empty)
2739
4
    : Expr(CompoundLiteralExprClass, Empty) { }
2740
2741
3.41k
  const Expr *getInitializer() const { return cast<Expr>(Init); }
2742
669
  Expr *getInitializer() { return cast<Expr>(Init); }
2743
4
  void setInitializer(Expr *E) { Init = E; }
2744
2745
3.51k
  bool isFileScope() const { return TInfoAndScope.getInt(); }
2746
4
  void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
2747
2748
553
  SourceLocation getLParenLoc() const { return LParenLoc; }
2749
4
  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
2750
2751
678
  TypeSourceInfo *getTypeSourceInfo() const {
2752
678
    return TInfoAndScope.getPointer();
2753
678
  }
2754
4
  void setTypeSourceInfo(TypeSourceInfo *tinfo) {
2755
4
    TInfoAndScope.setPointer(tinfo);
2756
4
  }
2757
2758
76.9k
  SourceLocation getLocStart() const LLVM_READONLY {
2759
76.9k
    // FIXME: Init should never be null.
2760
76.9k
    if (!Init)
2761
0
      return SourceLocation();
2762
76.9k
    if (LParenLoc.isInvalid())
2763
99
      return Init->getLocStart();
2764
76.8k
    return LParenLoc;
2765
76.8k
  }
2766
6.81k
  SourceLocation getLocEnd() const LLVM_READONLY {
2767
6.81k
    // FIXME: Init should never be null.
2768
6.81k
    if (!Init)
2769
0
      return SourceLocation();
2770
6.81k
    return Init->getLocEnd();
2771
6.81k
  }
2772
2773
6.22k
  static bool classof(const Stmt *T) {
2774
6.22k
    return T->getStmtClass() == CompoundLiteralExprClass;
2775
6.22k
  }
2776
2777
  // Iterators
2778
57.2k
  child_range children() { return child_range(&Init, &Init+1); }
2779
0
  const_child_range children() const {
2780
0
    return const_child_range(&Init, &Init + 1);
2781
0
  }
2782
};
2783
2784
/// CastExpr - Base class for type casts, including both implicit
2785
/// casts (ImplicitCastExpr) and explicit casts that have some
2786
/// representation in the source code (ExplicitCastExpr's derived
2787
/// classes).
2788
class CastExpr : public Expr {
2789
private:
2790
  Stmt *Op;
2791
2792
  bool CastConsistency() const;
2793
2794
161k
  const CXXBaseSpecifier * const *path_buffer() const {
2795
161k
    return const_cast<CastExpr*>(this)->path_buffer();
2796
161k
  }
2797
  CXXBaseSpecifier **path_buffer();
2798
2799
21.9M
  void setBasePathSize(unsigned basePathSize) {
2800
21.9M
    CastExprBits.BasePathSize = basePathSize;
2801
21.9M
    assert(CastExprBits.BasePathSize == basePathSize &&
2802
21.9M
           "basePathSize doesn't fit in bits of CastExprBits.BasePathSize!");
2803
21.9M
  }
2804
2805
protected:
2806
  CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
2807
           Expr *op, unsigned BasePathSize)
2808
      : Expr(SC, ty, VK, OK_Ordinary,
2809
             // Cast expressions are type-dependent if the type is
2810
             // dependent (C++ [temp.dep.expr]p3).
2811
             ty->isDependentType(),
2812
             // Cast expressions are value-dependent if the type is
2813
             // dependent or if the subexpression is value-dependent.
2814
             ty->isDependentType() || (op && op->isValueDependent()),
2815
             (ty->isInstantiationDependentType() ||
2816
              (op && op->isInstantiationDependent())),
2817
             // An implicit cast expression doesn't (lexically) contain an
2818
             // unexpanded pack, even if its target type does.
2819
             ((SC != ImplicitCastExprClass &&
2820
               ty->containsUnexpandedParameterPack()) ||
2821
              (op && op->containsUnexpandedParameterPack()))),
2822
21.8M
        Op(op) {
2823
21.8M
    CastExprBits.Kind = kind;
2824
21.8M
    setBasePathSize(BasePathSize);
2825
21.8M
    assert(CastConsistency());
2826
21.8M
  }
2827
2828
  /// Construct an empty cast.
2829
  CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
2830
99.3k
    : Expr(SC, Empty) {
2831
99.3k
    setBasePathSize(BasePathSize);
2832
99.3k
  }
2833
2834
public:
2835
69.1M
  CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
2836
99.3k
  void setCastKind(CastKind K) { CastExprBits.Kind = K; }
2837
2838
  static const char *getCastKindName(CastKind CK);
2839
2.37k
  const char *getCastKindName() const { return getCastKindName(getCastKind()); }
2840
2841
84.7M
  Expr *getSubExpr() { return cast<Expr>(Op); }
2842
94.9M
  const Expr *getSubExpr() const { return cast<Expr>(Op); }
2843
100k
  void setSubExpr(Expr *E) { Op = E; }
2844
2845
  /// Retrieve the cast subexpression as it was written in the source
2846
  /// code, looking through any implicit casts or other intermediate nodes
2847
  /// introduced by semantic analysis.
2848
  Expr *getSubExprAsWritten();
2849
276k
  const Expr *getSubExprAsWritten() const {
2850
276k
    return const_cast<CastExpr *>(this)->getSubExprAsWritten();
2851
276k
  }
2852
2853
  /// If this cast applies a user-defined conversion, retrieve the conversion
2854
  /// function that it invokes.
2855
  NamedDecl *getConversionFunction() const;
2856
2857
  typedef CXXBaseSpecifier **path_iterator;
2858
  typedef const CXXBaseSpecifier * const *path_const_iterator;
2859
1.18k
  bool path_empty() const { return CastExprBits.BasePathSize == 0; }
2860
760k
  unsigned path_size() const { return CastExprBits.BasePathSize; }
2861
347k
  path_iterator path_begin() { return path_buffer(); }
2862
247k
  path_iterator path_end() { return path_buffer() + path_size(); }
2863
80.7k
  path_const_iterator path_begin() const { return path_buffer(); }
2864
80.7k
  path_const_iterator path_end() const { return path_buffer() + path_size(); }
2865
2866
4
  const FieldDecl *getTargetUnionField() const {
2867
4
    assert(getCastKind() == CK_ToUnion);
2868
4
    return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
2869
4
  }
2870
2871
  static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
2872
                                                       QualType opType);
2873
  static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
2874
                                                       QualType opType);
2875
2876
97.0M
  static bool classof(const Stmt *T) {
2877
97.0M
    return T->getStmtClass() >= firstCastExprConstant &&
2878
97.0M
           
T->getStmtClass() <= lastCastExprConstant86.4M
;
2879
97.0M
  }
2880
2881
  // Iterators
2882
25.9M
  child_range children() { return child_range(&Op, &Op+1); }
2883
0
  const_child_range children() const { return const_child_range(&Op, &Op + 1); }
2884
};
2885
2886
/// ImplicitCastExpr - Allows us to explicitly represent implicit type
2887
/// conversions, which have no direct representation in the original
2888
/// source code. For example: converting T[]->T*, void f()->void
2889
/// (*f)(), float->double, short->int, etc.
2890
///
2891
/// In C, implicit casts always produce rvalues. However, in C++, an
2892
/// implicit cast whose result is being bound to a reference will be
2893
/// an lvalue or xvalue. For example:
2894
///
2895
/// @code
2896
/// class Base { };
2897
/// class Derived : public Base { };
2898
/// Derived &&ref();
2899
/// void f(Derived d) {
2900
///   Base& b = d; // initializer is an ImplicitCastExpr
2901
///                // to an lvalue of type Base
2902
///   Base&& r = ref(); // initializer is an ImplicitCastExpr
2903
///                     // to an xvalue of type Base
2904
/// }
2905
/// @endcode
2906
class ImplicitCastExpr final
2907
    : public CastExpr,
2908
      private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
2909
private:
2910
  ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
2911
                   unsigned BasePathLength, ExprValueKind VK)
2912
17.5M
    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) {
2913
17.5M
  }
2914
2915
  /// Construct an empty implicit cast.
2916
  explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
2917
98.3k
    : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
2918
2919
public:
2920
  enum OnStack_t { OnStack };
2921
  ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
2922
                   ExprValueKind VK)
2923
1.07M
    : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
2924
1.07M
  }
2925
2926
  static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
2927
                                  CastKind Kind, Expr *Operand,
2928
                                  const CXXCastPath *BasePath,
2929
                                  ExprValueKind Cat);
2930
2931
  static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
2932
                                       unsigned PathSize);
2933
2934
49.9M
  SourceLocation getLocStart() const LLVM_READONLY {
2935
49.9M
    return getSubExpr()->getLocStart();
2936
49.9M
  }
2937
4.43M
  SourceLocation getLocEnd() const LLVM_READONLY {
2938
4.43M
    return getSubExpr()->getLocEnd();
2939
4.43M
  }
2940
2941
208M
  static bool classof(const Stmt *T) {
2942
208M
    return T->getStmtClass() == ImplicitCastExprClass;
2943
208M
  }
2944
2945
  friend TrailingObjects;
2946
  friend class CastExpr;
2947
};
2948
2949
6.27M
inline Expr *Expr::IgnoreImpCasts() {
2950
6.27M
  Expr *e = this;
2951
9.16M
  while (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e))
2952
2.89M
    e = ice->getSubExpr();
2953
6.27M
  return e;
2954
6.27M
}
2955
2956
/// ExplicitCastExpr - An explicit cast written in the source
2957
/// code.
2958
///
2959
/// This class is effectively an abstract class, because it provides
2960
/// the basic representation of an explicitly-written cast without
2961
/// specifying which kind of cast (C cast, functional cast, static
2962
/// cast, etc.) was written; specific derived classes represent the
2963
/// particular style of cast and its location information.
2964
///
2965
/// Unlike implicit casts, explicit cast nodes have two different
2966
/// types: the type that was written into the source code, and the
2967
/// actual type of the expression as determined by semantic
2968
/// analysis. These types may differ slightly. For example, in C++ one
2969
/// can cast to a reference type, which indicates that the resulting
2970
/// expression will be an lvalue or xvalue. The reference type, however,
2971
/// will not be used as the type of the expression.
2972
class ExplicitCastExpr : public CastExpr {
2973
  /// TInfo - Source type info for the (written) type
2974
  /// this expression is casting to.
2975
  TypeSourceInfo *TInfo;
2976
2977
protected:
2978
  ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
2979
                   CastKind kind, Expr *op, unsigned PathSize,
2980
                   TypeSourceInfo *writtenTy)
2981
3.17M
    : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
2982
2983
  /// Construct an empty explicit cast.
2984
  ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
2985
1.02k
    : CastExpr(SC, Shell, PathSize) { }
2986
2987
public:
2988
  /// getTypeInfoAsWritten - Returns the type source info for the type
2989
  /// that this expression is casting to.
2990
624k
  TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
2991
1.02k
  void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
2992
2993
  /// getTypeAsWritten - Returns the type that this expression is
2994
  /// casting to, as written in the source code.
2995
236k
  QualType getTypeAsWritten() const { return TInfo->getType(); }
2996
2997
43.1M
  static bool classof(const Stmt *T) {
2998
43.1M
     return T->getStmtClass() >= firstExplicitCastExprConstant &&
2999
43.1M
            
T->getStmtClass() <= lastExplicitCastExprConstant33.0M
;
3000
43.1M
  }
3001
};
3002
3003
/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3004
/// cast in C++ (C++ [expr.cast]), which uses the syntax
3005
/// (Type)expr. For example: @c (int)f.
3006
class CStyleCastExpr final
3007
    : public ExplicitCastExpr,
3008
      private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
3009
  SourceLocation LPLoc; // the location of the left paren
3010
  SourceLocation RPLoc; // the location of the right paren
3011
3012
  CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3013
                 unsigned PathSize, TypeSourceInfo *writtenTy,
3014
                 SourceLocation l, SourceLocation r)
3015
    : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3016
2.86M
                       writtenTy), LPLoc(l), RPLoc(r) {}
3017
3018
  /// Construct an empty C-style explicit cast.
3019
  explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
3020
940
    : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
3021
3022
public:
3023
  static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
3024
                                ExprValueKind VK, CastKind K,
3025
                                Expr *Op, const CXXCastPath *BasePath,
3026
                                TypeSourceInfo *WrittenTy, SourceLocation L,
3027
                                SourceLocation R);
3028
3029
  static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3030
                                     unsigned PathSize);
3031
3032
128k
  SourceLocation getLParenLoc() const { return LPLoc; }
3033
940
  void setLParenLoc(SourceLocation L) { LPLoc = L; }
3034
3035
128k
  SourceLocation getRParenLoc() const { return RPLoc; }
3036
940
  void setRParenLoc(SourceLocation L) { RPLoc = L; }
3037
3038
11.7M
  SourceLocation getLocStart() const LLVM_READONLY { return LPLoc; }
3039
99.1k
  SourceLocation getLocEnd() const LLVM_READONLY {
3040
99.1k
    return getSubExpr()->getLocEnd();
3041
99.1k
  }
3042
3043
1.45M
  static bool classof(const Stmt *T) {
3044
1.45M
    return T->getStmtClass() == CStyleCastExprClass;
3045
1.45M
  }
3046
3047
  friend TrailingObjects;
3048
  friend class CastExpr;
3049
};
3050
3051
/// A builtin binary operation expression such as "x + y" or "x <= y".
3052
///
3053
/// This expression node kind describes a builtin binary operation,
3054
/// such as "x + y" for integer values "x" and "y". The operands will
3055
/// already have been converted to appropriate types (e.g., by
3056
/// performing promotions or conversions).
3057
///
3058
/// In C++, where operators may be overloaded, a different kind of
3059
/// expression node (CXXOperatorCallExpr) is used to express the
3060
/// invocation of an overloaded operator with operator syntax. Within
3061
/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3062
/// used to store an expression "x + y" depends on the subexpressions
3063
/// for x and y. If neither x or y is type-dependent, and the "+"
3064
/// operator resolves to a built-in operation, BinaryOperator will be
3065
/// used to express the computation (x and y may still be
3066
/// value-dependent). If either x or y is type-dependent, or if the
3067
/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3068
/// be used to express the computation.
3069
class BinaryOperator : public Expr {
3070
public:
3071
  typedef BinaryOperatorKind Opcode;
3072
3073
private:
3074
  unsigned Opc : 6;
3075
3076
  // This is only meaningful for operations on floating point types and 0
3077
  // otherwise.
3078
  unsigned FPFeatures : 2;
3079
  SourceLocation OpLoc;
3080
3081
  enum { LHS, RHS, END_EXPR };
3082
  Stmt* SubExprs[END_EXPR];
3083
public:
3084
3085
  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3086
                 ExprValueKind VK, ExprObjectKind OK,
3087
                 SourceLocation opLoc, FPOptions FPFeatures)
3088
    : Expr(BinaryOperatorClass, ResTy, VK, OK,
3089
           lhs->isTypeDependent() || rhs->isTypeDependent(),
3090
           lhs->isValueDependent() || rhs->isValueDependent(),
3091
           (lhs->isInstantiationDependent() ||
3092
            rhs->isInstantiationDependent()),
3093
           (lhs->containsUnexpandedParameterPack() ||
3094
            rhs->containsUnexpandedParameterPack())),
3095
6.06M
      Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3096
6.06M
    SubExprs[LHS] = lhs;
3097
6.06M
    SubExprs[RHS] = rhs;
3098
6.06M
    assert(!isCompoundAssignmentOp() &&
3099
6.06M
           "Use CompoundAssignOperator for compound assignments");
3100
6.06M
  }
3101
3102
  /// Construct an empty binary operator.
3103
  explicit BinaryOperator(EmptyShell Empty)
3104
102k
    : Expr(BinaryOperatorClass, Empty), Opc(BO_Comma) { }
3105
3106
10.8M
  SourceLocation getExprLoc() const LLVM_READONLY { return OpLoc; }
3107
5.49M
  SourceLocation getOperatorLoc() const { return OpLoc; }
3108
106k
  void setOperatorLoc(SourceLocation L) { OpLoc = L; }
3109
3110
106M
  Opcode getOpcode() const { return static_cast<Opcode>(Opc); }
3111
106k
  void setOpcode(Opcode O) { Opc = O; }
3112
3113
39.7M
  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3114
106k
  void setLHS(Expr *E) { SubExprs[LHS] = E; }
3115
28.3M
  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3116
106k
  void setRHS(Expr *E) { SubExprs[RHS] = E; }
3117
3118
6.19M
  SourceLocation getLocStart() const LLVM_READONLY {
3119
6.19M
    return getLHS()->getLocStart();
3120
6.19M
  }
3121
742k
  SourceLocation getLocEnd() const LLVM_READONLY {
3122
742k
    return getRHS()->getLocEnd();
3123
742k
  }
3124
3125
  /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3126
  /// corresponds to, e.g. "<<=".
3127
  static StringRef getOpcodeStr(Opcode Op);
3128
3129
1.28k
  StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3130
3131
  /// Retrieve the binary opcode that corresponds to the given
3132
  /// overloaded operator.
3133
  static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3134
3135
  /// Retrieve the overloaded operator kind that corresponds to
3136
  /// the given binary opcode.
3137
  static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3138
3139
  /// predicates to categorize the respective opcodes.
3140
151k
  bool isPtrMemOp() const { return Opc == BO_PtrMemD || 
Opc == BO_PtrMemI151k
; }
3141
165k
  static bool isMultiplicativeOp(Opcode Opc) {
3142
165k
    return Opc >= BO_Mul && Opc <= BO_Rem;
3143
165k
  }
3144
2.05k
  bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
3145
2.60M
  static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || 
Opc==BO_Sub2.19M
; }
3146
2.42M
  bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3147
177k
  static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || 
Opc == BO_Shr176k
; }
3148
209
  bool isShiftOp() const { return isShiftOp(getOpcode()); }
3149
3150
4.66M
  static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && 
Opc <= BO_Or1.96M
; }
3151
16.9k
  bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3152
3153
1.56M
  static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && 
Opc<=BO_GE1.56M
; }
3154
401k
  bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3155
3156
507k
  static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || 
Opc == BO_NE328k
; }
3157
451k
  bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3158
3159
9.62M
  static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && 
Opc<=BO_NE6.23M
; }
3160
4.69M
  bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3161
3162
71.4k
  static Opcode negateComparisonOp(Opcode Opc) {
3163
71.4k
    switch (Opc) {
3164
71.4k
    default:
3165
0
      llvm_unreachable("Not a comparison operator.");
3166
71.4k
    
case BO_LT: return BO_GE460
;
3167
71.4k
    
case BO_GT: return BO_LE787
;
3168
71.4k
    
case BO_LE: return BO_GT2.56k
;
3169
71.4k
    
case BO_GE: return BO_LT1.08k
;
3170
71.4k
    
case BO_EQ: return BO_NE2.83k
;
3171
71.4k
    
case BO_NE: return BO_EQ63.7k
;
3172
71.4k
    }
3173
71.4k
  }
3174
3175
1.36k
  static Opcode reverseComparisonOp(Opcode Opc) {
3176
1.36k
    switch (Opc) {
3177
1.36k
    default:
3178
0
      llvm_unreachable("Not a comparison operator.");
3179
1.36k
    
case BO_LT: return BO_GT476
;
3180
1.36k
    
case BO_GT: return BO_LT54
;
3181
1.36k
    
case BO_LE: return BO_GE31
;
3182
1.36k
    
case BO_GE: return BO_LE63
;
3183
1.36k
    case BO_EQ:
3184
736
    case BO_NE:
3185
736
      return Opc;
3186
1.36k
    }
3187
1.36k
  }
3188
3189
22.7M
  static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || 
Opc==BO_LOr21.5M
; }
3190
22.7M
  bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3191
3192
11.7M
  static bool isAssignmentOp(Opcode Opc) {
3193
11.7M
    return Opc >= BO_Assign && 
Opc <= BO_OrAssign1.54M
;
3194
11.7M
  }
3195
11.7M
  bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3196
3197
694k
  static bool isCompoundAssignmentOp(Opcode Opc) {
3198
694k
    return Opc > BO_Assign && 
Opc <= BO_OrAssign12.7k
;
3199
694k
  }
3200
694k
  bool isCompoundAssignmentOp() const {
3201
694k
    return isCompoundAssignmentOp(getOpcode());
3202
694k
  }
3203
19.8k
  static Opcode getOpForCompoundAssignment(Opcode Opc) {
3204
19.8k
    assert(isCompoundAssignmentOp(Opc));
3205
19.8k
    if (Opc >= BO_AndAssign)
3206
4.95k
      return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3207
14.9k
    else
3208
14.9k
      return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3209
19.8k
  }
3210
3211
  static bool isShiftAssignOp(Opcode Opc) {
3212
    return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3213
  }
3214
  bool isShiftAssignOp() const {
3215
    return isShiftAssignOp(getOpcode());
3216
  }
3217
3218
  // Return true if a binary operator using the specified opcode and operands
3219
  // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3220
  // integer to a pointer.
3221
  static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3222
                                               Expr *LHS, Expr *RHS);
3223
3224
248M
  static bool classof(const Stmt *S) {
3225
248M
    return S->getStmtClass() >= firstBinaryOperatorConstant &&
3226
248M
           
S->getStmtClass() <= lastBinaryOperatorConstant243M
;
3227
248M
  }
3228
3229
  // Iterators
3230
8.31M
  child_range children() {
3231
8.31M
    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3232
8.31M
  }
3233
0
  const_child_range children() const {
3234
0
    return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3235
0
  }
3236
3237
  // Set the FP contractability status of this operator. Only meaningful for
3238
  // operations on floating point types.
3239
106k
  void setFPFeatures(FPOptions F) { FPFeatures = F.getInt(); }
3240
3241
1.47M
  FPOptions getFPFeatures() const { return FPOptions(FPFeatures); }
3242
3243
  // Get the FP contractability status of this operator. Only meaningful for
3244
  // operations on floating point types.
3245
  bool isFPContractableWithinStatement() const {
3246
    return FPOptions(FPFeatures).allowFPContractWithinStatement();
3247
  }
3248
3249
protected:
3250
  BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3251
                 ExprValueKind VK, ExprObjectKind OK,
3252
                 SourceLocation opLoc, FPOptions FPFeatures, bool dead2)
3253
    : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3254
           lhs->isTypeDependent() || rhs->isTypeDependent(),
3255
           lhs->isValueDependent() || rhs->isValueDependent(),
3256
           (lhs->isInstantiationDependent() ||
3257
            rhs->isInstantiationDependent()),
3258
           (lhs->containsUnexpandedParameterPack() ||
3259
            rhs->containsUnexpandedParameterPack())),
3260
189k
      Opc(opc), FPFeatures(FPFeatures.getInt()), OpLoc(opLoc) {
3261
189k
    SubExprs[LHS] = lhs;
3262
189k
    SubExprs[RHS] = rhs;
3263
189k
  }
3264
3265
  BinaryOperator(StmtClass SC, EmptyShell Empty)
3266
4.24k
    : Expr(SC, Empty), Opc(BO_MulAssign) { }
3267
};
3268
3269
/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3270
/// track of the type the operation is performed in.  Due to the semantics of
3271
/// these operators, the operands are promoted, the arithmetic performed, an
3272
/// implicit conversion back to the result type done, then the assignment takes
3273
/// place.  This captures the intermediate type which the computation is done
3274
/// in.
3275
class CompoundAssignOperator : public BinaryOperator {
3276
  QualType ComputationLHSType;
3277
  QualType ComputationResultType;
3278
public:
3279
  CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3280
                         ExprValueKind VK, ExprObjectKind OK,
3281
                         QualType CompLHSType, QualType CompResultType,
3282
                         SourceLocation OpLoc, FPOptions FPFeatures)
3283
    : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3284
                     true),
3285
      ComputationLHSType(CompLHSType),
3286
189k
      ComputationResultType(CompResultType) {
3287
189k
    assert(isCompoundAssignmentOp() &&
3288
189k
           "Only should be used for compound assignments");
3289
189k
  }
3290
3291
  /// Build an empty compound assignment operator expression.
3292
  explicit CompoundAssignOperator(EmptyShell Empty)
3293
4.24k
    : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3294
3295
  // The two computation types are the type the LHS is converted
3296
  // to for the computation and the type of the result; the two are
3297
  // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3298
70.4k
  QualType getComputationLHSType() const { return ComputationLHSType; }
3299
4.24k
  void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3300
3301
232k
  QualType getComputationResultType() const { return ComputationResultType; }
3302
4.24k
  void setComputationResultType(QualType T) { ComputationResultType = T; }
3303
3304
2.08M
  static bool classof(const Stmt *S) {
3305
2.08M
    return S->getStmtClass() == CompoundAssignOperatorClass;
3306
2.08M
  }
3307
};
3308
3309
/// AbstractConditionalOperator - An abstract base class for
3310
/// ConditionalOperator and BinaryConditionalOperator.
3311
class AbstractConditionalOperator : public Expr {
3312
  SourceLocation QuestionLoc, ColonLoc;
3313
  friend class ASTStmtReader;
3314
3315
protected:
3316
  AbstractConditionalOperator(StmtClass SC, QualType T,
3317
                              ExprValueKind VK, ExprObjectKind OK,
3318
                              bool TD, bool VD, bool ID,
3319
                              bool ContainsUnexpandedParameterPack,
3320
                              SourceLocation qloc,
3321
                              SourceLocation cloc)
3322
    : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3323
224k
      QuestionLoc(qloc), ColonLoc(cloc) {}
3324
3325
  AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3326
4.22k
    : Expr(SC, Empty) { }
3327
3328
public:
3329
  // getCond - Return the expression representing the condition for
3330
  //   the ?: operator.
3331
  Expr *getCond() const;
3332
3333
  // getTrueExpr - Return the subexpression representing the value of
3334
  //   the expression if the condition evaluates to true.
3335
  Expr *getTrueExpr() const;
3336
3337
  // getFalseExpr - Return the subexpression representing the value of
3338
  //   the expression if the condition evaluates to false.  This is
3339
  //   the same as getRHS.
3340
  Expr *getFalseExpr() const;
3341
3342
198k
  SourceLocation getQuestionLoc() const { return QuestionLoc; }
3343
29.6k
  SourceLocation getColonLoc() const { return ColonLoc; }
3344
3345
1.77k
  static bool classof(const Stmt *T) {
3346
1.77k
    return T->getStmtClass() == ConditionalOperatorClass ||
3347
1.77k
           
T->getStmtClass() == BinaryConditionalOperatorClass1.75k
;
3348
1.77k
  }
3349
};
3350
3351
/// ConditionalOperator - The ?: ternary operator.  The GNU "missing
3352
/// middle" extension is a BinaryConditionalOperator.
3353
class ConditionalOperator : public AbstractConditionalOperator {
3354
  enum { COND, LHS, RHS, END_EXPR };
3355
  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3356
3357
  friend class ASTStmtReader;
3358
public:
3359
  ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3360
                      SourceLocation CLoc, Expr *rhs,
3361
                      QualType t, ExprValueKind VK, ExprObjectKind OK)
3362
    : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3363
           // FIXME: the type of the conditional operator doesn't
3364
           // depend on the type of the conditional, but the standard
3365
           // seems to imply that it could. File a bug!
3366
           (lhs->isTypeDependent() || rhs->isTypeDependent()),
3367
           (cond->isValueDependent() || lhs->isValueDependent() ||
3368
            rhs->isValueDependent()),
3369
           (cond->isInstantiationDependent() ||
3370
            lhs->isInstantiationDependent() ||
3371
            rhs->isInstantiationDependent()),
3372
           (cond->containsUnexpandedParameterPack() ||
3373
            lhs->containsUnexpandedParameterPack() ||
3374
            rhs->containsUnexpandedParameterPack()),
3375
224k
                                  QLoc, CLoc) {
3376
224k
    SubExprs[COND] = cond;
3377
224k
    SubExprs[LHS] = lhs;
3378
224k
    SubExprs[RHS] = rhs;
3379
224k
  }
3380
3381
  /// Build an empty conditional operator.
3382
  explicit ConditionalOperator(EmptyShell Empty)
3383
4.22k
    : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3384
3385
  // getCond - Return the expression representing the condition for
3386
  //   the ?: operator.
3387
1.49M
  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3388
3389
  // getTrueExpr - Return the subexpression representing the value of
3390
  //   the expression if the condition evaluates to true.
3391
514k
  Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3392
3393
  // getFalseExpr - Return the subexpression representing the value of
3394
  //   the expression if the condition evaluates to false.  This is
3395
  //   the same as getRHS.
3396
509k
  Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3397
3398
204k
  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3399
216k
  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3400
3401
508k
  SourceLocation getLocStart() const LLVM_READONLY {
3402
508k
    return getCond()->getLocStart();
3403
508k
  }
3404
7.07k
  SourceLocation getLocEnd() const LLVM_READONLY {
3405
7.07k
    return getRHS()->getLocEnd();
3406
7.07k
  }
3407
3408
36.9M
  static bool classof(const Stmt *T) {
3409
36.9M
    return T->getStmtClass() == ConditionalOperatorClass;
3410
36.9M
  }
3411
3412
  // Iterators
3413
103k
  child_range children() {
3414
103k
    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3415
103k
  }
3416
0
  const_child_range children() const {
3417
0
    return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3418
0
  }
3419
};
3420
3421
/// BinaryConditionalOperator - The GNU extension to the conditional
3422
/// operator which allows the middle operand to be omitted.
3423
///
3424
/// This is a different expression kind on the assumption that almost
3425
/// every client ends up needing to know that these are different.
3426
class BinaryConditionalOperator : public AbstractConditionalOperator {
3427
  enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3428
3429
  /// - the common condition/left-hand-side expression, which will be
3430
  ///   evaluated as the opaque value
3431
  /// - the condition, expressed in terms of the opaque value
3432
  /// - the left-hand-side, expressed in terms of the opaque value
3433
  /// - the right-hand-side
3434
  Stmt *SubExprs[NUM_SUBEXPRS];
3435
  OpaqueValueExpr *OpaqueValue;
3436
3437
  friend class ASTStmtReader;
3438
public:
3439
  BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3440
                            Expr *cond, Expr *lhs, Expr *rhs,
3441
                            SourceLocation qloc, SourceLocation cloc,
3442
                            QualType t, ExprValueKind VK, ExprObjectKind OK)
3443
    : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3444
           (common->isTypeDependent() || rhs->isTypeDependent()),
3445
           (common->isValueDependent() || rhs->isValueDependent()),
3446
           (common->isInstantiationDependent() ||
3447
            rhs->isInstantiationDependent()),
3448
           (common->containsUnexpandedParameterPack() ||
3449
            rhs->containsUnexpandedParameterPack()),
3450
                                  qloc, cloc),
3451
207
      OpaqueValue(opaqueValue) {
3452
207
    SubExprs[COMMON] = common;
3453
207
    SubExprs[COND] = cond;
3454
207
    SubExprs[LHS] = lhs;
3455
207
    SubExprs[RHS] = rhs;
3456
207
    assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value");
3457
207
  }
3458
3459
  /// Build an empty conditional operator.
3460
  explicit BinaryConditionalOperator(EmptyShell Empty)
3461
1
    : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3462
3463
  /// getCommon - Return the common expression, written to the
3464
  ///   left of the condition.  The opaque value will be bound to the
3465
  ///   result of this expression.
3466
2.04k
  Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3467
3468
  /// getOpaqueValue - Return the opaque value placeholder.
3469
694
  OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3470
3471
  /// getCond - Return the condition expression; this is defined
3472
  ///   in terms of the opaque value.
3473
1.51k
  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3474
3475
  /// getTrueExpr - Return the subexpression which will be
3476
  ///   evaluated if the condition evaluates to true;  this is defined
3477
  ///   in terms of the opaque value.
3478
1.06k
  Expr *getTrueExpr() const {
3479
1.06k
    return cast<Expr>(SubExprs[LHS]);
3480
1.06k
  }
3481
3482
  /// getFalseExpr - Return the subexpression which will be
3483
  ///   evaluated if the condnition evaluates to false; this is
3484
  ///   defined in terms of the opaque value.
3485
964
  Expr *getFalseExpr() const {
3486
964
    return cast<Expr>(SubExprs[RHS]);
3487
964
  }
3488
3489
1.22k
  SourceLocation getLocStart() const LLVM_READONLY {
3490
1.22k
    return getCommon()->getLocStart();
3491
1.22k
  }
3492
196
  SourceLocation getLocEnd() const LLVM_READONLY {
3493
196
    return getFalseExpr()->getLocEnd();
3494
196
  }
3495
3496
1.55M
  static bool classof(const Stmt *T) {
3497
1.55M
    return T->getStmtClass() == BinaryConditionalOperatorClass;
3498
1.55M
  }
3499
3500
  // Iterators
3501
440
  child_range children() {
3502
440
    return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3503
440
  }
3504
0
  const_child_range children() const {
3505
0
    return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3506
0
  }
3507
};
3508
3509
392k
inline Expr *AbstractConditionalOperator::getCond() const {
3510
392k
  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3511
391k
    return co->getCond();
3512
906
  return cast<BinaryConditionalOperator>(this)->getCond();
3513
906
}
3514
3515
210k
inline Expr *AbstractConditionalOperator::getTrueExpr() const {
3516
210k
  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3517
210k
    return co->getTrueExpr();
3518
500
  return cast<BinaryConditionalOperator>(this)->getTrueExpr();
3519
500
}
3520
3521
190k
inline Expr *AbstractConditionalOperator::getFalseExpr() const {
3522
190k
  if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3523
189k
    return co->getFalseExpr();
3524
436
  return cast<BinaryConditionalOperator>(this)->getFalseExpr();
3525
436
}
3526
3527
/// AddrLabelExpr - The GNU address of label extension, representing &&label.
3528
class AddrLabelExpr : public Expr {
3529
  SourceLocation AmpAmpLoc, LabelLoc;
3530
  LabelDecl *Label;
3531
public:
3532
  AddrLabelExpr(SourceLocation AALoc, SourceLocation LLoc, LabelDecl *L,
3533
                QualType t)
3534
    : Expr(AddrLabelExprClass, t, VK_RValue, OK_Ordinary, false, false, false,
3535
           false),
3536
272
      AmpAmpLoc(AALoc), LabelLoc(LLoc), Label(L) {}
3537
3538
  /// Build an empty address of a label expression.
3539
  explicit AddrLabelExpr(EmptyShell Empty)
3540
2
    : Expr(AddrLabelExprClass, Empty) { }
3541
3542
10
  SourceLocation getAmpAmpLoc() const { return AmpAmpLoc; }
3543
2
  void setAmpAmpLoc(SourceLocation L) { AmpAmpLoc = L; }
3544
11
  SourceLocation getLabelLoc() const { return LabelLoc; }
3545
2
  void setLabelLoc(SourceLocation L) { LabelLoc = L; }
3546
3547
1.55k
  SourceLocation getLocStart() const LLVM_READONLY { return AmpAmpLoc; }
3548
364
  SourceLocation getLocEnd() const LLVM_READONLY { return LabelLoc; }
3549
3550
734
  LabelDecl *getLabel() const { return Label; }
3551
2
  void setLabel(LabelDecl *L) { Label = L; }
3552
3553
290
  static bool classof(const Stmt *T) {
3554
290
    return T->getStmtClass() == AddrLabelExprClass;
3555
290
  }
3556
3557
  // Iterators
3558
1.14k
  child_range children() {
3559
1.14k
    return child_range(child_iterator(), child_iterator());
3560
1.14k
  }
3561
0
  const_child_range children() const {
3562
0
    return const_child_range(const_child_iterator(), const_child_iterator());
3563
0
  }
3564
};
3565
3566
/// StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
3567
/// The StmtExpr contains a single CompoundStmt node, which it evaluates and
3568
/// takes the value of the last subexpression.
3569
///
3570
/// A StmtExpr is always an r-value; values "returned" out of a
3571
/// StmtExpr will be copied.
3572
class StmtExpr : public Expr {
3573
  Stmt *SubStmt;
3574
  SourceLocation LParenLoc, RParenLoc;
3575
public:
3576
  // FIXME: Does type-dependence need to be computed differently?
3577
  // FIXME: Do we need to compute instantiation instantiation-dependence for
3578
  // statements? (ugh!)
3579
  StmtExpr(CompoundStmt *substmt, QualType T,
3580
           SourceLocation lp, SourceLocation rp) :
3581
    Expr(StmtExprClass, T, VK_RValue, OK_Ordinary,
3582
         T->isDependentType(), false, false, false),
3583
10.6k
    SubStmt(substmt), LParenLoc(lp), RParenLoc(rp) { }
3584
3585
  /// Build an empty statement expression.
3586
13
  explicit StmtExpr(EmptyShell Empty) : Expr(StmtExprClass, Empty) { }
3587
3588
2.55k
  CompoundStmt *getSubStmt() { return cast<CompoundStmt>(SubStmt); }
3589
12.8k
  const CompoundStmt *getSubStmt() const { return cast<CompoundStmt>(SubStmt); }
3590
13
  void setSubStmt(CompoundStmt *S) { SubStmt = S; }
3591
3592
20.2k
  SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
3593
333
  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3594
3595
29
  SourceLocation getLParenLoc() const { return LParenLoc; }
3596
13
  void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3597
29
  SourceLocation getRParenLoc() const { return RParenLoc; }
3598
13
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3599
3600
41.4M
  static bool classof(const Stmt *T) {
3601
41.4M
    return T->getStmtClass() == StmtExprClass;
3602
41.4M
  }
3603
3604
  // Iterators
3605
18.0k
  child_range children() { return child_range(&SubStmt, &SubStmt+1); }
3606
0
  const_child_range children() const {
3607
0
    return const_child_range(&SubStmt, &SubStmt + 1);
3608
0
  }
3609
};
3610
3611
/// ShuffleVectorExpr - clang-specific builtin-in function
3612
/// __builtin_shufflevector.
3613
/// This AST node represents a operator that does a constant
3614
/// shuffle, similar to LLVM's shufflevector instruction. It takes
3615
/// two vectors and a variable number of constant indices,
3616
/// and returns the appropriately shuffled vector.
3617
class ShuffleVectorExpr : public Expr {
3618
  SourceLocation BuiltinLoc, RParenLoc;
3619
3620
  // SubExprs - the list of values passed to the __builtin_shufflevector
3621
  // function. The first two are vectors, and the rest are constant
3622
  // indices.  The number of values in this list is always
3623
  // 2+the number of indices in the vector type.
3624
  Stmt **SubExprs;
3625
  unsigned NumExprs;
3626
3627
public:
3628
  ShuffleVectorExpr(const ASTContext &C, ArrayRef<Expr*> args, QualType Type,
3629
                    SourceLocation BLoc, SourceLocation RP);
3630
3631
  /// Build an empty vector-shuffle expression.
3632
  explicit ShuffleVectorExpr(EmptyShell Empty)
3633
2
    : Expr(ShuffleVectorExprClass, Empty), SubExprs(nullptr) { }
3634
3635
1.30k
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3636
2
  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3637
3638
1.30k
  SourceLocation getRParenLoc() const { return RParenLoc; }
3639
2
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3640
3641
202k
  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3642
19.7k
  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3643
3644
0
  static bool classof(const Stmt *T) {
3645
0
    return T->getStmtClass() == ShuffleVectorExprClass;
3646
0
  }
3647
3648
  /// getNumSubExprs - Return the size of the SubExprs array.  This includes the
3649
  /// constant expression, the actual arguments passed in, and the function
3650
  /// pointers.
3651
16.0k
  unsigned getNumSubExprs() const { return NumExprs; }
3652
3653
  /// Retrieve the array of expressions.
3654
4
  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
3655
3656
  /// getExpr - Return the Expr at the specified index.
3657
15.5k
  Expr *getExpr(unsigned Index) {
3658
15.5k
    assert((Index < NumExprs) && "Arg access out of range!");
3659
15.5k
    return cast<Expr>(SubExprs[Index]);
3660
15.5k
  }
3661
9.99k
  const Expr *getExpr(unsigned Index) const {
3662
9.99k
    assert((Index < NumExprs) && "Arg access out of range!");
3663
9.99k
    return cast<Expr>(SubExprs[Index]);
3664
9.99k
  }
3665
3666
  void setExprs(const ASTContext &C, ArrayRef<Expr *> Exprs);
3667
3668
9.99k
  llvm::APSInt getShuffleMaskIdx(const ASTContext &Ctx, unsigned N) const {
3669
9.99k
    assert((N < NumExprs - 2) && "Shuffle idx out of range!");
3670
9.99k
    return getExpr(N+2)->EvaluateKnownConstInt(Ctx);
3671
9.99k
  }
3672
3673
  // Iterators
3674
138k
  child_range children() {
3675
138k
    return child_range(&SubExprs[0], &SubExprs[0]+NumExprs);
3676
138k
  }
3677
0
  const_child_range children() const {
3678
0
    return const_child_range(&SubExprs[0], &SubExprs[0] + NumExprs);
3679
0
  }
3680
};
3681
3682
/// ConvertVectorExpr - Clang builtin function __builtin_convertvector
3683
/// This AST node provides support for converting a vector type to another
3684
/// vector type of the same arity.
3685
class ConvertVectorExpr : public Expr {
3686
private:
3687
  Stmt *SrcExpr;
3688
  TypeSourceInfo *TInfo;
3689
  SourceLocation BuiltinLoc, RParenLoc;
3690
3691
  friend class ASTReader;
3692
  friend class ASTStmtReader;
3693
0
  explicit ConvertVectorExpr(EmptyShell Empty) : Expr(ConvertVectorExprClass, Empty) {}
3694
3695
public:
3696
  ConvertVectorExpr(Expr* SrcExpr, TypeSourceInfo *TI, QualType DstType,
3697
             ExprValueKind VK, ExprObjectKind OK,
3698
             SourceLocation BuiltinLoc, SourceLocation RParenLoc)
3699
    : Expr(ConvertVectorExprClass, DstType, VK, OK,
3700
           DstType->isDependentType(),
3701
           DstType->isDependentType() || SrcExpr->isValueDependent(),
3702
           (DstType->isInstantiationDependentType() ||
3703
            SrcExpr->isInstantiationDependent()),
3704
           (DstType->containsUnexpandedParameterPack() ||
3705
            SrcExpr->containsUnexpandedParameterPack())),
3706
12.6k
  SrcExpr(SrcExpr), TInfo(TI), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
3707
3708
  /// getSrcExpr - Return the Expr to be converted.
3709
896
  Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
3710
3711
  /// getTypeSourceInfo - Return the destination type.
3712
351
  TypeSourceInfo *getTypeSourceInfo() const {
3713
351
    return TInfo;
3714
351
  }
3715
  void setTypeSourceInfo(TypeSourceInfo *ti) {
3716
    TInfo = ti;
3717
  }
3718
3719
  /// getBuiltinLoc - Return the location of the __builtin_convertvector token.
3720
350
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3721
3722
  /// getRParenLoc - Return the location of final right parenthesis.
3723
350
  SourceLocation getRParenLoc() const { return RParenLoc; }
3724
3725
16.8k
  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3726
10.2k
  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3727
3728
  static bool classof(const Stmt *T) {
3729
    return T->getStmtClass() == ConvertVectorExprClass;
3730
  }
3731
3732
  // Iterators
3733
25.8k
  child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
3734
0
  const_child_range children() const {
3735
0
    return const_child_range(&SrcExpr, &SrcExpr + 1);
3736
0
  }
3737
};
3738
3739
/// ChooseExpr - GNU builtin-in function __builtin_choose_expr.
3740
/// This AST node is similar to the conditional operator (?:) in C, with
3741
/// the following exceptions:
3742
/// - the test expression must be a integer constant expression.
3743
/// - the expression returned acts like the chosen subexpression in every
3744
///   visible way: the type is the same as that of the chosen subexpression,
3745
///   and all predicates (whether it's an l-value, whether it's an integer
3746
///   constant expression, etc.) return the same result as for the chosen
3747
///   sub-expression.
3748
class ChooseExpr : public Expr {
3749
  enum { COND, LHS, RHS, END_EXPR };
3750
  Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3751
  SourceLocation BuiltinLoc, RParenLoc;
3752
  bool CondIsTrue;
3753
public:
3754
  ChooseExpr(SourceLocation BLoc, Expr *cond, Expr *lhs, Expr *rhs,
3755
             QualType t, ExprValueKind VK, ExprObjectKind OK,
3756
             SourceLocation RP, bool condIsTrue,
3757
             bool TypeDependent, bool ValueDependent)
3758
    : Expr(ChooseExprClass, t, VK, OK, TypeDependent, ValueDependent,
3759
           (cond->isInstantiationDependent() ||
3760
            lhs->isInstantiationDependent() ||
3761
            rhs->isInstantiationDependent()),
3762
           (cond->containsUnexpandedParameterPack() ||
3763
            lhs->containsUnexpandedParameterPack() ||
3764
            rhs->containsUnexpandedParameterPack())),
3765
39
      BuiltinLoc(BLoc), RParenLoc(RP), CondIsTrue(condIsTrue) {
3766
39
      SubExprs[COND] = cond;
3767
39
      SubExprs[LHS] = lhs;
3768
39
      SubExprs[RHS] = rhs;
3769
39
    }
3770
3771
  /// Build an empty __builtin_choose_expr.
3772
1
  explicit ChooseExpr(EmptyShell Empty) : Expr(ChooseExprClass, Empty) { }
3773
3774
  /// isConditionTrue - Return whether the condition is true (i.e. not
3775
  /// equal to zero).
3776
230
  bool isConditionTrue() const {
3777
230
    assert(!isConditionDependent() &&
3778
230
           "Dependent condition isn't true or false");
3779
230
    return CondIsTrue;
3780
230
  }
3781
1
  void setIsConditionTrue(bool isTrue) { CondIsTrue = isTrue; }
3782
3783
184
  bool isConditionDependent() const {
3784
184
    return getCond()->isTypeDependent() || getCond()->isValueDependent();
3785
184
  }
3786
3787
  /// getChosenSubExpr - Return the subexpression chosen according to the
3788
  /// condition.
3789
227
  Expr *getChosenSubExpr() const {
3790
227
    return isConditionTrue() ? 
getLHS()102
:
getRHS()125
;
3791
227
  }
3792
3793
404
  Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3794
1
  void setCond(Expr *E) { SubExprs[COND] = E; }
3795
111
  Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3796
1
  void setLHS(Expr *E) { SubExprs[LHS] = E; }
3797
134
  Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3798
1
  void setRHS(Expr *E) { SubExprs[RHS] = E; }
3799
3800
5
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3801
1
  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3802
3803
5
  SourceLocation getRParenLoc() const { return RParenLoc; }
3804
1
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3805
3806
61
  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3807
12
  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3808
3809
326M
  static bool classof(const Stmt *T) {
3810
326M
    return T->getStmtClass() == ChooseExprClass;
3811
326M
  }
3812
3813
  // Iterators
3814
24
  child_range children() {
3815
24
    return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3816
24
  }
3817
0
  const_child_range children() const {
3818
0
    return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3819
0
  }
3820
};
3821
3822
/// GNUNullExpr - Implements the GNU __null extension, which is a name
3823
/// for a null pointer constant that has integral type (e.g., int or
3824
/// long) and is the same size and alignment as a pointer. The __null
3825
/// extension is typically only used by system headers, which define
3826
/// NULL as __null in C++ rather than using 0 (which is an integer
3827
/// that may not match the size of a pointer).
3828
class GNUNullExpr : public Expr {
3829
  /// TokenLoc - The location of the __null keyword.
3830
  SourceLocation TokenLoc;
3831
3832
public:
3833
  GNUNullExpr(QualType Ty, SourceLocation Loc)
3834
    : Expr(GNUNullExprClass, Ty, VK_RValue, OK_Ordinary, false, false, false,
3835
           false),
3836
7.22k
      TokenLoc(Loc) { }
3837
3838
  /// Build an empty GNU __null expression.
3839
0
  explicit GNUNullExpr(EmptyShell Empty) : Expr(GNUNullExprClass, Empty) { }
3840
3841
  /// getTokenLocation - The location of the __null token.
3842
0
  SourceLocation getTokenLocation() const { return TokenLoc; }
3843
0
  void setTokenLocation(SourceLocation L) { TokenLoc = L; }
3844
3845
31.4k
  SourceLocation getLocStart() const LLVM_READONLY { return TokenLoc; }
3846
10.2k
  SourceLocation getLocEnd() const LLVM_READONLY { return TokenLoc; }
3847
3848
11.4M
  static bool classof(const Stmt *T) {
3849
11.4M
    return T->getStmtClass() == GNUNullExprClass;
3850
11.4M
  }
3851
3852
  // Iterators
3853
7.28k
  child_range children() {
3854
7.28k
    return child_range(child_iterator(), child_iterator());
3855
7.28k
  }
3856
0
  const_child_range children() const {
3857
0
    return const_child_range(const_child_iterator(), const_child_iterator());
3858
0
  }
3859
};
3860
3861
/// Represents a call to the builtin function \c __builtin_va_arg.
3862
class VAArgExpr : public Expr {
3863
  Stmt *Val;
3864
  llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfo;
3865
  SourceLocation BuiltinLoc, RParenLoc;
3866
public:
3867
  VAArgExpr(SourceLocation BLoc, Expr *e, TypeSourceInfo *TInfo,
3868
            SourceLocation RPLoc, QualType t, bool IsMS)
3869
      : Expr(VAArgExprClass, t, VK_RValue, OK_Ordinary, t->isDependentType(),
3870
             false, (TInfo->getType()->isInstantiationDependentType() ||
3871
                     e->isInstantiationDependent()),
3872
             (TInfo->getType()->containsUnexpandedParameterPack() ||
3873
              e->containsUnexpandedParameterPack())),
3874
1.36k
        Val(e), TInfo(TInfo, IsMS), BuiltinLoc(BLoc), RParenLoc(RPLoc) {}
3875
3876
  /// Create an empty __builtin_va_arg expression.
3877
  explicit VAArgExpr(EmptyShell Empty)
3878
2
      : Expr(VAArgExprClass, Empty), Val(nullptr), TInfo(nullptr, false) {}
3879
3880
37
  const Expr *getSubExpr() const { return cast<Expr>(Val); }
3881
1.03k
  Expr *getSubExpr() { return cast<Expr>(Val); }
3882
2
  void setSubExpr(Expr *E) { Val = E; }
3883
3884
  /// Returns whether this is really a Win64 ABI va_arg expression.
3885
2.04k
  bool isMicrosoftABI() const { return TInfo.getInt(); }
3886
2
  void setIsMicrosoftABI(bool IsMS) { TInfo.setInt(IsMS); }
3887
3888
74
  TypeSourceInfo *getWrittenTypeInfo() const { return TInfo.getPointer(); }
3889
2
  void setWrittenTypeInfo(TypeSourceInfo *TI) { TInfo.setPointer(TI); }
3890
3891
14
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
3892
2
  void setBuiltinLoc(SourceLocation L) { BuiltinLoc = L; }
3893
3894
14
  SourceLocation getRParenLoc() const { return RParenLoc; }
3895
2
  void setRParenLoc(SourceLocation L) { RParenLoc = L; }
3896
3897
7.22k
  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
3898
357
  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
3899
3900
44
  static bool classof(const Stmt *T) {
3901
44
    return T->getStmtClass() == VAArgExprClass;
3902
44
  }
3903
3904
  // Iterators
3905
5.63k
  child_range children() { return child_range(&Val, &Val+1); }
3906
0
  const_child_range children() const {
3907
0
    return const_child_range(&Val, &Val + 1);
3908
0
  }
3909
};
3910
3911
/// Describes an C or C++ initializer list.
3912
///
3913
/// InitListExpr describes an initializer list, which can be used to
3914
/// initialize objects of different types, including
3915
/// struct/class/union types, arrays, and vectors. For example:
3916
///
3917
/// @code
3918
/// struct foo x = { 1, { 2, 3 } };
3919
/// @endcode
3920
///
3921
/// Prior to semantic analysis, an initializer list will represent the
3922
/// initializer list as written by the user, but will have the
3923
/// placeholder type "void". This initializer list is called the
3924
/// syntactic form of the initializer, and may contain C99 designated
3925
/// initializers (represented as DesignatedInitExprs), initializations
3926
/// of subobject members without explicit braces, and so on. Clients
3927
/// interested in the original syntax of the initializer list should
3928
/// use the syntactic form of the initializer list.
3929
///
3930
/// After semantic analysis, the initializer list will represent the
3931
/// semantic form of the initializer, where the initializations of all
3932
/// subobjects are made explicit with nested InitListExpr nodes and
3933
/// C99 designators have been eliminated by placing the designated
3934
/// initializations into the subobject they initialize. Additionally,
3935
/// any "holes" in the initialization, where no initializer has been
3936
/// specified for a particular subobject, will be replaced with
3937
/// implicitly-generated ImplicitValueInitExpr expressions that
3938
/// value-initialize the subobjects. Note, however, that the
3939
/// initializer lists may still have fewer initializers than there are
3940
/// elements to initialize within the object.
3941
///
3942
/// After semantic analysis has completed, given an initializer list,
3943
/// method isSemanticForm() returns true if and only if this is the
3944
/// semantic form of the initializer list (note: the same AST node
3945
/// may at the same time be the syntactic form).
3946
/// Given the semantic form of the initializer list, one can retrieve
3947
/// the syntactic form of that initializer list (when different)
3948
/// using method getSyntacticForm(); the method returns null if applied
3949
/// to a initializer list which is already in syntactic form.
3950
/// Similarly, given the syntactic form (i.e., an initializer list such
3951
/// that isSemanticForm() returns false), one can retrieve the semantic
3952
/// form using method getSemanticForm().
3953
/// Since many initializer lists have the same syntactic and semantic forms,
3954
/// getSyntacticForm() may return NULL, indicating that the current
3955
/// semantic initializer list also serves as its syntactic form.
3956
class InitListExpr : public Expr {
3957
  // FIXME: Eliminate this vector in favor of ASTContext allocation
3958
  typedef ASTVector<Stmt *> InitExprsTy;
3959
  InitExprsTy InitExprs;
3960
  SourceLocation LBraceLoc, RBraceLoc;
3961
3962
  /// The alternative form of the initializer list (if it exists).
3963
  /// The int part of the pair stores whether this initializer list is
3964
  /// in semantic form. If not null, the pointer points to:
3965
  ///   - the syntactic form, if this is in semantic form;
3966
  ///   - the semantic form, if this is in syntactic form.
3967
  llvm::PointerIntPair<InitListExpr *, 1, bool> AltForm;
3968
3969
  /// Either:
3970
  ///  If this initializer list initializes an array with more elements than
3971
  ///  there are initializers in the list, specifies an expression to be used
3972
  ///  for value initialization of the rest of the elements.
3973
  /// Or
3974
  ///  If this initializer list initializes a union, specifies which
3975
  ///  field within the union will be initialized.
3976
  llvm::PointerUnion<Expr *, FieldDecl *> ArrayFillerOrUnionFieldInit;
3977
3978
public:
3979
  InitListExpr(const ASTContext &C, SourceLocation lbraceloc,
3980
               ArrayRef<Expr*> initExprs, SourceLocation rbraceloc);
3981
3982
  /// Build an empty initializer list.
3983
  explicit InitListExpr(EmptyShell Empty)
3984
1.72k
    : Expr(InitListExprClass, Empty), AltForm(nullptr, true) { }
3985
3986
5.24M
  unsigned getNumInits() const { return InitExprs.size(); }
3987
3988
  /// Retrieve the set of initializers.
3989
178k
  Expr **getInits() { return reinterpret_cast<Expr **>(InitExprs.data()); }
3990
3991
  /// Retrieve the set of initializers.
3992
0
  Expr * const *getInits() const {
3993
0
    return reinterpret_cast<Expr * const *>(InitExprs.data());
3994
0
  }
3995
3996
144k
  ArrayRef<Expr *> inits() {
3997
144k
    return llvm::makeArrayRef(getInits(), getNumInits());
3998
144k
  }
3999
4000
0
  ArrayRef<Expr *> inits() const {
4001
0
    return llvm::makeArrayRef(getInits(), getNumInits());
4002
0
  }
4003
4004
692k
  const Expr *getInit(unsigned Init) const {
4005
692k
    assert(Init < getNumInits() && "Initializer access out of range!");
4006
692k
    return cast_or_null<Expr>(InitExprs[Init]);
4007
692k
  }
4008
4009
7.67M
  Expr *getInit(unsigned Init) {
4010
7.67M
    assert(Init < getNumInits() && "Initializer access out of range!");
4011
7.67M
    return cast_or_null<Expr>(InitExprs[Init]);
4012
7.67M
  }
4013
4014
1.67M
  void setInit(unsigned Init, Expr *expr) {
4015
1.67M
    assert(Init < getNumInits() && "Initializer access out of range!");
4016
1.67M
    InitExprs[Init] = expr;
4017
1.67M
4018
1.67M
    if (expr) {
4019
1.67M
      ExprBits.TypeDependent |= expr->isTypeDependent();
4020
1.67M
      ExprBits.ValueDependent |= expr->isValueDependent();
4021
1.67M
      ExprBits.InstantiationDependent |= expr->isInstantiationDependent();
4022
1.67M
      ExprBits.ContainsUnexpandedParameterPack |=
4023
1.67M
          expr->containsUnexpandedParameterPack();
4024
1.67M
    }
4025
1.67M
  }
4026
4027
  /// Reserve space for some number of initializers.
4028
  void reserveInits(const ASTContext &C, unsigned NumInits);
4029
4030
  /// Specify the number of initializers
4031
  ///
4032
  /// If there are more than @p NumInits initializers, the remaining
4033
  /// initializers will be destroyed. If there are fewer than @p
4034
  /// NumInits initializers, NULL expressions will be added for the
4035
  /// unknown initializers.
4036
  void resizeInits(const ASTContext &Context, unsigned NumInits);
4037
4038
  /// Updates the initializer at index @p Init with the new
4039
  /// expression @p expr, and returns the old expression at that
4040
  /// location.
4041
  ///
4042
  /// When @p Init is out of range for this initializer list, the
4043
  /// initializer list will be extended with NULL expressions to
4044
  /// accommodate the new entry.
4045
  Expr *updateInit(const ASTContext &C, unsigned Init, Expr *expr);
4046
4047
  /// If this initializer list initializes an array with more elements
4048
  /// than there are initializers in the list, specifies an expression to be
4049
  /// used for value initialization of the rest of the elements.
4050
155k
  Expr *getArrayFiller() {
4051
155k
    return ArrayFillerOrUnionFieldInit.dyn_cast<Expr *>();
4052
155k
  }
4053
131k
  const Expr *getArrayFiller() const {
4054
131k
    return const_cast<InitListExpr *>(this)->getArrayFiller();
4055
131k
  }
4056
  void setArrayFiller(Expr *filler);
4057
4058
  /// Return true if this is an array initializer and its array "filler"
4059
  /// has been set.
4060
38.3k
  bool hasArrayFiller() const { return getArrayFiller(); }
4061
4062
  /// If this initializes a union, specifies which field in the
4063
  /// union to initialize.
4064
  ///
4065
  /// Typically, this field is the first named field within the
4066
  /// union. However, a designated initializer can specify the
4067
  /// initialization of a different field within the union.
4068
18.1k
  FieldDecl *getInitializedFieldInUnion() {
4069
18.1k
    return ArrayFillerOrUnionFieldInit.dyn_cast<FieldDecl *>();
4070
18.1k
  }
4071
3.62k
  const FieldDecl *getInitializedFieldInUnion() const {
4072
3.62k
    return const_cast<InitListExpr *>(this)->getInitializedFieldInUnion();
4073
3.62k
  }
4074
2.87k
  void setInitializedFieldInUnion(FieldDecl *FD) {
4075
2.87k
    assert((FD == nullptr
4076
2.87k
            || getInitializedFieldInUnion() == nullptr
4077
2.87k
            || getInitializedFieldInUnion() == FD)
4078
2.87k
           && "Only one field of a union may be initialized at a time!");
4079
2.87k
    ArrayFillerOrUnionFieldInit = FD;
4080
2.87k
  }
4081
4082
  // Explicit InitListExpr's originate from source code (and have valid source
4083
  // locations). Implicit InitListExpr's are created by the semantic analyzer.
4084
0
  bool isExplicit() const {
4085
0
    return LBraceLoc.isValid() && RBraceLoc.isValid();
4086
0
  }
4087
4088
  // Is this an initializer for an array of characters, initialized by a string
4089
  // literal or an @encode?
4090
  bool isStringLiteralInit() const;
4091
4092
  /// Is this a transparent initializer list (that is, an InitListExpr that is
4093
  /// purely syntactic, and whose semantics are that of the sole contained
4094
  /// initializer)?
4095
  bool isTransparent() const;
4096
4097
  /// Is this the zero initializer {0} in a language which considers it
4098
  /// idiomatic?
4099
  bool isIdiomaticZeroInitializer(const LangOptions &LangOpts) const;
4100
4101
11.1k
  SourceLocation getLBraceLoc() const { return LBraceLoc; }
4102
1.72k
  void setLBraceLoc(SourceLocation Loc) { LBraceLoc = Loc; }
4103
10.9k
  SourceLocation getRBraceLoc() const { return RBraceLoc; }
4104
2.91k
  void setRBraceLoc(SourceLocation Loc) { RBraceLoc = Loc; }
4105
4106
1.27M
  bool isSemanticForm() const { return AltForm.getInt(); }
4107
396
  InitListExpr *getSemanticForm() const {
4108
396
    return isSemanticForm() ? 
nullptr0
: AltForm.getPointer();
4109
396
  }
4110
0
  bool isSyntacticForm() const {
4111
0
    return !AltForm.getInt() || !AltForm.getPointer();
4112
0
  }
4113
1.27M
  InitListExpr *getSyntacticForm() const {
4114
1.27M
    return isSemanticForm() ? 
AltForm.getPointer()969k
:
nullptr302k
;
4115
1.27M
  }
4116
4117
178k
  void setSyntacticForm(InitListExpr *Init) {
4118
178k
    AltForm.setPointer(Init);
4119
178k
    AltForm.setInt(true);
4120
178k
    Init->AltForm.setPointer(this);
4121
178k
    Init->AltForm.setInt(false);
4122
178k
  }
4123
4124
11.5k
  bool hadArrayRangeDesignator() const {
4125
11.5k
    return InitListExprBits.HadArrayRangeDesignator != 0;
4126
11.5k
  }
4127
242k
  void sawArrayRangeDesignator(bool ARD = true) {
4128
242k
    InitListExprBits.HadArrayRangeDesignator = ARD;
4129
242k
  }
4130
4131
  SourceLocation getLocStart() const LLVM_READONLY;
4132
  SourceLocation getLocEnd() const LLVM_READONLY;
4133
4134
92.8M
  static bool classof(const Stmt *T) {
4135
92.8M
    return T->getStmtClass() == InitListExprClass;
4136
92.8M
  }
4137
4138
  // Iterators
4139
352k
  child_range children() {
4140
352k
    const_child_range CCR = const_cast<const InitListExpr *>(this)->children();
4141
352k
    return child_range(cast_away_const(CCR.begin()),
4142
352k
                       cast_away_const(CCR.end()));
4143
352k
  }
4144
4145
352k
  const_child_range children() const {
4146
352k
    // FIXME: This does not include the array filler expression.
4147
352k
    if (InitExprs.empty())
4148
29.4k
      return const_child_range(const_child_iterator(), const_child_iterator());
4149
322k
    return const_child_range(&InitExprs[0], &InitExprs[0] + InitExprs.size());
4150
322k
  }
4151
4152
  typedef InitExprsTy::iterator iterator;
4153
  typedef InitExprsTy::const_iterator const_iterator;
4154
  typedef InitExprsTy::reverse_iterator reverse_iterator;
4155
  typedef InitExprsTy::const_reverse_iterator const_reverse_iterator;
4156
4157
0
  iterator begin() { return InitExprs.begin(); }
4158
7
  const_iterator begin() const { return InitExprs.begin(); }
4159
0
  iterator end() { return InitExprs.end(); }
4160
0
  const_iterator end() const { return InitExprs.end(); }
4161
0
  reverse_iterator rbegin() { return InitExprs.rbegin(); }
4162
840
  const_reverse_iterator rbegin() const { return InitExprs.rbegin(); }
4163
0
  reverse_iterator rend() { return InitExprs.rend(); }
4164
840
  const_reverse_iterator rend() const { return InitExprs.rend(); }
4165
4166
  friend class ASTStmtReader;
4167
  friend class ASTStmtWriter;
4168
};
4169
4170
/// Represents a C99 designated initializer expression.
4171
///
4172
/// A designated initializer expression (C99 6.7.8) contains one or
4173
/// more designators (which can be field designators, array
4174
/// designators, or GNU array-range designators) followed by an
4175
/// expression that initializes the field or element(s) that the
4176
/// designators refer to. For example, given:
4177
///
4178
/// @code
4179
/// struct point {
4180
///   double x;
4181
///   double y;
4182
/// };
4183
/// struct point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 };
4184
/// @endcode
4185
///
4186
/// The InitListExpr contains three DesignatedInitExprs, the first of
4187
/// which covers @c [2].y=1.0. This DesignatedInitExpr will have two
4188
/// designators, one array designator for @c [2] followed by one field
4189
/// designator for @c .y. The initialization expression will be 1.0.
4190
class DesignatedInitExpr final
4191
    : public Expr,
4192
      private llvm::TrailingObjects<DesignatedInitExpr, Stmt *> {
4193
public:
4194
  /// Forward declaration of the Designator class.
4195
  class Designator;
4196
4197
private:
4198
  /// The location of the '=' or ':' prior to the actual initializer
4199
  /// expression.
4200
  SourceLocation EqualOrColonLoc;
4201
4202
  /// Whether this designated initializer used the GNU deprecated
4203
  /// syntax rather than the C99 '=' syntax.
4204
  unsigned GNUSyntax : 1;
4205
4206
  /// The number of designators in this initializer expression.
4207
  unsigned NumDesignators : 15;
4208
4209
  /// The number of subexpressions of this initializer expression,
4210
  /// which contains both the initializer and any additional
4211
  /// expressions used by array and array-range designators.
4212
  unsigned NumSubExprs : 16;
4213
4214
  /// The designators in this designated initialization
4215
  /// expression.
4216
  Designator *Designators;
4217
4218
  DesignatedInitExpr(const ASTContext &C, QualType Ty,
4219
                     llvm::ArrayRef<Designator> Designators,
4220
                     SourceLocation EqualOrColonLoc, bool GNUSyntax,
4221
                     ArrayRef<Expr *> IndexExprs, Expr *Init);
4222
4223
  explicit DesignatedInitExpr(unsigned NumSubExprs)
4224
    : Expr(DesignatedInitExprClass, EmptyShell()),
4225
9
      NumDesignators(0), NumSubExprs(NumSubExprs), Designators(nullptr) { }
4226
4227
public:
4228
  /// A field designator, e.g., ".x".
4229
  struct FieldDesignator {
4230
    /// Refers to the field that is being initialized. The low bit
4231
    /// of this field determines whether this is actually a pointer
4232
    /// to an IdentifierInfo (if 1) or a FieldDecl (if 0). When
4233
    /// initially constructed, a field designator will store an
4234
    /// IdentifierInfo*. After semantic analysis has resolved that
4235
    /// name, the field designator will instead store a FieldDecl*.
4236
    uintptr_t NameOrField;
4237
4238
    /// The location of the '.' in the designated initializer.
4239
    unsigned DotLoc;
4240
4241
    /// The location of the field name in the designated initializer.
4242
    unsigned FieldLoc;
4243
  };
4244
4245
  /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4246
  struct ArrayOrRangeDesignator {
4247
    /// Location of the first index expression within the designated
4248
    /// initializer expression's list of subexpressions.
4249
    unsigned Index;
4250
    /// The location of the '[' starting the array range designator.
4251
    unsigned LBracketLoc;
4252
    /// The location of the ellipsis separating the start and end
4253
    /// indices. Only valid for GNU array-range designators.
4254
    unsigned EllipsisLoc;
4255
    /// The location of the ']' terminating the array range designator.
4256
    unsigned RBracketLoc;
4257
  };
4258
4259
  /// Represents a single C99 designator.
4260
  ///
4261
  /// @todo This class is infuriatingly similar to clang::Designator,
4262
  /// but minor differences (storing indices vs. storing pointers)
4263
  /// keep us from reusing it. Try harder, later, to rectify these
4264
  /// differences.
4265
  class Designator {
4266
    /// The kind of designator this describes.
4267
    enum {
4268
      FieldDesignator,
4269
      ArrayDesignator,
4270
      ArrayRangeDesignator
4271
    } Kind;
4272
4273
    union {
4274
      /// A field designator, e.g., ".x".
4275
      struct FieldDesignator Field;
4276
      /// An array or GNU array-range designator, e.g., "[9]" or "[10..15]".
4277
      struct ArrayOrRangeDesignator ArrayOrRange;
4278
    };
4279
    friend class DesignatedInitExpr;
4280
4281
  public:
4282
3.02k
    Designator() {}
4283
4284
    /// Initializes a field designator.
4285
    Designator(const IdentifierInfo *FieldName, SourceLocation DotLoc,
4286
               SourceLocation FieldLoc)
4287
2.64k
      : Kind(FieldDesignator) {
4288
2.64k
      Field.NameOrField = reinterpret_cast<uintptr_t>(FieldName) | 0x01;
4289
2.64k
      Field.DotLoc = DotLoc.getRawEncoding();
4290
2.64k
      Field.FieldLoc = FieldLoc.getRawEncoding();
4291
2.64k
    }
4292
4293
    /// Initializes an array designator.
4294
    Designator(unsigned Index, SourceLocation LBracketLoc,
4295
               SourceLocation RBracketLoc)
4296
300
      : Kind(ArrayDesignator) {
4297
300
      ArrayOrRange.Index = Index;
4298
300
      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4299
300
      ArrayOrRange.EllipsisLoc = SourceLocation().getRawEncoding();
4300
300
      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4301
300
    }
4302
4303
    /// Initializes a GNU array-range designator.
4304
    Designator(unsigned Index, SourceLocation LBracketLoc,
4305
               SourceLocation EllipsisLoc, SourceLocation RBracketLoc)
4306
26
      : Kind(ArrayRangeDesignator) {
4307
26
      ArrayOrRange.Index = Index;
4308
26
      ArrayOrRange.LBracketLoc = LBracketLoc.getRawEncoding();
4309
26
      ArrayOrRange.EllipsisLoc = EllipsisLoc.getRawEncoding();
4310
26
      ArrayOrRange.RBracketLoc = RBracketLoc.getRawEncoding();
4311
26
    }
4312
4313
6.56k
    bool isFieldDesignator() const { return Kind == FieldDesignator; }
4314
3.59k
    bool isArrayDesignator() const { return Kind == ArrayDesignator; }
4315
2.61k
    bool isArrayRangeDesignator() const { return Kind == ArrayRangeDesignator; }
4316
4317
    IdentifierInfo *getFieldName() const;
4318
4319
5.32k
    FieldDecl *getField() const {
4320
5.32k
      assert(Kind == FieldDesignator && "Only valid on a field designator");
4321
5.32k
      if (Field.NameOrField & 0x01)
4322
5.05k
        return nullptr;
4323
269
      else
4324
269
        return reinterpret_cast<FieldDecl *>(Field.NameOrField);
4325
5.32k
    }
4326
4327
2.63k
    void setField(FieldDecl *FD) {
4328
2.63k
      assert(Kind == FieldDesignator && "Only valid on a field designator");
4329
2.63k
      Field.NameOrField = reinterpret_cast<uintptr_t>(FD);
4330
2.63k
    }
4331
4332
605
    SourceLocation getDotLoc() const {
4333
605
      assert(Kind == FieldDesignator && "Only valid on a field designator");
4334
605
      return SourceLocation::getFromRawEncoding(Field.DotLoc);
4335
605
    }
4336
4337
2.76k
    SourceLocation getFieldLoc() const {
4338
2.76k
      assert(Kind == FieldDesignator && "Only valid on a field designator");
4339
2.76k
      return SourceLocation::getFromRawEncoding(Field.FieldLoc);
4340
2.76k
    }
4341
4342
161
    SourceLocation getLBracketLoc() const {
4343
161
      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4344
161
             "Only valid on an array or array-range designator");
4345
161
      return SourceLocation::getFromRawEncoding(ArrayOrRange.LBracketLoc);
4346
161
    }
4347
4348
52
    SourceLocation getRBracketLoc() const {
4349
52
      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4350
52
             "Only valid on an array or array-range designator");
4351
52
      return SourceLocation::getFromRawEncoding(ArrayOrRange.RBracketLoc);
4352
52
    }
4353
4354
8
    SourceLocation getEllipsisLoc() const {
4355
8
      assert(Kind == ArrayRangeDesignator &&
4356
8
             "Only valid on an array-range designator");
4357
8
      return SourceLocation::getFromRawEncoding(ArrayOrRange.EllipsisLoc);
4358
8
    }
4359
4360
60
    unsigned getFirstExprIndex() const {
4361
60
      assert((Kind == ArrayDesignator || Kind == ArrayRangeDesignator) &&
4362
60
             "Only valid on an array or array-range designator");
4363
60
      return ArrayOrRange.Index;
4364
60
    }
4365
4366
301
    SourceLocation getLocStart() const LLVM_READONLY {
4367
301
      if (Kind == FieldDesignator)
4368
225
        return getDotLoc().isInvalid()? 
getFieldLoc()8
:
getDotLoc()217
;
4369
76
      else
4370
76
        return getLBracketLoc();
4371
301
    }
4372
18
    SourceLocation getLocEnd() const LLVM_READONLY {
4373
18
      return Kind == FieldDesignator ? getFieldLoc() : 
getRBracketLoc()0
;
4374
18
    }
4375
18
    SourceRange getSourceRange() const LLVM_READONLY {
4376
18
      return SourceRange(getLocStart(), getLocEnd());
4377
18
    }
4378
  };
4379
4380
  static DesignatedInitExpr *Create(const ASTContext &C,
4381
                                    llvm::ArrayRef<Designator> Designators,
4382
                                    ArrayRef<Expr*> IndexExprs,
4383
                                    SourceLocation EqualOrColonLoc,
4384
                                    bool GNUSyntax, Expr *Init);
4385
4386
  static DesignatedInitExpr *CreateEmpty(const ASTContext &C,
4387
                                         unsigned NumIndexExprs);
4388
4389
  /// Returns the number of designators in this initializer.
4390
10.9k
  unsigned size() const { return NumDesignators; }
4391
4392
  // Iterator access to the designators.
4393
6.52k
  llvm::MutableArrayRef<Designator> designators() {
4394
6.52k
    return {Designators, NumDesignators};
4395
6.52k
  }
4396
4397
29
  llvm::ArrayRef<Designator> designators() const {
4398
29
    return {Designators, NumDesignators};
4399
29
  }
4400
4401
6.29k
  Designator *getDesignator(unsigned Idx) { return &designators()[Idx]; }
4402
0
  const Designator *getDesignator(unsigned Idx) const {
4403
0
    return &designators()[Idx];
4404
0
  }
4405
4406
  void setDesignators(const ASTContext &C, const Designator *Desigs,
4407
                      unsigned NumDesigs);
4408
4409
  Expr *getArrayIndex(const Designator &D) const;
4410
  Expr *getArrayRangeStart(const Designator &D) const;
4411
  Expr *getArrayRangeEnd(const Designator &D) const;
4412
4413
  /// Retrieve the location of the '=' that precedes the
4414
  /// initializer value itself, if present.
4415
153
  SourceLocation getEqualOrColonLoc() const { return EqualOrColonLoc; }
4416
9
  void setEqualOrColonLoc(SourceLocation L) { EqualOrColonLoc = L; }
4417
4418
  /// Determines whether this designated initializer used the
4419
  /// deprecated GNU syntax for designated initializers.
4420
167
  bool usesGNUSyntax() const { return GNUSyntax; }
4421
9
  void setGNUSyntax(bool GNU) { GNUSyntax = GNU; }
4422
4423
  /// Retrieve the initializer value.
4424
11.2k
  Expr *getInit() const {
4425
11.2k
    return cast<Expr>(*const_cast<DesignatedInitExpr*>(this)->child_begin());
4426
11.2k
  }
4427
4428
2.09k
  void setInit(Expr *init) {
4429
2.09k
    *child_begin() = init;
4430
2.09k
  }
4431
4432
  /// Retrieve the total number of subexpressions in this
4433
  /// designated initializer expression, including the actual
4434
  /// initialized value and any expressions that occur within array
4435
  /// and array-range designators.
4436
148
  unsigned getNumSubExprs() const { return NumSubExprs; }
4437
4438
827
  Expr *getSubExpr(unsigned Idx) const {
4439
827
    assert(Idx < NumSubExprs && "Subscript out of range");
4440
827
    return cast<Expr>(getTrailingObjects<Stmt *>()[Idx]);
4441
827
  }
4442
4443
14
  void setSubExpr(unsigned Idx, Expr *E) {
4444
14
    assert(Idx < NumSubExprs && "Subscript out of range");
4445
14
    getTrailingObjects<Stmt *>()[Idx] = E;
4446
14
  }
4447
4448
  /// Replaces the designator at index @p Idx with the series
4449
  /// of designators in [First, Last).
4450
  void ExpandDesignator(const ASTContext &C, unsigned Idx,
4451
                        const Designator *First, const Designator *Last);
4452
4453
  SourceRange getDesignatorsSourceRange() const;
4454
4455
  SourceLocation getLocStart() const LLVM_READONLY;
4456
  SourceLocation getLocEnd() const LLVM_READONLY;
4457
4458
2.91M
  static bool classof(const Stmt *T) {
4459
2.91M
    return T->getStmtClass() == DesignatedInitExprClass;
4460
2.91M
  }
4461
4462
  // Iterators
4463
16.3k
  child_range children() {
4464
16.3k
    Stmt **begin = getTrailingObjects<Stmt *>();
4465
16.3k
    return child_range(begin, begin + NumSubExprs);
4466
16.3k
  }
4467
0
  const_child_range children() const {
4468
0
    Stmt * const *begin = getTrailingObjects<Stmt *>();
4469
0
    return const_child_range(begin, begin + NumSubExprs);
4470
0
  }
4471
4472
  friend TrailingObjects;
4473
};
4474
4475
/// Represents a place-holder for an object not to be initialized by
4476
/// anything.
4477
///
4478
/// This only makes sense when it appears as part of an updater of a
4479
/// DesignatedInitUpdateExpr (see below). The base expression of a DIUE
4480
/// initializes a big object, and the NoInitExpr's mark the spots within the
4481
/// big object not to be overwritten by the updater.
4482
///
4483
/// \see DesignatedInitUpdateExpr
4484
class NoInitExpr : public Expr {
4485
public:
4486
  explicit NoInitExpr(QualType ty)
4487
    : Expr(NoInitExprClass, ty, VK_RValue, OK_Ordinary,
4488
39
           false, false, ty->isInstantiationDependentType(), false) { }
4489
4490
  explicit NoInitExpr(EmptyShell Empty)
4491
1
    : Expr(NoInitExprClass, Empty) { }
4492
4493
13.5k
  static bool classof(const Stmt *T) {
4494
13.5k
    return T->getStmtClass() == NoInitExprClass;
4495
13.5k
  }
4496
4497
51
  SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4498
0
  SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4499
4500
  // Iterators
4501
166
  child_range children() {
4502
166
    return child_range(child_iterator(), child_iterator());
4503
166
  }
4504
0
  const_child_range children() const {
4505
0
    return const_child_range(const_child_iterator(), const_child_iterator());
4506
0
  }
4507
};
4508
4509
// In cases like:
4510
//   struct Q { int a, b, c; };
4511
//   Q *getQ();
4512
//   void foo() {
4513
//     struct A { Q q; } a = { *getQ(), .q.b = 3 };
4514
//   }
4515
//
4516
// We will have an InitListExpr for a, with type A, and then a
4517
// DesignatedInitUpdateExpr for "a.q" with type Q. The "base" for this DIUE
4518
// is the call expression *getQ(); the "updater" for the DIUE is ".q.b = 3"
4519
//
4520
class DesignatedInitUpdateExpr : public Expr {
4521
  // BaseAndUpdaterExprs[0] is the base expression;
4522
  // BaseAndUpdaterExprs[1] is an InitListExpr overwriting part of the base.
4523
  Stmt *BaseAndUpdaterExprs[2];
4524
4525
public:
4526
  DesignatedInitUpdateExpr(const ASTContext &C, SourceLocation lBraceLoc,
4527
                           Expr *baseExprs, SourceLocation rBraceLoc);
4528
4529
  explicit DesignatedInitUpdateExpr(EmptyShell Empty)
4530
1
    : Expr(DesignatedInitUpdateExprClass, Empty) { }
4531
4532
  SourceLocation getLocStart() const LLVM_READONLY;
4533
  SourceLocation getLocEnd() const LLVM_READONLY;
4534
4535
1.16M
  static bool classof(const Stmt *T) {
4536
1.16M
    return T->getStmtClass() == DesignatedInitUpdateExprClass;
4537
1.16M
  }
4538
4539
135
  Expr *getBase() const { return cast<Expr>(BaseAndUpdaterExprs[0]); }
4540
1
  void setBase(Expr *Base) { BaseAndUpdaterExprs[0] = Base; }
4541
4542
119
  InitListExpr *getUpdater() const {
4543
119
    return cast<InitListExpr>(BaseAndUpdaterExprs[1]);
4544
119
  }
4545
1
  void setUpdater(Expr *Updater) { BaseAndUpdaterExprs[1] = Updater; }
4546
4547
  // Iterators
4548
  // children = the base and the updater
4549
97
  child_range children() {
4550
97
    return child_range(&BaseAndUpdaterExprs[0], &BaseAndUpdaterExprs[0] + 2);
4551
97
  }
4552
0
  const_child_range children() const {
4553
0
    return const_child_range(&BaseAndUpdaterExprs[0],
4554
0
                             &BaseAndUpdaterExprs[0] + 2);
4555
0
  }
4556
};
4557
4558
/// Represents a loop initializing the elements of an array.
4559
///
4560
/// The need to initialize the elements of an array occurs in a number of
4561
/// contexts:
4562
///
4563
///  * in the implicit copy/move constructor for a class with an array member
4564
///  * when a lambda-expression captures an array by value
4565
///  * when a decomposition declaration decomposes an array
4566
///
4567
/// There are two subexpressions: a common expression (the source array)
4568
/// that is evaluated once up-front, and a per-element initializer that
4569
/// runs once for each array element.
4570
///
4571
/// Within the per-element initializer, the common expression may be referenced
4572
/// via an OpaqueValueExpr, and the current index may be obtained via an
4573
/// ArrayInitIndexExpr.
4574
class ArrayInitLoopExpr : public Expr {
4575
  Stmt *SubExprs[2];
4576
4577
  explicit ArrayInitLoopExpr(EmptyShell Empty)
4578
1
      : Expr(ArrayInitLoopExprClass, Empty), SubExprs{} {}
4579
4580
public:
4581
  explicit ArrayInitLoopExpr(QualType T, Expr *CommonInit, Expr *ElementInit)
4582
      : Expr(ArrayInitLoopExprClass, T, VK_RValue, OK_Ordinary, false,
4583
             CommonInit->isValueDependent() || ElementInit->isValueDependent(),
4584
             T->isInstantiationDependentType(),
4585
             CommonInit->containsUnexpandedParameterPack() ||
4586
                 ElementInit->containsUnexpandedParameterPack()),
4587
848
        SubExprs{CommonInit, ElementInit} {}
4588
4589
  /// Get the common subexpression shared by all initializations (the source
4590
  /// array).
4591
892
  OpaqueValueExpr *getCommonExpr() const {
4592
892
    return cast<OpaqueValueExpr>(SubExprs[0]);
4593
892
  }
4594
4595
  /// Get the initializer to use for each array element.
4596
61
  Expr *getSubExpr() const { return cast<Expr>(SubExprs[1]); }
4597
4598
26
  llvm::APInt getArraySize() const {
4599
26
    return cast<ConstantArrayType>(getType()->castAsArrayTypeUnsafe())
4600
26
        ->getSize();
4601
26
  }
4602
4603
1.13M
  static bool classof(const Stmt *S) {
4604
1.13M
    return S->getStmtClass() == ArrayInitLoopExprClass;
4605
1.13M
  }
4606
4607
470
  SourceLocation getLocStart() const LLVM_READONLY {
4608
470
    return getCommonExpr()->getLocStart();
4609
470
  }
4610
385
  SourceLocation getLocEnd() const LLVM_READONLY {
4611
385
    return getCommonExpr()->getLocEnd();
4612
385
  }
4613
4614
921
  child_range children() {
4615
921
    return child_range(SubExprs, SubExprs + 2);
4616
921
  }
4617
0
  const_child_range children() const {
4618
0
    return const_child_range(SubExprs, SubExprs + 2);
4619
0
  }
4620
4621
  friend class ASTReader;
4622
  friend class ASTStmtReader;
4623
  friend class ASTStmtWriter;
4624
};
4625
4626
/// Represents the index of the current element of an array being
4627
/// initialized by an ArrayInitLoopExpr. This can only appear within the
4628
/// subexpression of an ArrayInitLoopExpr.
4629
class ArrayInitIndexExpr : public Expr {
4630
  explicit ArrayInitIndexExpr(EmptyShell Empty)
4631
1
      : Expr(ArrayInitIndexExprClass, Empty) {}
4632
4633
public:
4634
  explicit ArrayInitIndexExpr(QualType T)
4635
      : Expr(ArrayInitIndexExprClass, T, VK_RValue, OK_Ordinary,
4636
848
             false, false, false, false) {}
4637
4638
  static bool classof(const Stmt *S) {
4639
    return S->getStmtClass() == ArrayInitIndexExprClass;
4640
  }
4641
4642
137
  SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4643
72
  SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4644
4645
89
  child_range children() {
4646
89
    return child_range(child_iterator(), child_iterator());
4647
89
  }
4648
0
  const_child_range children() const {
4649
0
    return const_child_range(const_child_iterator(), const_child_iterator());
4650
0
  }
4651
4652
  friend class ASTReader;
4653
  friend class ASTStmtReader;
4654
};
4655
4656
/// Represents an implicitly-generated value initialization of
4657
/// an object of a given type.
4658
///
4659
/// Implicit value initializations occur within semantic initializer
4660
/// list expressions (InitListExpr) as placeholders for subobject
4661
/// initializations not explicitly specified by the user.
4662
///
4663
/// \see InitListExpr
4664
class ImplicitValueInitExpr : public Expr {
4665
public:
4666
  explicit ImplicitValueInitExpr(QualType ty)
4667
    : Expr(ImplicitValueInitExprClass, ty, VK_RValue, OK_Ordinary,
4668
453k
           false, false, ty->isInstantiationDependentType(), false) { }
4669
4670
  /// Construct an empty implicit value initialization.
4671
  explicit ImplicitValueInitExpr(EmptyShell Empty)
4672
55
    : Expr(ImplicitValueInitExprClass, Empty) { }
4673
4674
2.05M
  static bool classof(const Stmt *T) {
4675
2.05M
    return T->getStmtClass() == ImplicitValueInitExprClass;
4676
2.05M
  }
4677
4678
22.2k
  SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
4679
180
  SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
4680
4681
  // Iterators
4682
35.5k
  child_range children() {
4683
35.5k
    return child_range(child_iterator(), child_iterator());
4684
35.5k
  }
4685
0
  const_child_range children() const {
4686
0
    return const_child_range(const_child_iterator(), const_child_iterator());
4687
0
  }
4688
};
4689
4690
class ParenListExpr : public Expr {
4691
  Stmt **Exprs;
4692
  unsigned NumExprs;
4693
  SourceLocation LParenLoc, RParenLoc;
4694
4695
public:
4696
  ParenListExpr(const ASTContext& C, SourceLocation lparenloc,
4697
                ArrayRef<Expr*> exprs, SourceLocation rparenloc);
4698
4699
  /// Build an empty paren list.
4700
868
  explicit ParenListExpr(EmptyShell Empty) : Expr(ParenListExprClass, Empty) { }
4701
4702
885k
  unsigned getNumExprs() const { return NumExprs; }
4703
4704
3
  const Expr* getExpr(unsigned Init) const {
4705
3
    assert(Init < getNumExprs() && "Initializer access out of range!");
4706
3
    return cast_or_null<Expr>(Exprs[Init]);
4707
3
  }
4708
4709
468k
  Expr* getExpr(unsigned Init) {
4710
468k
    assert(Init < getNumExprs() && "Initializer access out of range!");
4711
468k
    return cast_or_null<Expr>(Exprs[Init]);
4712
468k
  }
4713
4714
405k
  Expr **getExprs() { return reinterpret_cast<Expr **>(Exprs); }
4715
4716
187
  ArrayRef<Expr *> exprs() {
4717
187
    return llvm::makeArrayRef(getExprs(), getNumExprs());
4718
187
  }
4719
4720
506k
  SourceLocation getLParenLoc() const { return LParenLoc; }
4721
506k
  SourceLocation getRParenLoc() const { return RParenLoc; }
4722
4723
380k
  SourceLocation getLocStart() const LLVM_READONLY { return LParenLoc; }
4724
375k
  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4725
4726
18.3M
  static bool classof(const Stmt *T) {
4727
18.3M
    return T->getStmtClass() == ParenListExprClass;
4728
18.3M
  }
4729
4730
  // Iterators
4731
38.2k
  child_range children() {
4732
38.2k
    return child_range(&Exprs[0], &Exprs[0]+NumExprs);
4733
38.2k
  }
4734
0
  const_child_range children() const {
4735
0
    return const_child_range(&Exprs[0], &Exprs[0] + NumExprs);
4736
0
  }
4737
4738
  friend class ASTStmtReader;
4739
  friend class ASTStmtWriter;
4740
};
4741
4742
/// Represents a C11 generic selection.
4743
///
4744
/// A generic selection (C11 6.5.1.1) contains an unevaluated controlling
4745
/// expression, followed by one or more generic associations.  Each generic
4746
/// association specifies a type name and an expression, or "default" and an
4747
/// expression (in which case it is known as a default generic association).
4748
/// The type and value of the generic selection are identical to those of its
4749
/// result expression, which is defined as the expression in the generic
4750
/// association with a type name that is compatible with the type of the
4751
/// controlling expression, or the expression in the default generic association
4752
/// if no types are compatible.  For example:
4753
///
4754
/// @code
4755
/// _Generic(X, double: 1, float: 2, default: 3)
4756
/// @endcode
4757
///
4758
/// The above expression evaluates to 1 if 1.0 is substituted for X, 2 if 1.0f
4759
/// or 3 if "hello".
4760
///
4761
/// As an extension, generic selections are allowed in C++, where the following
4762
/// additional semantics apply:
4763
///
4764
/// Any generic selection whose controlling expression is type-dependent or
4765
/// which names a dependent type in its association list is result-dependent,
4766
/// which means that the choice of result expression is dependent.
4767
/// Result-dependent generic associations are both type- and value-dependent.
4768
class GenericSelectionExpr : public Expr {
4769
  enum { CONTROLLING, END_EXPR };
4770
  TypeSourceInfo **AssocTypes;
4771
  Stmt **SubExprs;
4772
  unsigned NumAssocs, ResultIndex;
4773
  SourceLocation GenericLoc, DefaultLoc, RParenLoc;
4774
4775
public:
4776
  GenericSelectionExpr(const ASTContext &Context,
4777
                       SourceLocation GenericLoc, Expr *ControllingExpr,
4778
                       ArrayRef<TypeSourceInfo*> AssocTypes,
4779
                       ArrayRef<Expr*> AssocExprs,
4780
                       SourceLocation DefaultLoc, SourceLocation RParenLoc,
4781
                       bool ContainsUnexpandedParameterPack,
4782
                       unsigned ResultIndex);
4783
4784
  /// This constructor is used in the result-dependent case.
4785
  GenericSelectionExpr(const ASTContext &Context,
4786
                       SourceLocation GenericLoc, Expr *ControllingExpr,
4787
                       ArrayRef<TypeSourceInfo*> AssocTypes,
4788
                       ArrayRef<Expr*> AssocExprs,
4789
                       SourceLocation DefaultLoc, SourceLocation RParenLoc,
4790
                       bool ContainsUnexpandedParameterPack);
4791
4792
  explicit GenericSelectionExpr(EmptyShell Empty)
4793
1
    : Expr(GenericSelectionExprClass, Empty) { }
4794
4795
105
  unsigned getNumAssocs() const { return NumAssocs; }
4796
4797
15
  SourceLocation getGenericLoc() const { return GenericLoc; }
4798
15
  SourceLocation getDefaultLoc() const { return DefaultLoc; }
4799
15
  SourceLocation getRParenLoc() const { return RParenLoc; }
4800
4801
58
  const Expr *getAssocExpr(unsigned i) const {
4802
58
    return cast<Expr>(SubExprs[END_EXPR+i]);
4803
58
  }
4804
607
  Expr *getAssocExpr(unsigned i) { return cast<Expr>(SubExprs[END_EXPR+i]); }
4805
1
  ArrayRef<Expr *> getAssocExprs() const {
4806
1
    return NumAssocs
4807
1
               ? llvm::makeArrayRef(
4808
1
                     &reinterpret_cast<Expr **>(SubExprs)[END_EXPR], NumAssocs)
4809
1
               : 
None0
;
4810
1
  }
4811
12
  const TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) const {
4812
12
    return AssocTypes[i];
4813
12
  }
4814
70
  TypeSourceInfo *getAssocTypeSourceInfo(unsigned i) { return AssocTypes[i]; }
4815
1
  ArrayRef<TypeSourceInfo *> getAssocTypeSourceInfos() const {
4816
1
    return NumAssocs ? llvm::makeArrayRef(&AssocTypes[0], NumAssocs) : 
None0
;
4817
1
  }
4818
4819
12
  QualType getAssocType(unsigned i) const {
4820
12
    if (const TypeSourceInfo *TS = getAssocTypeSourceInfo(i))
4821
9
      return TS->getType();
4822
3
    else
4823
3
      return QualType();
4824
12
  }
4825
4826
0
  const Expr *getControllingExpr() const {
4827
0
    return cast<Expr>(SubExprs[CONTROLLING]);
4828
0
  }
4829
21
  Expr *getControllingExpr() { return cast<Expr>(SubExprs[CONTROLLING]); }
4830
4831
  /// Whether this generic selection is result-dependent.
4832
502
  bool isResultDependent() const { return ResultIndex == -1U; }
4833
4834
  /// The zero-based index of the result expression's generic association in
4835
  /// the generic selection's association list.  Defined only if the
4836
  /// generic selection is not result-dependent.
4837
593
  unsigned getResultIndex() const {
4838
593
    assert(!isResultDependent() && "Generic selection is result-dependent");
4839
593
    return ResultIndex;
4840
593
  }
4841
4842
  /// The generic selection's result expression.  Defined only if the
4843
  /// generic selection is not result-dependent.
4844
54
  const Expr *getResultExpr() const { return getAssocExpr(getResultIndex()); }
4845
537
  Expr *getResultExpr() { return getAssocExpr(getResultIndex()); }
4846
4847
372
  SourceLocation getLocStart() const LLVM_READONLY { return GenericLoc; }
4848
33
  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
4849
4850
327M
  static bool classof(const Stmt *T) {
4851
327M
    return T->getStmtClass() == GenericSelectionExprClass;
4852
327M
  }
4853
4854
7
  child_range children() {
4855
7
    return child_range(SubExprs, SubExprs+END_EXPR+NumAssocs);
4856
7
  }
4857
0
  const_child_range children() const {
4858
0
    return const_child_range(SubExprs, SubExprs + END_EXPR + NumAssocs);
4859
0
  }
4860
  friend class ASTStmtReader;
4861
};
4862
4863
//===----------------------------------------------------------------------===//
4864
// Clang Extensions
4865
//===----------------------------------------------------------------------===//
4866
4867
/// ExtVectorElementExpr - This represents access to specific elements of a
4868
/// vector, and may occur on the left hand side or right hand side.  For example
4869
/// the following is legal:  "V.xy = V.zw" if V is a 4 element extended vector.
4870
///
4871
/// Note that the base may have either vector or pointer to vector type, just
4872
/// like a struct field reference.
4873
///
4874
class ExtVectorElementExpr : public Expr {
4875
  Stmt *Base;
4876
  IdentifierInfo *Accessor;
4877
  SourceLocation AccessorLoc;
4878
public:
4879
  ExtVectorElementExpr(QualType ty, ExprValueKind VK, Expr *base,
4880
                       IdentifierInfo &accessor, SourceLocation loc)
4881
    : Expr(ExtVectorElementExprClass, ty, VK,
4882
           (VK == VK_RValue ? OK_Ordinary : OK_VectorComponent),
4883
           base->isTypeDependent(), base->isValueDependent(),
4884
           base->isInstantiationDependent(),
4885
           base->containsUnexpandedParameterPack()),
4886
402
      Base(base), Accessor(&accessor), AccessorLoc(loc) {}
4887
4888
  /// Build an empty vector element expression.
4889
  explicit ExtVectorElementExpr(EmptyShell Empty)
4890
15
    : Expr(ExtVectorElementExprClass, Empty) { }
4891
4892
4.26k
  const Expr *getBase() const { return cast<Expr>(Base); }
4893
29
  Expr *getBase() { return cast<Expr>(Base); }
4894
15
  void setBase(Expr *E) { Base = E; }
4895
4896
65
  IdentifierInfo &getAccessor() const { return *Accessor; }
4897
15
  void setAccessor(IdentifierInfo *II) { Accessor = II; }
4898
4899
17
  SourceLocation getAccessorLoc() const { return AccessorLoc; }
4900
15
  void setAccessorLoc(SourceLocation L) { AccessorLoc = L; }
4901
4902
  /// getNumElements - Get the number of components being selected.
4903
  unsigned getNumElements() const;
4904
4905
  /// containsDuplicateElements - Return true if any element access is
4906
  /// repeated.
4907
  bool containsDuplicateElements() const;
4908
4909
  /// getEncodedElementAccess - Encode the elements accessed into an llvm
4910
  /// aggregate Constant of ConstantInt(s).
4911
  void getEncodedElementAccess(SmallVectorImpl<uint32_t> &Elts) const;
4912
4913
3.27k
  SourceLocation getLocStart() const LLVM_READONLY {
4914
3.27k
    return getBase()->getLocStart();
4915
3.27k
  }
4916
47
  SourceLocation getLocEnd() const LLVM_READONLY { return AccessorLoc; }
4917
4918
  /// isArrow - Return true if the base expression is a pointer to vector,
4919
  /// return false if the base expression is a vector.
4920
  bool isArrow() const;
4921
4922
611k
  static bool classof(const Stmt *T) {
4923
611k
    return T->getStmtClass() == ExtVectorElementExprClass;
4924
611k
  }
4925
4926
  // Iterators
4927
1.02k
  child_range children() { return child_range(&Base, &Base+1); }
4928
0
  const_child_range children() const {
4929
0
    return const_child_range(&Base, &Base + 1);
4930
0
  }
4931
};
4932
4933
/// BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
4934
/// ^{ statement-body }   or   ^(int arg1, float arg2){ statement-body }
4935
class BlockExpr : public Expr {
4936
protected:
4937
  BlockDecl *TheBlock;
4938
public:
4939
  BlockExpr(BlockDecl *BD, QualType ty)
4940
    : Expr(BlockExprClass, ty, VK_RValue, OK_Ordinary,
4941
           ty->isDependentType(), ty->isDependentType(),
4942
           ty->isInstantiationDependentType() || BD->isDependentContext(),
4943
           false),
4944
2.54k
      TheBlock(BD) {}
4945
4946
  /// Build an empty block expression.
4947
9
  explicit BlockExpr(EmptyShell Empty) : Expr(BlockExprClass, Empty) { }
4948
4949
4.58k
  const BlockDecl *getBlockDecl() const { return TheBlock; }
4950
11.7k
  BlockDecl *getBlockDecl() { return TheBlock; }
4951
9
  void setBlockDecl(BlockDecl *BD) { TheBlock = BD; }
4952
4953
  // Convenience functions for probing the underlying BlockDecl.
4954
  SourceLocation getCaretLocation() const;
4955
  const Stmt *getBody() const;
4956
  Stmt *getBody();
4957
4958
20.1k
  SourceLocation getLocStart() const LLVM_READONLY { return getCaretLocation(); }
4959
3.05k
  SourceLocation getLocEnd() const LLVM_READONLY { return getBody()->getLocEnd(); }
4960
4961
  /// getFunctionType - Return the underlying function type for this block.
4962
  const FunctionProtoType *getFunctionType() const;
4963
4964
18.7k
  static bool classof(const Stmt *T) {
4965
18.7k
    return T->getStmtClass() == BlockExprClass;
4966
18.7k
  }
4967
4968
  // Iterators
4969
4.18k
  child_range children() {
4970
4.18k
    return child_range(child_iterator(), child_iterator());
4971
4.18k
  }
4972
0
  const_child_range children() const {
4973
0
    return const_child_range(const_child_iterator(), const_child_iterator());
4974
0
  }
4975
};
4976
4977
/// AsTypeExpr - Clang builtin function __builtin_astype [OpenCL 6.2.4.2]
4978
/// This AST node provides support for reinterpreting a type to another
4979
/// type of the same size.
4980
class AsTypeExpr : public Expr {
4981
private:
4982
  Stmt *SrcExpr;
4983
  SourceLocation BuiltinLoc, RParenLoc;
4984
4985
  friend class ASTReader;
4986
  friend class ASTStmtReader;
4987
0
  explicit AsTypeExpr(EmptyShell Empty) : Expr(AsTypeExprClass, Empty) {}
4988
4989
public:
4990
  AsTypeExpr(Expr* SrcExpr, QualType DstType,
4991
             ExprValueKind VK, ExprObjectKind OK,
4992
             SourceLocation BuiltinLoc, SourceLocation RParenLoc)
4993
    : Expr(AsTypeExprClass, DstType, VK, OK,
4994
           DstType->isDependentType(),
4995
           DstType->isDependentType() || SrcExpr->isValueDependent(),
4996
           (DstType->isInstantiationDependentType() ||
4997
            SrcExpr->isInstantiationDependent()),
4998
           (DstType->containsUnexpandedParameterPack() ||
4999
            SrcExpr->containsUnexpandedParameterPack())),
5000
20
  SrcExpr(SrcExpr), BuiltinLoc(BuiltinLoc), RParenLoc(RParenLoc) {}
5001
5002
  /// getSrcExpr - Return the Expr to be converted.
5003
17
  Expr *getSrcExpr() const { return cast<Expr>(SrcExpr); }
5004
5005
  /// getBuiltinLoc - Return the location of the __builtin_astype token.
5006
0
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5007
5008
  /// getRParenLoc - Return the location of final right parenthesis.
5009
0
  SourceLocation getRParenLoc() const { return RParenLoc; }
5010
5011
158
  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
5012
0
  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
5013
5014
  static bool classof(const Stmt *T) {
5015
    return T->getStmtClass() == AsTypeExprClass;
5016
  }
5017
5018
  // Iterators
5019
72
  child_range children() { return child_range(&SrcExpr, &SrcExpr+1); }
5020
0
  const_child_range children() const {
5021
0
    return const_child_range(&SrcExpr, &SrcExpr + 1);
5022
0
  }
5023
};
5024
5025
/// PseudoObjectExpr - An expression which accesses a pseudo-object
5026
/// l-value.  A pseudo-object is an abstract object, accesses to which
5027
/// are translated to calls.  The pseudo-object expression has a
5028
/// syntactic form, which shows how the expression was actually
5029
/// written in the source code, and a semantic form, which is a series
5030
/// of expressions to be executed in order which detail how the
5031
/// operation is actually evaluated.  Optionally, one of the semantic
5032
/// forms may also provide a result value for the expression.
5033
///
5034
/// If any of the semantic-form expressions is an OpaqueValueExpr,
5035
/// that OVE is required to have a source expression, and it is bound
5036
/// to the result of that source expression.  Such OVEs may appear
5037
/// only in subsequent semantic-form expressions and as
5038
/// sub-expressions of the syntactic form.
5039
///
5040
/// PseudoObjectExpr should be used only when an operation can be
5041
/// usefully described in terms of fairly simple rewrite rules on
5042
/// objects and functions that are meant to be used by end-developers.
5043
/// For example, under the Itanium ABI, dynamic casts are implemented
5044
/// as a call to a runtime function called __dynamic_cast; using this
5045
/// class to describe that would be inappropriate because that call is
5046
/// not really part of the user-visible semantics, and instead the
5047
/// cast is properly reflected in the AST and IR-generation has been
5048
/// taught to generate the call as necessary.  In contrast, an
5049
/// Objective-C property access is semantically defined to be
5050
/// equivalent to a particular message send, and this is very much
5051
/// part of the user model.  The name of this class encourages this
5052
/// modelling design.
5053
class PseudoObjectExpr final
5054
    : public Expr,
5055
      private llvm::TrailingObjects<PseudoObjectExpr, Expr *> {
5056
  // PseudoObjectExprBits.NumSubExprs - The number of sub-expressions.
5057
  // Always at least two, because the first sub-expression is the
5058
  // syntactic form.
5059
5060
  // PseudoObjectExprBits.ResultIndex - The index of the
5061
  // sub-expression holding the result.  0 means the result is void,
5062
  // which is unambiguous because it's the index of the syntactic
5063
  // form.  Note that this is therefore 1 higher than the value passed
5064
  // in to Create, which is an index within the semantic forms.
5065
  // Note also that ASTStmtWriter assumes this encoding.
5066
5067
24.2k
  Expr **getSubExprsBuffer() { return getTrailingObjects<Expr *>(); }
5068
25.2k
  const Expr * const *getSubExprsBuffer() const {
5069
25.2k
    return getTrailingObjects<Expr *>();
5070
25.2k
  }
5071
5072
  PseudoObjectExpr(QualType type, ExprValueKind VK,
5073
                   Expr *syntactic, ArrayRef<Expr*> semantic,
5074
                   unsigned resultIndex);
5075
5076
  PseudoObjectExpr(EmptyShell shell, unsigned numSemanticExprs);
5077
5078
10.7k
  unsigned getNumSubExprs() const {
5079
10.7k
    return PseudoObjectExprBits.NumSubExprs;
5080
10.7k
  }
5081
5082
public:
5083
  /// NoResult - A value for the result index indicating that there is
5084
  /// no semantic result.
5085
  enum : unsigned { NoResult = ~0U };
5086
5087
  static PseudoObjectExpr *Create(const ASTContext &Context, Expr *syntactic,
5088
                                  ArrayRef<Expr*> semantic,
5089
                                  unsigned resultIndex);
5090
5091
  static PseudoObjectExpr *Create(const ASTContext &Context, EmptyShell shell,
5092
                                  unsigned numSemanticExprs);
5093
5094
  /// Return the syntactic form of this expression, i.e. the
5095
  /// expression it actually looks like.  Likely to be expressed in
5096
  /// terms of OpaqueValueExprs bound in the semantic form.
5097
3.48k
  Expr *getSyntacticForm() { return getSubExprsBuffer()[0]; }
5098
19.2k
  const Expr *getSyntacticForm() const { return getSubExprsBuffer()[0]; }
5099
5100
  /// Return the index of the result-bearing expression into the semantics
5101
  /// expressions, or PseudoObjectExpr::NoResult if there is none.
5102
31
  unsigned getResultExprIndex() const {
5103
31
    if (PseudoObjectExprBits.ResultIndex == 0) 
return NoResult3
;
5104
28
    return PseudoObjectExprBits.ResultIndex - 1;
5105
28
  }
5106
5107
  /// Return the result-bearing expression, or null if there is none.
5108
1.08k
  Expr *getResultExpr() {
5109
1.08k
    if (PseudoObjectExprBits.ResultIndex == 0)
5110
14
      return nullptr;
5111
1.06k
    return getSubExprsBuffer()[PseudoObjectExprBits.ResultIndex];
5112
1.06k
  }
5113
663
  const Expr *getResultExpr() const {
5114
663
    return const_cast<PseudoObjectExpr*>(this)->getResultExpr();
5115
663
  }
5116
5117
963
  unsigned getNumSemanticExprs() const { return getNumSubExprs() - 1; }
5118
5119
  typedef Expr * const *semantics_iterator;
5120
  typedef const Expr * const *const_semantics_iterator;
5121
4.21k
  semantics_iterator semantics_begin() {
5122
4.21k
    return getSubExprsBuffer() + 1;
5123
4.21k
  }
5124
387
  const_semantics_iterator semantics_begin() const {
5125
387
    return getSubExprsBuffer() + 1;
5126
387
  }
5127
4.21k
  semantics_iterator semantics_end() {
5128
4.21k
    return getSubExprsBuffer() + getNumSubExprs();
5129
4.21k
  }
5130
387
  const_semantics_iterator semantics_end() const {
5131
387
    return getSubExprsBuffer() + getNumSubExprs();
5132
387
  }
5133
5134
2.41k
  llvm::iterator_range<semantics_iterator> semantics() {
5135
2.41k
    return llvm::make_range(semantics_begin(), semantics_end());
5136
2.41k
  }
5137
0
  llvm::iterator_range<const_semantics_iterator> semantics() const {
5138
0
    return llvm::make_range(semantics_begin(), semantics_end());
5139
0
  }
5140
5141
2.16k
  Expr *getSemanticExpr(unsigned index) {
5142
2.16k
    assert(index + 1 < getNumSubExprs());
5143
2.16k
    return getSubExprsBuffer()[index + 1];
5144
2.16k
  }
5145
24
  const Expr *getSemanticExpr(unsigned index) const {
5146
24
    return const_cast<PseudoObjectExpr*>(this)->getSemanticExpr(index);
5147
24
  }
5148
5149
6.60k
  SourceLocation getExprLoc() const LLVM_READONLY {
5150
6.60k
    return getSyntacticForm()->getExprLoc();
5151
6.60k
  }
5152
5153
8.52k
  SourceLocation getLocStart() const LLVM_READONLY {
5154
8.52k
    return getSyntacticForm()->getLocStart();
5155
8.52k
  }
5156
1.81k
  SourceLocation getLocEnd() const LLVM_READONLY {
5157
1.81k
    return getSyntacticForm()->getLocEnd();
5158
1.81k
  }
5159
5160
5.21k
  child_range children() {
5161
5.21k
    const_child_range CCR =
5162
5.21k
        const_cast<const PseudoObjectExpr *>(this)->children();
5163
5.21k
    return child_range(cast_away_const(CCR.begin()),
5164
5.21k
                       cast_away_const(CCR.end()));
5165
5.21k
  }
5166
5.21k
  const_child_range children() const {
5167
5.21k
    Stmt *const *cs = const_cast<Stmt *const *>(
5168
5.21k
        reinterpret_cast<const Stmt *const *>(getSubExprsBuffer()));
5169
5.21k
    return const_child_range(cs, cs + getNumSubExprs());
5170
5.21k
  }
5171
5172
33.6M
  static bool classof(const Stmt *T) {
5173
33.6M
    return T->getStmtClass() == PseudoObjectExprClass;
5174
33.6M
  }
5175
5176
  friend TrailingObjects;
5177
  friend class ASTStmtReader;
5178
};
5179
5180
/// AtomicExpr - Variadic atomic builtins: __atomic_exchange, __atomic_fetch_*,
5181
/// __atomic_load, __atomic_store, and __atomic_compare_exchange_*, for the
5182
/// similarly-named C++11 instructions, and __c11 variants for <stdatomic.h>,
5183
/// and corresponding __opencl_atomic_* for OpenCL 2.0.
5184
/// All of these instructions take one primary pointer, at least one memory
5185
/// order. The instructions for which getScopeModel returns non-null value
5186
/// take one synch scope.
5187
class AtomicExpr : public Expr {
5188
public:
5189
  enum AtomicOp {
5190
#define BUILTIN(ID, TYPE, ATTRS)
5191
#define ATOMIC_BUILTIN(ID, TYPE, ATTRS) AO ## ID,
5192
#include "clang/Basic/Builtins.def"
5193
    // Avoid trailing comma
5194
    BI_First = 0
5195
  };
5196
5197
private:
5198
  /// Location of sub-expressions.
5199
  /// The location of Scope sub-expression is NumSubExprs - 1, which is
5200
  /// not fixed, therefore is not defined in enum.
5201
  enum { PTR, ORDER, VAL1, ORDER_FAIL, VAL2, WEAK, END_EXPR };
5202
  Stmt *SubExprs[END_EXPR + 1];
5203
  unsigned NumSubExprs;
5204
  SourceLocation BuiltinLoc, RParenLoc;
5205
  AtomicOp Op;
5206
5207
  friend class ASTStmtReader;
5208
public:
5209
  AtomicExpr(SourceLocation BLoc, ArrayRef<Expr*> args, QualType t,
5210
             AtomicOp op, SourceLocation RP);
5211
5212
  /// Determine the number of arguments the specified atomic builtin
5213
  /// should have.
5214
  static unsigned getNumSubExprs(AtomicOp Op);
5215
5216
  /// Build an empty AtomicExpr.
5217
112
  explicit AtomicExpr(EmptyShell Empty) : Expr(AtomicExprClass, Empty) { }
5218
5219
2.46k
  Expr *getPtr() const {
5220
2.46k
    return cast<Expr>(SubExprs[PTR]);
5221
2.46k
  }
5222
669
  Expr *getOrder() const {
5223
669
    return cast<Expr>(SubExprs[ORDER]);
5224
669
  }
5225
73
  Expr *getScope() const {
5226
73
    assert(getScopeModel() && "No scope");
5227
73
    return cast<Expr>(SubExprs[NumSubExprs - 1]);
5228
73
  }
5229
636
  Expr *getVal1() const {
5230
636
    if (Op == AO__c11_atomic_init || 
Op == AO__opencl_atomic_init621
)
5231
17
      return cast<Expr>(SubExprs[ORDER]);
5232
619
    assert(NumSubExprs > VAL1);
5233
619
    return cast<Expr>(SubExprs[VAL1]);
5234
619
  }
5235
73
  Expr *getOrderFail() const {
5236
73
    assert(NumSubExprs > ORDER_FAIL);
5237
73
    return cast<Expr>(SubExprs[ORDER_FAIL]);
5238
73
  }
5239
83
  Expr *getVal2() const {
5240
83
    if (Op == AO__atomic_exchange)
5241
10
      return cast<Expr>(SubExprs[ORDER_FAIL]);
5242
73
    assert(NumSubExprs > VAL2);
5243
73
    return cast<Expr>(SubExprs[VAL2]);
5244
73
  }
5245
34
  Expr *getWeak() const {
5246
34
    assert(NumSubExprs > WEAK);
5247
34
    return cast<Expr>(SubExprs[WEAK]);
5248
34
  }
5249
  QualType getValueType() const;
5250
5251
13.9k
  AtomicOp getOp() const { return Op; }
5252
158
  unsigned getNumSubExprs() const { return NumSubExprs; }
5253
5254
409
  Expr **getSubExprs() { return reinterpret_cast<Expr **>(SubExprs); }
5255
117
  const Expr * const *getSubExprs() const {
5256
117
    return reinterpret_cast<Expr * const *>(SubExprs);
5257
117
  }
5258
5259
875
  bool isVolatile() const {
5260
875
    return getPtr()->getType()->getPointeeType().isVolatileQualified();
5261
875
  }
5262
5263
748
  bool isCmpXChg() const {
5264
748
    return getOp() == AO__c11_atomic_compare_exchange_strong ||
5265
748
           
getOp() == AO__c11_atomic_compare_exchange_weak725
||
5266
748
           
getOp() == AO__opencl_atomic_compare_exchange_strong723
||
5267
748
           
getOp() == AO__opencl_atomic_compare_exchange_weak713
||
5268
748
           
getOp() == AO__atomic_compare_exchange693
||
5269
748
           
getOp() == AO__atomic_compare_exchange_n655
;
5270
748
  }
5271
5272
499
  bool isOpenCL() const {
5273
499
    return getOp() >= AO__opencl_atomic_init &&
5274
499
           
getOp() <= AO__opencl_atomic_fetch_max92
;
5275
499
  }
5276
5277
116
  SourceLocation getBuiltinLoc() const { return BuiltinLoc; }
5278
116
  SourceLocation getRParenLoc() const { return RParenLoc; }
5279
5280
16.3k
  SourceLocation getLocStart() const LLVM_READONLY { return BuiltinLoc; }
5281
547
  SourceLocation getLocEnd() const LLVM_READONLY { return RParenLoc; }
5282
5283
711
  static bool classof(const Stmt *T) {
5284
711
    return T->getStmtClass() == AtomicExprClass;
5285
711
  }
5286
5287
  // Iterators
5288
8.54k
  child_range children() {
5289
8.54k
    return child_range(SubExprs, SubExprs+NumSubExprs);
5290
8.54k
  }
5291
0
  const_child_range children() const {
5292
0
    return const_child_range(SubExprs, SubExprs + NumSubExprs);
5293
0
  }
5294
5295
  /// Get atomic scope model for the atomic op code.
5296
  /// \return empty atomic scope model if the atomic op code does not have
5297
  ///   scope operand.
5298
5.28k
  static std::unique_ptr<AtomicScopeModel> getScopeModel(AtomicOp Op) {
5299
5.28k
    auto Kind =
5300
5.28k
        (Op >= AO__opencl_atomic_load && 
Op <= AO__opencl_atomic_fetch_max416
)
5301
5.28k
            ? 
AtomicScopeModelKind::OpenCL384
5302
5.28k
            : 
AtomicScopeModelKind::None4.90k
;
5303
5.28k
    return AtomicScopeModel::create(Kind);
5304
5.28k
  }
5305
5306
  /// Get atomic scope model.
5307
  /// \return empty atomic scope model if this atomic expression does not have
5308
  ///   scope operand.
5309
1.46k
  std::unique_ptr<AtomicScopeModel> getScopeModel() const {
5310
1.46k
    return getScopeModel(getOp());
5311
1.46k
  }
5312
};
5313
5314
/// TypoExpr - Internal placeholder for expressions where typo correction
5315
/// still needs to be performed and/or an error diagnostic emitted.
5316
class TypoExpr : public Expr {
5317
public:
5318
  TypoExpr(QualType T)
5319
      : Expr(TypoExprClass, T, VK_LValue, OK_Ordinary,
5320
             /*isTypeDependent*/ true,
5321
             /*isValueDependent*/ true,
5322
             /*isInstantiationDependent*/ true,
5323
1.08k
             /*containsUnexpandedParameterPack*/ false) {
5324
1.08k
    assert(T->isDependentType() && "TypoExpr given a non-dependent type");
5325
1.08k
  }
5326
5327
791
  child_range children() {
5328
791
    return child_range(child_iterator(), child_iterator());
5329
791
  }
5330
0
  const_child_range children() const {
5331
0
    return const_child_range(const_child_iterator(), const_child_iterator());
5332
0
  }
5333
5334
315
  SourceLocation getLocStart() const LLVM_READONLY { return SourceLocation(); }
5335
168
  SourceLocation getLocEnd() const LLVM_READONLY { return SourceLocation(); }
5336
  
5337
2.33k
  static bool classof(const Stmt *T) {
5338
2.33k
    return T->getStmtClass() == TypoExprClass;
5339
2.33k
  }
5340
5341
};
5342
} // end namespace clang
5343
<