Home | History | Annotate | Download | only in Sema
      1 //===------- TreeTransform.h - Semantic Tree Transformation -----*- 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 //  This file implements a semantic tree transformation that takes a given
     10 //  AST and rebuilds it, possibly transforming some nodes in the process.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_CLANG_SEMA_TREETRANSFORM_H
     15 #define LLVM_CLANG_SEMA_TREETRANSFORM_H
     16 
     17 #include "TypeLocBuilder.h"
     18 #include "clang/AST/Decl.h"
     19 #include "clang/AST/DeclObjC.h"
     20 #include "clang/AST/DeclTemplate.h"
     21 #include "clang/AST/Expr.h"
     22 #include "clang/AST/ExprCXX.h"
     23 #include "clang/AST/ExprObjC.h"
     24 #include "clang/AST/Stmt.h"
     25 #include "clang/AST/StmtCXX.h"
     26 #include "clang/AST/StmtObjC.h"
     27 #include "clang/AST/StmtOpenMP.h"
     28 #include "clang/Lex/Preprocessor.h"
     29 #include "clang/Sema/Designator.h"
     30 #include "clang/Sema/Lookup.h"
     31 #include "clang/Sema/Ownership.h"
     32 #include "clang/Sema/ParsedTemplate.h"
     33 #include "clang/Sema/ScopeInfo.h"
     34 #include "clang/Sema/SemaDiagnostic.h"
     35 #include "clang/Sema/SemaInternal.h"
     36 #include "llvm/ADT/ArrayRef.h"
     37 #include "llvm/Support/ErrorHandling.h"
     38 #include <algorithm>
     39 
     40 namespace clang {
     41 using namespace sema;
     42 
     43 /// \brief A semantic tree transformation that allows one to transform one
     44 /// abstract syntax tree into another.
     45 ///
     46 /// A new tree transformation is defined by creating a new subclass \c X of
     47 /// \c TreeTransform<X> and then overriding certain operations to provide
     48 /// behavior specific to that transformation. For example, template
     49 /// instantiation is implemented as a tree transformation where the
     50 /// transformation of TemplateTypeParmType nodes involves substituting the
     51 /// template arguments for their corresponding template parameters; a similar
     52 /// transformation is performed for non-type template parameters and
     53 /// template template parameters.
     54 ///
     55 /// This tree-transformation template uses static polymorphism to allow
     56 /// subclasses to customize any of its operations. Thus, a subclass can
     57 /// override any of the transformation or rebuild operators by providing an
     58 /// operation with the same signature as the default implementation. The
     59 /// overridding function should not be virtual.
     60 ///
     61 /// Semantic tree transformations are split into two stages, either of which
     62 /// can be replaced by a subclass. The "transform" step transforms an AST node
     63 /// or the parts of an AST node using the various transformation functions,
     64 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
     65 /// node of the appropriate kind from the pieces. The default transformation
     66 /// routines recursively transform the operands to composite AST nodes (e.g.,
     67 /// the pointee type of a PointerType node) and, if any of those operand nodes
     68 /// were changed by the transformation, invokes the rebuild operation to create
     69 /// a new AST node.
     70 ///
     71 /// Subclasses can customize the transformation at various levels. The
     72 /// most coarse-grained transformations involve replacing TransformType(),
     73 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
     74 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
     75 /// new implementations.
     76 ///
     77 /// For more fine-grained transformations, subclasses can replace any of the
     78 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
     79 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
     80 /// replacing TransformTemplateTypeParmType() allows template instantiation
     81 /// to substitute template arguments for their corresponding template
     82 /// parameters. Additionally, subclasses can override the \c RebuildXXX
     83 /// functions to control how AST nodes are rebuilt when their operands change.
     84 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
     85 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
     86 /// be able to use more efficient rebuild steps.
     87 ///
     88 /// There are a handful of other functions that can be overridden, allowing one
     89 /// to avoid traversing nodes that don't need any transformation
     90 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
     91 /// operands have not changed (\c AlwaysRebuild()), and customize the
     92 /// default locations and entity names used for type-checking
     93 /// (\c getBaseLocation(), \c getBaseEntity()).
     94 template<typename Derived>
     95 class TreeTransform {
     96   /// \brief Private RAII object that helps us forget and then re-remember
     97   /// the template argument corresponding to a partially-substituted parameter
     98   /// pack.
     99   class ForgetPartiallySubstitutedPackRAII {
    100     Derived &Self;
    101     TemplateArgument Old;
    102 
    103   public:
    104     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
    105       Old = Self.ForgetPartiallySubstitutedPack();
    106     }
    107 
    108     ~ForgetPartiallySubstitutedPackRAII() {
    109       Self.RememberPartiallySubstitutedPack(Old);
    110     }
    111   };
    112 
    113 protected:
    114   Sema &SemaRef;
    115 
    116   /// \brief The set of local declarations that have been transformed, for
    117   /// cases where we are forced to build new declarations within the transformer
    118   /// rather than in the subclass (e.g., lambda closure types).
    119   llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
    120 
    121 public:
    122   /// \brief Initializes a new tree transformer.
    123   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
    124 
    125   /// \brief Retrieves a reference to the derived class.
    126   Derived &getDerived() { return static_cast<Derived&>(*this); }
    127 
    128   /// \brief Retrieves a reference to the derived class.
    129   const Derived &getDerived() const {
    130     return static_cast<const Derived&>(*this);
    131   }
    132 
    133   static inline ExprResult Owned(Expr *E) { return E; }
    134   static inline StmtResult Owned(Stmt *S) { return S; }
    135 
    136   /// \brief Retrieves a reference to the semantic analysis object used for
    137   /// this tree transform.
    138   Sema &getSema() const { return SemaRef; }
    139 
    140   /// \brief Whether the transformation should always rebuild AST nodes, even
    141   /// if none of the children have changed.
    142   ///
    143   /// Subclasses may override this function to specify when the transformation
    144   /// should rebuild all AST nodes.
    145   bool AlwaysRebuild() { return false; }
    146 
    147   /// \brief Returns the location of the entity being transformed, if that
    148   /// information was not available elsewhere in the AST.
    149   ///
    150   /// By default, returns no source-location information. Subclasses can
    151   /// provide an alternative implementation that provides better location
    152   /// information.
    153   SourceLocation getBaseLocation() { return SourceLocation(); }
    154 
    155   /// \brief Returns the name of the entity being transformed, if that
    156   /// information was not available elsewhere in the AST.
    157   ///
    158   /// By default, returns an empty name. Subclasses can provide an alternative
    159   /// implementation with a more precise name.
    160   DeclarationName getBaseEntity() { return DeclarationName(); }
    161 
    162   /// \brief Sets the "base" location and entity when that
    163   /// information is known based on another transformation.
    164   ///
    165   /// By default, the source location and entity are ignored. Subclasses can
    166   /// override this function to provide a customized implementation.
    167   void setBase(SourceLocation Loc, DeclarationName Entity) { }
    168 
    169   /// \brief RAII object that temporarily sets the base location and entity
    170   /// used for reporting diagnostics in types.
    171   class TemporaryBase {
    172     TreeTransform &Self;
    173     SourceLocation OldLocation;
    174     DeclarationName OldEntity;
    175 
    176   public:
    177     TemporaryBase(TreeTransform &Self, SourceLocation Location,
    178                   DeclarationName Entity) : Self(Self) {
    179       OldLocation = Self.getDerived().getBaseLocation();
    180       OldEntity = Self.getDerived().getBaseEntity();
    181 
    182       if (Location.isValid())
    183         Self.getDerived().setBase(Location, Entity);
    184     }
    185 
    186     ~TemporaryBase() {
    187       Self.getDerived().setBase(OldLocation, OldEntity);
    188     }
    189   };
    190 
    191   /// \brief Determine whether the given type \p T has already been
    192   /// transformed.
    193   ///
    194   /// Subclasses can provide an alternative implementation of this routine
    195   /// to short-circuit evaluation when it is known that a given type will
    196   /// not change. For example, template instantiation need not traverse
    197   /// non-dependent types.
    198   bool AlreadyTransformed(QualType T) {
    199     return T.isNull();
    200   }
    201 
    202   /// \brief Determine whether the given call argument should be dropped, e.g.,
    203   /// because it is a default argument.
    204   ///
    205   /// Subclasses can provide an alternative implementation of this routine to
    206   /// determine which kinds of call arguments get dropped. By default,
    207   /// CXXDefaultArgument nodes are dropped (prior to transformation).
    208   bool DropCallArgument(Expr *E) {
    209     return E->isDefaultArgument();
    210   }
    211 
    212   /// \brief Determine whether we should expand a pack expansion with the
    213   /// given set of parameter packs into separate arguments by repeatedly
    214   /// transforming the pattern.
    215   ///
    216   /// By default, the transformer never tries to expand pack expansions.
    217   /// Subclasses can override this routine to provide different behavior.
    218   ///
    219   /// \param EllipsisLoc The location of the ellipsis that identifies the
    220   /// pack expansion.
    221   ///
    222   /// \param PatternRange The source range that covers the entire pattern of
    223   /// the pack expansion.
    224   ///
    225   /// \param Unexpanded The set of unexpanded parameter packs within the
    226   /// pattern.
    227   ///
    228   /// \param ShouldExpand Will be set to \c true if the transformer should
    229   /// expand the corresponding pack expansions into separate arguments. When
    230   /// set, \c NumExpansions must also be set.
    231   ///
    232   /// \param RetainExpansion Whether the caller should add an unexpanded
    233   /// pack expansion after all of the expanded arguments. This is used
    234   /// when extending explicitly-specified template argument packs per
    235   /// C++0x [temp.arg.explicit]p9.
    236   ///
    237   /// \param NumExpansions The number of separate arguments that will be in
    238   /// the expanded form of the corresponding pack expansion. This is both an
    239   /// input and an output parameter, which can be set by the caller if the
    240   /// number of expansions is known a priori (e.g., due to a prior substitution)
    241   /// and will be set by the callee when the number of expansions is known.
    242   /// The callee must set this value when \c ShouldExpand is \c true; it may
    243   /// set this value in other cases.
    244   ///
    245   /// \returns true if an error occurred (e.g., because the parameter packs
    246   /// are to be instantiated with arguments of different lengths), false
    247   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
    248   /// must be set.
    249   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
    250                                SourceRange PatternRange,
    251                                ArrayRef<UnexpandedParameterPack> Unexpanded,
    252                                bool &ShouldExpand,
    253                                bool &RetainExpansion,
    254                                Optional<unsigned> &NumExpansions) {
    255     ShouldExpand = false;
    256     return false;
    257   }
    258 
    259   /// \brief "Forget" about the partially-substituted pack template argument,
    260   /// when performing an instantiation that must preserve the parameter pack
    261   /// use.
    262   ///
    263   /// This routine is meant to be overridden by the template instantiator.
    264   TemplateArgument ForgetPartiallySubstitutedPack() {
    265     return TemplateArgument();
    266   }
    267 
    268   /// \brief "Remember" the partially-substituted pack template argument
    269   /// after performing an instantiation that must preserve the parameter pack
    270   /// use.
    271   ///
    272   /// This routine is meant to be overridden by the template instantiator.
    273   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
    274 
    275   /// \brief Note to the derived class when a function parameter pack is
    276   /// being expanded.
    277   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
    278 
    279   /// \brief Transforms the given type into another type.
    280   ///
    281   /// By default, this routine transforms a type by creating a
    282   /// TypeSourceInfo for it and delegating to the appropriate
    283   /// function.  This is expensive, but we don't mind, because
    284   /// this method is deprecated anyway;  all users should be
    285   /// switched to storing TypeSourceInfos.
    286   ///
    287   /// \returns the transformed type.
    288   QualType TransformType(QualType T);
    289 
    290   /// \brief Transforms the given type-with-location into a new
    291   /// type-with-location.
    292   ///
    293   /// By default, this routine transforms a type by delegating to the
    294   /// appropriate TransformXXXType to build a new type.  Subclasses
    295   /// may override this function (to take over all type
    296   /// transformations) or some set of the TransformXXXType functions
    297   /// to alter the transformation.
    298   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
    299 
    300   /// \brief Transform the given type-with-location into a new
    301   /// type, collecting location information in the given builder
    302   /// as necessary.
    303   ///
    304   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
    305 
    306   /// \brief Transform the given statement.
    307   ///
    308   /// By default, this routine transforms a statement by delegating to the
    309   /// appropriate TransformXXXStmt function to transform a specific kind of
    310   /// statement or the TransformExpr() function to transform an expression.
    311   /// Subclasses may override this function to transform statements using some
    312   /// other mechanism.
    313   ///
    314   /// \returns the transformed statement.
    315   StmtResult TransformStmt(Stmt *S);
    316 
    317   /// \brief Transform the given statement.
    318   ///
    319   /// By default, this routine transforms a statement by delegating to the
    320   /// appropriate TransformOMPXXXClause function to transform a specific kind
    321   /// of clause. Subclasses may override this function to transform statements
    322   /// using some other mechanism.
    323   ///
    324   /// \returns the transformed OpenMP clause.
    325   OMPClause *TransformOMPClause(OMPClause *S);
    326 
    327   /// \brief Transform the given expression.
    328   ///
    329   /// By default, this routine transforms an expression by delegating to the
    330   /// appropriate TransformXXXExpr function to build a new expression.
    331   /// Subclasses may override this function to transform expressions using some
    332   /// other mechanism.
    333   ///
    334   /// \returns the transformed expression.
    335   ExprResult TransformExpr(Expr *E);
    336 
    337   /// \brief Transform the given initializer.
    338   ///
    339   /// By default, this routine transforms an initializer by stripping off the
    340   /// semantic nodes added by initialization, then passing the result to
    341   /// TransformExpr or TransformExprs.
    342   ///
    343   /// \returns the transformed initializer.
    344   ExprResult TransformInitializer(Expr *Init, bool CXXDirectInit);
    345 
    346   /// \brief Transform the given list of expressions.
    347   ///
    348   /// This routine transforms a list of expressions by invoking
    349   /// \c TransformExpr() for each subexpression. However, it also provides
    350   /// support for variadic templates by expanding any pack expansions (if the
    351   /// derived class permits such expansion) along the way. When pack expansions
    352   /// are present, the number of outputs may not equal the number of inputs.
    353   ///
    354   /// \param Inputs The set of expressions to be transformed.
    355   ///
    356   /// \param NumInputs The number of expressions in \c Inputs.
    357   ///
    358   /// \param IsCall If \c true, then this transform is being performed on
    359   /// function-call arguments, and any arguments that should be dropped, will
    360   /// be.
    361   ///
    362   /// \param Outputs The transformed input expressions will be added to this
    363   /// vector.
    364   ///
    365   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
    366   /// due to transformation.
    367   ///
    368   /// \returns true if an error occurred, false otherwise.
    369   bool TransformExprs(Expr **Inputs, unsigned NumInputs, bool IsCall,
    370                       SmallVectorImpl<Expr *> &Outputs,
    371                       bool *ArgChanged = 0);
    372 
    373   /// \brief Transform the given declaration, which is referenced from a type
    374   /// or expression.
    375   ///
    376   /// By default, acts as the identity function on declarations, unless the
    377   /// transformer has had to transform the declaration itself. Subclasses
    378   /// may override this function to provide alternate behavior.
    379   Decl *TransformDecl(SourceLocation Loc, Decl *D) {
    380     llvm::DenseMap<Decl *, Decl *>::iterator Known
    381       = TransformedLocalDecls.find(D);
    382     if (Known != TransformedLocalDecls.end())
    383       return Known->second;
    384 
    385     return D;
    386   }
    387 
    388   /// \brief Transform the attributes associated with the given declaration and
    389   /// place them on the new declaration.
    390   ///
    391   /// By default, this operation does nothing. Subclasses may override this
    392   /// behavior to transform attributes.
    393   void transformAttrs(Decl *Old, Decl *New) { }
    394 
    395   /// \brief Note that a local declaration has been transformed by this
    396   /// transformer.
    397   ///
    398   /// Local declarations are typically transformed via a call to
    399   /// TransformDefinition. However, in some cases (e.g., lambda expressions),
    400   /// the transformer itself has to transform the declarations. This routine
    401   /// can be overridden by a subclass that keeps track of such mappings.
    402   void transformedLocalDecl(Decl *Old, Decl *New) {
    403     TransformedLocalDecls[Old] = New;
    404   }
    405 
    406   /// \brief Transform the definition of the given declaration.
    407   ///
    408   /// By default, invokes TransformDecl() to transform the declaration.
    409   /// Subclasses may override this function to provide alternate behavior.
    410   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
    411     return getDerived().TransformDecl(Loc, D);
    412   }
    413 
    414   /// \brief Transform the given declaration, which was the first part of a
    415   /// nested-name-specifier in a member access expression.
    416   ///
    417   /// This specific declaration transformation only applies to the first
    418   /// identifier in a nested-name-specifier of a member access expression, e.g.,
    419   /// the \c T in \c x->T::member
    420   ///
    421   /// By default, invokes TransformDecl() to transform the declaration.
    422   /// Subclasses may override this function to provide alternate behavior.
    423   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
    424     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
    425   }
    426 
    427   /// \brief Transform the given nested-name-specifier with source-location
    428   /// information.
    429   ///
    430   /// By default, transforms all of the types and declarations within the
    431   /// nested-name-specifier. Subclasses may override this function to provide
    432   /// alternate behavior.
    433   NestedNameSpecifierLoc TransformNestedNameSpecifierLoc(
    434                                                     NestedNameSpecifierLoc NNS,
    435                                           QualType ObjectType = QualType(),
    436                                           NamedDecl *FirstQualifierInScope = 0);
    437 
    438   /// \brief Transform the given declaration name.
    439   ///
    440   /// By default, transforms the types of conversion function, constructor,
    441   /// and destructor names and then (if needed) rebuilds the declaration name.
    442   /// Identifiers and selectors are returned unmodified. Sublcasses may
    443   /// override this function to provide alternate behavior.
    444   DeclarationNameInfo
    445   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
    446 
    447   /// \brief Transform the given template name.
    448   ///
    449   /// \param SS The nested-name-specifier that qualifies the template
    450   /// name. This nested-name-specifier must already have been transformed.
    451   ///
    452   /// \param Name The template name to transform.
    453   ///
    454   /// \param NameLoc The source location of the template name.
    455   ///
    456   /// \param ObjectType If we're translating a template name within a member
    457   /// access expression, this is the type of the object whose member template
    458   /// is being referenced.
    459   ///
    460   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
    461   /// also refers to a name within the current (lexical) scope, this is the
    462   /// declaration it refers to.
    463   ///
    464   /// By default, transforms the template name by transforming the declarations
    465   /// and nested-name-specifiers that occur within the template name.
    466   /// Subclasses may override this function to provide alternate behavior.
    467   TemplateName TransformTemplateName(CXXScopeSpec &SS,
    468                                      TemplateName Name,
    469                                      SourceLocation NameLoc,
    470                                      QualType ObjectType = QualType(),
    471                                      NamedDecl *FirstQualifierInScope = 0);
    472 
    473   /// \brief Transform the given template argument.
    474   ///
    475   /// By default, this operation transforms the type, expression, or
    476   /// declaration stored within the template argument and constructs a
    477   /// new template argument from the transformed result. Subclasses may
    478   /// override this function to provide alternate behavior.
    479   ///
    480   /// Returns true if there was an error.
    481   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
    482                                  TemplateArgumentLoc &Output);
    483 
    484   /// \brief Transform the given set of template arguments.
    485   ///
    486   /// By default, this operation transforms all of the template arguments
    487   /// in the input set using \c TransformTemplateArgument(), and appends
    488   /// the transformed arguments to the output list.
    489   ///
    490   /// Note that this overload of \c TransformTemplateArguments() is merely
    491   /// a convenience function. Subclasses that wish to override this behavior
    492   /// should override the iterator-based member template version.
    493   ///
    494   /// \param Inputs The set of template arguments to be transformed.
    495   ///
    496   /// \param NumInputs The number of template arguments in \p Inputs.
    497   ///
    498   /// \param Outputs The set of transformed template arguments output by this
    499   /// routine.
    500   ///
    501   /// Returns true if an error occurred.
    502   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
    503                                   unsigned NumInputs,
    504                                   TemplateArgumentListInfo &Outputs) {
    505     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs);
    506   }
    507 
    508   /// \brief Transform the given set of template arguments.
    509   ///
    510   /// By default, this operation transforms all of the template arguments
    511   /// in the input set using \c TransformTemplateArgument(), and appends
    512   /// the transformed arguments to the output list.
    513   ///
    514   /// \param First An iterator to the first template argument.
    515   ///
    516   /// \param Last An iterator one step past the last template argument.
    517   ///
    518   /// \param Outputs The set of transformed template arguments output by this
    519   /// routine.
    520   ///
    521   /// Returns true if an error occurred.
    522   template<typename InputIterator>
    523   bool TransformTemplateArguments(InputIterator First,
    524                                   InputIterator Last,
    525                                   TemplateArgumentListInfo &Outputs);
    526 
    527   /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
    528   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
    529                                  TemplateArgumentLoc &ArgLoc);
    530 
    531   /// \brief Fakes up a TypeSourceInfo for a type.
    532   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
    533     return SemaRef.Context.getTrivialTypeSourceInfo(T,
    534                        getDerived().getBaseLocation());
    535   }
    536 
    537 #define ABSTRACT_TYPELOC(CLASS, PARENT)
    538 #define TYPELOC(CLASS, PARENT)                                   \
    539   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
    540 #include "clang/AST/TypeLocNodes.def"
    541 
    542   QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
    543                                       FunctionProtoTypeLoc TL,
    544                                       CXXRecordDecl *ThisContext,
    545                                       unsigned ThisTypeQuals);
    546 
    547   StmtResult
    548   TransformSEHHandler(Stmt *Handler);
    549 
    550   QualType
    551   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
    552                                       TemplateSpecializationTypeLoc TL,
    553                                       TemplateName Template);
    554 
    555   QualType
    556   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
    557                                       DependentTemplateSpecializationTypeLoc TL,
    558                                                TemplateName Template,
    559                                                CXXScopeSpec &SS);
    560 
    561   QualType
    562   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
    563                                                DependentTemplateSpecializationTypeLoc TL,
    564                                          NestedNameSpecifierLoc QualifierLoc);
    565 
    566   /// \brief Transforms the parameters of a function type into the
    567   /// given vectors.
    568   ///
    569   /// The result vectors should be kept in sync; null entries in the
    570   /// variables vector are acceptable.
    571   ///
    572   /// Return true on error.
    573   bool TransformFunctionTypeParams(SourceLocation Loc,
    574                                    ParmVarDecl **Params, unsigned NumParams,
    575                                    const QualType *ParamTypes,
    576                                    SmallVectorImpl<QualType> &PTypes,
    577                                    SmallVectorImpl<ParmVarDecl*> *PVars);
    578 
    579   /// \brief Transforms a single function-type parameter.  Return null
    580   /// on error.
    581   ///
    582   /// \param indexAdjustment - A number to add to the parameter's
    583   ///   scope index;  can be negative
    584   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
    585                                           int indexAdjustment,
    586                                           Optional<unsigned> NumExpansions,
    587                                           bool ExpectParameterPack);
    588 
    589   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
    590 
    591   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
    592   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
    593 
    594   /// \brief Transform the captures and body of a lambda expression.
    595   ExprResult TransformLambdaScope(LambdaExpr *E, CXXMethodDecl *CallOperator);
    596 
    597   ExprResult TransformAddressOfOperand(Expr *E);
    598   ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
    599                                                 bool IsAddressOfOperand);
    600 
    601 #define STMT(Node, Parent)                        \
    602   StmtResult Transform##Node(Node *S);
    603 #define EXPR(Node, Parent)                        \
    604   ExprResult Transform##Node(Node *E);
    605 #define ABSTRACT_STMT(Stmt)
    606 #include "clang/AST/StmtNodes.inc"
    607 
    608 #define OPENMP_CLAUSE(Name, Class)                        \
    609   OMPClause *Transform ## Class(Class *S);
    610 #include "clang/Basic/OpenMPKinds.def"
    611 
    612   /// \brief Build a new pointer type given its pointee type.
    613   ///
    614   /// By default, performs semantic analysis when building the pointer type.
    615   /// Subclasses may override this routine to provide different behavior.
    616   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
    617 
    618   /// \brief Build a new block pointer type given its pointee type.
    619   ///
    620   /// By default, performs semantic analysis when building the block pointer
    621   /// type. Subclasses may override this routine to provide different behavior.
    622   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
    623 
    624   /// \brief Build a new reference type given the type it references.
    625   ///
    626   /// By default, performs semantic analysis when building the
    627   /// reference type. Subclasses may override this routine to provide
    628   /// different behavior.
    629   ///
    630   /// \param LValue whether the type was written with an lvalue sigil
    631   /// or an rvalue sigil.
    632   QualType RebuildReferenceType(QualType ReferentType,
    633                                 bool LValue,
    634                                 SourceLocation Sigil);
    635 
    636   /// \brief Build a new member pointer type given the pointee type and the
    637   /// class type it refers into.
    638   ///
    639   /// By default, performs semantic analysis when building the member pointer
    640   /// type. Subclasses may override this routine to provide different behavior.
    641   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
    642                                     SourceLocation Sigil);
    643 
    644   /// \brief Build a new array type given the element type, size
    645   /// modifier, size of the array (if known), size expression, and index type
    646   /// qualifiers.
    647   ///
    648   /// By default, performs semantic analysis when building the array type.
    649   /// Subclasses may override this routine to provide different behavior.
    650   /// Also by default, all of the other Rebuild*Array
    651   QualType RebuildArrayType(QualType ElementType,
    652                             ArrayType::ArraySizeModifier SizeMod,
    653                             const llvm::APInt *Size,
    654                             Expr *SizeExpr,
    655                             unsigned IndexTypeQuals,
    656                             SourceRange BracketsRange);
    657 
    658   /// \brief Build a new constant array type given the element type, size
    659   /// modifier, (known) size of the array, and index type qualifiers.
    660   ///
    661   /// By default, performs semantic analysis when building the array type.
    662   /// Subclasses may override this routine to provide different behavior.
    663   QualType RebuildConstantArrayType(QualType ElementType,
    664                                     ArrayType::ArraySizeModifier SizeMod,
    665                                     const llvm::APInt &Size,
    666                                     unsigned IndexTypeQuals,
    667                                     SourceRange BracketsRange);
    668 
    669   /// \brief Build a new incomplete array type given the element type, size
    670   /// modifier, and index type qualifiers.
    671   ///
    672   /// By default, performs semantic analysis when building the array type.
    673   /// Subclasses may override this routine to provide different behavior.
    674   QualType RebuildIncompleteArrayType(QualType ElementType,
    675                                       ArrayType::ArraySizeModifier SizeMod,
    676                                       unsigned IndexTypeQuals,
    677                                       SourceRange BracketsRange);
    678 
    679   /// \brief Build a new variable-length array type given the element type,
    680   /// size modifier, size expression, and index type qualifiers.
    681   ///
    682   /// By default, performs semantic analysis when building the array type.
    683   /// Subclasses may override this routine to provide different behavior.
    684   QualType RebuildVariableArrayType(QualType ElementType,
    685                                     ArrayType::ArraySizeModifier SizeMod,
    686                                     Expr *SizeExpr,
    687                                     unsigned IndexTypeQuals,
    688                                     SourceRange BracketsRange);
    689 
    690   /// \brief Build a new dependent-sized array type given the element type,
    691   /// size modifier, size expression, and index type qualifiers.
    692   ///
    693   /// By default, performs semantic analysis when building the array type.
    694   /// Subclasses may override this routine to provide different behavior.
    695   QualType RebuildDependentSizedArrayType(QualType ElementType,
    696                                           ArrayType::ArraySizeModifier SizeMod,
    697                                           Expr *SizeExpr,
    698                                           unsigned IndexTypeQuals,
    699                                           SourceRange BracketsRange);
    700 
    701   /// \brief Build a new vector type given the element type and
    702   /// number of elements.
    703   ///
    704   /// By default, performs semantic analysis when building the vector type.
    705   /// Subclasses may override this routine to provide different behavior.
    706   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
    707                              VectorType::VectorKind VecKind);
    708 
    709   /// \brief Build a new extended vector type given the element type and
    710   /// number of elements.
    711   ///
    712   /// By default, performs semantic analysis when building the vector type.
    713   /// Subclasses may override this routine to provide different behavior.
    714   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
    715                                 SourceLocation AttributeLoc);
    716 
    717   /// \brief Build a new potentially dependently-sized extended vector type
    718   /// given the element type and number of elements.
    719   ///
    720   /// By default, performs semantic analysis when building the vector type.
    721   /// Subclasses may override this routine to provide different behavior.
    722   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
    723                                               Expr *SizeExpr,
    724                                               SourceLocation AttributeLoc);
    725 
    726   /// \brief Build a new function type.
    727   ///
    728   /// By default, performs semantic analysis when building the function type.
    729   /// Subclasses may override this routine to provide different behavior.
    730   QualType RebuildFunctionProtoType(QualType T,
    731                                     llvm::MutableArrayRef<QualType> ParamTypes,
    732                                     const FunctionProtoType::ExtProtoInfo &EPI);
    733 
    734   /// \brief Build a new unprototyped function type.
    735   QualType RebuildFunctionNoProtoType(QualType ResultType);
    736 
    737   /// \brief Rebuild an unresolved typename type, given the decl that
    738   /// the UnresolvedUsingTypenameDecl was transformed to.
    739   QualType RebuildUnresolvedUsingType(Decl *D);
    740 
    741   /// \brief Build a new typedef type.
    742   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
    743     return SemaRef.Context.getTypeDeclType(Typedef);
    744   }
    745 
    746   /// \brief Build a new class/struct/union type.
    747   QualType RebuildRecordType(RecordDecl *Record) {
    748     return SemaRef.Context.getTypeDeclType(Record);
    749   }
    750 
    751   /// \brief Build a new Enum type.
    752   QualType RebuildEnumType(EnumDecl *Enum) {
    753     return SemaRef.Context.getTypeDeclType(Enum);
    754   }
    755 
    756   /// \brief Build a new typeof(expr) type.
    757   ///
    758   /// By default, performs semantic analysis when building the typeof type.
    759   /// Subclasses may override this routine to provide different behavior.
    760   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
    761 
    762   /// \brief Build a new typeof(type) type.
    763   ///
    764   /// By default, builds a new TypeOfType with the given underlying type.
    765   QualType RebuildTypeOfType(QualType Underlying);
    766 
    767   /// \brief Build a new unary transform type.
    768   QualType RebuildUnaryTransformType(QualType BaseType,
    769                                      UnaryTransformType::UTTKind UKind,
    770                                      SourceLocation Loc);
    771 
    772   /// \brief Build a new C++11 decltype type.
    773   ///
    774   /// By default, performs semantic analysis when building the decltype type.
    775   /// Subclasses may override this routine to provide different behavior.
    776   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
    777 
    778   /// \brief Build a new C++11 auto type.
    779   ///
    780   /// By default, builds a new AutoType with the given deduced type.
    781   QualType RebuildAutoType(QualType Deduced, bool IsDecltypeAuto) {
    782     // Note, IsDependent is always false here: we implicitly convert an 'auto'
    783     // which has been deduced to a dependent type into an undeduced 'auto', so
    784     // that we'll retry deduction after the transformation.
    785     return SemaRef.Context.getAutoType(Deduced, IsDecltypeAuto);
    786   }
    787 
    788   /// \brief Build a new template specialization type.
    789   ///
    790   /// By default, performs semantic analysis when building the template
    791   /// specialization type. Subclasses may override this routine to provide
    792   /// different behavior.
    793   QualType RebuildTemplateSpecializationType(TemplateName Template,
    794                                              SourceLocation TemplateLoc,
    795                                              TemplateArgumentListInfo &Args);
    796 
    797   /// \brief Build a new parenthesized type.
    798   ///
    799   /// By default, builds a new ParenType type from the inner type.
    800   /// Subclasses may override this routine to provide different behavior.
    801   QualType RebuildParenType(QualType InnerType) {
    802     return SemaRef.Context.getParenType(InnerType);
    803   }
    804 
    805   /// \brief Build a new qualified name type.
    806   ///
    807   /// By default, builds a new ElaboratedType type from the keyword,
    808   /// the nested-name-specifier and the named type.
    809   /// Subclasses may override this routine to provide different behavior.
    810   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
    811                                  ElaboratedTypeKeyword Keyword,
    812                                  NestedNameSpecifierLoc QualifierLoc,
    813                                  QualType Named) {
    814     return SemaRef.Context.getElaboratedType(Keyword,
    815                                          QualifierLoc.getNestedNameSpecifier(),
    816                                              Named);
    817   }
    818 
    819   /// \brief Build a new typename type that refers to a template-id.
    820   ///
    821   /// By default, builds a new DependentNameType type from the
    822   /// nested-name-specifier and the given type. Subclasses may override
    823   /// this routine to provide different behavior.
    824   QualType RebuildDependentTemplateSpecializationType(
    825                                           ElaboratedTypeKeyword Keyword,
    826                                           NestedNameSpecifierLoc QualifierLoc,
    827                                           const IdentifierInfo *Name,
    828                                           SourceLocation NameLoc,
    829                                           TemplateArgumentListInfo &Args) {
    830     // Rebuild the template name.
    831     // TODO: avoid TemplateName abstraction
    832     CXXScopeSpec SS;
    833     SS.Adopt(QualifierLoc);
    834     TemplateName InstName
    835       = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(), 0);
    836 
    837     if (InstName.isNull())
    838       return QualType();
    839 
    840     // If it's still dependent, make a dependent specialization.
    841     if (InstName.getAsDependentTemplateName())
    842       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
    843                                           QualifierLoc.getNestedNameSpecifier(),
    844                                                                     Name,
    845                                                                     Args);
    846 
    847     // Otherwise, make an elaborated type wrapping a non-dependent
    848     // specialization.
    849     QualType T =
    850     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
    851     if (T.isNull()) return QualType();
    852 
    853     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == 0)
    854       return T;
    855 
    856     return SemaRef.Context.getElaboratedType(Keyword,
    857                                        QualifierLoc.getNestedNameSpecifier(),
    858                                              T);
    859   }
    860 
    861   /// \brief Build a new typename type that refers to an identifier.
    862   ///
    863   /// By default, performs semantic analysis when building the typename type
    864   /// (or elaborated type). Subclasses may override this routine to provide
    865   /// different behavior.
    866   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
    867                                     SourceLocation KeywordLoc,
    868                                     NestedNameSpecifierLoc QualifierLoc,
    869                                     const IdentifierInfo *Id,
    870                                     SourceLocation IdLoc) {
    871     CXXScopeSpec SS;
    872     SS.Adopt(QualifierLoc);
    873 
    874     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
    875       // If the name is still dependent, just build a new dependent name type.
    876       if (!SemaRef.computeDeclContext(SS))
    877         return SemaRef.Context.getDependentNameType(Keyword,
    878                                           QualifierLoc.getNestedNameSpecifier(),
    879                                                     Id);
    880     }
    881 
    882     if (Keyword == ETK_None || Keyword == ETK_Typename)
    883       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
    884                                        *Id, IdLoc);
    885 
    886     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
    887 
    888     // We had a dependent elaborated-type-specifier that has been transformed
    889     // into a non-dependent elaborated-type-specifier. Find the tag we're
    890     // referring to.
    891     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
    892     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
    893     if (!DC)
    894       return QualType();
    895 
    896     if (SemaRef.RequireCompleteDeclContext(SS, DC))
    897       return QualType();
    898 
    899     TagDecl *Tag = 0;
    900     SemaRef.LookupQualifiedName(Result, DC);
    901     switch (Result.getResultKind()) {
    902       case LookupResult::NotFound:
    903       case LookupResult::NotFoundInCurrentInstantiation:
    904         break;
    905 
    906       case LookupResult::Found:
    907         Tag = Result.getAsSingle<TagDecl>();
    908         break;
    909 
    910       case LookupResult::FoundOverloaded:
    911       case LookupResult::FoundUnresolvedValue:
    912         llvm_unreachable("Tag lookup cannot find non-tags");
    913 
    914       case LookupResult::Ambiguous:
    915         // Let the LookupResult structure handle ambiguities.
    916         return QualType();
    917     }
    918 
    919     if (!Tag) {
    920       // Check where the name exists but isn't a tag type and use that to emit
    921       // better diagnostics.
    922       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
    923       SemaRef.LookupQualifiedName(Result, DC);
    924       switch (Result.getResultKind()) {
    925         case LookupResult::Found:
    926         case LookupResult::FoundOverloaded:
    927         case LookupResult::FoundUnresolvedValue: {
    928           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
    929           unsigned Kind = 0;
    930           if (isa<TypedefDecl>(SomeDecl)) Kind = 1;
    931           else if (isa<TypeAliasDecl>(SomeDecl)) Kind = 2;
    932           else if (isa<ClassTemplateDecl>(SomeDecl)) Kind = 3;
    933           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << Kind;
    934           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
    935           break;
    936         }
    937         default:
    938           // FIXME: Would be nice to highlight just the source range.
    939           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
    940             << Kind << Id << DC;
    941           break;
    942       }
    943       return QualType();
    944     }
    945 
    946     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
    947                                               IdLoc, *Id)) {
    948       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
    949       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
    950       return QualType();
    951     }
    952 
    953     // Build the elaborated-type-specifier type.
    954     QualType T = SemaRef.Context.getTypeDeclType(Tag);
    955     return SemaRef.Context.getElaboratedType(Keyword,
    956                                          QualifierLoc.getNestedNameSpecifier(),
    957                                              T);
    958   }
    959 
    960   /// \brief Build a new pack expansion type.
    961   ///
    962   /// By default, builds a new PackExpansionType type from the given pattern.
    963   /// Subclasses may override this routine to provide different behavior.
    964   QualType RebuildPackExpansionType(QualType Pattern,
    965                                     SourceRange PatternRange,
    966                                     SourceLocation EllipsisLoc,
    967                                     Optional<unsigned> NumExpansions) {
    968     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
    969                                         NumExpansions);
    970   }
    971 
    972   /// \brief Build a new atomic type given its value type.
    973   ///
    974   /// By default, performs semantic analysis when building the atomic type.
    975   /// Subclasses may override this routine to provide different behavior.
    976   QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
    977 
    978   /// \brief Build a new template name given a nested name specifier, a flag
    979   /// indicating whether the "template" keyword was provided, and the template
    980   /// that the template name refers to.
    981   ///
    982   /// By default, builds the new template name directly. Subclasses may override
    983   /// this routine to provide different behavior.
    984   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
    985                                    bool TemplateKW,
    986                                    TemplateDecl *Template);
    987 
    988   /// \brief Build a new template name given a nested name specifier and the
    989   /// name that is referred to as a template.
    990   ///
    991   /// By default, performs semantic analysis to determine whether the name can
    992   /// be resolved to a specific template, then builds the appropriate kind of
    993   /// template name. Subclasses may override this routine to provide different
    994   /// behavior.
    995   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
    996                                    const IdentifierInfo &Name,
    997                                    SourceLocation NameLoc,
    998                                    QualType ObjectType,
    999                                    NamedDecl *FirstQualifierInScope);
   1000 
   1001   /// \brief Build a new template name given a nested name specifier and the
   1002   /// overloaded operator name that is referred to as a template.
   1003   ///
   1004   /// By default, performs semantic analysis to determine whether the name can
   1005   /// be resolved to a specific template, then builds the appropriate kind of
   1006   /// template name. Subclasses may override this routine to provide different
   1007   /// behavior.
   1008   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
   1009                                    OverloadedOperatorKind Operator,
   1010                                    SourceLocation NameLoc,
   1011                                    QualType ObjectType);
   1012 
   1013   /// \brief Build a new template name given a template template parameter pack
   1014   /// and the
   1015   ///
   1016   /// By default, performs semantic analysis to determine whether the name can
   1017   /// be resolved to a specific template, then builds the appropriate kind of
   1018   /// template name. Subclasses may override this routine to provide different
   1019   /// behavior.
   1020   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
   1021                                    const TemplateArgument &ArgPack) {
   1022     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
   1023   }
   1024 
   1025   /// \brief Build a new compound statement.
   1026   ///
   1027   /// By default, performs semantic analysis to build the new statement.
   1028   /// Subclasses may override this routine to provide different behavior.
   1029   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
   1030                                        MultiStmtArg Statements,
   1031                                        SourceLocation RBraceLoc,
   1032                                        bool IsStmtExpr) {
   1033     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
   1034                                        IsStmtExpr);
   1035   }
   1036 
   1037   /// \brief Build a new case statement.
   1038   ///
   1039   /// By default, performs semantic analysis to build the new statement.
   1040   /// Subclasses may override this routine to provide different behavior.
   1041   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
   1042                                    Expr *LHS,
   1043                                    SourceLocation EllipsisLoc,
   1044                                    Expr *RHS,
   1045                                    SourceLocation ColonLoc) {
   1046     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
   1047                                    ColonLoc);
   1048   }
   1049 
   1050   /// \brief Attach the body to a new case statement.
   1051   ///
   1052   /// By default, performs semantic analysis to build the new statement.
   1053   /// Subclasses may override this routine to provide different behavior.
   1054   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
   1055     getSema().ActOnCaseStmtBody(S, Body);
   1056     return S;
   1057   }
   1058 
   1059   /// \brief Build a new default statement.
   1060   ///
   1061   /// By default, performs semantic analysis to build the new statement.
   1062   /// Subclasses may override this routine to provide different behavior.
   1063   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
   1064                                       SourceLocation ColonLoc,
   1065                                       Stmt *SubStmt) {
   1066     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
   1067                                       /*CurScope=*/0);
   1068   }
   1069 
   1070   /// \brief Build a new label statement.
   1071   ///
   1072   /// By default, performs semantic analysis to build the new statement.
   1073   /// Subclasses may override this routine to provide different behavior.
   1074   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
   1075                               SourceLocation ColonLoc, Stmt *SubStmt) {
   1076     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
   1077   }
   1078 
   1079   /// \brief Build a new label statement.
   1080   ///
   1081   /// By default, performs semantic analysis to build the new statement.
   1082   /// Subclasses may override this routine to provide different behavior.
   1083   StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
   1084                                    ArrayRef<const Attr*> Attrs,
   1085                                    Stmt *SubStmt) {
   1086     return SemaRef.ActOnAttributedStmt(AttrLoc, Attrs, SubStmt);
   1087   }
   1088 
   1089   /// \brief Build a new "if" statement.
   1090   ///
   1091   /// By default, performs semantic analysis to build the new statement.
   1092   /// Subclasses may override this routine to provide different behavior.
   1093   StmtResult RebuildIfStmt(SourceLocation IfLoc, Sema::FullExprArg Cond,
   1094                            VarDecl *CondVar, Stmt *Then,
   1095                            SourceLocation ElseLoc, Stmt *Else) {
   1096     return getSema().ActOnIfStmt(IfLoc, Cond, CondVar, Then, ElseLoc, Else);
   1097   }
   1098 
   1099   /// \brief Start building a new switch statement.
   1100   ///
   1101   /// By default, performs semantic analysis to build the new statement.
   1102   /// Subclasses may override this routine to provide different behavior.
   1103   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
   1104                                     Expr *Cond, VarDecl *CondVar) {
   1105     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Cond,
   1106                                             CondVar);
   1107   }
   1108 
   1109   /// \brief Attach the body to the switch statement.
   1110   ///
   1111   /// By default, performs semantic analysis to build the new statement.
   1112   /// Subclasses may override this routine to provide different behavior.
   1113   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
   1114                                    Stmt *Switch, Stmt *Body) {
   1115     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
   1116   }
   1117 
   1118   /// \brief Build a new while statement.
   1119   ///
   1120   /// By default, performs semantic analysis to build the new statement.
   1121   /// Subclasses may override this routine to provide different behavior.
   1122   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, Sema::FullExprArg Cond,
   1123                               VarDecl *CondVar, Stmt *Body) {
   1124     return getSema().ActOnWhileStmt(WhileLoc, Cond, CondVar, Body);
   1125   }
   1126 
   1127   /// \brief Build a new do-while statement.
   1128   ///
   1129   /// By default, performs semantic analysis to build the new statement.
   1130   /// Subclasses may override this routine to provide different behavior.
   1131   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
   1132                            SourceLocation WhileLoc, SourceLocation LParenLoc,
   1133                            Expr *Cond, SourceLocation RParenLoc) {
   1134     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
   1135                                  Cond, RParenLoc);
   1136   }
   1137 
   1138   /// \brief Build a new for statement.
   1139   ///
   1140   /// By default, performs semantic analysis to build the new statement.
   1141   /// Subclasses may override this routine to provide different behavior.
   1142   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
   1143                             Stmt *Init, Sema::FullExprArg Cond,
   1144                             VarDecl *CondVar, Sema::FullExprArg Inc,
   1145                             SourceLocation RParenLoc, Stmt *Body) {
   1146     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
   1147                                   CondVar, Inc, RParenLoc, Body);
   1148   }
   1149 
   1150   /// \brief Build a new goto statement.
   1151   ///
   1152   /// By default, performs semantic analysis to build the new statement.
   1153   /// Subclasses may override this routine to provide different behavior.
   1154   StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
   1155                              LabelDecl *Label) {
   1156     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
   1157   }
   1158 
   1159   /// \brief Build a new indirect goto statement.
   1160   ///
   1161   /// By default, performs semantic analysis to build the new statement.
   1162   /// Subclasses may override this routine to provide different behavior.
   1163   StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
   1164                                      SourceLocation StarLoc,
   1165                                      Expr *Target) {
   1166     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
   1167   }
   1168 
   1169   /// \brief Build a new return statement.
   1170   ///
   1171   /// By default, performs semantic analysis to build the new statement.
   1172   /// Subclasses may override this routine to provide different behavior.
   1173   StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
   1174     return getSema().ActOnReturnStmt(ReturnLoc, Result);
   1175   }
   1176 
   1177   /// \brief Build a new declaration statement.
   1178   ///
   1179   /// By default, performs semantic analysis to build the new statement.
   1180   /// Subclasses may override this routine to provide different behavior.
   1181   StmtResult RebuildDeclStmt(llvm::MutableArrayRef<Decl *> Decls,
   1182                              SourceLocation StartLoc, SourceLocation EndLoc) {
   1183     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
   1184     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
   1185   }
   1186 
   1187   /// \brief Build a new inline asm statement.
   1188   ///
   1189   /// By default, performs semantic analysis to build the new statement.
   1190   /// Subclasses may override this routine to provide different behavior.
   1191   StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
   1192                                bool IsVolatile, unsigned NumOutputs,
   1193                                unsigned NumInputs, IdentifierInfo **Names,
   1194                                MultiExprArg Constraints, MultiExprArg Exprs,
   1195                                Expr *AsmString, MultiExprArg Clobbers,
   1196                                SourceLocation RParenLoc) {
   1197     return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
   1198                                      NumInputs, Names, Constraints, Exprs,
   1199                                      AsmString, Clobbers, RParenLoc);
   1200   }
   1201 
   1202   /// \brief Build a new MS style inline asm statement.
   1203   ///
   1204   /// By default, performs semantic analysis to build the new statement.
   1205   /// Subclasses may override this routine to provide different behavior.
   1206   StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
   1207                               ArrayRef<Token> AsmToks,
   1208                               StringRef AsmString,
   1209                               unsigned NumOutputs, unsigned NumInputs,
   1210                               ArrayRef<StringRef> Constraints,
   1211                               ArrayRef<StringRef> Clobbers,
   1212                               ArrayRef<Expr*> Exprs,
   1213                               SourceLocation EndLoc) {
   1214     return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
   1215                                     NumOutputs, NumInputs,
   1216                                     Constraints, Clobbers, Exprs, EndLoc);
   1217   }
   1218 
   1219   /// \brief Build a new Objective-C \@try statement.
   1220   ///
   1221   /// By default, performs semantic analysis to build the new statement.
   1222   /// Subclasses may override this routine to provide different behavior.
   1223   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
   1224                                         Stmt *TryBody,
   1225                                         MultiStmtArg CatchStmts,
   1226                                         Stmt *Finally) {
   1227     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
   1228                                         Finally);
   1229   }
   1230 
   1231   /// \brief Rebuild an Objective-C exception declaration.
   1232   ///
   1233   /// By default, performs semantic analysis to build the new declaration.
   1234   /// Subclasses may override this routine to provide different behavior.
   1235   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
   1236                                     TypeSourceInfo *TInfo, QualType T) {
   1237     return getSema().BuildObjCExceptionDecl(TInfo, T,
   1238                                             ExceptionDecl->getInnerLocStart(),
   1239                                             ExceptionDecl->getLocation(),
   1240                                             ExceptionDecl->getIdentifier());
   1241   }
   1242 
   1243   /// \brief Build a new Objective-C \@catch statement.
   1244   ///
   1245   /// By default, performs semantic analysis to build the new statement.
   1246   /// Subclasses may override this routine to provide different behavior.
   1247   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
   1248                                           SourceLocation RParenLoc,
   1249                                           VarDecl *Var,
   1250                                           Stmt *Body) {
   1251     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
   1252                                           Var, Body);
   1253   }
   1254 
   1255   /// \brief Build a new Objective-C \@finally statement.
   1256   ///
   1257   /// By default, performs semantic analysis to build the new statement.
   1258   /// Subclasses may override this routine to provide different behavior.
   1259   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
   1260                                             Stmt *Body) {
   1261     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
   1262   }
   1263 
   1264   /// \brief Build a new Objective-C \@throw statement.
   1265   ///
   1266   /// By default, performs semantic analysis to build the new statement.
   1267   /// Subclasses may override this routine to provide different behavior.
   1268   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
   1269                                           Expr *Operand) {
   1270     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
   1271   }
   1272 
   1273   /// \brief Build a new OpenMP parallel directive.
   1274   ///
   1275   /// By default, performs semantic analysis to build the new statement.
   1276   /// Subclasses may override this routine to provide different behavior.
   1277   StmtResult RebuildOMPParallelDirective(ArrayRef<OMPClause *> Clauses,
   1278                                          Stmt *AStmt,
   1279                                          SourceLocation StartLoc,
   1280                                          SourceLocation EndLoc) {
   1281     return getSema().ActOnOpenMPParallelDirective(Clauses, AStmt,
   1282                                                   StartLoc, EndLoc);
   1283   }
   1284 
   1285   /// \brief Build a new OpenMP 'default' clause.
   1286   ///
   1287   /// By default, performs semantic analysis to build the new statement.
   1288   /// Subclasses may override this routine to provide different behavior.
   1289   OMPClause *RebuildOMPDefaultClause(OpenMPDefaultClauseKind Kind,
   1290                                      SourceLocation KindKwLoc,
   1291                                      SourceLocation StartLoc,
   1292                                      SourceLocation LParenLoc,
   1293                                      SourceLocation EndLoc) {
   1294     return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
   1295                                               StartLoc, LParenLoc, EndLoc);
   1296   }
   1297 
   1298   /// \brief Build a new OpenMP 'private' clause.
   1299   ///
   1300   /// By default, performs semantic analysis to build the new statement.
   1301   /// Subclasses may override this routine to provide different behavior.
   1302   OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
   1303                                      SourceLocation StartLoc,
   1304                                      SourceLocation LParenLoc,
   1305                                      SourceLocation EndLoc) {
   1306     return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
   1307                                               EndLoc);
   1308   }
   1309 
   1310   /// \brief Rebuild the operand to an Objective-C \@synchronized statement.
   1311   ///
   1312   /// By default, performs semantic analysis to build the new statement.
   1313   /// Subclasses may override this routine to provide different behavior.
   1314   ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
   1315                                               Expr *object) {
   1316     return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
   1317   }
   1318 
   1319   /// \brief Build a new Objective-C \@synchronized statement.
   1320   ///
   1321   /// By default, performs semantic analysis to build the new statement.
   1322   /// Subclasses may override this routine to provide different behavior.
   1323   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
   1324                                            Expr *Object, Stmt *Body) {
   1325     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
   1326   }
   1327 
   1328   /// \brief Build a new Objective-C \@autoreleasepool statement.
   1329   ///
   1330   /// By default, performs semantic analysis to build the new statement.
   1331   /// Subclasses may override this routine to provide different behavior.
   1332   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
   1333                                             Stmt *Body) {
   1334     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
   1335   }
   1336 
   1337   /// \brief Build a new Objective-C fast enumeration statement.
   1338   ///
   1339   /// By default, performs semantic analysis to build the new statement.
   1340   /// Subclasses may override this routine to provide different behavior.
   1341   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
   1342                                           Stmt *Element,
   1343                                           Expr *Collection,
   1344                                           SourceLocation RParenLoc,
   1345                                           Stmt *Body) {
   1346     StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
   1347                                                 Element,
   1348                                                 Collection,
   1349                                                 RParenLoc);
   1350     if (ForEachStmt.isInvalid())
   1351       return StmtError();
   1352 
   1353     return getSema().FinishObjCForCollectionStmt(ForEachStmt.take(), Body);
   1354   }
   1355 
   1356   /// \brief Build a new C++ exception declaration.
   1357   ///
   1358   /// By default, performs semantic analysis to build the new decaration.
   1359   /// Subclasses may override this routine to provide different behavior.
   1360   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
   1361                                 TypeSourceInfo *Declarator,
   1362                                 SourceLocation StartLoc,
   1363                                 SourceLocation IdLoc,
   1364                                 IdentifierInfo *Id) {
   1365     VarDecl *Var = getSema().BuildExceptionDeclaration(0, Declarator,
   1366                                                        StartLoc, IdLoc, Id);
   1367     if (Var)
   1368       getSema().CurContext->addDecl(Var);
   1369     return Var;
   1370   }
   1371 
   1372   /// \brief Build a new C++ catch statement.
   1373   ///
   1374   /// By default, performs semantic analysis to build the new statement.
   1375   /// Subclasses may override this routine to provide different behavior.
   1376   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
   1377                                  VarDecl *ExceptionDecl,
   1378                                  Stmt *Handler) {
   1379     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
   1380                                                       Handler));
   1381   }
   1382 
   1383   /// \brief Build a new C++ try statement.
   1384   ///
   1385   /// By default, performs semantic analysis to build the new statement.
   1386   /// Subclasses may override this routine to provide different behavior.
   1387   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc,
   1388                                Stmt *TryBlock,
   1389                                MultiStmtArg Handlers) {
   1390     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
   1391   }
   1392 
   1393   /// \brief Build a new C++0x range-based for statement.
   1394   ///
   1395   /// By default, performs semantic analysis to build the new statement.
   1396   /// Subclasses may override this routine to provide different behavior.
   1397   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
   1398                                     SourceLocation ColonLoc,
   1399                                     Stmt *Range, Stmt *BeginEnd,
   1400                                     Expr *Cond, Expr *Inc,
   1401                                     Stmt *LoopVar,
   1402                                     SourceLocation RParenLoc) {
   1403     // If we've just learned that the range is actually an Objective-C
   1404     // collection, treat this as an Objective-C fast enumeration loop.
   1405     if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
   1406       if (RangeStmt->isSingleDecl()) {
   1407         if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
   1408           if (RangeVar->isInvalidDecl())
   1409             return StmtError();
   1410 
   1411           Expr *RangeExpr = RangeVar->getInit();
   1412           if (!RangeExpr->isTypeDependent() &&
   1413               RangeExpr->getType()->isObjCObjectPointerType())
   1414             return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar, RangeExpr,
   1415                                                         RParenLoc);
   1416         }
   1417       }
   1418     }
   1419 
   1420     return getSema().BuildCXXForRangeStmt(ForLoc, ColonLoc, Range, BeginEnd,
   1421                                           Cond, Inc, LoopVar, RParenLoc,
   1422                                           Sema::BFRK_Rebuild);
   1423   }
   1424 
   1425   /// \brief Build a new C++0x range-based for statement.
   1426   ///
   1427   /// By default, performs semantic analysis to build the new statement.
   1428   /// Subclasses may override this routine to provide different behavior.
   1429   StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
   1430                                           bool IsIfExists,
   1431                                           NestedNameSpecifierLoc QualifierLoc,
   1432                                           DeclarationNameInfo NameInfo,
   1433                                           Stmt *Nested) {
   1434     return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
   1435                                                 QualifierLoc, NameInfo, Nested);
   1436   }
   1437 
   1438   /// \brief Attach body to a C++0x range-based for statement.
   1439   ///
   1440   /// By default, performs semantic analysis to finish the new statement.
   1441   /// Subclasses may override this routine to provide different behavior.
   1442   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
   1443     return getSema().FinishCXXForRangeStmt(ForRange, Body);
   1444   }
   1445 
   1446   StmtResult RebuildSEHTryStmt(bool IsCXXTry,
   1447                                SourceLocation TryLoc,
   1448                                Stmt *TryBlock,
   1449                                Stmt *Handler) {
   1450     return getSema().ActOnSEHTryBlock(IsCXXTry,TryLoc,TryBlock,Handler);
   1451   }
   1452 
   1453   StmtResult RebuildSEHExceptStmt(SourceLocation Loc,
   1454                                   Expr *FilterExpr,
   1455                                   Stmt *Block) {
   1456     return getSema().ActOnSEHExceptBlock(Loc,FilterExpr,Block);
   1457   }
   1458 
   1459   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc,
   1460                                    Stmt *Block) {
   1461     return getSema().ActOnSEHFinallyBlock(Loc,Block);
   1462   }
   1463 
   1464   /// \brief Build a new expression that references a declaration.
   1465   ///
   1466   /// By default, performs semantic analysis to build the new expression.
   1467   /// Subclasses may override this routine to provide different behavior.
   1468   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
   1469                                         LookupResult &R,
   1470                                         bool RequiresADL) {
   1471     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
   1472   }
   1473 
   1474 
   1475   /// \brief Build a new expression that references a declaration.
   1476   ///
   1477   /// By default, performs semantic analysis to build the new expression.
   1478   /// Subclasses may override this routine to provide different behavior.
   1479   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
   1480                                 ValueDecl *VD,
   1481                                 const DeclarationNameInfo &NameInfo,
   1482                                 TemplateArgumentListInfo *TemplateArgs) {
   1483     CXXScopeSpec SS;
   1484     SS.Adopt(QualifierLoc);
   1485 
   1486     // FIXME: loses template args.
   1487 
   1488     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
   1489   }
   1490 
   1491   /// \brief Build a new expression in parentheses.
   1492   ///
   1493   /// By default, performs semantic analysis to build the new expression.
   1494   /// Subclasses may override this routine to provide different behavior.
   1495   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
   1496                                     SourceLocation RParen) {
   1497     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
   1498   }
   1499 
   1500   /// \brief Build a new pseudo-destructor expression.
   1501   ///
   1502   /// By default, performs semantic analysis to build the new expression.
   1503   /// Subclasses may override this routine to provide different behavior.
   1504   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
   1505                                             SourceLocation OperatorLoc,
   1506                                             bool isArrow,
   1507                                             CXXScopeSpec &SS,
   1508                                             TypeSourceInfo *ScopeType,
   1509                                             SourceLocation CCLoc,
   1510                                             SourceLocation TildeLoc,
   1511                                         PseudoDestructorTypeStorage Destroyed);
   1512 
   1513   /// \brief Build a new unary operator expression.
   1514   ///
   1515   /// By default, performs semantic analysis to build the new expression.
   1516   /// Subclasses may override this routine to provide different behavior.
   1517   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
   1518                                         UnaryOperatorKind Opc,
   1519                                         Expr *SubExpr) {
   1520     return getSema().BuildUnaryOp(/*Scope=*/0, OpLoc, Opc, SubExpr);
   1521   }
   1522 
   1523   /// \brief Build a new builtin offsetof expression.
   1524   ///
   1525   /// By default, performs semantic analysis to build the new expression.
   1526   /// Subclasses may override this routine to provide different behavior.
   1527   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
   1528                                        TypeSourceInfo *Type,
   1529                                        Sema::OffsetOfComponent *Components,
   1530                                        unsigned NumComponents,
   1531                                        SourceLocation RParenLoc) {
   1532     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
   1533                                           NumComponents, RParenLoc);
   1534   }
   1535 
   1536   /// \brief Build a new sizeof, alignof or vec_step expression with a
   1537   /// type argument.
   1538   ///
   1539   /// By default, performs semantic analysis to build the new expression.
   1540   /// Subclasses may override this routine to provide different behavior.
   1541   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
   1542                                          SourceLocation OpLoc,
   1543                                          UnaryExprOrTypeTrait ExprKind,
   1544                                          SourceRange R) {
   1545     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
   1546   }
   1547 
   1548   /// \brief Build a new sizeof, alignof or vec step expression with an
   1549   /// expression argument.
   1550   ///
   1551   /// By default, performs semantic analysis to build the new expression.
   1552   /// Subclasses may override this routine to provide different behavior.
   1553   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
   1554                                          UnaryExprOrTypeTrait ExprKind,
   1555                                          SourceRange R) {
   1556     ExprResult Result
   1557       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
   1558     if (Result.isInvalid())
   1559       return ExprError();
   1560 
   1561     return Result;
   1562   }
   1563 
   1564   /// \brief Build a new array subscript expression.
   1565   ///
   1566   /// By default, performs semantic analysis to build the new expression.
   1567   /// Subclasses may override this routine to provide different behavior.
   1568   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
   1569                                              SourceLocation LBracketLoc,
   1570                                              Expr *RHS,
   1571                                              SourceLocation RBracketLoc) {
   1572     return getSema().ActOnArraySubscriptExpr(/*Scope=*/0, LHS,
   1573                                              LBracketLoc, RHS,
   1574                                              RBracketLoc);
   1575   }
   1576 
   1577   /// \brief Build a new call expression.
   1578   ///
   1579   /// By default, performs semantic analysis to build the new expression.
   1580   /// Subclasses may override this routine to provide different behavior.
   1581   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
   1582                                    MultiExprArg Args,
   1583                                    SourceLocation RParenLoc,
   1584                                    Expr *ExecConfig = 0) {
   1585     return getSema().ActOnCallExpr(/*Scope=*/0, Callee, LParenLoc,
   1586                                    Args, RParenLoc, ExecConfig);
   1587   }
   1588 
   1589   /// \brief Build a new member access expression.
   1590   ///
   1591   /// By default, performs semantic analysis to build the new expression.
   1592   /// Subclasses may override this routine to provide different behavior.
   1593   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
   1594                                bool isArrow,
   1595                                NestedNameSpecifierLoc QualifierLoc,
   1596                                SourceLocation TemplateKWLoc,
   1597                                const DeclarationNameInfo &MemberNameInfo,
   1598                                ValueDecl *Member,
   1599                                NamedDecl *FoundDecl,
   1600                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
   1601                                NamedDecl *FirstQualifierInScope) {
   1602     ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
   1603                                                                       isArrow);
   1604     if (!Member->getDeclName()) {
   1605       // We have a reference to an unnamed field.  This is always the
   1606       // base of an anonymous struct/union member access, i.e. the
   1607       // field is always of record type.
   1608       assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
   1609       assert(Member->getType()->isRecordType() &&
   1610              "unnamed member not of record type?");
   1611 
   1612       BaseResult =
   1613         getSema().PerformObjectMemberConversion(BaseResult.take(),
   1614                                                 QualifierLoc.getNestedNameSpecifier(),
   1615                                                 FoundDecl, Member);
   1616       if (BaseResult.isInvalid())
   1617         return ExprError();
   1618       Base = BaseResult.take();
   1619       ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
   1620       MemberExpr *ME =
   1621         new (getSema().Context) MemberExpr(Base, isArrow,
   1622                                            Member, MemberNameInfo,
   1623                                            cast<FieldDecl>(Member)->getType(),
   1624                                            VK, OK_Ordinary);
   1625       return getSema().Owned(ME);
   1626     }
   1627 
   1628     CXXScopeSpec SS;
   1629     SS.Adopt(QualifierLoc);
   1630 
   1631     Base = BaseResult.take();
   1632     QualType BaseType = Base->getType();
   1633 
   1634     // FIXME: this involves duplicating earlier analysis in a lot of
   1635     // cases; we should avoid this when possible.
   1636     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
   1637     R.addDecl(FoundDecl);
   1638     R.resolveKind();
   1639 
   1640     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
   1641                                               SS, TemplateKWLoc,
   1642                                               FirstQualifierInScope,
   1643                                               R, ExplicitTemplateArgs);
   1644   }
   1645 
   1646   /// \brief Build a new binary operator expression.
   1647   ///
   1648   /// By default, performs semantic analysis to build the new expression.
   1649   /// Subclasses may override this routine to provide different behavior.
   1650   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
   1651                                          BinaryOperatorKind Opc,
   1652                                          Expr *LHS, Expr *RHS) {
   1653     return getSema().BuildBinOp(/*Scope=*/0, OpLoc, Opc, LHS, RHS);
   1654   }
   1655 
   1656   /// \brief Build a new conditional operator expression.
   1657   ///
   1658   /// By default, performs semantic analysis to build the new expression.
   1659   /// Subclasses may override this routine to provide different behavior.
   1660   ExprResult RebuildConditionalOperator(Expr *Cond,
   1661                                         SourceLocation QuestionLoc,
   1662                                         Expr *LHS,
   1663                                         SourceLocation ColonLoc,
   1664                                         Expr *RHS) {
   1665     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
   1666                                         LHS, RHS);
   1667   }
   1668 
   1669   /// \brief Build a new C-style cast expression.
   1670   ///
   1671   /// By default, performs semantic analysis to build the new expression.
   1672   /// Subclasses may override this routine to provide different behavior.
   1673   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
   1674                                          TypeSourceInfo *TInfo,
   1675                                          SourceLocation RParenLoc,
   1676                                          Expr *SubExpr) {
   1677     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
   1678                                          SubExpr);
   1679   }
   1680 
   1681   /// \brief Build a new compound literal expression.
   1682   ///
   1683   /// By default, performs semantic analysis to build the new expression.
   1684   /// Subclasses may override this routine to provide different behavior.
   1685   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
   1686                                               TypeSourceInfo *TInfo,
   1687                                               SourceLocation RParenLoc,
   1688                                               Expr *Init) {
   1689     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
   1690                                               Init);
   1691   }
   1692 
   1693   /// \brief Build a new extended vector element access expression.
   1694   ///
   1695   /// By default, performs semantic analysis to build the new expression.
   1696   /// Subclasses may override this routine to provide different behavior.
   1697   ExprResult RebuildExtVectorElementExpr(Expr *Base,
   1698                                                SourceLocation OpLoc,
   1699                                                SourceLocation AccessorLoc,
   1700                                                IdentifierInfo &Accessor) {
   1701 
   1702     CXXScopeSpec SS;
   1703     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
   1704     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
   1705                                               OpLoc, /*IsArrow*/ false,
   1706                                               SS, SourceLocation(),
   1707                                               /*FirstQualifierInScope*/ 0,
   1708                                               NameInfo,
   1709                                               /* TemplateArgs */ 0);
   1710   }
   1711 
   1712   /// \brief Build a new initializer list expression.
   1713   ///
   1714   /// By default, performs semantic analysis to build the new expression.
   1715   /// Subclasses may override this routine to provide different behavior.
   1716   ExprResult RebuildInitList(SourceLocation LBraceLoc,
   1717                              MultiExprArg Inits,
   1718                              SourceLocation RBraceLoc,
   1719                              QualType ResultTy) {
   1720     ExprResult Result
   1721       = SemaRef.ActOnInitList(LBraceLoc, Inits, RBraceLoc);
   1722     if (Result.isInvalid() || ResultTy->isDependentType())
   1723       return Result;
   1724 
   1725     // Patch in the result type we were given, which may have been computed
   1726     // when the initial InitListExpr was built.
   1727     InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
   1728     ILE->setType(ResultTy);
   1729     return Result;
   1730   }
   1731 
   1732   /// \brief Build a new designated initializer expression.
   1733   ///
   1734   /// By default, performs semantic analysis to build the new expression.
   1735   /// Subclasses may override this routine to provide different behavior.
   1736   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
   1737                                              MultiExprArg ArrayExprs,
   1738                                              SourceLocation EqualOrColonLoc,
   1739                                              bool GNUSyntax,
   1740                                              Expr *Init) {
   1741     ExprResult Result
   1742       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
   1743                                            Init);
   1744     if (Result.isInvalid())
   1745       return ExprError();
   1746 
   1747     return Result;
   1748   }
   1749 
   1750   /// \brief Build a new value-initialized expression.
   1751   ///
   1752   /// By default, builds the implicit value initialization without performing
   1753   /// any semantic analysis. Subclasses may override this routine to provide
   1754   /// different behavior.
   1755   ExprResult RebuildImplicitValueInitExpr(QualType T) {
   1756     return SemaRef.Owned(new (SemaRef.Context) ImplicitValueInitExpr(T));
   1757   }
   1758 
   1759   /// \brief Build a new \c va_arg expression.
   1760   ///
   1761   /// By default, performs semantic analysis to build the new expression.
   1762   /// Subclasses may override this routine to provide different behavior.
   1763   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
   1764                                     Expr *SubExpr, TypeSourceInfo *TInfo,
   1765                                     SourceLocation RParenLoc) {
   1766     return getSema().BuildVAArgExpr(BuiltinLoc,
   1767                                     SubExpr, TInfo,
   1768                                     RParenLoc);
   1769   }
   1770 
   1771   /// \brief Build a new expression list in parentheses.
   1772   ///
   1773   /// By default, performs semantic analysis to build the new expression.
   1774   /// Subclasses may override this routine to provide different behavior.
   1775   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
   1776                                   MultiExprArg SubExprs,
   1777                                   SourceLocation RParenLoc) {
   1778     return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
   1779   }
   1780 
   1781   /// \brief Build a new address-of-label expression.
   1782   ///
   1783   /// By default, performs semantic analysis, using the name of the label
   1784   /// rather than attempting to map the label statement itself.
   1785   /// Subclasses may override this routine to provide different behavior.
   1786   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
   1787                                   SourceLocation LabelLoc, LabelDecl *Label) {
   1788     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
   1789   }
   1790 
   1791   /// \brief Build a new GNU statement expression.
   1792   ///
   1793   /// By default, performs semantic analysis to build the new expression.
   1794   /// Subclasses may override this routine to provide different behavior.
   1795   ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
   1796                                    Stmt *SubStmt,
   1797                                    SourceLocation RParenLoc) {
   1798     return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
   1799   }
   1800 
   1801   /// \brief Build a new __builtin_choose_expr expression.
   1802   ///
   1803   /// By default, performs semantic analysis to build the new expression.
   1804   /// Subclasses may override this routine to provide different behavior.
   1805   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
   1806                                      Expr *Cond, Expr *LHS, Expr *RHS,
   1807                                      SourceLocation RParenLoc) {
   1808     return SemaRef.ActOnChooseExpr(BuiltinLoc,
   1809                                    Cond, LHS, RHS,
   1810                                    RParenLoc);
   1811   }
   1812 
   1813   /// \brief Build a new generic selection expression.
   1814   ///
   1815   /// By default, performs semantic analysis to build the new expression.
   1816   /// Subclasses may override this routine to provide different behavior.
   1817   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
   1818                                          SourceLocation DefaultLoc,
   1819                                          SourceLocation RParenLoc,
   1820                                          Expr *ControllingExpr,
   1821                                          ArrayRef<TypeSourceInfo *> Types,
   1822                                          ArrayRef<Expr *> Exprs) {
   1823     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
   1824                                                 ControllingExpr, Types, Exprs);
   1825   }
   1826 
   1827   /// \brief Build a new overloaded operator call expression.
   1828   ///
   1829   /// By default, performs semantic analysis to build the new expression.
   1830   /// The semantic analysis provides the behavior of template instantiation,
   1831   /// copying with transformations that turn what looks like an overloaded
   1832   /// operator call into a use of a builtin operator, performing
   1833   /// argument-dependent lookup, etc. Subclasses may override this routine to
   1834   /// provide different behavior.
   1835   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
   1836                                               SourceLocation OpLoc,
   1837                                               Expr *Callee,
   1838                                               Expr *First,
   1839                                               Expr *Second);
   1840 
   1841   /// \brief Build a new C++ "named" cast expression, such as static_cast or
   1842   /// reinterpret_cast.
   1843   ///
   1844   /// By default, this routine dispatches to one of the more-specific routines
   1845   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
   1846   /// Subclasses may override this routine to provide different behavior.
   1847   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
   1848                                            Stmt::StmtClass Class,
   1849                                            SourceLocation LAngleLoc,
   1850                                            TypeSourceInfo *TInfo,
   1851                                            SourceLocation RAngleLoc,
   1852                                            SourceLocation LParenLoc,
   1853                                            Expr *SubExpr,
   1854                                            SourceLocation RParenLoc) {
   1855     switch (Class) {
   1856     case Stmt::CXXStaticCastExprClass:
   1857       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
   1858                                                    RAngleLoc, LParenLoc,
   1859                                                    SubExpr, RParenLoc);
   1860 
   1861     case Stmt::CXXDynamicCastExprClass:
   1862       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
   1863                                                     RAngleLoc, LParenLoc,
   1864                                                     SubExpr, RParenLoc);
   1865 
   1866     case Stmt::CXXReinterpretCastExprClass:
   1867       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
   1868                                                         RAngleLoc, LParenLoc,
   1869                                                         SubExpr,
   1870                                                         RParenLoc);
   1871 
   1872     case Stmt::CXXConstCastExprClass:
   1873       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
   1874                                                    RAngleLoc, LParenLoc,
   1875                                                    SubExpr, RParenLoc);
   1876 
   1877     default:
   1878       llvm_unreachable("Invalid C++ named cast");
   1879     }
   1880   }
   1881 
   1882   /// \brief Build a new C++ static_cast expression.
   1883   ///
   1884   /// By default, performs semantic analysis to build the new expression.
   1885   /// Subclasses may override this routine to provide different behavior.
   1886   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
   1887                                             SourceLocation LAngleLoc,
   1888                                             TypeSourceInfo *TInfo,
   1889                                             SourceLocation RAngleLoc,
   1890                                             SourceLocation LParenLoc,
   1891                                             Expr *SubExpr,
   1892                                             SourceLocation RParenLoc) {
   1893     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
   1894                                        TInfo, SubExpr,
   1895                                        SourceRange(LAngleLoc, RAngleLoc),
   1896                                        SourceRange(LParenLoc, RParenLoc));
   1897   }
   1898 
   1899   /// \brief Build a new C++ dynamic_cast expression.
   1900   ///
   1901   /// By default, performs semantic analysis to build the new expression.
   1902   /// Subclasses may override this routine to provide different behavior.
   1903   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
   1904                                              SourceLocation LAngleLoc,
   1905                                              TypeSourceInfo *TInfo,
   1906                                              SourceLocation RAngleLoc,
   1907                                              SourceLocation LParenLoc,
   1908                                              Expr *SubExpr,
   1909                                              SourceLocation RParenLoc) {
   1910     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
   1911                                        TInfo, SubExpr,
   1912                                        SourceRange(LAngleLoc, RAngleLoc),
   1913                                        SourceRange(LParenLoc, RParenLoc));
   1914   }
   1915 
   1916   /// \brief Build a new C++ reinterpret_cast expression.
   1917   ///
   1918   /// By default, performs semantic analysis to build the new expression.
   1919   /// Subclasses may override this routine to provide different behavior.
   1920   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
   1921                                                  SourceLocation LAngleLoc,
   1922                                                  TypeSourceInfo *TInfo,
   1923                                                  SourceLocation RAngleLoc,
   1924                                                  SourceLocation LParenLoc,
   1925                                                  Expr *SubExpr,
   1926                                                  SourceLocation RParenLoc) {
   1927     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
   1928                                        TInfo, SubExpr,
   1929                                        SourceRange(LAngleLoc, RAngleLoc),
   1930                                        SourceRange(LParenLoc, RParenLoc));
   1931   }
   1932 
   1933   /// \brief Build a new C++ const_cast expression.
   1934   ///
   1935   /// By default, performs semantic analysis to build the new expression.
   1936   /// Subclasses may override this routine to provide different behavior.
   1937   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
   1938                                            SourceLocation LAngleLoc,
   1939                                            TypeSourceInfo *TInfo,
   1940                                            SourceLocation RAngleLoc,
   1941                                            SourceLocation LParenLoc,
   1942                                            Expr *SubExpr,
   1943                                            SourceLocation RParenLoc) {
   1944     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
   1945                                        TInfo, SubExpr,
   1946                                        SourceRange(LAngleLoc, RAngleLoc),
   1947                                        SourceRange(LParenLoc, RParenLoc));
   1948   }
   1949 
   1950   /// \brief Build a new C++ functional-style cast expression.
   1951   ///
   1952   /// By default, performs semantic analysis to build the new expression.
   1953   /// Subclasses may override this routine to provide different behavior.
   1954   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
   1955                                           SourceLocation LParenLoc,
   1956                                           Expr *Sub,
   1957                                           SourceLocation RParenLoc) {
   1958     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
   1959                                                MultiExprArg(&Sub, 1),
   1960                                                RParenLoc);
   1961   }
   1962 
   1963   /// \brief Build a new C++ typeid(type) expression.
   1964   ///
   1965   /// By default, performs semantic analysis to build the new expression.
   1966   /// Subclasses may override this routine to provide different behavior.
   1967   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
   1968                                         SourceLocation TypeidLoc,
   1969                                         TypeSourceInfo *Operand,
   1970                                         SourceLocation RParenLoc) {
   1971     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
   1972                                     RParenLoc);
   1973   }
   1974 
   1975 
   1976   /// \brief Build a new C++ typeid(expr) expression.
   1977   ///
   1978   /// By default, performs semantic analysis to build the new expression.
   1979   /// Subclasses may override this routine to provide different behavior.
   1980   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
   1981                                         SourceLocation TypeidLoc,
   1982                                         Expr *Operand,
   1983                                         SourceLocation RParenLoc) {
   1984     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
   1985                                     RParenLoc);
   1986   }
   1987 
   1988   /// \brief Build a new C++ __uuidof(type) expression.
   1989   ///
   1990   /// By default, performs semantic analysis to build the new expression.
   1991   /// Subclasses may override this routine to provide different behavior.
   1992   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
   1993                                         SourceLocation TypeidLoc,
   1994                                         TypeSourceInfo *Operand,
   1995                                         SourceLocation RParenLoc) {
   1996     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
   1997                                     RParenLoc);
   1998   }
   1999 
   2000   /// \brief Build a new C++ __uuidof(expr) expression.
   2001   ///
   2002   /// By default, performs semantic analysis to build the new expression.
   2003   /// Subclasses may override this routine to provide different behavior.
   2004   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
   2005                                         SourceLocation TypeidLoc,
   2006                                         Expr *Operand,
   2007                                         SourceLocation RParenLoc) {
   2008     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
   2009                                     RParenLoc);
   2010   }
   2011 
   2012   /// \brief Build a new C++ "this" expression.
   2013   ///
   2014   /// By default, builds a new "this" expression without performing any
   2015   /// semantic analysis. Subclasses may override this routine to provide
   2016   /// different behavior.
   2017   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
   2018                                 QualType ThisType,
   2019                                 bool isImplicit) {
   2020     getSema().CheckCXXThisCapture(ThisLoc);
   2021     return getSema().Owned(
   2022                       new (getSema().Context) CXXThisExpr(ThisLoc, ThisType,
   2023                                                           isImplicit));
   2024   }
   2025 
   2026   /// \brief Build a new C++ throw expression.
   2027   ///
   2028   /// By default, performs semantic analysis to build the new expression.
   2029   /// Subclasses may override this routine to provide different behavior.
   2030   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
   2031                                  bool IsThrownVariableInScope) {
   2032     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
   2033   }
   2034 
   2035   /// \brief Build a new C++ default-argument expression.
   2036   ///
   2037   /// By default, builds a new default-argument expression, which does not
   2038   /// require any semantic analysis. Subclasses may override this routine to
   2039   /// provide different behavior.
   2040   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
   2041                                             ParmVarDecl *Param) {
   2042     return getSema().Owned(CXXDefaultArgExpr::Create(getSema().Context, Loc,
   2043                                                      Param));
   2044   }
   2045 
   2046   /// \brief Build a new C++11 default-initialization expression.
   2047   ///
   2048   /// By default, builds a new default field initialization expression, which
   2049   /// does not require any semantic analysis. Subclasses may override this
   2050   /// routine to provide different behavior.
   2051   ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
   2052                                        FieldDecl *Field) {
   2053     return getSema().Owned(CXXDefaultInitExpr::Create(getSema().Context, Loc,
   2054                                                       Field));
   2055   }
   2056 
   2057   /// \brief Build a new C++ zero-initialization expression.
   2058   ///
   2059   /// By default, performs semantic analysis to build the new expression.
   2060   /// Subclasses may override this routine to provide different behavior.
   2061   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
   2062                                            SourceLocation LParenLoc,
   2063                                            SourceLocation RParenLoc) {
   2064     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
   2065                                                None, RParenLoc);
   2066   }
   2067 
   2068   /// \brief Build a new C++ "new" expression.
   2069   ///
   2070   /// By default, performs semantic analysis to build the new expression.
   2071   /// Subclasses may override this routine to provide different behavior.
   2072   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
   2073                                bool UseGlobal,
   2074                                SourceLocation PlacementLParen,
   2075                                MultiExprArg PlacementArgs,
   2076                                SourceLocation PlacementRParen,
   2077                                SourceRange TypeIdParens,
   2078                                QualType AllocatedType,
   2079                                TypeSourceInfo *AllocatedTypeInfo,
   2080                                Expr *ArraySize,
   2081                                SourceRange DirectInitRange,
   2082                                Expr *Initializer) {
   2083     return getSema().BuildCXXNew(StartLoc, UseGlobal,
   2084                                  PlacementLParen,
   2085                                  PlacementArgs,
   2086                                  PlacementRParen,
   2087                                  TypeIdParens,
   2088                                  AllocatedType,
   2089                                  AllocatedTypeInfo,
   2090                                  ArraySize,
   2091                                  DirectInitRange,
   2092                                  Initializer);
   2093   }
   2094 
   2095   /// \brief Build a new C++ "delete" expression.
   2096   ///
   2097   /// By default, performs semantic analysis to build the new expression.
   2098   /// Subclasses may override this routine to provide different behavior.
   2099   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
   2100                                         bool IsGlobalDelete,
   2101                                         bool IsArrayForm,
   2102                                         Expr *Operand) {
   2103     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
   2104                                     Operand);
   2105   }
   2106 
   2107   /// \brief Build a new unary type trait expression.
   2108   ///
   2109   /// By default, performs semantic analysis to build the new expression.
   2110   /// Subclasses may override this routine to provide different behavior.
   2111   ExprResult RebuildUnaryTypeTrait(UnaryTypeTrait Trait,
   2112                                    SourceLocation StartLoc,
   2113                                    TypeSourceInfo *T,
   2114                                    SourceLocation RParenLoc) {
   2115     return getSema().BuildUnaryTypeTrait(Trait, StartLoc, T, RParenLoc);
   2116   }
   2117 
   2118   /// \brief Build a new binary type trait expression.
   2119   ///
   2120   /// By default, performs semantic analysis to build the new expression.
   2121   /// Subclasses may override this routine to provide different behavior.
   2122   ExprResult RebuildBinaryTypeTrait(BinaryTypeTrait Trait,
   2123                                     SourceLocation StartLoc,
   2124                                     TypeSourceInfo *LhsT,
   2125                                     TypeSourceInfo *RhsT,
   2126                                     SourceLocation RParenLoc) {
   2127     return getSema().BuildBinaryTypeTrait(Trait, StartLoc, LhsT, RhsT, RParenLoc);
   2128   }
   2129 
   2130   /// \brief Build a new type trait expression.
   2131   ///
   2132   /// By default, performs semantic analysis to build the new expression.
   2133   /// Subclasses may override this routine to provide different behavior.
   2134   ExprResult RebuildTypeTrait(TypeTrait Trait,
   2135                               SourceLocation StartLoc,
   2136                               ArrayRef<TypeSourceInfo *> Args,
   2137                               SourceLocation RParenLoc) {
   2138     return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
   2139   }
   2140 
   2141   /// \brief Build a new array type trait expression.
   2142   ///
   2143   /// By default, performs semantic analysis to build the new expression.
   2144   /// Subclasses may override this routine to provide different behavior.
   2145   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
   2146                                    SourceLocation StartLoc,
   2147                                    TypeSourceInfo *TSInfo,
   2148                                    Expr *DimExpr,
   2149                                    SourceLocation RParenLoc) {
   2150     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
   2151   }
   2152 
   2153   /// \brief Build a new expression trait expression.
   2154   ///
   2155   /// By default, performs semantic analysis to build the new expression.
   2156   /// Subclasses may override this routine to provide different behavior.
   2157   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
   2158                                    SourceLocation StartLoc,
   2159                                    Expr *Queried,
   2160                                    SourceLocation RParenLoc) {
   2161     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
   2162   }
   2163 
   2164   /// \brief Build a new (previously unresolved) declaration reference
   2165   /// expression.
   2166   ///
   2167   /// By default, performs semantic analysis to build the new expression.
   2168   /// Subclasses may override this routine to provide different behavior.
   2169   ExprResult RebuildDependentScopeDeclRefExpr(
   2170                                           NestedNameSpecifierLoc QualifierLoc,
   2171                                           SourceLocation TemplateKWLoc,
   2172                                        const DeclarationNameInfo &NameInfo,
   2173                               const TemplateArgumentListInfo *TemplateArgs,
   2174                                           bool IsAddressOfOperand) {
   2175     CXXScopeSpec SS;
   2176     SS.Adopt(QualifierLoc);
   2177 
   2178     if (TemplateArgs || TemplateKWLoc.isValid())
   2179       return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc,
   2180                                                     NameInfo, TemplateArgs);
   2181 
   2182     return getSema().BuildQualifiedDeclarationNameExpr(SS, NameInfo,
   2183                                                        IsAddressOfOperand);
   2184   }
   2185 
   2186   /// \brief Build a new template-id expression.
   2187   ///
   2188   /// By default, performs semantic analysis to build the new expression.
   2189   /// Subclasses may override this routine to provide different behavior.
   2190   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
   2191                                    SourceLocation TemplateKWLoc,
   2192                                    LookupResult &R,
   2193                                    bool RequiresADL,
   2194                               const TemplateArgumentListInfo *TemplateArgs) {
   2195     return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
   2196                                          TemplateArgs);
   2197   }
   2198 
   2199   /// \brief Build a new object-construction expression.
   2200   ///
   2201   /// By default, performs semantic analysis to build the new expression.
   2202   /// Subclasses may override this routine to provide different behavior.
   2203   ExprResult RebuildCXXConstructExpr(QualType T,
   2204                                      SourceLocation Loc,
   2205                                      CXXConstructorDecl *Constructor,
   2206                                      bool IsElidable,
   2207                                      MultiExprArg Args,
   2208                                      bool HadMultipleCandidates,
   2209                                      bool ListInitialization,
   2210                                      bool RequiresZeroInit,
   2211                              CXXConstructExpr::ConstructionKind ConstructKind,
   2212                                      SourceRange ParenRange) {
   2213     SmallVector<Expr*, 8> ConvertedArgs;
   2214     if (getSema().CompleteConstructorCall(Constructor, Args, Loc,
   2215                                           ConvertedArgs))
   2216       return ExprError();
   2217 
   2218     return getSema().BuildCXXConstructExpr(Loc, T, Constructor, IsElidable,
   2219                                            ConvertedArgs,
   2220                                            HadMultipleCandidates,
   2221                                            ListInitialization,
   2222                                            RequiresZeroInit, ConstructKind,
   2223                                            ParenRange);
   2224   }
   2225 
   2226   /// \brief Build a new object-construction expression.
   2227   ///
   2228   /// By default, performs semantic analysis to build the new expression.
   2229   /// Subclasses may override this routine to provide different behavior.
   2230   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
   2231                                            SourceLocation LParenLoc,
   2232                                            MultiExprArg Args,
   2233                                            SourceLocation RParenLoc) {
   2234     return getSema().BuildCXXTypeConstructExpr(TSInfo,
   2235                                                LParenLoc,
   2236                                                Args,
   2237                                                RParenLoc);
   2238   }
   2239 
   2240   /// \brief Build a new object-construction expression.
   2241   ///
   2242   /// By default, performs semantic analysis to build the new expression.
   2243   /// Subclasses may override this routine to provide different behavior.
   2244   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
   2245                                                SourceLocation LParenLoc,
   2246                                                MultiExprArg Args,
   2247                                                SourceLocation RParenLoc) {
   2248     return getSema().BuildCXXTypeConstructExpr(TSInfo,
   2249                                                LParenLoc,
   2250                                                Args,
   2251                                                RParenLoc);
   2252   }
   2253 
   2254   /// \brief Build a new member reference expression.
   2255   ///
   2256   /// By default, performs semantic analysis to build the new expression.
   2257   /// Subclasses may override this routine to provide different behavior.
   2258   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
   2259                                                 QualType BaseType,
   2260                                                 bool IsArrow,
   2261                                                 SourceLocation OperatorLoc,
   2262                                           NestedNameSpecifierLoc QualifierLoc,
   2263                                                 SourceLocation TemplateKWLoc,
   2264                                             NamedDecl *FirstQualifierInScope,
   2265                                    const DeclarationNameInfo &MemberNameInfo,
   2266                               const TemplateArgumentListInfo *TemplateArgs) {
   2267     CXXScopeSpec SS;
   2268     SS.Adopt(QualifierLoc);
   2269 
   2270     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
   2271                                             OperatorLoc, IsArrow,
   2272                                             SS, TemplateKWLoc,
   2273                                             FirstQualifierInScope,
   2274                                             MemberNameInfo,
   2275                                             TemplateArgs);
   2276   }
   2277 
   2278   /// \brief Build a new member reference expression.
   2279   ///
   2280   /// By default, performs semantic analysis to build the new expression.
   2281   /// Subclasses may override this routine to provide different behavior.
   2282   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
   2283                                          SourceLocation OperatorLoc,
   2284                                          bool IsArrow,
   2285                                          NestedNameSpecifierLoc QualifierLoc,
   2286                                          SourceLocation TemplateKWLoc,
   2287                                          NamedDecl *FirstQualifierInScope,
   2288                                          LookupResult &R,
   2289                                 const TemplateArgumentListInfo *TemplateArgs) {
   2290     CXXScopeSpec SS;
   2291     SS.Adopt(QualifierLoc);
   2292 
   2293     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
   2294                                             OperatorLoc, IsArrow,
   2295                                             SS, TemplateKWLoc,
   2296                                             FirstQualifierInScope,
   2297                                             R, TemplateArgs);
   2298   }
   2299 
   2300   /// \brief Build a new noexcept expression.
   2301   ///
   2302   /// By default, performs semantic analysis to build the new expression.
   2303   /// Subclasses may override this routine to provide different behavior.
   2304   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
   2305     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
   2306   }
   2307 
   2308   /// \brief Build a new expression to compute the length of a parameter pack.
   2309   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
   2310                                    SourceLocation PackLoc,
   2311                                    SourceLocation RParenLoc,
   2312                                    Optional<unsigned> Length) {
   2313     if (Length)
   2314       return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
   2315                                                   OperatorLoc, Pack, PackLoc,
   2316                                                   RParenLoc, *Length);
   2317 
   2318     return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
   2319                                                 OperatorLoc, Pack, PackLoc,
   2320                                                 RParenLoc);
   2321   }
   2322 
   2323   /// \brief Build a new Objective-C boxed expression.
   2324   ///
   2325   /// By default, performs semantic analysis to build the new expression.
   2326   /// Subclasses may override this routine to provide different behavior.
   2327   ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
   2328     return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
   2329   }
   2330 
   2331   /// \brief Build a new Objective-C array literal.
   2332   ///
   2333   /// By default, performs semantic analysis to build the new expression.
   2334   /// Subclasses may override this routine to provide different behavior.
   2335   ExprResult RebuildObjCArrayLiteral(SourceRange Range,
   2336                                      Expr **Elements, unsigned NumElements) {
   2337     return getSema().BuildObjCArrayLiteral(Range,
   2338                                            MultiExprArg(Elements, NumElements));
   2339   }
   2340 
   2341   ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
   2342                                          Expr *Base, Expr *Key,
   2343                                          ObjCMethodDecl *getterMethod,
   2344                                          ObjCMethodDecl *setterMethod) {
   2345     return  getSema().BuildObjCSubscriptExpression(RB, Base, Key,
   2346                                                    getterMethod, setterMethod);
   2347   }
   2348 
   2349   /// \brief Build a new Objective-C dictionary literal.
   2350   ///
   2351   /// By default, performs semantic analysis to build the new expression.
   2352   /// Subclasses may override this routine to provide different behavior.
   2353   ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
   2354                                           ObjCDictionaryElement *Elements,
   2355                                           unsigned NumElements) {
   2356     return getSema().BuildObjCDictionaryLiteral(Range, Elements, NumElements);
   2357   }
   2358 
   2359   /// \brief Build a new Objective-C \@encode expression.
   2360   ///
   2361   /// By default, performs semantic analysis to build the new expression.
   2362   /// Subclasses may override this routine to provide different behavior.
   2363   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
   2364                                          TypeSourceInfo *EncodeTypeInfo,
   2365                                          SourceLocation RParenLoc) {
   2366     return SemaRef.Owned(SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo,
   2367                                                            RParenLoc));
   2368   }
   2369 
   2370   /// \brief Build a new Objective-C class message.
   2371   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
   2372                                           Selector Sel,
   2373                                           ArrayRef<SourceLocation> SelectorLocs,
   2374                                           ObjCMethodDecl *Method,
   2375                                           SourceLocation LBracLoc,
   2376                                           MultiExprArg Args,
   2377                                           SourceLocation RBracLoc) {
   2378     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
   2379                                      ReceiverTypeInfo->getType(),
   2380                                      /*SuperLoc=*/SourceLocation(),
   2381                                      Sel, Method, LBracLoc, SelectorLocs,
   2382                                      RBracLoc, Args);
   2383   }
   2384 
   2385   /// \brief Build a new Objective-C instance message.
   2386   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
   2387                                           Selector Sel,
   2388                                           ArrayRef<SourceLocation> SelectorLocs,
   2389                                           ObjCMethodDecl *Method,
   2390                                           SourceLocation LBracLoc,
   2391                                           MultiExprArg Args,
   2392                                           SourceLocation RBracLoc) {
   2393     return SemaRef.BuildInstanceMessage(Receiver,
   2394                                         Receiver->getType(),
   2395                                         /*SuperLoc=*/SourceLocation(),
   2396                                         Sel, Method, LBracLoc, SelectorLocs,
   2397                                         RBracLoc, Args);
   2398   }
   2399 
   2400   /// \brief Build a new Objective-C ivar reference expression.
   2401   ///
   2402   /// By default, performs semantic analysis to build the new expression.
   2403   /// Subclasses may override this routine to provide different behavior.
   2404   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
   2405                                           SourceLocation IvarLoc,
   2406                                           bool IsArrow, bool IsFreeIvar) {
   2407     // FIXME: We lose track of the IsFreeIvar bit.
   2408     CXXScopeSpec SS;
   2409     ExprResult Base = getSema().Owned(BaseArg);
   2410     LookupResult R(getSema(), Ivar->getDeclName(), IvarLoc,
   2411                    Sema::LookupMemberName);
   2412     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
   2413                                                          /*FIME:*/IvarLoc,
   2414                                                          SS, 0,
   2415                                                          false);
   2416     if (Result.isInvalid() || Base.isInvalid())
   2417       return ExprError();
   2418 
   2419     if (Result.get())
   2420       return Result;
   2421 
   2422     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
   2423                                               /*FIXME:*/IvarLoc, IsArrow,
   2424                                               SS, SourceLocation(),
   2425                                               /*FirstQualifierInScope=*/0,
   2426                                               R,
   2427                                               /*TemplateArgs=*/0);
   2428   }
   2429 
   2430   /// \brief Build a new Objective-C property reference expression.
   2431   ///
   2432   /// By default, performs semantic analysis to build the new expression.
   2433   /// Subclasses may override this routine to provide different behavior.
   2434   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
   2435                                         ObjCPropertyDecl *Property,
   2436                                         SourceLocation PropertyLoc) {
   2437     CXXScopeSpec SS;
   2438     ExprResult Base = getSema().Owned(BaseArg);
   2439     LookupResult R(getSema(), Property->getDeclName(), PropertyLoc,
   2440                    Sema::LookupMemberName);
   2441     bool IsArrow = false;
   2442     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
   2443                                                          /*FIME:*/PropertyLoc,
   2444                                                          SS, 0, false);
   2445     if (Result.isInvalid() || Base.isInvalid())
   2446       return ExprError();
   2447 
   2448     if (Result.get())
   2449       return Result;
   2450 
   2451     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
   2452                                               /*FIXME:*/PropertyLoc, IsArrow,
   2453                                               SS, SourceLocation(),
   2454                                               /*FirstQualifierInScope=*/0,
   2455                                               R,
   2456                                               /*TemplateArgs=*/0);
   2457   }
   2458 
   2459   /// \brief Build a new Objective-C property reference expression.
   2460   ///
   2461   /// By default, performs semantic analysis to build the new expression.
   2462   /// Subclasses may override this routine to provide different behavior.
   2463   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
   2464                                         ObjCMethodDecl *Getter,
   2465                                         ObjCMethodDecl *Setter,
   2466                                         SourceLocation PropertyLoc) {
   2467     // Since these expressions can only be value-dependent, we do not
   2468     // need to perform semantic analysis again.
   2469     return Owned(
   2470       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
   2471                                                   VK_LValue, OK_ObjCProperty,
   2472                                                   PropertyLoc, Base));
   2473   }
   2474 
   2475   /// \brief Build a new Objective-C "isa" expression.
   2476   ///
   2477   /// By default, performs semantic analysis to build the new expression.
   2478   /// Subclasses may override this routine to provide different behavior.
   2479   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
   2480                                 SourceLocation OpLoc,
   2481                                       bool IsArrow) {
   2482     CXXScopeSpec SS;
   2483     ExprResult Base = getSema().Owned(BaseArg);
   2484     LookupResult R(getSema(), &getSema().Context.Idents.get("isa"), IsaLoc,
   2485                    Sema::LookupMemberName);
   2486     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
   2487                                                          OpLoc,
   2488                                                          SS, 0, false);
   2489     if (Result.isInvalid() || Base.isInvalid())
   2490       return ExprError();
   2491 
   2492     if (Result.get())
   2493       return Result;
   2494 
   2495     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
   2496                                               OpLoc, IsArrow,
   2497                                               SS, SourceLocation(),
   2498                                               /*FirstQualifierInScope=*/0,
   2499                                               R,
   2500                                               /*TemplateArgs=*/0);
   2501   }
   2502 
   2503   /// \brief Build a new shuffle vector expression.
   2504   ///
   2505   /// By default, performs semantic analysis to build the new expression.
   2506   /// Subclasses may override this routine to provide different behavior.
   2507   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
   2508                                       MultiExprArg SubExprs,
   2509                                       SourceLocation RParenLoc) {
   2510     // Find the declaration for __builtin_shufflevector
   2511     const IdentifierInfo &Name
   2512       = SemaRef.Context.Idents.get("__builtin_shufflevector");
   2513     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
   2514     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
   2515     assert(!Lookup.empty() && "No __builtin_shufflevector?");
   2516 
   2517     // Build a reference to the __builtin_shufflevector builtin
   2518     FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
   2519     Expr *Callee = new (SemaRef.Context) DeclRefExpr(Builtin, false,
   2520                                                   SemaRef.Context.BuiltinFnTy,
   2521                                                   VK_RValue, BuiltinLoc);
   2522     QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
   2523     Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
   2524                                        CK_BuiltinFnToFnPtr).take();
   2525 
   2526     // Build the CallExpr
   2527     ExprResult TheCall = SemaRef.Owned(
   2528       new (SemaRef.Context) CallExpr(SemaRef.Context, Callee, SubExprs,
   2529                                      Builtin->getCallResultType(),
   2530                             Expr::getValueKindForType(Builtin->getResultType()),
   2531                                      RParenLoc));
   2532 
   2533     // Type-check the __builtin_shufflevector expression.
   2534     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.take()));
   2535   }
   2536 
   2537   /// \brief Build a new template argument pack expansion.
   2538   ///
   2539   /// By default, performs semantic analysis to build a new pack expansion
   2540   /// for a template argument. Subclasses may override this routine to provide
   2541   /// different behavior.
   2542   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
   2543                                            SourceLocation EllipsisLoc,
   2544                                            Optional<unsigned> NumExpansions) {
   2545     switch (Pattern.getArgument().getKind()) {
   2546     case TemplateArgument::Expression: {
   2547       ExprResult Result
   2548         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
   2549                                        EllipsisLoc, NumExpansions);
   2550       if (Result.isInvalid())
   2551         return TemplateArgumentLoc();
   2552 
   2553       return TemplateArgumentLoc(Result.get(), Result.get());
   2554     }
   2555 
   2556     case TemplateArgument::Template:
   2557       return TemplateArgumentLoc(TemplateArgument(
   2558                                           Pattern.getArgument().getAsTemplate(),
   2559                                                   NumExpansions),
   2560                                  Pattern.getTemplateQualifierLoc(),
   2561                                  Pattern.getTemplateNameLoc(),
   2562                                  EllipsisLoc);
   2563 
   2564     case TemplateArgument::Null:
   2565     case TemplateArgument::Integral:
   2566     case TemplateArgument::Declaration:
   2567     case TemplateArgument::Pack:
   2568     case TemplateArgument::TemplateExpansion:
   2569     case TemplateArgument::NullPtr:
   2570       llvm_unreachable("Pack expansion pattern has no parameter packs");
   2571 
   2572     case TemplateArgument::Type:
   2573       if (TypeSourceInfo *Expansion
   2574             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
   2575                                            EllipsisLoc,
   2576                                            NumExpansions))
   2577         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
   2578                                    Expansion);
   2579       break;
   2580     }
   2581 
   2582     return TemplateArgumentLoc();
   2583   }
   2584 
   2585   /// \brief Build a new expression pack expansion.
   2586   ///
   2587   /// By default, performs semantic analysis to build a new pack expansion
   2588   /// for an expression. Subclasses may override this routine to provide
   2589   /// different behavior.
   2590   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
   2591                                   Optional<unsigned> NumExpansions) {
   2592     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
   2593   }
   2594 
   2595   /// \brief Build a new atomic operation expression.
   2596   ///
   2597   /// By default, performs semantic analysis to build the new expression.
   2598   /// Subclasses may override this routine to provide different behavior.
   2599   ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc,
   2600                                MultiExprArg SubExprs,
   2601                                QualType RetTy,
   2602                                AtomicExpr::AtomicOp Op,
   2603                                SourceLocation RParenLoc) {
   2604     // Just create the expression; there is not any interesting semantic
   2605     // analysis here because we can't actually build an AtomicExpr until
   2606     // we are sure it is semantically sound.
   2607     return new (SemaRef.Context) AtomicExpr(BuiltinLoc, SubExprs, RetTy, Op,
   2608                                             RParenLoc);
   2609   }
   2610 
   2611 private:
   2612   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
   2613                                      QualType ObjectType,
   2614                                      NamedDecl *FirstQualifierInScope,
   2615                                      CXXScopeSpec &SS);
   2616 
   2617   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
   2618                                              QualType ObjectType,
   2619                                              NamedDecl *FirstQualifierInScope,
   2620                                              CXXScopeSpec &SS);
   2621 };
   2622 
   2623 template<typename Derived>
   2624 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
   2625   if (!S)
   2626     return SemaRef.Owned(S);
   2627 
   2628   switch (S->getStmtClass()) {
   2629   case Stmt::NoStmtClass: break;
   2630 
   2631   // Transform individual statement nodes
   2632 #define STMT(Node, Parent)                                              \
   2633   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
   2634 #define ABSTRACT_STMT(Node)
   2635 #define EXPR(Node, Parent)
   2636 #include "clang/AST/StmtNodes.inc"
   2637 
   2638   // Transform expressions by calling TransformExpr.
   2639 #define STMT(Node, Parent)
   2640 #define ABSTRACT_STMT(Stmt)
   2641 #define EXPR(Node, Parent) case Stmt::Node##Class:
   2642 #include "clang/AST/StmtNodes.inc"
   2643     {
   2644       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
   2645       if (E.isInvalid())
   2646         return StmtError();
   2647 
   2648       return getSema().ActOnExprStmt(E);
   2649     }
   2650   }
   2651 
   2652   return SemaRef.Owned(S);
   2653 }
   2654 
   2655 template<typename Derived>
   2656 OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
   2657   if (!S)
   2658     return S;
   2659 
   2660   switch (S->getClauseKind()) {
   2661   default: break;
   2662   // Transform individual clause nodes
   2663 #define OPENMP_CLAUSE(Name, Class)                                             \
   2664   case OMPC_ ## Name :                                                         \
   2665     return getDerived().Transform ## Class(cast<Class>(S));
   2666 #include "clang/Basic/OpenMPKinds.def"
   2667   }
   2668 
   2669   return S;
   2670 }
   2671 
   2672 
   2673 template<typename Derived>
   2674 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
   2675   if (!E)
   2676     return SemaRef.Owned(E);
   2677 
   2678   switch (E->getStmtClass()) {
   2679     case Stmt::NoStmtClass: break;
   2680 #define STMT(Node, Parent) case Stmt::Node##Class: break;
   2681 #define ABSTRACT_STMT(Stmt)
   2682 #define EXPR(Node, Parent)                                              \
   2683     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
   2684 #include "clang/AST/StmtNodes.inc"
   2685   }
   2686 
   2687   return SemaRef.Owned(E);
   2688 }
   2689 
   2690 template<typename Derived>
   2691 ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
   2692                                                         bool CXXDirectInit) {
   2693   // Initializers are instantiated like expressions, except that various outer
   2694   // layers are stripped.
   2695   if (!Init)
   2696     return SemaRef.Owned(Init);
   2697 
   2698   if (ExprWithCleanups *ExprTemp = dyn_cast<ExprWithCleanups>(Init))
   2699     Init = ExprTemp->getSubExpr();
   2700 
   2701   if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
   2702     Init = MTE->GetTemporaryExpr();
   2703 
   2704   while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
   2705     Init = Binder->getSubExpr();
   2706 
   2707   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
   2708     Init = ICE->getSubExprAsWritten();
   2709 
   2710   if (CXXStdInitializerListExpr *ILE =
   2711           dyn_cast<CXXStdInitializerListExpr>(Init))
   2712     return TransformInitializer(ILE->getSubExpr(), CXXDirectInit);
   2713 
   2714   // If this is not a direct-initializer, we only need to reconstruct
   2715   // InitListExprs. Other forms of copy-initialization will be a no-op if
   2716   // the initializer is already the right type.
   2717   CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
   2718   if (!CXXDirectInit && !(Construct && Construct->isListInitialization()))
   2719     return getDerived().TransformExpr(Init);
   2720 
   2721   // Revert value-initialization back to empty parens.
   2722   if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
   2723     SourceRange Parens = VIE->getSourceRange();
   2724     return getDerived().RebuildParenListExpr(Parens.getBegin(), None,
   2725                                              Parens.getEnd());
   2726   }
   2727 
   2728   // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
   2729   if (isa<ImplicitValueInitExpr>(Init))
   2730     return getDerived().RebuildParenListExpr(SourceLocation(), None,
   2731                                              SourceLocation());
   2732 
   2733   // Revert initialization by constructor back to a parenthesized or braced list
   2734   // of expressions. Any other form of initializer can just be reused directly.
   2735   if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
   2736     return getDerived().TransformExpr(Init);
   2737 
   2738   SmallVector<Expr*, 8> NewArgs;
   2739   bool ArgChanged = false;
   2740   if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
   2741                      /*IsCall*/true, NewArgs, &ArgChanged))
   2742     return ExprError();
   2743 
   2744   // If this was list initialization, revert to list form.
   2745   if (Construct->isListInitialization())
   2746     return getDerived().RebuildInitList(Construct->getLocStart(), NewArgs,
   2747                                         Construct->getLocEnd(),
   2748                                         Construct->getType());
   2749 
   2750   // Build a ParenListExpr to represent anything else.
   2751   SourceRange Parens = Construct->getParenRange();
   2752   return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
   2753                                            Parens.getEnd());
   2754 }
   2755 
   2756 template<typename Derived>
   2757 bool TreeTransform<Derived>::TransformExprs(Expr **Inputs,
   2758                                             unsigned NumInputs,
   2759                                             bool IsCall,
   2760                                       SmallVectorImpl<Expr *> &Outputs,
   2761                                             bool *ArgChanged) {
   2762   for (unsigned I = 0; I != NumInputs; ++I) {
   2763     // If requested, drop call arguments that need to be dropped.
   2764     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
   2765       if (ArgChanged)
   2766         *ArgChanged = true;
   2767 
   2768       break;
   2769     }
   2770 
   2771     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
   2772       Expr *Pattern = Expansion->getPattern();
   2773 
   2774       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   2775       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   2776       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   2777 
   2778       // Determine whether the set of unexpanded parameter packs can and should
   2779       // be expanded.
   2780       bool Expand = true;
   2781       bool RetainExpansion = false;
   2782       Optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
   2783       Optional<unsigned> NumExpansions = OrigNumExpansions;
   2784       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
   2785                                                Pattern->getSourceRange(),
   2786                                                Unexpanded,
   2787                                                Expand, RetainExpansion,
   2788                                                NumExpansions))
   2789         return true;
   2790 
   2791       if (!Expand) {
   2792         // The transform has determined that we should perform a simple
   2793         // transformation on the pack expansion, producing another pack
   2794         // expansion.
   2795         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   2796         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
   2797         if (OutPattern.isInvalid())
   2798           return true;
   2799 
   2800         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
   2801                                                 Expansion->getEllipsisLoc(),
   2802                                                            NumExpansions);
   2803         if (Out.isInvalid())
   2804           return true;
   2805 
   2806         if (ArgChanged)
   2807           *ArgChanged = true;
   2808         Outputs.push_back(Out.get());
   2809         continue;
   2810       }
   2811 
   2812       // Record right away that the argument was changed.  This needs
   2813       // to happen even if the array expands to nothing.
   2814       if (ArgChanged) *ArgChanged = true;
   2815 
   2816       // The transform has determined that we should perform an elementwise
   2817       // expansion of the pattern. Do so.
   2818       for (unsigned I = 0; I != *NumExpansions; ++I) {
   2819         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   2820         ExprResult Out = getDerived().TransformExpr(Pattern);
   2821         if (Out.isInvalid())
   2822           return true;
   2823 
   2824         if (Out.get()->containsUnexpandedParameterPack()) {
   2825           Out = RebuildPackExpansion(Out.get(), Expansion->getEllipsisLoc(),
   2826                                      OrigNumExpansions);
   2827           if (Out.isInvalid())
   2828             return true;
   2829         }
   2830 
   2831         Outputs.push_back(Out.get());
   2832       }
   2833 
   2834       continue;
   2835     }
   2836 
   2837     ExprResult Result =
   2838       IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
   2839              : getDerived().TransformExpr(Inputs[I]);
   2840     if (Result.isInvalid())
   2841       return true;
   2842 
   2843     if (Result.get() != Inputs[I] && ArgChanged)
   2844       *ArgChanged = true;
   2845 
   2846     Outputs.push_back(Result.get());
   2847   }
   2848 
   2849   return false;
   2850 }
   2851 
   2852 template<typename Derived>
   2853 NestedNameSpecifierLoc
   2854 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
   2855                                                     NestedNameSpecifierLoc NNS,
   2856                                                      QualType ObjectType,
   2857                                              NamedDecl *FirstQualifierInScope) {
   2858   SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
   2859   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
   2860        Qualifier = Qualifier.getPrefix())
   2861     Qualifiers.push_back(Qualifier);
   2862 
   2863   CXXScopeSpec SS;
   2864   while (!Qualifiers.empty()) {
   2865     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
   2866     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
   2867 
   2868     switch (QNNS->getKind()) {
   2869     case NestedNameSpecifier::Identifier:
   2870       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/0,
   2871                                               *QNNS->getAsIdentifier(),
   2872                                               Q.getLocalBeginLoc(),
   2873                                               Q.getLocalEndLoc(),
   2874                                               ObjectType, false, SS,
   2875                                               FirstQualifierInScope, false))
   2876         return NestedNameSpecifierLoc();
   2877 
   2878       break;
   2879 
   2880     case NestedNameSpecifier::Namespace: {
   2881       NamespaceDecl *NS
   2882         = cast_or_null<NamespaceDecl>(
   2883                                     getDerived().TransformDecl(
   2884                                                           Q.getLocalBeginLoc(),
   2885                                                        QNNS->getAsNamespace()));
   2886       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
   2887       break;
   2888     }
   2889 
   2890     case NestedNameSpecifier::NamespaceAlias: {
   2891       NamespaceAliasDecl *Alias
   2892         = cast_or_null<NamespaceAliasDecl>(
   2893                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
   2894                                                  QNNS->getAsNamespaceAlias()));
   2895       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
   2896                 Q.getLocalEndLoc());
   2897       break;
   2898     }
   2899 
   2900     case NestedNameSpecifier::Global:
   2901       // There is no meaningful transformation that one could perform on the
   2902       // global scope.
   2903       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
   2904       break;
   2905 
   2906     case NestedNameSpecifier::TypeSpecWithTemplate:
   2907     case NestedNameSpecifier::TypeSpec: {
   2908       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
   2909                                               FirstQualifierInScope, SS);
   2910 
   2911       if (!TL)
   2912         return NestedNameSpecifierLoc();
   2913 
   2914       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
   2915           (SemaRef.getLangOpts().CPlusPlus11 &&
   2916            TL.getType()->isEnumeralType())) {
   2917         assert(!TL.getType().hasLocalQualifiers() &&
   2918                "Can't get cv-qualifiers here");
   2919         if (TL.getType()->isEnumeralType())
   2920           SemaRef.Diag(TL.getBeginLoc(),
   2921                        diag::warn_cxx98_compat_enum_nested_name_spec);
   2922         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
   2923                   Q.getLocalEndLoc());
   2924         break;
   2925       }
   2926       // If the nested-name-specifier is an invalid type def, don't emit an
   2927       // error because a previous error should have already been emitted.
   2928       TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>();
   2929       if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
   2930         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
   2931           << TL.getType() << SS.getRange();
   2932       }
   2933       return NestedNameSpecifierLoc();
   2934     }
   2935     }
   2936 
   2937     // The qualifier-in-scope and object type only apply to the leftmost entity.
   2938     FirstQualifierInScope = 0;
   2939     ObjectType = QualType();
   2940   }
   2941 
   2942   // Don't rebuild the nested-name-specifier if we don't have to.
   2943   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
   2944       !getDerived().AlwaysRebuild())
   2945     return NNS;
   2946 
   2947   // If we can re-use the source-location data from the original
   2948   // nested-name-specifier, do so.
   2949   if (SS.location_size() == NNS.getDataLength() &&
   2950       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
   2951     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
   2952 
   2953   // Allocate new nested-name-specifier location information.
   2954   return SS.getWithLocInContext(SemaRef.Context);
   2955 }
   2956 
   2957 template<typename Derived>
   2958 DeclarationNameInfo
   2959 TreeTransform<Derived>
   2960 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
   2961   DeclarationName Name = NameInfo.getName();
   2962   if (!Name)
   2963     return DeclarationNameInfo();
   2964 
   2965   switch (Name.getNameKind()) {
   2966   case DeclarationName::Identifier:
   2967   case DeclarationName::ObjCZeroArgSelector:
   2968   case DeclarationName::ObjCOneArgSelector:
   2969   case DeclarationName::ObjCMultiArgSelector:
   2970   case DeclarationName::CXXOperatorName:
   2971   case DeclarationName::CXXLiteralOperatorName:
   2972   case DeclarationName::CXXUsingDirective:
   2973     return NameInfo;
   2974 
   2975   case DeclarationName::CXXConstructorName:
   2976   case DeclarationName::CXXDestructorName:
   2977   case DeclarationName::CXXConversionFunctionName: {
   2978     TypeSourceInfo *NewTInfo;
   2979     CanQualType NewCanTy;
   2980     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
   2981       NewTInfo = getDerived().TransformType(OldTInfo);
   2982       if (!NewTInfo)
   2983         return DeclarationNameInfo();
   2984       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
   2985     }
   2986     else {
   2987       NewTInfo = 0;
   2988       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
   2989       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
   2990       if (NewT.isNull())
   2991         return DeclarationNameInfo();
   2992       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
   2993     }
   2994 
   2995     DeclarationName NewName
   2996       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
   2997                                                            NewCanTy);
   2998     DeclarationNameInfo NewNameInfo(NameInfo);
   2999     NewNameInfo.setName(NewName);
   3000     NewNameInfo.setNamedTypeInfo(NewTInfo);
   3001     return NewNameInfo;
   3002   }
   3003   }
   3004 
   3005   llvm_unreachable("Unknown name kind.");
   3006 }
   3007 
   3008 template<typename Derived>
   3009 TemplateName
   3010 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
   3011                                               TemplateName Name,
   3012                                               SourceLocation NameLoc,
   3013                                               QualType ObjectType,
   3014                                               NamedDecl *FirstQualifierInScope) {
   3015   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
   3016     TemplateDecl *Template = QTN->getTemplateDecl();
   3017     assert(Template && "qualified template name must refer to a template");
   3018 
   3019     TemplateDecl *TransTemplate
   3020       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
   3021                                                               Template));
   3022     if (!TransTemplate)
   3023       return TemplateName();
   3024 
   3025     if (!getDerived().AlwaysRebuild() &&
   3026         SS.getScopeRep() == QTN->getQualifier() &&
   3027         TransTemplate == Template)
   3028       return Name;
   3029 
   3030     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
   3031                                             TransTemplate);
   3032   }
   3033 
   3034   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
   3035     if (SS.getScopeRep()) {
   3036       // These apply to the scope specifier, not the template.
   3037       ObjectType = QualType();
   3038       FirstQualifierInScope = 0;
   3039     }
   3040 
   3041     if (!getDerived().AlwaysRebuild() &&
   3042         SS.getScopeRep() == DTN->getQualifier() &&
   3043         ObjectType.isNull())
   3044       return Name;
   3045 
   3046     if (DTN->isIdentifier()) {
   3047       return getDerived().RebuildTemplateName(SS,
   3048                                               *DTN->getIdentifier(),
   3049                                               NameLoc,
   3050                                               ObjectType,
   3051                                               FirstQualifierInScope);
   3052     }
   3053 
   3054     return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
   3055                                             ObjectType);
   3056   }
   3057 
   3058   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
   3059     TemplateDecl *TransTemplate
   3060       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
   3061                                                               Template));
   3062     if (!TransTemplate)
   3063       return TemplateName();
   3064 
   3065     if (!getDerived().AlwaysRebuild() &&
   3066         TransTemplate == Template)
   3067       return Name;
   3068 
   3069     return TemplateName(TransTemplate);
   3070   }
   3071 
   3072   if (SubstTemplateTemplateParmPackStorage *SubstPack
   3073       = Name.getAsSubstTemplateTemplateParmPack()) {
   3074     TemplateTemplateParmDecl *TransParam
   3075     = cast_or_null<TemplateTemplateParmDecl>(
   3076             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
   3077     if (!TransParam)
   3078       return TemplateName();
   3079 
   3080     if (!getDerived().AlwaysRebuild() &&
   3081         TransParam == SubstPack->getParameterPack())
   3082       return Name;
   3083 
   3084     return getDerived().RebuildTemplateName(TransParam,
   3085                                             SubstPack->getArgumentPack());
   3086   }
   3087 
   3088   // These should be getting filtered out before they reach the AST.
   3089   llvm_unreachable("overloaded function decl survived to here");
   3090 }
   3091 
   3092 template<typename Derived>
   3093 void TreeTransform<Derived>::InventTemplateArgumentLoc(
   3094                                          const TemplateArgument &Arg,
   3095                                          TemplateArgumentLoc &Output) {
   3096   SourceLocation Loc = getDerived().getBaseLocation();
   3097   switch (Arg.getKind()) {
   3098   case TemplateArgument::Null:
   3099     llvm_unreachable("null template argument in TreeTransform");
   3100     break;
   3101 
   3102   case TemplateArgument::Type:
   3103     Output = TemplateArgumentLoc(Arg,
   3104                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
   3105 
   3106     break;
   3107 
   3108   case TemplateArgument::Template:
   3109   case TemplateArgument::TemplateExpansion: {
   3110     NestedNameSpecifierLocBuilder Builder;
   3111     TemplateName Template = Arg.getAsTemplate();
   3112     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
   3113       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
   3114     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
   3115       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
   3116 
   3117     if (Arg.getKind() == TemplateArgument::Template)
   3118       Output = TemplateArgumentLoc(Arg,
   3119                                    Builder.getWithLocInContext(SemaRef.Context),
   3120                                    Loc);
   3121     else
   3122       Output = TemplateArgumentLoc(Arg,
   3123                                    Builder.getWithLocInContext(SemaRef.Context),
   3124                                    Loc, Loc);
   3125 
   3126     break;
   3127   }
   3128 
   3129   case TemplateArgument::Expression:
   3130     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
   3131     break;
   3132 
   3133   case TemplateArgument::Declaration:
   3134   case TemplateArgument::Integral:
   3135   case TemplateArgument::Pack:
   3136   case TemplateArgument::NullPtr:
   3137     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
   3138     break;
   3139   }
   3140 }
   3141 
   3142 template<typename Derived>
   3143 bool TreeTransform<Derived>::TransformTemplateArgument(
   3144                                          const TemplateArgumentLoc &Input,
   3145                                          TemplateArgumentLoc &Output) {
   3146   const TemplateArgument &Arg = Input.getArgument();
   3147   switch (Arg.getKind()) {
   3148   case TemplateArgument::Null:
   3149   case TemplateArgument::Integral:
   3150   case TemplateArgument::Pack:
   3151   case TemplateArgument::Declaration:
   3152   case TemplateArgument::NullPtr:
   3153     llvm_unreachable("Unexpected TemplateArgument");
   3154 
   3155   case TemplateArgument::Type: {
   3156     TypeSourceInfo *DI = Input.getTypeSourceInfo();
   3157     if (DI == NULL)
   3158       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
   3159 
   3160     DI = getDerived().TransformType(DI);
   3161     if (!DI) return true;
   3162 
   3163     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
   3164     return false;
   3165   }
   3166 
   3167   case TemplateArgument::Template: {
   3168     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
   3169     if (QualifierLoc) {
   3170       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
   3171       if (!QualifierLoc)
   3172         return true;
   3173     }
   3174 
   3175     CXXScopeSpec SS;
   3176     SS.Adopt(QualifierLoc);
   3177     TemplateName Template
   3178       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
   3179                                            Input.getTemplateNameLoc());
   3180     if (Template.isNull())
   3181       return true;
   3182 
   3183     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
   3184                                  Input.getTemplateNameLoc());
   3185     return false;
   3186   }
   3187 
   3188   case TemplateArgument::TemplateExpansion:
   3189     llvm_unreachable("Caller should expand pack expansions");
   3190 
   3191   case TemplateArgument::Expression: {
   3192     // Template argument expressions are constant expressions.
   3193     EnterExpressionEvaluationContext Unevaluated(getSema(),
   3194                                                  Sema::ConstantEvaluated);
   3195 
   3196     Expr *InputExpr = Input.getSourceExpression();
   3197     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
   3198 
   3199     ExprResult E = getDerived().TransformExpr(InputExpr);
   3200     E = SemaRef.ActOnConstantExpression(E);
   3201     if (E.isInvalid()) return true;
   3202     Output = TemplateArgumentLoc(TemplateArgument(E.take()), E.take());
   3203     return false;
   3204   }
   3205   }
   3206 
   3207   // Work around bogus GCC warning
   3208   return true;
   3209 }
   3210 
   3211 /// \brief Iterator adaptor that invents template argument location information
   3212 /// for each of the template arguments in its underlying iterator.
   3213 template<typename Derived, typename InputIterator>
   3214 class TemplateArgumentLocInventIterator {
   3215   TreeTransform<Derived> &Self;
   3216   InputIterator Iter;
   3217 
   3218 public:
   3219   typedef TemplateArgumentLoc value_type;
   3220   typedef TemplateArgumentLoc reference;
   3221   typedef typename std::iterator_traits<InputIterator>::difference_type
   3222     difference_type;
   3223   typedef std::input_iterator_tag iterator_category;
   3224 
   3225   class pointer {
   3226     TemplateArgumentLoc Arg;
   3227 
   3228   public:
   3229     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
   3230 
   3231     const TemplateArgumentLoc *operator->() const { return &Arg; }
   3232   };
   3233 
   3234   TemplateArgumentLocInventIterator() { }
   3235 
   3236   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
   3237                                              InputIterator Iter)
   3238     : Self(Self), Iter(Iter) { }
   3239 
   3240   TemplateArgumentLocInventIterator &operator++() {
   3241     ++Iter;
   3242     return *this;
   3243   }
   3244 
   3245   TemplateArgumentLocInventIterator operator++(int) {
   3246     TemplateArgumentLocInventIterator Old(*this);
   3247     ++(*this);
   3248     return Old;
   3249   }
   3250 
   3251   reference operator*() const {
   3252     TemplateArgumentLoc Result;
   3253     Self.InventTemplateArgumentLoc(*Iter, Result);
   3254     return Result;
   3255   }
   3256 
   3257   pointer operator->() const { return pointer(**this); }
   3258 
   3259   friend bool operator==(const TemplateArgumentLocInventIterator &X,
   3260                          const TemplateArgumentLocInventIterator &Y) {
   3261     return X.Iter == Y.Iter;
   3262   }
   3263 
   3264   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
   3265                          const TemplateArgumentLocInventIterator &Y) {
   3266     return X.Iter != Y.Iter;
   3267   }
   3268 };
   3269 
   3270 template<typename Derived>
   3271 template<typename InputIterator>
   3272 bool TreeTransform<Derived>::TransformTemplateArguments(InputIterator First,
   3273                                                         InputIterator Last,
   3274                                             TemplateArgumentListInfo &Outputs) {
   3275   for (; First != Last; ++First) {
   3276     TemplateArgumentLoc Out;
   3277     TemplateArgumentLoc In = *First;
   3278 
   3279     if (In.getArgument().getKind() == TemplateArgument::Pack) {
   3280       // Unpack argument packs, which we translate them into separate
   3281       // arguments.
   3282       // FIXME: We could do much better if we could guarantee that the
   3283       // TemplateArgumentLocInfo for the pack expansion would be usable for
   3284       // all of the template arguments in the argument pack.
   3285       typedef TemplateArgumentLocInventIterator<Derived,
   3286                                                 TemplateArgument::pack_iterator>
   3287         PackLocIterator;
   3288       if (TransformTemplateArguments(PackLocIterator(*this,
   3289                                                  In.getArgument().pack_begin()),
   3290                                      PackLocIterator(*this,
   3291                                                    In.getArgument().pack_end()),
   3292                                      Outputs))
   3293         return true;
   3294 
   3295       continue;
   3296     }
   3297 
   3298     if (In.getArgument().isPackExpansion()) {
   3299       // We have a pack expansion, for which we will be substituting into
   3300       // the pattern.
   3301       SourceLocation Ellipsis;
   3302       Optional<unsigned> OrigNumExpansions;
   3303       TemplateArgumentLoc Pattern
   3304         = getSema().getTemplateArgumentPackExpansionPattern(
   3305               In, Ellipsis, OrigNumExpansions);
   3306 
   3307       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   3308       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   3309       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   3310 
   3311       // Determine whether the set of unexpanded parameter packs can and should
   3312       // be expanded.
   3313       bool Expand = true;
   3314       bool RetainExpansion = false;
   3315       Optional<unsigned> NumExpansions = OrigNumExpansions;
   3316       if (getDerived().TryExpandParameterPacks(Ellipsis,
   3317                                                Pattern.getSourceRange(),
   3318                                                Unexpanded,
   3319                                                Expand,
   3320                                                RetainExpansion,
   3321                                                NumExpansions))
   3322         return true;
   3323 
   3324       if (!Expand) {
   3325         // The transform has determined that we should perform a simple
   3326         // transformation on the pack expansion, producing another pack
   3327         // expansion.
   3328         TemplateArgumentLoc OutPattern;
   3329         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   3330         if (getDerived().TransformTemplateArgument(Pattern, OutPattern))
   3331           return true;
   3332 
   3333         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
   3334                                                 NumExpansions);
   3335         if (Out.getArgument().isNull())
   3336           return true;
   3337 
   3338         Outputs.addArgument(Out);
   3339         continue;
   3340       }
   3341 
   3342       // The transform has determined that we should perform an elementwise
   3343       // expansion of the pattern. Do so.
   3344       for (unsigned I = 0; I != *NumExpansions; ++I) {
   3345         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   3346 
   3347         if (getDerived().TransformTemplateArgument(Pattern, Out))
   3348           return true;
   3349 
   3350         if (Out.getArgument().containsUnexpandedParameterPack()) {
   3351           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
   3352                                                   OrigNumExpansions);
   3353           if (Out.getArgument().isNull())
   3354             return true;
   3355         }
   3356 
   3357         Outputs.addArgument(Out);
   3358       }
   3359 
   3360       // If we're supposed to retain a pack expansion, do so by temporarily
   3361       // forgetting the partially-substituted parameter pack.
   3362       if (RetainExpansion) {
   3363         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   3364 
   3365         if (getDerived().TransformTemplateArgument(Pattern, Out))
   3366           return true;
   3367 
   3368         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
   3369                                                 OrigNumExpansions);
   3370         if (Out.getArgument().isNull())
   3371           return true;
   3372 
   3373         Outputs.addArgument(Out);
   3374       }
   3375 
   3376       continue;
   3377     }
   3378 
   3379     // The simple case:
   3380     if (getDerived().TransformTemplateArgument(In, Out))
   3381       return true;
   3382 
   3383     Outputs.addArgument(Out);
   3384   }
   3385 
   3386   return false;
   3387 
   3388 }
   3389 
   3390 //===----------------------------------------------------------------------===//
   3391 // Type transformation
   3392 //===----------------------------------------------------------------------===//
   3393 
   3394 template<typename Derived>
   3395 QualType TreeTransform<Derived>::TransformType(QualType T) {
   3396   if (getDerived().AlreadyTransformed(T))
   3397     return T;
   3398 
   3399   // Temporary workaround.  All of these transformations should
   3400   // eventually turn into transformations on TypeLocs.
   3401   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
   3402                                                 getDerived().getBaseLocation());
   3403 
   3404   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
   3405 
   3406   if (!NewDI)
   3407     return QualType();
   3408 
   3409   return NewDI->getType();
   3410 }
   3411 
   3412 template<typename Derived>
   3413 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
   3414   // Refine the base location to the type's location.
   3415   TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
   3416                        getDerived().getBaseEntity());
   3417   if (getDerived().AlreadyTransformed(DI->getType()))
   3418     return DI;
   3419 
   3420   TypeLocBuilder TLB;
   3421 
   3422   TypeLoc TL = DI->getTypeLoc();
   3423   TLB.reserve(TL.getFullDataSize());
   3424 
   3425   QualType Result = getDerived().TransformType(TLB, TL);
   3426   if (Result.isNull())
   3427     return 0;
   3428 
   3429   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
   3430 }
   3431 
   3432 template<typename Derived>
   3433 QualType
   3434 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
   3435   switch (T.getTypeLocClass()) {
   3436 #define ABSTRACT_TYPELOC(CLASS, PARENT)
   3437 #define TYPELOC(CLASS, PARENT)                                                 \
   3438   case TypeLoc::CLASS:                                                         \
   3439     return getDerived().Transform##CLASS##Type(TLB,                            \
   3440                                                T.castAs<CLASS##TypeLoc>());
   3441 #include "clang/AST/TypeLocNodes.def"
   3442   }
   3443 
   3444   llvm_unreachable("unhandled type loc!");
   3445 }
   3446 
   3447 /// FIXME: By default, this routine adds type qualifiers only to types
   3448 /// that can have qualifiers, and silently suppresses those qualifiers
   3449 /// that are not permitted (e.g., qualifiers on reference or function
   3450 /// types). This is the right thing for template instantiation, but
   3451 /// probably not for other clients.
   3452 template<typename Derived>
   3453 QualType
   3454 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
   3455                                                QualifiedTypeLoc T) {
   3456   Qualifiers Quals = T.getType().getLocalQualifiers();
   3457 
   3458   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
   3459   if (Result.isNull())
   3460     return QualType();
   3461 
   3462   // Silently suppress qualifiers if the result type can't be qualified.
   3463   // FIXME: this is the right thing for template instantiation, but
   3464   // probably not for other clients.
   3465   if (Result->isFunctionType() || Result->isReferenceType())
   3466     return Result;
   3467 
   3468   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
   3469   // resulting type.
   3470   if (Quals.hasObjCLifetime()) {
   3471     if (!Result->isObjCLifetimeType() && !Result->isDependentType())
   3472       Quals.removeObjCLifetime();
   3473     else if (Result.getObjCLifetime()) {
   3474       // Objective-C ARC:
   3475       //   A lifetime qualifier applied to a substituted template parameter
   3476       //   overrides the lifetime qualifier from the template argument.
   3477       const AutoType *AutoTy;
   3478       if (const SubstTemplateTypeParmType *SubstTypeParam
   3479                                 = dyn_cast<SubstTemplateTypeParmType>(Result)) {
   3480         QualType Replacement = SubstTypeParam->getReplacementType();
   3481         Qualifiers Qs = Replacement.getQualifiers();
   3482         Qs.removeObjCLifetime();
   3483         Replacement
   3484           = SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(),
   3485                                              Qs);
   3486         Result = SemaRef.Context.getSubstTemplateTypeParmType(
   3487                                         SubstTypeParam->getReplacedParameter(),
   3488                                                               Replacement);
   3489         TLB.TypeWasModifiedSafely(Result);
   3490       } else if ((AutoTy = dyn_cast<AutoType>(Result)) && AutoTy->isDeduced()) {
   3491         // 'auto' types behave the same way as template parameters.
   3492         QualType Deduced = AutoTy->getDeducedType();
   3493         Qualifiers Qs = Deduced.getQualifiers();
   3494         Qs.removeObjCLifetime();
   3495         Deduced = SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(),
   3496                                                    Qs);
   3497         Result = SemaRef.Context.getAutoType(Deduced, AutoTy->isDecltypeAuto());
   3498         TLB.TypeWasModifiedSafely(Result);
   3499       } else {
   3500         // Otherwise, complain about the addition of a qualifier to an
   3501         // already-qualified type.
   3502         SourceRange R = T.getUnqualifiedLoc().getSourceRange();
   3503         SemaRef.Diag(R.getBegin(), diag::err_attr_objc_ownership_redundant)
   3504           << Result << R;
   3505 
   3506         Quals.removeObjCLifetime();
   3507       }
   3508     }
   3509   }
   3510   if (!Quals.empty()) {
   3511     Result = SemaRef.BuildQualifiedType(Result, T.getBeginLoc(), Quals);
   3512     // BuildQualifiedType might not add qualifiers if they are invalid.
   3513     if (Result.hasLocalQualifiers())
   3514       TLB.push<QualifiedTypeLoc>(Result);
   3515     // No location information to preserve.
   3516   }
   3517 
   3518   return Result;
   3519 }
   3520 
   3521 template<typename Derived>
   3522 TypeLoc
   3523 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
   3524                                                    QualType ObjectType,
   3525                                                    NamedDecl *UnqualLookup,
   3526                                                    CXXScopeSpec &SS) {
   3527   QualType T = TL.getType();
   3528   if (getDerived().AlreadyTransformed(T))
   3529     return TL;
   3530 
   3531   TypeLocBuilder TLB;
   3532   QualType Result;
   3533 
   3534   if (isa<TemplateSpecializationType>(T)) {
   3535     TemplateSpecializationTypeLoc SpecTL =
   3536         TL.castAs<TemplateSpecializationTypeLoc>();
   3537 
   3538     TemplateName Template =
   3539       getDerived().TransformTemplateName(SS,
   3540                                          SpecTL.getTypePtr()->getTemplateName(),
   3541                                          SpecTL.getTemplateNameLoc(),
   3542                                          ObjectType, UnqualLookup);
   3543     if (Template.isNull())
   3544       return TypeLoc();
   3545 
   3546     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
   3547                                                               Template);
   3548   } else if (isa<DependentTemplateSpecializationType>(T)) {
   3549     DependentTemplateSpecializationTypeLoc SpecTL =
   3550         TL.castAs<DependentTemplateSpecializationTypeLoc>();
   3551 
   3552     TemplateName Template
   3553       = getDerived().RebuildTemplateName(SS,
   3554                                          *SpecTL.getTypePtr()->getIdentifier(),
   3555                                          SpecTL.getTemplateNameLoc(),
   3556                                          ObjectType, UnqualLookup);
   3557     if (Template.isNull())
   3558       return TypeLoc();
   3559 
   3560     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
   3561                                                                        SpecTL,
   3562                                                                      Template,
   3563                                                                        SS);
   3564   } else {
   3565     // Nothing special needs to be done for these.
   3566     Result = getDerived().TransformType(TLB, TL);
   3567   }
   3568 
   3569   if (Result.isNull())
   3570     return TypeLoc();
   3571 
   3572   return TLB.getTypeSourceInfo(SemaRef.Context, Result)->getTypeLoc();
   3573 }
   3574 
   3575 template<typename Derived>
   3576 TypeSourceInfo *
   3577 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
   3578                                                    QualType ObjectType,
   3579                                                    NamedDecl *UnqualLookup,
   3580                                                    CXXScopeSpec &SS) {
   3581   // FIXME: Painfully copy-paste from the above!
   3582 
   3583   QualType T = TSInfo->getType();
   3584   if (getDerived().AlreadyTransformed(T))
   3585     return TSInfo;
   3586 
   3587   TypeLocBuilder TLB;
   3588   QualType Result;
   3589 
   3590   TypeLoc TL = TSInfo->getTypeLoc();
   3591   if (isa<TemplateSpecializationType>(T)) {
   3592     TemplateSpecializationTypeLoc SpecTL =
   3593         TL.castAs<TemplateSpecializationTypeLoc>();
   3594 
   3595     TemplateName Template
   3596     = getDerived().TransformTemplateName(SS,
   3597                                          SpecTL.getTypePtr()->getTemplateName(),
   3598                                          SpecTL.getTemplateNameLoc(),
   3599                                          ObjectType, UnqualLookup);
   3600     if (Template.isNull())
   3601       return 0;
   3602 
   3603     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
   3604                                                               Template);
   3605   } else if (isa<DependentTemplateSpecializationType>(T)) {
   3606     DependentTemplateSpecializationTypeLoc SpecTL =
   3607         TL.castAs<DependentTemplateSpecializationTypeLoc>();
   3608 
   3609     TemplateName Template
   3610       = getDerived().RebuildTemplateName(SS,
   3611                                          *SpecTL.getTypePtr()->getIdentifier(),
   3612                                          SpecTL.getTemplateNameLoc(),
   3613                                          ObjectType, UnqualLookup);
   3614     if (Template.isNull())
   3615       return 0;
   3616 
   3617     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
   3618                                                                        SpecTL,
   3619                                                                        Template,
   3620                                                                        SS);
   3621   } else {
   3622     // Nothing special needs to be done for these.
   3623     Result = getDerived().TransformType(TLB, TL);
   3624   }
   3625 
   3626   if (Result.isNull())
   3627     return 0;
   3628 
   3629   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
   3630 }
   3631 
   3632 template <class TyLoc> static inline
   3633 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
   3634   TyLoc NewT = TLB.push<TyLoc>(T.getType());
   3635   NewT.setNameLoc(T.getNameLoc());
   3636   return T.getType();
   3637 }
   3638 
   3639 template<typename Derived>
   3640 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
   3641                                                       BuiltinTypeLoc T) {
   3642   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
   3643   NewT.setBuiltinLoc(T.getBuiltinLoc());
   3644   if (T.needsExtraLocalData())
   3645     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
   3646   return T.getType();
   3647 }
   3648 
   3649 template<typename Derived>
   3650 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
   3651                                                       ComplexTypeLoc T) {
   3652   // FIXME: recurse?
   3653   return TransformTypeSpecType(TLB, T);
   3654 }
   3655 
   3656 template<typename Derived>
   3657 QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
   3658                                                       DecayedTypeLoc TL) {
   3659   QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
   3660   if (OriginalType.isNull())
   3661     return QualType();
   3662 
   3663   QualType Result = TL.getType();
   3664   if (getDerived().AlwaysRebuild() ||
   3665       OriginalType != TL.getOriginalLoc().getType())
   3666     Result = SemaRef.Context.getDecayedType(OriginalType);
   3667   TLB.push<DecayedTypeLoc>(Result);
   3668   // Nothing to set for DecayedTypeLoc.
   3669   return Result;
   3670 }
   3671 
   3672 template<typename Derived>
   3673 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
   3674                                                       PointerTypeLoc TL) {
   3675   QualType PointeeType
   3676     = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3677   if (PointeeType.isNull())
   3678     return QualType();
   3679 
   3680   QualType Result = TL.getType();
   3681   if (PointeeType->getAs<ObjCObjectType>()) {
   3682     // A dependent pointer type 'T *' has is being transformed such
   3683     // that an Objective-C class type is being replaced for 'T'. The
   3684     // resulting pointer type is an ObjCObjectPointerType, not a
   3685     // PointerType.
   3686     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
   3687 
   3688     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
   3689     NewT.setStarLoc(TL.getStarLoc());
   3690     return Result;
   3691   }
   3692 
   3693   if (getDerived().AlwaysRebuild() ||
   3694       PointeeType != TL.getPointeeLoc().getType()) {
   3695     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
   3696     if (Result.isNull())
   3697       return QualType();
   3698   }
   3699 
   3700   // Objective-C ARC can add lifetime qualifiers to the type that we're
   3701   // pointing to.
   3702   TLB.TypeWasModifiedSafely(Result->getPointeeType());
   3703 
   3704   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
   3705   NewT.setSigilLoc(TL.getSigilLoc());
   3706   return Result;
   3707 }
   3708 
   3709 template<typename Derived>
   3710 QualType
   3711 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
   3712                                                   BlockPointerTypeLoc TL) {
   3713   QualType PointeeType
   3714     = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3715   if (PointeeType.isNull())
   3716     return QualType();
   3717 
   3718   QualType Result = TL.getType();
   3719   if (getDerived().AlwaysRebuild() ||
   3720       PointeeType != TL.getPointeeLoc().getType()) {
   3721     Result = getDerived().RebuildBlockPointerType(PointeeType,
   3722                                                   TL.getSigilLoc());
   3723     if (Result.isNull())
   3724       return QualType();
   3725   }
   3726 
   3727   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
   3728   NewT.setSigilLoc(TL.getSigilLoc());
   3729   return Result;
   3730 }
   3731 
   3732 /// Transforms a reference type.  Note that somewhat paradoxically we
   3733 /// don't care whether the type itself is an l-value type or an r-value
   3734 /// type;  we only care if the type was *written* as an l-value type
   3735 /// or an r-value type.
   3736 template<typename Derived>
   3737 QualType
   3738 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
   3739                                                ReferenceTypeLoc TL) {
   3740   const ReferenceType *T = TL.getTypePtr();
   3741 
   3742   // Note that this works with the pointee-as-written.
   3743   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3744   if (PointeeType.isNull())
   3745     return QualType();
   3746 
   3747   QualType Result = TL.getType();
   3748   if (getDerived().AlwaysRebuild() ||
   3749       PointeeType != T->getPointeeTypeAsWritten()) {
   3750     Result = getDerived().RebuildReferenceType(PointeeType,
   3751                                                T->isSpelledAsLValue(),
   3752                                                TL.getSigilLoc());
   3753     if (Result.isNull())
   3754       return QualType();
   3755   }
   3756 
   3757   // Objective-C ARC can add lifetime qualifiers to the type that we're
   3758   // referring to.
   3759   TLB.TypeWasModifiedSafely(
   3760                      Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
   3761 
   3762   // r-value references can be rebuilt as l-value references.
   3763   ReferenceTypeLoc NewTL;
   3764   if (isa<LValueReferenceType>(Result))
   3765     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
   3766   else
   3767     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
   3768   NewTL.setSigilLoc(TL.getSigilLoc());
   3769 
   3770   return Result;
   3771 }
   3772 
   3773 template<typename Derived>
   3774 QualType
   3775 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
   3776                                                  LValueReferenceTypeLoc TL) {
   3777   return TransformReferenceType(TLB, TL);
   3778 }
   3779 
   3780 template<typename Derived>
   3781 QualType
   3782 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
   3783                                                  RValueReferenceTypeLoc TL) {
   3784   return TransformReferenceType(TLB, TL);
   3785 }
   3786 
   3787 template<typename Derived>
   3788 QualType
   3789 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
   3790                                                    MemberPointerTypeLoc TL) {
   3791   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3792   if (PointeeType.isNull())
   3793     return QualType();
   3794 
   3795   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
   3796   TypeSourceInfo* NewClsTInfo = 0;
   3797   if (OldClsTInfo) {
   3798     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
   3799     if (!NewClsTInfo)
   3800       return QualType();
   3801   }
   3802 
   3803   const MemberPointerType *T = TL.getTypePtr();
   3804   QualType OldClsType = QualType(T->getClass(), 0);
   3805   QualType NewClsType;
   3806   if (NewClsTInfo)
   3807     NewClsType = NewClsTInfo->getType();
   3808   else {
   3809     NewClsType = getDerived().TransformType(OldClsType);
   3810     if (NewClsType.isNull())
   3811       return QualType();
   3812   }
   3813 
   3814   QualType Result = TL.getType();
   3815   if (getDerived().AlwaysRebuild() ||
   3816       PointeeType != T->getPointeeType() ||
   3817       NewClsType != OldClsType) {
   3818     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
   3819                                                    TL.getStarLoc());
   3820     if (Result.isNull())
   3821       return QualType();
   3822   }
   3823 
   3824   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
   3825   NewTL.setSigilLoc(TL.getSigilLoc());
   3826   NewTL.setClassTInfo(NewClsTInfo);
   3827 
   3828   return Result;
   3829 }
   3830 
   3831 template<typename Derived>
   3832 QualType
   3833 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
   3834                                                    ConstantArrayTypeLoc TL) {
   3835   const ConstantArrayType *T = TL.getTypePtr();
   3836   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3837   if (ElementType.isNull())
   3838     return QualType();
   3839 
   3840   QualType Result = TL.getType();
   3841   if (getDerived().AlwaysRebuild() ||
   3842       ElementType != T->getElementType()) {
   3843     Result = getDerived().RebuildConstantArrayType(ElementType,
   3844                                                    T->getSizeModifier(),
   3845                                                    T->getSize(),
   3846                                              T->getIndexTypeCVRQualifiers(),
   3847                                                    TL.getBracketsRange());
   3848     if (Result.isNull())
   3849       return QualType();
   3850   }
   3851 
   3852   // We might have either a ConstantArrayType or a VariableArrayType now:
   3853   // a ConstantArrayType is allowed to have an element type which is a
   3854   // VariableArrayType if the type is dependent.  Fortunately, all array
   3855   // types have the same location layout.
   3856   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
   3857   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3858   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3859 
   3860   Expr *Size = TL.getSizeExpr();
   3861   if (Size) {
   3862     EnterExpressionEvaluationContext Unevaluated(SemaRef,
   3863                                                  Sema::ConstantEvaluated);
   3864     Size = getDerived().TransformExpr(Size).template takeAs<Expr>();
   3865     Size = SemaRef.ActOnConstantExpression(Size).take();
   3866   }
   3867   NewTL.setSizeExpr(Size);
   3868 
   3869   return Result;
   3870 }
   3871 
   3872 template<typename Derived>
   3873 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
   3874                                               TypeLocBuilder &TLB,
   3875                                               IncompleteArrayTypeLoc TL) {
   3876   const IncompleteArrayType *T = TL.getTypePtr();
   3877   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3878   if (ElementType.isNull())
   3879     return QualType();
   3880 
   3881   QualType Result = TL.getType();
   3882   if (getDerived().AlwaysRebuild() ||
   3883       ElementType != T->getElementType()) {
   3884     Result = getDerived().RebuildIncompleteArrayType(ElementType,
   3885                                                      T->getSizeModifier(),
   3886                                            T->getIndexTypeCVRQualifiers(),
   3887                                                      TL.getBracketsRange());
   3888     if (Result.isNull())
   3889       return QualType();
   3890   }
   3891 
   3892   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
   3893   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3894   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3895   NewTL.setSizeExpr(0);
   3896 
   3897   return Result;
   3898 }
   3899 
   3900 template<typename Derived>
   3901 QualType
   3902 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
   3903                                                    VariableArrayTypeLoc TL) {
   3904   const VariableArrayType *T = TL.getTypePtr();
   3905   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3906   if (ElementType.isNull())
   3907     return QualType();
   3908 
   3909   ExprResult SizeResult
   3910     = getDerived().TransformExpr(T->getSizeExpr());
   3911   if (SizeResult.isInvalid())
   3912     return QualType();
   3913 
   3914   Expr *Size = SizeResult.take();
   3915 
   3916   QualType Result = TL.getType();
   3917   if (getDerived().AlwaysRebuild() ||
   3918       ElementType != T->getElementType() ||
   3919       Size != T->getSizeExpr()) {
   3920     Result = getDerived().RebuildVariableArrayType(ElementType,
   3921                                                    T->getSizeModifier(),
   3922                                                    Size,
   3923                                              T->getIndexTypeCVRQualifiers(),
   3924                                                    TL.getBracketsRange());
   3925     if (Result.isNull())
   3926       return QualType();
   3927   }
   3928 
   3929   VariableArrayTypeLoc NewTL = TLB.push<VariableArrayTypeLoc>(Result);
   3930   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3931   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3932   NewTL.setSizeExpr(Size);
   3933 
   3934   return Result;
   3935 }
   3936 
   3937 template<typename Derived>
   3938 QualType
   3939 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
   3940                                              DependentSizedArrayTypeLoc TL) {
   3941   const DependentSizedArrayType *T = TL.getTypePtr();
   3942   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3943   if (ElementType.isNull())
   3944     return QualType();
   3945 
   3946   // Array bounds are constant expressions.
   3947   EnterExpressionEvaluationContext Unevaluated(SemaRef,
   3948                                                Sema::ConstantEvaluated);
   3949 
   3950   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
   3951   Expr *origSize = TL.getSizeExpr();
   3952   if (!origSize) origSize = T->getSizeExpr();
   3953 
   3954   ExprResult sizeResult
   3955     = getDerived().TransformExpr(origSize);
   3956   sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
   3957   if (sizeResult.isInvalid())
   3958     return QualType();
   3959 
   3960   Expr *size = sizeResult.get();
   3961 
   3962   QualType Result = TL.getType();
   3963   if (getDerived().AlwaysRebuild() ||
   3964       ElementType != T->getElementType() ||
   3965       size != origSize) {
   3966     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
   3967                                                          T->getSizeModifier(),
   3968                                                          size,
   3969                                                 T->getIndexTypeCVRQualifiers(),
   3970                                                         TL.getBracketsRange());
   3971     if (Result.isNull())
   3972       return QualType();
   3973   }
   3974 
   3975   // We might have any sort of array type now, but fortunately they
   3976   // all have the same location layout.
   3977   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
   3978   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3979   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3980   NewTL.setSizeExpr(size);
   3981 
   3982   return Result;
   3983 }
   3984 
   3985 template<typename Derived>
   3986 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
   3987                                       TypeLocBuilder &TLB,
   3988                                       DependentSizedExtVectorTypeLoc TL) {
   3989   const DependentSizedExtVectorType *T = TL.getTypePtr();
   3990 
   3991   // FIXME: ext vector locs should be nested
   3992   QualType ElementType = getDerived().TransformType(T->getElementType());
   3993   if (ElementType.isNull())
   3994     return QualType();
   3995 
   3996   // Vector sizes are constant expressions.
   3997   EnterExpressionEvaluationContext Unevaluated(SemaRef,
   3998                                                Sema::ConstantEvaluated);
   3999 
   4000   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
   4001   Size = SemaRef.ActOnConstantExpression(Size);
   4002   if (Size.isInvalid())
   4003     return QualType();
   4004 
   4005   QualType Result = TL.getType();
   4006   if (getDerived().AlwaysRebuild() ||
   4007       ElementType != T->getElementType() ||
   4008       Size.get() != T->getSizeExpr()) {
   4009     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
   4010                                                              Size.take(),
   4011                                                          T->getAttributeLoc());
   4012     if (Result.isNull())
   4013       return QualType();
   4014   }
   4015 
   4016   // Result might be dependent or not.
   4017   if (isa<DependentSizedExtVectorType>(Result)) {
   4018     DependentSizedExtVectorTypeLoc NewTL
   4019       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
   4020     NewTL.setNameLoc(TL.getNameLoc());
   4021   } else {
   4022     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
   4023     NewTL.setNameLoc(TL.getNameLoc());
   4024   }
   4025 
   4026   return Result;
   4027 }
   4028 
   4029 template<typename Derived>
   4030 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
   4031                                                      VectorTypeLoc TL) {
   4032   const VectorType *T = TL.getTypePtr();
   4033   QualType ElementType = getDerived().TransformType(T->getElementType());
   4034   if (ElementType.isNull())
   4035     return QualType();
   4036 
   4037   QualType Result = TL.getType();
   4038   if (getDerived().AlwaysRebuild() ||
   4039       ElementType != T->getElementType()) {
   4040     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
   4041                                             T->getVectorKind());
   4042     if (Result.isNull())
   4043       return QualType();
   4044   }
   4045 
   4046   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
   4047   NewTL.setNameLoc(TL.getNameLoc());
   4048 
   4049   return Result;
   4050 }
   4051 
   4052 template<typename Derived>
   4053 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
   4054                                                         ExtVectorTypeLoc TL) {
   4055   const VectorType *T = TL.getTypePtr();
   4056   QualType ElementType = getDerived().TransformType(T->getElementType());
   4057   if (ElementType.isNull())
   4058     return QualType();
   4059 
   4060   QualType Result = TL.getType();
   4061   if (getDerived().AlwaysRebuild() ||
   4062       ElementType != T->getElementType()) {
   4063     Result = getDerived().RebuildExtVectorType(ElementType,
   4064                                                T->getNumElements(),
   4065                                                /*FIXME*/ SourceLocation());
   4066     if (Result.isNull())
   4067       return QualType();
   4068   }
   4069 
   4070   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
   4071   NewTL.setNameLoc(TL.getNameLoc());
   4072 
   4073   return Result;
   4074 }
   4075 
   4076 template <typename Derived>
   4077 ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
   4078     ParmVarDecl *OldParm, int indexAdjustment, Optional<unsigned> NumExpansions,
   4079     bool ExpectParameterPack) {
   4080   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
   4081   TypeSourceInfo *NewDI = 0;
   4082 
   4083   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
   4084     // If we're substituting into a pack expansion type and we know the
   4085     // length we want to expand to, just substitute for the pattern.
   4086     TypeLoc OldTL = OldDI->getTypeLoc();
   4087     PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
   4088 
   4089     TypeLocBuilder TLB;
   4090     TypeLoc NewTL = OldDI->getTypeLoc();
   4091     TLB.reserve(NewTL.getFullDataSize());
   4092 
   4093     QualType Result = getDerived().TransformType(TLB,
   4094                                                OldExpansionTL.getPatternLoc());
   4095     if (Result.isNull())
   4096       return 0;
   4097 
   4098     Result = RebuildPackExpansionType(Result,
   4099                                 OldExpansionTL.getPatternLoc().getSourceRange(),
   4100                                       OldExpansionTL.getEllipsisLoc(),
   4101                                       NumExpansions);
   4102     if (Result.isNull())
   4103       return 0;
   4104 
   4105     PackExpansionTypeLoc NewExpansionTL
   4106       = TLB.push<PackExpansionTypeLoc>(Result);
   4107     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
   4108     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
   4109   } else
   4110     NewDI = getDerived().TransformType(OldDI);
   4111   if (!NewDI)
   4112     return 0;
   4113 
   4114   if (NewDI == OldDI && indexAdjustment == 0)
   4115     return OldParm;
   4116 
   4117   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
   4118                                              OldParm->getDeclContext(),
   4119                                              OldParm->getInnerLocStart(),
   4120                                              OldParm->getLocation(),
   4121                                              OldParm->getIdentifier(),
   4122                                              NewDI->getType(),
   4123                                              NewDI,
   4124                                              OldParm->getStorageClass(),
   4125                                              /* DefArg */ NULL);
   4126   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
   4127                         OldParm->getFunctionScopeIndex() + indexAdjustment);
   4128   return newParm;
   4129 }
   4130 
   4131 template<typename Derived>
   4132 bool TreeTransform<Derived>::
   4133   TransformFunctionTypeParams(SourceLocation Loc,
   4134                               ParmVarDecl **Params, unsigned NumParams,
   4135                               const QualType *ParamTypes,
   4136                               SmallVectorImpl<QualType> &OutParamTypes,
   4137                               SmallVectorImpl<ParmVarDecl*> *PVars) {
   4138   int indexAdjustment = 0;
   4139 
   4140   for (unsigned i = 0; i != NumParams; ++i) {
   4141     if (ParmVarDecl *OldParm = Params[i]) {
   4142       assert(OldParm->getFunctionScopeIndex() == i);
   4143 
   4144       Optional<unsigned> NumExpansions;
   4145       ParmVarDecl *NewParm = 0;
   4146       if (OldParm->isParameterPack()) {
   4147         // We have a function parameter pack that may need to be expanded.
   4148         SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   4149 
   4150         // Find the parameter packs that could be expanded.
   4151         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
   4152         PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
   4153         TypeLoc Pattern = ExpansionTL.getPatternLoc();
   4154         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
   4155         assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
   4156 
   4157         // Determine whether we should expand the parameter packs.
   4158         bool ShouldExpand = false;
   4159         bool RetainExpansion = false;
   4160         Optional<unsigned> OrigNumExpansions =
   4161             ExpansionTL.getTypePtr()->getNumExpansions();
   4162         NumExpansions = OrigNumExpansions;
   4163         if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
   4164                                                  Pattern.getSourceRange(),
   4165                                                  Unexpanded,
   4166                                                  ShouldExpand,
   4167                                                  RetainExpansion,
   4168                                                  NumExpansions)) {
   4169           return true;
   4170         }
   4171 
   4172         if (ShouldExpand) {
   4173           // Expand the function parameter pack into multiple, separate
   4174           // parameters.
   4175           getDerived().ExpandingFunctionParameterPack(OldParm);
   4176           for (unsigned I = 0; I != *NumExpansions; ++I) {
   4177             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   4178             ParmVarDecl *NewParm
   4179               = getDerived().TransformFunctionTypeParam(OldParm,
   4180                                                         indexAdjustment++,
   4181                                                         OrigNumExpansions,
   4182                                                 /*ExpectParameterPack=*/false);
   4183             if (!NewParm)
   4184               return true;
   4185 
   4186             OutParamTypes.push_back(NewParm->getType());
   4187             if (PVars)
   4188               PVars->push_back(NewParm);
   4189           }
   4190 
   4191           // If we're supposed to retain a pack expansion, do so by temporarily
   4192           // forgetting the partially-substituted parameter pack.
   4193           if (RetainExpansion) {
   4194             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   4195             ParmVarDecl *NewParm
   4196               = getDerived().TransformFunctionTypeParam(OldParm,
   4197                                                         indexAdjustment++,
   4198                                                         OrigNumExpansions,
   4199                                                 /*ExpectParameterPack=*/false);
   4200             if (!NewParm)
   4201               return true;
   4202 
   4203             OutParamTypes.push_back(NewParm->getType());
   4204             if (PVars)
   4205               PVars->push_back(NewParm);
   4206           }
   4207 
   4208           // The next parameter should have the same adjustment as the
   4209           // last thing we pushed, but we post-incremented indexAdjustment
   4210           // on every push.  Also, if we push nothing, the adjustment should
   4211           // go down by one.
   4212           indexAdjustment--;
   4213 
   4214           // We're done with the pack expansion.
   4215           continue;
   4216         }
   4217 
   4218         // We'll substitute the parameter now without expanding the pack
   4219         // expansion.
   4220         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   4221         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
   4222                                                           indexAdjustment,
   4223                                                           NumExpansions,
   4224                                                   /*ExpectParameterPack=*/true);
   4225       } else {
   4226         NewParm = getDerived().TransformFunctionTypeParam(
   4227             OldParm, indexAdjustment, None, /*ExpectParameterPack=*/ false);
   4228       }
   4229 
   4230       if (!NewParm)
   4231         return true;
   4232 
   4233       OutParamTypes.push_back(NewParm->getType());
   4234       if (PVars)
   4235         PVars->push_back(NewParm);
   4236       continue;
   4237     }
   4238 
   4239     // Deal with the possibility that we don't have a parameter
   4240     // declaration for this parameter.
   4241     QualType OldType = ParamTypes[i];
   4242     bool IsPackExpansion = false;
   4243     Optional<unsigned> NumExpansions;
   4244     QualType NewType;
   4245     if (const PackExpansionType *Expansion
   4246                                        = dyn_cast<PackExpansionType>(OldType)) {
   4247       // We have a function parameter pack that may need to be expanded.
   4248       QualType Pattern = Expansion->getPattern();
   4249       SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   4250       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   4251 
   4252       // Determine whether we should expand the parameter packs.
   4253       bool ShouldExpand = false;
   4254       bool RetainExpansion = false;
   4255       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
   4256                                                Unexpanded,
   4257                                                ShouldExpand,
   4258                                                RetainExpansion,
   4259                                                NumExpansions)) {
   4260         return true;
   4261       }
   4262 
   4263       if (ShouldExpand) {
   4264         // Expand the function parameter pack into multiple, separate
   4265         // parameters.
   4266         for (unsigned I = 0; I != *NumExpansions; ++I) {
   4267           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   4268           QualType NewType = getDerived().TransformType(Pattern);
   4269           if (NewType.isNull())
   4270             return true;
   4271 
   4272           OutParamTypes.push_back(NewType);
   4273           if (PVars)
   4274             PVars->push_back(0);
   4275         }
   4276 
   4277         // We're done with the pack expansion.
   4278         continue;
   4279       }
   4280 
   4281       // If we're supposed to retain a pack expansion, do so by temporarily
   4282       // forgetting the partially-substituted parameter pack.
   4283       if (RetainExpansion) {
   4284         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   4285         QualType NewType = getDerived().TransformType(Pattern);
   4286         if (NewType.isNull())
   4287           return true;
   4288 
   4289         OutParamTypes.push_back(NewType);
   4290         if (PVars)
   4291           PVars->push_back(0);
   4292       }
   4293 
   4294       // We'll substitute the parameter now without expanding the pack
   4295       // expansion.
   4296       OldType = Expansion->getPattern();
   4297       IsPackExpansion = true;
   4298       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   4299       NewType = getDerived().TransformType(OldType);
   4300     } else {
   4301       NewType = getDerived().TransformType(OldType);
   4302     }
   4303 
   4304     if (NewType.isNull())
   4305       return true;
   4306 
   4307     if (IsPackExpansion)
   4308       NewType = getSema().Context.getPackExpansionType(NewType,
   4309                                                        NumExpansions);
   4310 
   4311     OutParamTypes.push_back(NewType);
   4312     if (PVars)
   4313       PVars->push_back(0);
   4314   }
   4315 
   4316 #ifndef NDEBUG
   4317   if (PVars) {
   4318     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
   4319       if (ParmVarDecl *parm = (*PVars)[i])
   4320         assert(parm->getFunctionScopeIndex() == i);
   4321   }
   4322 #endif
   4323 
   4324   return false;
   4325 }
   4326 
   4327 template<typename Derived>
   4328 QualType
   4329 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
   4330                                                    FunctionProtoTypeLoc TL) {
   4331   return getDerived().TransformFunctionProtoType(TLB, TL, 0, 0);
   4332 }
   4333 
   4334 template<typename Derived>
   4335 QualType
   4336 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
   4337                                                    FunctionProtoTypeLoc TL,
   4338                                                    CXXRecordDecl *ThisContext,
   4339                                                    unsigned ThisTypeQuals) {
   4340   // Transform the parameters and return type.
   4341   //
   4342   // We are required to instantiate the params and return type in source order.
   4343   // When the function has a trailing return type, we instantiate the
   4344   // parameters before the return type,  since the return type can then refer
   4345   // to the parameters themselves (via decltype, sizeof, etc.).
   4346   //
   4347   SmallVector<QualType, 4> ParamTypes;
   4348   SmallVector<ParmVarDecl*, 4> ParamDecls;
   4349   const FunctionProtoType *T = TL.getTypePtr();
   4350 
   4351   QualType ResultType;
   4352 
   4353   if (T->hasTrailingReturn()) {
   4354     if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
   4355                                                  TL.getParmArray(),
   4356                                                  TL.getNumArgs(),
   4357                                              TL.getTypePtr()->arg_type_begin(),
   4358                                                  ParamTypes, &ParamDecls))
   4359       return QualType();
   4360 
   4361     {
   4362       // C++11 [expr.prim.general]p3:
   4363       //   If a declaration declares a member function or member function
   4364       //   template of a class X, the expression this is a prvalue of type
   4365       //   "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
   4366       //   and the end of the function-definition, member-declarator, or
   4367       //   declarator.
   4368       Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
   4369 
   4370       ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
   4371       if (ResultType.isNull())
   4372         return QualType();
   4373     }
   4374   }
   4375   else {
   4376     ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
   4377     if (ResultType.isNull())
   4378       return QualType();
   4379 
   4380     if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
   4381                                                  TL.getParmArray(),
   4382                                                  TL.getNumArgs(),
   4383                                              TL.getTypePtr()->arg_type_begin(),
   4384                                                  ParamTypes, &ParamDecls))
   4385       return QualType();
   4386   }
   4387 
   4388   // FIXME: Need to transform the exception-specification too.
   4389 
   4390   QualType Result = TL.getType();
   4391   if (getDerived().AlwaysRebuild() ||
   4392       ResultType != T->getResultType() ||
   4393       T->getNumArgs() != ParamTypes.size() ||
   4394       !std::equal(T->arg_type_begin(), T->arg_type_end(), ParamTypes.begin())) {
   4395     Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes,
   4396                                                    T->getExtProtoInfo());
   4397     if (Result.isNull())
   4398       return QualType();
   4399   }
   4400 
   4401   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
   4402   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
   4403   NewTL.setLParenLoc(TL.getLParenLoc());
   4404   NewTL.setRParenLoc(TL.getRParenLoc());
   4405   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
   4406   for (unsigned i = 0, e = NewTL.getNumArgs(); i != e; ++i)
   4407     NewTL.setArg(i, ParamDecls[i]);
   4408 
   4409   return Result;
   4410 }
   4411 
   4412 template<typename Derived>
   4413 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
   4414                                                  TypeLocBuilder &TLB,
   4415                                                  FunctionNoProtoTypeLoc TL) {
   4416   const FunctionNoProtoType *T = TL.getTypePtr();
   4417   QualType ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
   4418   if (ResultType.isNull())
   4419     return QualType();
   4420 
   4421   QualType Result = TL.getType();
   4422   if (getDerived().AlwaysRebuild() ||
   4423       ResultType != T->getResultType())
   4424     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
   4425 
   4426   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
   4427   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
   4428   NewTL.setLParenLoc(TL.getLParenLoc());
   4429   NewTL.setRParenLoc(TL.getRParenLoc());
   4430   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
   4431 
   4432   return Result;
   4433 }
   4434 
   4435 template<typename Derived> QualType
   4436 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
   4437                                                  UnresolvedUsingTypeLoc TL) {
   4438   const UnresolvedUsingType *T = TL.getTypePtr();
   4439   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
   4440   if (!D)
   4441     return QualType();
   4442 
   4443   QualType Result = TL.getType();
   4444   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
   4445     Result = getDerived().RebuildUnresolvedUsingType(D);
   4446     if (Result.isNull())
   4447       return QualType();
   4448   }
   4449 
   4450   // We might get an arbitrary type spec type back.  We should at
   4451   // least always get a type spec type, though.
   4452   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
   4453   NewTL.setNameLoc(TL.getNameLoc());
   4454 
   4455   return Result;
   4456 }
   4457 
   4458 template<typename Derived>
   4459 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
   4460                                                       TypedefTypeLoc TL) {
   4461   const TypedefType *T = TL.getTypePtr();
   4462   TypedefNameDecl *Typedef
   4463     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   4464                                                                T->getDecl()));
   4465   if (!Typedef)
   4466     return QualType();
   4467 
   4468   QualType Result = TL.getType();
   4469   if (getDerived().AlwaysRebuild() ||
   4470       Typedef != T->getDecl()) {
   4471     Result = getDerived().RebuildTypedefType(Typedef);
   4472     if (Result.isNull())
   4473       return QualType();
   4474   }
   4475 
   4476   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
   4477   NewTL.setNameLoc(TL.getNameLoc());
   4478 
   4479   return Result;
   4480 }
   4481 
   4482 template<typename Derived>
   4483 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
   4484                                                       TypeOfExprTypeLoc TL) {
   4485   // typeof expressions are not potentially evaluated contexts
   4486   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated,
   4487                                                Sema::ReuseLambdaContextDecl);
   4488 
   4489   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
   4490   if (E.isInvalid())
   4491     return QualType();
   4492 
   4493   E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
   4494   if (E.isInvalid())
   4495     return QualType();
   4496 
   4497   QualType Result = TL.getType();
   4498   if (getDerived().AlwaysRebuild() ||
   4499       E.get() != TL.getUnderlyingExpr()) {
   4500     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
   4501     if (Result.isNull())
   4502       return QualType();
   4503   }
   4504   else E.take();
   4505 
   4506   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
   4507   NewTL.setTypeofLoc(TL.getTypeofLoc());
   4508   NewTL.setLParenLoc(TL.getLParenLoc());
   4509   NewTL.setRParenLoc(TL.getRParenLoc());
   4510 
   4511   return Result;
   4512 }
   4513 
   4514 template<typename Derived>
   4515 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
   4516                                                      TypeOfTypeLoc TL) {
   4517   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
   4518   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
   4519   if (!New_Under_TI)
   4520     return QualType();
   4521 
   4522   QualType Result = TL.getType();
   4523   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
   4524     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
   4525     if (Result.isNull())
   4526       return QualType();
   4527   }
   4528 
   4529   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
   4530   NewTL.setTypeofLoc(TL.getTypeofLoc());
   4531   NewTL.setLParenLoc(TL.getLParenLoc());
   4532   NewTL.setRParenLoc(TL.getRParenLoc());
   4533   NewTL.setUnderlyingTInfo(New_Under_TI);
   4534 
   4535   return Result;
   4536 }
   4537 
   4538 template<typename Derived>
   4539 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
   4540                                                        DecltypeTypeLoc TL) {
   4541   const DecltypeType *T = TL.getTypePtr();
   4542 
   4543   // decltype expressions are not potentially evaluated contexts
   4544   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated, 0,
   4545                                                /*IsDecltype=*/ true);
   4546 
   4547   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
   4548   if (E.isInvalid())
   4549     return QualType();
   4550 
   4551   E = getSema().ActOnDecltypeExpression(E.take());
   4552   if (E.isInvalid())
   4553     return QualType();
   4554 
   4555   QualType Result = TL.getType();
   4556   if (getDerived().AlwaysRebuild() ||
   4557       E.get() != T->getUnderlyingExpr()) {
   4558     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
   4559     if (Result.isNull())
   4560       return QualType();
   4561   }
   4562   else E.take();
   4563 
   4564   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
   4565   NewTL.setNameLoc(TL.getNameLoc());
   4566 
   4567   return Result;
   4568 }
   4569 
   4570 template<typename Derived>
   4571 QualType TreeTransform<Derived>::TransformUnaryTransformType(
   4572                                                             TypeLocBuilder &TLB,
   4573                                                      UnaryTransformTypeLoc TL) {
   4574   QualType Result = TL.getType();
   4575   if (Result->isDependentType()) {
   4576     const UnaryTransformType *T = TL.getTypePtr();
   4577     QualType NewBase =
   4578       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
   4579     Result = getDerived().RebuildUnaryTransformType(NewBase,
   4580                                                     T->getUTTKind(),
   4581                                                     TL.getKWLoc());
   4582     if (Result.isNull())
   4583       return QualType();
   4584   }
   4585 
   4586   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
   4587   NewTL.setKWLoc(TL.getKWLoc());
   4588   NewTL.setParensRange(TL.getParensRange());
   4589   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
   4590   return Result;
   4591 }
   4592 
   4593 template<typename Derived>
   4594 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
   4595                                                    AutoTypeLoc TL) {
   4596   const AutoType *T = TL.getTypePtr();
   4597   QualType OldDeduced = T->getDeducedType();
   4598   QualType NewDeduced;
   4599   if (!OldDeduced.isNull()) {
   4600     NewDeduced = getDerived().TransformType(OldDeduced);
   4601     if (NewDeduced.isNull())
   4602       return QualType();
   4603   }
   4604 
   4605   QualType Result = TL.getType();
   4606   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
   4607       T->isDependentType()) {
   4608     Result = getDerived().RebuildAutoType(NewDeduced, T->isDecltypeAuto());
   4609     if (Result.isNull())
   4610       return QualType();
   4611   }
   4612 
   4613   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
   4614   NewTL.setNameLoc(TL.getNameLoc());
   4615 
   4616   return Result;
   4617 }
   4618 
   4619 template<typename Derived>
   4620 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
   4621                                                      RecordTypeLoc TL) {
   4622   const RecordType *T = TL.getTypePtr();
   4623   RecordDecl *Record
   4624     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   4625                                                           T->getDecl()));
   4626   if (!Record)
   4627     return QualType();
   4628 
   4629   QualType Result = TL.getType();
   4630   if (getDerived().AlwaysRebuild() ||
   4631       Record != T->getDecl()) {
   4632     Result = getDerived().RebuildRecordType(Record);
   4633     if (Result.isNull())
   4634       return QualType();
   4635   }
   4636 
   4637   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
   4638   NewTL.setNameLoc(TL.getNameLoc());
   4639 
   4640   return Result;
   4641 }
   4642 
   4643 template<typename Derived>
   4644 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
   4645                                                    EnumTypeLoc TL) {
   4646   const EnumType *T = TL.getTypePtr();
   4647   EnumDecl *Enum
   4648     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   4649                                                         T->getDecl()));
   4650   if (!Enum)
   4651     return QualType();
   4652 
   4653   QualType Result = TL.getType();
   4654   if (getDerived().AlwaysRebuild() ||
   4655       Enum != T->getDecl()) {
   4656     Result = getDerived().RebuildEnumType(Enum);
   4657     if (Result.isNull())
   4658       return QualType();
   4659   }
   4660 
   4661   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
   4662   NewTL.setNameLoc(TL.getNameLoc());
   4663 
   4664   return Result;
   4665 }
   4666 
   4667 template<typename Derived>
   4668 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
   4669                                          TypeLocBuilder &TLB,
   4670                                          InjectedClassNameTypeLoc TL) {
   4671   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
   4672                                        TL.getTypePtr()->getDecl());
   4673   if (!D) return QualType();
   4674 
   4675   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
   4676   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
   4677   return T;
   4678 }
   4679 
   4680 template<typename Derived>
   4681 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
   4682                                                 TypeLocBuilder &TLB,
   4683                                                 TemplateTypeParmTypeLoc TL) {
   4684   return TransformTypeSpecType(TLB, TL);
   4685 }
   4686 
   4687 template<typename Derived>
   4688 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
   4689                                          TypeLocBuilder &TLB,
   4690                                          SubstTemplateTypeParmTypeLoc TL) {
   4691   const SubstTemplateTypeParmType *T = TL.getTypePtr();
   4692 
   4693   // Substitute into the replacement type, which itself might involve something
   4694   // that needs to be transformed. This only tends to occur with default
   4695   // template arguments of template template parameters.
   4696   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
   4697   QualType Replacement = getDerived().TransformType(T->getReplacementType());
   4698   if (Replacement.isNull())
   4699     return QualType();
   4700 
   4701   // Always canonicalize the replacement type.
   4702   Replacement = SemaRef.Context.getCanonicalType(Replacement);
   4703   QualType Result
   4704     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
   4705                                                    Replacement);
   4706 
   4707   // Propagate type-source information.
   4708   SubstTemplateTypeParmTypeLoc NewTL
   4709     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
   4710   NewTL.setNameLoc(TL.getNameLoc());
   4711   return Result;
   4712 
   4713 }
   4714 
   4715 template<typename Derived>
   4716 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
   4717                                           TypeLocBuilder &TLB,
   4718                                           SubstTemplateTypeParmPackTypeLoc TL) {
   4719   return TransformTypeSpecType(TLB, TL);
   4720 }
   4721 
   4722 template<typename Derived>
   4723 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
   4724                                                         TypeLocBuilder &TLB,
   4725                                            TemplateSpecializationTypeLoc TL) {
   4726   const TemplateSpecializationType *T = TL.getTypePtr();
   4727 
   4728   // The nested-name-specifier never matters in a TemplateSpecializationType,
   4729   // because we can't have a dependent nested-name-specifier anyway.
   4730   CXXScopeSpec SS;
   4731   TemplateName Template
   4732     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
   4733                                          TL.getTemplateNameLoc());
   4734   if (Template.isNull())
   4735     return QualType();
   4736 
   4737   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
   4738 }
   4739 
   4740 template<typename Derived>
   4741 QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
   4742                                                      AtomicTypeLoc TL) {
   4743   QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
   4744   if (ValueType.isNull())
   4745     return QualType();
   4746 
   4747   QualType Result = TL.getType();
   4748   if (getDerived().AlwaysRebuild() ||
   4749       ValueType != TL.getValueLoc().getType()) {
   4750     Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
   4751     if (Result.isNull())
   4752       return QualType();
   4753   }
   4754 
   4755   AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
   4756   NewTL.setKWLoc(TL.getKWLoc());
   4757   NewTL.setLParenLoc(TL.getLParenLoc());
   4758   NewTL.setRParenLoc(TL.getRParenLoc());
   4759 
   4760   return Result;
   4761 }
   4762 
   4763   /// \brief Simple iterator that traverses the template arguments in a
   4764   /// container that provides a \c getArgLoc() member function.
   4765   ///
   4766   /// This iterator is intended to be used with the iterator form of
   4767   /// \c TreeTransform<Derived>::TransformTemplateArguments().
   4768   template<typename ArgLocContainer>
   4769   class TemplateArgumentLocContainerIterator {
   4770     ArgLocContainer *Container;
   4771     unsigned Index;
   4772 
   4773   public:
   4774     typedef TemplateArgumentLoc value_type;
   4775     typedef TemplateArgumentLoc reference;
   4776     typedef int difference_type;
   4777     typedef std::input_iterator_tag iterator_category;
   4778 
   4779     class pointer {
   4780       TemplateArgumentLoc Arg;
   4781 
   4782     public:
   4783       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
   4784 
   4785       const TemplateArgumentLoc *operator->() const {
   4786         return &Arg;
   4787       }
   4788     };
   4789 
   4790 
   4791     TemplateArgumentLocContainerIterator() {}
   4792 
   4793     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
   4794                                  unsigned Index)
   4795       : Container(&Container), Index(Index) { }
   4796 
   4797     TemplateArgumentLocContainerIterator &operator++() {
   4798       ++Index;
   4799       return *this;
   4800     }
   4801 
   4802     TemplateArgumentLocContainerIterator operator++(int) {
   4803       TemplateArgumentLocContainerIterator Old(*this);
   4804       ++(*this);
   4805       return Old;
   4806     }
   4807 
   4808     TemplateArgumentLoc operator*() const {
   4809       return Container->getArgLoc(Index);
   4810     }
   4811 
   4812     pointer operator->() const {
   4813       return pointer(Container->getArgLoc(Index));
   4814     }
   4815 
   4816     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
   4817                            const TemplateArgumentLocContainerIterator &Y) {
   4818       return X.Container == Y.Container && X.Index == Y.Index;
   4819     }
   4820 
   4821     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
   4822                            const TemplateArgumentLocContainerIterator &Y) {
   4823       return !(X == Y);
   4824     }
   4825   };
   4826 
   4827 
   4828 template <typename Derived>
   4829 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
   4830                                                         TypeLocBuilder &TLB,
   4831                                            TemplateSpecializationTypeLoc TL,
   4832                                                       TemplateName Template) {
   4833   TemplateArgumentListInfo NewTemplateArgs;
   4834   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   4835   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   4836   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
   4837     ArgIterator;
   4838   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   4839                                               ArgIterator(TL, TL.getNumArgs()),
   4840                                               NewTemplateArgs))
   4841     return QualType();
   4842 
   4843   // FIXME: maybe don't rebuild if all the template arguments are the same.
   4844 
   4845   QualType Result =
   4846     getDerived().RebuildTemplateSpecializationType(Template,
   4847                                                    TL.getTemplateNameLoc(),
   4848                                                    NewTemplateArgs);
   4849 
   4850   if (!Result.isNull()) {
   4851     // Specializations of template template parameters are represented as
   4852     // TemplateSpecializationTypes, and substitution of type alias templates
   4853     // within a dependent context can transform them into
   4854     // DependentTemplateSpecializationTypes.
   4855     if (isa<DependentTemplateSpecializationType>(Result)) {
   4856       DependentTemplateSpecializationTypeLoc NewTL
   4857         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   4858       NewTL.setElaboratedKeywordLoc(SourceLocation());
   4859       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
   4860       NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   4861       NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   4862       NewTL.setLAngleLoc(TL.getLAngleLoc());
   4863       NewTL.setRAngleLoc(TL.getRAngleLoc());
   4864       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4865         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4866       return Result;
   4867     }
   4868 
   4869     TemplateSpecializationTypeLoc NewTL
   4870       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   4871     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   4872     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   4873     NewTL.setLAngleLoc(TL.getLAngleLoc());
   4874     NewTL.setRAngleLoc(TL.getRAngleLoc());
   4875     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4876       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4877   }
   4878 
   4879   return Result;
   4880 }
   4881 
   4882 template <typename Derived>
   4883 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
   4884                                      TypeLocBuilder &TLB,
   4885                                      DependentTemplateSpecializationTypeLoc TL,
   4886                                      TemplateName Template,
   4887                                      CXXScopeSpec &SS) {
   4888   TemplateArgumentListInfo NewTemplateArgs;
   4889   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   4890   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   4891   typedef TemplateArgumentLocContainerIterator<
   4892             DependentTemplateSpecializationTypeLoc> ArgIterator;
   4893   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   4894                                               ArgIterator(TL, TL.getNumArgs()),
   4895                                               NewTemplateArgs))
   4896     return QualType();
   4897 
   4898   // FIXME: maybe don't rebuild if all the template arguments are the same.
   4899 
   4900   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
   4901     QualType Result
   4902       = getSema().Context.getDependentTemplateSpecializationType(
   4903                                                 TL.getTypePtr()->getKeyword(),
   4904                                                          DTN->getQualifier(),
   4905                                                          DTN->getIdentifier(),
   4906                                                                NewTemplateArgs);
   4907 
   4908     DependentTemplateSpecializationTypeLoc NewTL
   4909       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   4910     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   4911     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
   4912     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   4913     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   4914     NewTL.setLAngleLoc(TL.getLAngleLoc());
   4915     NewTL.setRAngleLoc(TL.getRAngleLoc());
   4916     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4917       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4918     return Result;
   4919   }
   4920 
   4921   QualType Result
   4922     = getDerived().RebuildTemplateSpecializationType(Template,
   4923                                                      TL.getTemplateNameLoc(),
   4924                                                      NewTemplateArgs);
   4925 
   4926   if (!Result.isNull()) {
   4927     /// FIXME: Wrap this in an elaborated-type-specifier?
   4928     TemplateSpecializationTypeLoc NewTL
   4929       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   4930     NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   4931     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   4932     NewTL.setLAngleLoc(TL.getLAngleLoc());
   4933     NewTL.setRAngleLoc(TL.getRAngleLoc());
   4934     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4935       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4936   }
   4937 
   4938   return Result;
   4939 }
   4940 
   4941 template<typename Derived>
   4942 QualType
   4943 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
   4944                                                 ElaboratedTypeLoc TL) {
   4945   const ElaboratedType *T = TL.getTypePtr();
   4946 
   4947   NestedNameSpecifierLoc QualifierLoc;
   4948   // NOTE: the qualifier in an ElaboratedType is optional.
   4949   if (TL.getQualifierLoc()) {
   4950     QualifierLoc
   4951       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   4952     if (!QualifierLoc)
   4953       return QualType();
   4954   }
   4955 
   4956   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
   4957   if (NamedT.isNull())
   4958     return QualType();
   4959 
   4960   // C++0x [dcl.type.elab]p2:
   4961   //   If the identifier resolves to a typedef-name or the simple-template-id
   4962   //   resolves to an alias template specialization, the
   4963   //   elaborated-type-specifier is ill-formed.
   4964   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
   4965     if (const TemplateSpecializationType *TST =
   4966           NamedT->getAs<TemplateSpecializationType>()) {
   4967       TemplateName Template = TST->getTemplateName();
   4968       if (TypeAliasTemplateDecl *TAT =
   4969           dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
   4970         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
   4971                      diag::err_tag_reference_non_tag) << 4;
   4972         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
   4973       }
   4974     }
   4975   }
   4976 
   4977   QualType Result = TL.getType();
   4978   if (getDerived().AlwaysRebuild() ||
   4979       QualifierLoc != TL.getQualifierLoc() ||
   4980       NamedT != T->getNamedType()) {
   4981     Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
   4982                                                 T->getKeyword(),
   4983                                                 QualifierLoc, NamedT);
   4984     if (Result.isNull())
   4985       return QualType();
   4986   }
   4987 
   4988   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   4989   NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   4990   NewTL.setQualifierLoc(QualifierLoc);
   4991   return Result;
   4992 }
   4993 
   4994 template<typename Derived>
   4995 QualType TreeTransform<Derived>::TransformAttributedType(
   4996                                                 TypeLocBuilder &TLB,
   4997                                                 AttributedTypeLoc TL) {
   4998   const AttributedType *oldType = TL.getTypePtr();
   4999   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
   5000   if (modifiedType.isNull())
   5001     return QualType();
   5002 
   5003   QualType result = TL.getType();
   5004 
   5005   // FIXME: dependent operand expressions?
   5006   if (getDerived().AlwaysRebuild() ||
   5007       modifiedType != oldType->getModifiedType()) {
   5008     // TODO: this is really lame; we should really be rebuilding the
   5009     // equivalent type from first principles.
   5010     QualType equivalentType
   5011       = getDerived().TransformType(oldType->getEquivalentType());
   5012     if (equivalentType.isNull())
   5013       return QualType();
   5014     result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
   5015                                                modifiedType,
   5016                                                equivalentType);
   5017   }
   5018 
   5019   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
   5020   newTL.setAttrNameLoc(TL.getAttrNameLoc());
   5021   if (TL.hasAttrOperand())
   5022     newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
   5023   if (TL.hasAttrExprOperand())
   5024     newTL.setAttrExprOperand(TL.getAttrExprOperand());
   5025   else if (TL.hasAttrEnumOperand())
   5026     newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
   5027 
   5028   return result;
   5029 }
   5030 
   5031 template<typename Derived>
   5032 QualType
   5033 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
   5034                                            ParenTypeLoc TL) {
   5035   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
   5036   if (Inner.isNull())
   5037     return QualType();
   5038 
   5039   QualType Result = TL.getType();
   5040   if (getDerived().AlwaysRebuild() ||
   5041       Inner != TL.getInnerLoc().getType()) {
   5042     Result = getDerived().RebuildParenType(Inner);
   5043     if (Result.isNull())
   5044       return QualType();
   5045   }
   5046 
   5047   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
   5048   NewTL.setLParenLoc(TL.getLParenLoc());
   5049   NewTL.setRParenLoc(TL.getRParenLoc());
   5050   return Result;
   5051 }
   5052 
   5053 template<typename Derived>
   5054 QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
   5055                                                       DependentNameTypeLoc TL) {
   5056   const DependentNameType *T = TL.getTypePtr();
   5057 
   5058   NestedNameSpecifierLoc QualifierLoc
   5059     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   5060   if (!QualifierLoc)
   5061     return QualType();
   5062 
   5063   QualType Result
   5064     = getDerived().RebuildDependentNameType(T->getKeyword(),
   5065                                             TL.getElaboratedKeywordLoc(),
   5066                                             QualifierLoc,
   5067                                             T->getIdentifier(),
   5068                                             TL.getNameLoc());
   5069   if (Result.isNull())
   5070     return QualType();
   5071 
   5072   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
   5073     QualType NamedT = ElabT->getNamedType();
   5074     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
   5075 
   5076     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   5077     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5078     NewTL.setQualifierLoc(QualifierLoc);
   5079   } else {
   5080     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
   5081     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5082     NewTL.setQualifierLoc(QualifierLoc);
   5083     NewTL.setNameLoc(TL.getNameLoc());
   5084   }
   5085   return Result;
   5086 }
   5087 
   5088 template<typename Derived>
   5089 QualType TreeTransform<Derived>::
   5090           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
   5091                                  DependentTemplateSpecializationTypeLoc TL) {
   5092   NestedNameSpecifierLoc QualifierLoc;
   5093   if (TL.getQualifierLoc()) {
   5094     QualifierLoc
   5095       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   5096     if (!QualifierLoc)
   5097       return QualType();
   5098   }
   5099 
   5100   return getDerived()
   5101            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
   5102 }
   5103 
   5104 template<typename Derived>
   5105 QualType TreeTransform<Derived>::
   5106 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
   5107                                    DependentTemplateSpecializationTypeLoc TL,
   5108                                        NestedNameSpecifierLoc QualifierLoc) {
   5109   const DependentTemplateSpecializationType *T = TL.getTypePtr();
   5110 
   5111   TemplateArgumentListInfo NewTemplateArgs;
   5112   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   5113   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   5114 
   5115   typedef TemplateArgumentLocContainerIterator<
   5116   DependentTemplateSpecializationTypeLoc> ArgIterator;
   5117   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   5118                                               ArgIterator(TL, TL.getNumArgs()),
   5119                                               NewTemplateArgs))
   5120     return QualType();
   5121 
   5122   QualType Result
   5123     = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
   5124                                                               QualifierLoc,
   5125                                                             T->getIdentifier(),
   5126                                                        TL.getTemplateNameLoc(),
   5127                                                             NewTemplateArgs);
   5128   if (Result.isNull())
   5129     return QualType();
   5130 
   5131   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
   5132     QualType NamedT = ElabT->getNamedType();
   5133 
   5134     // Copy information relevant to the template specialization.
   5135     TemplateSpecializationTypeLoc NamedTL
   5136       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
   5137     NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5138     NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5139     NamedTL.setLAngleLoc(TL.getLAngleLoc());
   5140     NamedTL.setRAngleLoc(TL.getRAngleLoc());
   5141     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   5142       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   5143 
   5144     // Copy information relevant to the elaborated type.
   5145     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   5146     NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5147     NewTL.setQualifierLoc(QualifierLoc);
   5148   } else if (isa<DependentTemplateSpecializationType>(Result)) {
   5149     DependentTemplateSpecializationTypeLoc SpecTL
   5150       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   5151     SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
   5152     SpecTL.setQualifierLoc(QualifierLoc);
   5153     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5154     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5155     SpecTL.setLAngleLoc(TL.getLAngleLoc());
   5156     SpecTL.setRAngleLoc(TL.getRAngleLoc());
   5157     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   5158       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   5159   } else {
   5160     TemplateSpecializationTypeLoc SpecTL
   5161       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   5162     SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
   5163     SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   5164     SpecTL.setLAngleLoc(TL.getLAngleLoc());
   5165     SpecTL.setRAngleLoc(TL.getRAngleLoc());
   5166     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   5167       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   5168   }
   5169   return Result;
   5170 }
   5171 
   5172 template<typename Derived>
   5173 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
   5174                                                       PackExpansionTypeLoc TL) {
   5175   QualType Pattern
   5176     = getDerived().TransformType(TLB, TL.getPatternLoc());
   5177   if (Pattern.isNull())
   5178     return QualType();
   5179 
   5180   QualType Result = TL.getType();
   5181   if (getDerived().AlwaysRebuild() ||
   5182       Pattern != TL.getPatternLoc().getType()) {
   5183     Result = getDerived().RebuildPackExpansionType(Pattern,
   5184                                            TL.getPatternLoc().getSourceRange(),
   5185                                                    TL.getEllipsisLoc(),
   5186                                            TL.getTypePtr()->getNumExpansions());
   5187     if (Result.isNull())
   5188       return QualType();
   5189   }
   5190 
   5191   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
   5192   NewT.setEllipsisLoc(TL.getEllipsisLoc());
   5193   return Result;
   5194 }
   5195 
   5196 template<typename Derived>
   5197 QualType
   5198 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
   5199                                                    ObjCInterfaceTypeLoc TL) {
   5200   // ObjCInterfaceType is never dependent.
   5201   TLB.pushFullCopy(TL);
   5202   return TL.getType();
   5203 }
   5204 
   5205 template<typename Derived>
   5206 QualType
   5207 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
   5208                                                 ObjCObjectTypeLoc TL) {
   5209   // ObjCObjectType is never dependent.
   5210   TLB.pushFullCopy(TL);
   5211   return TL.getType();
   5212 }
   5213 
   5214 template<typename Derived>
   5215 QualType
   5216 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
   5217                                                ObjCObjectPointerTypeLoc TL) {
   5218   // ObjCObjectPointerType is never dependent.
   5219   TLB.pushFullCopy(TL);
   5220   return TL.getType();
   5221 }
   5222 
   5223 //===----------------------------------------------------------------------===//
   5224 // Statement transformation
   5225 //===----------------------------------------------------------------------===//
   5226 template<typename Derived>
   5227 StmtResult
   5228 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
   5229   return SemaRef.Owned(S);
   5230 }
   5231 
   5232 template<typename Derived>
   5233 StmtResult
   5234 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
   5235   return getDerived().TransformCompoundStmt(S, false);
   5236 }
   5237 
   5238 template<typename Derived>
   5239 StmtResult
   5240 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
   5241                                               bool IsStmtExpr) {
   5242   Sema::CompoundScopeRAII CompoundScope(getSema());
   5243 
   5244   bool SubStmtInvalid = false;
   5245   bool SubStmtChanged = false;
   5246   SmallVector<Stmt*, 8> Statements;
   5247   for (CompoundStmt::body_iterator B = S->body_begin(), BEnd = S->body_end();
   5248        B != BEnd; ++B) {
   5249     StmtResult Result = getDerived().TransformStmt(*B);
   5250     if (Result.isInvalid()) {
   5251       // Immediately fail if this was a DeclStmt, since it's very
   5252       // likely that this will cause problems for future statements.
   5253       if (isa<DeclStmt>(*B))
   5254         return StmtError();
   5255 
   5256       // Otherwise, just keep processing substatements and fail later.
   5257       SubStmtInvalid = true;
   5258       continue;
   5259     }
   5260 
   5261     SubStmtChanged = SubStmtChanged || Result.get() != *B;
   5262     Statements.push_back(Result.takeAs<Stmt>());
   5263   }
   5264 
   5265   if (SubStmtInvalid)
   5266     return StmtError();
   5267 
   5268   if (!getDerived().AlwaysRebuild() &&
   5269       !SubStmtChanged)
   5270     return SemaRef.Owned(S);
   5271 
   5272   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
   5273                                           Statements,
   5274                                           S->getRBracLoc(),
   5275                                           IsStmtExpr);
   5276 }
   5277 
   5278 template<typename Derived>
   5279 StmtResult
   5280 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
   5281   ExprResult LHS, RHS;
   5282   {
   5283     EnterExpressionEvaluationContext Unevaluated(SemaRef,
   5284                                                  Sema::ConstantEvaluated);
   5285 
   5286     // Transform the left-hand case value.
   5287     LHS = getDerived().TransformExpr(S->getLHS());
   5288     LHS = SemaRef.ActOnConstantExpression(LHS);
   5289     if (LHS.isInvalid())
   5290       return StmtError();
   5291 
   5292     // Transform the right-hand case value (for the GNU case-range extension).
   5293     RHS = getDerived().TransformExpr(S->getRHS());
   5294     RHS = SemaRef.ActOnConstantExpression(RHS);
   5295     if (RHS.isInvalid())
   5296       return StmtError();
   5297   }
   5298 
   5299   // Build the case statement.
   5300   // Case statements are always rebuilt so that they will attached to their
   5301   // transformed switch statement.
   5302   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
   5303                                                        LHS.get(),
   5304                                                        S->getEllipsisLoc(),
   5305                                                        RHS.get(),
   5306                                                        S->getColonLoc());
   5307   if (Case.isInvalid())
   5308     return StmtError();
   5309 
   5310   // Transform the statement following the case
   5311   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   5312   if (SubStmt.isInvalid())
   5313     return StmtError();
   5314 
   5315   // Attach the body to the case statement
   5316   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
   5317 }
   5318 
   5319 template<typename Derived>
   5320 StmtResult
   5321 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
   5322   // Transform the statement following the default case
   5323   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   5324   if (SubStmt.isInvalid())
   5325     return StmtError();
   5326 
   5327   // Default statements are always rebuilt
   5328   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
   5329                                          SubStmt.get());
   5330 }
   5331 
   5332 template<typename Derived>
   5333 StmtResult
   5334 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
   5335   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   5336   if (SubStmt.isInvalid())
   5337     return StmtError();
   5338 
   5339   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
   5340                                         S->getDecl());
   5341   if (!LD)
   5342     return StmtError();
   5343 
   5344 
   5345   // FIXME: Pass the real colon location in.
   5346   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
   5347                                        cast<LabelDecl>(LD), SourceLocation(),
   5348                                        SubStmt.get());
   5349 }
   5350 
   5351 template<typename Derived>
   5352 StmtResult
   5353 TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S) {
   5354   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   5355   if (SubStmt.isInvalid())
   5356     return StmtError();
   5357 
   5358   // TODO: transform attributes
   5359   if (SubStmt.get() == S->getSubStmt() /* && attrs are the same */)
   5360     return S;
   5361 
   5362   return getDerived().RebuildAttributedStmt(S->getAttrLoc(),
   5363                                             S->getAttrs(),
   5364                                             SubStmt.get());
   5365 }
   5366 
   5367 template<typename Derived>
   5368 StmtResult
   5369 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
   5370   // Transform the condition
   5371   ExprResult Cond;
   5372   VarDecl *ConditionVar = 0;
   5373   if (S->getConditionVariable()) {
   5374     ConditionVar
   5375       = cast_or_null<VarDecl>(
   5376                    getDerived().TransformDefinition(
   5377                                       S->getConditionVariable()->getLocation(),
   5378                                                     S->getConditionVariable()));
   5379     if (!ConditionVar)
   5380       return StmtError();
   5381   } else {
   5382     Cond = getDerived().TransformExpr(S->getCond());
   5383 
   5384     if (Cond.isInvalid())
   5385       return StmtError();
   5386 
   5387     // Convert the condition to a boolean value.
   5388     if (S->getCond()) {
   5389       ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getIfLoc(),
   5390                                                          Cond.get());
   5391       if (CondE.isInvalid())
   5392         return StmtError();
   5393 
   5394       Cond = CondE.get();
   5395     }
   5396   }
   5397 
   5398   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
   5399   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   5400     return StmtError();
   5401 
   5402   // Transform the "then" branch.
   5403   StmtResult Then = getDerived().TransformStmt(S->getThen());
   5404   if (Then.isInvalid())
   5405     return StmtError();
   5406 
   5407   // Transform the "else" branch.
   5408   StmtResult Else = getDerived().TransformStmt(S->getElse());
   5409   if (Else.isInvalid())
   5410     return StmtError();
   5411 
   5412   if (!getDerived().AlwaysRebuild() &&
   5413       FullCond.get() == S->getCond() &&
   5414       ConditionVar == S->getConditionVariable() &&
   5415       Then.get() == S->getThen() &&
   5416       Else.get() == S->getElse())
   5417     return SemaRef.Owned(S);
   5418 
   5419   return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
   5420                                     Then.get(),
   5421                                     S->getElseLoc(), Else.get());
   5422 }
   5423 
   5424 template<typename Derived>
   5425 StmtResult
   5426 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
   5427   // Transform the condition.
   5428   ExprResult Cond;
   5429   VarDecl *ConditionVar = 0;
   5430   if (S->getConditionVariable()) {
   5431     ConditionVar
   5432       = cast_or_null<VarDecl>(
   5433                    getDerived().TransformDefinition(
   5434                                       S->getConditionVariable()->getLocation(),
   5435                                                     S->getConditionVariable()));
   5436     if (!ConditionVar)
   5437       return StmtError();
   5438   } else {
   5439     Cond = getDerived().TransformExpr(S->getCond());
   5440 
   5441     if (Cond.isInvalid())
   5442       return StmtError();
   5443   }
   5444 
   5445   // Rebuild the switch statement.
   5446   StmtResult Switch
   5447     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
   5448                                           ConditionVar);
   5449   if (Switch.isInvalid())
   5450     return StmtError();
   5451 
   5452   // Transform the body of the switch statement.
   5453   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5454   if (Body.isInvalid())
   5455     return StmtError();
   5456 
   5457   // Complete the switch statement.
   5458   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
   5459                                             Body.get());
   5460 }
   5461 
   5462 template<typename Derived>
   5463 StmtResult
   5464 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
   5465   // Transform the condition
   5466   ExprResult Cond;
   5467   VarDecl *ConditionVar = 0;
   5468   if (S->getConditionVariable()) {
   5469     ConditionVar
   5470       = cast_or_null<VarDecl>(
   5471                    getDerived().TransformDefinition(
   5472                                       S->getConditionVariable()->getLocation(),
   5473                                                     S->getConditionVariable()));
   5474     if (!ConditionVar)
   5475       return StmtError();
   5476   } else {
   5477     Cond = getDerived().TransformExpr(S->getCond());
   5478 
   5479     if (Cond.isInvalid())
   5480       return StmtError();
   5481 
   5482     if (S->getCond()) {
   5483       // Convert the condition to a boolean value.
   5484       ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getWhileLoc(),
   5485                                                          Cond.get());
   5486       if (CondE.isInvalid())
   5487         return StmtError();
   5488       Cond = CondE;
   5489     }
   5490   }
   5491 
   5492   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
   5493   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   5494     return StmtError();
   5495 
   5496   // Transform the body
   5497   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5498   if (Body.isInvalid())
   5499     return StmtError();
   5500 
   5501   if (!getDerived().AlwaysRebuild() &&
   5502       FullCond.get() == S->getCond() &&
   5503       ConditionVar == S->getConditionVariable() &&
   5504       Body.get() == S->getBody())
   5505     return Owned(S);
   5506 
   5507   return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
   5508                                        ConditionVar, Body.get());
   5509 }
   5510 
   5511 template<typename Derived>
   5512 StmtResult
   5513 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
   5514   // Transform the body
   5515   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5516   if (Body.isInvalid())
   5517     return StmtError();
   5518 
   5519   // Transform the condition
   5520   ExprResult Cond = getDerived().TransformExpr(S->getCond());
   5521   if (Cond.isInvalid())
   5522     return StmtError();
   5523 
   5524   if (!getDerived().AlwaysRebuild() &&
   5525       Cond.get() == S->getCond() &&
   5526       Body.get() == S->getBody())
   5527     return SemaRef.Owned(S);
   5528 
   5529   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
   5530                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
   5531                                     S->getRParenLoc());
   5532 }
   5533 
   5534 template<typename Derived>
   5535 StmtResult
   5536 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
   5537   // Transform the initialization statement
   5538   StmtResult Init = getDerived().TransformStmt(S->getInit());
   5539   if (Init.isInvalid())
   5540     return StmtError();
   5541 
   5542   // Transform the condition
   5543   ExprResult Cond;
   5544   VarDecl *ConditionVar = 0;
   5545   if (S->getConditionVariable()) {
   5546     ConditionVar
   5547       = cast_or_null<VarDecl>(
   5548                    getDerived().TransformDefinition(
   5549                                       S->getConditionVariable()->getLocation(),
   5550                                                     S->getConditionVariable()));
   5551     if (!ConditionVar)
   5552       return StmtError();
   5553   } else {
   5554     Cond = getDerived().TransformExpr(S->getCond());
   5555 
   5556     if (Cond.isInvalid())
   5557       return StmtError();
   5558 
   5559     if (S->getCond()) {
   5560       // Convert the condition to a boolean value.
   5561       ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getForLoc(),
   5562                                                          Cond.get());
   5563       if (CondE.isInvalid())
   5564         return StmtError();
   5565 
   5566       Cond = CondE.get();
   5567     }
   5568   }
   5569 
   5570   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
   5571   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   5572     return StmtError();
   5573 
   5574   // Transform the increment
   5575   ExprResult Inc = getDerived().TransformExpr(S->getInc());
   5576   if (Inc.isInvalid())
   5577     return StmtError();
   5578 
   5579   Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
   5580   if (S->getInc() && !FullInc.get())
   5581     return StmtError();
   5582 
   5583   // Transform the body
   5584   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5585   if (Body.isInvalid())
   5586     return StmtError();
   5587 
   5588   if (!getDerived().AlwaysRebuild() &&
   5589       Init.get() == S->getInit() &&
   5590       FullCond.get() == S->getCond() &&
   5591       Inc.get() == S->getInc() &&
   5592       Body.get() == S->getBody())
   5593     return SemaRef.Owned(S);
   5594 
   5595   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
   5596                                      Init.get(), FullCond, ConditionVar,
   5597                                      FullInc, S->getRParenLoc(), Body.get());
   5598 }
   5599 
   5600 template<typename Derived>
   5601 StmtResult
   5602 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
   5603   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
   5604                                         S->getLabel());
   5605   if (!LD)
   5606     return StmtError();
   5607 
   5608   // Goto statements must always be rebuilt, to resolve the label.
   5609   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
   5610                                       cast<LabelDecl>(LD));
   5611 }
   5612 
   5613 template<typename Derived>
   5614 StmtResult
   5615 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
   5616   ExprResult Target = getDerived().TransformExpr(S->getTarget());
   5617   if (Target.isInvalid())
   5618     return StmtError();
   5619   Target = SemaRef.MaybeCreateExprWithCleanups(Target.take());
   5620 
   5621   if (!getDerived().AlwaysRebuild() &&
   5622       Target.get() == S->getTarget())
   5623     return SemaRef.Owned(S);
   5624 
   5625   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
   5626                                               Target.get());
   5627 }
   5628 
   5629 template<typename Derived>
   5630 StmtResult
   5631 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
   5632   return SemaRef.Owned(S);
   5633 }
   5634 
   5635 template<typename Derived>
   5636 StmtResult
   5637 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
   5638   return SemaRef.Owned(S);
   5639 }
   5640 
   5641 template<typename Derived>
   5642 StmtResult
   5643 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
   5644   ExprResult Result = getDerived().TransformExpr(S->getRetValue());
   5645   if (Result.isInvalid())
   5646     return StmtError();
   5647 
   5648   // FIXME: We always rebuild the return statement because there is no way
   5649   // to tell whether the return type of the function has changed.
   5650   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
   5651 }
   5652 
   5653 template<typename Derived>
   5654 StmtResult
   5655 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
   5656   bool DeclChanged = false;
   5657   SmallVector<Decl *, 4> Decls;
   5658   for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
   5659        D != DEnd; ++D) {
   5660     Decl *Transformed = getDerived().TransformDefinition((*D)->getLocation(),
   5661                                                          *D);
   5662     if (!Transformed)
   5663       return StmtError();
   5664 
   5665     if (Transformed != *D)
   5666       DeclChanged = true;
   5667 
   5668     Decls.push_back(Transformed);
   5669   }
   5670 
   5671   if (!getDerived().AlwaysRebuild() && !DeclChanged)
   5672     return SemaRef.Owned(S);
   5673 
   5674   return getDerived().RebuildDeclStmt(Decls, S->getStartLoc(), S->getEndLoc());
   5675 }
   5676 
   5677 template<typename Derived>
   5678 StmtResult
   5679 TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
   5680 
   5681   SmallVector<Expr*, 8> Constraints;
   5682   SmallVector<Expr*, 8> Exprs;
   5683   SmallVector<IdentifierInfo *, 4> Names;
   5684 
   5685   ExprResult AsmString;
   5686   SmallVector<Expr*, 8> Clobbers;
   5687 
   5688   bool ExprsChanged = false;
   5689 
   5690   // Go through the outputs.
   5691   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
   5692     Names.push_back(S->getOutputIdentifier(I));
   5693 
   5694     // No need to transform the constraint literal.
   5695     Constraints.push_back(S->getOutputConstraintLiteral(I));
   5696 
   5697     // Transform the output expr.
   5698     Expr *OutputExpr = S->getOutputExpr(I);
   5699     ExprResult Result = getDerived().TransformExpr(OutputExpr);
   5700     if (Result.isInvalid())
   5701       return StmtError();
   5702 
   5703     ExprsChanged |= Result.get() != OutputExpr;
   5704 
   5705     Exprs.push_back(Result.get());
   5706   }
   5707 
   5708   // Go through the inputs.
   5709   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
   5710     Names.push_back(S->getInputIdentifier(I));
   5711 
   5712     // No need to transform the constraint literal.
   5713     Constraints.push_back(S->getInputConstraintLiteral(I));
   5714 
   5715     // Transform the input expr.
   5716     Expr *InputExpr = S->getInputExpr(I);
   5717     ExprResult Result = getDerived().TransformExpr(InputExpr);
   5718     if (Result.isInvalid())
   5719       return StmtError();
   5720 
   5721     ExprsChanged |= Result.get() != InputExpr;
   5722 
   5723     Exprs.push_back(Result.get());
   5724   }
   5725 
   5726   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
   5727     return SemaRef.Owned(S);
   5728 
   5729   // Go through the clobbers.
   5730   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
   5731     Clobbers.push_back(S->getClobberStringLiteral(I));
   5732 
   5733   // No need to transform the asm string literal.
   5734   AsmString = SemaRef.Owned(S->getAsmString());
   5735   return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
   5736                                         S->isVolatile(), S->getNumOutputs(),
   5737                                         S->getNumInputs(), Names.data(),
   5738                                         Constraints, Exprs, AsmString.get(),
   5739                                         Clobbers, S->getRParenLoc());
   5740 }
   5741 
   5742 template<typename Derived>
   5743 StmtResult
   5744 TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
   5745   ArrayRef<Token> AsmToks =
   5746     llvm::makeArrayRef(S->getAsmToks(), S->getNumAsmToks());
   5747 
   5748   bool HadError = false, HadChange = false;
   5749 
   5750   ArrayRef<Expr*> SrcExprs = S->getAllExprs();
   5751   SmallVector<Expr*, 8> TransformedExprs;
   5752   TransformedExprs.reserve(SrcExprs.size());
   5753   for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
   5754     ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
   5755     if (!Result.isUsable()) {
   5756       HadError = true;
   5757     } else {
   5758       HadChange |= (Result.get() != SrcExprs[i]);
   5759       TransformedExprs.push_back(Result.take());
   5760     }
   5761   }
   5762 
   5763   if (HadError) return StmtError();
   5764   if (!HadChange && !getDerived().AlwaysRebuild())
   5765     return Owned(S);
   5766 
   5767   return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
   5768                                        AsmToks, S->getAsmString(),
   5769                                        S->getNumOutputs(), S->getNumInputs(),
   5770                                        S->getAllConstraints(), S->getClobbers(),
   5771                                        TransformedExprs, S->getEndLoc());
   5772 }
   5773 
   5774 template<typename Derived>
   5775 StmtResult
   5776 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
   5777   // Transform the body of the @try.
   5778   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
   5779   if (TryBody.isInvalid())
   5780     return StmtError();
   5781 
   5782   // Transform the @catch statements (if present).
   5783   bool AnyCatchChanged = false;
   5784   SmallVector<Stmt*, 8> CatchStmts;
   5785   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
   5786     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
   5787     if (Catch.isInvalid())
   5788       return StmtError();
   5789     if (Catch.get() != S->getCatchStmt(I))
   5790