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