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 "clang/Sema/SemaInternal.h"
     18 #include "clang/Sema/Lookup.h"
     19 #include "clang/Sema/ParsedTemplate.h"
     20 #include "clang/Sema/SemaDiagnostic.h"
     21 #include "clang/Sema/ScopeInfo.h"
     22 #include "clang/AST/Decl.h"
     23 #include "clang/AST/DeclObjC.h"
     24 #include "clang/AST/DeclTemplate.h"
     25 #include "clang/AST/Expr.h"
     26 #include "clang/AST/ExprCXX.h"
     27 #include "clang/AST/ExprObjC.h"
     28 #include "clang/AST/Stmt.h"
     29 #include "clang/AST/StmtCXX.h"
     30 #include "clang/AST/StmtObjC.h"
     31 #include "clang/Sema/Ownership.h"
     32 #include "clang/Sema/Designator.h"
     33 #include "clang/Lex/Preprocessor.h"
     34 #include "llvm/Support/ErrorHandling.h"
     35 #include "TypeLocBuilder.h"
     36 #include <algorithm>
     37 
     38 namespace clang {
     39 using namespace sema;
     40 
     41 /// \brief A semantic tree transformation that allows one to transform one
     42 /// abstract syntax tree into another.
     43 ///
     44 /// A new tree transformation is defined by creating a new subclass \c X of
     45 /// \c TreeTransform<X> and then overriding certain operations to provide
     46 /// behavior specific to that transformation. For example, template
     47 /// instantiation is implemented as a tree transformation where the
     48 /// transformation of TemplateTypeParmType nodes involves substituting the
     49 /// template arguments for their corresponding template parameters; a similar
     50 /// transformation is performed for non-type template parameters and
     51 /// template template parameters.
     52 ///
     53 /// This tree-transformation template uses static polymorphism to allow
     54 /// subclasses to customize any of its operations. Thus, a subclass can
     55 /// override any of the transformation or rebuild operators by providing an
     56 /// operation with the same signature as the default implementation. The
     57 /// overridding function should not be virtual.
     58 ///
     59 /// Semantic tree transformations are split into two stages, either of which
     60 /// can be replaced by a subclass. The "transform" step transforms an AST node
     61 /// or the parts of an AST node using the various transformation functions,
     62 /// then passes the pieces on to the "rebuild" step, which constructs a new AST
     63 /// node of the appropriate kind from the pieces. The default transformation
     64 /// routines recursively transform the operands to composite AST nodes (e.g.,
     65 /// the pointee type of a PointerType node) and, if any of those operand nodes
     66 /// were changed by the transformation, invokes the rebuild operation to create
     67 /// a new AST node.
     68 ///
     69 /// Subclasses can customize the transformation at various levels. The
     70 /// most coarse-grained transformations involve replacing TransformType(),
     71 /// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
     72 /// TransformTemplateName(), or TransformTemplateArgument() with entirely
     73 /// new implementations.
     74 ///
     75 /// For more fine-grained transformations, subclasses can replace any of the
     76 /// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
     77 /// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
     78 /// replacing TransformTemplateTypeParmType() allows template instantiation
     79 /// to substitute template arguments for their corresponding template
     80 /// parameters. Additionally, subclasses can override the \c RebuildXXX
     81 /// functions to control how AST nodes are rebuilt when their operands change.
     82 /// By default, \c TreeTransform will invoke semantic analysis to rebuild
     83 /// AST nodes. However, certain other tree transformations (e.g, cloning) may
     84 /// be able to use more efficient rebuild steps.
     85 ///
     86 /// There are a handful of other functions that can be overridden, allowing one
     87 /// to avoid traversing nodes that don't need any transformation
     88 /// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
     89 /// operands have not changed (\c AlwaysRebuild()), and customize the
     90 /// default locations and entity names used for type-checking
     91 /// (\c getBaseLocation(), \c getBaseEntity()).
     92 template<typename Derived>
     93 class TreeTransform {
     94   /// \brief Private RAII object that helps us forget and then re-remember
     95   /// the template argument corresponding to a partially-substituted parameter
     96   /// pack.
     97   class ForgetPartiallySubstitutedPackRAII {
     98     Derived &Self;
     99     TemplateArgument Old;
    100 
    101   public:
    102     ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
    103       Old = Self.ForgetPartiallySubstitutedPack();
    104     }
    105 
    106     ~ForgetPartiallySubstitutedPackRAII() {
    107       Self.RememberPartiallySubstitutedPack(Old);
    108     }
    109   };
    110 
    111 protected:
    112   Sema &SemaRef;
    113 
    114 public:
    115   /// \brief Initializes a new tree transformer.
    116   TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
    117 
    118   /// \brief Retrieves a reference to the derived class.
    119   Derived &getDerived() { return static_cast<Derived&>(*this); }
    120 
    121   /// \brief Retrieves a reference to the derived class.
    122   const Derived &getDerived() const {
    123     return static_cast<const Derived&>(*this);
    124   }
    125 
    126   static inline ExprResult Owned(Expr *E) { return E; }
    127   static inline StmtResult Owned(Stmt *S) { return S; }
    128 
    129   /// \brief Retrieves a reference to the semantic analysis object used for
    130   /// this tree transform.
    131   Sema &getSema() const { return SemaRef; }
    132 
    133   /// \brief Whether the transformation should always rebuild AST nodes, even
    134   /// if none of the children have changed.
    135   ///
    136   /// Subclasses may override this function to specify when the transformation
    137   /// should rebuild all AST nodes.
    138   bool AlwaysRebuild() { return false; }
    139 
    140   /// \brief Returns the location of the entity being transformed, if that
    141   /// information was not available elsewhere in the AST.
    142   ///
    143   /// By default, returns no source-location information. Subclasses can
    144   /// provide an alternative implementation that provides better location
    145   /// information.
    146   SourceLocation getBaseLocation() { return SourceLocation(); }
    147 
    148   /// \brief Returns the name of the entity being transformed, if that
    149   /// information was not available elsewhere in the AST.
    150   ///
    151   /// By default, returns an empty name. Subclasses can provide an alternative
    152   /// implementation with a more precise name.
    153   DeclarationName getBaseEntity() { return DeclarationName(); }
    154 
    155   /// \brief Sets the "base" location and entity when that
    156   /// information is known based on another transformation.
    157   ///
    158   /// By default, the source location and entity are ignored. Subclasses can
    159   /// override this function to provide a customized implementation.
    160   void setBase(SourceLocation Loc, DeclarationName Entity) { }
    161 
    162   /// \brief RAII object that temporarily sets the base location and entity
    163   /// used for reporting diagnostics in types.
    164   class TemporaryBase {
    165     TreeTransform &Self;
    166     SourceLocation OldLocation;
    167     DeclarationName OldEntity;
    168 
    169   public:
    170     TemporaryBase(TreeTransform &Self, SourceLocation Location,
    171                   DeclarationName Entity) : Self(Self) {
    172       OldLocation = Self.getDerived().getBaseLocation();
    173       OldEntity = Self.getDerived().getBaseEntity();
    174 
    175       if (Location.isValid())
    176         Self.getDerived().setBase(Location, Entity);
    177     }
    178 
    179     ~TemporaryBase() {
    180       Self.getDerived().setBase(OldLocation, OldEntity);
    181     }
    182   };
    183 
    184   /// \brief Determine whether the given type \p T has already been
    185   /// transformed.
    186   ///
    187   /// Subclasses can provide an alternative implementation of this routine
    188   /// to short-circuit evaluation when it is known that a given type will
    189   /// not change. For example, template instantiation need not traverse
    190   /// non-dependent types.
    191   bool AlreadyTransformed(QualType T) {
    192     return T.isNull();
    193   }
    194 
    195   /// \brief Determine whether the given call argument should be dropped, e.g.,
    196   /// because it is a default argument.
    197   ///
    198   /// Subclasses can provide an alternative implementation of this routine to
    199   /// determine which kinds of call arguments get dropped. By default,
    200   /// CXXDefaultArgument nodes are dropped (prior to transformation).
    201   bool DropCallArgument(Expr *E) {
    202     return E->isDefaultArgument();
    203   }
    204 
    205   /// \brief Determine whether we should expand a pack expansion with the
    206   /// given set of parameter packs into separate arguments by repeatedly
    207   /// transforming the pattern.
    208   ///
    209   /// By default, the transformer never tries to expand pack expansions.
    210   /// Subclasses can override this routine to provide different behavior.
    211   ///
    212   /// \param EllipsisLoc The location of the ellipsis that identifies the
    213   /// pack expansion.
    214   ///
    215   /// \param PatternRange The source range that covers the entire pattern of
    216   /// the pack expansion.
    217   ///
    218   /// \param Unexpanded The set of unexpanded parameter packs within the
    219   /// pattern.
    220   ///
    221   /// \param NumUnexpanded The number of unexpanded parameter packs in
    222   /// \p Unexpanded.
    223   ///
    224   /// \param ShouldExpand Will be set to \c true if the transformer should
    225   /// expand the corresponding pack expansions into separate arguments. When
    226   /// set, \c NumExpansions must also be set.
    227   ///
    228   /// \param RetainExpansion Whether the caller should add an unexpanded
    229   /// pack expansion after all of the expanded arguments. This is used
    230   /// when extending explicitly-specified template argument packs per
    231   /// C++0x [temp.arg.explicit]p9.
    232   ///
    233   /// \param NumExpansions The number of separate arguments that will be in
    234   /// the expanded form of the corresponding pack expansion. This is both an
    235   /// input and an output parameter, which can be set by the caller if the
    236   /// number of expansions is known a priori (e.g., due to a prior substitution)
    237   /// and will be set by the callee when the number of expansions is known.
    238   /// The callee must set this value when \c ShouldExpand is \c true; it may
    239   /// set this value in other cases.
    240   ///
    241   /// \returns true if an error occurred (e.g., because the parameter packs
    242   /// are to be instantiated with arguments of different lengths), false
    243   /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
    244   /// must be set.
    245   bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
    246                                SourceRange PatternRange,
    247                                const UnexpandedParameterPack *Unexpanded,
    248                                unsigned NumUnexpanded,
    249                                bool &ShouldExpand,
    250                                bool &RetainExpansion,
    251                                llvm::Optional<unsigned> &NumExpansions) {
    252     ShouldExpand = false;
    253     return false;
    254   }
    255 
    256   /// \brief "Forget" about the partially-substituted pack template argument,
    257   /// when performing an instantiation that must preserve the parameter pack
    258   /// use.
    259   ///
    260   /// This routine is meant to be overridden by the template instantiator.
    261   TemplateArgument ForgetPartiallySubstitutedPack() {
    262     return TemplateArgument();
    263   }
    264 
    265   /// \brief "Remember" the partially-substituted pack template argument
    266   /// after performing an instantiation that must preserve the parameter pack
    267   /// use.
    268   ///
    269   /// This routine is meant to be overridden by the template instantiator.
    270   void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
    271 
    272   /// \brief Note to the derived class when a function parameter pack is
    273   /// being expanded.
    274   void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
    275 
    276   /// \brief Transforms the given type into another type.
    277   ///
    278   /// By default, this routine transforms a type by creating a
    279   /// TypeSourceInfo for it and delegating to the appropriate
    280   /// function.  This is expensive, but we don't mind, because
    281   /// this method is deprecated anyway;  all users should be
    282   /// switched to storing TypeSourceInfos.
    283   ///
    284   /// \returns the transformed type.
    285   QualType TransformType(QualType T);
    286 
    287   /// \brief Transforms the given type-with-location into a new
    288   /// type-with-location.
    289   ///
    290   /// By default, this routine transforms a type by delegating to the
    291   /// appropriate TransformXXXType to build a new type.  Subclasses
    292   /// may override this function (to take over all type
    293   /// transformations) or some set of the TransformXXXType functions
    294   /// to alter the transformation.
    295   TypeSourceInfo *TransformType(TypeSourceInfo *DI);
    296 
    297   /// \brief Transform the given type-with-location into a new
    298   /// type, collecting location information in the given builder
    299   /// as necessary.
    300   ///
    301   QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
    302 
    303   /// \brief Transform the given statement.
    304   ///
    305   /// By default, this routine transforms a statement by delegating to the
    306   /// appropriate TransformXXXStmt function to transform a specific kind of
    307   /// statement or the TransformExpr() function to transform an expression.
    308   /// Subclasses may override this function to transform statements using some
    309   /// other mechanism.
    310   ///
    311   /// \returns the transformed statement.
    312   StmtResult TransformStmt(Stmt *S);
    313 
    314   /// \brief Transform the given expression.
    315   ///
    316   /// By default, this routine transforms an expression by delegating to the
    317   /// appropriate TransformXXXExpr function to build a new expression.
    318   /// Subclasses may override this function to transform expressions using some
    319   /// other mechanism.
    320   ///
    321   /// \returns the transformed expression.
    322   ExprResult TransformExpr(Expr *E);
    323 
    324   /// \brief Transform the given list of expressions.
    325   ///
    326   /// This routine transforms a list of expressions by invoking
    327   /// \c TransformExpr() for each subexpression. However, it also provides
    328   /// support for variadic templates by expanding any pack expansions (if the
    329   /// derived class permits such expansion) along the way. When pack expansions
    330   /// are present, the number of outputs may not equal the number of inputs.
    331   ///
    332   /// \param Inputs The set of expressions to be transformed.
    333   ///
    334   /// \param NumInputs The number of expressions in \c Inputs.
    335   ///
    336   /// \param IsCall If \c true, then this transform is being performed on
    337   /// function-call arguments, and any arguments that should be dropped, will
    338   /// be.
    339   ///
    340   /// \param Outputs The transformed input expressions will be added to this
    341   /// vector.
    342   ///
    343   /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
    344   /// due to transformation.
    345   ///
    346   /// \returns true if an error occurred, false otherwise.
    347   bool TransformExprs(Expr **Inputs, unsigned NumInputs, bool IsCall,
    348                       llvm::SmallVectorImpl<Expr *> &Outputs,
    349                       bool *ArgChanged = 0);
    350 
    351   /// \brief Transform the given declaration, which is referenced from a type
    352   /// or expression.
    353   ///
    354   /// By default, acts as the identity function on declarations. Subclasses
    355   /// may override this function to provide alternate behavior.
    356   Decl *TransformDecl(SourceLocation Loc, Decl *D) { return D; }
    357 
    358   /// \brief Transform the definition of the given declaration.
    359   ///
    360   /// By default, invokes TransformDecl() to transform the declaration.
    361   /// Subclasses may override this function to provide alternate behavior.
    362   Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
    363     return getDerived().TransformDecl(Loc, D);
    364   }
    365 
    366   /// \brief Transform the given declaration, which was the first part of a
    367   /// nested-name-specifier in a member access expression.
    368   ///
    369   /// This specific declaration transformation only applies to the first
    370   /// identifier in a nested-name-specifier of a member access expression, e.g.,
    371   /// the \c T in \c x->T::member
    372   ///
    373   /// By default, invokes TransformDecl() to transform the declaration.
    374   /// Subclasses may override this function to provide alternate behavior.
    375   NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
    376     return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
    377   }
    378 
    379   /// \brief Transform the given nested-name-specifier with source-location
    380   /// information.
    381   ///
    382   /// By default, transforms all of the types and declarations within the
    383   /// nested-name-specifier. Subclasses may override this function to provide
    384   /// alternate behavior.
    385   NestedNameSpecifierLoc TransformNestedNameSpecifierLoc(
    386                                                     NestedNameSpecifierLoc NNS,
    387                                           QualType ObjectType = QualType(),
    388                                           NamedDecl *FirstQualifierInScope = 0);
    389 
    390   /// \brief Transform the given declaration name.
    391   ///
    392   /// By default, transforms the types of conversion function, constructor,
    393   /// and destructor names and then (if needed) rebuilds the declaration name.
    394   /// Identifiers and selectors are returned unmodified. Sublcasses may
    395   /// override this function to provide alternate behavior.
    396   DeclarationNameInfo
    397   TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
    398 
    399   /// \brief Transform the given template name.
    400   ///
    401   /// \param SS The nested-name-specifier that qualifies the template
    402   /// name. This nested-name-specifier must already have been transformed.
    403   ///
    404   /// \param Name The template name to transform.
    405   ///
    406   /// \param NameLoc The source location of the template name.
    407   ///
    408   /// \param ObjectType If we're translating a template name within a member
    409   /// access expression, this is the type of the object whose member template
    410   /// is being referenced.
    411   ///
    412   /// \param FirstQualifierInScope If the first part of a nested-name-specifier
    413   /// also refers to a name within the current (lexical) scope, this is the
    414   /// declaration it refers to.
    415   ///
    416   /// By default, transforms the template name by transforming the declarations
    417   /// and nested-name-specifiers that occur within the template name.
    418   /// Subclasses may override this function to provide alternate behavior.
    419   TemplateName TransformTemplateName(CXXScopeSpec &SS,
    420                                      TemplateName Name,
    421                                      SourceLocation NameLoc,
    422                                      QualType ObjectType = QualType(),
    423                                      NamedDecl *FirstQualifierInScope = 0);
    424 
    425   /// \brief Transform the given template argument.
    426   ///
    427   /// By default, this operation transforms the type, expression, or
    428   /// declaration stored within the template argument and constructs a
    429   /// new template argument from the transformed result. Subclasses may
    430   /// override this function to provide alternate behavior.
    431   ///
    432   /// Returns true if there was an error.
    433   bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
    434                                  TemplateArgumentLoc &Output);
    435 
    436   /// \brief Transform the given set of template arguments.
    437   ///
    438   /// By default, this operation transforms all of the template arguments
    439   /// in the input set using \c TransformTemplateArgument(), and appends
    440   /// the transformed arguments to the output list.
    441   ///
    442   /// Note that this overload of \c TransformTemplateArguments() is merely
    443   /// a convenience function. Subclasses that wish to override this behavior
    444   /// should override the iterator-based member template version.
    445   ///
    446   /// \param Inputs The set of template arguments to be transformed.
    447   ///
    448   /// \param NumInputs The number of template arguments in \p Inputs.
    449   ///
    450   /// \param Outputs The set of transformed template arguments output by this
    451   /// routine.
    452   ///
    453   /// Returns true if an error occurred.
    454   bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
    455                                   unsigned NumInputs,
    456                                   TemplateArgumentListInfo &Outputs) {
    457     return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs);
    458   }
    459 
    460   /// \brief Transform the given set of template arguments.
    461   ///
    462   /// By default, this operation transforms all of the template arguments
    463   /// in the input set using \c TransformTemplateArgument(), and appends
    464   /// the transformed arguments to the output list.
    465   ///
    466   /// \param First An iterator to the first template argument.
    467   ///
    468   /// \param Last An iterator one step past the last template argument.
    469   ///
    470   /// \param Outputs The set of transformed template arguments output by this
    471   /// routine.
    472   ///
    473   /// Returns true if an error occurred.
    474   template<typename InputIterator>
    475   bool TransformTemplateArguments(InputIterator First,
    476                                   InputIterator Last,
    477                                   TemplateArgumentListInfo &Outputs);
    478 
    479   /// \brief Fakes up a TemplateArgumentLoc for a given TemplateArgument.
    480   void InventTemplateArgumentLoc(const TemplateArgument &Arg,
    481                                  TemplateArgumentLoc &ArgLoc);
    482 
    483   /// \brief Fakes up a TypeSourceInfo for a type.
    484   TypeSourceInfo *InventTypeSourceInfo(QualType T) {
    485     return SemaRef.Context.getTrivialTypeSourceInfo(T,
    486                        getDerived().getBaseLocation());
    487   }
    488 
    489 #define ABSTRACT_TYPELOC(CLASS, PARENT)
    490 #define TYPELOC(CLASS, PARENT)                                   \
    491   QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
    492 #include "clang/AST/TypeLocNodes.def"
    493 
    494   StmtResult
    495   TransformSEHHandler(Stmt *Handler);
    496 
    497   QualType
    498   TransformTemplateSpecializationType(TypeLocBuilder &TLB,
    499                                       TemplateSpecializationTypeLoc TL,
    500                                       TemplateName Template);
    501 
    502   QualType
    503   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
    504                                       DependentTemplateSpecializationTypeLoc TL,
    505                                                TemplateName Template,
    506                                                CXXScopeSpec &SS);
    507 
    508   QualType
    509   TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
    510                                                DependentTemplateSpecializationTypeLoc TL,
    511                                          NestedNameSpecifierLoc QualifierLoc);
    512 
    513   /// \brief Transforms the parameters of a function type into the
    514   /// given vectors.
    515   ///
    516   /// The result vectors should be kept in sync; null entries in the
    517   /// variables vector are acceptable.
    518   ///
    519   /// Return true on error.
    520   bool TransformFunctionTypeParams(SourceLocation Loc,
    521                                    ParmVarDecl **Params, unsigned NumParams,
    522                                    const QualType *ParamTypes,
    523                                    llvm::SmallVectorImpl<QualType> &PTypes,
    524                                    llvm::SmallVectorImpl<ParmVarDecl*> *PVars);
    525 
    526   /// \brief Transforms a single function-type parameter.  Return null
    527   /// on error.
    528   ///
    529   /// \param indexAdjustment - A number to add to the parameter's
    530   ///   scope index;  can be negative
    531   ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
    532                                           int indexAdjustment,
    533                                         llvm::Optional<unsigned> NumExpansions);
    534 
    535   QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
    536 
    537   StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
    538   ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
    539 
    540 #define STMT(Node, Parent)                        \
    541   StmtResult Transform##Node(Node *S);
    542 #define EXPR(Node, Parent)                        \
    543   ExprResult Transform##Node(Node *E);
    544 #define ABSTRACT_STMT(Stmt)
    545 #include "clang/AST/StmtNodes.inc"
    546 
    547   /// \brief Build a new pointer type given its pointee type.
    548   ///
    549   /// By default, performs semantic analysis when building the pointer type.
    550   /// Subclasses may override this routine to provide different behavior.
    551   QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
    552 
    553   /// \brief Build a new block pointer type given its pointee type.
    554   ///
    555   /// By default, performs semantic analysis when building the block pointer
    556   /// type. Subclasses may override this routine to provide different behavior.
    557   QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
    558 
    559   /// \brief Build a new reference type given the type it references.
    560   ///
    561   /// By default, performs semantic analysis when building the
    562   /// reference type. Subclasses may override this routine to provide
    563   /// different behavior.
    564   ///
    565   /// \param LValue whether the type was written with an lvalue sigil
    566   /// or an rvalue sigil.
    567   QualType RebuildReferenceType(QualType ReferentType,
    568                                 bool LValue,
    569                                 SourceLocation Sigil);
    570 
    571   /// \brief Build a new member pointer type given the pointee type and the
    572   /// class type it refers into.
    573   ///
    574   /// By default, performs semantic analysis when building the member pointer
    575   /// type. Subclasses may override this routine to provide different behavior.
    576   QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
    577                                     SourceLocation Sigil);
    578 
    579   /// \brief Build a new array type given the element type, size
    580   /// modifier, size of the array (if known), size expression, and index type
    581   /// qualifiers.
    582   ///
    583   /// By default, performs semantic analysis when building the array type.
    584   /// Subclasses may override this routine to provide different behavior.
    585   /// Also by default, all of the other Rebuild*Array
    586   QualType RebuildArrayType(QualType ElementType,
    587                             ArrayType::ArraySizeModifier SizeMod,
    588                             const llvm::APInt *Size,
    589                             Expr *SizeExpr,
    590                             unsigned IndexTypeQuals,
    591                             SourceRange BracketsRange);
    592 
    593   /// \brief Build a new constant array type given the element type, size
    594   /// modifier, (known) size of the array, and index type qualifiers.
    595   ///
    596   /// By default, performs semantic analysis when building the array type.
    597   /// Subclasses may override this routine to provide different behavior.
    598   QualType RebuildConstantArrayType(QualType ElementType,
    599                                     ArrayType::ArraySizeModifier SizeMod,
    600                                     const llvm::APInt &Size,
    601                                     unsigned IndexTypeQuals,
    602                                     SourceRange BracketsRange);
    603 
    604   /// \brief Build a new incomplete array type given the element type, size
    605   /// modifier, and index type qualifiers.
    606   ///
    607   /// By default, performs semantic analysis when building the array type.
    608   /// Subclasses may override this routine to provide different behavior.
    609   QualType RebuildIncompleteArrayType(QualType ElementType,
    610                                       ArrayType::ArraySizeModifier SizeMod,
    611                                       unsigned IndexTypeQuals,
    612                                       SourceRange BracketsRange);
    613 
    614   /// \brief Build a new variable-length array type given the element type,
    615   /// size modifier, size expression, and index type qualifiers.
    616   ///
    617   /// By default, performs semantic analysis when building the array type.
    618   /// Subclasses may override this routine to provide different behavior.
    619   QualType RebuildVariableArrayType(QualType ElementType,
    620                                     ArrayType::ArraySizeModifier SizeMod,
    621                                     Expr *SizeExpr,
    622                                     unsigned IndexTypeQuals,
    623                                     SourceRange BracketsRange);
    624 
    625   /// \brief Build a new dependent-sized array type given the element type,
    626   /// size modifier, size expression, and index type qualifiers.
    627   ///
    628   /// By default, performs semantic analysis when building the array type.
    629   /// Subclasses may override this routine to provide different behavior.
    630   QualType RebuildDependentSizedArrayType(QualType ElementType,
    631                                           ArrayType::ArraySizeModifier SizeMod,
    632                                           Expr *SizeExpr,
    633                                           unsigned IndexTypeQuals,
    634                                           SourceRange BracketsRange);
    635 
    636   /// \brief Build a new vector type given the element type and
    637   /// number of elements.
    638   ///
    639   /// By default, performs semantic analysis when building the vector type.
    640   /// Subclasses may override this routine to provide different behavior.
    641   QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
    642                              VectorType::VectorKind VecKind);
    643 
    644   /// \brief Build a new extended vector type given the element type and
    645   /// number of elements.
    646   ///
    647   /// By default, performs semantic analysis when building the vector type.
    648   /// Subclasses may override this routine to provide different behavior.
    649   QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
    650                                 SourceLocation AttributeLoc);
    651 
    652   /// \brief Build a new potentially dependently-sized extended vector type
    653   /// given the element type and number of elements.
    654   ///
    655   /// By default, performs semantic analysis when building the vector type.
    656   /// Subclasses may override this routine to provide different behavior.
    657   QualType RebuildDependentSizedExtVectorType(QualType ElementType,
    658                                               Expr *SizeExpr,
    659                                               SourceLocation AttributeLoc);
    660 
    661   /// \brief Build a new function type.
    662   ///
    663   /// By default, performs semantic analysis when building the function type.
    664   /// Subclasses may override this routine to provide different behavior.
    665   QualType RebuildFunctionProtoType(QualType T,
    666                                     QualType *ParamTypes,
    667                                     unsigned NumParamTypes,
    668                                     bool Variadic, unsigned Quals,
    669                                     RefQualifierKind RefQualifier,
    670                                     const FunctionType::ExtInfo &Info);
    671 
    672   /// \brief Build a new unprototyped function type.
    673   QualType RebuildFunctionNoProtoType(QualType ResultType);
    674 
    675   /// \brief Rebuild an unresolved typename type, given the decl that
    676   /// the UnresolvedUsingTypenameDecl was transformed to.
    677   QualType RebuildUnresolvedUsingType(Decl *D);
    678 
    679   /// \brief Build a new typedef type.
    680   QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
    681     return SemaRef.Context.getTypeDeclType(Typedef);
    682   }
    683 
    684   /// \brief Build a new class/struct/union type.
    685   QualType RebuildRecordType(RecordDecl *Record) {
    686     return SemaRef.Context.getTypeDeclType(Record);
    687   }
    688 
    689   /// \brief Build a new Enum type.
    690   QualType RebuildEnumType(EnumDecl *Enum) {
    691     return SemaRef.Context.getTypeDeclType(Enum);
    692   }
    693 
    694   /// \brief Build a new typeof(expr) type.
    695   ///
    696   /// By default, performs semantic analysis when building the typeof type.
    697   /// Subclasses may override this routine to provide different behavior.
    698   QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc);
    699 
    700   /// \brief Build a new typeof(type) type.
    701   ///
    702   /// By default, builds a new TypeOfType with the given underlying type.
    703   QualType RebuildTypeOfType(QualType Underlying);
    704 
    705   /// \brief Build a new unary transform type.
    706   QualType RebuildUnaryTransformType(QualType BaseType,
    707                                      UnaryTransformType::UTTKind UKind,
    708                                      SourceLocation Loc);
    709 
    710   /// \brief Build a new C++0x decltype type.
    711   ///
    712   /// By default, performs semantic analysis when building the decltype type.
    713   /// Subclasses may override this routine to provide different behavior.
    714   QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
    715 
    716   /// \brief Build a new C++0x auto type.
    717   ///
    718   /// By default, builds a new AutoType with the given deduced type.
    719   QualType RebuildAutoType(QualType Deduced) {
    720     return SemaRef.Context.getAutoType(Deduced);
    721   }
    722 
    723   /// \brief Build a new template specialization type.
    724   ///
    725   /// By default, performs semantic analysis when building the template
    726   /// specialization type. Subclasses may override this routine to provide
    727   /// different behavior.
    728   QualType RebuildTemplateSpecializationType(TemplateName Template,
    729                                              SourceLocation TemplateLoc,
    730                                              TemplateArgumentListInfo &Args);
    731 
    732   /// \brief Build a new parenthesized type.
    733   ///
    734   /// By default, builds a new ParenType type from the inner type.
    735   /// Subclasses may override this routine to provide different behavior.
    736   QualType RebuildParenType(QualType InnerType) {
    737     return SemaRef.Context.getParenType(InnerType);
    738   }
    739 
    740   /// \brief Build a new qualified name type.
    741   ///
    742   /// By default, builds a new ElaboratedType type from the keyword,
    743   /// the nested-name-specifier and the named type.
    744   /// Subclasses may override this routine to provide different behavior.
    745   QualType RebuildElaboratedType(SourceLocation KeywordLoc,
    746                                  ElaboratedTypeKeyword Keyword,
    747                                  NestedNameSpecifierLoc QualifierLoc,
    748                                  QualType Named) {
    749     return SemaRef.Context.getElaboratedType(Keyword,
    750                                          QualifierLoc.getNestedNameSpecifier(),
    751                                              Named);
    752   }
    753 
    754   /// \brief Build a new typename type that refers to a template-id.
    755   ///
    756   /// By default, builds a new DependentNameType type from the
    757   /// nested-name-specifier and the given type. Subclasses may override
    758   /// this routine to provide different behavior.
    759   QualType RebuildDependentTemplateSpecializationType(
    760                                           ElaboratedTypeKeyword Keyword,
    761                                           NestedNameSpecifierLoc QualifierLoc,
    762                                           const IdentifierInfo *Name,
    763                                           SourceLocation NameLoc,
    764                                           TemplateArgumentListInfo &Args) {
    765     // Rebuild the template name.
    766     // TODO: avoid TemplateName abstraction
    767     CXXScopeSpec SS;
    768     SS.Adopt(QualifierLoc);
    769     TemplateName InstName
    770       = getDerived().RebuildTemplateName(SS, *Name, NameLoc, QualType(), 0);
    771 
    772     if (InstName.isNull())
    773       return QualType();
    774 
    775     // If it's still dependent, make a dependent specialization.
    776     if (InstName.getAsDependentTemplateName())
    777       return SemaRef.Context.getDependentTemplateSpecializationType(Keyword,
    778                                           QualifierLoc.getNestedNameSpecifier(),
    779                                                                     Name,
    780                                                                     Args);
    781 
    782     // Otherwise, make an elaborated type wrapping a non-dependent
    783     // specialization.
    784     QualType T =
    785     getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
    786     if (T.isNull()) return QualType();
    787 
    788     if (Keyword == ETK_None && QualifierLoc.getNestedNameSpecifier() == 0)
    789       return T;
    790 
    791     return SemaRef.Context.getElaboratedType(Keyword,
    792                                        QualifierLoc.getNestedNameSpecifier(),
    793                                              T);
    794   }
    795 
    796   /// \brief Build a new typename type that refers to an identifier.
    797   ///
    798   /// By default, performs semantic analysis when building the typename type
    799   /// (or elaborated type). Subclasses may override this routine to provide
    800   /// different behavior.
    801   QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
    802                                     SourceLocation KeywordLoc,
    803                                     NestedNameSpecifierLoc QualifierLoc,
    804                                     const IdentifierInfo *Id,
    805                                     SourceLocation IdLoc) {
    806     CXXScopeSpec SS;
    807     SS.Adopt(QualifierLoc);
    808 
    809     if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
    810       // If the name is still dependent, just build a new dependent name type.
    811       if (!SemaRef.computeDeclContext(SS))
    812         return SemaRef.Context.getDependentNameType(Keyword,
    813                                           QualifierLoc.getNestedNameSpecifier(),
    814                                                     Id);
    815     }
    816 
    817     if (Keyword == ETK_None || Keyword == ETK_Typename)
    818       return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
    819                                        *Id, IdLoc);
    820 
    821     TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
    822 
    823     // We had a dependent elaborated-type-specifier that has been transformed
    824     // into a non-dependent elaborated-type-specifier. Find the tag we're
    825     // referring to.
    826     LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
    827     DeclContext *DC = SemaRef.computeDeclContext(SS, false);
    828     if (!DC)
    829       return QualType();
    830 
    831     if (SemaRef.RequireCompleteDeclContext(SS, DC))
    832       return QualType();
    833 
    834     TagDecl *Tag = 0;
    835     SemaRef.LookupQualifiedName(Result, DC);
    836     switch (Result.getResultKind()) {
    837       case LookupResult::NotFound:
    838       case LookupResult::NotFoundInCurrentInstantiation:
    839         break;
    840 
    841       case LookupResult::Found:
    842         Tag = Result.getAsSingle<TagDecl>();
    843         break;
    844 
    845       case LookupResult::FoundOverloaded:
    846       case LookupResult::FoundUnresolvedValue:
    847         llvm_unreachable("Tag lookup cannot find non-tags");
    848         return QualType();
    849 
    850       case LookupResult::Ambiguous:
    851         // Let the LookupResult structure handle ambiguities.
    852         return QualType();
    853     }
    854 
    855     if (!Tag) {
    856       // Check where the name exists but isn't a tag type and use that to emit
    857       // better diagnostics.
    858       LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
    859       SemaRef.LookupQualifiedName(Result, DC);
    860       switch (Result.getResultKind()) {
    861         case LookupResult::Found:
    862         case LookupResult::FoundOverloaded:
    863         case LookupResult::FoundUnresolvedValue: {
    864           NamedDecl *SomeDecl = Result.getRepresentativeDecl();
    865           unsigned Kind = 0;
    866           if (isa<TypedefDecl>(SomeDecl)) Kind = 1;
    867           else if (isa<TypeAliasDecl>(SomeDecl)) Kind = 2;
    868           else if (isa<ClassTemplateDecl>(SomeDecl)) Kind = 3;
    869           SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << Kind;
    870           SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
    871           break;
    872         }
    873         default:
    874           // FIXME: Would be nice to highlight just the source range.
    875           SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
    876             << Kind << Id << DC;
    877           break;
    878       }
    879       return QualType();
    880     }
    881 
    882     if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
    883                                               IdLoc, *Id)) {
    884       SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
    885       SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
    886       return QualType();
    887     }
    888 
    889     // Build the elaborated-type-specifier type.
    890     QualType T = SemaRef.Context.getTypeDeclType(Tag);
    891     return SemaRef.Context.getElaboratedType(Keyword,
    892                                          QualifierLoc.getNestedNameSpecifier(),
    893                                              T);
    894   }
    895 
    896   /// \brief Build a new pack expansion type.
    897   ///
    898   /// By default, builds a new PackExpansionType type from the given pattern.
    899   /// Subclasses may override this routine to provide different behavior.
    900   QualType RebuildPackExpansionType(QualType Pattern,
    901                                     SourceRange PatternRange,
    902                                     SourceLocation EllipsisLoc,
    903                                     llvm::Optional<unsigned> NumExpansions) {
    904     return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
    905                                         NumExpansions);
    906   }
    907 
    908   /// \brief Build a new template name given a nested name specifier, a flag
    909   /// indicating whether the "template" keyword was provided, and the template
    910   /// that the template name refers to.
    911   ///
    912   /// By default, builds the new template name directly. Subclasses may override
    913   /// this routine to provide different behavior.
    914   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
    915                                    bool TemplateKW,
    916                                    TemplateDecl *Template);
    917 
    918   /// \brief Build a new template name given a nested name specifier and the
    919   /// name that is referred to as a template.
    920   ///
    921   /// By default, performs semantic analysis to determine whether the name can
    922   /// be resolved to a specific template, then builds the appropriate kind of
    923   /// template name. Subclasses may override this routine to provide different
    924   /// behavior.
    925   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
    926                                    const IdentifierInfo &Name,
    927                                    SourceLocation NameLoc,
    928                                    QualType ObjectType,
    929                                    NamedDecl *FirstQualifierInScope);
    930 
    931   /// \brief Build a new template name given a nested name specifier and the
    932   /// overloaded operator name that is referred to as a template.
    933   ///
    934   /// By default, performs semantic analysis to determine whether the name can
    935   /// be resolved to a specific template, then builds the appropriate kind of
    936   /// template name. Subclasses may override this routine to provide different
    937   /// behavior.
    938   TemplateName RebuildTemplateName(CXXScopeSpec &SS,
    939                                    OverloadedOperatorKind Operator,
    940                                    SourceLocation NameLoc,
    941                                    QualType ObjectType);
    942 
    943   /// \brief Build a new template name given a template template parameter pack
    944   /// and the
    945   ///
    946   /// By default, performs semantic analysis to determine whether the name can
    947   /// be resolved to a specific template, then builds the appropriate kind of
    948   /// template name. Subclasses may override this routine to provide different
    949   /// behavior.
    950   TemplateName RebuildTemplateName(TemplateTemplateParmDecl *Param,
    951                                    const TemplateArgument &ArgPack) {
    952     return getSema().Context.getSubstTemplateTemplateParmPack(Param, ArgPack);
    953   }
    954 
    955   /// \brief Build a new compound statement.
    956   ///
    957   /// By default, performs semantic analysis to build the new statement.
    958   /// Subclasses may override this routine to provide different behavior.
    959   StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
    960                                        MultiStmtArg Statements,
    961                                        SourceLocation RBraceLoc,
    962                                        bool IsStmtExpr) {
    963     return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
    964                                        IsStmtExpr);
    965   }
    966 
    967   /// \brief Build a new case statement.
    968   ///
    969   /// By default, performs semantic analysis to build the new statement.
    970   /// Subclasses may override this routine to provide different behavior.
    971   StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
    972                                    Expr *LHS,
    973                                    SourceLocation EllipsisLoc,
    974                                    Expr *RHS,
    975                                    SourceLocation ColonLoc) {
    976     return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
    977                                    ColonLoc);
    978   }
    979 
    980   /// \brief Attach the body to a new case statement.
    981   ///
    982   /// By default, performs semantic analysis to build the new statement.
    983   /// Subclasses may override this routine to provide different behavior.
    984   StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
    985     getSema().ActOnCaseStmtBody(S, Body);
    986     return S;
    987   }
    988 
    989   /// \brief Build a new default statement.
    990   ///
    991   /// By default, performs semantic analysis to build the new statement.
    992   /// Subclasses may override this routine to provide different behavior.
    993   StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
    994                                       SourceLocation ColonLoc,
    995                                       Stmt *SubStmt) {
    996     return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
    997                                       /*CurScope=*/0);
    998   }
    999 
   1000   /// \brief Build a new label statement.
   1001   ///
   1002   /// By default, performs semantic analysis to build the new statement.
   1003   /// Subclasses may override this routine to provide different behavior.
   1004   StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
   1005                               SourceLocation ColonLoc, Stmt *SubStmt) {
   1006     return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
   1007   }
   1008 
   1009   /// \brief Build a new "if" statement.
   1010   ///
   1011   /// By default, performs semantic analysis to build the new statement.
   1012   /// Subclasses may override this routine to provide different behavior.
   1013   StmtResult RebuildIfStmt(SourceLocation IfLoc, Sema::FullExprArg Cond,
   1014                            VarDecl *CondVar, Stmt *Then,
   1015                            SourceLocation ElseLoc, Stmt *Else) {
   1016     return getSema().ActOnIfStmt(IfLoc, Cond, CondVar, Then, ElseLoc, Else);
   1017   }
   1018 
   1019   /// \brief Start building a new switch statement.
   1020   ///
   1021   /// By default, performs semantic analysis to build the new statement.
   1022   /// Subclasses may override this routine to provide different behavior.
   1023   StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
   1024                                     Expr *Cond, VarDecl *CondVar) {
   1025     return getSema().ActOnStartOfSwitchStmt(SwitchLoc, Cond,
   1026                                             CondVar);
   1027   }
   1028 
   1029   /// \brief Attach the body to the switch statement.
   1030   ///
   1031   /// By default, performs semantic analysis to build the new statement.
   1032   /// Subclasses may override this routine to provide different behavior.
   1033   StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
   1034                                    Stmt *Switch, Stmt *Body) {
   1035     return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
   1036   }
   1037 
   1038   /// \brief Build a new while statement.
   1039   ///
   1040   /// By default, performs semantic analysis to build the new statement.
   1041   /// Subclasses may override this routine to provide different behavior.
   1042   StmtResult RebuildWhileStmt(SourceLocation WhileLoc, Sema::FullExprArg Cond,
   1043                               VarDecl *CondVar, Stmt *Body) {
   1044     return getSema().ActOnWhileStmt(WhileLoc, Cond, CondVar, Body);
   1045   }
   1046 
   1047   /// \brief Build a new do-while statement.
   1048   ///
   1049   /// By default, performs semantic analysis to build the new statement.
   1050   /// Subclasses may override this routine to provide different behavior.
   1051   StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
   1052                            SourceLocation WhileLoc, SourceLocation LParenLoc,
   1053                            Expr *Cond, SourceLocation RParenLoc) {
   1054     return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
   1055                                  Cond, RParenLoc);
   1056   }
   1057 
   1058   /// \brief Build a new for statement.
   1059   ///
   1060   /// By default, performs semantic analysis to build the new statement.
   1061   /// Subclasses may override this routine to provide different behavior.
   1062   StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
   1063                             Stmt *Init, Sema::FullExprArg Cond,
   1064                             VarDecl *CondVar, Sema::FullExprArg Inc,
   1065                             SourceLocation RParenLoc, Stmt *Body) {
   1066     return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
   1067                                   CondVar, Inc, RParenLoc, Body);
   1068   }
   1069 
   1070   /// \brief Build a new goto 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 RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
   1075                              LabelDecl *Label) {
   1076     return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
   1077   }
   1078 
   1079   /// \brief Build a new indirect goto 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 RebuildIndirectGotoStmt(SourceLocation GotoLoc,
   1084                                      SourceLocation StarLoc,
   1085                                      Expr *Target) {
   1086     return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
   1087   }
   1088 
   1089   /// \brief Build a new return 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 RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
   1094     return getSema().ActOnReturnStmt(ReturnLoc, Result);
   1095   }
   1096 
   1097   /// \brief Build a new declaration statement.
   1098   ///
   1099   /// By default, performs semantic analysis to build the new statement.
   1100   /// Subclasses may override this routine to provide different behavior.
   1101   StmtResult RebuildDeclStmt(Decl **Decls, unsigned NumDecls,
   1102                                    SourceLocation StartLoc,
   1103                                    SourceLocation EndLoc) {
   1104     Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls, NumDecls);
   1105     return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
   1106   }
   1107 
   1108   /// \brief Build a new inline asm statement.
   1109   ///
   1110   /// By default, performs semantic analysis to build the new statement.
   1111   /// Subclasses may override this routine to provide different behavior.
   1112   StmtResult RebuildAsmStmt(SourceLocation AsmLoc,
   1113                                   bool IsSimple,
   1114                                   bool IsVolatile,
   1115                                   unsigned NumOutputs,
   1116                                   unsigned NumInputs,
   1117                                   IdentifierInfo **Names,
   1118                                   MultiExprArg Constraints,
   1119                                   MultiExprArg Exprs,
   1120                                   Expr *AsmString,
   1121                                   MultiExprArg Clobbers,
   1122                                   SourceLocation RParenLoc,
   1123                                   bool MSAsm) {
   1124     return getSema().ActOnAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
   1125                                   NumInputs, Names, move(Constraints),
   1126                                   Exprs, AsmString, Clobbers,
   1127                                   RParenLoc, MSAsm);
   1128   }
   1129 
   1130   /// \brief Build a new Objective-C @try statement.
   1131   ///
   1132   /// By default, performs semantic analysis to build the new statement.
   1133   /// Subclasses may override this routine to provide different behavior.
   1134   StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
   1135                                         Stmt *TryBody,
   1136                                         MultiStmtArg CatchStmts,
   1137                                         Stmt *Finally) {
   1138     return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, move(CatchStmts),
   1139                                         Finally);
   1140   }
   1141 
   1142   /// \brief Rebuild an Objective-C exception declaration.
   1143   ///
   1144   /// By default, performs semantic analysis to build the new declaration.
   1145   /// Subclasses may override this routine to provide different behavior.
   1146   VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
   1147                                     TypeSourceInfo *TInfo, QualType T) {
   1148     return getSema().BuildObjCExceptionDecl(TInfo, T,
   1149                                             ExceptionDecl->getInnerLocStart(),
   1150                                             ExceptionDecl->getLocation(),
   1151                                             ExceptionDecl->getIdentifier());
   1152   }
   1153 
   1154   /// \brief Build a new Objective-C @catch statement.
   1155   ///
   1156   /// By default, performs semantic analysis to build the new statement.
   1157   /// Subclasses may override this routine to provide different behavior.
   1158   StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
   1159                                           SourceLocation RParenLoc,
   1160                                           VarDecl *Var,
   1161                                           Stmt *Body) {
   1162     return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
   1163                                           Var, Body);
   1164   }
   1165 
   1166   /// \brief Build a new Objective-C @finally statement.
   1167   ///
   1168   /// By default, performs semantic analysis to build the new statement.
   1169   /// Subclasses may override this routine to provide different behavior.
   1170   StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
   1171                                             Stmt *Body) {
   1172     return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
   1173   }
   1174 
   1175   /// \brief Build a new Objective-C @throw statement.
   1176   ///
   1177   /// By default, performs semantic analysis to build the new statement.
   1178   /// Subclasses may override this routine to provide different behavior.
   1179   StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
   1180                                           Expr *Operand) {
   1181     return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
   1182   }
   1183 
   1184   /// \brief Build a new Objective-C @synchronized statement.
   1185   ///
   1186   /// By default, performs semantic analysis to build the new statement.
   1187   /// Subclasses may override this routine to provide different behavior.
   1188   StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
   1189                                                  Expr *Object,
   1190                                                  Stmt *Body) {
   1191     return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object,
   1192                                                  Body);
   1193   }
   1194 
   1195   /// \brief Build a new Objective-C @autoreleasepool statement.
   1196   ///
   1197   /// By default, performs semantic analysis to build the new statement.
   1198   /// Subclasses may override this routine to provide different behavior.
   1199   StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
   1200                                             Stmt *Body) {
   1201     return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
   1202   }
   1203 
   1204 
   1205   /// \brief Build a new Objective-C fast enumeration statement.
   1206   ///
   1207   /// By default, performs semantic analysis to build the new statement.
   1208   /// Subclasses may override this routine to provide different behavior.
   1209   StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
   1210                                           SourceLocation LParenLoc,
   1211                                           Stmt *Element,
   1212                                           Expr *Collection,
   1213                                           SourceLocation RParenLoc,
   1214                                           Stmt *Body) {
   1215     return getSema().ActOnObjCForCollectionStmt(ForLoc, LParenLoc,
   1216                                                 Element,
   1217                                                 Collection,
   1218                                                 RParenLoc,
   1219                                                 Body);
   1220   }
   1221 
   1222   /// \brief Build a new C++ exception declaration.
   1223   ///
   1224   /// By default, performs semantic analysis to build the new decaration.
   1225   /// Subclasses may override this routine to provide different behavior.
   1226   VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
   1227                                 TypeSourceInfo *Declarator,
   1228                                 SourceLocation StartLoc,
   1229                                 SourceLocation IdLoc,
   1230                                 IdentifierInfo *Id) {
   1231     VarDecl *Var = getSema().BuildExceptionDeclaration(0, Declarator,
   1232                                                        StartLoc, IdLoc, Id);
   1233     if (Var)
   1234       getSema().CurContext->addDecl(Var);
   1235     return Var;
   1236   }
   1237 
   1238   /// \brief Build a new C++ catch statement.
   1239   ///
   1240   /// By default, performs semantic analysis to build the new statement.
   1241   /// Subclasses may override this routine to provide different behavior.
   1242   StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
   1243                                  VarDecl *ExceptionDecl,
   1244                                  Stmt *Handler) {
   1245     return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
   1246                                                       Handler));
   1247   }
   1248 
   1249   /// \brief Build a new C++ try statement.
   1250   ///
   1251   /// By default, performs semantic analysis to build the new statement.
   1252   /// Subclasses may override this routine to provide different behavior.
   1253   StmtResult RebuildCXXTryStmt(SourceLocation TryLoc,
   1254                                Stmt *TryBlock,
   1255                                MultiStmtArg Handlers) {
   1256     return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, move(Handlers));
   1257   }
   1258 
   1259   /// \brief Build a new C++0x range-based for statement.
   1260   ///
   1261   /// By default, performs semantic analysis to build the new statement.
   1262   /// Subclasses may override this routine to provide different behavior.
   1263   StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
   1264                                     SourceLocation ColonLoc,
   1265                                     Stmt *Range, Stmt *BeginEnd,
   1266                                     Expr *Cond, Expr *Inc,
   1267                                     Stmt *LoopVar,
   1268                                     SourceLocation RParenLoc) {
   1269     return getSema().BuildCXXForRangeStmt(ForLoc, ColonLoc, Range, BeginEnd,
   1270                                           Cond, Inc, LoopVar, RParenLoc);
   1271   }
   1272 
   1273   /// \brief Attach body to a C++0x range-based for statement.
   1274   ///
   1275   /// By default, performs semantic analysis to finish the new statement.
   1276   /// Subclasses may override this routine to provide different behavior.
   1277   StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
   1278     return getSema().FinishCXXForRangeStmt(ForRange, Body);
   1279   }
   1280 
   1281   StmtResult RebuildSEHTryStmt(bool IsCXXTry,
   1282                                SourceLocation TryLoc,
   1283                                Stmt *TryBlock,
   1284                                Stmt *Handler) {
   1285     return getSema().ActOnSEHTryBlock(IsCXXTry,TryLoc,TryBlock,Handler);
   1286   }
   1287 
   1288   StmtResult RebuildSEHExceptStmt(SourceLocation Loc,
   1289                                   Expr *FilterExpr,
   1290                                   Stmt *Block) {
   1291     return getSema().ActOnSEHExceptBlock(Loc,FilterExpr,Block);
   1292   }
   1293 
   1294   StmtResult RebuildSEHFinallyStmt(SourceLocation Loc,
   1295                                    Stmt *Block) {
   1296     return getSema().ActOnSEHFinallyBlock(Loc,Block);
   1297   }
   1298 
   1299   /// \brief Build a new expression that references a declaration.
   1300   ///
   1301   /// By default, performs semantic analysis to build the new expression.
   1302   /// Subclasses may override this routine to provide different behavior.
   1303   ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
   1304                                         LookupResult &R,
   1305                                         bool RequiresADL) {
   1306     return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
   1307   }
   1308 
   1309 
   1310   /// \brief Build a new expression that references a declaration.
   1311   ///
   1312   /// By default, performs semantic analysis to build the new expression.
   1313   /// Subclasses may override this routine to provide different behavior.
   1314   ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
   1315                                 ValueDecl *VD,
   1316                                 const DeclarationNameInfo &NameInfo,
   1317                                 TemplateArgumentListInfo *TemplateArgs) {
   1318     CXXScopeSpec SS;
   1319     SS.Adopt(QualifierLoc);
   1320 
   1321     // FIXME: loses template args.
   1322 
   1323     return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD);
   1324   }
   1325 
   1326   /// \brief Build a new expression in parentheses.
   1327   ///
   1328   /// By default, performs semantic analysis to build the new expression.
   1329   /// Subclasses may override this routine to provide different behavior.
   1330   ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
   1331                                     SourceLocation RParen) {
   1332     return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
   1333   }
   1334 
   1335   /// \brief Build a new pseudo-destructor expression.
   1336   ///
   1337   /// By default, performs semantic analysis to build the new expression.
   1338   /// Subclasses may override this routine to provide different behavior.
   1339   ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
   1340                                             SourceLocation OperatorLoc,
   1341                                             bool isArrow,
   1342                                             CXXScopeSpec &SS,
   1343                                             TypeSourceInfo *ScopeType,
   1344                                             SourceLocation CCLoc,
   1345                                             SourceLocation TildeLoc,
   1346                                         PseudoDestructorTypeStorage Destroyed);
   1347 
   1348   /// \brief Build a new unary operator expression.
   1349   ///
   1350   /// By default, performs semantic analysis to build the new expression.
   1351   /// Subclasses may override this routine to provide different behavior.
   1352   ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
   1353                                         UnaryOperatorKind Opc,
   1354                                         Expr *SubExpr) {
   1355     return getSema().BuildUnaryOp(/*Scope=*/0, OpLoc, Opc, SubExpr);
   1356   }
   1357 
   1358   /// \brief Build a new builtin offsetof expression.
   1359   ///
   1360   /// By default, performs semantic analysis to build the new expression.
   1361   /// Subclasses may override this routine to provide different behavior.
   1362   ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
   1363                                        TypeSourceInfo *Type,
   1364                                        Sema::OffsetOfComponent *Components,
   1365                                        unsigned NumComponents,
   1366                                        SourceLocation RParenLoc) {
   1367     return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
   1368                                           NumComponents, RParenLoc);
   1369   }
   1370 
   1371   /// \brief Build a new sizeof, alignof or vec_step expression with a
   1372   /// type argument.
   1373   ///
   1374   /// By default, performs semantic analysis to build the new expression.
   1375   /// Subclasses may override this routine to provide different behavior.
   1376   ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
   1377                                          SourceLocation OpLoc,
   1378                                          UnaryExprOrTypeTrait ExprKind,
   1379                                          SourceRange R) {
   1380     return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
   1381   }
   1382 
   1383   /// \brief Build a new sizeof, alignof or vec step expression with an
   1384   /// expression argument.
   1385   ///
   1386   /// By default, performs semantic analysis to build the new expression.
   1387   /// Subclasses may override this routine to provide different behavior.
   1388   ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
   1389                                          UnaryExprOrTypeTrait ExprKind,
   1390                                          SourceRange R) {
   1391     ExprResult Result
   1392       = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
   1393     if (Result.isInvalid())
   1394       return ExprError();
   1395 
   1396     return move(Result);
   1397   }
   1398 
   1399   /// \brief Build a new array subscript expression.
   1400   ///
   1401   /// By default, performs semantic analysis to build the new expression.
   1402   /// Subclasses may override this routine to provide different behavior.
   1403   ExprResult RebuildArraySubscriptExpr(Expr *LHS,
   1404                                              SourceLocation LBracketLoc,
   1405                                              Expr *RHS,
   1406                                              SourceLocation RBracketLoc) {
   1407     return getSema().ActOnArraySubscriptExpr(/*Scope=*/0, LHS,
   1408                                              LBracketLoc, RHS,
   1409                                              RBracketLoc);
   1410   }
   1411 
   1412   /// \brief Build a new call expression.
   1413   ///
   1414   /// By default, performs semantic analysis to build the new expression.
   1415   /// Subclasses may override this routine to provide different behavior.
   1416   ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
   1417                                    MultiExprArg Args,
   1418                                    SourceLocation RParenLoc,
   1419                                    Expr *ExecConfig = 0) {
   1420     return getSema().ActOnCallExpr(/*Scope=*/0, Callee, LParenLoc,
   1421                                    move(Args), RParenLoc, ExecConfig);
   1422   }
   1423 
   1424   /// \brief Build a new member access expression.
   1425   ///
   1426   /// By default, performs semantic analysis to build the new expression.
   1427   /// Subclasses may override this routine to provide different behavior.
   1428   ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
   1429                                bool isArrow,
   1430                                NestedNameSpecifierLoc QualifierLoc,
   1431                                const DeclarationNameInfo &MemberNameInfo,
   1432                                ValueDecl *Member,
   1433                                NamedDecl *FoundDecl,
   1434                         const TemplateArgumentListInfo *ExplicitTemplateArgs,
   1435                                NamedDecl *FirstQualifierInScope) {
   1436     if (!Member->getDeclName()) {
   1437       // We have a reference to an unnamed field.  This is always the
   1438       // base of an anonymous struct/union member access, i.e. the
   1439       // field is always of record type.
   1440       assert(!QualifierLoc && "Can't have an unnamed field with a qualifier!");
   1441       assert(Member->getType()->isRecordType() &&
   1442              "unnamed member not of record type?");
   1443 
   1444       ExprResult BaseResult =
   1445         getSema().PerformObjectMemberConversion(Base,
   1446                                                 QualifierLoc.getNestedNameSpecifier(),
   1447                                                 FoundDecl, Member);
   1448       if (BaseResult.isInvalid())
   1449         return ExprError();
   1450       Base = BaseResult.take();
   1451       ExprValueKind VK = isArrow ? VK_LValue : Base->getValueKind();
   1452       MemberExpr *ME =
   1453         new (getSema().Context) MemberExpr(Base, isArrow,
   1454                                            Member, MemberNameInfo,
   1455                                            cast<FieldDecl>(Member)->getType(),
   1456                                            VK, OK_Ordinary);
   1457       return getSema().Owned(ME);
   1458     }
   1459 
   1460     CXXScopeSpec SS;
   1461     SS.Adopt(QualifierLoc);
   1462 
   1463     ExprResult BaseResult = getSema().DefaultFunctionArrayConversion(Base);
   1464     if (BaseResult.isInvalid())
   1465       return ExprError();
   1466     Base = BaseResult.take();
   1467     QualType BaseType = Base->getType();
   1468 
   1469     // FIXME: this involves duplicating earlier analysis in a lot of
   1470     // cases; we should avoid this when possible.
   1471     LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
   1472     R.addDecl(FoundDecl);
   1473     R.resolveKind();
   1474 
   1475     return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
   1476                                               SS, FirstQualifierInScope,
   1477                                               R, ExplicitTemplateArgs);
   1478   }
   1479 
   1480   /// \brief Build a new binary operator expression.
   1481   ///
   1482   /// By default, performs semantic analysis to build the new expression.
   1483   /// Subclasses may override this routine to provide different behavior.
   1484   ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
   1485                                          BinaryOperatorKind Opc,
   1486                                          Expr *LHS, Expr *RHS) {
   1487     return getSema().BuildBinOp(/*Scope=*/0, OpLoc, Opc, LHS, RHS);
   1488   }
   1489 
   1490   /// \brief Build a new conditional operator expression.
   1491   ///
   1492   /// By default, performs semantic analysis to build the new expression.
   1493   /// Subclasses may override this routine to provide different behavior.
   1494   ExprResult RebuildConditionalOperator(Expr *Cond,
   1495                                         SourceLocation QuestionLoc,
   1496                                         Expr *LHS,
   1497                                         SourceLocation ColonLoc,
   1498                                         Expr *RHS) {
   1499     return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
   1500                                         LHS, RHS);
   1501   }
   1502 
   1503   /// \brief Build a new C-style cast expression.
   1504   ///
   1505   /// By default, performs semantic analysis to build the new expression.
   1506   /// Subclasses may override this routine to provide different behavior.
   1507   ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
   1508                                          TypeSourceInfo *TInfo,
   1509                                          SourceLocation RParenLoc,
   1510                                          Expr *SubExpr) {
   1511     return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
   1512                                          SubExpr);
   1513   }
   1514 
   1515   /// \brief Build a new compound literal expression.
   1516   ///
   1517   /// By default, performs semantic analysis to build the new expression.
   1518   /// Subclasses may override this routine to provide different behavior.
   1519   ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
   1520                                               TypeSourceInfo *TInfo,
   1521                                               SourceLocation RParenLoc,
   1522                                               Expr *Init) {
   1523     return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
   1524                                               Init);
   1525   }
   1526 
   1527   /// \brief Build a new extended vector element access expression.
   1528   ///
   1529   /// By default, performs semantic analysis to build the new expression.
   1530   /// Subclasses may override this routine to provide different behavior.
   1531   ExprResult RebuildExtVectorElementExpr(Expr *Base,
   1532                                                SourceLocation OpLoc,
   1533                                                SourceLocation AccessorLoc,
   1534                                                IdentifierInfo &Accessor) {
   1535 
   1536     CXXScopeSpec SS;
   1537     DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
   1538     return getSema().BuildMemberReferenceExpr(Base, Base->getType(),
   1539                                               OpLoc, /*IsArrow*/ false,
   1540                                               SS, /*FirstQualifierInScope*/ 0,
   1541                                               NameInfo,
   1542                                               /* TemplateArgs */ 0);
   1543   }
   1544 
   1545   /// \brief Build a new initializer list expression.
   1546   ///
   1547   /// By default, performs semantic analysis to build the new expression.
   1548   /// Subclasses may override this routine to provide different behavior.
   1549   ExprResult RebuildInitList(SourceLocation LBraceLoc,
   1550                              MultiExprArg Inits,
   1551                              SourceLocation RBraceLoc,
   1552                              QualType ResultTy) {
   1553     ExprResult Result
   1554       = SemaRef.ActOnInitList(LBraceLoc, move(Inits), RBraceLoc);
   1555     if (Result.isInvalid() || ResultTy->isDependentType())
   1556       return move(Result);
   1557 
   1558     // Patch in the result type we were given, which may have been computed
   1559     // when the initial InitListExpr was built.
   1560     InitListExpr *ILE = cast<InitListExpr>((Expr *)Result.get());
   1561     ILE->setType(ResultTy);
   1562     return move(Result);
   1563   }
   1564 
   1565   /// \brief Build a new designated initializer expression.
   1566   ///
   1567   /// By default, performs semantic analysis to build the new expression.
   1568   /// Subclasses may override this routine to provide different behavior.
   1569   ExprResult RebuildDesignatedInitExpr(Designation &Desig,
   1570                                              MultiExprArg ArrayExprs,
   1571                                              SourceLocation EqualOrColonLoc,
   1572                                              bool GNUSyntax,
   1573                                              Expr *Init) {
   1574     ExprResult Result
   1575       = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
   1576                                            Init);
   1577     if (Result.isInvalid())
   1578       return ExprError();
   1579 
   1580     ArrayExprs.release();
   1581     return move(Result);
   1582   }
   1583 
   1584   /// \brief Build a new value-initialized expression.
   1585   ///
   1586   /// By default, builds the implicit value initialization without performing
   1587   /// any semantic analysis. Subclasses may override this routine to provide
   1588   /// different behavior.
   1589   ExprResult RebuildImplicitValueInitExpr(QualType T) {
   1590     return SemaRef.Owned(new (SemaRef.Context) ImplicitValueInitExpr(T));
   1591   }
   1592 
   1593   /// \brief Build a new \c va_arg expression.
   1594   ///
   1595   /// By default, performs semantic analysis to build the new expression.
   1596   /// Subclasses may override this routine to provide different behavior.
   1597   ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
   1598                                     Expr *SubExpr, TypeSourceInfo *TInfo,
   1599                                     SourceLocation RParenLoc) {
   1600     return getSema().BuildVAArgExpr(BuiltinLoc,
   1601                                     SubExpr, TInfo,
   1602                                     RParenLoc);
   1603   }
   1604 
   1605   /// \brief Build a new expression list in parentheses.
   1606   ///
   1607   /// By default, performs semantic analysis to build the new expression.
   1608   /// Subclasses may override this routine to provide different behavior.
   1609   ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
   1610                                         MultiExprArg SubExprs,
   1611                                         SourceLocation RParenLoc) {
   1612     return getSema().ActOnParenOrParenListExpr(LParenLoc, RParenLoc,
   1613                                                move(SubExprs));
   1614   }
   1615 
   1616   /// \brief Build a new address-of-label expression.
   1617   ///
   1618   /// By default, performs semantic analysis, using the name of the label
   1619   /// rather than attempting to map the label statement itself.
   1620   /// Subclasses may override this routine to provide different behavior.
   1621   ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
   1622                                   SourceLocation LabelLoc, LabelDecl *Label) {
   1623     return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
   1624   }
   1625 
   1626   /// \brief Build a new GNU statement expression.
   1627   ///
   1628   /// By default, performs semantic analysis to build the new expression.
   1629   /// Subclasses may override this routine to provide different behavior.
   1630   ExprResult RebuildStmtExpr(SourceLocation LParenLoc,
   1631                                    Stmt *SubStmt,
   1632                                    SourceLocation RParenLoc) {
   1633     return getSema().ActOnStmtExpr(LParenLoc, SubStmt, RParenLoc);
   1634   }
   1635 
   1636   /// \brief Build a new __builtin_choose_expr expression.
   1637   ///
   1638   /// By default, performs semantic analysis to build the new expression.
   1639   /// Subclasses may override this routine to provide different behavior.
   1640   ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
   1641                                      Expr *Cond, Expr *LHS, Expr *RHS,
   1642                                      SourceLocation RParenLoc) {
   1643     return SemaRef.ActOnChooseExpr(BuiltinLoc,
   1644                                    Cond, LHS, RHS,
   1645                                    RParenLoc);
   1646   }
   1647 
   1648   /// \brief Build a new generic selection expression.
   1649   ///
   1650   /// By default, performs semantic analysis to build the new expression.
   1651   /// Subclasses may override this routine to provide different behavior.
   1652   ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
   1653                                          SourceLocation DefaultLoc,
   1654                                          SourceLocation RParenLoc,
   1655                                          Expr *ControllingExpr,
   1656                                          TypeSourceInfo **Types,
   1657                                          Expr **Exprs,
   1658                                          unsigned NumAssocs) {
   1659     return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
   1660                                                 ControllingExpr, Types, Exprs,
   1661                                                 NumAssocs);
   1662   }
   1663 
   1664   /// \brief Build a new overloaded operator call expression.
   1665   ///
   1666   /// By default, performs semantic analysis to build the new expression.
   1667   /// The semantic analysis provides the behavior of template instantiation,
   1668   /// copying with transformations that turn what looks like an overloaded
   1669   /// operator call into a use of a builtin operator, performing
   1670   /// argument-dependent lookup, etc. Subclasses may override this routine to
   1671   /// provide different behavior.
   1672   ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
   1673                                               SourceLocation OpLoc,
   1674                                               Expr *Callee,
   1675                                               Expr *First,
   1676                                               Expr *Second);
   1677 
   1678   /// \brief Build a new C++ "named" cast expression, such as static_cast or
   1679   /// reinterpret_cast.
   1680   ///
   1681   /// By default, this routine dispatches to one of the more-specific routines
   1682   /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
   1683   /// Subclasses may override this routine to provide different behavior.
   1684   ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
   1685                                            Stmt::StmtClass Class,
   1686                                            SourceLocation LAngleLoc,
   1687                                            TypeSourceInfo *TInfo,
   1688                                            SourceLocation RAngleLoc,
   1689                                            SourceLocation LParenLoc,
   1690                                            Expr *SubExpr,
   1691                                            SourceLocation RParenLoc) {
   1692     switch (Class) {
   1693     case Stmt::CXXStaticCastExprClass:
   1694       return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
   1695                                                    RAngleLoc, LParenLoc,
   1696                                                    SubExpr, RParenLoc);
   1697 
   1698     case Stmt::CXXDynamicCastExprClass:
   1699       return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
   1700                                                     RAngleLoc, LParenLoc,
   1701                                                     SubExpr, RParenLoc);
   1702 
   1703     case Stmt::CXXReinterpretCastExprClass:
   1704       return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
   1705                                                         RAngleLoc, LParenLoc,
   1706                                                         SubExpr,
   1707                                                         RParenLoc);
   1708 
   1709     case Stmt::CXXConstCastExprClass:
   1710       return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
   1711                                                    RAngleLoc, LParenLoc,
   1712                                                    SubExpr, RParenLoc);
   1713 
   1714     default:
   1715       assert(false && "Invalid C++ named cast");
   1716       break;
   1717     }
   1718 
   1719     return ExprError();
   1720   }
   1721 
   1722   /// \brief Build a new C++ static_cast expression.
   1723   ///
   1724   /// By default, performs semantic analysis to build the new expression.
   1725   /// Subclasses may override this routine to provide different behavior.
   1726   ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
   1727                                             SourceLocation LAngleLoc,
   1728                                             TypeSourceInfo *TInfo,
   1729                                             SourceLocation RAngleLoc,
   1730                                             SourceLocation LParenLoc,
   1731                                             Expr *SubExpr,
   1732                                             SourceLocation RParenLoc) {
   1733     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
   1734                                        TInfo, SubExpr,
   1735                                        SourceRange(LAngleLoc, RAngleLoc),
   1736                                        SourceRange(LParenLoc, RParenLoc));
   1737   }
   1738 
   1739   /// \brief Build a new C++ dynamic_cast expression.
   1740   ///
   1741   /// By default, performs semantic analysis to build the new expression.
   1742   /// Subclasses may override this routine to provide different behavior.
   1743   ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
   1744                                              SourceLocation LAngleLoc,
   1745                                              TypeSourceInfo *TInfo,
   1746                                              SourceLocation RAngleLoc,
   1747                                              SourceLocation LParenLoc,
   1748                                              Expr *SubExpr,
   1749                                              SourceLocation RParenLoc) {
   1750     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
   1751                                        TInfo, SubExpr,
   1752                                        SourceRange(LAngleLoc, RAngleLoc),
   1753                                        SourceRange(LParenLoc, RParenLoc));
   1754   }
   1755 
   1756   /// \brief Build a new C++ reinterpret_cast expression.
   1757   ///
   1758   /// By default, performs semantic analysis to build the new expression.
   1759   /// Subclasses may override this routine to provide different behavior.
   1760   ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
   1761                                                  SourceLocation LAngleLoc,
   1762                                                  TypeSourceInfo *TInfo,
   1763                                                  SourceLocation RAngleLoc,
   1764                                                  SourceLocation LParenLoc,
   1765                                                  Expr *SubExpr,
   1766                                                  SourceLocation RParenLoc) {
   1767     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
   1768                                        TInfo, SubExpr,
   1769                                        SourceRange(LAngleLoc, RAngleLoc),
   1770                                        SourceRange(LParenLoc, RParenLoc));
   1771   }
   1772 
   1773   /// \brief Build a new C++ const_cast expression.
   1774   ///
   1775   /// By default, performs semantic analysis to build the new expression.
   1776   /// Subclasses may override this routine to provide different behavior.
   1777   ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
   1778                                            SourceLocation LAngleLoc,
   1779                                            TypeSourceInfo *TInfo,
   1780                                            SourceLocation RAngleLoc,
   1781                                            SourceLocation LParenLoc,
   1782                                            Expr *SubExpr,
   1783                                            SourceLocation RParenLoc) {
   1784     return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
   1785                                        TInfo, SubExpr,
   1786                                        SourceRange(LAngleLoc, RAngleLoc),
   1787                                        SourceRange(LParenLoc, RParenLoc));
   1788   }
   1789 
   1790   /// \brief Build a new C++ functional-style cast expression.
   1791   ///
   1792   /// By default, performs semantic analysis to build the new expression.
   1793   /// Subclasses may override this routine to provide different behavior.
   1794   ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
   1795                                           SourceLocation LParenLoc,
   1796                                           Expr *Sub,
   1797                                           SourceLocation RParenLoc) {
   1798     return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
   1799                                                MultiExprArg(&Sub, 1),
   1800                                                RParenLoc);
   1801   }
   1802 
   1803   /// \brief Build a new C++ typeid(type) expression.
   1804   ///
   1805   /// By default, performs semantic analysis to build the new expression.
   1806   /// Subclasses may override this routine to provide different behavior.
   1807   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
   1808                                         SourceLocation TypeidLoc,
   1809                                         TypeSourceInfo *Operand,
   1810                                         SourceLocation RParenLoc) {
   1811     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
   1812                                     RParenLoc);
   1813   }
   1814 
   1815 
   1816   /// \brief Build a new C++ typeid(expr) expression.
   1817   ///
   1818   /// By default, performs semantic analysis to build the new expression.
   1819   /// Subclasses may override this routine to provide different behavior.
   1820   ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
   1821                                         SourceLocation TypeidLoc,
   1822                                         Expr *Operand,
   1823                                         SourceLocation RParenLoc) {
   1824     return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
   1825                                     RParenLoc);
   1826   }
   1827 
   1828   /// \brief Build a new C++ __uuidof(type) expression.
   1829   ///
   1830   /// By default, performs semantic analysis to build the new expression.
   1831   /// Subclasses may override this routine to provide different behavior.
   1832   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
   1833                                         SourceLocation TypeidLoc,
   1834                                         TypeSourceInfo *Operand,
   1835                                         SourceLocation RParenLoc) {
   1836     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
   1837                                     RParenLoc);
   1838   }
   1839 
   1840   /// \brief Build a new C++ __uuidof(expr) expression.
   1841   ///
   1842   /// By default, performs semantic analysis to build the new expression.
   1843   /// Subclasses may override this routine to provide different behavior.
   1844   ExprResult RebuildCXXUuidofExpr(QualType TypeInfoType,
   1845                                         SourceLocation TypeidLoc,
   1846                                         Expr *Operand,
   1847                                         SourceLocation RParenLoc) {
   1848     return getSema().BuildCXXUuidof(TypeInfoType, TypeidLoc, Operand,
   1849                                     RParenLoc);
   1850   }
   1851 
   1852   /// \brief Build a new C++ "this" expression.
   1853   ///
   1854   /// By default, builds a new "this" expression without performing any
   1855   /// semantic analysis. Subclasses may override this routine to provide
   1856   /// different behavior.
   1857   ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
   1858                                 QualType ThisType,
   1859                                 bool isImplicit) {
   1860     return getSema().Owned(
   1861                       new (getSema().Context) CXXThisExpr(ThisLoc, ThisType,
   1862                                                           isImplicit));
   1863   }
   1864 
   1865   /// \brief Build a new C++ throw expression.
   1866   ///
   1867   /// By default, performs semantic analysis to build the new expression.
   1868   /// Subclasses may override this routine to provide different behavior.
   1869   ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
   1870                                  bool IsThrownVariableInScope) {
   1871     return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
   1872   }
   1873 
   1874   /// \brief Build a new C++ default-argument expression.
   1875   ///
   1876   /// By default, builds a new default-argument expression, which does not
   1877   /// require any semantic analysis. Subclasses may override this routine to
   1878   /// provide different behavior.
   1879   ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc,
   1880                                             ParmVarDecl *Param) {
   1881     return getSema().Owned(CXXDefaultArgExpr::Create(getSema().Context, Loc,
   1882                                                      Param));
   1883   }
   1884 
   1885   /// \brief Build a new C++ zero-initialization expression.
   1886   ///
   1887   /// By default, performs semantic analysis to build the new expression.
   1888   /// Subclasses may override this routine to provide different behavior.
   1889   ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
   1890                                            SourceLocation LParenLoc,
   1891                                            SourceLocation RParenLoc) {
   1892     return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc,
   1893                                                MultiExprArg(getSema(), 0, 0),
   1894                                                RParenLoc);
   1895   }
   1896 
   1897   /// \brief Build a new C++ "new" expression.
   1898   ///
   1899   /// By default, performs semantic analysis to build the new expression.
   1900   /// Subclasses may override this routine to provide different behavior.
   1901   ExprResult RebuildCXXNewExpr(SourceLocation StartLoc,
   1902                                bool UseGlobal,
   1903                                SourceLocation PlacementLParen,
   1904                                MultiExprArg PlacementArgs,
   1905                                SourceLocation PlacementRParen,
   1906                                SourceRange TypeIdParens,
   1907                                QualType AllocatedType,
   1908                                TypeSourceInfo *AllocatedTypeInfo,
   1909                                Expr *ArraySize,
   1910                                SourceLocation ConstructorLParen,
   1911                                MultiExprArg ConstructorArgs,
   1912                                SourceLocation ConstructorRParen) {
   1913     return getSema().BuildCXXNew(StartLoc, UseGlobal,
   1914                                  PlacementLParen,
   1915                                  move(PlacementArgs),
   1916                                  PlacementRParen,
   1917                                  TypeIdParens,
   1918                                  AllocatedType,
   1919                                  AllocatedTypeInfo,
   1920                                  ArraySize,
   1921                                  ConstructorLParen,
   1922                                  move(ConstructorArgs),
   1923                                  ConstructorRParen);
   1924   }
   1925 
   1926   /// \brief Build a new C++ "delete" expression.
   1927   ///
   1928   /// By default, performs semantic analysis to build the new expression.
   1929   /// Subclasses may override this routine to provide different behavior.
   1930   ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
   1931                                         bool IsGlobalDelete,
   1932                                         bool IsArrayForm,
   1933                                         Expr *Operand) {
   1934     return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
   1935                                     Operand);
   1936   }
   1937 
   1938   /// \brief Build a new unary type trait expression.
   1939   ///
   1940   /// By default, performs semantic analysis to build the new expression.
   1941   /// Subclasses may override this routine to provide different behavior.
   1942   ExprResult RebuildUnaryTypeTrait(UnaryTypeTrait Trait,
   1943                                    SourceLocation StartLoc,
   1944                                    TypeSourceInfo *T,
   1945                                    SourceLocation RParenLoc) {
   1946     return getSema().BuildUnaryTypeTrait(Trait, StartLoc, T, RParenLoc);
   1947   }
   1948 
   1949   /// \brief Build a new binary type trait expression.
   1950   ///
   1951   /// By default, performs semantic analysis to build the new expression.
   1952   /// Subclasses may override this routine to provide different behavior.
   1953   ExprResult RebuildBinaryTypeTrait(BinaryTypeTrait Trait,
   1954                                     SourceLocation StartLoc,
   1955                                     TypeSourceInfo *LhsT,
   1956                                     TypeSourceInfo *RhsT,
   1957                                     SourceLocation RParenLoc) {
   1958     return getSema().BuildBinaryTypeTrait(Trait, StartLoc, LhsT, RhsT, RParenLoc);
   1959   }
   1960 
   1961   /// \brief Build a new array type trait expression.
   1962   ///
   1963   /// By default, performs semantic analysis to build the new expression.
   1964   /// Subclasses may override this routine to provide different behavior.
   1965   ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
   1966                                    SourceLocation StartLoc,
   1967                                    TypeSourceInfo *TSInfo,
   1968                                    Expr *DimExpr,
   1969                                    SourceLocation RParenLoc) {
   1970     return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
   1971   }
   1972 
   1973   /// \brief Build a new expression trait expression.
   1974   ///
   1975   /// By default, performs semantic analysis to build the new expression.
   1976   /// Subclasses may override this routine to provide different behavior.
   1977   ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
   1978                                    SourceLocation StartLoc,
   1979                                    Expr *Queried,
   1980                                    SourceLocation RParenLoc) {
   1981     return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
   1982   }
   1983 
   1984   /// \brief Build a new (previously unresolved) declaration reference
   1985   /// expression.
   1986   ///
   1987   /// By default, performs semantic analysis to build the new expression.
   1988   /// Subclasses may override this routine to provide different behavior.
   1989   ExprResult RebuildDependentScopeDeclRefExpr(
   1990                                           NestedNameSpecifierLoc QualifierLoc,
   1991                                        const DeclarationNameInfo &NameInfo,
   1992                               const TemplateArgumentListInfo *TemplateArgs) {
   1993     CXXScopeSpec SS;
   1994     SS.Adopt(QualifierLoc);
   1995 
   1996     if (TemplateArgs)
   1997       return getSema().BuildQualifiedTemplateIdExpr(SS, NameInfo,
   1998                                                     *TemplateArgs);
   1999 
   2000     return getSema().BuildQualifiedDeclarationNameExpr(SS, NameInfo);
   2001   }
   2002 
   2003   /// \brief Build a new template-id expression.
   2004   ///
   2005   /// By default, performs semantic analysis to build the new expression.
   2006   /// Subclasses may override this routine to provide different behavior.
   2007   ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
   2008                                          LookupResult &R,
   2009                                          bool RequiresADL,
   2010                               const TemplateArgumentListInfo &TemplateArgs) {
   2011     return getSema().BuildTemplateIdExpr(SS, R, RequiresADL, TemplateArgs);
   2012   }
   2013 
   2014   /// \brief Build a new object-construction expression.
   2015   ///
   2016   /// By default, performs semantic analysis to build the new expression.
   2017   /// Subclasses may override this routine to provide different behavior.
   2018   ExprResult RebuildCXXConstructExpr(QualType T,
   2019                                            SourceLocation Loc,
   2020                                            CXXConstructorDecl *Constructor,
   2021                                            bool IsElidable,
   2022                                            MultiExprArg Args,
   2023                                            bool RequiresZeroInit,
   2024                              CXXConstructExpr::ConstructionKind ConstructKind,
   2025                                            SourceRange ParenRange) {
   2026     ASTOwningVector<Expr*> ConvertedArgs(SemaRef);
   2027     if (getSema().CompleteConstructorCall(Constructor, move(Args), Loc,
   2028                                           ConvertedArgs))
   2029       return ExprError();
   2030 
   2031     return getSema().BuildCXXConstructExpr(Loc, T, Constructor, IsElidable,
   2032                                            move_arg(ConvertedArgs),
   2033                                            RequiresZeroInit, ConstructKind,
   2034                                            ParenRange);
   2035   }
   2036 
   2037   /// \brief Build a new object-construction expression.
   2038   ///
   2039   /// By default, performs semantic analysis to build the new expression.
   2040   /// Subclasses may override this routine to provide different behavior.
   2041   ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
   2042                                            SourceLocation LParenLoc,
   2043                                            MultiExprArg Args,
   2044                                            SourceLocation RParenLoc) {
   2045     return getSema().BuildCXXTypeConstructExpr(TSInfo,
   2046                                                LParenLoc,
   2047                                                move(Args),
   2048                                                RParenLoc);
   2049   }
   2050 
   2051   /// \brief Build a new object-construction expression.
   2052   ///
   2053   /// By default, performs semantic analysis to build the new expression.
   2054   /// Subclasses may override this routine to provide different behavior.
   2055   ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
   2056                                                SourceLocation LParenLoc,
   2057                                                MultiExprArg Args,
   2058                                                SourceLocation RParenLoc) {
   2059     return getSema().BuildCXXTypeConstructExpr(TSInfo,
   2060                                                LParenLoc,
   2061                                                move(Args),
   2062                                                RParenLoc);
   2063   }
   2064 
   2065   /// \brief Build a new member reference expression.
   2066   ///
   2067   /// By default, performs semantic analysis to build the new expression.
   2068   /// Subclasses may override this routine to provide different behavior.
   2069   ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
   2070                                                 QualType BaseType,
   2071                                                 bool IsArrow,
   2072                                                 SourceLocation OperatorLoc,
   2073                                           NestedNameSpecifierLoc QualifierLoc,
   2074                                             NamedDecl *FirstQualifierInScope,
   2075                                    const DeclarationNameInfo &MemberNameInfo,
   2076                               const TemplateArgumentListInfo *TemplateArgs) {
   2077     CXXScopeSpec SS;
   2078     SS.Adopt(QualifierLoc);
   2079 
   2080     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
   2081                                             OperatorLoc, IsArrow,
   2082                                             SS, FirstQualifierInScope,
   2083                                             MemberNameInfo,
   2084                                             TemplateArgs);
   2085   }
   2086 
   2087   /// \brief Build a new member reference expression.
   2088   ///
   2089   /// By default, performs semantic analysis to build the new expression.
   2090   /// Subclasses may override this routine to provide different behavior.
   2091   ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE,
   2092                                                QualType BaseType,
   2093                                                SourceLocation OperatorLoc,
   2094                                                bool IsArrow,
   2095                                            NestedNameSpecifierLoc QualifierLoc,
   2096                                                NamedDecl *FirstQualifierInScope,
   2097                                                LookupResult &R,
   2098                                 const TemplateArgumentListInfo *TemplateArgs) {
   2099     CXXScopeSpec SS;
   2100     SS.Adopt(QualifierLoc);
   2101 
   2102     return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
   2103                                             OperatorLoc, IsArrow,
   2104                                             SS, FirstQualifierInScope,
   2105                                             R, TemplateArgs);
   2106   }
   2107 
   2108   /// \brief Build a new noexcept expression.
   2109   ///
   2110   /// By default, performs semantic analysis to build the new expression.
   2111   /// Subclasses may override this routine to provide different behavior.
   2112   ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
   2113     return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
   2114   }
   2115 
   2116   /// \brief Build a new expression to compute the length of a parameter pack.
   2117   ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
   2118                                    SourceLocation PackLoc,
   2119                                    SourceLocation RParenLoc,
   2120                                    unsigned Length) {
   2121     return new (SemaRef.Context) SizeOfPackExpr(SemaRef.Context.getSizeType(),
   2122                                                 OperatorLoc, Pack, PackLoc,
   2123                                                 RParenLoc, Length);
   2124   }
   2125 
   2126   /// \brief Build a new Objective-C @encode expression.
   2127   ///
   2128   /// By default, performs semantic analysis to build the new expression.
   2129   /// Subclasses may override this routine to provide different behavior.
   2130   ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
   2131                                          TypeSourceInfo *EncodeTypeInfo,
   2132                                          SourceLocation RParenLoc) {
   2133     return SemaRef.Owned(SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo,
   2134                                                            RParenLoc));
   2135   }
   2136 
   2137   /// \brief Build a new Objective-C class message.
   2138   ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
   2139                                           Selector Sel,
   2140                                           SourceLocation SelectorLoc,
   2141                                           ObjCMethodDecl *Method,
   2142                                           SourceLocation LBracLoc,
   2143                                           MultiExprArg Args,
   2144                                           SourceLocation RBracLoc) {
   2145     return SemaRef.BuildClassMessage(ReceiverTypeInfo,
   2146                                      ReceiverTypeInfo->getType(),
   2147                                      /*SuperLoc=*/SourceLocation(),
   2148                                      Sel, Method, LBracLoc, SelectorLoc,
   2149                                      RBracLoc, move(Args));
   2150   }
   2151 
   2152   /// \brief Build a new Objective-C instance message.
   2153   ExprResult RebuildObjCMessageExpr(Expr *Receiver,
   2154                                           Selector Sel,
   2155                                           SourceLocation SelectorLoc,
   2156                                           ObjCMethodDecl *Method,
   2157                                           SourceLocation LBracLoc,
   2158                                           MultiExprArg Args,
   2159                                           SourceLocation RBracLoc) {
   2160     return SemaRef.BuildInstanceMessage(Receiver,
   2161                                         Receiver->getType(),
   2162                                         /*SuperLoc=*/SourceLocation(),
   2163                                         Sel, Method, LBracLoc, SelectorLoc,
   2164                                         RBracLoc, move(Args));
   2165   }
   2166 
   2167   /// \brief Build a new Objective-C ivar reference expression.
   2168   ///
   2169   /// By default, performs semantic analysis to build the new expression.
   2170   /// Subclasses may override this routine to provide different behavior.
   2171   ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
   2172                                           SourceLocation IvarLoc,
   2173                                           bool IsArrow, bool IsFreeIvar) {
   2174     // FIXME: We lose track of the IsFreeIvar bit.
   2175     CXXScopeSpec SS;
   2176     ExprResult Base = getSema().Owned(BaseArg);
   2177     LookupResult R(getSema(), Ivar->getDeclName(), IvarLoc,
   2178                    Sema::LookupMemberName);
   2179     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
   2180                                                          /*FIME:*/IvarLoc,
   2181                                                          SS, 0,
   2182                                                          false);
   2183     if (Result.isInvalid() || Base.isInvalid())
   2184       return ExprError();
   2185 
   2186     if (Result.get())
   2187       return move(Result);
   2188 
   2189     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
   2190                                               /*FIXME:*/IvarLoc, IsArrow, SS,
   2191                                               /*FirstQualifierInScope=*/0,
   2192                                               R,
   2193                                               /*TemplateArgs=*/0);
   2194   }
   2195 
   2196   /// \brief Build a new Objective-C property reference expression.
   2197   ///
   2198   /// By default, performs semantic analysis to build the new expression.
   2199   /// Subclasses may override this routine to provide different behavior.
   2200   ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
   2201                                               ObjCPropertyDecl *Property,
   2202                                               SourceLocation PropertyLoc) {
   2203     CXXScopeSpec SS;
   2204     ExprResult Base = getSema().Owned(BaseArg);
   2205     LookupResult R(getSema(), Property->getDeclName(), PropertyLoc,
   2206                    Sema::LookupMemberName);
   2207     bool IsArrow = false;
   2208     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
   2209                                                          /*FIME:*/PropertyLoc,
   2210                                                          SS, 0, false);
   2211     if (Result.isInvalid() || Base.isInvalid())
   2212       return ExprError();
   2213 
   2214     if (Result.get())
   2215       return move(Result);
   2216 
   2217     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
   2218                                               /*FIXME:*/PropertyLoc, IsArrow,
   2219                                               SS,
   2220                                               /*FirstQualifierInScope=*/0,
   2221                                               R,
   2222                                               /*TemplateArgs=*/0);
   2223   }
   2224 
   2225   /// \brief Build a new Objective-C property reference expression.
   2226   ///
   2227   /// By default, performs semantic analysis to build the new expression.
   2228   /// Subclasses may override this routine to provide different behavior.
   2229   ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
   2230                                         ObjCMethodDecl *Getter,
   2231                                         ObjCMethodDecl *Setter,
   2232                                         SourceLocation PropertyLoc) {
   2233     // Since these expressions can only be value-dependent, we do not
   2234     // need to perform semantic analysis again.
   2235     return Owned(
   2236       new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
   2237                                                   VK_LValue, OK_ObjCProperty,
   2238                                                   PropertyLoc, Base));
   2239   }
   2240 
   2241   /// \brief Build a new Objective-C "isa" expression.
   2242   ///
   2243   /// By default, performs semantic analysis to build the new expression.
   2244   /// Subclasses may override this routine to provide different behavior.
   2245   ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
   2246                                       bool IsArrow) {
   2247     CXXScopeSpec SS;
   2248     ExprResult Base = getSema().Owned(BaseArg);
   2249     LookupResult R(getSema(), &getSema().Context.Idents.get("isa"), IsaLoc,
   2250                    Sema::LookupMemberName);
   2251     ExprResult Result = getSema().LookupMemberExpr(R, Base, IsArrow,
   2252                                                          /*FIME:*/IsaLoc,
   2253                                                          SS, 0, false);
   2254     if (Result.isInvalid() || Base.isInvalid())
   2255       return ExprError();
   2256 
   2257     if (Result.get())
   2258       return move(Result);
   2259 
   2260     return getSema().BuildMemberReferenceExpr(Base.get(), Base.get()->getType(),
   2261                                               /*FIXME:*/IsaLoc, IsArrow, SS,
   2262                                               /*FirstQualifierInScope=*/0,
   2263                                               R,
   2264                                               /*TemplateArgs=*/0);
   2265   }
   2266 
   2267   /// \brief Build a new shuffle vector expression.
   2268   ///
   2269   /// By default, performs semantic analysis to build the new expression.
   2270   /// Subclasses may override this routine to provide different behavior.
   2271   ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
   2272                                       MultiExprArg SubExprs,
   2273                                       SourceLocation RParenLoc) {
   2274     // Find the declaration for __builtin_shufflevector
   2275     const IdentifierInfo &Name
   2276       = SemaRef.Context.Idents.get("__builtin_shufflevector");
   2277     TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
   2278     DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
   2279     assert(Lookup.first != Lookup.second && "No __builtin_shufflevector?");
   2280 
   2281     // Build a reference to the __builtin_shufflevector builtin
   2282     FunctionDecl *Builtin = cast<FunctionDecl>(*Lookup.first);
   2283     ExprResult Callee
   2284       = SemaRef.Owned(new (SemaRef.Context) DeclRefExpr(Builtin, Builtin->getType(),
   2285                                                         VK_LValue, BuiltinLoc));
   2286     Callee = SemaRef.UsualUnaryConversions(Callee.take());
   2287     if (Callee.isInvalid())
   2288       return ExprError();
   2289 
   2290     // Build the CallExpr
   2291     unsigned NumSubExprs = SubExprs.size();
   2292     Expr **Subs = (Expr **)SubExprs.release();
   2293     ExprResult TheCall = SemaRef.Owned(
   2294       new (SemaRef.Context) CallExpr(SemaRef.Context, Callee.take(),
   2295                                                        Subs, NumSubExprs,
   2296                                                    Builtin->getCallResultType(),
   2297                             Expr::getValueKindForType(Builtin->getResultType()),
   2298                                      RParenLoc));
   2299 
   2300     // Type-check the __builtin_shufflevector expression.
   2301     return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.take()));
   2302   }
   2303 
   2304   /// \brief Build a new template argument pack expansion.
   2305   ///
   2306   /// By default, performs semantic analysis to build a new pack expansion
   2307   /// for a template argument. Subclasses may override this routine to provide
   2308   /// different behavior.
   2309   TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
   2310                                            SourceLocation EllipsisLoc,
   2311                                        llvm::Optional<unsigned> NumExpansions) {
   2312     switch (Pattern.getArgument().getKind()) {
   2313     case TemplateArgument::Expression: {
   2314       ExprResult Result
   2315         = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
   2316                                        EllipsisLoc, NumExpansions);
   2317       if (Result.isInvalid())
   2318         return TemplateArgumentLoc();
   2319 
   2320       return TemplateArgumentLoc(Result.get(), Result.get());
   2321     }
   2322 
   2323     case TemplateArgument::Template:
   2324       return TemplateArgumentLoc(TemplateArgument(
   2325                                           Pattern.getArgument().getAsTemplate(),
   2326                                                   NumExpansions),
   2327                                  Pattern.getTemplateQualifierLoc(),
   2328                                  Pattern.getTemplateNameLoc(),
   2329                                  EllipsisLoc);
   2330 
   2331     case TemplateArgument::Null:
   2332     case TemplateArgument::Integral:
   2333     case TemplateArgument::Declaration:
   2334     case TemplateArgument::Pack:
   2335     case TemplateArgument::TemplateExpansion:
   2336       llvm_unreachable("Pack expansion pattern has no parameter packs");
   2337 
   2338     case TemplateArgument::Type:
   2339       if (TypeSourceInfo *Expansion
   2340             = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
   2341                                            EllipsisLoc,
   2342                                            NumExpansions))
   2343         return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
   2344                                    Expansion);
   2345       break;
   2346     }
   2347 
   2348     return TemplateArgumentLoc();
   2349   }
   2350 
   2351   /// \brief Build a new expression pack expansion.
   2352   ///
   2353   /// By default, performs semantic analysis to build a new pack expansion
   2354   /// for an expression. Subclasses may override this routine to provide
   2355   /// different behavior.
   2356   ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
   2357                                   llvm::Optional<unsigned> NumExpansions) {
   2358     return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
   2359   }
   2360 
   2361 private:
   2362   TypeLoc TransformTypeInObjectScope(TypeLoc TL,
   2363                                      QualType ObjectType,
   2364                                      NamedDecl *FirstQualifierInScope,
   2365                                      CXXScopeSpec &SS);
   2366 
   2367   TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
   2368                                              QualType ObjectType,
   2369                                              NamedDecl *FirstQualifierInScope,
   2370                                              CXXScopeSpec &SS);
   2371 };
   2372 
   2373 template<typename Derived>
   2374 StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S) {
   2375   if (!S)
   2376     return SemaRef.Owned(S);
   2377 
   2378   switch (S->getStmtClass()) {
   2379   case Stmt::NoStmtClass: break;
   2380 
   2381   // Transform individual statement nodes
   2382 #define STMT(Node, Parent)                                              \
   2383   case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
   2384 #define ABSTRACT_STMT(Node)
   2385 #define EXPR(Node, Parent)
   2386 #include "clang/AST/StmtNodes.inc"
   2387 
   2388   // Transform expressions by calling TransformExpr.
   2389 #define STMT(Node, Parent)
   2390 #define ABSTRACT_STMT(Stmt)
   2391 #define EXPR(Node, Parent) case Stmt::Node##Class:
   2392 #include "clang/AST/StmtNodes.inc"
   2393     {
   2394       ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
   2395       if (E.isInvalid())
   2396         return StmtError();
   2397 
   2398       return getSema().ActOnExprStmt(getSema().MakeFullExpr(E.take()));
   2399     }
   2400   }
   2401 
   2402   return SemaRef.Owned(S);
   2403 }
   2404 
   2405 
   2406 template<typename Derived>
   2407 ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
   2408   if (!E)
   2409     return SemaRef.Owned(E);
   2410 
   2411   switch (E->getStmtClass()) {
   2412     case Stmt::NoStmtClass: break;
   2413 #define STMT(Node, Parent) case Stmt::Node##Class: break;
   2414 #define ABSTRACT_STMT(Stmt)
   2415 #define EXPR(Node, Parent)                                              \
   2416     case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
   2417 #include "clang/AST/StmtNodes.inc"
   2418   }
   2419 
   2420   return SemaRef.Owned(E);
   2421 }
   2422 
   2423 template<typename Derived>
   2424 bool TreeTransform<Derived>::TransformExprs(Expr **Inputs,
   2425                                             unsigned NumInputs,
   2426                                             bool IsCall,
   2427                                       llvm::SmallVectorImpl<Expr *> &Outputs,
   2428                                             bool *ArgChanged) {
   2429   for (unsigned I = 0; I != NumInputs; ++I) {
   2430     // If requested, drop call arguments that need to be dropped.
   2431     if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
   2432       if (ArgChanged)
   2433         *ArgChanged = true;
   2434 
   2435       break;
   2436     }
   2437 
   2438     if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
   2439       Expr *Pattern = Expansion->getPattern();
   2440 
   2441       llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   2442       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   2443       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   2444 
   2445       // Determine whether the set of unexpanded parameter packs can and should
   2446       // be expanded.
   2447       bool Expand = true;
   2448       bool RetainExpansion = false;
   2449       llvm::Optional<unsigned> OrigNumExpansions
   2450         = Expansion->getNumExpansions();
   2451       llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
   2452       if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
   2453                                                Pattern->getSourceRange(),
   2454                                                Unexpanded.data(),
   2455                                                Unexpanded.size(),
   2456                                                Expand, RetainExpansion,
   2457                                                NumExpansions))
   2458         return true;
   2459 
   2460       if (!Expand) {
   2461         // The transform has determined that we should perform a simple
   2462         // transformation on the pack expansion, producing another pack
   2463         // expansion.
   2464         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   2465         ExprResult OutPattern = getDerived().TransformExpr(Pattern);
   2466         if (OutPattern.isInvalid())
   2467           return true;
   2468 
   2469         ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
   2470                                                 Expansion->getEllipsisLoc(),
   2471                                                            NumExpansions);
   2472         if (Out.isInvalid())
   2473           return true;
   2474 
   2475         if (ArgChanged)
   2476           *ArgChanged = true;
   2477         Outputs.push_back(Out.get());
   2478         continue;
   2479       }
   2480 
   2481       // Record right away that the argument was changed.  This needs
   2482       // to happen even if the array expands to nothing.
   2483       if (ArgChanged) *ArgChanged = true;
   2484 
   2485       // The transform has determined that we should perform an elementwise
   2486       // expansion of the pattern. Do so.
   2487       for (unsigned I = 0; I != *NumExpansions; ++I) {
   2488         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   2489         ExprResult Out = getDerived().TransformExpr(Pattern);
   2490         if (Out.isInvalid())
   2491           return true;
   2492 
   2493         if (Out.get()->containsUnexpandedParameterPack()) {
   2494           Out = RebuildPackExpansion(Out.get(), Expansion->getEllipsisLoc(),
   2495                                      OrigNumExpansions);
   2496           if (Out.isInvalid())
   2497             return true;
   2498         }
   2499 
   2500         Outputs.push_back(Out.get());
   2501       }
   2502 
   2503       continue;
   2504     }
   2505 
   2506     ExprResult Result = getDerived().TransformExpr(Inputs[I]);
   2507     if (Result.isInvalid())
   2508       return true;
   2509 
   2510     if (Result.get() != Inputs[I] && ArgChanged)
   2511       *ArgChanged = true;
   2512 
   2513     Outputs.push_back(Result.get());
   2514   }
   2515 
   2516   return false;
   2517 }
   2518 
   2519 template<typename Derived>
   2520 NestedNameSpecifierLoc
   2521 TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
   2522                                                     NestedNameSpecifierLoc NNS,
   2523                                                      QualType ObjectType,
   2524                                              NamedDecl *FirstQualifierInScope) {
   2525   llvm::SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
   2526   for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
   2527        Qualifier = Qualifier.getPrefix())
   2528     Qualifiers.push_back(Qualifier);
   2529 
   2530   CXXScopeSpec SS;
   2531   while (!Qualifiers.empty()) {
   2532     NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
   2533     NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
   2534 
   2535     switch (QNNS->getKind()) {
   2536     case NestedNameSpecifier::Identifier:
   2537       if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/0,
   2538                                               *QNNS->getAsIdentifier(),
   2539                                               Q.getLocalBeginLoc(),
   2540                                               Q.getLocalEndLoc(),
   2541                                               ObjectType, false, SS,
   2542                                               FirstQualifierInScope, false))
   2543         return NestedNameSpecifierLoc();
   2544 
   2545       break;
   2546 
   2547     case NestedNameSpecifier::Namespace: {
   2548       NamespaceDecl *NS
   2549         = cast_or_null<NamespaceDecl>(
   2550                                     getDerived().TransformDecl(
   2551                                                           Q.getLocalBeginLoc(),
   2552                                                        QNNS->getAsNamespace()));
   2553       SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
   2554       break;
   2555     }
   2556 
   2557     case NestedNameSpecifier::NamespaceAlias: {
   2558       NamespaceAliasDecl *Alias
   2559         = cast_or_null<NamespaceAliasDecl>(
   2560                       getDerived().TransformDecl(Q.getLocalBeginLoc(),
   2561                                                  QNNS->getAsNamespaceAlias()));
   2562       SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
   2563                 Q.getLocalEndLoc());
   2564       break;
   2565     }
   2566 
   2567     case NestedNameSpecifier::Global:
   2568       // There is no meaningful transformation that one could perform on the
   2569       // global scope.
   2570       SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
   2571       break;
   2572 
   2573     case NestedNameSpecifier::TypeSpecWithTemplate:
   2574     case NestedNameSpecifier::TypeSpec: {
   2575       TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
   2576                                               FirstQualifierInScope, SS);
   2577 
   2578       if (!TL)
   2579         return NestedNameSpecifierLoc();
   2580 
   2581       if (TL.getType()->isDependentType() || TL.getType()->isRecordType() ||
   2582           (SemaRef.getLangOptions().CPlusPlus0x &&
   2583            TL.getType()->isEnumeralType())) {
   2584         assert(!TL.getType().hasLocalQualifiers() &&
   2585                "Can't get cv-qualifiers here");
   2586         SS.Extend(SemaRef.Context, /*FIXME:*/SourceLocation(), TL,
   2587                   Q.getLocalEndLoc());
   2588         break;
   2589       }
   2590       // If the nested-name-specifier is an invalid type def, don't emit an
   2591       // error because a previous error should have already been emitted.
   2592       TypedefTypeLoc* TTL = dyn_cast<TypedefTypeLoc>(&TL);
   2593       if (!TTL || !TTL->getTypedefNameDecl()->isInvalidDecl()) {
   2594         SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
   2595           << TL.getType() << SS.getRange();
   2596       }
   2597       return NestedNameSpecifierLoc();
   2598     }
   2599     }
   2600 
   2601     // The qualifier-in-scope and object type only apply to the leftmost entity.
   2602     FirstQualifierInScope = 0;
   2603     ObjectType = QualType();
   2604   }
   2605 
   2606   // Don't rebuild the nested-name-specifier if we don't have to.
   2607   if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
   2608       !getDerived().AlwaysRebuild())
   2609     return NNS;
   2610 
   2611   // If we can re-use the source-location data from the original
   2612   // nested-name-specifier, do so.
   2613   if (SS.location_size() == NNS.getDataLength() &&
   2614       memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
   2615     return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
   2616 
   2617   // Allocate new nested-name-specifier location information.
   2618   return SS.getWithLocInContext(SemaRef.Context);
   2619 }
   2620 
   2621 template<typename Derived>
   2622 DeclarationNameInfo
   2623 TreeTransform<Derived>
   2624 ::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
   2625   DeclarationName Name = NameInfo.getName();
   2626   if (!Name)
   2627     return DeclarationNameInfo();
   2628 
   2629   switch (Name.getNameKind()) {
   2630   case DeclarationName::Identifier:
   2631   case DeclarationName::ObjCZeroArgSelector:
   2632   case DeclarationName::ObjCOneArgSelector:
   2633   case DeclarationName::ObjCMultiArgSelector:
   2634   case DeclarationName::CXXOperatorName:
   2635   case DeclarationName::CXXLiteralOperatorName:
   2636   case DeclarationName::CXXUsingDirective:
   2637     return NameInfo;
   2638 
   2639   case DeclarationName::CXXConstructorName:
   2640   case DeclarationName::CXXDestructorName:
   2641   case DeclarationName::CXXConversionFunctionName: {
   2642     TypeSourceInfo *NewTInfo;
   2643     CanQualType NewCanTy;
   2644     if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
   2645       NewTInfo = getDerived().TransformType(OldTInfo);
   2646       if (!NewTInfo)
   2647         return DeclarationNameInfo();
   2648       NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
   2649     }
   2650     else {
   2651       NewTInfo = 0;
   2652       TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
   2653       QualType NewT = getDerived().TransformType(Name.getCXXNameType());
   2654       if (NewT.isNull())
   2655         return DeclarationNameInfo();
   2656       NewCanTy = SemaRef.Context.getCanonicalType(NewT);
   2657     }
   2658 
   2659     DeclarationName NewName
   2660       = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
   2661                                                            NewCanTy);
   2662     DeclarationNameInfo NewNameInfo(NameInfo);
   2663     NewNameInfo.setName(NewName);
   2664     NewNameInfo.setNamedTypeInfo(NewTInfo);
   2665     return NewNameInfo;
   2666   }
   2667   }
   2668 
   2669   assert(0 && "Unknown name kind.");
   2670   return DeclarationNameInfo();
   2671 }
   2672 
   2673 template<typename Derived>
   2674 TemplateName
   2675 TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
   2676                                               TemplateName Name,
   2677                                               SourceLocation NameLoc,
   2678                                               QualType ObjectType,
   2679                                               NamedDecl *FirstQualifierInScope) {
   2680   if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
   2681     TemplateDecl *Template = QTN->getTemplateDecl();
   2682     assert(Template && "qualified template name must refer to a template");
   2683 
   2684     TemplateDecl *TransTemplate
   2685       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
   2686                                                               Template));
   2687     if (!TransTemplate)
   2688       return TemplateName();
   2689 
   2690     if (!getDerived().AlwaysRebuild() &&
   2691         SS.getScopeRep() == QTN->getQualifier() &&
   2692         TransTemplate == Template)
   2693       return Name;
   2694 
   2695     return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
   2696                                             TransTemplate);
   2697   }
   2698 
   2699   if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
   2700     if (SS.getScopeRep()) {
   2701       // These apply to the scope specifier, not the template.
   2702       ObjectType = QualType();
   2703       FirstQualifierInScope = 0;
   2704     }
   2705 
   2706     if (!getDerived().AlwaysRebuild() &&
   2707         SS.getScopeRep() == DTN->getQualifier() &&
   2708         ObjectType.isNull())
   2709       return Name;
   2710 
   2711     if (DTN->isIdentifier()) {
   2712       return getDerived().RebuildTemplateName(SS,
   2713                                               *DTN->getIdentifier(),
   2714                                               NameLoc,
   2715                                               ObjectType,
   2716                                               FirstQualifierInScope);
   2717     }
   2718 
   2719     return getDerived().RebuildTemplateName(SS, DTN->getOperator(), NameLoc,
   2720                                             ObjectType);
   2721   }
   2722 
   2723   if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
   2724     TemplateDecl *TransTemplate
   2725       = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
   2726                                                               Template));
   2727     if (!TransTemplate)
   2728       return TemplateName();
   2729 
   2730     if (!getDerived().AlwaysRebuild() &&
   2731         TransTemplate == Template)
   2732       return Name;
   2733 
   2734     return TemplateName(TransTemplate);
   2735   }
   2736 
   2737   if (SubstTemplateTemplateParmPackStorage *SubstPack
   2738       = Name.getAsSubstTemplateTemplateParmPack()) {
   2739     TemplateTemplateParmDecl *TransParam
   2740     = cast_or_null<TemplateTemplateParmDecl>(
   2741             getDerived().TransformDecl(NameLoc, SubstPack->getParameterPack()));
   2742     if (!TransParam)
   2743       return TemplateName();
   2744 
   2745     if (!getDerived().AlwaysRebuild() &&
   2746         TransParam == SubstPack->getParameterPack())
   2747       return Name;
   2748 
   2749     return getDerived().RebuildTemplateName(TransParam,
   2750                                             SubstPack->getArgumentPack());
   2751   }
   2752 
   2753   // These should be getting filtered out before they reach the AST.
   2754   llvm_unreachable("overloaded function decl survived to here");
   2755   return TemplateName();
   2756 }
   2757 
   2758 template<typename Derived>
   2759 void TreeTransform<Derived>::InventTemplateArgumentLoc(
   2760                                          const TemplateArgument &Arg,
   2761                                          TemplateArgumentLoc &Output) {
   2762   SourceLocation Loc = getDerived().getBaseLocation();
   2763   switch (Arg.getKind()) {
   2764   case TemplateArgument::Null:
   2765     llvm_unreachable("null template argument in TreeTransform");
   2766     break;
   2767 
   2768   case TemplateArgument::Type:
   2769     Output = TemplateArgumentLoc(Arg,
   2770                SemaRef.Context.getTrivialTypeSourceInfo(Arg.getAsType(), Loc));
   2771 
   2772     break;
   2773 
   2774   case TemplateArgument::Template:
   2775   case TemplateArgument::TemplateExpansion: {
   2776     NestedNameSpecifierLocBuilder Builder;
   2777     TemplateName Template = Arg.getAsTemplate();
   2778     if (DependentTemplateName *DTN = Template.getAsDependentTemplateName())
   2779       Builder.MakeTrivial(SemaRef.Context, DTN->getQualifier(), Loc);
   2780     else if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName())
   2781       Builder.MakeTrivial(SemaRef.Context, QTN->getQualifier(), Loc);
   2782 
   2783     if (Arg.getKind() == TemplateArgument::Template)
   2784       Output = TemplateArgumentLoc(Arg,
   2785                                    Builder.getWithLocInContext(SemaRef.Context),
   2786                                    Loc);
   2787     else
   2788       Output = TemplateArgumentLoc(Arg,
   2789                                    Builder.getWithLocInContext(SemaRef.Context),
   2790                                    Loc, Loc);
   2791 
   2792     break;
   2793   }
   2794 
   2795   case TemplateArgument::Expression:
   2796     Output = TemplateArgumentLoc(Arg, Arg.getAsExpr());
   2797     break;
   2798 
   2799   case TemplateArgument::Declaration:
   2800   case TemplateArgument::Integral:
   2801   case TemplateArgument::Pack:
   2802     Output = TemplateArgumentLoc(Arg, TemplateArgumentLocInfo());
   2803     break;
   2804   }
   2805 }
   2806 
   2807 template<typename Derived>
   2808 bool TreeTransform<Derived>::TransformTemplateArgument(
   2809                                          const TemplateArgumentLoc &Input,
   2810                                          TemplateArgumentLoc &Output) {
   2811   const TemplateArgument &Arg = Input.getArgument();
   2812   switch (Arg.getKind()) {
   2813   case TemplateArgument::Null:
   2814   case TemplateArgument::Integral:
   2815     Output = Input;
   2816     return false;
   2817 
   2818   case TemplateArgument::Type: {
   2819     TypeSourceInfo *DI = Input.getTypeSourceInfo();
   2820     if (DI == NULL)
   2821       DI = InventTypeSourceInfo(Input.getArgument().getAsType());
   2822 
   2823     DI = getDerived().TransformType(DI);
   2824     if (!DI) return true;
   2825 
   2826     Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
   2827     return false;
   2828   }
   2829 
   2830   case TemplateArgument::Declaration: {
   2831     // FIXME: we should never have to transform one of these.
   2832     DeclarationName Name;
   2833     if (NamedDecl *ND = dyn_cast<NamedDecl>(Arg.getAsDecl()))
   2834       Name = ND->getDeclName();
   2835     TemporaryBase Rebase(*this, Input.getLocation(), Name);
   2836     Decl *D = getDerived().TransformDecl(Input.getLocation(), Arg.getAsDecl());
   2837     if (!D) return true;
   2838 
   2839     Expr *SourceExpr = Input.getSourceDeclExpression();
   2840     if (SourceExpr) {
   2841       EnterExpressionEvaluationContext Unevaluated(getSema(),
   2842                                                    Sema::Unevaluated);
   2843       ExprResult E = getDerived().TransformExpr(SourceExpr);
   2844       SourceExpr = (E.isInvalid() ? 0 : E.take());
   2845     }
   2846 
   2847     Output = TemplateArgumentLoc(TemplateArgument(D), SourceExpr);
   2848     return false;
   2849   }
   2850 
   2851   case TemplateArgument::Template: {
   2852     NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
   2853     if (QualifierLoc) {
   2854       QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
   2855       if (!QualifierLoc)
   2856         return true;
   2857     }
   2858 
   2859     CXXScopeSpec SS;
   2860     SS.Adopt(QualifierLoc);
   2861     TemplateName Template
   2862       = getDerived().TransformTemplateName(SS, Arg.getAsTemplate(),
   2863                                            Input.getTemplateNameLoc());
   2864     if (Template.isNull())
   2865       return true;
   2866 
   2867     Output = TemplateArgumentLoc(TemplateArgument(Template), QualifierLoc,
   2868                                  Input.getTemplateNameLoc());
   2869     return false;
   2870   }
   2871 
   2872   case TemplateArgument::TemplateExpansion:
   2873     llvm_unreachable("Caller should expand pack expansions");
   2874 
   2875   case TemplateArgument::Expression: {
   2876     // Template argument expressions are not potentially evaluated.
   2877     EnterExpressionEvaluationContext Unevaluated(getSema(),
   2878                                                  Sema::Unevaluated);
   2879 
   2880     Expr *InputExpr = Input.getSourceExpression();
   2881     if (!InputExpr) InputExpr = Input.getArgument().getAsExpr();
   2882 
   2883     ExprResult E = getDerived().TransformExpr(InputExpr);
   2884     if (E.isInvalid()) return true;
   2885     Output = TemplateArgumentLoc(TemplateArgument(E.take()), E.take());
   2886     return false;
   2887   }
   2888 
   2889   case TemplateArgument::Pack: {
   2890     llvm::SmallVector<TemplateArgument, 4> TransformedArgs;
   2891     TransformedArgs.reserve(Arg.pack_size());
   2892     for (TemplateArgument::pack_iterator A = Arg.pack_begin(),
   2893                                       AEnd = Arg.pack_end();
   2894          A != AEnd; ++A) {
   2895 
   2896       // FIXME: preserve source information here when we start
   2897       // caring about parameter packs.
   2898 
   2899       TemplateArgumentLoc InputArg;
   2900       TemplateArgumentLoc OutputArg;
   2901       getDerived().InventTemplateArgumentLoc(*A, InputArg);
   2902       if (getDerived().TransformTemplateArgument(InputArg, OutputArg))
   2903         return true;
   2904 
   2905       TransformedArgs.push_back(OutputArg.getArgument());
   2906     }
   2907 
   2908     TemplateArgument *TransformedArgsPtr
   2909       = new (getSema().Context) TemplateArgument[TransformedArgs.size()];
   2910     std::copy(TransformedArgs.begin(), TransformedArgs.end(),
   2911               TransformedArgsPtr);
   2912     Output = TemplateArgumentLoc(TemplateArgument(TransformedArgsPtr,
   2913                                                   TransformedArgs.size()),
   2914                                  Input.getLocInfo());
   2915     return false;
   2916   }
   2917   }
   2918 
   2919   // Work around bogus GCC warning
   2920   return true;
   2921 }
   2922 
   2923 /// \brief Iterator adaptor that invents template argument location information
   2924 /// for each of the template arguments in its underlying iterator.
   2925 template<typename Derived, typename InputIterator>
   2926 class TemplateArgumentLocInventIterator {
   2927   TreeTransform<Derived> &Self;
   2928   InputIterator Iter;
   2929 
   2930 public:
   2931   typedef TemplateArgumentLoc value_type;
   2932   typedef TemplateArgumentLoc reference;
   2933   typedef typename std::iterator_traits<InputIterator>::difference_type
   2934     difference_type;
   2935   typedef std::input_iterator_tag iterator_category;
   2936 
   2937   class pointer {
   2938     TemplateArgumentLoc Arg;
   2939 
   2940   public:
   2941     explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
   2942 
   2943     const TemplateArgumentLoc *operator->() const { return &Arg; }
   2944   };
   2945 
   2946   TemplateArgumentLocInventIterator() { }
   2947 
   2948   explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
   2949                                              InputIterator Iter)
   2950     : Self(Self), Iter(Iter) { }
   2951 
   2952   TemplateArgumentLocInventIterator &operator++() {
   2953     ++Iter;
   2954     return *this;
   2955   }
   2956 
   2957   TemplateArgumentLocInventIterator operator++(int) {
   2958     TemplateArgumentLocInventIterator Old(*this);
   2959     ++(*this);
   2960     return Old;
   2961   }
   2962 
   2963   reference operator*() const {
   2964     TemplateArgumentLoc Result;
   2965     Self.InventTemplateArgumentLoc(*Iter, Result);
   2966     return Result;
   2967   }
   2968 
   2969   pointer operator->() const { return pointer(**this); }
   2970 
   2971   friend bool operator==(const TemplateArgumentLocInventIterator &X,
   2972                          const TemplateArgumentLocInventIterator &Y) {
   2973     return X.Iter == Y.Iter;
   2974   }
   2975 
   2976   friend bool operator!=(const TemplateArgumentLocInventIterator &X,
   2977                          const TemplateArgumentLocInventIterator &Y) {
   2978     return X.Iter != Y.Iter;
   2979   }
   2980 };
   2981 
   2982 template<typename Derived>
   2983 template<typename InputIterator>
   2984 bool TreeTransform<Derived>::TransformTemplateArguments(InputIterator First,
   2985                                                         InputIterator Last,
   2986                                             TemplateArgumentListInfo &Outputs) {
   2987   for (; First != Last; ++First) {
   2988     TemplateArgumentLoc Out;
   2989     TemplateArgumentLoc In = *First;
   2990 
   2991     if (In.getArgument().getKind() == TemplateArgument::Pack) {
   2992       // Unpack argument packs, which we translate them into separate
   2993       // arguments.
   2994       // FIXME: We could do much better if we could guarantee that the
   2995       // TemplateArgumentLocInfo for the pack expansion would be usable for
   2996       // all of the template arguments in the argument pack.
   2997       typedef TemplateArgumentLocInventIterator<Derived,
   2998                                                 TemplateArgument::pack_iterator>
   2999         PackLocIterator;
   3000       if (TransformTemplateArguments(PackLocIterator(*this,
   3001                                                  In.getArgument().pack_begin()),
   3002                                      PackLocIterator(*this,
   3003                                                    In.getArgument().pack_end()),
   3004                                      Outputs))
   3005         return true;
   3006 
   3007       continue;
   3008     }
   3009 
   3010     if (In.getArgument().isPackExpansion()) {
   3011       // We have a pack expansion, for which we will be substituting into
   3012       // the pattern.
   3013       SourceLocation Ellipsis;
   3014       llvm::Optional<unsigned> OrigNumExpansions;
   3015       TemplateArgumentLoc Pattern
   3016         = In.getPackExpansionPattern(Ellipsis, OrigNumExpansions,
   3017                                      getSema().Context);
   3018 
   3019       llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   3020       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   3021       assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
   3022 
   3023       // Determine whether the set of unexpanded parameter packs can and should
   3024       // be expanded.
   3025       bool Expand = true;
   3026       bool RetainExpansion = false;
   3027       llvm::Optional<unsigned> NumExpansions = OrigNumExpansions;
   3028       if (getDerived().TryExpandParameterPacks(Ellipsis,
   3029                                                Pattern.getSourceRange(),
   3030                                                Unexpanded.data(),
   3031                                                Unexpanded.size(),
   3032                                                Expand,
   3033                                                RetainExpansion,
   3034                                                NumExpansions))
   3035         return true;
   3036 
   3037       if (!Expand) {
   3038         // The transform has determined that we should perform a simple
   3039         // transformation on the pack expansion, producing another pack
   3040         // expansion.
   3041         TemplateArgumentLoc OutPattern;
   3042         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   3043         if (getDerived().TransformTemplateArgument(Pattern, OutPattern))
   3044           return true;
   3045 
   3046         Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
   3047                                                 NumExpansions);
   3048         if (Out.getArgument().isNull())
   3049           return true;
   3050 
   3051         Outputs.addArgument(Out);
   3052         continue;
   3053       }
   3054 
   3055       // The transform has determined that we should perform an elementwise
   3056       // expansion of the pattern. Do so.
   3057       for (unsigned I = 0; I != *NumExpansions; ++I) {
   3058         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   3059 
   3060         if (getDerived().TransformTemplateArgument(Pattern, Out))
   3061           return true;
   3062 
   3063         if (Out.getArgument().containsUnexpandedParameterPack()) {
   3064           Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
   3065                                                   OrigNumExpansions);
   3066           if (Out.getArgument().isNull())
   3067             return true;
   3068         }
   3069 
   3070         Outputs.addArgument(Out);
   3071       }
   3072 
   3073       // If we're supposed to retain a pack expansion, do so by temporarily
   3074       // forgetting the partially-substituted parameter pack.
   3075       if (RetainExpansion) {
   3076         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   3077 
   3078         if (getDerived().TransformTemplateArgument(Pattern, Out))
   3079           return true;
   3080 
   3081         Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
   3082                                                 OrigNumExpansions);
   3083         if (Out.getArgument().isNull())
   3084           return true;
   3085 
   3086         Outputs.addArgument(Out);
   3087       }
   3088 
   3089       continue;
   3090     }
   3091 
   3092     // The simple case:
   3093     if (getDerived().TransformTemplateArgument(In, Out))
   3094       return true;
   3095 
   3096     Outputs.addArgument(Out);
   3097   }
   3098 
   3099   return false;
   3100 
   3101 }
   3102 
   3103 //===----------------------------------------------------------------------===//
   3104 // Type transformation
   3105 //===----------------------------------------------------------------------===//
   3106 
   3107 template<typename Derived>
   3108 QualType TreeTransform<Derived>::TransformType(QualType T) {
   3109   if (getDerived().AlreadyTransformed(T))
   3110     return T;
   3111 
   3112   // Temporary workaround.  All of these transformations should
   3113   // eventually turn into transformations on TypeLocs.
   3114   TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
   3115                                                 getDerived().getBaseLocation());
   3116 
   3117   TypeSourceInfo *NewDI = getDerived().TransformType(DI);
   3118 
   3119   if (!NewDI)
   3120     return QualType();
   3121 
   3122   return NewDI->getType();
   3123 }
   3124 
   3125 template<typename Derived>
   3126 TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
   3127   if (getDerived().AlreadyTransformed(DI->getType()))
   3128     return DI;
   3129 
   3130   TypeLocBuilder TLB;
   3131 
   3132   TypeLoc TL = DI->getTypeLoc();
   3133   TLB.reserve(TL.getFullDataSize());
   3134 
   3135   QualType Result = getDerived().TransformType(TLB, TL);
   3136   if (Result.isNull())
   3137     return 0;
   3138 
   3139   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
   3140 }
   3141 
   3142 template<typename Derived>
   3143 QualType
   3144 TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
   3145   switch (T.getTypeLocClass()) {
   3146 #define ABSTRACT_TYPELOC(CLASS, PARENT)
   3147 #define TYPELOC(CLASS, PARENT) \
   3148   case TypeLoc::CLASS: \
   3149     return getDerived().Transform##CLASS##Type(TLB, cast<CLASS##TypeLoc>(T));
   3150 #include "clang/AST/TypeLocNodes.def"
   3151   }
   3152 
   3153   llvm_unreachable("unhandled type loc!");
   3154   return QualType();
   3155 }
   3156 
   3157 /// FIXME: By default, this routine adds type qualifiers only to types
   3158 /// that can have qualifiers, and silently suppresses those qualifiers
   3159 /// that are not permitted (e.g., qualifiers on reference or function
   3160 /// types). This is the right thing for template instantiation, but
   3161 /// probably not for other clients.
   3162 template<typename Derived>
   3163 QualType
   3164 TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
   3165                                                QualifiedTypeLoc T) {
   3166   Qualifiers Quals = T.getType().getLocalQualifiers();
   3167 
   3168   QualType Result = getDerived().TransformType(TLB, T.getUnqualifiedLoc());
   3169   if (Result.isNull())
   3170     return QualType();
   3171 
   3172   // Silently suppress qualifiers if the result type can't be qualified.
   3173   // FIXME: this is the right thing for template instantiation, but
   3174   // probably not for other clients.
   3175   if (Result->isFunctionType() || Result->isReferenceType())
   3176     return Result;
   3177 
   3178   // Suppress Objective-C lifetime qualifiers if they don't make sense for the
   3179   // resulting type.
   3180   if (Quals.hasObjCLifetime()) {
   3181     if (!Result->isObjCLifetimeType() && !Result->isDependentType())
   3182       Quals.removeObjCLifetime();
   3183     else if (Result.getObjCLifetime()) {
   3184       // Objective-C ARC:
   3185       //   A lifetime qualifier applied to a substituted template parameter
   3186       //   overrides the lifetime qualifier from the template argument.
   3187       if (const SubstTemplateTypeParmType *SubstTypeParam
   3188                                 = dyn_cast<SubstTemplateTypeParmType>(Result)) {
   3189         QualType Replacement = SubstTypeParam->getReplacementType();
   3190         Qualifiers Qs = Replacement.getQualifiers();
   3191         Qs.removeObjCLifetime();
   3192         Replacement
   3193           = SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(),
   3194                                              Qs);
   3195         Result = SemaRef.Context.getSubstTemplateTypeParmType(
   3196                                         SubstTypeParam->getReplacedParameter(),
   3197                                                               Replacement);
   3198         TLB.TypeWasModifiedSafely(Result);
   3199       } else {
   3200         // Otherwise, complain about the addition of a qualifier to an
   3201         // already-qualified type.
   3202         SourceRange R = TLB.getTemporaryTypeLoc(Result).getSourceRange();
   3203         SemaRef.Diag(R.getBegin(), diag::err_attr_objc_ownership_redundant)
   3204           << Result << R;
   3205 
   3206         Quals.removeObjCLifetime();
   3207       }
   3208     }
   3209   }
   3210   if (!Quals.empty()) {
   3211     Result = SemaRef.BuildQualifiedType(Result, T.getBeginLoc(), Quals);
   3212     TLB.push<QualifiedTypeLoc>(Result);
   3213     // No location information to preserve.
   3214   }
   3215 
   3216   return Result;
   3217 }
   3218 
   3219 template<typename Derived>
   3220 TypeLoc
   3221 TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
   3222                                                    QualType ObjectType,
   3223                                                    NamedDecl *UnqualLookup,
   3224                                                    CXXScopeSpec &SS) {
   3225   QualType T = TL.getType();
   3226   if (getDerived().AlreadyTransformed(T))
   3227     return TL;
   3228 
   3229   TypeLocBuilder TLB;
   3230   QualType Result;
   3231 
   3232   if (isa<TemplateSpecializationType>(T)) {
   3233     TemplateSpecializationTypeLoc SpecTL
   3234       = cast<TemplateSpecializationTypeLoc>(TL);
   3235 
   3236     TemplateName Template =
   3237       getDerived().TransformTemplateName(SS,
   3238                                          SpecTL.getTypePtr()->getTemplateName(),
   3239                                          SpecTL.getTemplateNameLoc(),
   3240                                          ObjectType, UnqualLookup);
   3241     if (Template.isNull())
   3242       return TypeLoc();
   3243 
   3244     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
   3245                                                               Template);
   3246   } else if (isa<DependentTemplateSpecializationType>(T)) {
   3247     DependentTemplateSpecializationTypeLoc SpecTL
   3248       = cast<DependentTemplateSpecializationTypeLoc>(TL);
   3249 
   3250     TemplateName Template
   3251       = getDerived().RebuildTemplateName(SS,
   3252                                          *SpecTL.getTypePtr()->getIdentifier(),
   3253                                          SpecTL.getNameLoc(),
   3254                                          ObjectType, UnqualLookup);
   3255     if (Template.isNull())
   3256       return TypeLoc();
   3257 
   3258     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
   3259                                                                        SpecTL,
   3260                                                                      Template,
   3261                                                                        SS);
   3262   } else {
   3263     // Nothing special needs to be done for these.
   3264     Result = getDerived().TransformType(TLB, TL);
   3265   }
   3266 
   3267   if (Result.isNull())
   3268     return TypeLoc();
   3269 
   3270   return TLB.getTypeSourceInfo(SemaRef.Context, Result)->getTypeLoc();
   3271 }
   3272 
   3273 template<typename Derived>
   3274 TypeSourceInfo *
   3275 TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
   3276                                                    QualType ObjectType,
   3277                                                    NamedDecl *UnqualLookup,
   3278                                                    CXXScopeSpec &SS) {
   3279   // FIXME: Painfully copy-paste from the above!
   3280 
   3281   QualType T = TSInfo->getType();
   3282   if (getDerived().AlreadyTransformed(T))
   3283     return TSInfo;
   3284 
   3285   TypeLocBuilder TLB;
   3286   QualType Result;
   3287 
   3288   TypeLoc TL = TSInfo->getTypeLoc();
   3289   if (isa<TemplateSpecializationType>(T)) {
   3290     TemplateSpecializationTypeLoc SpecTL
   3291       = cast<TemplateSpecializationTypeLoc>(TL);
   3292 
   3293     TemplateName Template
   3294     = getDerived().TransformTemplateName(SS,
   3295                                          SpecTL.getTypePtr()->getTemplateName(),
   3296                                          SpecTL.getTemplateNameLoc(),
   3297                                          ObjectType, UnqualLookup);
   3298     if (Template.isNull())
   3299       return 0;
   3300 
   3301     Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
   3302                                                               Template);
   3303   } else if (isa<DependentTemplateSpecializationType>(T)) {
   3304     DependentTemplateSpecializationTypeLoc SpecTL
   3305       = cast<DependentTemplateSpecializationTypeLoc>(TL);
   3306 
   3307     TemplateName Template
   3308       = getDerived().RebuildTemplateName(SS,
   3309                                          *SpecTL.getTypePtr()->getIdentifier(),
   3310                                          SpecTL.getNameLoc(),
   3311                                          ObjectType, UnqualLookup);
   3312     if (Template.isNull())
   3313       return 0;
   3314 
   3315     Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
   3316                                                                        SpecTL,
   3317                                                                        Template,
   3318                                                                        SS);
   3319   } else {
   3320     // Nothing special needs to be done for these.
   3321     Result = getDerived().TransformType(TLB, TL);
   3322   }
   3323 
   3324   if (Result.isNull())
   3325     return 0;
   3326 
   3327   return TLB.getTypeSourceInfo(SemaRef.Context, Result);
   3328 }
   3329 
   3330 template <class TyLoc> static inline
   3331 QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
   3332   TyLoc NewT = TLB.push<TyLoc>(T.getType());
   3333   NewT.setNameLoc(T.getNameLoc());
   3334   return T.getType();
   3335 }
   3336 
   3337 template<typename Derived>
   3338 QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
   3339                                                       BuiltinTypeLoc T) {
   3340   BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
   3341   NewT.setBuiltinLoc(T.getBuiltinLoc());
   3342   if (T.needsExtraLocalData())
   3343     NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
   3344   return T.getType();
   3345 }
   3346 
   3347 template<typename Derived>
   3348 QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
   3349                                                       ComplexTypeLoc T) {
   3350   // FIXME: recurse?
   3351   return TransformTypeSpecType(TLB, T);
   3352 }
   3353 
   3354 template<typename Derived>
   3355 QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
   3356                                                       PointerTypeLoc TL) {
   3357   QualType PointeeType
   3358     = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3359   if (PointeeType.isNull())
   3360     return QualType();
   3361 
   3362   QualType Result = TL.getType();
   3363   if (PointeeType->getAs<ObjCObjectType>()) {
   3364     // A dependent pointer type 'T *' has is being transformed such
   3365     // that an Objective-C class type is being replaced for 'T'. The
   3366     // resulting pointer type is an ObjCObjectPointerType, not a
   3367     // PointerType.
   3368     Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
   3369 
   3370     ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
   3371     NewT.setStarLoc(TL.getStarLoc());
   3372     return Result;
   3373   }
   3374 
   3375   if (getDerived().AlwaysRebuild() ||
   3376       PointeeType != TL.getPointeeLoc().getType()) {
   3377     Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
   3378     if (Result.isNull())
   3379       return QualType();
   3380   }
   3381 
   3382   // Objective-C ARC can add lifetime qualifiers to the type that we're
   3383   // pointing to.
   3384   TLB.TypeWasModifiedSafely(Result->getPointeeType());
   3385 
   3386   PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
   3387   NewT.setSigilLoc(TL.getSigilLoc());
   3388   return Result;
   3389 }
   3390 
   3391 template<typename Derived>
   3392 QualType
   3393 TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
   3394                                                   BlockPointerTypeLoc TL) {
   3395   QualType PointeeType
   3396     = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3397   if (PointeeType.isNull())
   3398     return QualType();
   3399 
   3400   QualType Result = TL.getType();
   3401   if (getDerived().AlwaysRebuild() ||
   3402       PointeeType != TL.getPointeeLoc().getType()) {
   3403     Result = getDerived().RebuildBlockPointerType(PointeeType,
   3404                                                   TL.getSigilLoc());
   3405     if (Result.isNull())
   3406       return QualType();
   3407   }
   3408 
   3409   BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
   3410   NewT.setSigilLoc(TL.getSigilLoc());
   3411   return Result;
   3412 }
   3413 
   3414 /// Transforms a reference type.  Note that somewhat paradoxically we
   3415 /// don't care whether the type itself is an l-value type or an r-value
   3416 /// type;  we only care if the type was *written* as an l-value type
   3417 /// or an r-value type.
   3418 template<typename Derived>
   3419 QualType
   3420 TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
   3421                                                ReferenceTypeLoc TL) {
   3422   const ReferenceType *T = TL.getTypePtr();
   3423 
   3424   // Note that this works with the pointee-as-written.
   3425   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3426   if (PointeeType.isNull())
   3427     return QualType();
   3428 
   3429   QualType Result = TL.getType();
   3430   if (getDerived().AlwaysRebuild() ||
   3431       PointeeType != T->getPointeeTypeAsWritten()) {
   3432     Result = getDerived().RebuildReferenceType(PointeeType,
   3433                                                T->isSpelledAsLValue(),
   3434                                                TL.getSigilLoc());
   3435     if (Result.isNull())
   3436       return QualType();
   3437   }
   3438 
   3439   // Objective-C ARC can add lifetime qualifiers to the type that we're
   3440   // referring to.
   3441   TLB.TypeWasModifiedSafely(
   3442                      Result->getAs<ReferenceType>()->getPointeeTypeAsWritten());
   3443 
   3444   // r-value references can be rebuilt as l-value references.
   3445   ReferenceTypeLoc NewTL;
   3446   if (isa<LValueReferenceType>(Result))
   3447     NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
   3448   else
   3449     NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
   3450   NewTL.setSigilLoc(TL.getSigilLoc());
   3451 
   3452   return Result;
   3453 }
   3454 
   3455 template<typename Derived>
   3456 QualType
   3457 TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
   3458                                                  LValueReferenceTypeLoc TL) {
   3459   return TransformReferenceType(TLB, TL);
   3460 }
   3461 
   3462 template<typename Derived>
   3463 QualType
   3464 TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
   3465                                                  RValueReferenceTypeLoc TL) {
   3466   return TransformReferenceType(TLB, TL);
   3467 }
   3468 
   3469 template<typename Derived>
   3470 QualType
   3471 TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
   3472                                                    MemberPointerTypeLoc TL) {
   3473   QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
   3474   if (PointeeType.isNull())
   3475     return QualType();
   3476 
   3477   TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
   3478   TypeSourceInfo* NewClsTInfo = 0;
   3479   if (OldClsTInfo) {
   3480     NewClsTInfo = getDerived().TransformType(OldClsTInfo);
   3481     if (!NewClsTInfo)
   3482       return QualType();
   3483   }
   3484 
   3485   const MemberPointerType *T = TL.getTypePtr();
   3486   QualType OldClsType = QualType(T->getClass(), 0);
   3487   QualType NewClsType;
   3488   if (NewClsTInfo)
   3489     NewClsType = NewClsTInfo->getType();
   3490   else {
   3491     NewClsType = getDerived().TransformType(OldClsType);
   3492     if (NewClsType.isNull())
   3493       return QualType();
   3494   }
   3495 
   3496   QualType Result = TL.getType();
   3497   if (getDerived().AlwaysRebuild() ||
   3498       PointeeType != T->getPointeeType() ||
   3499       NewClsType != OldClsType) {
   3500     Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
   3501                                                    TL.getStarLoc());
   3502     if (Result.isNull())
   3503       return QualType();
   3504   }
   3505 
   3506   MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
   3507   NewTL.setSigilLoc(TL.getSigilLoc());
   3508   NewTL.setClassTInfo(NewClsTInfo);
   3509 
   3510   return Result;
   3511 }
   3512 
   3513 template<typename Derived>
   3514 QualType
   3515 TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
   3516                                                    ConstantArrayTypeLoc TL) {
   3517   const ConstantArrayType *T = TL.getTypePtr();
   3518   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3519   if (ElementType.isNull())
   3520     return QualType();
   3521 
   3522   QualType Result = TL.getType();
   3523   if (getDerived().AlwaysRebuild() ||
   3524       ElementType != T->getElementType()) {
   3525     Result = getDerived().RebuildConstantArrayType(ElementType,
   3526                                                    T->getSizeModifier(),
   3527                                                    T->getSize(),
   3528                                              T->getIndexTypeCVRQualifiers(),
   3529                                                    TL.getBracketsRange());
   3530     if (Result.isNull())
   3531       return QualType();
   3532   }
   3533 
   3534   ConstantArrayTypeLoc NewTL = TLB.push<ConstantArrayTypeLoc>(Result);
   3535   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3536   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3537 
   3538   Expr *Size = TL.getSizeExpr();
   3539   if (Size) {
   3540     EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   3541     Size = getDerived().TransformExpr(Size).template takeAs<Expr>();
   3542   }
   3543   NewTL.setSizeExpr(Size);
   3544 
   3545   return Result;
   3546 }
   3547 
   3548 template<typename Derived>
   3549 QualType TreeTransform<Derived>::TransformIncompleteArrayType(
   3550                                               TypeLocBuilder &TLB,
   3551                                               IncompleteArrayTypeLoc TL) {
   3552   const IncompleteArrayType *T = TL.getTypePtr();
   3553   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3554   if (ElementType.isNull())
   3555     return QualType();
   3556 
   3557   QualType Result = TL.getType();
   3558   if (getDerived().AlwaysRebuild() ||
   3559       ElementType != T->getElementType()) {
   3560     Result = getDerived().RebuildIncompleteArrayType(ElementType,
   3561                                                      T->getSizeModifier(),
   3562                                            T->getIndexTypeCVRQualifiers(),
   3563                                                      TL.getBracketsRange());
   3564     if (Result.isNull())
   3565       return QualType();
   3566   }
   3567 
   3568   IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
   3569   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3570   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3571   NewTL.setSizeExpr(0);
   3572 
   3573   return Result;
   3574 }
   3575 
   3576 template<typename Derived>
   3577 QualType
   3578 TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
   3579                                                    VariableArrayTypeLoc TL) {
   3580   const VariableArrayType *T = TL.getTypePtr();
   3581   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3582   if (ElementType.isNull())
   3583     return QualType();
   3584 
   3585   // Array bounds are not potentially evaluated contexts
   3586   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   3587 
   3588   ExprResult SizeResult
   3589     = getDerived().TransformExpr(T->getSizeExpr());
   3590   if (SizeResult.isInvalid())
   3591     return QualType();
   3592 
   3593   Expr *Size = SizeResult.take();
   3594 
   3595   QualType Result = TL.getType();
   3596   if (getDerived().AlwaysRebuild() ||
   3597       ElementType != T->getElementType() ||
   3598       Size != T->getSizeExpr()) {
   3599     Result = getDerived().RebuildVariableArrayType(ElementType,
   3600                                                    T->getSizeModifier(),
   3601                                                    Size,
   3602                                              T->getIndexTypeCVRQualifiers(),
   3603                                                    TL.getBracketsRange());
   3604     if (Result.isNull())
   3605       return QualType();
   3606   }
   3607 
   3608   VariableArrayTypeLoc NewTL = TLB.push<VariableArrayTypeLoc>(Result);
   3609   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3610   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3611   NewTL.setSizeExpr(Size);
   3612 
   3613   return Result;
   3614 }
   3615 
   3616 template<typename Derived>
   3617 QualType
   3618 TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
   3619                                              DependentSizedArrayTypeLoc TL) {
   3620   const DependentSizedArrayType *T = TL.getTypePtr();
   3621   QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
   3622   if (ElementType.isNull())
   3623     return QualType();
   3624 
   3625   // Array bounds are not potentially evaluated contexts
   3626   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   3627 
   3628   // Prefer the expression from the TypeLoc;  the other may have been uniqued.
   3629   Expr *origSize = TL.getSizeExpr();
   3630   if (!origSize) origSize = T->getSizeExpr();
   3631 
   3632   ExprResult sizeResult
   3633     = getDerived().TransformExpr(origSize);
   3634   if (sizeResult.isInvalid())
   3635     return QualType();
   3636 
   3637   Expr *size = sizeResult.get();
   3638 
   3639   QualType Result = TL.getType();
   3640   if (getDerived().AlwaysRebuild() ||
   3641       ElementType != T->getElementType() ||
   3642       size != origSize) {
   3643     Result = getDerived().RebuildDependentSizedArrayType(ElementType,
   3644                                                          T->getSizeModifier(),
   3645                                                          size,
   3646                                                 T->getIndexTypeCVRQualifiers(),
   3647                                                         TL.getBracketsRange());
   3648     if (Result.isNull())
   3649       return QualType();
   3650   }
   3651 
   3652   // We might have any sort of array type now, but fortunately they
   3653   // all have the same location layout.
   3654   ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
   3655   NewTL.setLBracketLoc(TL.getLBracketLoc());
   3656   NewTL.setRBracketLoc(TL.getRBracketLoc());
   3657   NewTL.setSizeExpr(size);
   3658 
   3659   return Result;
   3660 }
   3661 
   3662 template<typename Derived>
   3663 QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
   3664                                       TypeLocBuilder &TLB,
   3665                                       DependentSizedExtVectorTypeLoc TL) {
   3666   const DependentSizedExtVectorType *T = TL.getTypePtr();
   3667 
   3668   // FIXME: ext vector locs should be nested
   3669   QualType ElementType = getDerived().TransformType(T->getElementType());
   3670   if (ElementType.isNull())
   3671     return QualType();
   3672 
   3673   // Vector sizes are not potentially evaluated contexts
   3674   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   3675 
   3676   ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
   3677   if (Size.isInvalid())
   3678     return QualType();
   3679 
   3680   QualType Result = TL.getType();
   3681   if (getDerived().AlwaysRebuild() ||
   3682       ElementType != T->getElementType() ||
   3683       Size.get() != T->getSizeExpr()) {
   3684     Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
   3685                                                              Size.take(),
   3686                                                          T->getAttributeLoc());
   3687     if (Result.isNull())
   3688       return QualType();
   3689   }
   3690 
   3691   // Result might be dependent or not.
   3692   if (isa<DependentSizedExtVectorType>(Result)) {
   3693     DependentSizedExtVectorTypeLoc NewTL
   3694       = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
   3695     NewTL.setNameLoc(TL.getNameLoc());
   3696   } else {
   3697     ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
   3698     NewTL.setNameLoc(TL.getNameLoc());
   3699   }
   3700 
   3701   return Result;
   3702 }
   3703 
   3704 template<typename Derived>
   3705 QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
   3706                                                      VectorTypeLoc TL) {
   3707   const VectorType *T = TL.getTypePtr();
   3708   QualType ElementType = getDerived().TransformType(T->getElementType());
   3709   if (ElementType.isNull())
   3710     return QualType();
   3711 
   3712   QualType Result = TL.getType();
   3713   if (getDerived().AlwaysRebuild() ||
   3714       ElementType != T->getElementType()) {
   3715     Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
   3716                                             T->getVectorKind());
   3717     if (Result.isNull())
   3718       return QualType();
   3719   }
   3720 
   3721   VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
   3722   NewTL.setNameLoc(TL.getNameLoc());
   3723 
   3724   return Result;
   3725 }
   3726 
   3727 template<typename Derived>
   3728 QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
   3729                                                         ExtVectorTypeLoc TL) {
   3730   const VectorType *T = TL.getTypePtr();
   3731   QualType ElementType = getDerived().TransformType(T->getElementType());
   3732   if (ElementType.isNull())
   3733     return QualType();
   3734 
   3735   QualType Result = TL.getType();
   3736   if (getDerived().AlwaysRebuild() ||
   3737       ElementType != T->getElementType()) {
   3738     Result = getDerived().RebuildExtVectorType(ElementType,
   3739                                                T->getNumElements(),
   3740                                                /*FIXME*/ SourceLocation());
   3741     if (Result.isNull())
   3742       return QualType();
   3743   }
   3744 
   3745   ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
   3746   NewTL.setNameLoc(TL.getNameLoc());
   3747 
   3748   return Result;
   3749 }
   3750 
   3751 template<typename Derived>
   3752 ParmVarDecl *
   3753 TreeTransform<Derived>::TransformFunctionTypeParam(ParmVarDecl *OldParm,
   3754                                                    int indexAdjustment,
   3755                                        llvm::Optional<unsigned> NumExpansions) {
   3756   TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
   3757   TypeSourceInfo *NewDI = 0;
   3758 
   3759   if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
   3760     // If we're substituting into a pack expansion type and we know the
   3761     TypeLoc OldTL = OldDI->getTypeLoc();
   3762     PackExpansionTypeLoc OldExpansionTL = cast<PackExpansionTypeLoc>(OldTL);
   3763 
   3764     TypeLocBuilder TLB;
   3765     TypeLoc NewTL = OldDI->getTypeLoc();
   3766     TLB.reserve(NewTL.getFullDataSize());
   3767 
   3768     QualType Result = getDerived().TransformType(TLB,
   3769                                                OldExpansionTL.getPatternLoc());
   3770     if (Result.isNull())
   3771       return 0;
   3772 
   3773     Result = RebuildPackExpansionType(Result,
   3774                                 OldExpansionTL.getPatternLoc().getSourceRange(),
   3775                                       OldExpansionTL.getEllipsisLoc(),
   3776                                       NumExpansions);
   3777     if (Result.isNull())
   3778       return 0;
   3779 
   3780     PackExpansionTypeLoc NewExpansionTL
   3781       = TLB.push<PackExpansionTypeLoc>(Result);
   3782     NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
   3783     NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
   3784   } else
   3785     NewDI = getDerived().TransformType(OldDI);
   3786   if (!NewDI)
   3787     return 0;
   3788 
   3789   if (NewDI == OldDI && indexAdjustment == 0)
   3790     return OldParm;
   3791 
   3792   ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
   3793                                              OldParm->getDeclContext(),
   3794                                              OldParm->getInnerLocStart(),
   3795                                              OldParm->getLocation(),
   3796                                              OldParm->getIdentifier(),
   3797                                              NewDI->getType(),
   3798                                              NewDI,
   3799                                              OldParm->getStorageClass(),
   3800                                              OldParm->getStorageClassAsWritten(),
   3801                                              /* DefArg */ NULL);
   3802   newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
   3803                         OldParm->getFunctionScopeIndex() + indexAdjustment);
   3804   return newParm;
   3805 }
   3806 
   3807 template<typename Derived>
   3808 bool TreeTransform<Derived>::
   3809   TransformFunctionTypeParams(SourceLocation Loc,
   3810                               ParmVarDecl **Params, unsigned NumParams,
   3811                               const QualType *ParamTypes,
   3812                               llvm::SmallVectorImpl<QualType> &OutParamTypes,
   3813                               llvm::SmallVectorImpl<ParmVarDecl*> *PVars) {
   3814   int indexAdjustment = 0;
   3815 
   3816   for (unsigned i = 0; i != NumParams; ++i) {
   3817     if (ParmVarDecl *OldParm = Params[i]) {
   3818       assert(OldParm->getFunctionScopeIndex() == i);
   3819 
   3820       llvm::Optional<unsigned> NumExpansions;
   3821       ParmVarDecl *NewParm = 0;
   3822       if (OldParm->isParameterPack()) {
   3823         // We have a function parameter pack that may need to be expanded.
   3824         llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   3825 
   3826         // Find the parameter packs that could be expanded.
   3827         TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
   3828         PackExpansionTypeLoc ExpansionTL = cast<PackExpansionTypeLoc>(TL);
   3829         TypeLoc Pattern = ExpansionTL.getPatternLoc();
   3830         SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
   3831         assert(Unexpanded.size() > 0 && "Could not find parameter packs!");
   3832 
   3833         // Determine whether we should expand the parameter packs.
   3834         bool ShouldExpand = false;
   3835         bool RetainExpansion = false;
   3836         llvm::Optional<unsigned> OrigNumExpansions
   3837           = ExpansionTL.getTypePtr()->getNumExpansions();
   3838         NumExpansions = OrigNumExpansions;
   3839         if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
   3840                                                  Pattern.getSourceRange(),
   3841                                                  Unexpanded.data(),
   3842                                                  Unexpanded.size(),
   3843                                                  ShouldExpand,
   3844                                                  RetainExpansion,
   3845                                                  NumExpansions)) {
   3846           return true;
   3847         }
   3848 
   3849         if (ShouldExpand) {
   3850           // Expand the function parameter pack into multiple, separate
   3851           // parameters.
   3852           getDerived().ExpandingFunctionParameterPack(OldParm);
   3853           for (unsigned I = 0; I != *NumExpansions; ++I) {
   3854             Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   3855             ParmVarDecl *NewParm
   3856               = getDerived().TransformFunctionTypeParam(OldParm,
   3857                                                         indexAdjustment++,
   3858                                                         OrigNumExpansions);
   3859             if (!NewParm)
   3860               return true;
   3861 
   3862             OutParamTypes.push_back(NewParm->getType());
   3863             if (PVars)
   3864               PVars->push_back(NewParm);
   3865           }
   3866 
   3867           // If we're supposed to retain a pack expansion, do so by temporarily
   3868           // forgetting the partially-substituted parameter pack.
   3869           if (RetainExpansion) {
   3870             ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   3871             ParmVarDecl *NewParm
   3872               = getDerived().TransformFunctionTypeParam(OldParm,
   3873                                                         indexAdjustment++,
   3874                                                         OrigNumExpansions);
   3875             if (!NewParm)
   3876               return true;
   3877 
   3878             OutParamTypes.push_back(NewParm->getType());
   3879             if (PVars)
   3880               PVars->push_back(NewParm);
   3881           }
   3882 
   3883           // The next parameter should have the same adjustment as the
   3884           // last thing we pushed, but we post-incremented indexAdjustment
   3885           // on every push.  Also, if we push nothing, the adjustment should
   3886           // go down by one.
   3887           indexAdjustment--;
   3888 
   3889           // We're done with the pack expansion.
   3890           continue;
   3891         }
   3892 
   3893         // We'll substitute the parameter now without expanding the pack
   3894         // expansion.
   3895         Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   3896         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
   3897                                                           indexAdjustment,
   3898                                                           NumExpansions);
   3899       } else {
   3900         NewParm = getDerived().TransformFunctionTypeParam(OldParm,
   3901                                                           indexAdjustment,
   3902                                                   llvm::Optional<unsigned>());
   3903       }
   3904 
   3905       if (!NewParm)
   3906         return true;
   3907 
   3908       OutParamTypes.push_back(NewParm->getType());
   3909       if (PVars)
   3910         PVars->push_back(NewParm);
   3911       continue;
   3912     }
   3913 
   3914     // Deal with the possibility that we don't have a parameter
   3915     // declaration for this parameter.
   3916     QualType OldType = ParamTypes[i];
   3917     bool IsPackExpansion = false;
   3918     llvm::Optional<unsigned> NumExpansions;
   3919     QualType NewType;
   3920     if (const PackExpansionType *Expansion
   3921                                        = dyn_cast<PackExpansionType>(OldType)) {
   3922       // We have a function parameter pack that may need to be expanded.
   3923       QualType Pattern = Expansion->getPattern();
   3924       llvm::SmallVector<UnexpandedParameterPack, 2> Unexpanded;
   3925       getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
   3926 
   3927       // Determine whether we should expand the parameter packs.
   3928       bool ShouldExpand = false;
   3929       bool RetainExpansion = false;
   3930       if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
   3931                                                Unexpanded.data(),
   3932                                                Unexpanded.size(),
   3933                                                ShouldExpand,
   3934                                                RetainExpansion,
   3935                                                NumExpansions)) {
   3936         return true;
   3937       }
   3938 
   3939       if (ShouldExpand) {
   3940         // Expand the function parameter pack into multiple, separate
   3941         // parameters.
   3942         for (unsigned I = 0; I != *NumExpansions; ++I) {
   3943           Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
   3944           QualType NewType = getDerived().TransformType(Pattern);
   3945           if (NewType.isNull())
   3946             return true;
   3947 
   3948           OutParamTypes.push_back(NewType);
   3949           if (PVars)
   3950             PVars->push_back(0);
   3951         }
   3952 
   3953         // We're done with the pack expansion.
   3954         continue;
   3955       }
   3956 
   3957       // If we're supposed to retain a pack expansion, do so by temporarily
   3958       // forgetting the partially-substituted parameter pack.
   3959       if (RetainExpansion) {
   3960         ForgetPartiallySubstitutedPackRAII Forget(getDerived());
   3961         QualType NewType = getDerived().TransformType(Pattern);
   3962         if (NewType.isNull())
   3963           return true;
   3964 
   3965         OutParamTypes.push_back(NewType);
   3966         if (PVars)
   3967           PVars->push_back(0);
   3968       }
   3969 
   3970       // We'll substitute the parameter now without expanding the pack
   3971       // expansion.
   3972       OldType = Expansion->getPattern();
   3973       IsPackExpansion = true;
   3974       Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
   3975       NewType = getDerived().TransformType(OldType);
   3976     } else {
   3977       NewType = getDerived().TransformType(OldType);
   3978     }
   3979 
   3980     if (NewType.isNull())
   3981       return true;
   3982 
   3983     if (IsPackExpansion)
   3984       NewType = getSema().Context.getPackExpansionType(NewType,
   3985                                                        NumExpansions);
   3986 
   3987     OutParamTypes.push_back(NewType);
   3988     if (PVars)
   3989       PVars->push_back(0);
   3990   }
   3991 
   3992 #ifndef NDEBUG
   3993   if (PVars) {
   3994     for (unsigned i = 0, e = PVars->size(); i != e; ++i)
   3995       if (ParmVarDecl *parm = (*PVars)[i])
   3996         assert(parm->getFunctionScopeIndex() == i);
   3997   }
   3998 #endif
   3999 
   4000   return false;
   4001 }
   4002 
   4003 template<typename Derived>
   4004 QualType
   4005 TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
   4006                                                    FunctionProtoTypeLoc TL) {
   4007   // Transform the parameters and return type.
   4008   //
   4009   // We instantiate in source order, with the return type first followed by
   4010   // the parameters, because users tend to expect this (even if they shouldn't
   4011   // rely on it!).
   4012   //
   4013   // When the function has a trailing return type, we instantiate the
   4014   // parameters before the return type,  since the return type can then refer
   4015   // to the parameters themselves (via decltype, sizeof, etc.).
   4016   //
   4017   llvm::SmallVector<QualType, 4> ParamTypes;
   4018   llvm::SmallVector<ParmVarDecl*, 4> ParamDecls;
   4019   const FunctionProtoType *T = TL.getTypePtr();
   4020 
   4021   QualType ResultType;
   4022 
   4023   if (TL.getTrailingReturn()) {
   4024     if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
   4025                                                  TL.getParmArray(),
   4026                                                  TL.getNumArgs(),
   4027                                              TL.getTypePtr()->arg_type_begin(),
   4028                                                  ParamTypes, &ParamDecls))
   4029       return QualType();
   4030 
   4031     ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
   4032     if (ResultType.isNull())
   4033       return QualType();
   4034   }
   4035   else {
   4036     ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
   4037     if (ResultType.isNull())
   4038       return QualType();
   4039 
   4040     if (getDerived().TransformFunctionTypeParams(TL.getBeginLoc(),
   4041                                                  TL.getParmArray(),
   4042                                                  TL.getNumArgs(),
   4043                                              TL.getTypePtr()->arg_type_begin(),
   4044                                                  ParamTypes, &ParamDecls))
   4045       return QualType();
   4046   }
   4047 
   4048   QualType Result = TL.getType();
   4049   if (getDerived().AlwaysRebuild() ||
   4050       ResultType != T->getResultType() ||
   4051       T->getNumArgs() != ParamTypes.size() ||
   4052       !std::equal(T->arg_type_begin(), T->arg_type_end(), ParamTypes.begin())) {
   4053     Result = getDerived().RebuildFunctionProtoType(ResultType,
   4054                                                    ParamTypes.data(),
   4055                                                    ParamTypes.size(),
   4056                                                    T->isVariadic(),
   4057                                                    T->getTypeQuals(),
   4058                                                    T->getRefQualifier(),
   4059                                                    T->getExtInfo());
   4060     if (Result.isNull())
   4061       return QualType();
   4062   }
   4063 
   4064   FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
   4065   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
   4066   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
   4067   NewTL.setTrailingReturn(TL.getTrailingReturn());
   4068   for (unsigned i = 0, e = NewTL.getNumArgs(); i != e; ++i)
   4069     NewTL.setArg(i, ParamDecls[i]);
   4070 
   4071   return Result;
   4072 }
   4073 
   4074 template<typename Derived>
   4075 QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
   4076                                                  TypeLocBuilder &TLB,
   4077                                                  FunctionNoProtoTypeLoc TL) {
   4078   const FunctionNoProtoType *T = TL.getTypePtr();
   4079   QualType ResultType = getDerived().TransformType(TLB, TL.getResultLoc());
   4080   if (ResultType.isNull())
   4081     return QualType();
   4082 
   4083   QualType Result = TL.getType();
   4084   if (getDerived().AlwaysRebuild() ||
   4085       ResultType != T->getResultType())
   4086     Result = getDerived().RebuildFunctionNoProtoType(ResultType);
   4087 
   4088   FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
   4089   NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
   4090   NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
   4091   NewTL.setTrailingReturn(false);
   4092 
   4093   return Result;
   4094 }
   4095 
   4096 template<typename Derived> QualType
   4097 TreeTransform<Derived>::TransformUnresolvedUsingType(TypeLocBuilder &TLB,
   4098                                                  UnresolvedUsingTypeLoc TL) {
   4099   const UnresolvedUsingType *T = TL.getTypePtr();
   4100   Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
   4101   if (!D)
   4102     return QualType();
   4103 
   4104   QualType Result = TL.getType();
   4105   if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
   4106     Result = getDerived().RebuildUnresolvedUsingType(D);
   4107     if (Result.isNull())
   4108       return QualType();
   4109   }
   4110 
   4111   // We might get an arbitrary type spec type back.  We should at
   4112   // least always get a type spec type, though.
   4113   TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
   4114   NewTL.setNameLoc(TL.getNameLoc());
   4115 
   4116   return Result;
   4117 }
   4118 
   4119 template<typename Derived>
   4120 QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
   4121                                                       TypedefTypeLoc TL) {
   4122   const TypedefType *T = TL.getTypePtr();
   4123   TypedefNameDecl *Typedef
   4124     = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   4125                                                                T->getDecl()));
   4126   if (!Typedef)
   4127     return QualType();
   4128 
   4129   QualType Result = TL.getType();
   4130   if (getDerived().AlwaysRebuild() ||
   4131       Typedef != T->getDecl()) {
   4132     Result = getDerived().RebuildTypedefType(Typedef);
   4133     if (Result.isNull())
   4134       return QualType();
   4135   }
   4136 
   4137   TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
   4138   NewTL.setNameLoc(TL.getNameLoc());
   4139 
   4140   return Result;
   4141 }
   4142 
   4143 template<typename Derived>
   4144 QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
   4145                                                       TypeOfExprTypeLoc TL) {
   4146   // typeof expressions are not potentially evaluated contexts
   4147   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   4148 
   4149   ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
   4150   if (E.isInvalid())
   4151     return QualType();
   4152 
   4153   QualType Result = TL.getType();
   4154   if (getDerived().AlwaysRebuild() ||
   4155       E.get() != TL.getUnderlyingExpr()) {
   4156     Result = getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc());
   4157     if (Result.isNull())
   4158       return QualType();
   4159   }
   4160   else E.take();
   4161 
   4162   TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
   4163   NewTL.setTypeofLoc(TL.getTypeofLoc());
   4164   NewTL.setLParenLoc(TL.getLParenLoc());
   4165   NewTL.setRParenLoc(TL.getRParenLoc());
   4166 
   4167   return Result;
   4168 }
   4169 
   4170 template<typename Derived>
   4171 QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
   4172                                                      TypeOfTypeLoc TL) {
   4173   TypeSourceInfo* Old_Under_TI = TL.getUnderlyingTInfo();
   4174   TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
   4175   if (!New_Under_TI)
   4176     return QualType();
   4177 
   4178   QualType Result = TL.getType();
   4179   if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
   4180     Result = getDerived().RebuildTypeOfType(New_Under_TI->getType());
   4181     if (Result.isNull())
   4182       return QualType();
   4183   }
   4184 
   4185   TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
   4186   NewTL.setTypeofLoc(TL.getTypeofLoc());
   4187   NewTL.setLParenLoc(TL.getLParenLoc());
   4188   NewTL.setRParenLoc(TL.getRParenLoc());
   4189   NewTL.setUnderlyingTInfo(New_Under_TI);
   4190 
   4191   return Result;
   4192 }
   4193 
   4194 template<typename Derived>
   4195 QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
   4196                                                        DecltypeTypeLoc TL) {
   4197   const DecltypeType *T = TL.getTypePtr();
   4198 
   4199   // decltype expressions are not potentially evaluated contexts
   4200   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   4201 
   4202   ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
   4203   if (E.isInvalid())
   4204     return QualType();
   4205 
   4206   QualType Result = TL.getType();
   4207   if (getDerived().AlwaysRebuild() ||
   4208       E.get() != T->getUnderlyingExpr()) {
   4209     Result = getDerived().RebuildDecltypeType(E.get(), TL.getNameLoc());
   4210     if (Result.isNull())
   4211       return QualType();
   4212   }
   4213   else E.take();
   4214 
   4215   DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
   4216   NewTL.setNameLoc(TL.getNameLoc());
   4217 
   4218   return Result;
   4219 }
   4220 
   4221 template<typename Derived>
   4222 QualType TreeTransform<Derived>::TransformUnaryTransformType(
   4223                                                             TypeLocBuilder &TLB,
   4224                                                      UnaryTransformTypeLoc TL) {
   4225   QualType Result = TL.getType();
   4226   if (Result->isDependentType()) {
   4227     const UnaryTransformType *T = TL.getTypePtr();
   4228     QualType NewBase =
   4229       getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
   4230     Result = getDerived().RebuildUnaryTransformType(NewBase,
   4231                                                     T->getUTTKind(),
   4232                                                     TL.getKWLoc());
   4233     if (Result.isNull())
   4234       return QualType();
   4235   }
   4236 
   4237   UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
   4238   NewTL.setKWLoc(TL.getKWLoc());
   4239   NewTL.setParensRange(TL.getParensRange());
   4240   NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
   4241   return Result;
   4242 }
   4243 
   4244 template<typename Derived>
   4245 QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
   4246                                                    AutoTypeLoc TL) {
   4247   const AutoType *T = TL.getTypePtr();
   4248   QualType OldDeduced = T->getDeducedType();
   4249   QualType NewDeduced;
   4250   if (!OldDeduced.isNull()) {
   4251     NewDeduced = getDerived().TransformType(OldDeduced);
   4252     if (NewDeduced.isNull())
   4253       return QualType();
   4254   }
   4255 
   4256   QualType Result = TL.getType();
   4257   if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced) {
   4258     Result = getDerived().RebuildAutoType(NewDeduced);
   4259     if (Result.isNull())
   4260       return QualType();
   4261   }
   4262 
   4263   AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
   4264   NewTL.setNameLoc(TL.getNameLoc());
   4265 
   4266   return Result;
   4267 }
   4268 
   4269 template<typename Derived>
   4270 QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
   4271                                                      RecordTypeLoc TL) {
   4272   const RecordType *T = TL.getTypePtr();
   4273   RecordDecl *Record
   4274     = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   4275                                                           T->getDecl()));
   4276   if (!Record)
   4277     return QualType();
   4278 
   4279   QualType Result = TL.getType();
   4280   if (getDerived().AlwaysRebuild() ||
   4281       Record != T->getDecl()) {
   4282     Result = getDerived().RebuildRecordType(Record);
   4283     if (Result.isNull())
   4284       return QualType();
   4285   }
   4286 
   4287   RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
   4288   NewTL.setNameLoc(TL.getNameLoc());
   4289 
   4290   return Result;
   4291 }
   4292 
   4293 template<typename Derived>
   4294 QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
   4295                                                    EnumTypeLoc TL) {
   4296   const EnumType *T = TL.getTypePtr();
   4297   EnumDecl *Enum
   4298     = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
   4299                                                         T->getDecl()));
   4300   if (!Enum)
   4301     return QualType();
   4302 
   4303   QualType Result = TL.getType();
   4304   if (getDerived().AlwaysRebuild() ||
   4305       Enum != T->getDecl()) {
   4306     Result = getDerived().RebuildEnumType(Enum);
   4307     if (Result.isNull())
   4308       return QualType();
   4309   }
   4310 
   4311   EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
   4312   NewTL.setNameLoc(TL.getNameLoc());
   4313 
   4314   return Result;
   4315 }
   4316 
   4317 template<typename Derived>
   4318 QualType TreeTransform<Derived>::TransformInjectedClassNameType(
   4319                                          TypeLocBuilder &TLB,
   4320                                          InjectedClassNameTypeLoc TL) {
   4321   Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
   4322                                        TL.getTypePtr()->getDecl());
   4323   if (!D) return QualType();
   4324 
   4325   QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
   4326   TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
   4327   return T;
   4328 }
   4329 
   4330 template<typename Derived>
   4331 QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
   4332                                                 TypeLocBuilder &TLB,
   4333                                                 TemplateTypeParmTypeLoc TL) {
   4334   return TransformTypeSpecType(TLB, TL);
   4335 }
   4336 
   4337 template<typename Derived>
   4338 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
   4339                                          TypeLocBuilder &TLB,
   4340                                          SubstTemplateTypeParmTypeLoc TL) {
   4341   const SubstTemplateTypeParmType *T = TL.getTypePtr();
   4342 
   4343   // Substitute into the replacement type, which itself might involve something
   4344   // that needs to be transformed. This only tends to occur with default
   4345   // template arguments of template template parameters.
   4346   TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
   4347   QualType Replacement = getDerived().TransformType(T->getReplacementType());
   4348   if (Replacement.isNull())
   4349     return QualType();
   4350 
   4351   // Always canonicalize the replacement type.
   4352   Replacement = SemaRef.Context.getCanonicalType(Replacement);
   4353   QualType Result
   4354     = SemaRef.Context.getSubstTemplateTypeParmType(T->getReplacedParameter(),
   4355                                                    Replacement);
   4356 
   4357   // Propagate type-source information.
   4358   SubstTemplateTypeParmTypeLoc NewTL
   4359     = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
   4360   NewTL.setNameLoc(TL.getNameLoc());
   4361   return Result;
   4362 
   4363 }
   4364 
   4365 template<typename Derived>
   4366 QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
   4367                                           TypeLocBuilder &TLB,
   4368                                           SubstTemplateTypeParmPackTypeLoc TL) {
   4369   return TransformTypeSpecType(TLB, TL);
   4370 }
   4371 
   4372 template<typename Derived>
   4373 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
   4374                                                         TypeLocBuilder &TLB,
   4375                                            TemplateSpecializationTypeLoc TL) {
   4376   const TemplateSpecializationType *T = TL.getTypePtr();
   4377 
   4378   // The nested-name-specifier never matters in a TemplateSpecializationType,
   4379   // because we can't have a dependent nested-name-specifier anyway.
   4380   CXXScopeSpec SS;
   4381   TemplateName Template
   4382     = getDerived().TransformTemplateName(SS, T->getTemplateName(),
   4383                                          TL.getTemplateNameLoc());
   4384   if (Template.isNull())
   4385     return QualType();
   4386 
   4387   return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
   4388 }
   4389 
   4390 namespace {
   4391   /// \brief Simple iterator that traverses the template arguments in a
   4392   /// container that provides a \c getArgLoc() member function.
   4393   ///
   4394   /// This iterator is intended to be used with the iterator form of
   4395   /// \c TreeTransform<Derived>::TransformTemplateArguments().
   4396   template<typename ArgLocContainer>
   4397   class TemplateArgumentLocContainerIterator {
   4398     ArgLocContainer *Container;
   4399     unsigned Index;
   4400 
   4401   public:
   4402     typedef TemplateArgumentLoc value_type;
   4403     typedef TemplateArgumentLoc reference;
   4404     typedef int difference_type;
   4405     typedef std::input_iterator_tag iterator_category;
   4406 
   4407     class pointer {
   4408       TemplateArgumentLoc Arg;
   4409 
   4410     public:
   4411       explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
   4412 
   4413       const TemplateArgumentLoc *operator->() const {
   4414         return &Arg;
   4415       }
   4416     };
   4417 
   4418 
   4419     TemplateArgumentLocContainerIterator() {}
   4420 
   4421     TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
   4422                                  unsigned Index)
   4423       : Container(&Container), Index(Index) { }
   4424 
   4425     TemplateArgumentLocContainerIterator &operator++() {
   4426       ++Index;
   4427       return *this;
   4428     }
   4429 
   4430     TemplateArgumentLocContainerIterator operator++(int) {
   4431       TemplateArgumentLocContainerIterator Old(*this);
   4432       ++(*this);
   4433       return Old;
   4434     }
   4435 
   4436     TemplateArgumentLoc operator*() const {
   4437       return Container->getArgLoc(Index);
   4438     }
   4439 
   4440     pointer operator->() const {
   4441       return pointer(Container->getArgLoc(Index));
   4442     }
   4443 
   4444     friend bool operator==(const TemplateArgumentLocContainerIterator &X,
   4445                            const TemplateArgumentLocContainerIterator &Y) {
   4446       return X.Container == Y.Container && X.Index == Y.Index;
   4447     }
   4448 
   4449     friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
   4450                            const TemplateArgumentLocContainerIterator &Y) {
   4451       return !(X == Y);
   4452     }
   4453   };
   4454 }
   4455 
   4456 
   4457 template <typename Derived>
   4458 QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
   4459                                                         TypeLocBuilder &TLB,
   4460                                            TemplateSpecializationTypeLoc TL,
   4461                                                       TemplateName Template) {
   4462   TemplateArgumentListInfo NewTemplateArgs;
   4463   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   4464   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   4465   typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
   4466     ArgIterator;
   4467   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   4468                                               ArgIterator(TL, TL.getNumArgs()),
   4469                                               NewTemplateArgs))
   4470     return QualType();
   4471 
   4472   // FIXME: maybe don't rebuild if all the template arguments are the same.
   4473 
   4474   QualType Result =
   4475     getDerived().RebuildTemplateSpecializationType(Template,
   4476                                                    TL.getTemplateNameLoc(),
   4477                                                    NewTemplateArgs);
   4478 
   4479   if (!Result.isNull()) {
   4480     // Specializations of template template parameters are represented as
   4481     // TemplateSpecializationTypes, and substitution of type alias templates
   4482     // within a dependent context can transform them into
   4483     // DependentTemplateSpecializationTypes.
   4484     if (isa<DependentTemplateSpecializationType>(Result)) {
   4485       DependentTemplateSpecializationTypeLoc NewTL
   4486         = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   4487       NewTL.setKeywordLoc(TL.getTemplateNameLoc());
   4488       NewTL.setQualifierLoc(NestedNameSpecifierLoc());
   4489       NewTL.setNameLoc(TL.getTemplateNameLoc());
   4490       NewTL.setLAngleLoc(TL.getLAngleLoc());
   4491       NewTL.setRAngleLoc(TL.getRAngleLoc());
   4492       for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4493         NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4494       return Result;
   4495     }
   4496 
   4497     TemplateSpecializationTypeLoc NewTL
   4498       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   4499     NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
   4500     NewTL.setLAngleLoc(TL.getLAngleLoc());
   4501     NewTL.setRAngleLoc(TL.getRAngleLoc());
   4502     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4503       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4504   }
   4505 
   4506   return Result;
   4507 }
   4508 
   4509 template <typename Derived>
   4510 QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
   4511                                      TypeLocBuilder &TLB,
   4512                                      DependentTemplateSpecializationTypeLoc TL,
   4513                                      TemplateName Template,
   4514                                      CXXScopeSpec &SS) {
   4515   TemplateArgumentListInfo NewTemplateArgs;
   4516   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   4517   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   4518   typedef TemplateArgumentLocContainerIterator<
   4519             DependentTemplateSpecializationTypeLoc> ArgIterator;
   4520   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   4521                                               ArgIterator(TL, TL.getNumArgs()),
   4522                                               NewTemplateArgs))
   4523     return QualType();
   4524 
   4525   // FIXME: maybe don't rebuild if all the template arguments are the same.
   4526 
   4527   if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
   4528     QualType Result
   4529       = getSema().Context.getDependentTemplateSpecializationType(
   4530                                                 TL.getTypePtr()->getKeyword(),
   4531                                                          DTN->getQualifier(),
   4532                                                          DTN->getIdentifier(),
   4533                                                                NewTemplateArgs);
   4534 
   4535     DependentTemplateSpecializationTypeLoc NewTL
   4536       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   4537     NewTL.setKeywordLoc(TL.getKeywordLoc());
   4538 
   4539     NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
   4540     NewTL.setNameLoc(TL.getNameLoc());
   4541     NewTL.setLAngleLoc(TL.getLAngleLoc());
   4542     NewTL.setRAngleLoc(TL.getRAngleLoc());
   4543     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4544       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4545     return Result;
   4546   }
   4547 
   4548   QualType Result
   4549     = getDerived().RebuildTemplateSpecializationType(Template,
   4550                                                      TL.getNameLoc(),
   4551                                                      NewTemplateArgs);
   4552 
   4553   if (!Result.isNull()) {
   4554     /// FIXME: Wrap this in an elaborated-type-specifier?
   4555     TemplateSpecializationTypeLoc NewTL
   4556       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   4557     NewTL.setTemplateNameLoc(TL.getNameLoc());
   4558     NewTL.setLAngleLoc(TL.getLAngleLoc());
   4559     NewTL.setRAngleLoc(TL.getRAngleLoc());
   4560     for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
   4561       NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
   4562   }
   4563 
   4564   return Result;
   4565 }
   4566 
   4567 template<typename Derived>
   4568 QualType
   4569 TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
   4570                                                 ElaboratedTypeLoc TL) {
   4571   const ElaboratedType *T = TL.getTypePtr();
   4572 
   4573   NestedNameSpecifierLoc QualifierLoc;
   4574   // NOTE: the qualifier in an ElaboratedType is optional.
   4575   if (TL.getQualifierLoc()) {
   4576     QualifierLoc
   4577       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   4578     if (!QualifierLoc)
   4579       return QualType();
   4580   }
   4581 
   4582   QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
   4583   if (NamedT.isNull())
   4584     return QualType();
   4585 
   4586   // C++0x [dcl.type.elab]p2:
   4587   //   If the identifier resolves to a typedef-name or the simple-template-id
   4588   //   resolves to an alias template specialization, the
   4589   //   elaborated-type-specifier is ill-formed.
   4590   if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
   4591     if (const TemplateSpecializationType *TST =
   4592           NamedT->getAs<TemplateSpecializationType>()) {
   4593       TemplateName Template = TST->getTemplateName();
   4594       if (TypeAliasTemplateDecl *TAT =
   4595           dyn_cast_or_null<TypeAliasTemplateDecl>(Template.getAsTemplateDecl())) {
   4596         SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
   4597                      diag::err_tag_reference_non_tag) << 4;
   4598         SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
   4599       }
   4600     }
   4601   }
   4602 
   4603   QualType Result = TL.getType();
   4604   if (getDerived().AlwaysRebuild() ||
   4605       QualifierLoc != TL.getQualifierLoc() ||
   4606       NamedT != T->getNamedType()) {
   4607     Result = getDerived().RebuildElaboratedType(TL.getKeywordLoc(),
   4608                                                 T->getKeyword(),
   4609                                                 QualifierLoc, NamedT);
   4610     if (Result.isNull())
   4611       return QualType();
   4612   }
   4613 
   4614   ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   4615   NewTL.setKeywordLoc(TL.getKeywordLoc());
   4616   NewTL.setQualifierLoc(QualifierLoc);
   4617   return Result;
   4618 }
   4619 
   4620 template<typename Derived>
   4621 QualType TreeTransform<Derived>::TransformAttributedType(
   4622                                                 TypeLocBuilder &TLB,
   4623                                                 AttributedTypeLoc TL) {
   4624   const AttributedType *oldType = TL.getTypePtr();
   4625   QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
   4626   if (modifiedType.isNull())
   4627     return QualType();
   4628 
   4629   QualType result = TL.getType();
   4630 
   4631   // FIXME: dependent operand expressions?
   4632   if (getDerived().AlwaysRebuild() ||
   4633       modifiedType != oldType->getModifiedType()) {
   4634     // TODO: this is really lame; we should really be rebuilding the
   4635     // equivalent type from first principles.
   4636     QualType equivalentType
   4637       = getDerived().TransformType(oldType->getEquivalentType());
   4638     if (equivalentType.isNull())
   4639       return QualType();
   4640     result = SemaRef.Context.getAttributedType(oldType->getAttrKind(),
   4641                                                modifiedType,
   4642                                                equivalentType);
   4643   }
   4644 
   4645   AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
   4646   newTL.setAttrNameLoc(TL.getAttrNameLoc());
   4647   if (TL.hasAttrOperand())
   4648     newTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
   4649   if (TL.hasAttrExprOperand())
   4650     newTL.setAttrExprOperand(TL.getAttrExprOperand());
   4651   else if (TL.hasAttrEnumOperand())
   4652     newTL.setAttrEnumOperandLoc(TL.getAttrEnumOperandLoc());
   4653 
   4654   return result;
   4655 }
   4656 
   4657 template<typename Derived>
   4658 QualType
   4659 TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
   4660                                            ParenTypeLoc TL) {
   4661   QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
   4662   if (Inner.isNull())
   4663     return QualType();
   4664 
   4665   QualType Result = TL.getType();
   4666   if (getDerived().AlwaysRebuild() ||
   4667       Inner != TL.getInnerLoc().getType()) {
   4668     Result = getDerived().RebuildParenType(Inner);
   4669     if (Result.isNull())
   4670       return QualType();
   4671   }
   4672 
   4673   ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
   4674   NewTL.setLParenLoc(TL.getLParenLoc());
   4675   NewTL.setRParenLoc(TL.getRParenLoc());
   4676   return Result;
   4677 }
   4678 
   4679 template<typename Derived>
   4680 QualType TreeTransform<Derived>::TransformDependentNameType(TypeLocBuilder &TLB,
   4681                                                       DependentNameTypeLoc TL) {
   4682   const DependentNameType *T = TL.getTypePtr();
   4683 
   4684   NestedNameSpecifierLoc QualifierLoc
   4685     = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   4686   if (!QualifierLoc)
   4687     return QualType();
   4688 
   4689   QualType Result
   4690     = getDerived().RebuildDependentNameType(T->getKeyword(),
   4691                                             TL.getKeywordLoc(),
   4692                                             QualifierLoc,
   4693                                             T->getIdentifier(),
   4694                                             TL.getNameLoc());
   4695   if (Result.isNull())
   4696     return QualType();
   4697 
   4698   if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
   4699     QualType NamedT = ElabT->getNamedType();
   4700     TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
   4701 
   4702     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   4703     NewTL.setKeywordLoc(TL.getKeywordLoc());
   4704     NewTL.setQualifierLoc(QualifierLoc);
   4705   } else {
   4706     DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
   4707     NewTL.setKeywordLoc(TL.getKeywordLoc());
   4708     NewTL.setQualifierLoc(QualifierLoc);
   4709     NewTL.setNameLoc(TL.getNameLoc());
   4710   }
   4711   return Result;
   4712 }
   4713 
   4714 template<typename Derived>
   4715 QualType TreeTransform<Derived>::
   4716           TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
   4717                                  DependentTemplateSpecializationTypeLoc TL) {
   4718   NestedNameSpecifierLoc QualifierLoc;
   4719   if (TL.getQualifierLoc()) {
   4720     QualifierLoc
   4721       = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
   4722     if (!QualifierLoc)
   4723       return QualType();
   4724   }
   4725 
   4726   return getDerived()
   4727            .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
   4728 }
   4729 
   4730 template<typename Derived>
   4731 QualType TreeTransform<Derived>::
   4732 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
   4733                                    DependentTemplateSpecializationTypeLoc TL,
   4734                                        NestedNameSpecifierLoc QualifierLoc) {
   4735   const DependentTemplateSpecializationType *T = TL.getTypePtr();
   4736 
   4737   TemplateArgumentListInfo NewTemplateArgs;
   4738   NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
   4739   NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
   4740 
   4741   typedef TemplateArgumentLocContainerIterator<
   4742   DependentTemplateSpecializationTypeLoc> ArgIterator;
   4743   if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
   4744                                               ArgIterator(TL, TL.getNumArgs()),
   4745                                               NewTemplateArgs))
   4746     return QualType();
   4747 
   4748   QualType Result
   4749     = getDerived().RebuildDependentTemplateSpecializationType(T->getKeyword(),
   4750                                                               QualifierLoc,
   4751                                                             T->getIdentifier(),
   4752                                                             TL.getNameLoc(),
   4753                                                             NewTemplateArgs);
   4754   if (Result.isNull())
   4755     return QualType();
   4756 
   4757   if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
   4758     QualType NamedT = ElabT->getNamedType();
   4759 
   4760     // Copy information relevant to the template specialization.
   4761     TemplateSpecializationTypeLoc NamedTL
   4762       = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
   4763     NamedTL.setTemplateNameLoc(TL.getNameLoc());
   4764     NamedTL.setLAngleLoc(TL.getLAngleLoc());
   4765     NamedTL.setRAngleLoc(TL.getRAngleLoc());
   4766     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   4767       NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   4768 
   4769     // Copy information relevant to the elaborated type.
   4770     ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
   4771     NewTL.setKeywordLoc(TL.getKeywordLoc());
   4772     NewTL.setQualifierLoc(QualifierLoc);
   4773   } else if (isa<DependentTemplateSpecializationType>(Result)) {
   4774     DependentTemplateSpecializationTypeLoc SpecTL
   4775       = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
   4776     SpecTL.setKeywordLoc(TL.getKeywordLoc());
   4777     SpecTL.setQualifierLoc(QualifierLoc);
   4778     SpecTL.setNameLoc(TL.getNameLoc());
   4779     SpecTL.setLAngleLoc(TL.getLAngleLoc());
   4780     SpecTL.setRAngleLoc(TL.getRAngleLoc());
   4781     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   4782       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   4783   } else {
   4784     TemplateSpecializationTypeLoc SpecTL
   4785       = TLB.push<TemplateSpecializationTypeLoc>(Result);
   4786     SpecTL.setTemplateNameLoc(TL.getNameLoc());
   4787     SpecTL.setLAngleLoc(TL.getLAngleLoc());
   4788     SpecTL.setRAngleLoc(TL.getRAngleLoc());
   4789     for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
   4790       SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
   4791   }
   4792   return Result;
   4793 }
   4794 
   4795 template<typename Derived>
   4796 QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
   4797                                                       PackExpansionTypeLoc TL) {
   4798   QualType Pattern
   4799     = getDerived().TransformType(TLB, TL.getPatternLoc());
   4800   if (Pattern.isNull())
   4801     return QualType();
   4802 
   4803   QualType Result = TL.getType();
   4804   if (getDerived().AlwaysRebuild() ||
   4805       Pattern != TL.getPatternLoc().getType()) {
   4806     Result = getDerived().RebuildPackExpansionType(Pattern,
   4807                                            TL.getPatternLoc().getSourceRange(),
   4808                                                    TL.getEllipsisLoc(),
   4809                                            TL.getTypePtr()->getNumExpansions());
   4810     if (Result.isNull())
   4811       return QualType();
   4812   }
   4813 
   4814   PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
   4815   NewT.setEllipsisLoc(TL.getEllipsisLoc());
   4816   return Result;
   4817 }
   4818 
   4819 template<typename Derived>
   4820 QualType
   4821 TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
   4822                                                    ObjCInterfaceTypeLoc TL) {
   4823   // ObjCInterfaceType is never dependent.
   4824   TLB.pushFullCopy(TL);
   4825   return TL.getType();
   4826 }
   4827 
   4828 template<typename Derived>
   4829 QualType
   4830 TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
   4831                                                 ObjCObjectTypeLoc TL) {
   4832   // ObjCObjectType is never dependent.
   4833   TLB.pushFullCopy(TL);
   4834   return TL.getType();
   4835 }
   4836 
   4837 template<typename Derived>
   4838 QualType
   4839 TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
   4840                                                ObjCObjectPointerTypeLoc TL) {
   4841   // ObjCObjectPointerType is never dependent.
   4842   TLB.pushFullCopy(TL);
   4843   return TL.getType();
   4844 }
   4845 
   4846 //===----------------------------------------------------------------------===//
   4847 // Statement transformation
   4848 //===----------------------------------------------------------------------===//
   4849 template<typename Derived>
   4850 StmtResult
   4851 TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
   4852   return SemaRef.Owned(S);
   4853 }
   4854 
   4855 template<typename Derived>
   4856 StmtResult
   4857 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
   4858   return getDerived().TransformCompoundStmt(S, false);
   4859 }
   4860 
   4861 template<typename Derived>
   4862 StmtResult
   4863 TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
   4864                                               bool IsStmtExpr) {
   4865   bool SubStmtInvalid = false;
   4866   bool SubStmtChanged = false;
   4867   ASTOwningVector<Stmt*> Statements(getSema());
   4868   for (CompoundStmt::body_iterator B = S->body_begin(), BEnd = S->body_end();
   4869        B != BEnd; ++B) {
   4870     StmtResult Result = getDerived().TransformStmt(*B);
   4871     if (Result.isInvalid()) {
   4872       // Immediately fail if this was a DeclStmt, since it's very
   4873       // likely that this will cause problems for future statements.
   4874       if (isa<DeclStmt>(*B))
   4875         return StmtError();
   4876 
   4877       // Otherwise, just keep processing substatements and fail later.
   4878       SubStmtInvalid = true;
   4879       continue;
   4880     }
   4881 
   4882     SubStmtChanged = SubStmtChanged || Result.get() != *B;
   4883     Statements.push_back(Result.takeAs<Stmt>());
   4884   }
   4885 
   4886   if (SubStmtInvalid)
   4887     return StmtError();
   4888 
   4889   if (!getDerived().AlwaysRebuild() &&
   4890       !SubStmtChanged)
   4891     return SemaRef.Owned(S);
   4892 
   4893   return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
   4894                                           move_arg(Statements),
   4895                                           S->getRBracLoc(),
   4896                                           IsStmtExpr);
   4897 }
   4898 
   4899 template<typename Derived>
   4900 StmtResult
   4901 TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
   4902   ExprResult LHS, RHS;
   4903   {
   4904     // The case value expressions are not potentially evaluated.
   4905     EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   4906 
   4907     // Transform the left-hand case value.
   4908     LHS = getDerived().TransformExpr(S->getLHS());
   4909     if (LHS.isInvalid())
   4910       return StmtError();
   4911 
   4912     // Transform the right-hand case value (for the GNU case-range extension).
   4913     RHS = getDerived().TransformExpr(S->getRHS());
   4914     if (RHS.isInvalid())
   4915       return StmtError();
   4916   }
   4917 
   4918   // Build the case statement.
   4919   // Case statements are always rebuilt so that they will attached to their
   4920   // transformed switch statement.
   4921   StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
   4922                                                        LHS.get(),
   4923                                                        S->getEllipsisLoc(),
   4924                                                        RHS.get(),
   4925                                                        S->getColonLoc());
   4926   if (Case.isInvalid())
   4927     return StmtError();
   4928 
   4929   // Transform the statement following the case
   4930   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   4931   if (SubStmt.isInvalid())
   4932     return StmtError();
   4933 
   4934   // Attach the body to the case statement
   4935   return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
   4936 }
   4937 
   4938 template<typename Derived>
   4939 StmtResult
   4940 TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
   4941   // Transform the statement following the default case
   4942   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   4943   if (SubStmt.isInvalid())
   4944     return StmtError();
   4945 
   4946   // Default statements are always rebuilt
   4947   return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
   4948                                          SubStmt.get());
   4949 }
   4950 
   4951 template<typename Derived>
   4952 StmtResult
   4953 TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S) {
   4954   StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt());
   4955   if (SubStmt.isInvalid())
   4956     return StmtError();
   4957 
   4958   Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
   4959                                         S->getDecl());
   4960   if (!LD)
   4961     return StmtError();
   4962 
   4963 
   4964   // FIXME: Pass the real colon location in.
   4965   return getDerived().RebuildLabelStmt(S->getIdentLoc(),
   4966                                        cast<LabelDecl>(LD), SourceLocation(),
   4967                                        SubStmt.get());
   4968 }
   4969 
   4970 template<typename Derived>
   4971 StmtResult
   4972 TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
   4973   // Transform the condition
   4974   ExprResult Cond;
   4975   VarDecl *ConditionVar = 0;
   4976   if (S->getConditionVariable()) {
   4977     ConditionVar
   4978       = cast_or_null<VarDecl>(
   4979                    getDerived().TransformDefinition(
   4980                                       S->getConditionVariable()->getLocation(),
   4981                                                     S->getConditionVariable()));
   4982     if (!ConditionVar)
   4983       return StmtError();
   4984   } else {
   4985     Cond = getDerived().TransformExpr(S->getCond());
   4986 
   4987     if (Cond.isInvalid())
   4988       return StmtError();
   4989 
   4990     // Convert the condition to a boolean value.
   4991     if (S->getCond()) {
   4992       ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getIfLoc(),
   4993                                                          Cond.get());
   4994       if (CondE.isInvalid())
   4995         return StmtError();
   4996 
   4997       Cond = CondE.get();
   4998     }
   4999   }
   5000 
   5001   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
   5002   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   5003     return StmtError();
   5004 
   5005   // Transform the "then" branch.
   5006   StmtResult Then = getDerived().TransformStmt(S->getThen());
   5007   if (Then.isInvalid())
   5008     return StmtError();
   5009 
   5010   // Transform the "else" branch.
   5011   StmtResult Else = getDerived().TransformStmt(S->getElse());
   5012   if (Else.isInvalid())
   5013     return StmtError();
   5014 
   5015   if (!getDerived().AlwaysRebuild() &&
   5016       FullCond.get() == S->getCond() &&
   5017       ConditionVar == S->getConditionVariable() &&
   5018       Then.get() == S->getThen() &&
   5019       Else.get() == S->getElse())
   5020     return SemaRef.Owned(S);
   5021 
   5022   return getDerived().RebuildIfStmt(S->getIfLoc(), FullCond, ConditionVar,
   5023                                     Then.get(),
   5024                                     S->getElseLoc(), Else.get());
   5025 }
   5026 
   5027 template<typename Derived>
   5028 StmtResult
   5029 TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
   5030   // Transform the condition.
   5031   ExprResult Cond;
   5032   VarDecl *ConditionVar = 0;
   5033   if (S->getConditionVariable()) {
   5034     ConditionVar
   5035       = cast_or_null<VarDecl>(
   5036                    getDerived().TransformDefinition(
   5037                                       S->getConditionVariable()->getLocation(),
   5038                                                     S->getConditionVariable()));
   5039     if (!ConditionVar)
   5040       return StmtError();
   5041   } else {
   5042     Cond = getDerived().TransformExpr(S->getCond());
   5043 
   5044     if (Cond.isInvalid())
   5045       return StmtError();
   5046   }
   5047 
   5048   // Rebuild the switch statement.
   5049   StmtResult Switch
   5050     = getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), Cond.get(),
   5051                                           ConditionVar);
   5052   if (Switch.isInvalid())
   5053     return StmtError();
   5054 
   5055   // Transform the body of the switch statement.
   5056   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5057   if (Body.isInvalid())
   5058     return StmtError();
   5059 
   5060   // Complete the switch statement.
   5061   return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
   5062                                             Body.get());
   5063 }
   5064 
   5065 template<typename Derived>
   5066 StmtResult
   5067 TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
   5068   // Transform the condition
   5069   ExprResult Cond;
   5070   VarDecl *ConditionVar = 0;
   5071   if (S->getConditionVariable()) {
   5072     ConditionVar
   5073       = cast_or_null<VarDecl>(
   5074                    getDerived().TransformDefinition(
   5075                                       S->getConditionVariable()->getLocation(),
   5076                                                     S->getConditionVariable()));
   5077     if (!ConditionVar)
   5078       return StmtError();
   5079   } else {
   5080     Cond = getDerived().TransformExpr(S->getCond());
   5081 
   5082     if (Cond.isInvalid())
   5083       return StmtError();
   5084 
   5085     if (S->getCond()) {
   5086       // Convert the condition to a boolean value.
   5087       ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getWhileLoc(),
   5088                                                          Cond.get());
   5089       if (CondE.isInvalid())
   5090         return StmtError();
   5091       Cond = CondE;
   5092     }
   5093   }
   5094 
   5095   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
   5096   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   5097     return StmtError();
   5098 
   5099   // Transform the body
   5100   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5101   if (Body.isInvalid())
   5102     return StmtError();
   5103 
   5104   if (!getDerived().AlwaysRebuild() &&
   5105       FullCond.get() == S->getCond() &&
   5106       ConditionVar == S->getConditionVariable() &&
   5107       Body.get() == S->getBody())
   5108     return Owned(S);
   5109 
   5110   return getDerived().RebuildWhileStmt(S->getWhileLoc(), FullCond,
   5111                                        ConditionVar, Body.get());
   5112 }
   5113 
   5114 template<typename Derived>
   5115 StmtResult
   5116 TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
   5117   // Transform the body
   5118   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5119   if (Body.isInvalid())
   5120     return StmtError();
   5121 
   5122   // Transform the condition
   5123   ExprResult Cond = getDerived().TransformExpr(S->getCond());
   5124   if (Cond.isInvalid())
   5125     return StmtError();
   5126 
   5127   if (!getDerived().AlwaysRebuild() &&
   5128       Cond.get() == S->getCond() &&
   5129       Body.get() == S->getBody())
   5130     return SemaRef.Owned(S);
   5131 
   5132   return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
   5133                                     /*FIXME:*/S->getWhileLoc(), Cond.get(),
   5134                                     S->getRParenLoc());
   5135 }
   5136 
   5137 template<typename Derived>
   5138 StmtResult
   5139 TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
   5140   // Transform the initialization statement
   5141   StmtResult Init = getDerived().TransformStmt(S->getInit());
   5142   if (Init.isInvalid())
   5143     return StmtError();
   5144 
   5145   // Transform the condition
   5146   ExprResult Cond;
   5147   VarDecl *ConditionVar = 0;
   5148   if (S->getConditionVariable()) {
   5149     ConditionVar
   5150       = cast_or_null<VarDecl>(
   5151                    getDerived().TransformDefinition(
   5152                                       S->getConditionVariable()->getLocation(),
   5153                                                     S->getConditionVariable()));
   5154     if (!ConditionVar)
   5155       return StmtError();
   5156   } else {
   5157     Cond = getDerived().TransformExpr(S->getCond());
   5158 
   5159     if (Cond.isInvalid())
   5160       return StmtError();
   5161 
   5162     if (S->getCond()) {
   5163       // Convert the condition to a boolean value.
   5164       ExprResult CondE = getSema().ActOnBooleanCondition(0, S->getForLoc(),
   5165                                                          Cond.get());
   5166       if (CondE.isInvalid())
   5167         return StmtError();
   5168 
   5169       Cond = CondE.get();
   5170     }
   5171   }
   5172 
   5173   Sema::FullExprArg FullCond(getSema().MakeFullExpr(Cond.take()));
   5174   if (!S->getConditionVariable() && S->getCond() && !FullCond.get())
   5175     return StmtError();
   5176 
   5177   // Transform the increment
   5178   ExprResult Inc = getDerived().TransformExpr(S->getInc());
   5179   if (Inc.isInvalid())
   5180     return StmtError();
   5181 
   5182   Sema::FullExprArg FullInc(getSema().MakeFullExpr(Inc.get()));
   5183   if (S->getInc() && !FullInc.get())
   5184     return StmtError();
   5185 
   5186   // Transform the body
   5187   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5188   if (Body.isInvalid())
   5189     return StmtError();
   5190 
   5191   if (!getDerived().AlwaysRebuild() &&
   5192       Init.get() == S->getInit() &&
   5193       FullCond.get() == S->getCond() &&
   5194       Inc.get() == S->getInc() &&
   5195       Body.get() == S->getBody())
   5196     return SemaRef.Owned(S);
   5197 
   5198   return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
   5199                                      Init.get(), FullCond, ConditionVar,
   5200                                      FullInc, S->getRParenLoc(), Body.get());
   5201 }
   5202 
   5203 template<typename Derived>
   5204 StmtResult
   5205 TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
   5206   Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
   5207                                         S->getLabel());
   5208   if (!LD)
   5209     return StmtError();
   5210 
   5211   // Goto statements must always be rebuilt, to resolve the label.
   5212   return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
   5213                                       cast<LabelDecl>(LD));
   5214 }
   5215 
   5216 template<typename Derived>
   5217 StmtResult
   5218 TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
   5219   ExprResult Target = getDerived().TransformExpr(S->getTarget());
   5220   if (Target.isInvalid())
   5221     return StmtError();
   5222 
   5223   if (!getDerived().AlwaysRebuild() &&
   5224       Target.get() == S->getTarget())
   5225     return SemaRef.Owned(S);
   5226 
   5227   return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
   5228                                               Target.get());
   5229 }
   5230 
   5231 template<typename Derived>
   5232 StmtResult
   5233 TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
   5234   return SemaRef.Owned(S);
   5235 }
   5236 
   5237 template<typename Derived>
   5238 StmtResult
   5239 TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
   5240   return SemaRef.Owned(S);
   5241 }
   5242 
   5243 template<typename Derived>
   5244 StmtResult
   5245 TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
   5246   ExprResult Result = getDerived().TransformExpr(S->getRetValue());
   5247   if (Result.isInvalid())
   5248     return StmtError();
   5249 
   5250   // FIXME: We always rebuild the return statement because there is no way
   5251   // to tell whether the return type of the function has changed.
   5252   return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
   5253 }
   5254 
   5255 template<typename Derived>
   5256 StmtResult
   5257 TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
   5258   bool DeclChanged = false;
   5259   llvm::SmallVector<Decl *, 4> Decls;
   5260   for (DeclStmt::decl_iterator D = S->decl_begin(), DEnd = S->decl_end();
   5261        D != DEnd; ++D) {
   5262     Decl *Transformed = getDerived().TransformDefinition((*D)->getLocation(),
   5263                                                          *D);
   5264     if (!Transformed)
   5265       return StmtError();
   5266 
   5267     if (Transformed != *D)
   5268       DeclChanged = true;
   5269 
   5270     Decls.push_back(Transformed);
   5271   }
   5272 
   5273   if (!getDerived().AlwaysRebuild() && !DeclChanged)
   5274     return SemaRef.Owned(S);
   5275 
   5276   return getDerived().RebuildDeclStmt(Decls.data(), Decls.size(),
   5277                                       S->getStartLoc(), S->getEndLoc());
   5278 }
   5279 
   5280 template<typename Derived>
   5281 StmtResult
   5282 TreeTransform<Derived>::TransformAsmStmt(AsmStmt *S) {
   5283 
   5284   ASTOwningVector<Expr*> Constraints(getSema());
   5285   ASTOwningVector<Expr*> Exprs(getSema());
   5286   llvm::SmallVector<IdentifierInfo *, 4> Names;
   5287 
   5288   ExprResult AsmString;
   5289   ASTOwningVector<Expr*> Clobbers(getSema());
   5290 
   5291   bool ExprsChanged = false;
   5292 
   5293   // Go through the outputs.
   5294   for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
   5295     Names.push_back(S->getOutputIdentifier(I));
   5296 
   5297     // No need to transform the constraint literal.
   5298     Constraints.push_back(S->getOutputConstraintLiteral(I));
   5299 
   5300     // Transform the output expr.
   5301     Expr *OutputExpr = S->getOutputExpr(I);
   5302     ExprResult Result = getDerived().TransformExpr(OutputExpr);
   5303     if (Result.isInvalid())
   5304       return StmtError();
   5305 
   5306     ExprsChanged |= Result.get() != OutputExpr;
   5307 
   5308     Exprs.push_back(Result.get());
   5309   }
   5310 
   5311   // Go through the inputs.
   5312   for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
   5313     Names.push_back(S->getInputIdentifier(I));
   5314 
   5315     // No need to transform the constraint literal.
   5316     Constraints.push_back(S->getInputConstraintLiteral(I));
   5317 
   5318     // Transform the input expr.
   5319     Expr *InputExpr = S->getInputExpr(I);
   5320     ExprResult Result = getDerived().TransformExpr(InputExpr);
   5321     if (Result.isInvalid())
   5322       return StmtError();
   5323 
   5324     ExprsChanged |= Result.get() != InputExpr;
   5325 
   5326     Exprs.push_back(Result.get());
   5327   }
   5328 
   5329   if (!getDerived().AlwaysRebuild() && !ExprsChanged)
   5330     return SemaRef.Owned(S);
   5331 
   5332   // Go through the clobbers.
   5333   for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
   5334     Clobbers.push_back(S->getClobber(I));
   5335 
   5336   // No need to transform the asm string literal.
   5337   AsmString = SemaRef.Owned(S->getAsmString());
   5338 
   5339   return getDerived().RebuildAsmStmt(S->getAsmLoc(),
   5340                                      S->isSimple(),
   5341                                      S->isVolatile(),
   5342                                      S->getNumOutputs(),
   5343                                      S->getNumInputs(),
   5344                                      Names.data(),
   5345                                      move_arg(Constraints),
   5346                                      move_arg(Exprs),
   5347                                      AsmString.get(),
   5348                                      move_arg(Clobbers),
   5349                                      S->getRParenLoc(),
   5350                                      S->isMSAsm());
   5351 }
   5352 
   5353 
   5354 template<typename Derived>
   5355 StmtResult
   5356 TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
   5357   // Transform the body of the @try.
   5358   StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
   5359   if (TryBody.isInvalid())
   5360     return StmtError();
   5361 
   5362   // Transform the @catch statements (if present).
   5363   bool AnyCatchChanged = false;
   5364   ASTOwningVector<Stmt*> CatchStmts(SemaRef);
   5365   for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
   5366     StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
   5367     if (Catch.isInvalid())
   5368       return StmtError();
   5369     if (Catch.get() != S->getCatchStmt(I))
   5370       AnyCatchChanged = true;
   5371     CatchStmts.push_back(Catch.release());
   5372   }
   5373 
   5374   // Transform the @finally statement (if present).
   5375   StmtResult Finally;
   5376   if (S->getFinallyStmt()) {
   5377     Finally = getDerived().TransformStmt(S->getFinallyStmt());
   5378     if (Finally.isInvalid())
   5379       return StmtError();
   5380   }
   5381 
   5382   // If nothing changed, just retain this statement.
   5383   if (!getDerived().AlwaysRebuild() &&
   5384       TryBody.get() == S->getTryBody() &&
   5385       !AnyCatchChanged &&
   5386       Finally.get() == S->getFinallyStmt())
   5387     return SemaRef.Owned(S);
   5388 
   5389   // Build a new statement.
   5390   return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
   5391                                            move_arg(CatchStmts), Finally.get());
   5392 }
   5393 
   5394 template<typename Derived>
   5395 StmtResult
   5396 TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
   5397   // Transform the @catch parameter, if there is one.
   5398   VarDecl *Var = 0;
   5399   if (VarDecl *FromVar = S->getCatchParamDecl()) {
   5400     TypeSourceInfo *TSInfo = 0;
   5401     if (FromVar->getTypeSourceInfo()) {
   5402       TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
   5403       if (!TSInfo)
   5404         return StmtError();
   5405     }
   5406 
   5407     QualType T;
   5408     if (TSInfo)
   5409       T = TSInfo->getType();
   5410     else {
   5411       T = getDerived().TransformType(FromVar->getType());
   5412       if (T.isNull())
   5413         return StmtError();
   5414     }
   5415 
   5416     Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
   5417     if (!Var)
   5418       return StmtError();
   5419   }
   5420 
   5421   StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
   5422   if (Body.isInvalid())
   5423     return StmtError();
   5424 
   5425   return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
   5426                                              S->getRParenLoc(),
   5427                                              Var, Body.get());
   5428 }
   5429 
   5430 template<typename Derived>
   5431 StmtResult
   5432 TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
   5433   // Transform the body.
   5434   StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
   5435   if (Body.isInvalid())
   5436     return StmtError();
   5437 
   5438   // If nothing changed, just retain this statement.
   5439   if (!getDerived().AlwaysRebuild() &&
   5440       Body.get() == S->getFinallyBody())
   5441     return SemaRef.Owned(S);
   5442 
   5443   // Build a new statement.
   5444   return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
   5445                                                Body.get());
   5446 }
   5447 
   5448 template<typename Derived>
   5449 StmtResult
   5450 TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
   5451   ExprResult Operand;
   5452   if (S->getThrowExpr()) {
   5453     Operand = getDerived().TransformExpr(S->getThrowExpr());
   5454     if (Operand.isInvalid())
   5455       return StmtError();
   5456   }
   5457 
   5458   if (!getDerived().AlwaysRebuild() &&
   5459       Operand.get() == S->getThrowExpr())
   5460     return getSema().Owned(S);
   5461 
   5462   return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
   5463 }
   5464 
   5465 template<typename Derived>
   5466 StmtResult
   5467 TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
   5468                                                   ObjCAtSynchronizedStmt *S) {
   5469   // Transform the object we are locking.
   5470   ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
   5471   if (Object.isInvalid())
   5472     return StmtError();
   5473 
   5474   // Transform the body.
   5475   StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
   5476   if (Body.isInvalid())
   5477     return StmtError();
   5478 
   5479   // If nothing change, just retain the current statement.
   5480   if (!getDerived().AlwaysRebuild() &&
   5481       Object.get() == S->getSynchExpr() &&
   5482       Body.get() == S->getSynchBody())
   5483     return SemaRef.Owned(S);
   5484 
   5485   // Build a new statement.
   5486   return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
   5487                                                     Object.get(), Body.get());
   5488 }
   5489 
   5490 template<typename Derived>
   5491 StmtResult
   5492 TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
   5493                                               ObjCAutoreleasePoolStmt *S) {
   5494   // Transform the body.
   5495   StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
   5496   if (Body.isInvalid())
   5497     return StmtError();
   5498 
   5499   // If nothing changed, just retain this statement.
   5500   if (!getDerived().AlwaysRebuild() &&
   5501       Body.get() == S->getSubStmt())
   5502     return SemaRef.Owned(S);
   5503 
   5504   // Build a new statement.
   5505   return getDerived().RebuildObjCAutoreleasePoolStmt(
   5506                         S->getAtLoc(), Body.get());
   5507 }
   5508 
   5509 template<typename Derived>
   5510 StmtResult
   5511 TreeTransform<Derived>::TransformObjCForCollectionStmt(
   5512                                                   ObjCForCollectionStmt *S) {
   5513   // Transform the element statement.
   5514   StmtResult Element = getDerived().TransformStmt(S->getElement());
   5515   if (Element.isInvalid())
   5516     return StmtError();
   5517 
   5518   // Transform the collection expression.
   5519   ExprResult Collection = getDerived().TransformExpr(S->getCollection());
   5520   if (Collection.isInvalid())
   5521     return StmtError();
   5522 
   5523   // Transform the body.
   5524   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5525   if (Body.isInvalid())
   5526     return StmtError();
   5527 
   5528   // If nothing changed, just retain this statement.
   5529   if (!getDerived().AlwaysRebuild() &&
   5530       Element.get() == S->getElement() &&
   5531       Collection.get() == S->getCollection() &&
   5532       Body.get() == S->getBody())
   5533     return SemaRef.Owned(S);
   5534 
   5535   // Build a new statement.
   5536   return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
   5537                                                    /*FIXME:*/S->getForLoc(),
   5538                                                    Element.get(),
   5539                                                    Collection.get(),
   5540                                                    S->getRParenLoc(),
   5541                                                    Body.get());
   5542 }
   5543 
   5544 
   5545 template<typename Derived>
   5546 StmtResult
   5547 TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
   5548   // Transform the exception declaration, if any.
   5549   VarDecl *Var = 0;
   5550   if (S->getExceptionDecl()) {
   5551     VarDecl *ExceptionDecl = S->getExceptionDecl();
   5552     TypeSourceInfo *T = getDerived().TransformType(
   5553                                             ExceptionDecl->getTypeSourceInfo());
   5554     if (!T)
   5555       return StmtError();
   5556 
   5557     Var = getDerived().RebuildExceptionDecl(ExceptionDecl, T,
   5558                                             ExceptionDecl->getInnerLocStart(),
   5559                                             ExceptionDecl->getLocation(),
   5560                                             ExceptionDecl->getIdentifier());
   5561     if (!Var || Var->isInvalidDecl())
   5562       return StmtError();
   5563   }
   5564 
   5565   // Transform the actual exception handler.
   5566   StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
   5567   if (Handler.isInvalid())
   5568     return StmtError();
   5569 
   5570   if (!getDerived().AlwaysRebuild() &&
   5571       !Var &&
   5572       Handler.get() == S->getHandlerBlock())
   5573     return SemaRef.Owned(S);
   5574 
   5575   return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(),
   5576                                           Var,
   5577                                           Handler.get());
   5578 }
   5579 
   5580 template<typename Derived>
   5581 StmtResult
   5582 TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
   5583   // Transform the try block itself.
   5584   StmtResult TryBlock
   5585     = getDerived().TransformCompoundStmt(S->getTryBlock());
   5586   if (TryBlock.isInvalid())
   5587     return StmtError();
   5588 
   5589   // Transform the handlers.
   5590   bool HandlerChanged = false;
   5591   ASTOwningVector<Stmt*> Handlers(SemaRef);
   5592   for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
   5593     StmtResult Handler
   5594       = getDerived().TransformCXXCatchStmt(S->getHandler(I));
   5595     if (Handler.isInvalid())
   5596       return StmtError();
   5597 
   5598     HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
   5599     Handlers.push_back(Handler.takeAs<Stmt>());
   5600   }
   5601 
   5602   if (!getDerived().AlwaysRebuild() &&
   5603       TryBlock.get() == S->getTryBlock() &&
   5604       !HandlerChanged)
   5605     return SemaRef.Owned(S);
   5606 
   5607   return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
   5608                                         move_arg(Handlers));
   5609 }
   5610 
   5611 template<typename Derived>
   5612 StmtResult
   5613 TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
   5614   StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
   5615   if (Range.isInvalid())
   5616     return StmtError();
   5617 
   5618   StmtResult BeginEnd = getDerived().TransformStmt(S->getBeginEndStmt());
   5619   if (BeginEnd.isInvalid())
   5620     return StmtError();
   5621 
   5622   ExprResult Cond = getDerived().TransformExpr(S->getCond());
   5623   if (Cond.isInvalid())
   5624     return StmtError();
   5625 
   5626   ExprResult Inc = getDerived().TransformExpr(S->getInc());
   5627   if (Inc.isInvalid())
   5628     return StmtError();
   5629 
   5630   StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
   5631   if (LoopVar.isInvalid())
   5632     return StmtError();
   5633 
   5634   StmtResult NewStmt = S;
   5635   if (getDerived().AlwaysRebuild() ||
   5636       Range.get() != S->getRangeStmt() ||
   5637       BeginEnd.get() != S->getBeginEndStmt() ||
   5638       Cond.get() != S->getCond() ||
   5639       Inc.get() != S->getInc() ||
   5640       LoopVar.get() != S->getLoopVarStmt())
   5641     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
   5642                                                   S->getColonLoc(), Range.get(),
   5643                                                   BeginEnd.get(), Cond.get(),
   5644                                                   Inc.get(), LoopVar.get(),
   5645                                                   S->getRParenLoc());
   5646 
   5647   StmtResult Body = getDerived().TransformStmt(S->getBody());
   5648   if (Body.isInvalid())
   5649     return StmtError();
   5650 
   5651   // Body has changed but we didn't rebuild the for-range statement. Rebuild
   5652   // it now so we have a new statement to attach the body to.
   5653   if (Body.get() != S->getBody() && NewStmt.get() == S)
   5654     NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
   5655                                                   S->getColonLoc(), Range.get(),
   5656                                                   BeginEnd.get(), Cond.get(),
   5657                                                   Inc.get(), LoopVar.get(),
   5658                                                   S->getRParenLoc());
   5659 
   5660   if (NewStmt.get() == S)
   5661     return SemaRef.Owned(S);
   5662 
   5663   return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
   5664 }
   5665 
   5666 template<typename Derived>
   5667 StmtResult
   5668 TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
   5669   StmtResult TryBlock; //  = getDerived().TransformCompoundStmt(S->getTryBlock());
   5670   if(TryBlock.isInvalid()) return StmtError();
   5671 
   5672   StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
   5673   if(!getDerived().AlwaysRebuild() &&
   5674      TryBlock.get() == S->getTryBlock() &&
   5675      Handler.get() == S->getHandler())
   5676     return SemaRef.Owned(S);
   5677 
   5678   return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(),
   5679                                         S->getTryLoc(),
   5680                                         TryBlock.take(),
   5681                                         Handler.take());
   5682 }
   5683 
   5684 template<typename Derived>
   5685 StmtResult
   5686 TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
   5687   StmtResult Block; //  = getDerived().TransformCompoundStatement(S->getBlock());
   5688   if(Block.isInvalid()) return StmtError();
   5689 
   5690   return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(),
   5691                                             Block.take());
   5692 }
   5693 
   5694 template<typename Derived>
   5695 StmtResult
   5696 TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
   5697   ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
   5698   if(FilterExpr.isInvalid()) return StmtError();
   5699 
   5700   StmtResult Block; //  = getDerived().TransformCompoundStatement(S->getBlock());
   5701   if(Block.isInvalid()) return StmtError();
   5702 
   5703   return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(),
   5704                                            FilterExpr.take(),
   5705                                            Block.take());
   5706 }
   5707 
   5708 template<typename Derived>
   5709 StmtResult
   5710 TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
   5711   if(isa<SEHFinallyStmt>(Handler))
   5712     return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
   5713   else
   5714     return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
   5715 }
   5716 
   5717 //===----------------------------------------------------------------------===//
   5718 // Expression transformation
   5719 //===----------------------------------------------------------------------===//
   5720 template<typename Derived>
   5721 ExprResult
   5722 TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
   5723   return SemaRef.Owned(E);
   5724 }
   5725 
   5726 template<typename Derived>
   5727 ExprResult
   5728 TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
   5729   NestedNameSpecifierLoc QualifierLoc;
   5730   if (E->getQualifierLoc()) {
   5731     QualifierLoc
   5732       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   5733     if (!QualifierLoc)
   5734       return ExprError();
   5735   }
   5736 
   5737   ValueDecl *ND
   5738     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
   5739                                                          E->getDecl()));
   5740   if (!ND)
   5741     return ExprError();
   5742 
   5743   DeclarationNameInfo NameInfo = E->getNameInfo();
   5744   if (NameInfo.getName()) {
   5745     NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
   5746     if (!NameInfo.getName())
   5747       return ExprError();
   5748   }
   5749 
   5750   if (!getDerived().AlwaysRebuild() &&
   5751       QualifierLoc == E->getQualifierLoc() &&
   5752       ND == E->getDecl() &&
   5753       NameInfo.getName() == E->getDecl()->getDeclName() &&
   5754       !E->hasExplicitTemplateArgs()) {
   5755 
   5756     // Mark it referenced in the new context regardless.
   5757     // FIXME: this is a bit instantiation-specific.
   5758     SemaRef.MarkDeclarationReferenced(E->getLocation(), ND);
   5759 
   5760     return SemaRef.Owned(E);
   5761   }
   5762 
   5763   TemplateArgumentListInfo TransArgs, *TemplateArgs = 0;
   5764   if (E->hasExplicitTemplateArgs()) {
   5765     TemplateArgs = &TransArgs;
   5766     TransArgs.setLAngleLoc(E->getLAngleLoc());
   5767     TransArgs.setRAngleLoc(E->getRAngleLoc());
   5768     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   5769                                                 E->getNumTemplateArgs(),
   5770                                                 TransArgs))
   5771       return ExprError();
   5772   }
   5773 
   5774   return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
   5775                                          TemplateArgs);
   5776 }
   5777 
   5778 template<typename Derived>
   5779 ExprResult
   5780 TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
   5781   return SemaRef.Owned(E);
   5782 }
   5783 
   5784 template<typename Derived>
   5785 ExprResult
   5786 TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
   5787   return SemaRef.Owned(E);
   5788 }
   5789 
   5790 template<typename Derived>
   5791 ExprResult
   5792 TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
   5793   return SemaRef.Owned(E);
   5794 }
   5795 
   5796 template<typename Derived>
   5797 ExprResult
   5798 TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
   5799   return SemaRef.Owned(E);
   5800 }
   5801 
   5802 template<typename Derived>
   5803 ExprResult
   5804 TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
   5805   return SemaRef.Owned(E);
   5806 }
   5807 
   5808 template<typename Derived>
   5809 ExprResult
   5810 TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
   5811   ExprResult ControllingExpr =
   5812     getDerived().TransformExpr(E->getControllingExpr());
   5813   if (ControllingExpr.isInvalid())
   5814     return ExprError();
   5815 
   5816   llvm::SmallVector<Expr *, 4> AssocExprs;
   5817   llvm::SmallVector<TypeSourceInfo *, 4> AssocTypes;
   5818   for (unsigned i = 0; i != E->getNumAssocs(); ++i) {
   5819     TypeSourceInfo *TS = E->getAssocTypeSourceInfo(i);
   5820     if (TS) {
   5821       TypeSourceInfo *AssocType = getDerived().TransformType(TS);
   5822       if (!AssocType)
   5823         return ExprError();
   5824       AssocTypes.push_back(AssocType);
   5825     } else {
   5826       AssocTypes.push_back(0);
   5827     }
   5828 
   5829     ExprResult AssocExpr = getDerived().TransformExpr(E->getAssocExpr(i));
   5830     if (AssocExpr.isInvalid())
   5831       return ExprError();
   5832     AssocExprs.push_back(AssocExpr.release());
   5833   }
   5834 
   5835   return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
   5836                                                   E->getDefaultLoc(),
   5837                                                   E->getRParenLoc(),
   5838                                                   ControllingExpr.release(),
   5839                                                   AssocTypes.data(),
   5840                                                   AssocExprs.data(),
   5841                                                   E->getNumAssocs());
   5842 }
   5843 
   5844 template<typename Derived>
   5845 ExprResult
   5846 TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
   5847   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   5848   if (SubExpr.isInvalid())
   5849     return ExprError();
   5850 
   5851   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
   5852     return SemaRef.Owned(E);
   5853 
   5854   return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
   5855                                        E->getRParen());
   5856 }
   5857 
   5858 template<typename Derived>
   5859 ExprResult
   5860 TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
   5861   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   5862   if (SubExpr.isInvalid())
   5863     return ExprError();
   5864 
   5865   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
   5866     return SemaRef.Owned(E);
   5867 
   5868   return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
   5869                                            E->getOpcode(),
   5870                                            SubExpr.get());
   5871 }
   5872 
   5873 template<typename Derived>
   5874 ExprResult
   5875 TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
   5876   // Transform the type.
   5877   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
   5878   if (!Type)
   5879     return ExprError();
   5880 
   5881   // Transform all of the components into components similar to what the
   5882   // parser uses.
   5883   // FIXME: It would be slightly more efficient in the non-dependent case to
   5884   // just map FieldDecls, rather than requiring the rebuilder to look for
   5885   // the fields again. However, __builtin_offsetof is rare enough in
   5886   // template code that we don't care.
   5887   bool ExprChanged = false;
   5888   typedef Sema::OffsetOfComponent Component;
   5889   typedef OffsetOfExpr::OffsetOfNode Node;
   5890   llvm::SmallVector<Component, 4> Components;
   5891   for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
   5892     const Node &ON = E->getComponent(I);
   5893     Component Comp;
   5894     Comp.isBrackets = true;
   5895     Comp.LocStart = ON.getSourceRange().getBegin();
   5896     Comp.LocEnd = ON.getSourceRange().getEnd();
   5897     switch (ON.getKind()) {
   5898     case Node::Array: {
   5899       Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
   5900       ExprResult Index = getDerived().TransformExpr(FromIndex);
   5901       if (Index.isInvalid())
   5902         return ExprError();
   5903 
   5904       ExprChanged = ExprChanged || Index.get() != FromIndex;
   5905       Comp.isBrackets = true;
   5906       Comp.U.E = Index.get();
   5907       break;
   5908     }
   5909 
   5910     case Node::Field:
   5911     case Node::Identifier:
   5912       Comp.isBrackets = false;
   5913       Comp.U.IdentInfo = ON.getFieldName();
   5914       if (!Comp.U.IdentInfo)
   5915         continue;
   5916 
   5917       break;
   5918 
   5919     case Node::Base:
   5920       // Will be recomputed during the rebuild.
   5921       continue;
   5922     }
   5923 
   5924     Components.push_back(Comp);
   5925   }
   5926 
   5927   // If nothing changed, retain the existing expression.
   5928   if (!getDerived().AlwaysRebuild() &&
   5929       Type == E->getTypeSourceInfo() &&
   5930       !ExprChanged)
   5931     return SemaRef.Owned(E);
   5932 
   5933   // Build a new offsetof expression.
   5934   return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
   5935                                           Components.data(), Components.size(),
   5936                                           E->getRParenLoc());
   5937 }
   5938 
   5939 template<typename Derived>
   5940 ExprResult
   5941 TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
   5942   assert(getDerived().AlreadyTransformed(E->getType()) &&
   5943          "opaque value expression requires transformation");
   5944   return SemaRef.Owned(E);
   5945 }
   5946 
   5947 template<typename Derived>
   5948 ExprResult
   5949 TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
   5950                                                 UnaryExprOrTypeTraitExpr *E) {
   5951   if (E->isArgumentType()) {
   5952     TypeSourceInfo *OldT = E->getArgumentTypeInfo();
   5953 
   5954     TypeSourceInfo *NewT = getDerived().TransformType(OldT);
   5955     if (!NewT)
   5956       return ExprError();
   5957 
   5958     if (!getDerived().AlwaysRebuild() && OldT == NewT)
   5959       return SemaRef.Owned(E);
   5960 
   5961     return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
   5962                                                     E->getKind(),
   5963                                                     E->getSourceRange());
   5964   }
   5965 
   5966   ExprResult SubExpr;
   5967   {
   5968     // C++0x [expr.sizeof]p1:
   5969     //   The operand is either an expression, which is an unevaluated operand
   5970     //   [...]
   5971     EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   5972 
   5973     SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
   5974     if (SubExpr.isInvalid())
   5975       return ExprError();
   5976 
   5977     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
   5978       return SemaRef.Owned(E);
   5979   }
   5980 
   5981   return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
   5982                                                   E->getOperatorLoc(),
   5983                                                   E->getKind(),
   5984                                                   E->getSourceRange());
   5985 }
   5986 
   5987 template<typename Derived>
   5988 ExprResult
   5989 TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
   5990   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   5991   if (LHS.isInvalid())
   5992     return ExprError();
   5993 
   5994   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   5995   if (RHS.isInvalid())
   5996     return ExprError();
   5997 
   5998 
   5999   if (!getDerived().AlwaysRebuild() &&
   6000       LHS.get() == E->getLHS() &&
   6001       RHS.get() == E->getRHS())
   6002     return SemaRef.Owned(E);
   6003 
   6004   return getDerived().RebuildArraySubscriptExpr(LHS.get(),
   6005                                            /*FIXME:*/E->getLHS()->getLocStart(),
   6006                                                 RHS.get(),
   6007                                                 E->getRBracketLoc());
   6008 }
   6009 
   6010 template<typename Derived>
   6011 ExprResult
   6012 TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
   6013   // Transform the callee.
   6014   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
   6015   if (Callee.isInvalid())
   6016     return ExprError();
   6017 
   6018   // Transform arguments.
   6019   bool ArgChanged = false;
   6020   ASTOwningVector<Expr*> Args(SemaRef);
   6021   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   6022                                   &ArgChanged))
   6023     return ExprError();
   6024 
   6025   if (!getDerived().AlwaysRebuild() &&
   6026       Callee.get() == E->getCallee() &&
   6027       !ArgChanged)
   6028     return SemaRef.Owned(E);
   6029 
   6030   // FIXME: Wrong source location information for the '('.
   6031   SourceLocation FakeLParenLoc
   6032     = ((Expr *)Callee.get())->getSourceRange().getBegin();
   6033   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
   6034                                       move_arg(Args),
   6035                                       E->getRParenLoc());
   6036 }
   6037 
   6038 template<typename Derived>
   6039 ExprResult
   6040 TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
   6041   ExprResult Base = getDerived().TransformExpr(E->getBase());
   6042   if (Base.isInvalid())
   6043     return ExprError();
   6044 
   6045   NestedNameSpecifierLoc QualifierLoc;
   6046   if (E->hasQualifier()) {
   6047     QualifierLoc
   6048       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   6049 
   6050     if (!QualifierLoc)
   6051       return ExprError();
   6052   }
   6053 
   6054   ValueDecl *Member
   6055     = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
   6056                                                          E->getMemberDecl()));
   6057   if (!Member)
   6058     return ExprError();
   6059 
   6060   NamedDecl *FoundDecl = E->getFoundDecl();
   6061   if (FoundDecl == E->getMemberDecl()) {
   6062     FoundDecl = Member;
   6063   } else {
   6064     FoundDecl = cast_or_null<NamedDecl>(
   6065                    getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
   6066     if (!FoundDecl)
   6067       return ExprError();
   6068   }
   6069 
   6070   if (!getDerived().AlwaysRebuild() &&
   6071       Base.get() == E->getBase() &&
   6072       QualifierLoc == E->getQualifierLoc() &&
   6073       Member == E->getMemberDecl() &&
   6074       FoundDecl == E->getFoundDecl() &&
   6075       !E->hasExplicitTemplateArgs()) {
   6076 
   6077     // Mark it referenced in the new context regardless.
   6078     // FIXME: this is a bit instantiation-specific.
   6079     SemaRef.MarkDeclarationReferenced(E->getMemberLoc(), Member);
   6080     return SemaRef.Owned(E);
   6081   }
   6082 
   6083   TemplateArgumentListInfo TransArgs;
   6084   if (E->hasExplicitTemplateArgs()) {
   6085     TransArgs.setLAngleLoc(E->getLAngleLoc());
   6086     TransArgs.setRAngleLoc(E->getRAngleLoc());
   6087     if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   6088                                                 E->getNumTemplateArgs(),
   6089                                                 TransArgs))
   6090       return ExprError();
   6091   }
   6092 
   6093   // FIXME: Bogus source location for the operator
   6094   SourceLocation FakeOperatorLoc
   6095     = SemaRef.PP.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
   6096 
   6097   // FIXME: to do this check properly, we will need to preserve the
   6098   // first-qualifier-in-scope here, just in case we had a dependent
   6099   // base (and therefore couldn't do the check) and a
   6100   // nested-name-qualifier (and therefore could do the lookup).
   6101   NamedDecl *FirstQualifierInScope = 0;
   6102 
   6103   return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
   6104                                         E->isArrow(),
   6105                                         QualifierLoc,
   6106                                         E->getMemberNameInfo(),
   6107                                         Member,
   6108                                         FoundDecl,
   6109                                         (E->hasExplicitTemplateArgs()
   6110                                            ? &TransArgs : 0),
   6111                                         FirstQualifierInScope);
   6112 }
   6113 
   6114 template<typename Derived>
   6115 ExprResult
   6116 TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
   6117   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   6118   if (LHS.isInvalid())
   6119     return ExprError();
   6120 
   6121   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   6122   if (RHS.isInvalid())
   6123     return ExprError();
   6124 
   6125   if (!getDerived().AlwaysRebuild() &&
   6126       LHS.get() == E->getLHS() &&
   6127       RHS.get() == E->getRHS())
   6128     return SemaRef.Owned(E);
   6129 
   6130   return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
   6131                                             LHS.get(), RHS.get());
   6132 }
   6133 
   6134 template<typename Derived>
   6135 ExprResult
   6136 TreeTransform<Derived>::TransformCompoundAssignOperator(
   6137                                                       CompoundAssignOperator *E) {
   6138   return getDerived().TransformBinaryOperator(E);
   6139 }
   6140 
   6141 template<typename Derived>
   6142 ExprResult TreeTransform<Derived>::
   6143 TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
   6144   // Just rebuild the common and RHS expressions and see whether we
   6145   // get any changes.
   6146 
   6147   ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
   6148   if (commonExpr.isInvalid())
   6149     return ExprError();
   6150 
   6151   ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
   6152   if (rhs.isInvalid())
   6153     return ExprError();
   6154 
   6155   if (!getDerived().AlwaysRebuild() &&
   6156       commonExpr.get() == e->getCommon() &&
   6157       rhs.get() == e->getFalseExpr())
   6158     return SemaRef.Owned(e);
   6159 
   6160   return getDerived().RebuildConditionalOperator(commonExpr.take(),
   6161                                                  e->getQuestionLoc(),
   6162                                                  0,
   6163                                                  e->getColonLoc(),
   6164                                                  rhs.get());
   6165 }
   6166 
   6167 template<typename Derived>
   6168 ExprResult
   6169 TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
   6170   ExprResult Cond = getDerived().TransformExpr(E->getCond());
   6171   if (Cond.isInvalid())
   6172     return ExprError();
   6173 
   6174   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   6175   if (LHS.isInvalid())
   6176     return ExprError();
   6177 
   6178   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   6179   if (RHS.isInvalid())
   6180     return ExprError();
   6181 
   6182   if (!getDerived().AlwaysRebuild() &&
   6183       Cond.get() == E->getCond() &&
   6184       LHS.get() == E->getLHS() &&
   6185       RHS.get() == E->getRHS())
   6186     return SemaRef.Owned(E);
   6187 
   6188   return getDerived().RebuildConditionalOperator(Cond.get(),
   6189                                                  E->getQuestionLoc(),
   6190                                                  LHS.get(),
   6191                                                  E->getColonLoc(),
   6192                                                  RHS.get());
   6193 }
   6194 
   6195 template<typename Derived>
   6196 ExprResult
   6197 TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
   6198   // Implicit casts are eliminated during transformation, since they
   6199   // will be recomputed by semantic analysis after transformation.
   6200   return getDerived().TransformExpr(E->getSubExprAsWritten());
   6201 }
   6202 
   6203 template<typename Derived>
   6204 ExprResult
   6205 TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
   6206   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
   6207   if (!Type)
   6208     return ExprError();
   6209 
   6210   ExprResult SubExpr
   6211     = getDerived().TransformExpr(E->getSubExprAsWritten());
   6212   if (SubExpr.isInvalid())
   6213     return ExprError();
   6214 
   6215   if (!getDerived().AlwaysRebuild() &&
   6216       Type == E->getTypeInfoAsWritten() &&
   6217       SubExpr.get() == E->getSubExpr())
   6218     return SemaRef.Owned(E);
   6219 
   6220   return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
   6221                                             Type,
   6222                                             E->getRParenLoc(),
   6223                                             SubExpr.get());
   6224 }
   6225 
   6226 template<typename Derived>
   6227 ExprResult
   6228 TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
   6229   TypeSourceInfo *OldT = E->getTypeSourceInfo();
   6230   TypeSourceInfo *NewT = getDerived().TransformType(OldT);
   6231   if (!NewT)
   6232     return ExprError();
   6233 
   6234   ExprResult Init = getDerived().TransformExpr(E->getInitializer());
   6235   if (Init.isInvalid())
   6236     return ExprError();
   6237 
   6238   if (!getDerived().AlwaysRebuild() &&
   6239       OldT == NewT &&
   6240       Init.get() == E->getInitializer())
   6241     return SemaRef.Owned(E);
   6242 
   6243   // Note: the expression type doesn't necessarily match the
   6244   // type-as-written, but that's okay, because it should always be
   6245   // derivable from the initializer.
   6246 
   6247   return getDerived().RebuildCompoundLiteralExpr(E->getLParenLoc(), NewT,
   6248                                    /*FIXME:*/E->getInitializer()->getLocEnd(),
   6249                                                  Init.get());
   6250 }
   6251 
   6252 template<typename Derived>
   6253 ExprResult
   6254 TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
   6255   ExprResult Base = getDerived().TransformExpr(E->getBase());
   6256   if (Base.isInvalid())
   6257     return ExprError();
   6258 
   6259   if (!getDerived().AlwaysRebuild() &&
   6260       Base.get() == E->getBase())
   6261     return SemaRef.Owned(E);
   6262 
   6263   // FIXME: Bad source location
   6264   SourceLocation FakeOperatorLoc
   6265     = SemaRef.PP.getLocForEndOfToken(E->getBase()->getLocEnd());
   6266   return getDerived().RebuildExtVectorElementExpr(Base.get(), FakeOperatorLoc,
   6267                                                   E->getAccessorLoc(),
   6268                                                   E->getAccessor());
   6269 }
   6270 
   6271 template<typename Derived>
   6272 ExprResult
   6273 TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
   6274   bool InitChanged = false;
   6275 
   6276   ASTOwningVector<Expr*, 4> Inits(SemaRef);
   6277   if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
   6278                                   Inits, &InitChanged))
   6279     return ExprError();
   6280 
   6281   if (!getDerived().AlwaysRebuild() && !InitChanged)
   6282     return SemaRef.Owned(E);
   6283 
   6284   return getDerived().RebuildInitList(E->getLBraceLoc(), move_arg(Inits),
   6285                                       E->getRBraceLoc(), E->getType());
   6286 }
   6287 
   6288 template<typename Derived>
   6289 ExprResult
   6290 TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
   6291   Designation Desig;
   6292 
   6293   // transform the initializer value
   6294   ExprResult Init = getDerived().TransformExpr(E->getInit());
   6295   if (Init.isInvalid())
   6296     return ExprError();
   6297 
   6298   // transform the designators.
   6299   ASTOwningVector<Expr*, 4> ArrayExprs(SemaRef);
   6300   bool ExprChanged = false;
   6301   for (DesignatedInitExpr::designators_iterator D = E->designators_begin(),
   6302                                              DEnd = E->designators_end();
   6303        D != DEnd; ++D) {
   6304     if (D->isFieldDesignator()) {
   6305       Desig.AddDesignator(Designator::getField(D->getFieldName(),
   6306                                                D->getDotLoc(),
   6307                                                D->getFieldLoc()));
   6308       continue;
   6309     }
   6310 
   6311     if (D->isArrayDesignator()) {
   6312       ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(*D));
   6313       if (Index.isInvalid())
   6314         return ExprError();
   6315 
   6316       Desig.AddDesignator(Designator::getArray(Index.get(),
   6317                                                D->getLBracketLoc()));
   6318 
   6319       ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(*D);
   6320       ArrayExprs.push_back(Index.release());
   6321       continue;
   6322     }
   6323 
   6324     assert(D->isArrayRangeDesignator() && "New kind of designator?");
   6325     ExprResult Start
   6326       = getDerived().TransformExpr(E->getArrayRangeStart(*D));
   6327     if (Start.isInvalid())
   6328       return ExprError();
   6329 
   6330     ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(*D));
   6331     if (End.isInvalid())
   6332       return ExprError();
   6333 
   6334     Desig.AddDesignator(Designator::getArrayRange(Start.get(),
   6335                                                   End.get(),
   6336                                                   D->getLBracketLoc(),
   6337                                                   D->getEllipsisLoc()));
   6338 
   6339     ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(*D) ||
   6340       End.get() != E->getArrayRangeEnd(*D);
   6341 
   6342     ArrayExprs.push_back(Start.release());
   6343     ArrayExprs.push_back(End.release());
   6344   }
   6345 
   6346   if (!getDerived().AlwaysRebuild() &&
   6347       Init.get() == E->getInit() &&
   6348       !ExprChanged)
   6349     return SemaRef.Owned(E);
   6350 
   6351   return getDerived().RebuildDesignatedInitExpr(Desig, move_arg(ArrayExprs),
   6352                                                 E->getEqualOrColonLoc(),
   6353                                                 E->usesGNUSyntax(), Init.get());
   6354 }
   6355 
   6356 template<typename Derived>
   6357 ExprResult
   6358 TreeTransform<Derived>::TransformImplicitValueInitExpr(
   6359                                                      ImplicitValueInitExpr *E) {
   6360   TemporaryBase Rebase(*this, E->getLocStart(), DeclarationName());
   6361 
   6362   // FIXME: Will we ever have proper type location here? Will we actually
   6363   // need to transform the type?
   6364   QualType T = getDerived().TransformType(E->getType());
   6365   if (T.isNull())
   6366     return ExprError();
   6367 
   6368   if (!getDerived().AlwaysRebuild() &&
   6369       T == E->getType())
   6370     return SemaRef.Owned(E);
   6371 
   6372   return getDerived().RebuildImplicitValueInitExpr(T);
   6373 }
   6374 
   6375 template<typename Derived>
   6376 ExprResult
   6377 TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
   6378   TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
   6379   if (!TInfo)
   6380     return ExprError();
   6381 
   6382   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   6383   if (SubExpr.isInvalid())
   6384     return ExprError();
   6385 
   6386   if (!getDerived().AlwaysRebuild() &&
   6387       TInfo == E->getWrittenTypeInfo() &&
   6388       SubExpr.get() == E->getSubExpr())
   6389     return SemaRef.Owned(E);
   6390 
   6391   return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
   6392                                        TInfo, E->getRParenLoc());
   6393 }
   6394 
   6395 template<typename Derived>
   6396 ExprResult
   6397 TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
   6398   bool ArgumentChanged = false;
   6399   ASTOwningVector<Expr*, 4> Inits(SemaRef);
   6400   if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
   6401                      &ArgumentChanged))
   6402     return ExprError();
   6403 
   6404   return getDerived().RebuildParenListExpr(E->getLParenLoc(),
   6405                                            move_arg(Inits),
   6406                                            E->getRParenLoc());
   6407 }
   6408 
   6409 /// \brief Transform an address-of-label expression.
   6410 ///
   6411 /// By default, the transformation of an address-of-label expression always
   6412 /// rebuilds the expression, so that the label identifier can be resolved to
   6413 /// the corresponding label statement by semantic analysis.
   6414 template<typename Derived>
   6415 ExprResult
   6416 TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
   6417   Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
   6418                                         E->getLabel());
   6419   if (!LD)
   6420     return ExprError();
   6421 
   6422   return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
   6423                                            cast<LabelDecl>(LD));
   6424 }
   6425 
   6426 template<typename Derived>
   6427 ExprResult
   6428 TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
   6429   StmtResult SubStmt
   6430     = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
   6431   if (SubStmt.isInvalid())
   6432     return ExprError();
   6433 
   6434   if (!getDerived().AlwaysRebuild() &&
   6435       SubStmt.get() == E->getSubStmt())
   6436     return SemaRef.Owned(E);
   6437 
   6438   return getDerived().RebuildStmtExpr(E->getLParenLoc(),
   6439                                       SubStmt.get(),
   6440                                       E->getRParenLoc());
   6441 }
   6442 
   6443 template<typename Derived>
   6444 ExprResult
   6445 TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
   6446   ExprResult Cond = getDerived().TransformExpr(E->getCond());
   6447   if (Cond.isInvalid())
   6448     return ExprError();
   6449 
   6450   ExprResult LHS = getDerived().TransformExpr(E->getLHS());
   6451   if (LHS.isInvalid())
   6452     return ExprError();
   6453 
   6454   ExprResult RHS = getDerived().TransformExpr(E->getRHS());
   6455   if (RHS.isInvalid())
   6456     return ExprError();
   6457 
   6458   if (!getDerived().AlwaysRebuild() &&
   6459       Cond.get() == E->getCond() &&
   6460       LHS.get() == E->getLHS() &&
   6461       RHS.get() == E->getRHS())
   6462     return SemaRef.Owned(E);
   6463 
   6464   return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
   6465                                         Cond.get(), LHS.get(), RHS.get(),
   6466                                         E->getRParenLoc());
   6467 }
   6468 
   6469 template<typename Derived>
   6470 ExprResult
   6471 TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
   6472   return SemaRef.Owned(E);
   6473 }
   6474 
   6475 template<typename Derived>
   6476 ExprResult
   6477 TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
   6478   switch (E->getOperator()) {
   6479   case OO_New:
   6480   case OO_Delete:
   6481   case OO_Array_New:
   6482   case OO_Array_Delete:
   6483     llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr");
   6484     return ExprError();
   6485 
   6486   case OO_Call: {
   6487     // This is a call to an object's operator().
   6488     assert(E->getNumArgs() >= 1 && "Object call is missing arguments");
   6489 
   6490     // Transform the object itself.
   6491     ExprResult Object = getDerived().TransformExpr(E->getArg(0));
   6492     if (Object.isInvalid())
   6493       return ExprError();
   6494 
   6495     // FIXME: Poor location information
   6496     SourceLocation FakeLParenLoc
   6497       = SemaRef.PP.getLocForEndOfToken(
   6498                               static_cast<Expr *>(Object.get())->getLocEnd());
   6499 
   6500     // Transform the call arguments.
   6501     ASTOwningVector<Expr*> Args(SemaRef);
   6502     if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
   6503                                     Args))
   6504       return ExprError();
   6505 
   6506     return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc,
   6507                                         move_arg(Args),
   6508                                         E->getLocEnd());
   6509   }
   6510 
   6511 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
   6512   case OO_##Name:
   6513 #define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
   6514 #include "clang/Basic/OperatorKinds.def"
   6515   case OO_Subscript:
   6516     // Handled below.
   6517     break;
   6518 
   6519   case OO_Conditional:
   6520     llvm_unreachable("conditional operator is not actually overloadable");
   6521     return ExprError();
   6522 
   6523   case OO_None:
   6524   case NUM_OVERLOADED_OPERATORS:
   6525     llvm_unreachable("not an overloaded operator?");
   6526     return ExprError();
   6527   }
   6528 
   6529   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
   6530   if (Callee.isInvalid())
   6531     return ExprError();
   6532 
   6533   ExprResult First = getDerived().TransformExpr(E->getArg(0));
   6534   if (First.isInvalid())
   6535     return ExprError();
   6536 
   6537   ExprResult Second;
   6538   if (E->getNumArgs() == 2) {
   6539     Second = getDerived().TransformExpr(E->getArg(1));
   6540     if (Second.isInvalid())
   6541       return ExprError();
   6542   }
   6543 
   6544   if (!getDerived().AlwaysRebuild() &&
   6545       Callee.get() == E->getCallee() &&
   6546       First.get() == E->getArg(0) &&
   6547       (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
   6548     return SemaRef.Owned(E);
   6549 
   6550   return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
   6551                                                  E->getOperatorLoc(),
   6552                                                  Callee.get(),
   6553                                                  First.get(),
   6554                                                  Second.get());
   6555 }
   6556 
   6557 template<typename Derived>
   6558 ExprResult
   6559 TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
   6560   return getDerived().TransformCallExpr(E);
   6561 }
   6562 
   6563 template<typename Derived>
   6564 ExprResult
   6565 TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
   6566   // Transform the callee.
   6567   ExprResult Callee = getDerived().TransformExpr(E->getCallee());
   6568   if (Callee.isInvalid())
   6569     return ExprError();
   6570 
   6571   // Transform exec config.
   6572   ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
   6573   if (EC.isInvalid())
   6574     return ExprError();
   6575 
   6576   // Transform arguments.
   6577   bool ArgChanged = false;
   6578   ASTOwningVector<Expr*> Args(SemaRef);
   6579   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   6580                                   &ArgChanged))
   6581     return ExprError();
   6582 
   6583   if (!getDerived().AlwaysRebuild() &&
   6584       Callee.get() == E->getCallee() &&
   6585       !ArgChanged)
   6586     return SemaRef.Owned(E);
   6587 
   6588   // FIXME: Wrong source location information for the '('.
   6589   SourceLocation FakeLParenLoc
   6590     = ((Expr *)Callee.get())->getSourceRange().getBegin();
   6591   return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
   6592                                       move_arg(Args),
   6593                                       E->getRParenLoc(), EC.get());
   6594 }
   6595 
   6596 template<typename Derived>
   6597 ExprResult
   6598 TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
   6599   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
   6600   if (!Type)
   6601     return ExprError();
   6602 
   6603   ExprResult SubExpr
   6604     = getDerived().TransformExpr(E->getSubExprAsWritten());
   6605   if (SubExpr.isInvalid())
   6606     return ExprError();
   6607 
   6608   if (!getDerived().AlwaysRebuild() &&
   6609       Type == E->getTypeInfoAsWritten() &&
   6610       SubExpr.get() == E->getSubExpr())
   6611     return SemaRef.Owned(E);
   6612 
   6613   // FIXME: Poor source location information here.
   6614   SourceLocation FakeLAngleLoc
   6615     = SemaRef.PP.getLocForEndOfToken(E->getOperatorLoc());
   6616   SourceLocation FakeRAngleLoc = E->getSubExpr()->getSourceRange().getBegin();
   6617   SourceLocation FakeRParenLoc
   6618     = SemaRef.PP.getLocForEndOfToken(
   6619                                   E->getSubExpr()->getSourceRange().getEnd());
   6620   return getDerived().RebuildCXXNamedCastExpr(E->getOperatorLoc(),
   6621                                               E->getStmtClass(),
   6622                                               FakeLAngleLoc,
   6623                                               Type,
   6624                                               FakeRAngleLoc,
   6625                                               FakeRAngleLoc,
   6626                                               SubExpr.get(),
   6627                                               FakeRParenLoc);
   6628 }
   6629 
   6630 template<typename Derived>
   6631 ExprResult
   6632 TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
   6633   return getDerived().TransformCXXNamedCastExpr(E);
   6634 }
   6635 
   6636 template<typename Derived>
   6637 ExprResult
   6638 TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
   6639   return getDerived().TransformCXXNamedCastExpr(E);
   6640 }
   6641 
   6642 template<typename Derived>
   6643 ExprResult
   6644 TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
   6645                                                       CXXReinterpretCastExpr *E) {
   6646   return getDerived().TransformCXXNamedCastExpr(E);
   6647 }
   6648 
   6649 template<typename Derived>
   6650 ExprResult
   6651 TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
   6652   return getDerived().TransformCXXNamedCastExpr(E);
   6653 }
   6654 
   6655 template<typename Derived>
   6656 ExprResult
   6657 TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
   6658                                                      CXXFunctionalCastExpr *E) {
   6659   TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
   6660   if (!Type)
   6661     return ExprError();
   6662 
   6663   ExprResult SubExpr
   6664     = getDerived().TransformExpr(E->getSubExprAsWritten());
   6665   if (SubExpr.isInvalid())
   6666     return ExprError();
   6667 
   6668   if (!getDerived().AlwaysRebuild() &&
   6669       Type == E->getTypeInfoAsWritten() &&
   6670       SubExpr.get() == E->getSubExpr())
   6671     return SemaRef.Owned(E);
   6672 
   6673   return getDerived().RebuildCXXFunctionalCastExpr(Type,
   6674                                       /*FIXME:*/E->getSubExpr()->getLocStart(),
   6675                                                    SubExpr.get(),
   6676                                                    E->getRParenLoc());
   6677 }
   6678 
   6679 template<typename Derived>
   6680 ExprResult
   6681 TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
   6682   if (E->isTypeOperand()) {
   6683     TypeSourceInfo *TInfo
   6684       = getDerived().TransformType(E->getTypeOperandSourceInfo());
   6685     if (!TInfo)
   6686       return ExprError();
   6687 
   6688     if (!getDerived().AlwaysRebuild() &&
   6689         TInfo == E->getTypeOperandSourceInfo())
   6690       return SemaRef.Owned(E);
   6691 
   6692     return getDerived().RebuildCXXTypeidExpr(E->getType(),
   6693                                              E->getLocStart(),
   6694                                              TInfo,
   6695                                              E->getLocEnd());
   6696   }
   6697 
   6698   // We don't know whether the expression is potentially evaluated until
   6699   // after we perform semantic analysis, so the expression is potentially
   6700   // potentially evaluated.
   6701   EnterExpressionEvaluationContext Unevaluated(SemaRef,
   6702                                       Sema::PotentiallyPotentiallyEvaluated);
   6703 
   6704   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
   6705   if (SubExpr.isInvalid())
   6706     return ExprError();
   6707 
   6708   if (!getDerived().AlwaysRebuild() &&
   6709       SubExpr.get() == E->getExprOperand())
   6710     return SemaRef.Owned(E);
   6711 
   6712   return getDerived().RebuildCXXTypeidExpr(E->getType(),
   6713                                            E->getLocStart(),
   6714                                            SubExpr.get(),
   6715                                            E->getLocEnd());
   6716 }
   6717 
   6718 template<typename Derived>
   6719 ExprResult
   6720 TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
   6721   if (E->isTypeOperand()) {
   6722     TypeSourceInfo *TInfo
   6723       = getDerived().TransformType(E->getTypeOperandSourceInfo());
   6724     if (!TInfo)
   6725       return ExprError();
   6726 
   6727     if (!getDerived().AlwaysRebuild() &&
   6728         TInfo == E->getTypeOperandSourceInfo())
   6729       return SemaRef.Owned(E);
   6730 
   6731     return getDerived().RebuildCXXUuidofExpr(E->getType(),
   6732                                              E->getLocStart(),
   6733                                              TInfo,
   6734                                              E->getLocEnd());
   6735   }
   6736 
   6737   // We don't know whether the expression is potentially evaluated until
   6738   // after we perform semantic analysis, so the expression is potentially
   6739   // potentially evaluated.
   6740   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   6741 
   6742   ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
   6743   if (SubExpr.isInvalid())
   6744     return ExprError();
   6745 
   6746   if (!getDerived().AlwaysRebuild() &&
   6747       SubExpr.get() == E->getExprOperand())
   6748     return SemaRef.Owned(E);
   6749 
   6750   return getDerived().RebuildCXXUuidofExpr(E->getType(),
   6751                                            E->getLocStart(),
   6752                                            SubExpr.get(),
   6753                                            E->getLocEnd());
   6754 }
   6755 
   6756 template<typename Derived>
   6757 ExprResult
   6758 TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
   6759   return SemaRef.Owned(E);
   6760 }
   6761 
   6762 template<typename Derived>
   6763 ExprResult
   6764 TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
   6765                                                      CXXNullPtrLiteralExpr *E) {
   6766   return SemaRef.Owned(E);
   6767 }
   6768 
   6769 template<typename Derived>
   6770 ExprResult
   6771 TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
   6772   DeclContext *DC = getSema().getFunctionLevelDeclContext();
   6773   QualType T;
   6774   if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
   6775     T = MD->getThisType(getSema().Context);
   6776   else
   6777     T = getSema().Context.getPointerType(
   6778       getSema().Context.getRecordType(cast<CXXRecordDecl>(DC)));
   6779 
   6780   if (!getDerived().AlwaysRebuild() && T == E->getType())
   6781     return SemaRef.Owned(E);
   6782 
   6783   return getDerived().RebuildCXXThisExpr(E->getLocStart(), T, E->isImplicit());
   6784 }
   6785 
   6786 template<typename Derived>
   6787 ExprResult
   6788 TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
   6789   ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
   6790   if (SubExpr.isInvalid())
   6791     return ExprError();
   6792 
   6793   if (!getDerived().AlwaysRebuild() &&
   6794       SubExpr.get() == E->getSubExpr())
   6795     return SemaRef.Owned(E);
   6796 
   6797   return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
   6798                                           E->isThrownVariableInScope());
   6799 }
   6800 
   6801 template<typename Derived>
   6802 ExprResult
   6803 TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
   6804   ParmVarDecl *Param
   6805     = cast_or_null<ParmVarDecl>(getDerived().TransformDecl(E->getLocStart(),
   6806                                                            E->getParam()));
   6807   if (!Param)
   6808     return ExprError();
   6809 
   6810   if (!getDerived().AlwaysRebuild() &&
   6811       Param == E->getParam())
   6812     return SemaRef.Owned(E);
   6813 
   6814   return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param);
   6815 }
   6816 
   6817 template<typename Derived>
   6818 ExprResult
   6819 TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
   6820                                                     CXXScalarValueInitExpr *E) {
   6821   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
   6822   if (!T)
   6823     return ExprError();
   6824 
   6825   if (!getDerived().AlwaysRebuild() &&
   6826       T == E->getTypeSourceInfo())
   6827     return SemaRef.Owned(E);
   6828 
   6829   return getDerived().RebuildCXXScalarValueInitExpr(T,
   6830                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
   6831                                                     E->getRParenLoc());
   6832 }
   6833 
   6834 template<typename Derived>
   6835 ExprResult
   6836 TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
   6837   // Transform the type that we're allocating
   6838   TypeSourceInfo *AllocTypeInfo
   6839     = getDerived().TransformType(E->getAllocatedTypeSourceInfo());
   6840   if (!AllocTypeInfo)
   6841     return ExprError();
   6842 
   6843   // Transform the size of the array we're allocating (if any).
   6844   ExprResult ArraySize = getDerived().TransformExpr(E->getArraySize());
   6845   if (ArraySize.isInvalid())
   6846     return ExprError();
   6847 
   6848   // Transform the placement arguments (if any).
   6849   bool ArgumentChanged = false;
   6850   ASTOwningVector<Expr*> PlacementArgs(SemaRef);
   6851   if (getDerived().TransformExprs(E->getPlacementArgs(),
   6852                                   E->getNumPlacementArgs(), true,
   6853                                   PlacementArgs, &ArgumentChanged))
   6854     return ExprError();
   6855 
   6856   // transform the constructor arguments (if any).
   6857   ASTOwningVector<Expr*> ConstructorArgs(SemaRef);
   6858   if (TransformExprs(E->getConstructorArgs(), E->getNumConstructorArgs(), true,
   6859                      ConstructorArgs, &ArgumentChanged))
   6860     return ExprError();
   6861 
   6862   // Transform constructor, new operator, and delete operator.
   6863   CXXConstructorDecl *Constructor = 0;
   6864   if (E->getConstructor()) {
   6865     Constructor = cast_or_null<CXXConstructorDecl>(
   6866                                    getDerived().TransformDecl(E->getLocStart(),
   6867                                                          E->getConstructor()));
   6868     if (!Constructor)
   6869       return ExprError();
   6870   }
   6871 
   6872   FunctionDecl *OperatorNew = 0;
   6873   if (E->getOperatorNew()) {
   6874     OperatorNew = cast_or_null<FunctionDecl>(
   6875                                  getDerived().TransformDecl(E->getLocStart(),
   6876                                                          E->getOperatorNew()));
   6877     if (!OperatorNew)
   6878       return ExprError();
   6879   }
   6880 
   6881   FunctionDecl *OperatorDelete = 0;
   6882   if (E->getOperatorDelete()) {
   6883     OperatorDelete = cast_or_null<FunctionDecl>(
   6884                                    getDerived().TransformDecl(E->getLocStart(),
   6885                                                        E->getOperatorDelete()));
   6886     if (!OperatorDelete)
   6887       return ExprError();
   6888   }
   6889 
   6890   if (!getDerived().AlwaysRebuild() &&
   6891       AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
   6892       ArraySize.get() == E->getArraySize() &&
   6893       Constructor == E->getConstructor() &&
   6894       OperatorNew == E->getOperatorNew() &&
   6895       OperatorDelete == E->getOperatorDelete() &&
   6896       !ArgumentChanged) {
   6897     // Mark any declarations we need as referenced.
   6898     // FIXME: instantiation-specific.
   6899     if (Constructor)
   6900       SemaRef.MarkDeclarationReferenced(E->getLocStart(), Constructor);
   6901     if (OperatorNew)
   6902       SemaRef.MarkDeclarationReferenced(E->getLocStart(), OperatorNew);
   6903     if (OperatorDelete)
   6904       SemaRef.MarkDeclarationReferenced(E->getLocStart(), OperatorDelete);
   6905     return SemaRef.Owned(E);
   6906   }
   6907 
   6908   QualType AllocType = AllocTypeInfo->getType();
   6909   if (!ArraySize.get()) {
   6910     // If no array size was specified, but the new expression was
   6911     // instantiated with an array type (e.g., "new T" where T is
   6912     // instantiated with "int[4]"), extract the outer bound from the
   6913     // array type as our array size. We do this with constant and
   6914     // dependently-sized array types.
   6915     const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
   6916     if (!ArrayT) {
   6917       // Do nothing
   6918     } else if (const ConstantArrayType *ConsArrayT
   6919                                      = dyn_cast<ConstantArrayType>(ArrayT)) {
   6920       ArraySize
   6921         = SemaRef.Owned(IntegerLiteral::Create(SemaRef.Context,
   6922                                                ConsArrayT->getSize(),
   6923                                                SemaRef.Context.getSizeType(),
   6924                                                /*FIXME:*/E->getLocStart()));
   6925       AllocType = ConsArrayT->getElementType();
   6926     } else if (const DependentSizedArrayType *DepArrayT
   6927                               = dyn_cast<DependentSizedArrayType>(ArrayT)) {
   6928       if (DepArrayT->getSizeExpr()) {
   6929         ArraySize = SemaRef.Owned(DepArrayT->getSizeExpr());
   6930         AllocType = DepArrayT->getElementType();
   6931       }
   6932     }
   6933   }
   6934 
   6935   return getDerived().RebuildCXXNewExpr(E->getLocStart(),
   6936                                         E->isGlobalNew(),
   6937                                         /*FIXME:*/E->getLocStart(),
   6938                                         move_arg(PlacementArgs),
   6939                                         /*FIXME:*/E->getLocStart(),
   6940                                         E->getTypeIdParens(),
   6941                                         AllocType,
   6942                                         AllocTypeInfo,
   6943                                         ArraySize.get(),
   6944                                         /*FIXME:*/E->hasInitializer()
   6945                                           ? E->getLocStart()
   6946                                           : SourceLocation(),
   6947                                         move_arg(ConstructorArgs),
   6948                                         /*FIXME:*/E->hasInitializer()
   6949                                           ? E->getLocEnd()
   6950                                           : SourceLocation());
   6951 }
   6952 
   6953 template<typename Derived>
   6954 ExprResult
   6955 TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
   6956   ExprResult Operand = getDerived().TransformExpr(E->getArgument());
   6957   if (Operand.isInvalid())
   6958     return ExprError();
   6959 
   6960   // Transform the delete operator, if known.
   6961   FunctionDecl *OperatorDelete = 0;
   6962   if (E->getOperatorDelete()) {
   6963     OperatorDelete = cast_or_null<FunctionDecl>(
   6964                                    getDerived().TransformDecl(E->getLocStart(),
   6965                                                        E->getOperatorDelete()));
   6966     if (!OperatorDelete)
   6967       return ExprError();
   6968   }
   6969 
   6970   if (!getDerived().AlwaysRebuild() &&
   6971       Operand.get() == E->getArgument() &&
   6972       OperatorDelete == E->getOperatorDelete()) {
   6973     // Mark any declarations we need as referenced.
   6974     // FIXME: instantiation-specific.
   6975     if (OperatorDelete)
   6976       SemaRef.MarkDeclarationReferenced(E->getLocStart(), OperatorDelete);
   6977 
   6978     if (!E->getArgument()->isTypeDependent()) {
   6979       QualType Destroyed = SemaRef.Context.getBaseElementType(
   6980                                                          E->getDestroyedType());
   6981       if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
   6982         CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
   6983         SemaRef.MarkDeclarationReferenced(E->getLocStart(),
   6984                                           SemaRef.LookupDestructor(Record));
   6985       }
   6986     }
   6987 
   6988     return SemaRef.Owned(E);
   6989   }
   6990 
   6991   return getDerived().RebuildCXXDeleteExpr(E->getLocStart(),
   6992                                            E->isGlobalDelete(),
   6993                                            E->isArrayForm(),
   6994                                            Operand.get());
   6995 }
   6996 
   6997 template<typename Derived>
   6998 ExprResult
   6999 TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
   7000                                                      CXXPseudoDestructorExpr *E) {
   7001   ExprResult Base = getDerived().TransformExpr(E->getBase());
   7002   if (Base.isInvalid())
   7003     return ExprError();
   7004 
   7005   ParsedType ObjectTypePtr;
   7006   bool MayBePseudoDestructor = false;
   7007   Base = SemaRef.ActOnStartCXXMemberReference(0, Base.get(),
   7008                                               E->getOperatorLoc(),
   7009                                         E->isArrow()? tok::arrow : tok::period,
   7010                                               ObjectTypePtr,
   7011                                               MayBePseudoDestructor);
   7012   if (Base.isInvalid())
   7013     return ExprError();
   7014 
   7015   QualType ObjectType = ObjectTypePtr.get();
   7016   NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
   7017   if (QualifierLoc) {
   7018     QualifierLoc
   7019       = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
   7020     if (!QualifierLoc)
   7021       return ExprError();
   7022   }
   7023   CXXScopeSpec SS;
   7024   SS.Adopt(QualifierLoc);
   7025 
   7026   PseudoDestructorTypeStorage Destroyed;
   7027   if (E->getDestroyedTypeInfo()) {
   7028     TypeSourceInfo *DestroyedTypeInfo
   7029       = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
   7030                                                 ObjectType, 0, SS);
   7031     if (!DestroyedTypeInfo)
   7032       return ExprError();
   7033     Destroyed = DestroyedTypeInfo;
   7034   } else if (ObjectType->isDependentType()) {
   7035     // We aren't likely to be able to resolve the identifier down to a type
   7036     // now anyway, so just retain the identifier.
   7037     Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
   7038                                             E->getDestroyedTypeLoc());
   7039   } else {
   7040     // Look for a destructor known with the given name.
   7041     ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
   7042                                               *E->getDestroyedTypeIdentifier(),
   7043                                                 E->getDestroyedTypeLoc(),
   7044                                                 /*Scope=*/0,
   7045                                                 SS, ObjectTypePtr,
   7046                                                 false);
   7047     if (!T)
   7048       return ExprError();
   7049 
   7050     Destroyed
   7051       = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
   7052                                                  E->getDestroyedTypeLoc());
   7053   }
   7054 
   7055   TypeSourceInfo *ScopeTypeInfo = 0;
   7056   if (E->getScopeTypeInfo()) {
   7057     ScopeTypeInfo = getDerived().TransformType(E->getScopeTypeInfo());
   7058     if (!ScopeTypeInfo)
   7059       return ExprError();
   7060   }
   7061 
   7062   return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
   7063                                                      E->getOperatorLoc(),
   7064                                                      E->isArrow(),
   7065                                                      SS,
   7066                                                      ScopeTypeInfo,
   7067                                                      E->getColonColonLoc(),
   7068                                                      E->getTildeLoc(),
   7069                                                      Destroyed);
   7070 }
   7071 
   7072 template<typename Derived>
   7073 ExprResult
   7074 TreeTransform<Derived>::TransformUnresolvedLookupExpr(
   7075                                                   UnresolvedLookupExpr *Old) {
   7076   LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
   7077                  Sema::LookupOrdinaryName);
   7078 
   7079   // Transform all the decls.
   7080   for (UnresolvedLookupExpr::decls_iterator I = Old->decls_begin(),
   7081          E = Old->decls_end(); I != E; ++I) {
   7082     NamedDecl *InstD = static_cast<NamedDecl*>(
   7083                                  getDerived().TransformDecl(Old->getNameLoc(),
   7084                                                             *I));
   7085     if (!InstD) {
   7086       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
   7087       // This can happen because of dependent hiding.
   7088       if (isa<UsingShadowDecl>(*I))
   7089         continue;
   7090       else
   7091         return ExprError();
   7092     }
   7093 
   7094     // Expand using declarations.
   7095     if (isa<UsingDecl>(InstD)) {
   7096       UsingDecl *UD = cast<UsingDecl>(InstD);
   7097       for (UsingDecl::shadow_iterator I = UD->shadow_begin(),
   7098              E = UD->shadow_end(); I != E; ++I)
   7099         R.addDecl(*I);
   7100       continue;
   7101     }
   7102 
   7103     R.addDecl(InstD);
   7104   }
   7105 
   7106   // Resolve a kind, but don't do any further analysis.  If it's
   7107   // ambiguous, the callee needs to deal with it.
   7108   R.resolveKind();
   7109 
   7110   // Rebuild the nested-name qualifier, if present.
   7111   CXXScopeSpec SS;
   7112   if (Old->getQualifierLoc()) {
   7113     NestedNameSpecifierLoc QualifierLoc
   7114       = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
   7115     if (!QualifierLoc)
   7116       return ExprError();
   7117 
   7118     SS.Adopt(QualifierLoc);
   7119   }
   7120 
   7121   if (Old->getNamingClass()) {
   7122     CXXRecordDecl *NamingClass
   7123       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
   7124                                                             Old->getNameLoc(),
   7125                                                         Old->getNamingClass()));
   7126     if (!NamingClass)
   7127       return ExprError();
   7128 
   7129     R.setNamingClass(NamingClass);
   7130   }
   7131 
   7132   // If we have no template arguments, it's a normal declaration name.
   7133   if (!Old->hasExplicitTemplateArgs())
   7134     return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
   7135 
   7136   // If we have template arguments, rebuild them, then rebuild the
   7137   // templateid expression.
   7138   TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
   7139   if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
   7140                                               Old->getNumTemplateArgs(),
   7141                                               TransArgs))
   7142     return ExprError();
   7143 
   7144   return getDerived().RebuildTemplateIdExpr(SS, R, Old->requiresADL(),
   7145                                             TransArgs);
   7146 }
   7147 
   7148 template<typename Derived>
   7149 ExprResult
   7150 TreeTransform<Derived>::TransformUnaryTypeTraitExpr(UnaryTypeTraitExpr *E) {
   7151   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
   7152   if (!T)
   7153     return ExprError();
   7154 
   7155   if (!getDerived().AlwaysRebuild() &&
   7156       T == E->getQueriedTypeSourceInfo())
   7157     return SemaRef.Owned(E);
   7158 
   7159   return getDerived().RebuildUnaryTypeTrait(E->getTrait(),
   7160                                             E->getLocStart(),
   7161                                             T,
   7162                                             E->getLocEnd());
   7163 }
   7164 
   7165 template<typename Derived>
   7166 ExprResult
   7167 TreeTransform<Derived>::TransformBinaryTypeTraitExpr(BinaryTypeTraitExpr *E) {
   7168   TypeSourceInfo *LhsT = getDerived().TransformType(E->getLhsTypeSourceInfo());
   7169   if (!LhsT)
   7170     return ExprError();
   7171 
   7172   TypeSourceInfo *RhsT = getDerived().TransformType(E->getRhsTypeSourceInfo());
   7173   if (!RhsT)
   7174     return ExprError();
   7175 
   7176   if (!getDerived().AlwaysRebuild() &&
   7177       LhsT == E->getLhsTypeSourceInfo() && RhsT == E->getRhsTypeSourceInfo())
   7178     return SemaRef.Owned(E);
   7179 
   7180   return getDerived().RebuildBinaryTypeTrait(E->getTrait(),
   7181                                             E->getLocStart(),
   7182                                             LhsT, RhsT,
   7183                                             E->getLocEnd());
   7184 }
   7185 
   7186 template<typename Derived>
   7187 ExprResult
   7188 TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
   7189   TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
   7190   if (!T)
   7191     return ExprError();
   7192 
   7193   if (!getDerived().AlwaysRebuild() &&
   7194       T == E->getQueriedTypeSourceInfo())
   7195     return SemaRef.Owned(E);
   7196 
   7197   ExprResult SubExpr;
   7198   {
   7199     EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   7200     SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
   7201     if (SubExpr.isInvalid())
   7202       return ExprError();
   7203 
   7204     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
   7205       return SemaRef.Owned(E);
   7206   }
   7207 
   7208   return getDerived().RebuildArrayTypeTrait(E->getTrait(),
   7209                                             E->getLocStart(),
   7210                                             T,
   7211                                             SubExpr.get(),
   7212                                             E->getLocEnd());
   7213 }
   7214 
   7215 template<typename Derived>
   7216 ExprResult
   7217 TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
   7218   ExprResult SubExpr;
   7219   {
   7220     EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   7221     SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
   7222     if (SubExpr.isInvalid())
   7223       return ExprError();
   7224 
   7225     if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
   7226       return SemaRef.Owned(E);
   7227   }
   7228 
   7229   return getDerived().RebuildExpressionTrait(
   7230       E->getTrait(), E->getLocStart(), SubExpr.get(), E->getLocEnd());
   7231 }
   7232 
   7233 template<typename Derived>
   7234 ExprResult
   7235 TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
   7236                                                DependentScopeDeclRefExpr *E) {
   7237   NestedNameSpecifierLoc QualifierLoc
   7238   = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
   7239   if (!QualifierLoc)
   7240     return ExprError();
   7241 
   7242   // TODO: If this is a conversion-function-id, verify that the
   7243   // destination type name (if present) resolves the same way after
   7244   // instantiation as it did in the local scope.
   7245 
   7246   DeclarationNameInfo NameInfo
   7247     = getDerived().TransformDeclarationNameInfo(E->getNameInfo());
   7248   if (!NameInfo.getName())
   7249     return ExprError();
   7250 
   7251   if (!E->hasExplicitTemplateArgs()) {
   7252     if (!getDerived().AlwaysRebuild() &&
   7253         QualifierLoc == E->getQualifierLoc() &&
   7254         // Note: it is sufficient to compare the Name component of NameInfo:
   7255         // if name has not changed, DNLoc has not changed either.
   7256         NameInfo.getName() == E->getDeclName())
   7257       return SemaRef.Owned(E);
   7258 
   7259     return getDerived().RebuildDependentScopeDeclRefExpr(QualifierLoc,
   7260                                                          NameInfo,
   7261                                                          /*TemplateArgs*/ 0);
   7262   }
   7263 
   7264   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
   7265   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   7266                                               E->getNumTemplateArgs(),
   7267                                               TransArgs))
   7268     return ExprError();
   7269 
   7270   return getDerived().RebuildDependentScopeDeclRefExpr(QualifierLoc,
   7271                                                        NameInfo,
   7272                                                        &TransArgs);
   7273 }
   7274 
   7275 template<typename Derived>
   7276 ExprResult
   7277 TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
   7278   // CXXConstructExprs are always implicit, so when we have a
   7279   // 1-argument construction we just transform that argument.
   7280   if (E->getNumArgs() == 1 ||
   7281       (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1))))
   7282     return getDerived().TransformExpr(E->getArg(0));
   7283 
   7284   TemporaryBase Rebase(*this, /*FIXME*/E->getLocStart(), DeclarationName());
   7285 
   7286   QualType T = getDerived().TransformType(E->getType());
   7287   if (T.isNull())
   7288     return ExprError();
   7289 
   7290   CXXConstructorDecl *Constructor
   7291     = cast_or_null<CXXConstructorDecl>(
   7292                                 getDerived().TransformDecl(E->getLocStart(),
   7293                                                          E->getConstructor()));
   7294   if (!Constructor)
   7295     return ExprError();
   7296 
   7297   bool ArgumentChanged = false;
   7298   ASTOwningVector<Expr*> Args(SemaRef);
   7299   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   7300                                   &ArgumentChanged))
   7301     return ExprError();
   7302 
   7303   if (!getDerived().AlwaysRebuild() &&
   7304       T == E->getType() &&
   7305       Constructor == E->getConstructor() &&
   7306       !ArgumentChanged) {
   7307     // Mark the constructor as referenced.
   7308     // FIXME: Instantiation-specific
   7309     SemaRef.MarkDeclarationReferenced(E->getLocStart(), Constructor);
   7310     return SemaRef.Owned(E);
   7311   }
   7312 
   7313   return getDerived().RebuildCXXConstructExpr(T, /*FIXME:*/E->getLocStart(),
   7314                                               Constructor, E->isElidable(),
   7315                                               move_arg(Args),
   7316                                               E->requiresZeroInitialization(),
   7317                                               E->getConstructionKind(),
   7318                                               E->getParenRange());
   7319 }
   7320 
   7321 /// \brief Transform a C++ temporary-binding expression.
   7322 ///
   7323 /// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
   7324 /// transform the subexpression and return that.
   7325 template<typename Derived>
   7326 ExprResult
   7327 TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
   7328   return getDerived().TransformExpr(E->getSubExpr());
   7329 }
   7330 
   7331 /// \brief Transform a C++ expression that contains cleanups that should
   7332 /// be run after the expression is evaluated.
   7333 ///
   7334 /// Since ExprWithCleanups nodes are implicitly generated, we
   7335 /// just transform the subexpression and return that.
   7336 template<typename Derived>
   7337 ExprResult
   7338 TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
   7339   return getDerived().TransformExpr(E->getSubExpr());
   7340 }
   7341 
   7342 template<typename Derived>
   7343 ExprResult
   7344 TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
   7345                                                     CXXTemporaryObjectExpr *E) {
   7346   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
   7347   if (!T)
   7348     return ExprError();
   7349 
   7350   CXXConstructorDecl *Constructor
   7351     = cast_or_null<CXXConstructorDecl>(
   7352                                   getDerived().TransformDecl(E->getLocStart(),
   7353                                                          E->getConstructor()));
   7354   if (!Constructor)
   7355     return ExprError();
   7356 
   7357   bool ArgumentChanged = false;
   7358   ASTOwningVector<Expr*> Args(SemaRef);
   7359   Args.reserve(E->getNumArgs());
   7360   if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
   7361                      &ArgumentChanged))
   7362     return ExprError();
   7363 
   7364   if (!getDerived().AlwaysRebuild() &&
   7365       T == E->getTypeSourceInfo() &&
   7366       Constructor == E->getConstructor() &&
   7367       !ArgumentChanged) {
   7368     // FIXME: Instantiation-specific
   7369     SemaRef.MarkDeclarationReferenced(E->getLocStart(), Constructor);
   7370     return SemaRef.MaybeBindToTemporary(E);
   7371   }
   7372 
   7373   return getDerived().RebuildCXXTemporaryObjectExpr(T,
   7374                                           /*FIXME:*/T->getTypeLoc().getEndLoc(),
   7375                                                     move_arg(Args),
   7376                                                     E->getLocEnd());
   7377 }
   7378 
   7379 template<typename Derived>
   7380 ExprResult
   7381 TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
   7382                                                   CXXUnresolvedConstructExpr *E) {
   7383   TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
   7384   if (!T)
   7385     return ExprError();
   7386 
   7387   bool ArgumentChanged = false;
   7388   ASTOwningVector<Expr*> Args(SemaRef);
   7389   Args.reserve(E->arg_size());
   7390   if (getDerived().TransformExprs(E->arg_begin(), E->arg_size(), true, Args,
   7391                                   &ArgumentChanged))
   7392     return ExprError();
   7393 
   7394   if (!getDerived().AlwaysRebuild() &&
   7395       T == E->getTypeSourceInfo() &&
   7396       !ArgumentChanged)
   7397     return SemaRef.Owned(E);
   7398 
   7399   // FIXME: we're faking the locations of the commas
   7400   return getDerived().RebuildCXXUnresolvedConstructExpr(T,
   7401                                                         E->getLParenLoc(),
   7402                                                         move_arg(Args),
   7403                                                         E->getRParenLoc());
   7404 }
   7405 
   7406 template<typename Derived>
   7407 ExprResult
   7408 TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
   7409                                              CXXDependentScopeMemberExpr *E) {
   7410   // Transform the base of the expression.
   7411   ExprResult Base((Expr*) 0);
   7412   Expr *OldBase;
   7413   QualType BaseType;
   7414   QualType ObjectType;
   7415   if (!E->isImplicitAccess()) {
   7416     OldBase = E->getBase();
   7417     Base = getDerived().TransformExpr(OldBase);
   7418     if (Base.isInvalid())
   7419       return ExprError();
   7420 
   7421     // Start the member reference and compute the object's type.
   7422     ParsedType ObjectTy;
   7423     bool MayBePseudoDestructor = false;
   7424     Base = SemaRef.ActOnStartCXXMemberReference(0, Base.get(),
   7425                                                 E->getOperatorLoc(),
   7426                                       E->isArrow()? tok::arrow : tok::period,
   7427                                                 ObjectTy,
   7428                                                 MayBePseudoDestructor);
   7429     if (Base.isInvalid())
   7430       return ExprError();
   7431 
   7432     ObjectType = ObjectTy.get();
   7433     BaseType = ((Expr*) Base.get())->getType();
   7434   } else {
   7435     OldBase = 0;
   7436     BaseType = getDerived().TransformType(E->getBaseType());
   7437     ObjectType = BaseType->getAs<PointerType>()->getPointeeType();
   7438   }
   7439 
   7440   // Transform the first part of the nested-name-specifier that qualifies
   7441   // the member name.
   7442   NamedDecl *FirstQualifierInScope
   7443     = getDerived().TransformFirstQualifierInScope(
   7444                                             E->getFirstQualifierFoundInScope(),
   7445                                             E->getQualifierLoc().getBeginLoc());
   7446 
   7447   NestedNameSpecifierLoc QualifierLoc;
   7448   if (E->getQualifier()) {
   7449     QualifierLoc
   7450       = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
   7451                                                      ObjectType,
   7452                                                      FirstQualifierInScope);
   7453     if (!QualifierLoc)
   7454       return ExprError();
   7455   }
   7456 
   7457   // TODO: If this is a conversion-function-id, verify that the
   7458   // destination type name (if present) resolves the same way after
   7459   // instantiation as it did in the local scope.
   7460 
   7461   DeclarationNameInfo NameInfo
   7462     = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
   7463   if (!NameInfo.getName())
   7464     return ExprError();
   7465 
   7466   if (!E->hasExplicitTemplateArgs()) {
   7467     // This is a reference to a member without an explicitly-specified
   7468     // template argument list. Optimize for this common case.
   7469     if (!getDerived().AlwaysRebuild() &&
   7470         Base.get() == OldBase &&
   7471         BaseType == E->getBaseType() &&
   7472         QualifierLoc == E->getQualifierLoc() &&
   7473         NameInfo.getName() == E->getMember() &&
   7474         FirstQualifierInScope == E->getFirstQualifierFoundInScope())
   7475       return SemaRef.Owned(E);
   7476 
   7477     return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
   7478                                                        BaseType,
   7479                                                        E->isArrow(),
   7480                                                        E->getOperatorLoc(),
   7481                                                        QualifierLoc,
   7482                                                        FirstQualifierInScope,
   7483                                                        NameInfo,
   7484                                                        /*TemplateArgs*/ 0);
   7485   }
   7486 
   7487   TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
   7488   if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
   7489                                               E->getNumTemplateArgs(),
   7490                                               TransArgs))
   7491     return ExprError();
   7492 
   7493   return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
   7494                                                      BaseType,
   7495                                                      E->isArrow(),
   7496                                                      E->getOperatorLoc(),
   7497                                                      QualifierLoc,
   7498                                                      FirstQualifierInScope,
   7499                                                      NameInfo,
   7500                                                      &TransArgs);
   7501 }
   7502 
   7503 template<typename Derived>
   7504 ExprResult
   7505 TreeTransform<Derived>::TransformUnresolvedMemberExpr(UnresolvedMemberExpr *Old) {
   7506   // Transform the base of the expression.
   7507   ExprResult Base((Expr*) 0);
   7508   QualType BaseType;
   7509   if (!Old->isImplicitAccess()) {
   7510     Base = getDerived().TransformExpr(Old->getBase());
   7511     if (Base.isInvalid())
   7512       return ExprError();
   7513     BaseType = ((Expr*) Base.get())->getType();
   7514   } else {
   7515     BaseType = getDerived().TransformType(Old->getBaseType());
   7516   }
   7517 
   7518   NestedNameSpecifierLoc QualifierLoc;
   7519   if (Old->getQualifierLoc()) {
   7520     QualifierLoc
   7521     = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
   7522     if (!QualifierLoc)
   7523       return ExprError();
   7524   }
   7525 
   7526   LookupResult R(SemaRef, Old->getMemberNameInfo(),
   7527                  Sema::LookupOrdinaryName);
   7528 
   7529   // Transform all the decls.
   7530   for (UnresolvedMemberExpr::decls_iterator I = Old->decls_begin(),
   7531          E = Old->decls_end(); I != E; ++I) {
   7532     NamedDecl *InstD = static_cast<NamedDecl*>(
   7533                                 getDerived().TransformDecl(Old->getMemberLoc(),
   7534                                                            *I));
   7535     if (!InstD) {
   7536       // Silently ignore these if a UsingShadowDecl instantiated to nothing.
   7537       // This can happen because of dependent hiding.
   7538       if (isa<UsingShadowDecl>(*I))
   7539         continue;
   7540       else {
   7541         R.clear();
   7542         return ExprError();
   7543       }
   7544     }
   7545 
   7546     // Expand using declarations.
   7547     if (isa<UsingDecl>(InstD)) {
   7548       UsingDecl *UD = cast<UsingDecl>(InstD);
   7549       for (UsingDecl::shadow_iterator I = UD->shadow_begin(),
   7550              E = UD->shadow_end(); I != E; ++I)
   7551         R.addDecl(*I);
   7552       continue;
   7553     }
   7554 
   7555     R.addDecl(InstD);
   7556   }
   7557 
   7558   R.resolveKind();
   7559 
   7560   // Determine the naming class.
   7561   if (Old->getNamingClass()) {
   7562     CXXRecordDecl *NamingClass
   7563       = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
   7564                                                           Old->getMemberLoc(),
   7565                                                         Old->getNamingClass()));
   7566     if (!NamingClass)
   7567       return ExprError();
   7568 
   7569     R.setNamingClass(NamingClass);
   7570   }
   7571 
   7572   TemplateArgumentListInfo TransArgs;
   7573   if (Old->hasExplicitTemplateArgs()) {
   7574     TransArgs.setLAngleLoc(Old->getLAngleLoc());
   7575     TransArgs.setRAngleLoc(Old->getRAngleLoc());
   7576     if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
   7577                                                 Old->getNumTemplateArgs(),
   7578                                                 TransArgs))
   7579       return ExprError();
   7580   }
   7581 
   7582   // FIXME: to do this check properly, we will need to preserve the
   7583   // first-qualifier-in-scope here, just in case we had a dependent
   7584   // base (and therefore couldn't do the check) and a
   7585   // nested-name-qualifier (and therefore could do the lookup).
   7586   NamedDecl *FirstQualifierInScope = 0;
   7587 
   7588   return getDerived().RebuildUnresolvedMemberExpr(Base.get(),
   7589                                                   BaseType,
   7590                                                   Old->getOperatorLoc(),
   7591                                                   Old->isArrow(),
   7592                                                   QualifierLoc,
   7593                                                   FirstQualifierInScope,
   7594                                                   R,
   7595                                               (Old->hasExplicitTemplateArgs()
   7596                                                   ? &TransArgs : 0));
   7597 }
   7598 
   7599 template<typename Derived>
   7600 ExprResult
   7601 TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
   7602   EnterExpressionEvaluationContext Unevaluated(SemaRef, Sema::Unevaluated);
   7603   ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
   7604   if (SubExpr.isInvalid())
   7605     return ExprError();
   7606 
   7607   if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
   7608     return SemaRef.Owned(E);
   7609 
   7610   return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
   7611 }
   7612 
   7613 template<typename Derived>
   7614 ExprResult
   7615 TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
   7616   ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
   7617   if (Pattern.isInvalid())
   7618     return ExprError();
   7619 
   7620   if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
   7621     return SemaRef.Owned(E);
   7622 
   7623   return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
   7624                                            E->getNumExpansions());
   7625 }
   7626 
   7627 template<typename Derived>
   7628 ExprResult
   7629 TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
   7630   // If E is not value-dependent, then nothing will change when we transform it.
   7631   // Note: This is an instantiation-centric view.
   7632   if (!E->isValueDependent())
   7633     return SemaRef.Owned(E);
   7634 
   7635   // Note: None of the implementations of TryExpandParameterPacks can ever
   7636   // produce a diagnostic when given only a single unexpanded parameter pack,
   7637   // so
   7638   UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
   7639   bool ShouldExpand = false;
   7640   bool RetainExpansion = false;
   7641   llvm::Optional<unsigned> NumExpansions;
   7642   if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
   7643                                            &Unexpanded, 1,
   7644                                            ShouldExpand, RetainExpansion,
   7645                                            NumExpansions))
   7646     return ExprError();
   7647 
   7648   if (!ShouldExpand || RetainExpansion)
   7649     return SemaRef.Owned(E);
   7650 
   7651   // We now know the length of the parameter pack, so build a new expression
   7652   // that stores that length.
   7653   return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
   7654                                             E->getPackLoc(), E->getRParenLoc(),
   7655                                             *NumExpansions);
   7656 }
   7657 
   7658 template<typename Derived>
   7659 ExprResult
   7660 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
   7661                                           SubstNonTypeTemplateParmPackExpr *E) {
   7662   // Default behavior is to do nothing with this transformation.
   7663   return SemaRef.Owned(E);
   7664 }
   7665 
   7666 template<typename Derived>
   7667 ExprResult
   7668 TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
   7669                                           SubstNonTypeTemplateParmExpr *E) {
   7670   // Default behavior is to do nothing with this transformation.
   7671   return SemaRef.Owned(E);
   7672 }
   7673 
   7674 template<typename Derived>
   7675 ExprResult
   7676 TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
   7677                                                   MaterializeTemporaryExpr *E) {
   7678   return getDerived().TransformExpr(E->GetTemporaryExpr());
   7679 }
   7680 
   7681 template<typename Derived>
   7682 ExprResult
   7683 TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
   7684   return SemaRef.Owned(E);
   7685 }
   7686 
   7687 template<typename Derived>
   7688 ExprResult
   7689 TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
   7690   TypeSourceInfo *EncodedTypeInfo
   7691     = getDerived().TransformType(E->getEncodedTypeSourceInfo());
   7692   if (!EncodedTypeInfo)
   7693     return ExprError();
   7694 
   7695   if (!getDerived().AlwaysRebuild() &&
   7696       EncodedTypeInfo == E->getEncodedTypeSourceInfo())
   7697     return SemaRef.Owned(E);
   7698 
   7699   return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
   7700                                             EncodedTypeInfo,
   7701                                             E->getRParenLoc());
   7702 }
   7703 
   7704 template<typename Derived>
   7705 ExprResult TreeTransform<Derived>::
   7706 TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
   7707   ExprResult result = getDerived().TransformExpr(E->getSubExpr());
   7708   if (result.isInvalid()) return ExprError();
   7709   Expr *subExpr = result.take();
   7710 
   7711   if (!getDerived().AlwaysRebuild() &&
   7712       subExpr == E->getSubExpr())
   7713     return SemaRef.Owned(E);
   7714 
   7715   return SemaRef.Owned(new(SemaRef.Context)
   7716       ObjCIndirectCopyRestoreExpr(subExpr, E->getType(), E->shouldCopy()));
   7717 }
   7718 
   7719 template<typename Derived>
   7720 ExprResult TreeTransform<Derived>::
   7721 TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
   7722   TypeSourceInfo *TSInfo
   7723     = getDerived().TransformType(E->getTypeInfoAsWritten());
   7724   if (!TSInfo)
   7725     return ExprError();
   7726 
   7727   ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
   7728   if (Result.isInvalid())
   7729     return ExprError();
   7730 
   7731   if (!getDerived().AlwaysRebuild() &&
   7732       TSInfo == E->getTypeInfoAsWritten() &&
   7733       Result.get() == E->getSubExpr())
   7734     return SemaRef.Owned(E);
   7735 
   7736   return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
   7737                                       E->getBridgeKeywordLoc(), TSInfo,
   7738                                       Result.get());
   7739 }
   7740 
   7741 template<typename Derived>
   7742 ExprResult
   7743 TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
   7744   // Transform arguments.
   7745   bool ArgChanged = false;
   7746   ASTOwningVector<Expr*> Args(SemaRef);
   7747   Args.reserve(E->getNumArgs());
   7748   if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
   7749                                   &ArgChanged))
   7750     return ExprError();
   7751 
   7752   if (E->getReceiverKind() == ObjCMessageExpr::Class) {
   7753     // Class message: transform the receiver type.
   7754     TypeSourceInfo *ReceiverTypeInfo
   7755       = getDerived().TransformType(E->getClassReceiverTypeInfo());
   7756     if (!ReceiverTypeInfo)
   7757       return ExprError();
   7758 
   7759     // If nothing changed, just retain the existing message send.
   7760     if (!getDerived().AlwaysRebuild() &&
   7761         ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
   7762       return SemaRef.Owned(E);
   7763 
   7764     // Build a new class message send.
   7765     return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
   7766                                                E->getSelector(),
   7767                                                E->getSelectorLoc(),
   7768                                                E->getMethodDecl(),
   7769                                                E->getLeftLoc(),
   7770                                                move_arg(Args),
   7771                                                E->getRightLoc());
   7772   }
   7773 
   7774   // Instance message: transform the receiver
   7775   assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&
   7776          "Only class and instance messages may be instantiated");
   7777   ExprResult Receiver
   7778     = getDerived().TransformExpr(E->getInstanceReceiver());
   7779   if (Receiver.isInvalid())
   7780     return ExprError();
   7781 
   7782   // If nothing changed, just retain the existing message send.
   7783   if (!getDerived().AlwaysRebuild() &&
   7784       Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
   7785     return SemaRef.Owned(E);
   7786 
   7787   // Build a new instance message send.
   7788   return getDerived().RebuildObjCMessageExpr(Receiver.get(),
   7789                                              E->getSelector(),
   7790                                              E->getSelectorLoc(),
   7791                                              E->getMethodDecl(),
   7792                                              E->getLeftLoc(),
   7793                                              move_arg(Args),
   7794                                              E->getRightLoc());
   7795 }
   7796 
   7797 template<typename Derived>
   7798 ExprResult
   7799 TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
   7800   return SemaRef.Owned(E);
   7801 }
   7802 
   7803 template<typename Derived>
   7804 ExprResult
   7805 TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
   7806   return SemaRef.Owned(E);
   7807 }
   7808 
   7809 template<typename Derived>
   7810 ExprResult
   7811 TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
   7812   // Transform the base expression.
   7813   ExprResult Base = getDerived().TransformExpr(E->getBase());
   7814   if (Base.isInvalid())
   7815     return ExprError();
   7816 
   7817   // We don't need to transform the ivar; it will never change.
   7818 
   7819   // If nothing changed, just retain the existing expression.
   7820   if (!getDerived().AlwaysRebuild() &&
   7821       Base.get() == E->getBase())
   7822     return SemaRef.Owned(E);
   7823 
   7824   return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
   7825                                              E->getLocation(),
   7826                                              E->isArrow(), E->isFreeIvar());
   7827 }
   7828 
   7829 template<typename Derived>
   7830 ExprResult
   7831 TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
   7832   // 'super' and types never change. Property never changes. Just
   7833   // retain the existing expression.
   7834   if (!E->isObjectReceiver())
   7835     return SemaRef.Owned(E);
   7836 
   7837   // Transform the base expression.
   7838   ExprResult Base = getDerived().TransformExpr(E->getBase());
   7839   if (Base.isInvalid())
   7840     return ExprError();
   7841 
   7842   // We don't need to transform the property; it will never change.
   7843 
   7844   // If nothing changed, just retain the existing expression.
   7845   if (!getDerived().AlwaysRebuild() &&
   7846       Base.get() == E->getBase())
   7847     return SemaRef.Owned(E);
   7848 
   7849   if (E->isExplicitProperty())
   7850     return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
   7851                                                    E->getExplicitProperty(),
   7852                                                    E->getLocation());
   7853 
   7854   return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
   7855                                                  E->getType(),
   7856                                                  E->getImplicitPropertyGetter(),
   7857                                                  E->getImplicitPropertySetter(),
   7858                                                  E->getLocation());
   7859 }
   7860 
   7861 template<typename Derived>
   7862 ExprResult
   7863 TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
   7864   // Transform the base expression.
   7865   ExprResult Base = getDerived().TransformExpr(E->getBase());
   7866   if (Base.isInvalid())
   7867     return ExprError();
   7868 
   7869   // If nothing changed, just retain the existing expression.
   7870   if (!getDerived().AlwaysRebuild() &&
   7871       Base.get() == E->getBase())
   7872     return SemaRef.Owned(E);
   7873 
   7874   return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
   7875                                          E->isArrow());
   7876 }
   7877 
   7878 template<typename Derived>
   7879 ExprResult
   7880 TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
   7881   bool ArgumentChanged = false;
   7882   ASTOwningVector<Expr*> SubExprs(SemaRef);
   7883   SubExprs.reserve(E->getNumSubExprs());
   7884   if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
   7885                                   SubExprs, &ArgumentChanged))
   7886     return ExprError();
   7887 
   7888   if (!getDerived().AlwaysRebuild() &&
   7889       !ArgumentChanged)
   7890     return SemaRef.Owned(E);
   7891 
   7892   return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
   7893                                                move_arg(SubExprs),
   7894                                                E->getRParenLoc());
   7895 }
   7896 
   7897 template<typename Derived>
   7898 ExprResult
   7899 TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
   7900   BlockDecl *oldBlock = E->getBlockDecl();
   7901 
   7902   SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/0);
   7903   BlockScopeInfo *blockScope = SemaRef.getCurBlock();
   7904 
   7905   blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
   7906   // We built a new blockScopeInfo in call to ActOnBlockStart
   7907   // in above, CapturesCXXThis need be set here from the block
   7908   // expression.
   7909   blockScope->CapturesCXXThis = oldBlock->capturesCXXThis();
   7910 
   7911   llvm::SmallVector<ParmVarDecl*, 4> params;
   7912   llvm::SmallVector<QualType, 4> paramTypes;
   7913 
   7914   // Parameter substitution.
   7915   if (getDerived().TransformFunctionTypeParams(E->getCaretLocation(),
   7916                                                oldBlock->param_begin(),
   7917                                                oldBlock->param_size(),
   7918                                                0, paramTypes, &params))
   7919     return true;
   7920 
   7921   const FunctionType *exprFunctionType = E->getFunctionType();
   7922   QualType exprResultType = exprFunctionType->getResultType();
   7923   if (!exprResultType.isNull()) {
   7924     if (!exprResultType->isDependentType())
   7925       blockScope->ReturnType = exprResultType;
   7926     else if (exprResultType != getSema().Context.DependentTy)
   7927       blockScope->ReturnType = getDerived().TransformType(exprResultType);
   7928   }
   7929 
   7930   // If the return type has not been determined yet, leave it as a dependent
   7931   // type; it'll get set when we process the body.
   7932   if (blockScope->ReturnType.isNull())
   7933     blockScope->ReturnType = getSema().Context.DependentTy;
   7934 
   7935   // Don't allow returning a objc interface by value.
   7936   if (blockScope->ReturnType->isObjCObjectType()) {
   7937     getSema().Diag(E->getCaretLocation(),
   7938                    diag::err_object_cannot_be_passed_returned_by_value)
   7939       << 0 << blockScope->ReturnType;
   7940     return ExprError();
   7941   }
   7942 
   7943   QualType functionType = getDerived().RebuildFunctionProtoType(
   7944                                                         blockScope->ReturnType,
   7945                                                         paramTypes.data(),
   7946                                                         paramTypes.size(),
   7947                                                         oldBlock->isVariadic(),
   7948                                                         0, RQ_None,
   7949                                                exprFunctionType->getExtInfo());
   7950   blockScope->FunctionType = functionType;
   7951 
   7952   // Set the parameters on the block decl.
   7953   if (!params.empty())
   7954     blockScope->TheDecl->setParams(params.data(), params.size());
   7955 
   7956   // If the return type wasn't explicitly set, it will have been marked as a
   7957   // dependent type (DependentTy); clear out the return type setting so
   7958   // we will deduce the return type when type-checking the block's body.
   7959   if (blockScope->ReturnType == getSema().Context.DependentTy)
   7960     blockScope->ReturnType = QualType();
   7961 
   7962   // Transform the body
   7963   StmtResult body = getDerived().TransformStmt(E->getBody());
   7964   if (body.isInvalid())
   7965     return ExprError();
   7966 
   7967 #ifndef NDEBUG
   7968   // In builds with assertions, make sure that we captured everything we
   7969   // captured before.
   7970   if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
   7971     for (BlockDecl::capture_iterator i = oldBlock->capture_begin(),
   7972            e = oldBlock->capture_end(); i != e; ++i) {
   7973       VarDecl *oldCapture = i->getVariable();
   7974 
   7975       // Ignore parameter packs.
   7976       if (isa<ParmVarDecl>(oldCapture) &&
   7977           cast<ParmVarDecl>(oldCapture)->isParameterPack())
   7978         continue;
   7979 
   7980       VarDecl *newCapture =
   7981         cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
   7982                                                  oldCapture));
   7983       assert(blockScope->CaptureMap.count(newCapture));
   7984     }
   7985   }
   7986 #endif
   7987 
   7988   return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
   7989                                     /*Scope=*/0);
   7990 }
   7991 
   7992 template<typename Derived>
   7993 ExprResult
   7994 TreeTransform<Derived>::TransformBlockDeclRefExpr(BlockDeclRefExpr *E) {
   7995   ValueDecl *ND
   7996   = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
   7997                                                        E->getDecl()));
   7998   if (!ND)
   7999     return ExprError();
   8000 
   8001   if (!getDerived().AlwaysRebuild() &&
   8002       ND == E->getDecl()) {
   8003     // Mark it referenced in the new context regardless.
   8004     // FIXME: this is a bit instantiation-specific.
   8005     SemaRef.MarkDeclarationReferenced(E->getLocation(), ND);
   8006 
   8007     return SemaRef.Owned(E);
   8008   }
   8009 
   8010   DeclarationNameInfo NameInfo(E->getDecl()->getDeclName(), E->getLocation());
   8011   return getDerived().RebuildDeclRefExpr(NestedNameSpecifierLoc(),
   8012                                          ND, NameInfo, 0);
   8013 }
   8014 
   8015 template<typename Derived>
   8016 ExprResult
   8017 TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
   8018   assert(false && "Cannot transform asType expressions yet");
   8019   return SemaRef.Owned(E);
   8020 }
   8021 
   8022 //===----------------------------------------------------------------------===//
   8023 // Type reconstruction
   8024 //===----------------------------------------------------------------------===//
   8025 
   8026 template<typename Derived>
   8027 QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
   8028                                                     SourceLocation Star) {
   8029   return SemaRef.BuildPointerType(PointeeType, Star,
   8030                                   getDerived().getBaseEntity());
   8031 }
   8032 
   8033 template<typename Derived>
   8034 QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
   8035                                                          SourceLocation Star) {
   8036   return SemaRef.BuildBlockPointerType(PointeeType, Star,
   8037                                        getDerived().getBaseEntity());
   8038 }
   8039 
   8040 template<typename Derived>
   8041 QualType
   8042 TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
   8043                                              bool WrittenAsLValue,
   8044                                              SourceLocation Sigil) {
   8045   return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
   8046                                     Sigil, getDerived().getBaseEntity());
   8047 }
   8048 
   8049 template<typename Derived>
   8050 QualType
   8051 TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
   8052                                                  QualType ClassType,
   8053                                                  SourceLocation Sigil) {
   8054   return SemaRef.BuildMemberPointerType(PointeeType, ClassType,
   8055                                         Sigil, getDerived().getBaseEntity());
   8056 }
   8057 
   8058 template<typename Derived>
   8059 QualType
   8060 TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
   8061                                          ArrayType::ArraySizeModifier SizeMod,
   8062                                          const llvm::APInt *Size,
   8063                                          Expr *SizeExpr,
   8064                                          unsigned IndexTypeQuals,
   8065                                          SourceRange BracketsRange) {
   8066   if (SizeExpr || !Size)
   8067     return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
   8068                                   IndexTypeQuals, BracketsRange,
   8069                                   getDerived().getBaseEntity());
   8070 
   8071   QualType Types[] = {
   8072     SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
   8073     SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
   8074     SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
   8075   };
   8076   const unsigned NumTypes = sizeof(Types) / sizeof(QualType);
   8077   QualType SizeType;
   8078   for (unsigned I = 0; I != NumTypes; ++I)
   8079     if (Size->getBitWidth() == SemaRef.Context.getIntWidth(Types[I])) {
   8080       SizeType = Types[I];
   8081       break;
   8082     }
   8083 
   8084   IntegerLiteral ArraySize(SemaRef.Context, *Size, SizeType,
   8085                            /*FIXME*/BracketsRange.getBegin());
   8086   return SemaRef.BuildArrayType(ElementType, SizeMod, &ArraySize,
   8087                                 IndexTypeQuals, BracketsRange,
   8088                                 getDerived().getBaseEntity());
   8089 }
   8090 
   8091 template<typename Derived>
   8092 QualType
   8093 TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
   8094                                                  ArrayType::ArraySizeModifier SizeMod,
   8095                                                  const llvm::APInt &Size,
   8096                                                  unsigned IndexTypeQuals,
   8097                                                  SourceRange BracketsRange) {
   8098   return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, 0,
   8099                                         IndexTypeQuals, BracketsRange);
   8100 }
   8101 
   8102 template<typename Derived>
   8103 QualType
   8104 TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
   8105                                           ArrayType::ArraySizeModifier SizeMod,
   8106                                                  unsigned IndexTypeQuals,
   8107                                                    SourceRange BracketsRange) {
   8108   return getDerived().RebuildArrayType(ElementType, SizeMod, 0, 0,
   8109                                        IndexTypeQuals, BracketsRange);
   8110 }
   8111 
   8112 template<typename Derived>
   8113 QualType
   8114 TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
   8115                                           ArrayType::ArraySizeModifier SizeMod,
   8116                                                  Expr *SizeExpr,
   8117                                                  unsigned IndexTypeQuals,
   8118                                                  SourceRange BracketsRange) {
   8119   return getDerived().RebuildArrayType(ElementType, SizeMod, 0,
   8120                                        SizeExpr,
   8121                                        IndexTypeQuals, BracketsRange);
   8122 }
   8123 
   8124 template<typename Derived>
   8125 QualType
   8126 TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
   8127                                           ArrayType::ArraySizeModifier SizeMod,
   8128                                                        Expr *SizeExpr,
   8129                                                        unsigned IndexTypeQuals,
   8130                                                    SourceRange BracketsRange) {
   8131   return getDerived().RebuildArrayType(ElementType, SizeMod, 0,
   8132                                        SizeExpr,
   8133                                        IndexTypeQuals, BracketsRange);
   8134 }
   8135 
   8136 template<typename Derived>
   8137 QualType TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
   8138                                                unsigned NumElements,
   8139                                                VectorType::VectorKind VecKind) {
   8140   // FIXME: semantic checking!
   8141   return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
   8142 }
   8143 
   8144 template<typename Derived>
   8145 QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
   8146                                                       unsigned NumElements,
   8147                                                  SourceLocation AttributeLoc) {
   8148   llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
   8149                           NumElements, true);
   8150   IntegerLiteral *VectorSize
   8151     = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
   8152                              AttributeLoc);
   8153   return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
   8154 }
   8155 
   8156 template<typename Derived>
   8157 QualType
   8158 TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
   8159                                                            Expr *SizeExpr,
   8160                                                   SourceLocation AttributeLoc) {
   8161   return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
   8162 }
   8163 
   8164 template<typename Derived>
   8165 QualType TreeTransform<Derived>::RebuildFunctionProtoType(QualType T,
   8166                                                           QualType *ParamTypes,
   8167                                                         unsigned NumParamTypes,
   8168                                                           bool Variadic,
   8169                                                           unsigned Quals,
   8170                                                   RefQualifierKind RefQualifier,
   8171                                             const FunctionType::ExtInfo &Info) {
   8172   return SemaRef.BuildFunctionType(T, ParamTypes, NumParamTypes, Variadic,
   8173                                    Quals, RefQualifier,
   8174                                    getDerived().getBaseLocation(),
   8175                                    getDerived().getBaseEntity(),
   8176                                    Info);
   8177 }
   8178 
   8179 template<typename Derived>
   8180 QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
   8181   return SemaRef.Context.getFunctionNoProtoType(T);
   8182 }
   8183 
   8184 template<typename Derived>
   8185 QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(Decl *D) {
   8186   assert(D && "no decl found");
   8187   if (D->isInvalidDecl()) return QualType();
   8188 
   8189   // FIXME: Doesn't account for ObjCInterfaceDecl!
   8190   TypeDecl *Ty;
   8191   if (isa<UsingDecl>(D)) {
   8192     UsingDecl *Using = cast<UsingDecl>(D);
   8193     assert(Using->isTypeName() &&
   8194            "UnresolvedUsingTypenameDecl transformed to non-typename using");
   8195 
   8196     // A valid resolved using typename decl points to exactly one type decl.
   8197     assert(++Using->shadow_begin() == Using->shadow_end());
   8198     Ty = cast<TypeDecl>((*Using->shadow_begin())->getTargetDecl());
   8199 
   8200   } else {
   8201     assert(isa<UnresolvedUsingTypenameDecl>(D) &&
   8202            "UnresolvedUsingTypenameDecl transformed to non-using decl");
   8203     Ty = cast<UnresolvedUsingTypenameDecl>(D);
   8204   }
   8205 
   8206   return SemaRef.Context.getTypeDeclType(Ty);
   8207 }
   8208 
   8209 template<typename Derived>
   8210 QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E,
   8211                                                        SourceLocation Loc) {
   8212   return SemaRef.BuildTypeofExprType(E, Loc);
   8213 }
   8214 
   8215 template<typename Derived>
   8216 QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying) {
   8217   return SemaRef.Context.getTypeOfType(Underlying);
   8218 }
   8219 
   8220 template<typename Derived>
   8221 QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E,
   8222                                                      SourceLocation Loc) {
   8223   return SemaRef.BuildDecltypeType(E, Loc);
   8224 }
   8225 
   8226 template<typename Derived>
   8227 QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
   8228                                             UnaryTransformType::UTTKind UKind,
   8229                                             SourceLocation Loc) {
   8230   return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
   8231 }
   8232 
   8233 template<typename Derived>
   8234 QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
   8235                                                       TemplateName Template,
   8236                                              SourceLocation TemplateNameLoc,
   8237                                      TemplateArgumentListInfo &TemplateArgs) {
   8238   return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
   8239 }
   8240 
   8241 template<typename Derived>
   8242 TemplateName
   8243 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
   8244                                             bool TemplateKW,
   8245                                             TemplateDecl *Template) {
   8246   return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
   8247                                                   Template);
   8248 }
   8249 
   8250 template<typename Derived>
   8251 TemplateName
   8252 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
   8253                                             const IdentifierInfo &Name,
   8254                                             SourceLocation NameLoc,
   8255                                             QualType ObjectType,
   8256                                             NamedDecl *FirstQualifierInScope) {
   8257   UnqualifiedId TemplateName;
   8258   TemplateName.setIdentifier(&Name, NameLoc);
   8259   Sema::TemplateTy Template;
   8260   getSema().ActOnDependentTemplateName(/*Scope=*/0,
   8261                                        /*FIXME:*/SourceLocation(),
   8262                                        SS,
   8263                                        TemplateName,
   8264                                        ParsedType::make(ObjectType),
   8265                                        /*EnteringContext=*/false,
   8266                                        Template);
   8267   return Template.get();
   8268 }
   8269 
   8270 template<typename Derived>
   8271 TemplateName
   8272 TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
   8273                                             OverloadedOperatorKind Operator,
   8274                                             SourceLocation NameLoc,
   8275                                             QualType ObjectType) {
   8276   UnqualifiedId Name;
   8277   // FIXME: Bogus location information.
   8278   SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
   8279   Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
   8280   Sema::TemplateTy Template;
   8281   getSema().ActOnDependentTemplateName(/*Scope=*/0,
   8282                                        /*FIXME:*/SourceLocation(),
   8283                                        SS,
   8284                                        Name,
   8285                                        ParsedType::make(ObjectType),
   8286                                        /*EnteringContext=*/false,
   8287                                        Template);
   8288   return Template.template getAsVal<TemplateName>();
   8289 }
   8290 
   8291 template<typename Derived>
   8292 ExprResult
   8293 TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
   8294                                                    SourceLocation OpLoc,
   8295                                                    Expr *OrigCallee,
   8296                                                    Expr *First,
   8297                                                    Expr *Second) {
   8298   Expr *Callee = OrigCallee->IgnoreParenCasts();
   8299   bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
   8300 
   8301   // Determine whether this should be a builtin operation.
   8302   if (Op == OO_Subscript) {
   8303     if (!First->getType()->isOverloadableType() &&
   8304         !Second->getType()->isOverloadableType())
   8305       return getSema().CreateBuiltinArraySubscriptExpr(First,
   8306                                                        Callee->getLocStart(),
   8307                                                        Second, OpLoc);
   8308   } else if (Op == OO_Arrow) {
   8309     // -> is never a builtin operation.
   8310     return SemaRef.BuildOverloadedArrowExpr(0, First, OpLoc);
   8311   } else if (Second == 0 || isPostIncDec) {
   8312     if (!First->getType()->isOverloadableType()) {
   8313       // The argument is not of overloadable type, so try to create a
   8314       // built-in unary operation.
   8315       UnaryOperatorKind Opc
   8316         = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
   8317 
   8318       return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
   8319     }
   8320   } else {
   8321     if (!First->getType()->isOverloadableType() &&
   8322         !Second->getType()->isOverloadableType()) {
   8323       // Neither of the arguments is an overloadable type, so try to
   8324       // create a built-in binary operation.
   8325       BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
   8326       ExprResult Result
   8327         = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
   8328       if (Result.isInvalid())
   8329         return ExprError();
   8330 
   8331       return move(Result);
   8332     }
   8333   }
   8334 
   8335   // Compute the transformed set of functions (and function templates) to be
   8336   // used during overload resolution.
   8337   UnresolvedSet<16> Functions;
   8338 
   8339   if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
   8340     assert(ULE->requiresADL());
   8341 
   8342     // FIXME: Do we have to check
   8343     // IsAcceptableNonMemberOperatorCandidate for each of these?
   8344     Functions.append(ULE->decls_begin(), ULE->decls_end());
   8345   } else {
   8346     Functions.addDecl(cast<DeclRefExpr>(Callee)->getDecl());
   8347   }
   8348 
   8349   // Add any functions found via argument-dependent lookup.
   8350   Expr *Args[2] = { First, Second };
   8351   unsigned NumArgs = 1 + (Second != 0);
   8352 
   8353   // Create the overloaded operator invocation for unary operators.
   8354   if (NumArgs == 1 || isPostIncDec) {
   8355     UnaryOperatorKind Opc
   8356       = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
   8357     return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First);
   8358   }
   8359 
   8360   if (Op == OO_Subscript) {
   8361     SourceLocation LBrace;
   8362     SourceLocation RBrace;
   8363 
   8364     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
   8365         DeclarationNameLoc &NameLoc = DRE->getNameInfo().getInfo();
   8366         LBrace = SourceLocation::getFromRawEncoding(
   8367                     NameLoc.CXXOperatorName.BeginOpNameLoc);
   8368         RBrace = SourceLocation::getFromRawEncoding(
   8369                     NameLoc.CXXOperatorName.EndOpNameLoc);
   8370     } else {
   8371         LBrace = Callee->getLocStart();
   8372         RBrace = OpLoc;
   8373     }
   8374 
   8375     return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
   8376                                                       First, Second);
   8377   }
   8378 
   8379   // Create the overloaded operator invocation for binary operators.
   8380   BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
   8381   ExprResult Result
   8382     = SemaRef.CreateOverloadedBinOp(OpLoc, Opc, Functions, Args[0], Args[1]);
   8383   if (Result.isInvalid())
   8384     return ExprError();
   8385 
   8386   return move(Result);
   8387 }
   8388 
   8389 template<typename Derived>
   8390 ExprResult
   8391 TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
   8392                                                      SourceLocation OperatorLoc,
   8393                                                        bool isArrow,
   8394                                                        CXXScopeSpec &SS,
   8395                                                      TypeSourceInfo *ScopeType,
   8396                                                        SourceLocation CCLoc,
   8397                                                        SourceLocation TildeLoc,
   8398                                         PseudoDestructorTypeStorage Destroyed) {
   8399   QualType BaseType = Base->getType();
   8400   if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
   8401       (!isArrow && !BaseType->getAs<RecordType>()) ||
   8402       (isArrow && BaseType->getAs<PointerType>() &&
   8403        !BaseType->getAs<PointerType>()->getPointeeType()
   8404                                               ->template getAs<RecordType>())){
   8405     // This pseudo-destructor expression is still a pseudo-destructor.
   8406     return SemaRef.BuildPseudoDestructorExpr(Base, OperatorLoc,
   8407                                              isArrow? tok::arrow : tok::period,
   8408                                              SS, ScopeType, CCLoc, TildeLoc,
   8409                                              Destroyed,
   8410                                              /*FIXME?*/true);
   8411   }
   8412 
   8413   TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
   8414   DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
   8415                  SemaRef.Context.getCanonicalType(DestroyedType->getType())));
   8416   DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
   8417   NameInfo.setNamedTypeInfo(DestroyedType);
   8418 
   8419   // FIXME: the ScopeType should be tacked onto SS.
   8420 
   8421   return getSema().BuildMemberReferenceExpr(Base, BaseType,
   8422                                             OperatorLoc, isArrow,
   8423                                             SS, /*FIXME: FirstQualifier*/ 0,
   8424                                             NameInfo,
   8425                                             /*TemplateArgs*/ 0);
   8426 }
   8427 
   8428 } // end namespace clang
   8429 
   8430 #endif // LLVM_CLANG_SEMA_TREETRANSFORM_H
   8431