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